Skip to content

v2 fix 7: scored, dominance-aware per-well pairing with confidence and margin - #20

Merged
bnemoz merged 7 commits into
mainfrom
v2/scored-pairing
Nov 18, 2026
Merged

bnemoz merged 7 commits into
mainfrom
v2/scored-pairing

Conversation

@bnemoz

@bnemoz bnemoz commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Fix 7: scored, dominance-aware per-well pairing with a confidence and a margin per pair

Why

run() kept a barcode only if assign_pairs found exactly 1 heavy + 1 light chain. Barcodes with several chains in a well (1H+2L, 2H+1L, 2H+2L…) hold about 32% of productive UMIs and were dropped entirely, although in about half of the 1H+2L / 2H+1L cases one chain dominates by ≥2× in UMIs.

What

New module pairplex/pairing.py. The pairing block of run() is now a single pair_well(...) call, which keeps merge conflicts with lanes A1/C small.

Scored rule (new default, pairing="scored"), applied per (well, barcode):

  1. Take the productive heavy chains (IGH) and the productive light chains. IGK and IGL form one light group, because a cell expresses one light chain, so kappa and lambda compete.
  2. Merge contigs of the same locus that share V gene, J gene and CDR3 aa (collapse_clonal=True), summing their support. These are one chain split into two consensus clusters, or clonal relatives, and they should not compete with each other. Without this step, a barcode holding two copies of one heavy fails the dominance test and the lineage is lost.
  3. Rank each group by corrected UMIs (metadata CSV umis, joined on contig name), then reads, then name.
  4. Emit the top heavy + top light if, in each group, u1 ≥ min_dominance × u2 (default 2: the top chain holds ≥ 2/3 of a 2-chain group). Near-even splits, where picking the top chain is close to a coin flip, stay unpaired.
  5. Score:
    • confidence = s_H × s_L, with s = u1 / (U + 1): the top chain's share of the group's UMIs, with one pseudo-UMI for an unobserved competitor. It lies in [0, 1), rises with the top chain's support and falls with every competitor's.
    • margin = min over groups of (u1 − u2) / (U + 1).
    • umis:0, umis:1: the support used for ranking.

Outputs:

  • annotated/<well>_paired.{parquet,tsv} now include resolved multi-chain barcodes, plus columns confidence, margin, umis:0, umis:1.
  • New pairs/pairs.parquet: all wells concatenated in the contract schema (barcode, well, name, confidence, margin, plus locus, v_gene, j_gene, junction, cdr3_aa, sequence_id, sequence, umis for :0/:1; well is the source well). It is written only in scored mode.

Options (run() and CLI):

run() CLI default
pairing ("scored" / "exact") --pairing "scored"
min_dominance --min-dominance 2.0
collapse_clonal --collapse-clonal/--no-collapse-clonal True
legacy --legacy False

legacy=True forces "exact", the unchanged v2-base code path. pooled_pairing.py is untouched.

Legacy parity

On the 2 simulated smoke wells, legacy=True reproduces v2-base exactly for metadata, consensus FASTA, and the unpaired and paired parquet/TSV files. Row order differs because v2-base itself is order-nondeterministic (as_completed), so the comparison sorts rows by key first. In legacy mode no pairs/ directory is written.

Tests

pairplex/tests/test_pairing.py:

  • resolve_barcode cases:
    • 1H+1L, strong and 1-UMI support;
    • 1H+2L with a dominant chain;
    • ambiguous 2H+2L;
    • kappa vs lambda;
    • threshold boundary and tie-break by reads;
    • monotonicity of the confidence;
    • a missing locus group.
  • Well-level resolution:
    • clonal relatives get collapsed;
    • different clonotypes still compete.
  • Output writing and the contract schema.
  • Exact mode.
  • An opt-in end-to-end smoke test, with PAIRPLEX_SMOKE_READS pointing to a directory of per-well FASTQs. It runs legacy and scored mode and checks outputs and columns.

pytest pairplex: 30 passed, 1 skipped; the smoke test also passes when enabled.

Benchmark

Candidate run B-scored-dom2-collapse (commit a32d67d, all 4 datasets), compared with compare.py --pairs-vs per_well. pairs/pairs.parquet holds per-well pairs, so it is compared with the baseline per-well set.

[PASS] sim_cal / per_well
   precision            0.593 ->      0.619
   cell_recall          0.126 ->      0.147
   emitted               1413 ->       1575
[FAIL] sim_cal / pooled
   precision            0.627 ->      0.626
   cell_recall          0.152 ->      0.151
   emitted               1585 ->       1585
   n_conf0.9               41 ->         41
   prec_conf0.9         0.878 ->      0.878
[PASS] sim_cal / pairs (vs baseline per_well)
   precision            0.593 ->      0.619
   cell_recall          0.126 ->      0.147
   emitted               1413 ->       1575
   n_conf0.9                — ->          0
[PASS] sim_imp / per_well
   precision            0.865 ->      0.947
   cell_recall          0.199 ->      0.788
   emitted               1632 ->       5917
[PASS] sim_imp / pooled
   precision            0.967 ->      0.967
   cell_recall          0.871 ->      0.871
   emitted               6368 ->       6370
   n_conf0.9             4387 ->       4387
   prec_conf0.9         0.987 ->      0.988
[PASS] sim_imp / pairs (vs baseline per_well)
   precision            0.865 ->      0.947
   cell_recall          0.199 ->      0.788
   emitted               1632 ->       5917
   n_conf0.9                — ->          0
runtime: 17386s -> 18991s (PASS, 1.09x, limit 1.5x)
OVERALL: FAIL (only sim_cal / pooled; see below)

Real data (clonal purity):

dataset / set verdict purity delta
real_d02 / per_well PASS +4.7 pts
real_d02 / pairs (vs per_well) PASS +4.7 pts
real_d02 / pooled PASS +0.1 pt
real_d07 / per_well PASS +1.6 pts
real_d07 / pairs (vs per_well) PASS +1.6 pts
real_d07 / pooled PASS 0.0 pt

About the one FAIL (sim_cal / pooled). compare.py reports OVERALL FAIL because of this set. Pooled pairing reads only *_unpaired.parquet and metadata/*.csv, which this PR does not change. The same commit run sims-only (B-scored-dom2-collapse-sim) gave sim_cal / pooled 0.628 / 0.152 (PASS). The first version (B-scored-dom2) gave 0.630 / 0.152 (PASS). This FAIL therefore looks like run-to-run nondeterminism in the shared upstream pipeline, not an effect of this change. It is still a FAIL under the rule as written, and I am reporting it as one.

Other runs:

  • B-scored-dom2 (commit 564bb4c, no clonal collapse, 4 datasets) passed everything. sim_cal per-well: 0.608 precision / 13.8% recall. sim_imp: 0.941 / 66.8%. Real purity deltas: +4.4 and +1.5 pts.
  • B-scored-dom2-collapse-sim (sims only) passed everything. Collapsing improved both precision and recall on both sims, so it was kept. min_dominance was not tuned: only the default 2.0 was run.

Confidence scale. The confidence ranks pairs well, but it is under-confident and never reaches 0.9 on the sims (n_conf0.9 = 0).

Precision per confidence bin on the sims:

bin sim_cal sim_imp
0.1–0.3 0.54 0.41
0.3–0.6 0.72 0.96
0.6–0.9 1.00 (n = 3) 0.99

On real data, purity rises in the same way across bins (about 0.5 below 0.6, above 0.99 from 0.6 up), and the ≥0.9 bin is pure on both datasets.

Two reasons for the low values:

  • The product of two shares with a pseudo-count is harsh: a 1H+1L barcode needs about 19 UMIs per chain to reach 0.9.
  • Per-bin precision depends on the regime (leakage, ambient): the 0.3–0.6 bin holds 0.72 on sim_cal against 0.96 on sim_imp. A per-barcode, per-well score cannot see the regime, so no fixed mapping can be calibrated for both.

I did not rescale it on the benchmark. Treat confidence as an ordinal score: monotonic and documented, but not a calibrated probability. A per-reaction calibration, for example using the leakage that pair-pooled estimates, would be the principled next step.

Lineage retention: REVIEW (real_d02 and real_d07, per_well and pairs sets). 15 baseline lineages of ≥5 cells are lost in total (5 in one reaction, 10 in the other), all with 0 cells recovered.

I checked the baseline per-well pairs of every lost lineage on the harness pod: 171 of 171 have a non-productive heavy chain (several CDRH3s contain a stop codon). The scored rule pairs productive chains only, per the spec. The v2-base rule paired any chain, and 16–20% of baseline per-well pairs contain a non-productive chain. These losses are therefore intended: they are not real lineages being dropped by multi-chain resolution.

Cells recovered for baseline clones of ≥10 cells: 0.95–0.96. Light-chain coherence of the expanded clones is unchanged or slightly up. The clone identifiers are held back from this public PR and can be shared privately.

Risks / open points

  • Pairs with a non-productive chain are no longer emitted. This is per the spec, but it is a behaviour change. If those pairs are wanted (for example for QC), they could come back behind an option.
  • The confidence is not calibrated (see above).
  • TCR is not handled by either rule. Neither was it before: assign_pairs light/heavy groups are BCR-only.

🤖 Generated with Claude Code

bnemoz and others added 7 commits November 17, 2026 16:18
Adds pairplex/umi.py:collapse_umis_directional (UMI-tools directional adjacency,
neighbour generation, N-containing UMIs absorbed but never absorbing). process_droplet
collapses UMIs per droplet partition: umi_raw keeps the raw UMI, metadata umis is the
corrected count and umis_raw the raw count; min_cluster_umis filters on corrected counts.

run(umi_collapse='directional'|'none'), CLI --umi-collapse; run(legacy=True) / --legacy
forces 'none' (v2-base behaviour).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fix 7)

Barcodes with several productive chains in a well were dropped by the exact
1 heavy + 1 light rule. The new default ranks productive heavy and light
(IGK+IGL) chains by UMIs then reads, emits the top heavy + top light when each
group's top chain has >= min_dominance x the second's UMIs (default 2), and
scores each pair: confidence = s_H * s_L with s = u1/(U + 1), margin =
min over groups of (u1 - u2)/(U + 1). Per-well paired files gain confidence,
margin, umis:0, umis:1; all wells are written to pairs/pairs.parquet in the
contract schema. pairing='exact' / legacy=True keep the v2-base rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e, QC report

- annotated outputs carry cluster support: umis, reads, cluster_fraction,
  barcode, contig (unpaired) and umis:0/1, reads:0/1, ... (paired); the
  always-null abstar `umi` column is dropped (a consensus contig has no
  single UMI; the count lives in `umis`)
- qc/stage_counts.csv: drop counts at every stage, per well and TOTAL
  (reads, barcode groups, empty sequences skipped by greedy_clustering,
  clusters failing each filter, annotation outcomes, chain composition,
  emitted pairs)
- qc/annotation_failures.csv: abstar record errors (from its failures.tsv
  warning), unassigned reasons, productivity issues, missing junctions
- qc/report.{json,md}: fragment fraction by locus, UMI Hamming-1 excess
  vs shuffled null, heavy-junction multi-barcode share, leakage f by
  chain (>= 8 wells), pair confidence distribution, clonal light-chain
  purity with chance and a memory-only caveat
- new run() kwargs support_columns=True, qc=True, legacy=False (legacy
  forces both off and reproduces v2-base); matching CLI options
- pairing is unchanged; logic lives in pairplex/qc.py behind small hooks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two same-locus contigs of one (well, barcode) sharing V gene, J gene and CDR3 aa
are one chain split into two consensus clusters, or clonal relatives. Ranked
separately they split the UMIs and fail the dominance test, dropping the
barcode (and the lineage). Merge them first (summed UMIs/reads, best contig
kept). Option collapse_clonal (default True), CLI --collapse-clonal/--no-collapse-clonal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…x/barcode_prefer_exact alongside umi_collapse; legacy forces all)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… all v2 options; abstar always gets an explicit mmseqs_threads)

Stacked on #18 (v2/umi-collapse-perwell): merge #18 first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- one legacy flag forcing every v2 option (now also pairing='exact')
- qc chain-composition counts taken before the pairing rule; emitted_pairs from pair_well
- umis:0/1 keep #19's meaning (the contig's own UMI count); the ranking support summed over
  merged same-clonotype contigs moves to chain_umis:0/1 (also in pairs/pairs.parquet)

Stacked on #19 (which is stacked on #18): merge #18, then #19, then this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@bnemoz
bnemoz merged commit 91397e0 into main Nov 18, 2026
8 checks passed
bnemoz added a commit that referenced this pull request Nov 18, 2026
legacy also forces pooling='per_well'; the per-well-only options (umi_collapse, pairing,
min_dominance, collapse_clonal, support_columns, qc) are documented as not applying in
cross-well mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant