Skip to content

feat: detect putative recombinant regions 🧪 - #1774

Merged
ivan-aksamentov merged 62 commits into
masterfrom
feat/recombination-detection
Nov 17, 2026
Merged

ivan-aksamentov merged 62 commits into
masterfrom
feat/recombination-detection

Conversation

@ivan-aksamentov

@ivan-aksamentov ivan-aksamentov commented Jul 8, 2026 •

Copy link
Copy Markdown
Member
Previous description (replaced 2026-11-11)
  • Related to: #1768
  • Sibling in nextclade_data: #464

🧪 Try it

Provenance

Design and function contract specified in the Nextclade multi-reference meeting (2026-06-26). Implementation follows a Python prototype and its algorithm notes.

Motivation

A recombinant sequence -- one whose genome is a mosaic of segments from different lineages -- produces a localized cluster of private mutations when placed on the reference tree. Nextclade currently has no way to distinguish this pattern from a poorly sequenced region, a novel variant, or contamination. The private-mutation QC rule penalizes all three equally.

This PR adds a per-sequence detector that identifies where the breakpoints are, without naming the donor lineage. Downstream consumers can mask the flagged regions and re-place if needed.

Design

The full specification is in the decision record, which covers the model, estimation, pipeline integration, configuration, output, viewer, and deferred work. The summary below is for reviewers who want to evaluate the approach without reading the full document.

Model

A two-state Hidden Markov Model walks the alignment with states wildtype ($w$) and recombinant ($r$), decoded by Viterbi in log-space [src]. At each reference position the model sees one of three observations relative to the sequence's inferred parent:

Observation Meaning Emission
Ref matches parent $P = 1 - \mu_w$ or $1 - \mu_r$ by state
Mut private substitution $P = \mu_w$ or $\mu_r$ by state
Missing N, deletion, ambiguity, placement-masked $P = 1$ (both states)

Missing positions contribute no evidence but allow transitions to persist across uncovered stretches, so a recombinant region bridging an N run is not split. Deletions are Missing because a large deletion is one mutational event, not a cluster of per-site mutations that would inflate local density and trigger false calls. Placement-masked sites are Missing to prevent false calls at homoplasic positions.

The joint likelihood for observation sequence $s$ given hidden states $h$ is:

$$P(s \mid h) = P(h_1) \prod_{l=1}^{L} P(s_l \mid h_l) \prod_{l=1}^{L-1} T(h_{l+1} \mid h_l)$$

where $s = (s_1, \ldots, s_L)$ is the observation sequence, $h = (h_1, \ldots, h_L)$ is the hidden state sequence with $h_l \in {w, r}$, $P(s_l \mid h_l)$ is the emission probability, and $T$ is a symmetric transition matrix with off-diagonal $\gamma$.

Parameters

Three parameters govern the model [src]:

Parameter Role Default estimation
$\gamma$ transition rate $1 / L_\text{ref}$ (one expected switch per genome)
$\mu_w$ wildtype emission mean terminal branch length / $L_\text{ref}$
$\mu_r$ recombinant emission median pairwise inter-clade leaf distance / $L_\text{ref}$

Parameters are resolved once per dataset, not per sequence. Each parameter resolves independently: an explicit pathogen.json value bypasses estimation for that parameter. Estimation counts substitutions and insertions but excludes deletions (a deletion token is identified structurally by a gap query base, not by string suffix). $\mu_r$ uses leaf-to-leaf MRCA path distances, not founder-to-founder distances, because short founder branches underestimate inter-clade divergence.

Each state transition costs $c = \ln((1-\gamma)/\gamma)$ nats; the decoder switches only when accumulated emission evidence exceeds $c$. For a 30 kb genome, $c \approx 10.3$ nats.

Three invariants are enforced on every construction and deserialization path: all parameters in $(0,1)$; $\gamma < 0.5$; $\mu_r > \mu_w$.

Forward-backward confidence

After Viterbi identifies intervals, the forward-backward algorithm [src] computes per-site posterior marginals $P(h_l = r \mid s)$ in log-space. Each interval receives a confidence score equal to the mean posterior marginal within it -- a per-call reliability measure that Viterbi's single hard path cannot express. Values near 1 indicate high posterior certainty; values near 0.5 indicate ambiguous evidence.

Forward-backward runs only when Viterbi finds at least one interval, avoiding the $O(L)$ memory cost for the common case.

Pipeline integration

Detection runs per-sequence in the parallel phase, after private mutation calling [src]:

  1. Gate on minPrivateSubsToRun (default 1) -- a sequence with no private substitutions has an all-Ref/Missing observation vector, so the recombinant state can never outscore wildtype
  2. Assemble non-comparable positions (N, deletions, ambiguities, placement-masked sites)
  3. Build the observation vector: Ref for aligned positions, Mut for private substitutions, then non-comparable ranges override to Missing
  4. Viterbi decode, extract maximal runs of recombinant state, trim leading/trailing Missing
  5. Forward-backward marginals and per-interval confidence (skipped when step 4 finds nothing)

Configuration

pathogen.json snippet (all fields optional):

{
  "recombination": {
    "enabled": true,
    "minPrivateSubsToRun": 1,
    "gamma": 3.3e-5,
    "muW": 0.001,
    "muR": 0.01
  }
}
  • enabled: absent = default-on, true = explicit opt-in, false = disabled
  • minPrivateSubsToRun: skip sequences below this count (default 1)
  • gamma, muW, muR: when set, bypass tree-based estimation for that parameter. Must satisfy $(0,1)$, $\gamma < 0.5$, $\mu_r > \mu_w$

The companion scripts/recombination_params in nextclade_data computes these values from a dataset's tree and reference, for freezing reviewed parameters into pathogen.json.

When a dataset cannot support detection (no tree, fewer than two clades, no branch mutations):

  • Default-on (enabled absent): silently skipped
  • Explicit enabled: true: dataset-level error naming the cause

Invalid explicit parameters are always errors. The skip reasons are enumerated by RecombinationSkipReason [src].

Output

Recombination is an observation about sequence origin, not a quality metric, so results go into dedicated output columns rather than the QC system.

JSON: recombination field on each sequence result, omitted when no intervals found:

{
  "regions": [{ "range": { "begin": 100, "end": 200 }, "length": 100, "confidence": 0.95 }],
  "totalRegions": 1,
  "totalLength": 100,
  "longestRegion": { "range": { "begin": 100, "end": 200 }, "length": 100, "confidence": 0.95 }
}

TSV: dot-notation columns in a dedicated Recombination category (recombination.regions, recombination.regionConfidences, recombination.totalRegions, recombination.totalLength, recombination.longestRegion.range, recombination.longestRegion.length).

Viewer

  • Purple markers (#8f2fd4 fill, #e0b3ff border) in all nucleotide views (absolute and relative)
  • Confidence-scaled opacity (minimum fill 0.35, minimum border 0.5)
  • Tooltip: "Putative recombinant" with range, length, and confidence percentage
  • Rec. column in the results table, sortable by total recombinant length, with a tooltip showing region count, total length, longest region, and per-region confidence
Image

Differences from the prototype

  • Three-valued observations: Missing with emission probability 1 instead of binary ${0, 1}$
  • Placement-masked sites: treated as Missing to prevent false calls at homoplasic positions
  • Interval trimming: leading/trailing Missing stripped so reported ranges start and end at covered positions
  • Forward-backward confidence: conditional on non-empty Viterbi output, avoiding $O(L)$ memory for the common case
  • Parameter validation: $\gamma < 0.5$ and deserialization through TryFrom in addition to range checks

Work items

  • Implement Viterbi decoder with three-valued observations and log-space arithmetic [src]
  • Estimate $\gamma$, $\mu_w$, $\mu_r$ from tree topology, calibrating on substitutions with deletions excluded [src]
  • Wire detection into the per-sequence pipeline with skip-reason warnings [src]
  • Add forward-backward algorithm with per-interval confidence [src]
  • Restructure results into RecombinationRegion with dot-notation TSV columns and Rec. table column
  • Render purple recombination markers in all nucleotide views with confidence-scaled opacity
  • Rework parameter resolution: independent overrides, minPrivateSubsToRun gate, deserialization validation, structural branch-mutation parsing
  • Improve test assertions with shared macros (pretty_assert_ulps_eq!, assert_error!) and whole-value comparison
  • Document algorithm, config, and output in user docs [doc]
  • File decision record: kb/decisions/recombination-detection.md
  • File issues: false-positive modes, parameter calibration, estimator statistics
  • File proposals: decoder performance, parity test coverage

Known issues

Possible improvements

  • Related to: #1768
  • Test data in nextclade_data: #464 (not for merging)
video-recombination-detection.mp4

🧪 Try it

Detection is on in the test datasets of #464. CLI binaries: GHA artifacts. In the web app, set "Genetic feature" to "Nucleotide sequence" to see the purple bands.

Selected datasets whose example sequences get recombination calls. Most example sequences have no call and show --: sort by the Rec. column to bring the calls to the top.

🧪 All test datasets: web links and CLI flags

CLI: nextclade run --server https://raw.githubusercontent.com/nextstrain/nextclade_data/refs/heads/feat/recombination-detection/data_output with the flags of the row.

Dataset Example sequences with calls Web CLI
nextstrain/sars-cov-2/BA.2 11 of 165 open --dataset-name nextstrain/sars-cov-2/BA.2
nextstrain/sars-cov-2/XBB 11 of 165 open --dataset-name nextstrain/sars-cov-2/XBB
community/neherlab/hiv-1/hxb2 9 of 32 open --dataset-name community/neherlab/hiv-1/hxb2
enpen/enterovirus/cva16 7 of 34 open --dataset-name enpen/enterovirus/cva16
nextstrain/hmpv/all-clades/NC_039199 6 of 98 open --dataset-name nextstrain/hmpv/all-clades/NC_039199
nextstrain/sars-cov-2/BA.2.86 6 of 165 open --dataset-name nextstrain/sars-cov-2/BA.2.86
community/v-gen-lab/dengue/denv1 3 of 67 open --dataset-name community/v-gen-lab/dengue/denv1
enpen/enterovirus/ev-a71 3 of 37 open --dataset-name enpen/enterovirus/ev-a71
enpen/enterovirus/ev-d68 3 of 30 open --dataset-name enpen/enterovirus/ev-d68
community/v-gen-lab/dengue/denv4 2 of 31 open --dataset-name community/v-gen-lab/dengue/denv4
nextstrain/orthoebolavirus/ebov 2 of 40 open --dataset-name nextstrain/orthoebolavirus/ebov
nextstrain/rsv/a/EPI_ISL_412866 2 of 32 open --dataset-name nextstrain/rsv/a/EPI_ISL_412866
nextstrain/rsv/b/EPI_ISL_1653999 2 of 32 open --dataset-name nextstrain/rsv/b/EPI_ISL_1653999
community/isuvdl/mazeller/prrsv2/orf5/yimim2023 1 of 50 open --dataset-name community/isuvdl/mazeller/prrsv2/orf5/yimim2023
community/v-gen-lab/dengue/denv2 1 of 89 open --dataset-name community/v-gen-lab/dengue/denv2
enpen/enterovirus/cva10 1 of 30 open --dataset-name enpen/enterovirus/cva10
nextstrain/measles/N450/WHO-2012 1 of 34 open --dataset-name nextstrain/measles/N450/WHO-2012
nextstrain/ndv/class-2/NC_075404 1 of 20 open --dataset-name nextstrain/ndv/class-2/NC_075404
nextstrain/rubella/E1 1 of 33 open --dataset-name nextstrain/rubella/E1
nextstrain/sars-cov-2/wuhan-hu-1/orfs 1 of 165 open --dataset-name nextstrain/sars-cov-2/wuhan-hu-1/orfs
nextstrain/sars-cov-2/wuhan-hu-1/proteins 1 of 165 open --dataset-name nextstrain/sars-cov-2/wuhan-hu-1/proteins
community/UdeM-LMIVV/BabyV/PRRSV2/nsp3-4-5/Baby2026 0 of 8 open --dataset-name community/UdeM-LMIVV/BabyV/PRRSV2/nsp3-4-5/Baby2026
community/anses/swIAV/H1 0 of 5 open --dataset-name community/anses/swIAV/H1
community/anses/swIAV/H3 0 of 3 open --dataset-name community/anses/swIAV/H3
community/anses/swIAV/N1 0 of 5 open --dataset-name community/anses/swIAV/N1
community/anses/swIAV/N2 0 of 7 open --dataset-name community/anses/swIAV/N2
community/genspectrum/marburg/HK1980/all-lineages 0 of 20 open --dataset-name community/genspectrum/marburg/HK1980/all-lineages
community/itps/zikav 0 of 100 open --dataset-name community/itps/zikav
community/moncla-lab/iav-h5/ha/2.3.2.1 0 of 12 open --dataset-name community/moncla-lab/iav-h5/ha/2.3.2.1
community/moncla-lab/iav-h5/ha/2.3.4.4 0 of 19 open --dataset-name community/moncla-lab/iav-h5/ha/2.3.4.4
community/moncla-lab/iav-h5/ha/all-clades 0 of 49 open --dataset-name community/moncla-lab/iav-h5/ha/all-clades
community/pathoplexus/cchfv/S 0 of 50 open --dataset-name community/pathoplexus/cchfv/S
community/pathoplexus/yellow-fever-virus 0 of 32 open --dataset-name community/pathoplexus/yellow-fever-virus
community/v-gen-lab/chikV/genotypes 0 of 39 open --dataset-name community/v-gen-lab/chikV/genotypes
community/v-gen-lab/dengue/denv3 0 of 38 open --dataset-name community/v-gen-lab/dengue/denv3
nextstrain/flu/b/ha/KX058884 0 of 49 open --dataset-name nextstrain/flu/b/ha/KX058884
nextstrain/flu/b/na/CY073894 0 of 49 open --dataset-name nextstrain/flu/b/na/CY073894
nextstrain/flu/h1n1pdm/ha/CY121680 0 of 48 open --dataset-name nextstrain/flu/h1n1pdm/ha/CY121680
nextstrain/flu/h1n1pdm/ha/MW626062 0 of 48 open --dataset-name nextstrain/flu/h1n1pdm/ha/MW626062
nextstrain/flu/h1n1pdm/na/MW626056 0 of 48 open --dataset-name nextstrain/flu/h1n1pdm/na/MW626056
nextstrain/flu/h3n2/ha/CY163680 0 of 49 open --dataset-name nextstrain/flu/h3n2/ha/CY163680
nextstrain/flu/h3n2/ha/EPI1857216 0 of 49 open --dataset-name nextstrain/flu/h3n2/ha/EPI1857216
nextstrain/flu/h3n2/na/EPI1857215 0 of 49 open --dataset-name nextstrain/flu/h3n2/na/EPI1857215
nextstrain/flu/vic/ha/KX058884 0 of 49 open --dataset-name nextstrain/flu/vic/ha/KX058884
nextstrain/flu/vic/na/CY073894 0 of 49 open --dataset-name nextstrain/flu/vic/na/CY073894
nextstrain/flu/yam/ha/JN993010 0 of 44 open --dataset-name nextstrain/flu/yam/ha/JN993010
nextstrain/mpox/all-clades 0 of 13 open --dataset-name nextstrain/mpox/all-clades
nextstrain/mpox/clade-i 0 of 6 open --dataset-name nextstrain/mpox/clade-i
nextstrain/mpox/clade-iib 0 of 5 open --dataset-name nextstrain/mpox/clade-iib
nextstrain/mpox/lineage-b.1 0 of 9 open --dataset-name nextstrain/mpox/lineage-b.1
nextstrain/ndv/class-1/AB524405 0 of 20 open --dataset-name nextstrain/ndv/class-1/AB524405
nextstrain/wnv/all-lineages 0 of 91 open --dataset-name nextstrain/wnv/all-lineages
nextstrain/yellow-fever/prM-E 0 of 34 open --dataset-name nextstrain/yellow-fever/prM-E
🧪 Smoke test: run every test dataset
#!/usr/bin/env bash
# Run Nextclade of PR #1774 on the example sequences of every test dataset of nextclade_data PR #464.
# Output of each dataset: recombination-test/<dataset name>/

NEXTCLADE=nextclade   # path to the nextclade binary of PR #1774
BRANCH=https://raw.githubusercontent.com/nextstrain/nextclade_data/refs/heads/feat/recombination-detection

while read -r name examples; do
  echo "=== $name"
  curl -fsSL "$BRANCH/data/$name/$examples" |
    "$NEXTCLADE" run --server "$BRANCH/data_output" --dataset-name "$name" --output-all "recombination-test/$name"
done <<'DATASETS'
community/UdeM-LMIVV/BabyV/PRRSV2/nsp3-4-5/Baby2026 sequences.fasta
community/anses/swIAV/H1 sequences.fasta
community/anses/swIAV/H3 sequences.fasta
community/anses/swIAV/N1 sequences.fasta
community/anses/swIAV/N2 sequences.fasta
community/genspectrum/marburg/HK1980/all-lineages examples.fasta
community/isuvdl/mazeller/prrsv2/orf5/yimim2023 sequences.fasta
community/itps/zikav sequences.fasta
community/moncla-lab/iav-h5/ha/2.3.2.1 example_sequences.fasta
community/moncla-lab/iav-h5/ha/2.3.4.4 example_sequences.fasta
community/moncla-lab/iav-h5/ha/all-clades example_sequences.fasta
community/neherlab/hiv-1/hxb2 sequences.fasta
community/pathoplexus/cchfv/S sample_S.fasta
community/pathoplexus/yellow-fever-virus sequences.fasta
community/v-gen-lab/chikV/genotypes sequences.fasta
community/v-gen-lab/dengue/denv1 sequences.fasta
community/v-gen-lab/dengue/denv2 sequences.fasta
community/v-gen-lab/dengue/denv3 sequences.fasta
community/v-gen-lab/dengue/denv4 sequences.fasta
enpen/enterovirus/cva10 sequences.fasta
enpen/enterovirus/cva16 sequences.fasta
enpen/enterovirus/ev-a71 sequences.fasta
enpen/enterovirus/ev-d68 sequences.fasta
nextstrain/flu/b/ha/KX058884 sequences.fasta
nextstrain/flu/b/na/CY073894 sequences.fasta
nextstrain/flu/h1n1pdm/ha/CY121680 sequences.fasta
nextstrain/flu/h1n1pdm/ha/MW626062 sequences.fasta
nextstrain/flu/h1n1pdm/na/MW626056 sequences.fasta
nextstrain/flu/h3n2/ha/CY163680 sequences.fasta
nextstrain/flu/h3n2/ha/EPI1857216 sequences.fasta
nextstrain/flu/h3n2/na/EPI1857215 sequences.fasta
nextstrain/flu/vic/ha/KX058884 sequences.fasta
nextstrain/flu/vic/na/CY073894 sequences.fasta
nextstrain/flu/yam/ha/JN993010 sequences.fasta
nextstrain/hmpv/all-clades/NC_039199 sequences.fasta
nextstrain/measles/N450/WHO-2012 sequences.fasta
nextstrain/mpox/all-clades sequences.fasta
nextstrain/mpox/clade-i sequences.fasta
nextstrain/mpox/clade-iib sequences.fasta
nextstrain/mpox/lineage-b.1 sequences.fasta
nextstrain/ndv/class-1/AB524405 sequences.fasta
nextstrain/ndv/class-2/NC_075404 sequences.fasta
nextstrain/orthoebolavirus/ebov example_sequences.fasta
nextstrain/rsv/a/EPI_ISL_412866 sequences.fasta
nextstrain/rsv/b/EPI_ISL_1653999 sequences.fasta
nextstrain/rubella/E1 sequences.fasta
nextstrain/sars-cov-2/BA.2 sequences.fasta
nextstrain/sars-cov-2/BA.2.86 sequences.fasta
nextstrain/sars-cov-2/XBB sequences.fasta
nextstrain/sars-cov-2/wuhan-hu-1/orfs sequences.fasta
nextstrain/sars-cov-2/wuhan-hu-1/proteins sequences.fasta
nextstrain/wnv/all-lineages examples.fasta
nextstrain/yellow-fever/prM-E sequences.fasta
DATASETS

Provenance

Design and function contract specified in the Nextclade multi-reference meeting (2026-06-26). Implementation follows a Python prototype and its algorithm notes. A scientific review of the first implementation (2026-11) set the opt-in, the default $\gamma$, and the checks of the calls; the checks follow the reviewers' reimplementation of the call pipeline.

Motivation

A recombinant sequence -- one whose genome is a mosaic of segments from different lineages -- produces a localized cluster of private mutations when placed on the reference tree. Nextclade currently has no way to distinguish this pattern from a poorly sequenced region, a novel variant, or contamination. The private-mutation QC rule penalizes all three equally.

This PR adds a per-sequence detector that identifies where the breakpoints are, without naming the donor lineage. Downstream consumers can mask the flagged regions and re-place if needed.

Design

The full specification is in the decision record, which covers the model, estimation, the checks of the calls, opt-in, configuration, output, viewer, and deferred work. The summary below is for reviewers who want to evaluate the approach without reading the full document.

Model

A two-state Hidden Markov Model walks the alignment with states wildtype ($w$) and recombinant ($r$), decoded by Viterbi in log-space [src]. At each reference position the model sees one of three observations relative to the sequence's inferred parent [src]:

Observation Meaning Emission
Ref matches parent $P = 1 - \mu_w$ or $1 - \mu_r$ by state
Mut private substitution $P = \mu_w$ or $\mu_r$ by state
Missing N, deletion, ambiguity, placement-masked $P = 1$ (both states)

Missing positions contribute no evidence but allow transitions to persist across uncovered stretches, so a recombinant region bridging an N run is not split. Deletions are Missing because a large deletion is one mutational event, not a cluster of per-site mutations that would inflate local density and trigger false calls. Placement-masked sites are Missing to prevent false calls at homoplasic positions. Each maximal run of the recombinant state, trimmed to covered ends [src], is a candidate region.

Parameters

Three parameters govern the model [src]:

Parameter Role Default estimation
$\gamma$ transition rate $0.01 / L_\text{ref}$ [src]
$\mu_w$ wildtype emission mean terminal branch length / $L_\text{ref}$
$\mu_r$ recombinant emission median pairwise inter-clade leaf distance / $L_\text{ref}$

Parameters are resolved once per dataset, not per sequence. Each parameter resolves independently: an explicit pathogen.json value bypasses estimation for that parameter. Estimation counts true substitutions only, because the decoder observes neither insertions nor deletions. Recombinants are rare in many viral species, so the expected switch rate is far below one per genome: each state transition costs $c = \ln((1-\gamma)/\gamma) \approx 14.9$ nats for a 30 kb genome, and the low rate removes very short calls. Three invariants are enforced on every construction and deserialization path: all parameters in $(0,1)$; $\gamma &lt; 0.5$; $\mu_r &gt; \mu_w$ [src].

Parameter estimation in the dataset repository

scripts/recombination_params in nextclade_data computes the same three estimates from a dataset's reference tree and writes them into its pathogen.json, so that a dataset carries reviewed values. The test datasets of #464 carry values computed this way.

  • Estimation of $\gamma$, $\mu_w$, $\mu_r$ from the tree [src]
  • Expected state switches per genome, which gives $\gamma = 0.01 / L_\text{ref}$ [src]

Checks of the calls

The decoder marks every stretch of high mutation density, including short stretches next to missing data, stretches that are mostly N, and whole divergent sequences or short fragments, where an all-recombinant path pays no switch cost. Nextclade reports a call only when the evidence is strong [src]:

  • Region checks [src]: drop a region whose fraction of missing sites is above maxRegionMissingFraction (default 0.5), otherwise drop it when its span is below minRegionLength (default 50)
  • Sequence checks [src], each dropping all regions of the sequence:
    1. Coverage: the regions span more than maxRecombinantFraction (default 2/3) of the alignment range
    2. Rest of the sequence [src]: the private mutations outside the regions reach the private-mutation QC threshold scaled to the rest, $\text{weighted total} \ge (\text{typical} + \text{cutoff}) \cdot L_m / L_\text{ref}$, where $L_m$ is the number of covered sites outside the regions. The weighted total comes from the QC rule's own counting [src]

Opt-in

Detection runs only for datasets that enable it with recombination.enabled, because the model does not fit every pathogen (in HIV, the whole genome carries a high density of private mutations). Nextclade CLI overrides the dataset in both directions with --with-recombination and --without-recombination; one function decides [src]. When detection is on, every reason that blocks it fails the dataset load with an error that names the cause [src]: no reference tree, an invalid setting, a parameter that the tree cannot estimate (for example fewer than two clades), or no qc.privateMutations rule.

Configuration

All settings sit in the recombination object of pathogen.json [src]. Values for SARS-CoV-2:

{
  "recombination": {
    "enabled": true,
    "gamma": 3.3e-7,
    "muW": 0.00017,
    "muR": 0.0061,
    "minRegionLength": 50,
    "maxRegionMissingFraction": 0.5,
    "maxRecombinantFraction": 0.667
  }
}

enabled defaults to false; every other field is optional. Nextclade reports the effective $\gamma$, $\mu_w$, $\mu_r$ of each run as recombinationParams in nextclade.json; dataset curators copy reviewed values into pathogen.json to freeze them.

🧪 Values set in the test datasets of #464
Dataset gamma muW muR Source
community/UdeM-LMIVV/BabyV/PRRSV2/nsp3-4-5/Baby2026 5.51e-06 0.0108 0.305 src
community/anses/swIAV/H1 5.71e-06 0.0387 0.492 src
community/anses/swIAV/H3 5.76e-06 0.0281 0.246 src
community/anses/swIAV/N1 7.09e-06 0.0131 0.289 src
community/anses/swIAV/N2 6.96e-06 0.0326 0.269 src
community/genspectrum/marburg/HK1980/all-lineages 5.23e-07 0.00084 0.0891 src
community/isuvdl/mazeller/prrsv2/orf5/yimim2023 1.66e-05 0.0113 0.234 src
community/itps/zikav 9.25e-07 0.00103 0.153 src
community/moncla-lab/iav-h5/ha/2.3.2.1 5.87e-06 0.0346 0.119 src
community/moncla-lab/iav-h5/ha/2.3.4.4 5.87e-06 0.0317 0.126 src
community/moncla-lab/iav-h5/ha/all-clades 5.68e-06 0.0774 0.248 src
community/neherlab/hiv-1/hxb2 1.09e-06 0.0311 0.256 src
community/pathoplexus/cchfv/S 5.98e-06 0.00461 0.19 src
community/pathoplexus/yellow-fever-virus 9.21e-07 0.00144 0.208 src
community/v-gen-lab/chikV/genotypes 8.46e-07 0.000775 0.085 src
community/v-gen-lab/dengue/denv1 9.32e-07 0.00397 0.105 src
community/v-gen-lab/dengue/denv2 9.33e-07 0.00428 0.114 src
community/v-gen-lab/dengue/denv3 9.34e-07 0.00432 0.0855 src
community/v-gen-lab/dengue/denv4 9.39e-07 0.0066 0.109 src
enpen/enterovirus/cva10 1.35e-06 0.00617 0.356 src
enpen/enterovirus/cva16 1.35e-06 0.00531 0.191 src
enpen/enterovirus/ev-a71 1.35e-06 0.00587 0.371 src
enpen/enterovirus/ev-d68 1.36e-06 0.00223 0.162 src
nextstrain/flu/b/ha/KX058884 5.31e-06 0.00106 0.123 src
nextstrain/flu/b/na/CY073894 7.14e-06 0.00107 0.0435 src
nextstrain/flu/h1n1pdm/ha/CY121680 5.71e-06 0.00112 0.0371 src
nextstrain/flu/h1n1pdm/ha/MW626062 5.71e-06 0.000957 0.024 src
nextstrain/flu/h1n1pdm/na/MW626056 6.98e-06 0.000884 0.0181 src
nextstrain/flu/h3n2/ha/CY163680 5.76e-06 0.00116 0.0328 src
nextstrain/flu/h3n2/ha/EPI1857216 5.82e-06 0.00103 0.0274 src
nextstrain/flu/h3n2/na/EPI1857215 6.95e-06 0.001 0.0174 src
nextstrain/flu/vic/ha/KX058884 5.31e-06 0.000792 0.0186 src
nextstrain/flu/vic/na/CY073894 7.14e-06 0.000937 0.0164 src
nextstrain/flu/yam/ha/JN993010 5.7e-06 0.000989 0.0251 src
nextstrain/hmpv/all-clades/NC_039199 7.49e-07 0.00162 0.245 src
nextstrain/measles/N450/WHO-2012 2.22e-05 0.00214 0.0911 src
nextstrain/mpox/all-clades 5.07e-08 1.95e-05 0.00472 src
nextstrain/mpox/clade-i 5.08e-08 1.9e-05 0.000756 src
nextstrain/mpox/clade-iib 5.07e-08 1.51e-05 0.00276 src
nextstrain/mpox/lineage-b.1 5.07e-08 9.88e-06 0.000578 src
nextstrain/ndv/class-1/AB524405 6.58e-07 0.00372 0.313 src
nextstrain/ndv/class-2/NC_075404 6.59e-07 0.00523 0.39 src
nextstrain/orthoebolavirus/ebov 5.27e-07 0.000105 0.0267 src
nextstrain/rsv/a/EPI_ISL_412866 6.57e-07 0.00091 0.0171 src
nextstrain/rsv/b/EPI_ISL_1653999 6.57e-07 0.000906 0.0155 src
nextstrain/rubella/E1 6.93e-06 0.00536 0.0624 src
nextstrain/sars-cov-2/BA.2 3.34e-07 0.000118 0.00241 src
nextstrain/sars-cov-2/BA.2.86 3.34e-07 0.000117 0.00348 src
nextstrain/sars-cov-2/XBB 3.34e-07 0.000118 0.00241 src
nextstrain/sars-cov-2/wuhan-hu-1/orfs 3.34e-07 0.000171 0.00612 src
nextstrain/sars-cov-2/wuhan-hu-1/proteins 3.34e-07 0.000171 0.00612 src
nextstrain/wnv/all-lineages 9.07e-07 0.00917 0.286 src
nextstrain/yellow-fever/prM-E 1.49e-05 0.00511 0.213 src

Output

Recombination is an observation about sequence origin, not a quality metric, so results go into dedicated output fields rather than the QC system. Without detection, the outputs carry no recombination fields.

JSON: recombination field on each sequence result, omitted when the sequence has no call; the effective parameters once per run as recombinationParams:

{
  "regions": [{ "range": { "begin": 100, "end": 200 }, "length": 100 }],
  "totalRegions": 1,
  "totalLength": 100,
  "longestRegion": { "range": { "begin": 100, "end": 200 }, "length": 100 }
}

TSV: dot-notation columns in a dedicated Recombination category (recombination.regions, recombination.totalRegions, recombination.totalLength, recombination.longestRegion.range, recombination.longestRegion.length), present only for datasets that run detection [src].

Viewer

  • Purple markers (#8f2fd4 fill, #e0b3ff border) in all nucleotide views (absolute and relative)
  • Tooltip: "Putative recombinant" with range and length
  • Rec. column in the results table, only for datasets that run detection, sortable by total recombinant length, with a tooltip showing region count, total length, longest region, and the region list

Differences from the prototype

  • Three-valued observations: Missing with emission probability 1 instead of binary ${0, 1}$
  • Placement-masked sites: treated as Missing to prevent false calls at homoplasic positions
  • Interval trimming: leading/trailing Missing stripped so reported ranges start and end at covered positions
  • Checks of the calls: region and sequence checks after decoding
  • Parameter validation: $\gamma &lt; 0.5$ and deserialization through TryFrom in addition to range checks

Validation

  • Unit tests for each check at its boundary values, the setup errors, the opt-in decision, and the per-sequence entry point; golden-master parity of the Viterbi path with the prototype
  • Acceptance on the example sequences of CVA16, EV-D68, SARS-CoV-2, flu H3N2 HA, RSV-A and mpox (332 sequences): the reviewers' call pipeline, with the rest-of-sequence check on the fraction of the genome, gives the same calls as this build on every sequence
  • Against the reviewers' published table of proposed calls, 26 of 27 sequences match. CVA16 FN298942, a fragment that covers 479 of 7413 sites, loses its call: its rest scales by the fraction of the genome (threshold 5.7) instead of the fraction of the sequence (threshold 88.7)

Work items

  • Implement Viterbi decoder with three-valued observations and log-space arithmetic
  • Estimate $\gamma$, $\mu_w$, $\mu_r$ from the reference tree and the reference length, calibrating on substitutions only
  • Wire detection into the per-sequence pipeline [src] [src]
  • Report regions as RecombinationRegion with dot-notation TSV columns and a Rec. table column
  • Render purple recombination markers in all nucleotide views
  • Make detection opt-in per dataset, with CLI overrides and load errors that name the cause
  • Drop weak regions, and calls that cover most of a sequence or whose rest does not fit the tree
  • Document algorithm, config, and output in user docs [doc]
  • Record the design: kb/decisions/recombination-detection.md

Known issues

Possible improvements

@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Two-state HMM (wildtype vs recombinant) decoded by Viterbi in log-space.
Three-valued observations (Ref, Mut, Missing) where Missing emits with
probability 1 in both states, contributing no evidence while allowing
transitions across uncovered stretches.

Adds pathogen.json config schema with gamma, muW, muR parameters.
- gamma = 1/L: one expected state switch per genome
- muW = mean terminal branch length / L: typical divergence of a new sequence
- muR = median pairwise inter-clade leaf distance / L: expected mutation
  density in a region from a different clade
Run detection per-sequence in the parallel phase after private mutation
calling. Surface skip reasons through the warnings output when detection
cannot run (no tree, too few clades, no branch mutations).
Purple markers on the sequence view with tooltip showing "Putative
recombinant", nucleotide range, and length.
Enforce invariants on construction: parameters in (0,1), gamma < 0.5
(state switching rarer than staying), muR > muW (recombinant state carries
elevated divergence). Trim leading/trailing Missing positions from decoded
intervals so reported ranges start and end at covered positions.
Use pairwise leaf-to-leaf distances via MRCA path lengths instead of
founder-to-founder distances. Founder distances underestimate inter-clade
divergence when founder branches are short relative to the tips.
… as missing

Exclude deletions from per-branch mutation counts: a deletion is a single
event, not a run of per-site mutations. Treat placement-masked positions
as Missing to prevent false recombinant calls at homoplasic sites.
Nested RecombinationRegion with range, length, and optional confidence.
Dot-notation TSV columns in a dedicated Recombination output category.
Rec. column in the results table with sortable total length and tooltip.
Forward-backward algorithm computes per-site posterior marginals in
log-space. Each Viterbi-decoded interval receives a confidence score
equal to the mean posterior marginal within it. Higher confidence
produces more opaque markers in the viewer.
Show markers in absolute and all relative views. Add per-region
confidence to the Rec. column tooltip. Cap the tooltip region list
before building React elements.
Resolve each HMM parameter independently: explicit pathogen.json values
bypass estimation for that parameter. Validate RecombinationHmmParams on
deserialization via TryFrom. Parse branch mutation tokens structurally to
classify deletions by gap base. Add minPrivateSubsToRun gate (default 1).
Introduce shared test macros (pretty_assert_ulps_eq!,
pretty_assert_abs_diff_eq!, assert_error!). Derive PartialEq on result
types and compare whole values.
Add algorithm page to user docs. Document pathogen.json recombination
config, output columns, and parameter bounds. Fix broken pipe escaping in
the QC-status TSV table.
Decision record covering model specification, parameter estimation,
observation model, pipeline integration, configuration, output format,
and viewer behavior. Includes follow-up proposals and minimizer scoring
notes.
Point the gamma and muW references at the current `estimate_gamma` and `estimate_mu_w` functions in `recombination_estimate.rs`; the old line ranges had drifted onto unrelated code as helpers were added above them.
ivan-aksamentov and others added 27 commits November 17, 2026 16:08
- Add a direct `compute_log_emission` test with hand-derived `ln` values, independent of the brute-force oracles (which reuse the same emission function) so a Ref/Mut or wildtype/recombinant column swap is caught.
- Collapse per-element assertion loops: the brute-force marginal test compares each state column as a whole slice (`approx` implements `AbsDiffEq` for `[f64]`), and the qualitative-band and confidence loops become single min/max assertions that report the offending extreme.
- Add boundary cases: zero reference length for `build_observations`, a per-field `muW` out-of-range override, and full `RecombinationConfig` camelCase serde round-trip.
- Use `json_parse` for golden-master fixtures; drop assertions entailed by a preceding whole-value equality; pair range and confidence at the `from_ranges` call sites.

The serde round-trip keeps a 2-ULP tolerance: serde_json's default float parser is best-effort, not bit-exact (its `float_roundtrip` feature would guarantee exactness), so a bit-exact assertion flakes by ~1 ULP. The genome-scale golden-master tolerance stays at 1e-7: the measured max marginal divergence from the prototype's `log(0)` smoothing is 3.19e-8, so 1e-8 does not pass.
Repoint KB issue and proposal links, and the golden-master capture-script header, to the split `recombination/*.rs` files: the monolithic `recombination.rs` and `recombination_estimate.rs` no longer exist. Stale line anchors are dropped, since the split changed line numbers; the links now target the correct concern file.

Also convert the algorithm page's definition lists from `term -- description` to `term: description`.
`ColumnRecombination` and `SequenceMarkerRecombination` each reimplemented percentage rendering. Extract `formatPercentage` and `formatPercentageOfTotal` so the precision and the zero-denominator policy live in one place.
- `ln(0.1)` in the emission test equals `-LN_10`; the hand-derived `ln` expected values are a deliberate oracle, not an approximation of a named constant.
The muW/muR tree-based estimates counted insertion tokens (gap reference, e.g. "-10A") as branch substitutions, but the decoder never observes insertions: its `Mut` emissions come from `private_substitutions` only and `build_observations` has no insertion channel. Counting them calibrated the emission rates against events the model cannot score, inflating both rates on externally produced trees (augur/TreeTime) that carry insertion tokens.

Count a branch mutation only when both reference and query bases are present (non-gap), so calibration matches the substitution-only event set the decoder sees. Nextclade-built trees carry substitutions only and are unaffected.
Reconcile the decision record with the substitution-only calibration: both muW and muR count a branch mutation only when reference and query bases are present, so neither insertions nor deletions contribute. Update the nextclade_data mirror description accordingly and remove the now-resolved known issue.
- Function-level `#[allow]` does not suppress warnings from `#[case]` attribute arguments; module-level does
- The recombination columns form a static category, so a separate include flag duplicated the category selection and was never read
- Viterbi decoding alone decides the calls; the region and sequence checks replace the confidence score as the evidence filter
- `recombination.enabled` in pathogen.json switches detection on; `--with-recombination` and `--without-recombination` override it in both directions
- When detection is on, every reason that blocks it fails the dataset load with an error that names the cause, instead of a silent skip
- Only a sequence without private substitutions cannot produce a call, so the skip stays internal and exact
- Recombinants are rare in many viral species, so the expected switch rate is far below one per genome; the higher switch cost also needs more mutations for a call and removes very short calls
- A region whose span is mostly missing data, or that is shorter than a minimal length, rests on too little evidence for a call
- `recombination.maxRegionMissingFraction` (default 0.5) and `recombination.minRegionLength` (default 50) set the thresholds
- The weighted total of the private mutations rule becomes reusable on a subset of positions, so the recombination checks can apply it to the part of a sequence outside the recombinant regions
…e rest does not fit the tree

- A sequence whose regions span more than `recombination.maxRecombinantFraction` (default 2/3) of its alignment carries no localized signal
- The private mutations outside the regions must still pass the private mutations QC rule, with `typical` and `cutoff` scaled by the covered fraction of the genome outside the regions; detection therefore requires `qc.privateMutations`
- The output tables have no recombination columns and the results table has no Rec. column for a dataset that does not run detection
@ivan-aksamentov
ivan-aksamentov force-pushed the feat/recombination-detection branch from eb4445b to 3ffc42c Compare November 17, 2026 15:19
@ivan-aksamentov
ivan-aksamentov merged commit 3ffc42c into master Nov 17, 2026
@ivan-aksamentov
ivan-aksamentov deleted the feat/recombination-detection branch November 17, 2026 15:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants