strainphase 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
strainphase/core.py ADDED
@@ -0,0 +1,3719 @@
1
+ #!/usr/bin/env python3
2
+ """Hybrid graph-probabilistic haplotype reconstruction for long-read metagenomics.
3
+
4
+ 1. Create overlapping windows (step = window_size / 2)
5
+ 2. Per window: graph initialization + EM refinement
6
+ 3. Link haplotypes across windows where consensus agrees on shared SNVs
7
+ 4. Output tracks with merged consensus spanning multiple windows (results_to_dataframe:
8
+ one row per TRACK, span_bp = span_end - span_start, n_windows = windows spanned)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import bisect
14
+ import logging
15
+ import os
16
+ import warnings
17
+ import zlib
18
+ from collections import Counter, defaultdict
19
+ from collections.abc import Iterable, Iterator
20
+ from dataclasses import dataclass, field
21
+ from multiprocessing import Pool
22
+
23
+ import community as community_louvain
24
+ import networkx as nx
25
+ import numpy as np
26
+ from scipy.special import logsumexp
27
+ from scipy.stats import binom
28
+
29
+ # python-louvain installs as `community`; an unrelated PyPI package of the same
30
+ # name shadows it and fails later with an AttributeError. Check identity once, here.
31
+ if not hasattr(community_louvain, "best_partition"):
32
+ raise ImportError(
33
+ "The installed `community` module is not python-louvain: it has no "
34
+ "best_partition(). Some other package of that name is shadowing it. "
35
+ "Fix with: pip uninstall -y community && pip install python-louvain "
36
+ "(conda: the package is `python-louvain`, NOT `louvain`, which is an "
37
+ "unrelated igraph binding.)"
38
+ )
39
+
40
+ try:
41
+ import pysam
42
+
43
+ HAS_PYSAM = True
44
+ except ImportError:
45
+ HAS_PYSAM = False
46
+ logging.warning("pysam not installed; I/O functions will not work")
47
+
48
+
49
+ # =============================================================================
50
+ # WARNING THROTTLING
51
+ # =============================================================================
52
+
53
+
54
+ class WarningThrottler:
55
+ """Throttle repeated warnings to avoid spam."""
56
+
57
+ _warned: set[str] = set()
58
+
59
+ @classmethod
60
+ def warn_once(cls, key: str, message: str):
61
+ if key not in cls._warned:
62
+ warnings.warn(message, stacklevel=2)
63
+ cls._warned.add(key)
64
+
65
+
66
+
67
+ # =============================================================================
68
+ # CONFIGURATION WITH VALIDATION
69
+ # =============================================================================
70
+
71
+
72
+ @dataclass
73
+ class HaplotyperConfig:
74
+ """Configuration for the haplotyper.
75
+
76
+ Every threshold and filter is a field here; ``__post_init__`` validates them
77
+ on construction.
78
+ """
79
+
80
+ # =========== WINDOW PARAMETERS ===========
81
+ window_size: int = 20000
82
+ # Two deliberate depth floors. min_reads_per_window gates de-novo PHASING (separating
83
+ # haplotypes at 50/50 needs ~10-20 reads; 3 manufactures the abundance==1.0 artifact);
84
+ # min_reads_for_rescue gates whether a window is BUILT AT ALL, so it can still receive a
85
+ # rescued anchor haplotype (which needs less evidence than de-novo separation). A window
86
+ # with rescue <= n < phasing is created but not phased.
87
+ # min_snvs_per_window: 1 skips only empty windows; higher filters sparse regions.
88
+ min_snvs_per_window: int = 1
89
+ min_reads_per_window: int = 10
90
+ min_reads_for_rescue: int = 5
91
+
92
+ # =========== READ FILTERING ===========
93
+ min_mapq: int = 20
94
+ min_base_quality: int = 20
95
+ default_base_quality: int = 20
96
+ # Cap per window; above it reads are kept by a seeded hash of the read id, so
97
+ # overlapping windows keep the same molecules.
98
+ max_reads_per_window: int = 500
99
+ # A read must physically cover at least this many bp of a window to count in it, so a
100
+ # 1 bp clip does not enter n_reads_examined / junk / the abundance denominator as a full span.
101
+ min_read_window_overlap_bp: int = 500
102
+ # Two reads must physically overlap by at least this much to be compared at all.
103
+ min_read_read_overlap_bp: int = 500
104
+
105
+ # Spill per-sample WindowResults to <output_dir>/tmp during the first pass rather than
106
+ # holding every sample's reads in RAM. Cross-sample rescue reads only `.haplotypes` off
107
+ # other samples, so the heavy fields can live on disk. See longitudinal.process_mag_longitudinal.
108
+ spill_results_to_disk: bool = True
109
+ # Windows are handed to the worker pool in batches of n_workers * this, so the input
110
+ # list for a contig is never fully materialised at once.
111
+ window_batch_factor: int = 4
112
+
113
+ # =========== VARIANT FILTERING ===========
114
+ min_depth_site: int = 3
115
+ # Optional AF band. None (default) keeps all variants: a position fixed at AF=0/1 in one
116
+ # timepoint is still informative across timepoints. Set e.g. (0.05, 0.95) for within-sample
117
+ # polymorphic sites only.
118
+ af_range: tuple[float, float] | None = None
119
+
120
+ # =========== MUTATION HANDLING — INVARIANT ===========
121
+ # No ``include_indels`` or ``require_biallelic`` flag exists. Every mutation
122
+ # type (SNV, MNP->SNVs, insertion, deletion) is loaded and every multi-allelic
123
+ # (>2 allele) site is kept. Hard invariant — see ``docs/MUTATION_HANDLING.md``.
124
+
125
+ # =========== GRAPH CONSTRUCTION ===========
126
+ min_shared_snvs_for_edge: int = 1
127
+ min_reads_per_cluster: int = 3
128
+
129
+ # Minimum physical overlap between two entities, below which the verdict is an
130
+ # explicit NON-MERGE rather than "unknown" (Strainy's I = 1000).
131
+ min_entity_overlap_bp: int = 500
132
+ # SVs stay in the identity comparison (default False): an inversion is a marker like any
133
+ # other, and its two orientations trade frequency over time as the flip trajectory. Knob
134
+ # only to measure the effect.
135
+ exclude_sv_from_identity: bool = False
136
+
137
+ # =========== EM PARAMETERS ===========
138
+ em_max_iter: int = 30
139
+ em_tolerance: float = 1e-5
140
+ dirichlet_alpha: float = 1.0
141
+ min_hap_eff_weight: float = 3.0
142
+ min_gamma_for_vote: float = 0.01
143
+
144
+ # =========== JUNK MODEL ===========
145
+ junk_divergence_rate: float = 0.10
146
+
147
+ # HAPLOTYPE IDENTITY: identity_distance is the single rate for every "same entity?" test
148
+ # (read-vs-read, hap-vs-hap, rescue); each comparison carries its own evidence floor:
149
+ # read vs read min_shared_snvs_for_edge = 1
150
+ # haplotype vs hap min_shared_markers = 3
151
+ # read vs haplotype min_shared_for_rescue = 3
152
+ # cross-sample track_merge_min_shared_markers = 1
153
+ identity_distance: float = 0.02
154
+ min_shared_markers: int = 3
155
+ # Agreeing markers a track pair needs before the cross-sample merge joins them. 1 is a
156
+ # permissive first pass: exact agreement cannot fuse two genotypes that disagree
157
+ # anywhere both call, so this trades only evidence volume. Raising it splits hard.
158
+ track_merge_min_shared_markers: int = 1
159
+ # --- MARKER SET (computed once, used by the cross-sample merge) ----------------------
160
+ # A position is a candidate marker when >1 allele is seen at it anywhere on the contig.
161
+ # An allele is kept when it reaches marker_min_reads reads OR marker_min_frac of a
162
+ # sample's reads at that position, in at least marker_min_samples samples; a position
163
+ # survives when >= 2 alleles do. The two alleles need NOT co-occur in one sample: a
164
+ # swept position is fixed within each sample, so requiring both in one would discard the
165
+ # very events this tool finds. See supported_marker_positions.
166
+ marker_min_frac: float = 0.10
167
+ marker_min_reads: int = 3
168
+ marker_min_samples: int = 2
169
+
170
+ assign_confidence_threshold: float = 0.90
171
+
172
+ binomial_alpha: float = 0.05
173
+
174
+ # =========== LONGITUDINAL PARAMETERS ===========
175
+ min_weight_for_anchor: float = 0.15
176
+ min_shared_for_rescue: int = 3 # Min shared SNVs with actual calls for rescue matching
177
+ rescued_min_weight: float = 0.02
178
+
179
+ # =========== ABUNDANCE COHERENCE ===========
180
+ # A genome cannot hold two frequencies at one locus at one time. Tested on raw counts
181
+ # (never the derived, already-quantised `abundance`) with Fisher's exact test, so the
182
+ # rule tightens as depth grows instead of using a fixed cutoff. Single timepoint only:
183
+ # a window-merging check, never a cross-timepoint comparison.
184
+ abundance_coherence_alpha: float = 0.01
185
+ min_reads_for_coherence: int = 10
186
+
187
+ # =========== LINKING DIAGNOSTICS ===========
188
+ linking_debug: bool = False # Record detailed linking diagnostics
189
+ linking_debug_max_records: int = 5000 # Cap to avoid massive files
190
+
191
+ # Window-level shared SNV POSITIONS (does the window pair even have common sites).
192
+ min_shared_snvs_for_link: int = 3
193
+ # How many windows ahead link_windows may reach. Overlapping neighbours are compared on
194
+ # consensus; reach > 1 also admits NON-overlapping windows (disjoint positions, so linked
195
+ # on shared reads alone), covering the marker-free window that would otherwise be an
196
+ # unbridgeable hub. Default 2; set 1 to link only overlapping windows. Rationale: docs/design/core.md.
197
+ link_window_reach: int = 2
198
+ # Shared reads to link a NON-overlapping pair. Consensus cannot gate these (disjoint
199
+ # positions), so this plus reciprocal best match is the whole evidence; do not lower casually.
200
+ link_min_shared_reads: int = 2
201
+ # Coverage-invariant companion to link_min_shared_reads: a non-overlapping link also needs
202
+ # shared_reads >= frac * min(each hap's CONTINUING reads), so the bar rises with depth for
203
+ # abundant strains and stays at the floor for rare ones. 0.0 = disabled (floor only).
204
+ link_shared_read_frac: float = 0.0
205
+ # Co-supported span of the two haplotypes inside the shared region, as a fraction of it.
206
+ # Window geometry alone is useless (tiles overlap by exactly 50% or 0%). 25% of a 10 kb
207
+ # overlap is 2500 bp, above min_entity_overlap_bp; 50% is too aggressive given under-merging risk.
208
+ min_cosupported_span_frac: float = 0.25
209
+
210
+ # =========== RUNTIME PARAMETERS ===========
211
+ # Seeded by DEFAULT (42), not None. Louvain read clustering (GraphInitializer) is handed
212
+ # this as random_state, and the per-window subsample is a stable function of it, so both
213
+ # depend on the seed. None made reruns disagree in the ~8th decimal; set an integer to
214
+ # vary the draw deliberately.
215
+ random_seed: int | None = 42
216
+ n_workers: int = 1 # Number of parallel workers for window processing (1=sequential)
217
+
218
+ def __post_init__(self):
219
+ """Validate configuration parameters."""
220
+
221
+ # Junk divergence rate
222
+ if not (0 < self.junk_divergence_rate < 0.75):
223
+ raise ValueError(
224
+ f"junk_divergence_rate must be in (0, 0.75), got {self.junk_divergence_rate}"
225
+ )
226
+
227
+ if self.track_merge_min_shared_markers < 1:
228
+ raise ValueError(
229
+ "track_merge_min_shared_markers must be >= 1, got "
230
+ f"{self.track_merge_min_shared_markers}"
231
+ )
232
+
233
+ if self.marker_min_frac > 0.5:
234
+ raise ValueError(
235
+ f"marker_min_frac should be <= 0.5, got {self.marker_min_frac}"
236
+ )
237
+
238
+ # A reach below 1 drops the overlapping-neighbour link every track is built from.
239
+ if self.link_window_reach < 1:
240
+ raise ValueError(
241
+ f"link_window_reach must be >= 1, got {self.link_window_reach}"
242
+ )
243
+ if self.link_min_shared_reads < 1:
244
+ raise ValueError(
245
+ f"link_min_shared_reads must be >= 1, got {self.link_min_shared_reads}"
246
+ )
247
+ if not (0.0 <= self.link_shared_read_frac < 1.0):
248
+ raise ValueError(
249
+ f"link_shared_read_frac must be in [0, 1), got {self.link_shared_read_frac}"
250
+ )
251
+
252
+ # Merge distance threshold
253
+ if not (0 <= self.identity_distance <= 1):
254
+ raise ValueError(
255
+ f"identity_distance must be in [0, 1], got {self.identity_distance}"
256
+ )
257
+
258
+ # AF range (optional)
259
+ if self.af_range is not None and not (
260
+ 0 <= self.af_range[0] < self.af_range[1] <= 1
261
+ ):
262
+ raise ValueError(
263
+ f"af_range must be (low, high) with 0 <= low < high <= 1, got {self.af_range}"
264
+ )
265
+
266
+ # Confidence threshold
267
+ if not (0 < self.assign_confidence_threshold <= 1):
268
+ raise ValueError(
269
+ f"assign_confidence_threshold must be in (0, 1], got {self.assign_confidence_threshold}"
270
+ )
271
+
272
+ # Window size
273
+ if self.window_size < 100:
274
+ raise ValueError(f"window_size too small: {self.window_size}")
275
+
276
+ # Rescue floor must sit at or below the phasing floor (a window must be buildable
277
+ # before it can be phased). Clamp rather than raise: lowering the phasing floor means
278
+ # "be more permissive".
279
+ if self.min_reads_for_rescue > self.min_reads_per_window:
280
+ object.__setattr__(self, "min_reads_for_rescue", self.min_reads_per_window)
281
+
282
+
283
+ if not (0 <= self.min_cosupported_span_frac <= 1):
284
+ raise ValueError(
285
+ f"min_cosupported_span_frac must be in [0, 1], got "
286
+ f"{self.min_cosupported_span_frac}"
287
+ )
288
+
289
+
290
+ if not (0 < self.abundance_coherence_alpha < 1):
291
+ raise ValueError(
292
+ f"abundance_coherence_alpha must be in (0, 1), got "
293
+ f"{self.abundance_coherence_alpha}"
294
+ )
295
+
296
+ # EM iterations
297
+ if self.em_max_iter < 1:
298
+ raise ValueError(f"em_max_iter must be >= 1, got {self.em_max_iter}")
299
+
300
+ DEFAULT_CONFIG = HaplotyperConfig()
301
+
302
+
303
+ # =============================================================================
304
+ # DATA STRUCTURES
305
+ # =============================================================================
306
+
307
+
308
+ # config field -> the argparse attribute that sets it. A field whose flag a given parser
309
+ # does not define keeps its dataclass default, which lets one builder serve every subcommand.
310
+ _CONFIG_FROM_ARG: dict[str, str] = {
311
+ "window_size": "window_size",
312
+ "max_reads_per_window": "max_reads",
313
+ "min_mapq": "min_mapq",
314
+ "min_depth_site": "min_depth_site",
315
+ "random_seed": "seed",
316
+ "min_weight_for_anchor": "min_anchor_weight",
317
+ "rescued_min_weight": "rescued_min_weight",
318
+ "min_reads_per_window": "min_reads_per_window",
319
+ "min_reads_for_rescue": "min_reads_for_rescue",
320
+ "min_cosupported_span_frac": "min_cosupported_span_frac",
321
+ "min_shared_snvs_for_link": "min_shared_snvs_for_link",
322
+ "identity_distance": "identity_distance",
323
+ "min_shared_markers": "min_shared_markers",
324
+ "track_merge_min_shared_markers": "track_merge_min_shared_markers",
325
+ "link_window_reach": "link_window_reach",
326
+ "link_min_shared_reads": "link_min_shared_reads",
327
+ "link_shared_read_frac": "link_shared_read_frac",
328
+ "abundance_coherence_alpha": "abundance_coherence_alpha",
329
+ "min_reads_for_coherence": "min_reads_for_coherence",
330
+ "window_batch_factor": "window_batch_factor",
331
+ }
332
+
333
+
334
+ def config_from_args(args, **overrides) -> HaplotyperConfig:
335
+ """Build one ``HaplotyperConfig`` from any entry point's parsed arguments.
336
+
337
+ ``overrides`` win over the parsed values, for the few settings an entry point fixes
338
+ rather than exposes. Flags that invert or derive their field (``--no-spill``,
339
+ ``--workers``, ``--af-range``) are handled explicitly below, since a name-to-name
340
+ table cannot express them.
341
+ """
342
+ values: dict = {}
343
+ for cfg_field, attr in _CONFIG_FROM_ARG.items():
344
+ if hasattr(args, attr):
345
+ values[cfg_field] = getattr(args, attr)
346
+
347
+ # One --min-overlap-bp governs all three physical-overlap floors (read-vs-window,
348
+ # read-vs-read, entity-vs-entity); the fields stay separate so a library caller can differ them.
349
+ if getattr(args, "min_overlap_bp", None) is not None:
350
+ values["min_read_window_overlap_bp"] = args.min_overlap_bp
351
+ values["min_read_read_overlap_bp"] = args.min_overlap_bp
352
+ values["min_entity_overlap_bp"] = args.min_overlap_bp
353
+
354
+ # argparse hands back a LIST for nargs=2, and af_range is part of the VCF-load
355
+ # cache key, which a list cannot be - so convert here rather than at the use site.
356
+ if getattr(args, "af_range", None):
357
+ values["af_range"] = tuple(args.af_range)
358
+
359
+ # Inverted and derived flags.
360
+ if hasattr(args, "no_spill"):
361
+ values["spill_results_to_disk"] = not args.no_spill
362
+ if hasattr(args, "workers"):
363
+ values["n_workers"] = max(1, args.workers)
364
+
365
+ values.update(overrides)
366
+ return HaplotyperConfig(**values)
367
+
368
+
369
+ @dataclass
370
+ class Read:
371
+ """Lightweight container for read data. All positions are 1-based (VCF convention)."""
372
+
373
+ id: str
374
+ contig: str
375
+ mapq: int
376
+ alleles: dict[int, str] = field(default_factory=dict)
377
+ quals: dict[int, int] = field(default_factory=dict)
378
+ sample: str | None = None
379
+ # Reference alignment span, 1-based [start, end), for the physical-overlap gates.
380
+ # Default (0, 0) means "unknown" - the overlap gates are then skipped, not made to reject.
381
+ ref_start: int = 0
382
+ ref_end: int = 0
383
+ # Aligned reference intervals, 1-based [start, end), one per alignment segment. Empty for
384
+ # a single-alignment read (its outer span IS its coverage); a split-alignment molecule
385
+ # carries one per segment so a covers() test does not answer yes inside its own gap.
386
+ segments: list[tuple[int, int]] = field(default_factory=list)
387
+
388
+ def covers(self, pos: int) -> bool:
389
+ """Is *pos* inside an ALIGNED part of this read? Unknown span (0, 0) is False."""
390
+ if self.segments:
391
+ return any(s <= pos < e for s, e in self.segments)
392
+ return self.ref_start <= pos < self.ref_end
393
+
394
+ def overlap_bp(self, other: Read) -> int:
395
+ """Physical reference overlap with *other*, in bp. -1 when either span is unknown."""
396
+ if self.ref_end <= self.ref_start or other.ref_end <= other.ref_start:
397
+ return -1
398
+ return max(0, min(self.ref_end, other.ref_end) - max(self.ref_start, other.ref_start))
399
+
400
+
401
+ @dataclass
402
+ class Window:
403
+ """A genomic window (contig interval) with its SNVs and reads.
404
+
405
+ snv_pos/ref_alleles come from the VCF; reads are pulled from the BAM in make_windows_lazy.
406
+ """
407
+
408
+ contig: str
409
+ start: int # 1-based, inclusive
410
+ end: int # 1-based, exclusive
411
+ snv_pos: list[int] = field(default_factory=list) # SNV positions (from VCF)
412
+ ref_alleles: dict[int, str] = field(default_factory=dict) # REF base per SNV (from VCF)
413
+ # Reads overlapping this window, in gamma-row order. After offload_heavy these are
414
+ # id-only _ReadRef stand-ins: row order and ids survive, alleles do not, so anything
415
+ # needing alleles must run before the offload.
416
+ reads: list[Read] = field(default_factory=list)
417
+ # Per-position site type ("snv"/"del"/"ins"/"sv"). Carried here because the identity
418
+ # code needs to know which positions are SVs to (optionally) exclude them from the distance.
419
+ site_type: dict[int, str] = field(default_factory=dict)
420
+ sample: str | None = None # Optional timepoint/sample label (redundant with Read.sample)
421
+ window_idx: int = 0 # Position in contig's window sequence
422
+
423
+ # Cached position sets for graph building (optimization)
424
+ _pos_sets: list[set[int]] | None = field(default=None, repr=False)
425
+
426
+ def get_read_position_sets(self) -> list[set[int]]:
427
+ """Get precomputed position sets for each read (cached)."""
428
+ if self._pos_sets is None:
429
+ self._pos_sets = [
430
+ {p for p in r.alleles if self.start <= p < self.end} for r in self.reads
431
+ ]
432
+ return self._pos_sets
433
+
434
+ @property
435
+ def n_snvs(self) -> int:
436
+ return len(self.snv_pos)
437
+
438
+ @property
439
+ def n_reads(self) -> int:
440
+ return len(self.reads)
441
+
442
+
443
+ @dataclass
444
+ class Haplotype:
445
+ """A resolved haplotype within a window."""
446
+
447
+ consensus: dict[int, str]
448
+ weight: float = 0.0 # Mixture weight (pi) after EM / post-merge / rescue.
449
+ supporting_reads: int = 0
450
+ confidence: float = 0.0 # Mean gamma over confident reads for this haplotype.
451
+ track_id: str | None = None # Assigned after window linking
452
+ rescued_from: str | None = None # Donor timepoint, when cross-timepoint rescue created it
453
+
454
+ def distance_to(
455
+ self, other: Haplotype, positions: list[int], max_mismatches: int | None = None
456
+ ) -> tuple[float, int, int]:
457
+ """Normalized Hamming distance over *positions*, with optional early exit at
458
+ *max_mismatches*. Returns (distance, n_mismatches, n_shared).
459
+
460
+ INVARIANT: n_shared == 0 returns distance 1.0 (incomparable); callers must check
461
+ n_shared before trusting the distance.
462
+ """
463
+ total = 0
464
+ mismatches = 0
465
+ for pos in positions:
466
+ b1 = self.consensus.get(pos)
467
+ b2 = other.consensus.get(pos)
468
+ if b1 is None or b2 is None:
469
+ continue
470
+ total += 1
471
+ if b1 != b2:
472
+ mismatches += 1
473
+ if max_mismatches is not None and mismatches > max_mismatches:
474
+ return 1.0, mismatches, total
475
+ if total == 0:
476
+ return 1.0, 0, 0
477
+ return mismatches / total, mismatches, total
478
+
479
+ def get_differing_positions(self, other: Haplotype, positions: list[int]) -> list[int]:
480
+ """Return list of positions where haplotypes differ."""
481
+ return [
482
+ pos
483
+ for pos in positions
484
+ if (b1 := self.consensus.get(pos)) is not None
485
+ and (b2 := other.consensus.get(pos)) is not None
486
+ and b1 != b2
487
+ ]
488
+
489
+
490
+ @dataclass
491
+ class WindowResult:
492
+ """Complete results from processing a single window."""
493
+
494
+ window: Window
495
+ haplotypes: list[Haplotype]
496
+ gamma: np.ndarray
497
+ pi: np.ndarray
498
+ log_likelihood: float
499
+ assignments: list[dict]
500
+ converged: bool
501
+ iterations: int
502
+ linking_debug: list[dict] = field(default_factory=list)
503
+ # Step-1 comparisons that failed on a genuine allele disagreement (failed_mismatch only),
504
+ # kept so the verdict survives to the output as an absolute negative. failed_no_evidence
505
+ # is a measurement hole and is not recorded.
506
+ link_mismatches: list[dict] = field(default_factory=list)
507
+ # Step-1 abundance refusals (one sample, two adjacent windows), recorded so the verdict
508
+ # carries over to the cross-sample merge instead of being recomputed pairwise.
509
+ link_abundance_refusals: list[dict] = field(default_factory=list)
510
+ n_reads_examined: int = 0
511
+ reads_within_mismatch_per_hap: list[int] = field(default_factory=list)
512
+ # Scalar summaries of `gamma`, recorded before the heavy fields are offloaded so the
513
+ # output tables can still be built while reads/gamma live on disk. -1 = not recorded.
514
+ n_reads_total: int = -1
515
+ n_junk_reads: int = -1
516
+ heavy_offloaded: bool = False
517
+
518
+ # ---------------- Heavy-field offload ----------------
519
+ # window.reads is ~99% of a WindowResult's footprint and is needed only while the
520
+ # window's own sample is phased or rescued, so it is offloaded; gamma (~1000x smaller)
521
+ # is still read when the output tables are built and stays resident. The WindowResult
522
+ # object itself must stay resident: the rescue panel mutates its Haplotype weights in place.
523
+ # Footprint measurement: docs/design/core.md.
524
+
525
+ def offload_heavy(self) -> list:
526
+ """Detach and return this window's reads, recording the read-count summaries."""
527
+ if self.heavy_offloaded:
528
+ return []
529
+ self.n_reads_total, self.n_junk_reads = self.junk_read_counts()
530
+ reads = self.window.reads
531
+ self.window.reads = []
532
+ self.window._pos_sets = None
533
+ # `assignments` is deliberately NOT cleared: read-overlap threading reads it after
534
+ # every sample is phased, and it is cheap (one small dict per read). See docs/design/core.md.
535
+ self.heavy_offloaded = True
536
+ return reads
537
+
538
+ def restore_heavy(self, reads: list) -> None:
539
+ """Re-attach reads detached by :meth:`offload_heavy`."""
540
+ self.window.reads = reads
541
+ self.window._pos_sets = None
542
+ self.heavy_offloaded = False
543
+
544
+ def junk_read_counts(self) -> tuple[int, int]:
545
+ """``(n_reads_total, n_junk_reads)`` whether or not gamma is resident."""
546
+ if self.gamma is not None and self.gamma.size:
547
+ return (
548
+ int(self.gamma.shape[0]),
549
+ int((self.gamma[:, self.gamma.shape[1] - 1] >= 0.5).sum()),
550
+ )
551
+ if self.n_reads_total >= 0:
552
+ return self.n_reads_total, self.n_junk_reads
553
+ return 0, 0
554
+
555
+ def validate(self) -> bool:
556
+ """Validate internal consistency."""
557
+ n_reads = len(self.window.reads)
558
+ n_haps = len(self.haplotypes)
559
+ k_eff = n_haps + 1 # haplotypes + 1 junk component
560
+
561
+ assert self.gamma.shape == (
562
+ n_reads,
563
+ k_eff,
564
+ ), f"gamma shape {self.gamma.shape} != expected ({n_reads}, {k_eff})"
565
+
566
+ # Each row of gamma is a probability distribution (sums to ~1).
567
+ row_sums = self.gamma.sum(axis=1)
568
+ assert np.allclose(
569
+ row_sums, 1.0, atol=1e-6
570
+ ), f"gamma rows don't sum to 1: min={row_sums.min()}, max={row_sums.max()}"
571
+
572
+ # pi is a probability distribution (sums to ~1) with k_eff entries.
573
+ assert np.isclose(self.pi.sum(), 1.0, atol=1e-6), f"pi doesn't sum to 1: {self.pi.sum()}"
574
+
575
+ assert len(self.pi) == k_eff, f"pi length {len(self.pi)} != k_eff {k_eff}"
576
+
577
+ if self.reads_within_mismatch_per_hap:
578
+ assert len(self.reads_within_mismatch_per_hap) == n_haps, (
579
+ f"reads_within_mismatch_per_hap length {len(self.reads_within_mismatch_per_hap)} != n_haps {n_haps}"
580
+ )
581
+
582
+ return True
583
+
584
+
585
+ class _ReadRef:
586
+ """A read's identity, kept after its alleles have been released.
587
+
588
+ window.reads is emptied by offload_heavy, but a gamma row still has to say WHICH read it
589
+ belongs to - that correspondence is the read partition. The id alone preserves it at
590
+ ~1500x less memory than the whole Read; nothing else survives, so reaching for .alleles
591
+ here raises an AttributeError naming this class rather than silently seeing none.
592
+ Rationale: docs/design/core.md.
593
+ """
594
+
595
+ __slots__ = ("id",)
596
+
597
+ def __init__(self, read_id: str) -> None:
598
+ self.id = read_id
599
+
600
+ def __repr__(self) -> str: # pragma: no cover - diagnostics only
601
+ return f"_ReadRef({self.id!r})"
602
+
603
+
604
+ def _read_sort_hash(read_id: str, seed: int | None) -> int:
605
+ """Stable per-read sort key for window-consistent subsampling.
606
+
607
+ CRC32 over the seeded id (not hash(), which is salted per process) is stable across
608
+ processes, runs and machines; the seed is mixed in so a different random_seed redraws.
609
+ """
610
+ return zlib.crc32(f"{seed}:{read_id}".encode())
611
+
612
+
613
+ _EMPTY_READS: frozenset = frozenset()
614
+
615
+
616
+ def _detach_reads(wr: WindowResult) -> list:
617
+ """Offload a window's reads, leaving id-only stand-ins in gamma-row order.
618
+
619
+ Returns the detached Read objects so the caller can spill them; ``restore_heavy``
620
+ lays the real ones back over the stand-ins. Idempotent, and order-independent across
621
+ the several WindowResults that can share one Window after rescue.
622
+ """
623
+ refs = [r if isinstance(r, _ReadRef) else _ReadRef(r.id) for r in wr.window.reads]
624
+ reads = wr.offload_heavy()
625
+ wr.window.reads = refs
626
+ return reads
627
+
628
+
629
+ def _compute_read_mismatch_counts(
630
+ window: Window,
631
+ haplotypes: list[Haplotype],
632
+ identity_distance: float,
633
+ ) -> tuple[int, list[int]]:
634
+ """Count reads within ``identity_distance`` of each haplotype consensus."""
635
+ n_reads = len(window.reads)
636
+ if not haplotypes or n_reads == 0:
637
+ return n_reads, [0] * len(haplotypes)
638
+
639
+ hap_positions = [set(h.consensus.keys()) for h in haplotypes]
640
+ counts = [0] * len(haplotypes)
641
+ read_pos_sets = window.get_read_position_sets()
642
+
643
+ for read, read_pos in zip(window.reads, read_pos_sets): # noqa: B905
644
+ if not read_pos:
645
+ continue
646
+ for hi, hap in enumerate(haplotypes):
647
+ shared_positions = read_pos & hap_positions[hi]
648
+ n_shared = len(shared_positions)
649
+ if n_shared == 0:
650
+ continue
651
+ mismatches = 0
652
+ for pos in shared_positions:
653
+ if read.alleles.get(pos) != hap.consensus.get(pos):
654
+ mismatches += 1
655
+ if (mismatches / n_shared) < identity_distance:
656
+ counts[hi] += 1
657
+
658
+ return n_reads, counts
659
+
660
+
661
+ @dataclass
662
+ class RescueStatistic:
663
+ """Statistics for a single haplotype rescue event."""
664
+
665
+ sample: str # Timepoint where rescue occurred
666
+ rescued_timepoint: str # Timepoint label for the rescued read/haplotype (usually same as sample)
667
+ contig: str
668
+ window_start: int
669
+ track_id: str
670
+ was_rescued: bool
671
+ original_weight: float
672
+ rescued_weight: float
673
+ donor_timepoint: str # Timepoint that provided the anchor
674
+ anchor_distance: float
675
+ n_shared_with_anchor: int
676
+ n_mismatched_with_anchor: int
677
+ reason: str = "" # Debug reason for rescue outcome
678
+
679
+
680
+ # =============================================================================
681
+ # LOG-PROBABILITY CACHE
682
+ # =============================================================================
683
+
684
+
685
+ class LogProbCache:
686
+ """Cache of log-probability computations, avoiding redundant 10**(-Q/10) calls.
687
+
688
+ Mismatch probability is spread uniformly over the n_alleles - 1 non-matching states. The
689
+ alphabet is always {A,C,G,T,DEL,INS} (n_alleles=6) because indels are always processed
690
+ (invariant, docs/MUTATION_HANDLING.md); SV pseudo-alleles reuse the same 6-state model.
691
+ """
692
+
693
+ def __init__(self, max_q: int = 60, n_alleles: int = 4):
694
+ """Precompute log probabilities for all Q scores."""
695
+ if n_alleles < 2:
696
+ raise ValueError(f"n_alleles must be >= 2, got {n_alleles}")
697
+ self._log_match = np.zeros(max_q + 1)
698
+ self._log_mismatch = np.zeros(max_q + 1)
699
+ self.n_alleles = n_alleles
700
+ # Junk tables depend on junk_divergence_rate, which is config, not alphabet.
701
+ self._junk_tables: dict[float, tuple[np.ndarray, np.ndarray]] = {}
702
+
703
+ denom = float(n_alleles - 1)
704
+ for q in range(max_q + 1):
705
+ p_err = 10 ** (-q / 10.0)
706
+ self._log_match[q] = np.log(1.0 - p_err + 1e-12)
707
+ self._log_mismatch[q] = np.log(p_err / denom + 1e-12)
708
+
709
+ def log_prob_base(self, hap_base: str, read_base: str, q: int) -> float:
710
+ """Get log probability from cache."""
711
+ q = min(q, len(self._log_match) - 1)
712
+ if hap_base == read_base:
713
+ return self._log_match[q]
714
+ return self._log_mismatch[q]
715
+
716
+ def log_mismatch(self, q: int) -> float:
717
+ """``log P(obs | the true allele is something else)`` at quality *q*."""
718
+ return float(self._log_mismatch[min(q, len(self._log_mismatch) - 1)])
719
+
720
+ def log_odds(self, q: int) -> float:
721
+ """``log P(obs | agree) - log P(obs | disagree)`` at quality *q*: the weight a
722
+ consensus vote uses. Spans 6.20 nats at Q20 to 15.42 at Q60, so a confident base
723
+ outvotes several unreliable ones.
724
+ """
725
+ q = min(q, len(self._log_match) - 1)
726
+ return float(self._log_match[q] - self._log_mismatch[q])
727
+
728
+ def junk_tables(self, p_div: float) -> tuple[np.ndarray, np.ndarray]:
729
+ """Per-quality (log P(obs == REF), log P(obs == a given non-REF)) under the junk
730
+ model, cached per divergence rate.
731
+
732
+ Junk is a read off a genome diverged from the reference at p_div, OBSERVED through the
733
+ same per-base error channel the haplotype components use, so the two effects compose
734
+ here rather than junk being scored at a flat rate. The boundary stays quality-dependent
735
+ (junk_divergence_rate is the prior on divergence, not a decision threshold).
736
+ Crossover measurements: docs/design/core.md.
737
+ """
738
+ cached = self._junk_tables.get(p_div)
739
+ if cached is None:
740
+ n = float(self.n_alleles)
741
+ d = float(p_div)
742
+ q = np.arange(len(self._log_match))
743
+ e = 10.0 ** (-q / 10.0)
744
+ p_ref = (1.0 - d) * (1.0 - e) + d * e / (n - 1.0)
745
+ p_alt = (
746
+ (1.0 - d) * e / (n - 1.0)
747
+ + (d / (n - 1.0)) * (1.0 - e)
748
+ + (n - 2.0) * (d / (n - 1.0)) * (e / (n - 1.0))
749
+ )
750
+ cached = (np.log(p_ref + 1e-12), np.log(p_alt + 1e-12))
751
+ self._junk_tables[p_div] = cached
752
+ return cached
753
+
754
+
755
+ # Single global cache. The alphabet is always {A,C,G,T,DEL,INS} (indels are
756
+ # always processed — invariant), so the 6-state error model is used everywhere.
757
+ _LOG_PROB_CACHE = LogProbCache(n_alleles=6)
758
+
759
+ # log P(read allele | a component with no allele at this position): marginalising the
760
+ # unknown allele over the alphabet gives exactly 1/n_alleles. Every mixture component must be
761
+ # scored over the SAME site set or the softmax that makes gamma is not a posterior (worked
762
+ # example of the footprint asymmetry this fixes: docs/design/core.md).
763
+ _LOG_MISSING_SITE = float(np.log(1.0 / _LOG_PROB_CACHE.n_alleles))
764
+
765
+ # Reference base an SV pseudo-site carries: an SV has no single reference allele, so the
766
+ # anchor gets a placeholder no read can equal, which is why the junk model steps over these sites.
767
+ _SV_PLACEHOLDER_REF = "N"
768
+
769
+
770
+ def _read_support(read: Read, snv_set: set[int]) -> list[int]:
771
+ """The sites this read is scored at: its own calls that are window variant sites.
772
+
773
+ One list per read, shared by every mixture component, which is what makes the E-step
774
+ a comparison of like with like.
775
+ """
776
+ return [p for p in read.alleles if p in snv_set]
777
+
778
+
779
+ def _log_prob_read_hap(
780
+ read: Read, consensus: dict[int, str], support: list[int], default_q: int
781
+ ) -> float | None:
782
+ """``log P(read | haplotype)`` over *support*.
783
+
784
+ A support position the consensus does not reach is explicit missing data, not an
785
+ absent term: it costs ``_LOG_MISSING_SITE``, the same constant every other component
786
+ pays there. ``None`` means the haplotype says nothing about this read at all (no
787
+ shared called site), which is the one case where it must not compete for it.
788
+ """
789
+ log_prob = 0.0
790
+ overlap = 0
791
+ for pos in support:
792
+ hap_base = consensus.get(pos)
793
+ if hap_base is None:
794
+ log_prob += _LOG_MISSING_SITE
795
+ continue
796
+ q = read.quals.get(pos, default_q)
797
+ log_prob += _LOG_PROB_CACHE.log_prob_base(hap_base, read.alleles[pos], q)
798
+ overlap += 1
799
+ return log_prob if overlap > 0 else None
800
+
801
+
802
+ def _log_prob_read_junk(
803
+ read: Read,
804
+ support: list[int],
805
+ ref_alleles: dict[int, str],
806
+ p_div: float,
807
+ default_q: int,
808
+ ) -> float:
809
+ """``log P(read | junk)`` over the same *support* the haplotype components use.
810
+
811
+ Junk is a genome diverged from the reference at p_div, so a site with no usable reference
812
+ allele carries no junk evidence and takes the missing-data term: sites the loader never
813
+ anchored, and SV pseudo-sites (anchor "N"). SV pseudo-sites must be stepped over or junk
814
+ pays a phantom mismatch at every SV anchor. Split-read breakpoints are NOT excluded: their
815
+ anchor holds CONTINUOUS, which a read crossing with an unbroken alignment genuinely matches.
816
+ Measurement: docs/design/core.md.
817
+ """
818
+ log_ref, log_alt = _LOG_PROB_CACHE.junk_tables(p_div)
819
+ max_q = len(log_ref) - 1
820
+ log_prob = 0.0
821
+ for pos in support:
822
+ ref_base = ref_alleles.get(pos)
823
+ if ref_base is None or ref_base == _SV_PLACEHOLDER_REF:
824
+ log_prob += _LOG_MISSING_SITE
825
+ continue
826
+ q = min(read.quals.get(pos, default_q), max_q)
827
+ log_prob += log_ref[q] if read.alleles[pos] == ref_base else log_alt[q]
828
+ return float(log_prob)
829
+
830
+ def _em_read_tensors(reads, support, ref_alleles, p_div, default_q, cache):
831
+ """Build the E-step tensors that are CONSTANT across EM iterations.
832
+
833
+ Reads, support sites and qualities do not change during EM (only consensuses do), so the
834
+ integer allele matrix, per-(read, site) log_match/log_mismatch, and junk log-likelihood
835
+ are built ONCE here. Vectorised replacement for the per-(read, hap) _log_prob_read_hap /
836
+ _log_prob_read_junk loop; numerically identical to summing those calls (float order aside).
837
+ Returns tensors plus ``alleles``, the shared string->int encoder so read/hap/ref alleles
838
+ compare as integers.
839
+ """
840
+ sites = sorted({p for sup in support for p in sup})
841
+ site_idx = {p: s for s, p in enumerate(sites)}
842
+ n_reads, n_sites = len(reads), len(sites)
843
+ max_q = len(cache._log_match) - 1
844
+
845
+ alleles: dict[str, int] = {}
846
+
847
+ def code(a: str) -> int:
848
+ c = alleles.get(a)
849
+ if c is None:
850
+ c = len(alleles)
851
+ alleles[a] = c
852
+ return c
853
+
854
+ read_code = np.full((n_reads, n_sites), -1, dtype=np.int32)
855
+ read_q = np.zeros((n_reads, n_sites), dtype=np.int32)
856
+ for i, r in enumerate(reads):
857
+ r_alleles, r_quals = r.alleles, r.quals
858
+ for p in support[i]:
859
+ s = site_idx[p]
860
+ read_code[i, s] = code(r_alleles[p])
861
+ read_q[i, s] = min(r_quals.get(p, default_q), max_q)
862
+
863
+ sup_mask = read_code >= 0
864
+ lm = cache._log_match[read_q] # (n_reads, n_sites) log P(match) at each q
865
+ lmm = cache._log_mismatch[read_q] # (n_reads, n_sites) log P(mismatch)
866
+
867
+ # Junk component: constant across iterations. A site with no reference allele,
868
+ # or an SV placeholder, takes the missing-data term (see _log_prob_read_junk).
869
+ log_ref, log_alt = cache.junk_tables(p_div)
870
+ ref_code = np.full(n_sites, -1, dtype=np.int32)
871
+ for p, base in ref_alleles.items():
872
+ s = site_idx.get(p)
873
+ if s is not None and base != _SV_PLACEHOLDER_REF:
874
+ ref_code[s] = code(base)
875
+ ref_present = ref_code >= 0
876
+ jr = log_ref[read_q]
877
+ ja = log_alt[read_q]
878
+ junk_contrib = np.where(
879
+ ref_present[None, :],
880
+ np.where(read_code == ref_code[None, :], jr, ja),
881
+ _LOG_MISSING_SITE,
882
+ )
883
+ logl_junk = np.where(sup_mask, junk_contrib, 0.0).sum(axis=1)
884
+
885
+ return site_idx, alleles, code, read_code, sup_mask, lm, lmm, logl_junk
886
+
887
+
888
+ def _em_logl_hap(haplotypes, site_idx, code, read_code, sup_mask, lm, lmm):
889
+ """Vectorised ``log P(read | hap)`` matrix, one column per haplotype.
890
+
891
+ Identical to _log_prob_read_hap per (read, hap): a support site the consensus does not
892
+ reach costs _LOG_MISSING_SITE; a covered site is log_match/log_mismatch at the read's
893
+ quality; a read with zero shared covered sites gets -inf (must not compete), matching the
894
+ None return. ``code`` extends the encoder with hap-only alleles (which can only mismatch).
895
+ """
896
+ n_reads, n_sites = read_code.shape
897
+ n_haps = len(haplotypes)
898
+ logl = np.full((n_reads, n_haps), -np.inf)
899
+ for k, hap in enumerate(haplotypes):
900
+ hc = np.full(n_sites, -1, dtype=np.int32)
901
+ for p, base in hap.consensus.items():
902
+ s = site_idx.get(p)
903
+ if s is not None:
904
+ hc[s] = code(base)
905
+ present = hc >= 0
906
+ contrib = np.where(
907
+ present[None, :],
908
+ np.where(read_code == hc[None, :], lm, lmm),
909
+ _LOG_MISSING_SITE,
910
+ )
911
+ total = np.where(sup_mask, contrib, 0.0).sum(axis=1)
912
+ overlap = (sup_mask & present[None, :]).sum(axis=1)
913
+ logl[:, k] = np.where(overlap > 0, total, -np.inf)
914
+ return logl
915
+
916
+
917
+ def _em_hap_consensus(gamma_k, read_code, sup_mask, lo, lmm, n_alleles,
918
+ sites, dec, snv_pos, min_gamma):
919
+ """Vectorised weighted-vote consensus for one haplotype (M-step).
920
+
921
+ Identical to the per-read voting loop: each read with ``gamma >= min_gamma``
922
+ contributes, at each of its support sites, ``gamma * log_odds(q)`` toward the
923
+ allele it calls and ``gamma * log_mismatch(q)`` to the position's mismatch
924
+ floor; an allele is taken only where ``floor + its vote`` beats calling
925
+ nothing (``cover * _LOG_MISSING_SITE``). Reuses the read x site tensors built
926
+ once by :func:`_em_read_tensors`. Returns the consensus dict, or ``None`` if no
927
+ read voted (the "if not allele_votes: continue" case).
928
+ """
929
+ w = np.where(gamma_k >= min_gamma, gamma_k, 0.0)
930
+ ew = w[:, None] * sup_mask # effective weight per (read, site)
931
+ if not ew.any():
932
+ return None
933
+ cover = ew.sum(axis=0) # (n_sites,)
934
+ floor = (ew * lmm).sum(axis=0) # (n_sites,)
935
+ contrib = ew * lo # (n_reads, n_sites) vote weight
936
+ n_sites = read_code.shape[1]
937
+ votes = np.full((n_sites, n_alleles), -np.inf)
938
+ for a in range(n_alleles):
939
+ m = read_code == a
940
+ if not m.any():
941
+ continue
942
+ col = np.where(m, contrib, 0.0).sum(axis=0)
943
+ votes[(m & sup_mask).any(axis=0), a] = col[(m & sup_mask).any(axis=0)]
944
+ best = votes.argmax(axis=1)
945
+ best_val = votes[np.arange(n_sites), best]
946
+ keep = np.isfinite(best_val) & (floor + best_val > cover * _LOG_MISSING_SITE)
947
+ return {
948
+ sites[s]: dec[int(best[s])]
949
+ for s in np.nonzero(keep)[0]
950
+ if sites[s] in snv_pos
951
+ }
952
+
953
+
954
+ # Padding (bp) around an SV breakpoint anchor when deciding whether a read's
955
+ # reference span brackets it. Absorbs Sniffles breakpoint imprecision
956
+ # (CIPOS/CIEND) and soft-clip edges. See strainphase.sv_encoding.
957
+ _SV_ANCHOR_PAD = 50
958
+
959
+
960
+ # =============================================================================
961
+ # I/O FUNCTIONS - LAZY LOADING
962
+ # =============================================================================
963
+
964
+ # Canonical single-base alleles. Anything else at a substitution offset (N,
965
+ # IUPAC codes, symbolic) is counted and logged rather than silently taken.
966
+ _ACGT = frozenset("ACGT")
967
+
968
+
969
+ def _atomize_allele(pos: int, ref: str, alt: str) -> list[tuple[int, str, str, str]]:
970
+ """Decompose one REF/ALT pair into atomic variants ``(pos, ref, alt, type)``.
971
+
972
+ The single uniform decomposition applied to every allele:
973
+
974
+ * 1bp REF / 1bp ALT -> one ``snv``
975
+ * equal-length multi-base (MNP) -> one ``snv`` per differing offset
976
+ * REF longer (net deletion) -> one ``del`` (positions trusted as-is)
977
+ * ALT longer (net insertion) -> one ``ins`` (positions trusted as-is)
978
+
979
+ INVARIANT: indels and MNPs are ALWAYS decomposed and kept (docs/MUTATION_HANDLING.md).
980
+ Non-ACGT bases at a substitution offset yield no primitive; the empty result is counted
981
+ by the caller, never dropped silently.
982
+ """
983
+ ref = ref.upper()
984
+ alt = alt.upper()
985
+ if ref == alt:
986
+ return []
987
+ lr, la = len(ref), len(alt)
988
+ if lr == la:
989
+ # SNV (lr == 1) or MNP (lr > 1): one SNV per differing, canonical offset.
990
+ return [
991
+ (pos + i, ref[i], alt[i], "snv")
992
+ for i in range(lr)
993
+ if ref[i] != alt[i] and ref[i] in _ACGT and alt[i] in _ACGT
994
+ ]
995
+ # Length-changing: a single indel primitive (del if REF longer, else ins).
996
+ return [(pos, ref, alt, "del" if lr > la else "ins")]
997
+
998
+
999
+ def _log_load_summary(vcf_path: str, contig_id: str | None, stats: dict[str, int]) -> None:
1000
+ """Log a full per-load accounting so no variant is ever dropped silently.
1001
+
1002
+ Emits one INFO line with sites loaded per type and every skip reason with a
1003
+ non-zero count. If any records were skipped, also emits a one-line WARNING
1004
+ naming the reasons, so a reviewer scanning logs sees the loss immediately.
1005
+ """
1006
+ loaded = {
1007
+ k[len("loaded_") :]: v for k, v in stats.items() if k.startswith("loaded_")
1008
+ }
1009
+ n_sites = sum(loaded.values())
1010
+ skips = {
1011
+ k: v for k, v in stats.items() if k.startswith("skip_") or k in (
1012
+ "position_conflict",
1013
+ "duplicate_site",
1014
+ # These must be listed or the loss goes unreported.
1015
+ "allele_collapsed_same_key",
1016
+ "anchor_base_conflict",
1017
+ )
1018
+ }
1019
+ where = f" [{contig_id}]" if contig_id else ""
1020
+ loaded_str = " ".join(f"{k}={v}" for k, v in sorted(loaded.items())) or "none"
1021
+ logging.info(
1022
+ # "edits" not "sites": one position may hold several, so per-kind counts sum to more.
1023
+ "load_snvs%s %s: %d records seen -> %d edits at %d positions (%s); "
1024
+ "mnp_atomized=%d multiallelic_records=%d",
1025
+ where,
1026
+ os.path.basename(vcf_path),
1027
+ stats.get("records_seen", 0),
1028
+ n_sites,
1029
+ stats.get("n_positions", 0),
1030
+ loaded_str,
1031
+ stats.get("mnp_atomized", 0),
1032
+ stats.get("multiallelic_records", 0),
1033
+ )
1034
+ dropped = {k: v for k, v in skips.items() if v}
1035
+ if dropped:
1036
+ logging.warning(
1037
+ "load_snvs%s %s: %d record/allele rejections (NOT silent) -> %s",
1038
+ where,
1039
+ os.path.basename(vcf_path),
1040
+ sum(dropped.values()),
1041
+ " ".join(f"{k}={v}" for k, v in sorted(dropped.items())),
1042
+ )
1043
+
1044
+
1045
+ # One parsed VCF per (path, contig, sample, gate settings). A longitudinal run calls
1046
+ # process_contig once per sample, and under a cohort union VCF each re-parses the identical
1047
+ # file; keyed on the settings that change what is kept, so a config change still re-parses.
1048
+ # Bounded because a run touches one contig at a time. Measurement: docs/design/core.md.
1049
+ _SNV_CACHE: dict[tuple, tuple] = {}
1050
+ _SNV_CACHE_MAX = 8
1051
+
1052
+
1053
+ def _copy_snv_tables(tables: tuple) -> tuple:
1054
+ """Shallow-copy every container in a parsed-VCF tuple.
1055
+
1056
+ One copy per container suffices: mutating callers (process_contig's SV merge,
1057
+ iter_windows_lazy's breakpoint registration) append to the position list and assign into
1058
+ the top-level dicts; nobody reaches del_span/ins_len's inner sets, which stay shared.
1059
+ Written by type so a caller stubbing the loader with a shorter tuple still gets copies.
1060
+ """
1061
+ out = []
1062
+ for t in tables:
1063
+ if isinstance(t, list):
1064
+ out.append(list(t))
1065
+ elif isinstance(t, dict):
1066
+ out.append(dict(t))
1067
+ elif isinstance(t, set):
1068
+ out.append(set(t))
1069
+ else:
1070
+ out.append(t)
1071
+ return tuple(out)
1072
+
1073
+
1074
+ def load_snvs(
1075
+ vcf_path: str,
1076
+ contig_id: str | None = None,
1077
+ sample_name: str | None = None,
1078
+ config: HaplotyperConfig = DEFAULT_CONFIG,
1079
+ ):
1080
+ """Cached wrapper (see _SNV_CACHE). Returns a FRESH SHALLOW COPY of the parsed tables on
1081
+ every call, hit or miss, so a caller may mutate what it gets back.
1082
+
1083
+ It must: process_contig and iter_windows_lazy append SV/breakpoint pseudo-sites into the
1084
+ returned tables, so handing back the cached objects would leak one sample's SV anchors
1085
+ into the next under a shared union VCF. History: docs/design/core.md.
1086
+ """
1087
+ key = (vcf_path, contig_id, sample_name, config.min_depth_site, config.af_range)
1088
+ hit = _SNV_CACHE.get(key)
1089
+ if hit is not None:
1090
+ return _copy_snv_tables(hit)
1091
+ out = _load_snvs_uncached(vcf_path, contig_id, sample_name, config)
1092
+ if len(_SNV_CACHE) >= _SNV_CACHE_MAX:
1093
+ _SNV_CACHE.pop(next(iter(_SNV_CACHE)))
1094
+ _SNV_CACHE[key] = out
1095
+ return _copy_snv_tables(out)
1096
+
1097
+
1098
+
1099
+ def _load_snvs_uncached(
1100
+ vcf_path: str,
1101
+ contig_id: str | None = None,
1102
+ sample_name: str | None = None,
1103
+ config: HaplotyperConfig = DEFAULT_CONFIG,
1104
+ ) -> tuple[
1105
+ list[int],
1106
+ dict[int, str],
1107
+ dict[int, int],
1108
+ dict[int, float | None],
1109
+ dict[int, str],
1110
+ dict[int, frozenset[str]],
1111
+ dict[int, set[tuple[int, int]]],
1112
+ dict[int, set[int]],
1113
+ ]:
1114
+ """Load variants from a VCF as atomic sites: SNVs (MNP blocks split per position) and
1115
+ indels, each site typed ``"snv"``/``"del"``/``"ins"``. Indels and multi-allelic sites are
1116
+ ALWAYS kept (invariant, docs/MUTATION_HANDLING.md).
1117
+
1118
+ The caller is trusted: no realignment or fuzz-matching. Run ``bcftools norm -f REF``
1119
+ upstream so placement is canonical.
1120
+
1121
+ Returns
1122
+ -------
1123
+ snv_pos Sorted variant positions (1-based VCF anchor).
1124
+ ref_alleles Single-base REFERENCE base at the anchor, NOT the record's full REF string
1125
+ (reads carry one base or an indel token, so a multi-base REF could never
1126
+ match and made every read a mismatch at every deletion site).
1127
+ depth, af Per-position depth and alt AF (may be None). AF is Number=A, so a
1128
+ multi-allelic position holds the FIRST allele's frequency; nothing
1129
+ downstream reads it (the per-ALT values drive the af_range gate).
1130
+ site_type Per-position type of the FIRST variant registered (kept a plain str so
1131
+ ``site_type[p] == "sv"`` tests hold; ``"sv"`` is added later by the SV merge).
1132
+ site_kinds Per-position set of ALL kinds registered, e.g. ``{"snv", "del"}``.
1133
+ del_span Per deletion site: SET of inclusive 1-based ``(start, end)`` footprints;
1134
+ each becomes its own ``DEL<len>`` allele.
1135
+ ins_len Per insertion site: SET of inserted lengths; each its own ``INS<len>``.
1136
+
1137
+ Nothing is dropped silently: every rejection (FILTER!=PASS, missing/low DP, optional AF
1138
+ band) is counted and logged. FILTER/DP are record-level; the AF band is per-ALLELE, so it
1139
+ rejects only the allele outside it, never a multi-allelic record's other alleles. A
1140
+ position may hold more than one variant, each its own allele downstream. One collapse
1141
+ remains, counted as ``allele_collapsed_same_key``: two insertions of the same length at one
1142
+ anchor differing only in inserted sequence (token is ``INS<len>``). Details: docs/design/core.md.
1143
+ """
1144
+ if not HAS_PYSAM:
1145
+ raise ImportError("pysam required for VCF parsing")
1146
+
1147
+ snv_pos: list[int] = []
1148
+ seen_pos: set[int] = set()
1149
+ ref_alleles: dict[int, str] = {}
1150
+ depth: dict[int, int] = {}
1151
+ af: dict[int, float | None] = {}
1152
+ site_type: dict[int, str] = {}
1153
+ site_kinds: dict[int, set[str]] = {}
1154
+ del_span: dict[int, set[tuple[int, int]]] = {}
1155
+ ins_len: dict[int, set[int]] = {}
1156
+
1157
+ # Full accounting so no variant is ever dropped silently.
1158
+ stats: dict[str, int] = defaultdict(int)
1159
+
1160
+ def _register(apos: int, aref: str, aalt: str, stype: str, dp, site_af) -> bool:
1161
+ """Record one atomic variant; returns True if it added a new allele-defining edit.
1162
+
1163
+ A position may hold more than one variant, each its own allele downstream.
1164
+ ``ref_alleles[apos]`` holds the single-base anchor base, not the record's full REF
1165
+ string (see load_snvs).
1166
+ """
1167
+ if apos <= 0:
1168
+ stats["skip_out_of_bounds"] += 1
1169
+ return False
1170
+
1171
+ anchor = aref[0]
1172
+ if apos not in seen_pos:
1173
+ seen_pos.add(apos)
1174
+ snv_pos.append(apos)
1175
+ ref_alleles[apos] = anchor
1176
+ depth[apos] = dp
1177
+ af[apos] = site_af
1178
+ site_type[apos] = stype # FIRST kind wins; see site_kinds for all of them
1179
+ site_kinds[apos] = set()
1180
+ elif ref_alleles[apos] != anchor:
1181
+ # Records disagreeing on a position's reference base = inconsistent input.
1182
+ stats["anchor_base_conflict"] += 1
1183
+
1184
+ # After bcftools norm, indels are left-anchored: REF starts with the anchor base(s)
1185
+ # matching ALT, then deletes/inserts the trailing bases. Positions are trusted exactly.
1186
+ added = False
1187
+ if stype == "del":
1188
+ del_start = apos + len(aalt)
1189
+ del_end = apos + len(aref) - 1
1190
+ if del_end >= del_start:
1191
+ spans = del_span.setdefault(apos, set())
1192
+ added = (del_start, del_end) not in spans
1193
+ spans.add((del_start, del_end))
1194
+ else:
1195
+ stats["skip_degenerate_del"] += 1
1196
+ elif stype == "ins":
1197
+ lens = ins_len.setdefault(apos, set())
1198
+ ilen = len(aalt) - len(aref)
1199
+ added = ilen not in lens
1200
+ if not added:
1201
+ # Same anchor and inserted length, different sequence: INS<len> cannot tell
1202
+ # them apart. Counted, not silent.
1203
+ stats["allele_collapsed_same_key"] += 1
1204
+ lens.add(ilen)
1205
+ else: # snv — multiple ALTs at one position need no extra bookkeeping,
1206
+ # the read supplies whichever base it carries.
1207
+ added = "snv" not in site_kinds[apos]
1208
+ if not added:
1209
+ stats["duplicate_site"] += 1
1210
+
1211
+ if stype == "del" and not added:
1212
+ stats["duplicate_site"] += 1
1213
+ site_kinds[apos].add(stype)
1214
+ if added:
1215
+ stats[f"loaded_{stype}"] += 1
1216
+ return added
1217
+
1218
+ vcf = pysam.VariantFile(vcf_path)
1219
+
1220
+ n_samples = len(vcf.header.samples)
1221
+ if n_samples > 1 and sample_name is None:
1222
+ raise ValueError(
1223
+ f"VCF has {n_samples} samples but no sample_name specified. "
1224
+ f"Available: {list(vcf.header.samples)}"
1225
+ )
1226
+
1227
+ # A contig the VCF never declares carries no variants (callers emit ##contig lines only
1228
+ # for contigs they called on). pysam raises "invalid contig" on fetch, so ask first.
1229
+ if contig_id and contig_id not in vcf.header.contigs:
1230
+ records = ()
1231
+ stats["contig_not_in_vcf"] = 1
1232
+ elif contig_id:
1233
+ records = vcf.fetch(contig=contig_id)
1234
+ else:
1235
+ records = vcf.fetch()
1236
+
1237
+ for record in records:
1238
+ stats["records_seen"] += 1
1239
+
1240
+ # Filter check (counted, not silent).
1241
+ if record.filter.keys() and "PASS" not in record.filter.keys():
1242
+ stats["skip_filter_not_pass"] += 1
1243
+ continue
1244
+
1245
+ alts = record.alts
1246
+ if alts is None or len(alts) == 0:
1247
+ stats["skip_no_alt"] += 1
1248
+ continue
1249
+
1250
+ ref = record.ref
1251
+
1252
+ # Get sample (for DP/AD fallbacks on caller VCFs that carry them there).
1253
+ if sample_name is not None:
1254
+ sample = record.samples[sample_name]
1255
+ elif n_samples > 0:
1256
+ sample = record.samples[0]
1257
+ else:
1258
+ sample = None
1259
+
1260
+ site_depth = None
1261
+ if "DP" in record.info:
1262
+ site_depth = record.info["DP"]
1263
+ elif sample is not None and "DP" in sample:
1264
+ site_depth = sample["DP"]
1265
+
1266
+ if site_depth is None:
1267
+ stats["skip_no_depth"] += 1
1268
+ continue
1269
+ if site_depth < config.min_depth_site:
1270
+ stats["skip_low_depth"] += 1
1271
+ continue
1272
+
1273
+ # Extract AF. INFO/AF is Number=A — one frequency PER ALT — so it is kept as a
1274
+ # per-ALT sequence rather than collapsed to element [0]. AD is Number=R (REF
1275
+ # first), so ALT i's frequency is ad[i + 1] over the total.
1276
+ alt_afs: tuple[float, ...] | None = None
1277
+ if "AF" in record.info:
1278
+ raw_af = record.info["AF"]
1279
+ alt_afs = tuple(raw_af) if isinstance(raw_af, tuple) else (raw_af,)
1280
+ elif sample is not None and "AD" in sample:
1281
+ ad = sample["AD"]
1282
+ if ad and len(ad) >= 2 and sum(ad) > 0:
1283
+ ad_total = sum(ad)
1284
+ alt_afs = tuple(a / ad_total for a in ad[1:])
1285
+
1286
+ if len(alts) > 1:
1287
+ stats["multiallelic_records"] += 1
1288
+
1289
+ # Decompose EVERY allele into atomic primitives via the one shared helper. All
1290
+ # mutation types and all (>2) alleles are ALWAYS kept; --af-range is the only gate.
1291
+ for alt_idx, alt in enumerate(alts):
1292
+ # The AF band is a PER-ALLELE gate: applied here, not once per record, so it
1293
+ # rejects only the allele outside the band, not the record's other alleles.
1294
+ alt_af = (
1295
+ alt_afs[alt_idx]
1296
+ if alt_afs is not None and alt_idx < len(alt_afs)
1297
+ else None
1298
+ )
1299
+ if config.af_range is not None and alt_af is not None:
1300
+ if not (config.af_range[0] <= alt_af <= config.af_range[1]):
1301
+ stats["skip_af_band"] += 1
1302
+ continue
1303
+ if alt is None or alt == "*" or alt.startswith("<"):
1304
+ # Spanning-deletion star / symbolic (gVCF <*>, <DEL> …): no
1305
+ # concrete allele to phase against.
1306
+ stats["skip_symbolic_allele"] += 1
1307
+ continue
1308
+ prims = _atomize_allele(record.pos, ref, alt)
1309
+ if not prims:
1310
+ # Identical (no-op) or non-ACGT ambiguity code — counted here.
1311
+ stats["skip_noncanonical"] += 1
1312
+ continue
1313
+ if len(ref) == len(alt) and len(ref) > 1:
1314
+ stats["mnp_atomized"] += 1
1315
+ for apos, aref, aalt, stype in prims:
1316
+ _register(apos, aref, aalt, stype, site_depth, alt_af)
1317
+
1318
+ vcf.close()
1319
+
1320
+ stats["n_positions"] = len(seen_pos)
1321
+ _log_load_summary(vcf_path, contig_id, stats)
1322
+ return (
1323
+ snv_pos, ref_alleles, depth, af, site_type,
1324
+ {p: frozenset(k) for p, k in site_kinds.items()},
1325
+ del_span, ins_len,
1326
+ )
1327
+
1328
+
1329
+ def make_windows_lazy(
1330
+ bam_path: str,
1331
+ contig_id: str,
1332
+ contig_length: int,
1333
+ snv_positions: list[int],
1334
+ ref_alleles: dict[int, str],
1335
+ config: HaplotyperConfig = DEFAULT_CONFIG,
1336
+ sample_id: str | None = None,
1337
+ site_type: dict[int, str] | None = None,
1338
+ site_kinds: dict[int, frozenset[str]] | None = None,
1339
+ del_span: dict[int, set[tuple[int, int]]] | None = None,
1340
+ ins_len: dict[int, set[int]] | None = None,
1341
+ sv_support: dict[int, dict[str, set[str]]] | None = None,
1342
+ ) -> list[Window]:
1343
+ """Eager wrapper around :func:`iter_windows_lazy` for callers wanting all of a contig's
1344
+ windows at once (tests, scripts). Prefer the iterator in production: materialising every
1345
+ window holds every window's reads at once, the single largest allocation on a dense contig.
1346
+ """
1347
+ return list(
1348
+ iter_windows_lazy(
1349
+ bam_path,
1350
+ contig_id,
1351
+ contig_length,
1352
+ snv_positions,
1353
+ ref_alleles,
1354
+ config,
1355
+ sample_id,
1356
+ site_type=site_type,
1357
+ site_kinds=site_kinds,
1358
+ del_span=del_span,
1359
+ ins_len=ins_len,
1360
+ sv_support=sv_support,
1361
+ )
1362
+ )
1363
+
1364
+
1365
+ def iter_windows_lazy(
1366
+ bam_path: str,
1367
+ contig_id: str,
1368
+ contig_length: int,
1369
+ snv_positions: list[int],
1370
+ ref_alleles: dict[int, str],
1371
+ config: HaplotyperConfig = DEFAULT_CONFIG,
1372
+ sample_id: str | None = None,
1373
+ site_type: dict[int, str] | None = None,
1374
+ site_kinds: dict[int, frozenset[str]] | None = None,
1375
+ del_span: dict[int, set[tuple[int, int]]] | None = None,
1376
+ ins_len: dict[int, set[int]] | None = None,
1377
+ sv_support: dict[int, dict[str, set[str]]] | None = None,
1378
+ ) -> Iterator[Window]:
1379
+ """Yield overlapping windows (50% overlap, step = window_size / 2) with lazy per-window
1380
+ read loading, so haplotypes can link across boundaries via shared SNVs.
1381
+
1382
+ O(W * reads_per_window) time, O(window) memory: the caller processes and releases each
1383
+ window before the next one's reads are pulled from the BAM.
1384
+ """
1385
+ if not HAS_PYSAM:
1386
+ raise ImportError("pysam required for BAM parsing")
1387
+
1388
+ snv_pos_sorted = sorted([p for p in snv_positions if 0 < p <= contig_length])
1389
+ if not snv_pos_sorted:
1390
+ return
1391
+
1392
+ # No RNG here any more: the per-window read cap now selects by a stable hash of the
1393
+ # read id (see the subsample below), so window contents no longer depend on a draw.
1394
+ bam = pysam.AlignmentFile(bam_path, "rb")
1395
+
1396
+ step_size = config.window_size // 2
1397
+ window_idx = 0
1398
+
1399
+ for start in range(1, contig_length + 1, step_size):
1400
+ end = min(start + config.window_size, contig_length + 1)
1401
+
1402
+ # No size-based window skipping: small/trailing windows are kept and filtered
1403
+ # downstream by the empty-window check / min_reads_per_window.
1404
+
1405
+ # Bisect the [start, end) slice of sorted snv_pos_sorted instead of scanning all
1406
+ # variants per window (the linear scan dominated self-time; see docs/design/core.md).
1407
+ lo = bisect.bisect_left(snv_pos_sorted, start)
1408
+ hi = bisect.bisect_left(snv_pos_sorted, end)
1409
+ window_snvs = snv_pos_sorted[lo:hi]
1410
+
1411
+ if len(window_snvs) < config.min_snvs_per_window:
1412
+ continue
1413
+
1414
+ snv_set = set(window_snvs)
1415
+ reads = []
1416
+
1417
+ # Partition window sites by type. Sites without a recorded type default to "snv".
1418
+ st = site_type or {}
1419
+ # Fall back to one kind per position (not an empty map) so a caller passing site_type
1420
+ # but not site_kinds keeps single-kind behaviour rather than losing indel parsing.
1421
+ sk = site_kinds or {p: frozenset({t}) for p, t in st.items()}
1422
+ ds = del_span or {}
1423
+ il = ins_len or {}
1424
+ sv_sup = sv_support or {}
1425
+ # Per-window indel index (O(1) lookups at use time):
1426
+ # del_key_to_pos: (D-op start_1b, D-op length) -> indel site pos
1427
+ # ins_key_to_pos: (I-op anchor_1b, inserted length) -> indel site pos
1428
+ # Keys are SIZE-specific, so a <len>-bp indel is its own DEL<len>/INS<len> allele.
1429
+ # Membership is by site_kinds, not site_type: a position may be both SNV and indel, so
1430
+ # it must reach the CIGAR walk; reads without the indel fall through to the anchor base.
1431
+ indel_site_set = {
1432
+ p for p in window_snvs
1433
+ if sk.get(p, frozenset()) & {"del", "ins"}
1434
+ }
1435
+ # SV pseudo-sites: the "present" allele is the UNIQUE event ID (not a generic INS/DEL
1436
+ # token), so reads cluster only on the identical event. Kept separate from
1437
+ # indel_site_set so the D/I exact-match logic never touches them.
1438
+ sv_site_set = {p for p in window_snvs if st.get(p, "snv") == "sv"} # SV anchors never co-occur with a called variant (see process_contig)
1439
+ # Sites parsed outside the base-by-base SNV loop (indels + SVs).
1440
+ special_site_set = indel_site_set | sv_site_set
1441
+ del_key_to_pos: dict[tuple[int, int], int] = {}
1442
+ ins_key_to_pos: dict[tuple[int, int], int] = {}
1443
+ for p in indel_site_set:
1444
+ # ds[p]/il[p] are SETS: one anchor may carry several edits, each its own
1445
+ # DEL<len>/INS<len> allele. A position can appear in both loops.
1446
+ for d_start, d_end in ds.get(p, ()):
1447
+ del_key_to_pos[(d_start, d_end - d_start + 1)] = p
1448
+ for ilen in il.get(p, ()):
1449
+ # (anchor, inserted length): a read matches only a same-size insertion.
1450
+ ins_key_to_pos[(p, ilen)] = p
1451
+
1452
+ # pysam fetch uses 0-based coordinates
1453
+ for aln in bam.fetch(contig_id, start - 1, end - 1):
1454
+ # SECONDARY stays out (an alternative placement of counted sequence); SUPPLEMENTARY
1455
+ # is kept as a different PART of the same molecule, merged into one Read below.
1456
+ if aln.is_secondary or aln.is_unmapped:
1457
+ continue
1458
+ if aln.mapping_quality < config.min_mapq:
1459
+ continue
1460
+
1461
+ # Physical read-to-window overlap. pysam reference_start/_end are 0-based
1462
+ # half-open; the window is [start-1, end-1) in the same frame.
1463
+ a_start = aln.reference_start
1464
+ a_end = aln.reference_end
1465
+ if a_end is None:
1466
+ continue
1467
+ win_overlap = min(a_end, end - 1) - max(a_start, start - 1)
1468
+ if win_overlap < config.min_read_window_overlap_bp:
1469
+ # A read barely clipping the window edge carries almost no information yet
1470
+ # would count like a full-span read in n_reads_examined / the abundance denom.
1471
+ continue
1472
+
1473
+ r = Read(
1474
+ id=aln.query_name,
1475
+ contig=contig_id,
1476
+ mapq=aln.mapping_quality,
1477
+ sample=sample_id,
1478
+ ref_start=a_start + 1, # store 1-based to match allele positions
1479
+ ref_end=a_end + 1,
1480
+ )
1481
+
1482
+ query_seq = aln.query_sequence
1483
+ query_qual = aln.query_qualities
1484
+
1485
+ if query_seq is None:
1486
+ continue
1487
+
1488
+ if query_qual is None:
1489
+ WarningThrottler.warn_once(
1490
+ "no_qual",
1491
+ f"Some reads lack quality scores. Using default Q{config.default_base_quality}.",
1492
+ )
1493
+
1494
+ # Extract alleles at SNV positions via a TARGETED CIGAR walk: emit only at this
1495
+ # read's SNV positions, O(variants on read) not O(read length), byte-identical to
1496
+ # get_aligned_pairs. Indel/SV sites are excluded here (handled by the scan below).
1497
+ has_overlap = False
1498
+ # SNV-only targets, sorted, so the walk advances monotonically (break sites are
1499
+ # appended only after this loop).
1500
+ snv_targets = (
1501
+ window_snvs
1502
+ if not special_site_set
1503
+ else [p for p in window_snvs if p not in special_site_set]
1504
+ )
1505
+ n_targets = len(snv_targets)
1506
+ if n_targets:
1507
+ ti = 0
1508
+ ref_cur = aln.reference_start # 0-based
1509
+ q_cur = 0
1510
+ for op, length in (aln.cigartuples or ()):
1511
+ if ti >= n_targets:
1512
+ break
1513
+ if op in (0, 7, 8): # M / = / X consume ref and query together
1514
+ seg_end = ref_cur + length # 0-based, exclusive
1515
+ # Targets before this segment fell in a D/N gap: no query base, no call.
1516
+ while ti < n_targets and snv_targets[ti] - 1 < ref_cur:
1517
+ ti += 1
1518
+ while ti < n_targets and snv_targets[ti] - 1 < seg_end:
1519
+ pos = snv_targets[ti]
1520
+ qp = q_cur + (pos - 1 - ref_cur)
1521
+ qual = (
1522
+ query_qual[qp] if query_qual else config.default_base_quality
1523
+ )
1524
+ if qual >= config.min_base_quality:
1525
+ r.alleles[pos] = query_seq[qp]
1526
+ r.quals[pos] = qual
1527
+ has_overlap = True
1528
+ ti += 1
1529
+ ref_cur, q_cur = seg_end, q_cur + length
1530
+ elif op == 1: # I consumes query only
1531
+ q_cur += length
1532
+ elif op in (2, 3): # D / N consume ref only
1533
+ ref_cur += length
1534
+ elif op == 4: # S (soft clip) consumes query only
1535
+ q_cur += length
1536
+ # H (5) / P (6) consume neither
1537
+
1538
+ # Extract alleles at indel sites. A read carries the variant iff its CIGAR has the
1539
+ # matching indel op (positions trusted exactly):
1540
+ # DEL: a D op of exactly the deleted length -> "DEL<len>"
1541
+ # INS: an I op of exactly the inserted length at the anchor -> "INS<len>"
1542
+ # Size is part of the allele, so a <len>-bp indel clusters only with same-size
1543
+ # reads. Else a matched base over the anchor is the read's "vote against"; else no call.
1544
+ if special_site_set and aln.cigartuples:
1545
+ # Quality for a DEL<len>/INS<len>/event-id token. These are not base calls, so
1546
+ # they take default_base_quality, NOT MAPQ (which the EM would misread as a
1547
+ # per-base Phred, over-weighting indels; see docs/design/core.md). MAPQ lives on Read.mapq.
1548
+ token_qual = config.default_base_quality
1549
+ # Single CIGAR walk: collect indel events and the matched-base
1550
+ # ref->query mapping for indel/SV-anchor positions only.
1551
+ ref_cursor = aln.reference_start # 0-based
1552
+ query_cursor = 0
1553
+ # Calls at indel anchors; REF-base fallback resolved at the end.
1554
+ indel_calls: dict[int, tuple[str, int]] = {}
1555
+ # ref_pos_1b -> query_idx for indel/SV anchors covered by M/=/X.
1556
+ anchor_qpos: dict[int, int] = {}
1557
+
1558
+ for op, length in aln.cigartuples:
1559
+ if op in (0, 7, 8): # M / = / X — consumes both
1560
+ # Remember the query index of each indel/SV anchor for the matched-base fallback.
1561
+ op_start_1b = ref_cursor + 1
1562
+ op_end_1b_excl = ref_cursor + length + 1
1563
+ for pos in special_site_set:
1564
+ if op_start_1b <= pos < op_end_1b_excl:
1565
+ anchor_qpos[pos] = query_cursor + (pos - op_start_1b)
1566
+ ref_cursor += length
1567
+ query_cursor += length
1568
+ elif op == 2: # D
1569
+ key = (ref_cursor + 1, length)
1570
+ pos = del_key_to_pos.get(key)
1571
+ if pos is not None:
1572
+ # per-edit token: a <len>-bp deletion is its own allele.
1573
+ indel_calls[pos] = (f"DEL{length}", token_qual)
1574
+ ref_cursor += length
1575
+ elif op == 1: # I
1576
+ # Anchor = ref_cursor in 1-based terms; match on (anchor, inserted
1577
+ # length) so a <len>-bp insertion is its own allele.
1578
+ pos = ins_key_to_pos.get((ref_cursor, length))
1579
+ if pos is not None:
1580
+ indel_calls[pos] = (f"INS{length}", token_qual)
1581
+ query_cursor += length
1582
+ elif op == 3: # N: consumes ref only
1583
+ ref_cursor += length
1584
+ elif op == 4: # S: consumes query only
1585
+ query_cursor += length
1586
+ # op 5 (H) and 6 (P) consume neither.
1587
+
1588
+ # Apply DEL/INS calls.
1589
+ for pos, (allele, mq) in indel_calls.items():
1590
+ r.alleles[pos] = allele
1591
+ r.quals[pos] = mq
1592
+ has_overlap = True
1593
+
1594
+ # Apply SV pseudo-site "present" calls: a read carries an event iff its name is
1595
+ # in THAT event's supporting-read set AND this alignment's span brackets the
1596
+ # anchor (small pad). The allele is the event ID (distinct events = multi-allelic);
1597
+ # the span check stops a read's OTHER split segment from crediting the event here.
1598
+ if sv_site_set and aln.reference_end is not None:
1599
+ aln_start_1b = aln.reference_start + 1
1600
+ aln_end_1b = aln.reference_end # 1-based inclusive (None-guarded above)
1601
+ for pos in sv_site_set:
1602
+ events = sv_sup.get(pos)
1603
+ if not events:
1604
+ continue
1605
+ if not (aln_start_1b - _SV_ANCHOR_PAD <= pos <= aln_end_1b + _SV_ANCHOR_PAD):
1606
+ continue
1607
+ for event_id, ev_reads in events.items():
1608
+ if aln.query_name in ev_reads:
1609
+ r.alleles[pos] = event_id
1610
+ r.quals[pos] = token_qual
1611
+ has_overlap = True
1612
+ break
1613
+
1614
+ # For indel/SV sites with no event call but a matched anchor
1615
+ # base, record the base as the read's "ref-like" (absent) vote.
1616
+ for pos, qpos in anchor_qpos.items():
1617
+ if pos in r.alleles: # already called (indel or SV present)
1618
+ continue
1619
+ base = query_seq[qpos]
1620
+ qual = (
1621
+ query_qual[qpos] if query_qual else config.default_base_quality
1622
+ )
1623
+ if qual >= config.min_base_quality:
1624
+ r.alleles[pos] = base
1625
+ r.quals[pos] = qual
1626
+ has_overlap = True
1627
+
1628
+ if has_overlap:
1629
+ reads.append(r)
1630
+
1631
+ # Re-assemble split molecules into single reads, and register the breakpoints
1632
+ # they reveal as sites. Done before subsampling so the cap counts molecules.
1633
+ reads, break_sites = _merge_split_reads(reads, config, snv_set)
1634
+ for bp in break_sites:
1635
+ if bp not in snv_set and start <= bp < end:
1636
+ window_snvs.append(bp)
1637
+ snv_set.add(bp)
1638
+ ref_alleles[bp] = CONTINUOUS
1639
+ st[bp] = "sv"
1640
+ if break_sites:
1641
+ window_snvs.sort()
1642
+
1643
+ # Subsample consistently across windows: keep the reads whose ids hash smallest, so two
1644
+ # overlapping windows pick the same reads from the molecules they share (an independent
1645
+ # per-window draw left ~2-3 shared where biology has hundreds; the linker depends on this).
1646
+ if config.max_reads_per_window and len(reads) > config.max_reads_per_window:
1647
+ reads = [
1648
+ r for _, _, r in sorted(
1649
+ (_read_sort_hash(r.id, config.random_seed), i, r)
1650
+ for i, r in enumerate(reads)
1651
+ )[: config.max_reads_per_window]
1652
+ ]
1653
+
1654
+ # Window CREATION uses the lower rescue floor, so the [rescue, phasing) band still
1655
+ # exists and can receive a rescued anchor haplotype. De-novo PHASING is gated separately
1656
+ # in process_window() at the higher min_reads_per_window.
1657
+ if len(reads) < config.min_reads_for_rescue:
1658
+ continue
1659
+
1660
+ w = Window(contig=contig_id, start=start, end=end, sample=sample_id, window_idx=window_idx)
1661
+ w.snv_pos = window_snvs
1662
+ # Guarded: a caller supplying positions without an anchor base must not take the
1663
+ # whole contig down here.
1664
+ w.ref_alleles = {p: ref_alleles[p] for p in window_snvs if p in ref_alleles}
1665
+ w.reads = reads
1666
+ # Carry site types through; the identity code needs them to exclude SV positions.
1667
+ w.site_type = {p: st[p] for p in window_snvs if p in st}
1668
+ yield w
1669
+ window_idx += 1
1670
+
1671
+ bam.close()
1672
+
1673
+
1674
+ # =============================================================================
1675
+ # OPTIMIZED GRAPH INITIALIZER
1676
+ # =============================================================================
1677
+
1678
+
1679
+ class GraphInitializer:
1680
+ """Seed haplotypes by clustering the read-overlap graph into Louvain communities."""
1681
+
1682
+ def __init__(self, config: HaplotyperConfig = DEFAULT_CONFIG):
1683
+ self.config = config
1684
+
1685
+ def build_overlap_graph(self, window: Window) -> nx.Graph:
1686
+ """Build the read-overlap graph: an edge joins two reads within identity_distance."""
1687
+ graph = nx.Graph()
1688
+ reads = window.reads
1689
+ n_reads = len(reads)
1690
+
1691
+ # one node per read (read indices)
1692
+ for i in range(n_reads):
1693
+ graph.add_node(i)
1694
+
1695
+ # SNV positions each read covers (cached)
1696
+ pos_sets = window.get_read_position_sets()
1697
+
1698
+ # Connect reads that share enough SNVs and agree closely.
1699
+ for i in range(n_reads):
1700
+ pos_i = pos_sets[i]
1701
+ if not pos_i:
1702
+ continue
1703
+
1704
+ for j in range(i + 1, n_reads):
1705
+ pos_j = pos_sets[j]
1706
+ shared = pos_i & pos_j
1707
+ n_shared = len(shared)
1708
+
1709
+ if n_shared < self.config.min_shared_snvs_for_edge:
1710
+ continue
1711
+
1712
+ r_i, r_j = reads[i], reads[j]
1713
+
1714
+ # Physical read-read overlap. -1 = spans unknown (e.g. synthetic test reads),
1715
+ # so the gate is skipped rather than rejecting everything.
1716
+ ov = r_i.overlap_bp(r_j)
1717
+ if 0 <= ov < self.config.min_read_read_overlap_bp:
1718
+ continue
1719
+
1720
+ # Count mismatches with early exit. The gate is the rate:
1721
+ # floor(identity_distance * n_shared) (forces 0 mismatches below n_shared=50 at 2%).
1722
+ max_allowed = int(self.config.identity_distance * n_shared)
1723
+ mismatches = 0
1724
+ exceeded = False
1725
+
1726
+ for p in shared:
1727
+ if r_i.alleles[p] != r_j.alleles[p]:
1728
+ mismatches += 1
1729
+ if mismatches > max_allowed:
1730
+ exceeded = True
1731
+ break
1732
+
1733
+ if not exceeded:
1734
+ mismatch_frac = mismatches / n_shared
1735
+ # Edge weight = #shared SNVs scaled by agreement (higher is better).
1736
+ weight = (1.0 - mismatch_frac) * n_shared
1737
+ graph.add_edge(i, j, weight=weight)
1738
+
1739
+ return graph
1740
+
1741
+ def derive_consensus(self, cluster_reads: list[Read], window: Window) -> dict[int, str]:
1742
+ """Derive consensus from cluster reads."""
1743
+ allele_counts = defaultdict(lambda: defaultdict(int))
1744
+
1745
+ for r in cluster_reads:
1746
+ for pos, base in r.alleles.items():
1747
+ if window.start <= pos < window.end and pos in window.snv_pos:
1748
+ allele_counts[pos][base] += 1
1749
+
1750
+ # Consensus = most frequent allele at each SNV position.
1751
+ consensus = {}
1752
+ for pos in window.snv_pos:
1753
+ if pos in allele_counts:
1754
+ consensus[pos] = max(allele_counts[pos], key=allele_counts[pos].get)
1755
+
1756
+ return consensus
1757
+
1758
+ def get_initial_haplotypes(self, window: Window) -> tuple[list[Haplotype], list[int]]:
1759
+ """Initialize haplotypes using graph clustering."""
1760
+ graph = self.build_overlap_graph(window)
1761
+
1762
+ if graph.number_of_edges() == 0:
1763
+ # No edges => no clustering signal; fall back to single consensus haplotype.
1764
+ consensus = self.derive_consensus(window.reads, window)
1765
+ if consensus:
1766
+ return [Haplotype(consensus=consensus, supporting_reads=len(window.reads))], [
1767
+ len(window.reads)
1768
+ ]
1769
+ return [], []
1770
+
1771
+ # Louvain community detection. random_state is passed explicitly: without it
1772
+ # python-louvain draws from the unseeded global `random`, making reruns disagree at ~1e-7.
1773
+ partition = community_louvain.best_partition(
1774
+ graph, weight="weight", random_state=self.config.random_seed
1775
+ )
1776
+
1777
+ clusters = defaultdict(list)
1778
+ for node_idx, cluster_id in partition.items():
1779
+ clusters[cluster_id].append(window.reads[node_idx])
1780
+
1781
+ # one consensus per cluster
1782
+ initial_haps = []
1783
+ cluster_sizes = []
1784
+
1785
+ for _cluster_id, cluster_reads in clusters.items():
1786
+ if len(cluster_reads) < self.config.min_reads_per_cluster:
1787
+ continue
1788
+
1789
+ consensus = self.derive_consensus(cluster_reads, window)
1790
+ if consensus:
1791
+ hap = Haplotype(consensus=consensus, supporting_reads=len(cluster_reads))
1792
+ initial_haps.append(hap)
1793
+ cluster_sizes.append(len(cluster_reads))
1794
+
1795
+ return initial_haps, cluster_sizes
1796
+
1797
+
1798
+ # =============================================================================
1799
+ # OPTIMIZED EM ENGINE
1800
+ # =============================================================================
1801
+
1802
+
1803
+ class EMHaplotyper:
1804
+ """Quality-weighted EM refinement of window haplotypes, with a junk component."""
1805
+
1806
+ def __init__(
1807
+ self,
1808
+ window: Window,
1809
+ initial_haplotypes: list[Haplotype],
1810
+ cluster_sizes: list[int] | None = None,
1811
+ config: HaplotyperConfig = DEFAULT_CONFIG,
1812
+ ):
1813
+ self.window = window
1814
+ self.haplotypes = initial_haplotypes
1815
+ self.cluster_sizes = cluster_sizes
1816
+ self.reads = window.reads
1817
+ self.config = config
1818
+
1819
+ # Single 6-state alphabet {A,C,G,T,DEL,INS} — indels are always on.
1820
+ self._cache = _LOG_PROB_CACHE
1821
+
1822
+ # The site set every component is scored over, fixed for the whole run: this is what
1823
+ # makes gamma a posterior (components compared on the same observations) and the
1824
+ # log-likelihood a function of the parameters alone.
1825
+ self._snv_set = set(window.snv_pos)
1826
+ self._support = [_read_support(r, self._snv_set) for r in self.reads]
1827
+
1828
+
1829
+
1830
+ def run(self) -> tuple[list[Haplotype], np.ndarray, np.ndarray, float, bool, int]:
1831
+ """Run EM with cached log-probability computations."""
1832
+ haplotypes = self.haplotypes
1833
+ reads = self.reads
1834
+ n_reads = len(reads)
1835
+ n_haps = len(haplotypes)
1836
+
1837
+ if n_haps == 0:
1838
+ # Degenerate case: only junk class.
1839
+ gamma = np.ones((n_reads, 1))
1840
+ pi = np.array([1.0])
1841
+ return [], gamma, pi, -np.inf, True, 0
1842
+
1843
+ k_eff = n_haps + 1
1844
+ junk_idx = n_haps
1845
+
1846
+ # Initialize mixture weights (pi): either from cluster sizes or uniform.
1847
+ if self.cluster_sizes:
1848
+ cluster_total = sum(self.cluster_sizes)
1849
+ junk_init = max(1, n_reads - cluster_total)
1850
+ pi = np.array(self.cluster_sizes + [junk_init], dtype=float)
1851
+ pi /= pi.sum()
1852
+ else:
1853
+ pi = np.ones(k_eff) / k_eff
1854
+
1855
+ gamma = np.zeros((n_reads, k_eff))
1856
+ prev_log_like = -np.inf
1857
+ converged = False
1858
+
1859
+ # E-step tensors constant across iterations (allele matrix, match/mismatch log-probs,
1860
+ # junk log-likelihood), built once; only logl_hap is recomputed per iteration.
1861
+ (
1862
+ _em_site_idx, _em_alleles, _em_code, _em_read_code,
1863
+ _em_sup_mask, _em_lm, _em_lmm, logl_junk,
1864
+ ) = _em_read_tensors(
1865
+ reads,
1866
+ self._support,
1867
+ self.window.ref_alleles,
1868
+ self.config.junk_divergence_rate,
1869
+ self.config.default_base_quality,
1870
+ _LOG_PROB_CACHE,
1871
+ )
1872
+ # Derived constants for the vectorised M-step vote: log_odds = log_match - log_mismatch,
1873
+ # a code->allele decoder, a site-index->position list, the read-allele alphabet size.
1874
+ _em_lo = _em_lm - _em_lmm
1875
+ _em_sites = sorted(_em_site_idx, key=_em_site_idx.get)
1876
+ _em_dec = {c: a for a, c in _em_alleles.items()}
1877
+ _em_n_alleles = (
1878
+ int(_em_read_code.max()) + 1
1879
+ if _em_read_code.size and _em_read_code.max() >= 0
1880
+ else 0
1881
+ )
1882
+ _em_snv_pos = set(self.window.snv_pos)
1883
+
1884
+ for iteration in range(self.config.em_max_iter):
1885
+ # E-STEP prep: log P(read | haplotype) for the current consensuses.
1886
+ # (logl_junk is constant across iterations, computed once above.)
1887
+ logl_hap = _em_logl_hap(
1888
+ haplotypes, _em_site_idx, _em_code, _em_read_code,
1889
+ _em_sup_mask, _em_lm, _em_lmm,
1890
+ )
1891
+
1892
+ # E-STEP: gamma[i,k] and the data log-likelihood from ONE batched logsumexp over
1893
+ # the (n_reads x k_eff) log-posterior.
1894
+ log_pi = np.log(pi + 1e-12)
1895
+ logp = np.full((n_reads, k_eff), -np.inf)
1896
+ logp[:, :n_haps] = log_pi[:n_haps][None, :] + logl_hap # -inf where logl_hap -inf
1897
+ logp[:, junk_idx] = log_pi[junk_idx] + logl_junk
1898
+ log_sum = logsumexp(logp, axis=1) # (n_reads,)
1899
+ gamma[:] = 0.0
1900
+ good = ~np.isneginf(log_sum)
1901
+ gamma[good] = np.exp(logp[good] - log_sum[good, None])
1902
+ gamma[~good, junk_idx] = 1.0
1903
+ # Junk is always finite, so log_sum is finite for every read; summing it reproduces
1904
+ # the per-read logsumexp total.
1905
+ log_like = float(log_sum.sum())
1906
+
1907
+ # M-STEP: update mixture weights and haplotype consensuses.
1908
+ # nk = effective counts per component (with Dirichlet smoothing).
1909
+ nk = gamma.sum(axis=0) + (self.config.dirichlet_alpha - 1.0)
1910
+ pi = nk / nk.sum()
1911
+
1912
+ # Rebuild haplotypes by weighted voting over reads.
1913
+ new_haps = []
1914
+ surviving_indices = []
1915
+
1916
+ for k in range(n_haps):
1917
+ if nk[k] < self.config.min_hap_eff_weight:
1918
+ continue
1919
+
1920
+ # Rebuild this haplotype's consensus by gamma-weighted voting (see
1921
+ # _em_hap_consensus). "no vote" -> None and "all failed the floor" -> {}.
1922
+ new_consensus = _em_hap_consensus(
1923
+ gamma[:, k], _em_read_code, _em_sup_mask, _em_lo, _em_lmm,
1924
+ _em_n_alleles, _em_sites, _em_dec, _em_snv_pos,
1925
+ self.config.min_gamma_for_vote,
1926
+ )
1927
+ if len(new_consensus) >= self.config.min_snvs_per_window:
1928
+ new_haps.append(Haplotype(consensus=new_consensus))
1929
+ surviving_indices.append(k)
1930
+
1931
+ # Update structures after pruning low-weight haplotypes.
1932
+ haplotypes = new_haps
1933
+ n_haps = len(haplotypes)
1934
+
1935
+ if n_haps == 0:
1936
+ pi = np.array([1.0])
1937
+ gamma = np.ones((n_reads, 1))
1938
+ return [], gamma, pi, log_like, True, iteration + 1
1939
+
1940
+ # Rebuild pi and gamma to match the surviving haplotypes.
1941
+ junk_mass = nk[-1]
1942
+ nk_surv = nk[surviving_indices]
1943
+ nk_new = np.concatenate([nk_surv, [junk_mass]])
1944
+ pi = nk_new / nk_new.sum()
1945
+
1946
+ k_eff = n_haps + 1
1947
+ junk_idx = n_haps
1948
+
1949
+ gamma_new = np.zeros((n_reads, k_eff))
1950
+ for new_k, old_k in enumerate(surviving_indices):
1951
+ gamma_new[:, new_k] = gamma[:, old_k]
1952
+ gamma_new[:, junk_idx] = gamma[:, -1]
1953
+ gamma = gamma_new
1954
+
1955
+ row_sums = gamma.sum(axis=1, keepdims=True)
1956
+ # A read whose whole responsibility sat on pruned haplotypes has nothing left; put
1957
+ # its mass on junk (what "no haplotype explains this read" means) so the row stays a
1958
+ # distribution. The next E-step usually overwrites it, except on a converging iteration.
1959
+ dead_rows = (row_sums[:, 0] == 0.0)
1960
+ if dead_rows.any():
1961
+ gamma[dead_rows, :] = 0.0
1962
+ gamma[dead_rows, junk_idx] = 1.0
1963
+ row_sums[dead_rows] = 1.0
1964
+ gamma /= row_sums
1965
+
1966
+ # Convergence: relative change in log-likelihood (large negative numbers).
1967
+ if prev_log_like != -np.inf and abs(prev_log_like) > 1e-10:
1968
+ relative_change = abs(log_like - prev_log_like) / abs(prev_log_like)
1969
+ if relative_change < self.config.em_tolerance:
1970
+ converged = True
1971
+ break
1972
+ else:
1973
+ # For first iteration or very small log-likelihood, use absolute tolerance
1974
+ if abs(log_like - prev_log_like) < self.config.em_tolerance:
1975
+ converged = True
1976
+ break
1977
+ prev_log_like = log_like
1978
+
1979
+ # Final metadata: weights, read support, and confidence per haplotype.
1980
+ for k, hap in enumerate(haplotypes):
1981
+ hap.weight = pi[k]
1982
+ hap.supporting_reads = int(
1983
+ (gamma[:, k] >= self.config.assign_confidence_threshold).sum()
1984
+ )
1985
+ confident_mask = gamma[:, k] >= self.config.assign_confidence_threshold
1986
+ if confident_mask.sum() > 0:
1987
+ hap.confidence = float(gamma[confident_mask, k].mean())
1988
+
1989
+ return haplotypes, gamma, pi, log_like, converged, iteration + 1
1990
+
1991
+
1992
+ # =============================================================================
1993
+ # POST-PROCESSOR (with 1-SNP validation)
1994
+ # =============================================================================
1995
+
1996
+
1997
+ class PostProcessor:
1998
+ """Post-processing: within-window haplotype merging and the 1-SNV validator."""
1999
+
2000
+ def __init__(self, config: HaplotyperConfig = DEFAULT_CONFIG):
2001
+ self.config = config
2002
+
2003
+ def should_merge_1snp_pair(
2004
+ self,
2005
+ hap1: Haplotype,
2006
+ hap2: Haplotype,
2007
+ k1: int,
2008
+ k2: int,
2009
+ window: Window,
2010
+ gamma: np.ndarray,
2011
+ n_timepoints_seen: int = 1,
2012
+ ) -> bool:
2013
+ """Decide whether a pair differing at one SNV should be merged.
2014
+
2015
+ Always applied: a single differing site is exactly where a real low-abundance
2016
+ strain and a sequencing artefact look alike. Read support leads, then the binomial
2017
+ test when few timepoints are seen, then the frequency floor as a backstop.
2018
+ """
2019
+ diff_positions = hap1.get_differing_positions(hap2, window.snv_pos)
2020
+ if len(diff_positions) != 1:
2021
+ return True
2022
+
2023
+ diff_pos = diff_positions[0]
2024
+
2025
+ if hap1.weight < hap2.weight:
2026
+ minor_hap, minor_k = hap1, k1
2027
+ else:
2028
+ minor_hap, minor_k = hap2, k2
2029
+
2030
+ minor_supporting = int((gamma[:, minor_k] >= self.config.assign_confidence_threshold).sum())
2031
+ if minor_supporting < self.config.marker_min_reads:
2032
+ return True
2033
+
2034
+ if n_timepoints_seen < self.config.marker_min_samples:
2035
+ minor_base = minor_hap.consensus.get(diff_pos)
2036
+ if minor_base is None:
2037
+ return True
2038
+
2039
+ minor_count = 0
2040
+ total_at_pos = 0
2041
+ p_error_sum = 0.0
2042
+ for read in window.reads:
2043
+ if diff_pos in read.alleles:
2044
+ total_at_pos += 1
2045
+ q = read.quals.get(diff_pos, self.config.default_base_quality)
2046
+ # /3: the null is that the minor calls are sequencing errors that
2047
+ # happened to produce THIS base, one of the three alternatives.
2048
+ p_error_sum += 10 ** (-q / 10.0) / 3.0
2049
+ if read.alleles[diff_pos] == minor_base:
2050
+ minor_count += 1
2051
+
2052
+ if total_at_pos == 0:
2053
+ return True
2054
+
2055
+ # The reads' own base qualities, not a fixed Q30: assuming Q30 asserts an accuracy
2056
+ # the data need not carry and errs towards SPLIT (phantom strains; measurement in
2057
+ # docs/design/core.md). The binomial wants one rate, so the mean over the reads stands in.
2058
+ p_error = p_error_sum / total_at_pos
2059
+ alpha_corrected = self.config.binomial_alpha / len(window.snv_pos)
2060
+ p_value = 1 - binom.cdf(minor_count - 1, total_at_pos, p_error)
2061
+
2062
+ if p_value > alpha_corrected:
2063
+ return True
2064
+
2065
+ # Frequency floor, as a backstop: a haplotype below marker_min_frac is still not
2066
+ # counted as a separate strain even when the evidence above looks real.
2067
+ if minor_hap.weight < self.config.marker_min_frac:
2068
+ return True
2069
+
2070
+ return False
2071
+
2072
+ def merge_similar_haplotypes(
2073
+ self,
2074
+ haplotypes: list[Haplotype],
2075
+ gamma: np.ndarray,
2076
+ pi: np.ndarray,
2077
+ window: Window,
2078
+ n_timepoints_seen: int = 1,
2079
+ ) -> tuple[list[Haplotype], np.ndarray, np.ndarray]:
2080
+ """Merge haplotypes that are one entity, comparing over informative positions."""
2081
+ n_haps = len(haplotypes)
2082
+ if n_haps <= 1:
2083
+ return haplotypes, gamma, pi
2084
+
2085
+ # Compare over informative positions only, like link_windows: a rate over every called
2086
+ # site dilutes a true difference as depth grows. Comparison-time only; nothing is pruned
2087
+ # from a consensus, so wider-scope steps still see every position.
2088
+ markers = variable_marker_positions(
2089
+ (h.consensus for h in haplotypes), window.site_type, self.config
2090
+ )
2091
+ compare_positions = sorted(markers) if markers else list(window.snv_pos)
2092
+ max_mismatches = None
2093
+
2094
+ used = set()
2095
+ new_haplotypes = []
2096
+ old_to_new = [-1] * n_haps
2097
+
2098
+ # Greedy grouping: for each unused haplotype, merge any other haplotype
2099
+ # within the distance threshold (and passing the 1-SNP guard if needed).
2100
+ for i in range(n_haps):
2101
+ if i in used:
2102
+ continue
2103
+
2104
+ group = [i]
2105
+ for j in range(i + 1, n_haps):
2106
+ if j in used:
2107
+ continue
2108
+
2109
+ # Two questions, two denominators. Co-support ("overlap enough to compare?") is
2110
+ # over every called position (what min_shared_markers was calibrated against);
2111
+ # identity ("same entity?") is over the informative positions only.
2112
+ _d, _nd, n_shared = haplotypes[i].distance_to(
2113
+ haplotypes[j], window.snv_pos, None
2114
+ )
2115
+ if n_shared < self.config.min_shared_markers:
2116
+ continue
2117
+ _d2, n_diff, _ns = haplotypes[i].distance_to(
2118
+ haplotypes[j], compare_positions, max_mismatches
2119
+ )
2120
+
2121
+ # No rate over informative positions, only a count: 0 diffs is one entity, 1 is
2122
+ # the should_merge_1snp_pair case, >=2 is a real difference at any depth. Same
2123
+ # rule track_merge applies across samples (byte-identity + a 1-SNV guard), so the
2124
+ # within-window and cross-sample merges agree.
2125
+ if n_diff == 0:
2126
+ group.append(j)
2127
+ elif n_diff == 1:
2128
+ if not self.should_merge_1snp_pair(
2129
+ haplotypes[i], haplotypes[j], i, j, window, gamma,
2130
+ n_timepoints_seen
2131
+ ):
2132
+ continue
2133
+ group.append(j)
2134
+
2135
+ used.update(group)
2136
+
2137
+ # Merge consensus by weighted voting across the group.
2138
+ allele_votes = defaultdict(lambda: defaultdict(float))
2139
+ for g in group:
2140
+ weight = pi[g]
2141
+ for pos, base in haplotypes[g].consensus.items():
2142
+ allele_votes[pos][base] += weight
2143
+
2144
+ merged_consensus = {}
2145
+ for pos, counts in allele_votes.items():
2146
+ merged_consensus[pos] = max(counts, key=counts.get)
2147
+
2148
+ new_idx = len(new_haplotypes)
2149
+ new_haplotypes.append(Haplotype(consensus=merged_consensus))
2150
+ for g in group:
2151
+ old_to_new[g] = new_idx
2152
+
2153
+ # Rebuild pi and gamma for the merged haplotypes.
2154
+ new_k_count = len(new_haplotypes)
2155
+ new_pi = np.zeros(new_k_count + 1)
2156
+
2157
+ for old_k, new_k in enumerate(old_to_new):
2158
+ if new_k >= 0:
2159
+ new_pi[new_k] += pi[old_k]
2160
+ new_pi[-1] = pi[-1]
2161
+ new_pi /= new_pi.sum()
2162
+
2163
+ new_gamma = np.zeros((gamma.shape[0], new_k_count + 1))
2164
+ for old_k, new_k in enumerate(old_to_new):
2165
+ if new_k >= 0:
2166
+ new_gamma[:, new_k] += gamma[:, old_k]
2167
+ new_gamma[:, -1] = gamma[:, -1]
2168
+
2169
+ row_sums = new_gamma.sum(axis=1, keepdims=True)
2170
+ row_sums[row_sums == 0] = 1.0
2171
+ new_gamma /= row_sums
2172
+
2173
+ # Update haplotype metadata after merging.
2174
+ for k, hap in enumerate(new_haplotypes):
2175
+ hap.weight = new_pi[k]
2176
+ hap.supporting_reads = int(
2177
+ (new_gamma[:, k] >= self.config.assign_confidence_threshold).sum()
2178
+ )
2179
+ confident_mask = new_gamma[:, k] >= self.config.assign_confidence_threshold
2180
+ if confident_mask.sum() > 0:
2181
+ hap.confidence = float(new_gamma[confident_mask, k].mean())
2182
+
2183
+ return new_haplotypes, new_gamma, new_pi
2184
+
2185
+ def assign_reads(self, reads: list[Read], gamma: np.ndarray) -> list[dict]:
2186
+ """Hard assignment of reads.
2187
+
2188
+ Load-bearing, not a debugging aid: feeds the shared-read link path in link_windows and
2189
+ post-hoc read-overlap threading. Cheap (one small dict per read).
2190
+ """
2191
+ assignments = []
2192
+ n_reads, k_eff = gamma.shape
2193
+ junk_idx = k_eff - 1
2194
+
2195
+ for i in range(n_reads):
2196
+ probs = gamma[i, :]
2197
+ best_k = int(np.argmax(probs))
2198
+ best_prob = float(probs[best_k])
2199
+
2200
+ is_junk = best_k == junk_idx
2201
+
2202
+ if is_junk:
2203
+ hap_id = None
2204
+ is_ambiguous = False
2205
+ elif best_prob >= self.config.assign_confidence_threshold:
2206
+ hap_id = best_k
2207
+ is_ambiguous = False
2208
+ else:
2209
+ hap_id = None
2210
+ is_ambiguous = True
2211
+
2212
+ assignments.append(
2213
+ {
2214
+ "read_id": reads[i].id,
2215
+ "hap_id": hap_id,
2216
+ # The argmax haplotype REGARDLESS of confidence (None only for junk). hap_id
2217
+ # above is withheld below assign_confidence_threshold, right for calling a
2218
+ # read's haplotype but wrong for LINKING: near-identical strains leave most
2219
+ # reads at gamma 0.6-0.89, exactly where linking evidence matters most.
2220
+ "best_hap": None if is_junk else best_k,
2221
+ "prob": best_prob,
2222
+ "is_junk": is_junk,
2223
+ "is_ambiguous": is_ambiguous,
2224
+ }
2225
+ )
2226
+
2227
+ return assignments
2228
+
2229
+
2230
+ # =============================================================================
2231
+ # OPTIMIZED LONGITUDINAL INTEGRATOR
2232
+ # =============================================================================
2233
+
2234
+ # Weight the junk component keeps no matter what a rescue takes from it, for numerical
2235
+ # stability. A rescue is funded ENTIRELY out of junk, so this floor is also the gate on
2236
+ # whether a rescue can happen at all: below it there is nothing to fund one with.
2237
+ _MIN_JUNK_WEIGHT = 0.01
2238
+
2239
+
2240
+ class LongitudinalIntegrator:
2241
+ """Cross-timepoint integration: anchor panels and low-abundance rescue."""
2242
+
2243
+ def __init__(self, config: HaplotyperConfig = DEFAULT_CONFIG):
2244
+ self.config = config
2245
+ self.rescue_statistics: list[RescueStatistic] = []
2246
+
2247
+ def build_anchor_panel_for_key(
2248
+ self,
2249
+ sample_results: dict[str, WindowResult],
2250
+ *,
2251
+ include_low_weight: bool = False,
2252
+ exclude_sample: str | None = None,
2253
+ ) -> tuple[list[Haplotype], list[str]]:
2254
+ """Build the anchor panel from a sample_results dict already filtered to one window key."""
2255
+ anchor_haps = []
2256
+ anchor_samples = []
2257
+
2258
+ for sample_id, wr in sample_results.items():
2259
+ if exclude_sample and sample_id == exclude_sample:
2260
+ continue
2261
+ for hap in wr.haplotypes:
2262
+ if include_low_weight or hap.weight >= self.config.min_weight_for_anchor:
2263
+ anchor_haps.append(hap)
2264
+ anchor_samples.append(sample_id)
2265
+
2266
+ return anchor_haps, anchor_samples
2267
+
2268
+ def rescue_window_result(
2269
+ self,
2270
+ window_result: WindowResult,
2271
+ anchor_haps: list[Haplotype],
2272
+ anchor_samples: list[str],
2273
+ sample_results: dict[str, WindowResult],
2274
+ current_sample: str,
2275
+ ) -> WindowResult:
2276
+ """Rescue missing haplotypes: junk-assigned reads that match an anchor from another
2277
+ timepoint become a new haplotype built from those reads.
2278
+ """
2279
+ if not anchor_haps:
2280
+ # Try to get anchors including low-weight ones
2281
+ anchor_haps, anchor_samples = self.build_anchor_panel_for_key(
2282
+ sample_results,
2283
+ include_low_weight=True,
2284
+ exclude_sample=current_sample,
2285
+ )
2286
+ if not anchor_haps:
2287
+ self.rescue_statistics.append(
2288
+ RescueStatistic(
2289
+ sample=current_sample,
2290
+ rescued_timepoint=current_sample,
2291
+ contig=window_result.window.contig,
2292
+ window_start=window_result.window.start,
2293
+ track_id="window",
2294
+ was_rescued=False,
2295
+ original_weight=0.0,
2296
+ rescued_weight=0.0,
2297
+ donor_timepoint="",
2298
+ anchor_distance=-1.0,
2299
+ n_shared_with_anchor=0,
2300
+ n_mismatched_with_anchor=0,
2301
+ reason="no_anchors",
2302
+ )
2303
+ )
2304
+ return window_result
2305
+
2306
+ window = window_result.window
2307
+ haplotypes = list(window_result.haplotypes) # Make mutable copy
2308
+ gamma = window_result.gamma.copy()
2309
+ pi = window_result.pi.copy()
2310
+ reads = window.reads
2311
+
2312
+ n_haps = len(haplotypes)
2313
+ junk_idx = n_haps # Last column in gamma/pi is the junk component.
2314
+ junk_weight = pi[junk_idx] if len(pi) > junk_idx else 0.0
2315
+
2316
+ junk_threshold = 0.5 # Read is "junk" if gamma[:, junk_idx] > this
2317
+ junk_read_mask = gamma[:, junk_idx] > junk_threshold
2318
+ n_junk_reads = junk_read_mask.sum()
2319
+
2320
+ logging.debug(
2321
+ f" Rescue check: {n_junk_reads}/{len(reads)} junk reads, "
2322
+ f"junk_weight={junk_weight:.3f}, {len(anchor_haps)} anchors"
2323
+ )
2324
+
2325
+ # Even a single junk read matching an anchor from another timepoint is meaningful,
2326
+ # as long as the match is near-exact (controlled by identity_distance).
2327
+ if n_junk_reads < 1:
2328
+ # Not enough junk reads to rescue
2329
+ self.rescue_statistics.append(
2330
+ RescueStatistic(
2331
+ sample=current_sample,
2332
+ rescued_timepoint=current_sample,
2333
+ contig=window.contig,
2334
+ window_start=window.start,
2335
+ track_id="window",
2336
+ was_rescued=False,
2337
+ original_weight=junk_weight,
2338
+ rescued_weight=junk_weight,
2339
+ donor_timepoint="",
2340
+ anchor_distance=-1.0,
2341
+ n_shared_with_anchor=0,
2342
+ n_mismatched_with_anchor=0,
2343
+ reason="no_junk_reads",
2344
+ )
2345
+ )
2346
+ return window_result
2347
+
2348
+ # A rescue is funded entirely out of junk's weight, down to _MIN_JUNK_WEIGHT; below
2349
+ # that floor there is nothing to fund one with and proceeding is harmful (rescued
2350
+ # weights scale to 0, junk inflates). A junk read count above 0 does not imply the weight is there.
2351
+ if junk_weight - _MIN_JUNK_WEIGHT <= 0.0:
2352
+ self.rescue_statistics.append(
2353
+ RescueStatistic(
2354
+ sample=current_sample,
2355
+ rescued_timepoint=current_sample,
2356
+ contig=window.contig,
2357
+ window_start=window.start,
2358
+ track_id="window",
2359
+ was_rescued=False,
2360
+ original_weight=junk_weight,
2361
+ rescued_weight=junk_weight,
2362
+ donor_timepoint="",
2363
+ anchor_distance=-1.0,
2364
+ n_shared_with_anchor=0,
2365
+ n_mismatched_with_anchor=0,
2366
+ reason="junk_below_floor",
2367
+ )
2368
+ )
2369
+ return window_result
2370
+
2371
+ # Avoid duplicating an already-present haplotype in this window.
2372
+ existing_consensuses = [h.consensus for h in haplotypes]
2373
+
2374
+ max_distance = self.config.identity_distance
2375
+ min_shared = self.config.min_shared_for_rescue
2376
+ min_shared_for_read = 2 # Lower threshold for individual reads
2377
+
2378
+ # ---- Step 1: For each junk read, find all anchors it matches (distance).
2379
+ # read_matches[i] = list of (anchor_idx, distance) for read i (junk only).
2380
+ read_matches: dict[int, list[tuple[int, float]]] = defaultdict(list)
2381
+ for i, read in enumerate(reads):
2382
+ if not junk_read_mask[i]:
2383
+ continue
2384
+ for anchor_idx, anchor in enumerate(anchor_haps):
2385
+ n_shared = 0
2386
+ n_match = 0
2387
+ for pos, allele in read.alleles.items():
2388
+ if pos in anchor.consensus:
2389
+ n_shared += 1
2390
+ if anchor.consensus[pos] == allele:
2391
+ n_match += 1
2392
+ if n_shared >= min_shared_for_read:
2393
+ distance = 1.0 - (n_match / n_shared)
2394
+ if distance <= max_distance:
2395
+ read_matches[i].append((anchor_idx, distance))
2396
+
2397
+ # ---- Step 2: Assign each junk read to exactly one anchor (best distance, then lowest
2398
+ # index), avoiding the double-counting that inflated total_rescued_weight.
2399
+ anchor_to_reads: dict[int, list[tuple[int, int, int, int]]] = defaultdict(list)
2400
+ for i, matches in read_matches.items():
2401
+ if not matches:
2402
+ continue
2403
+ # Best = smallest distance, then smallest anchor_idx
2404
+ anchor_idx, dist = min(matches, key=lambda x: (x[1], x[0]))
2405
+ read = reads[i]
2406
+ n_shared = 0
2407
+ n_match = 0
2408
+ for pos, allele in read.alleles.items():
2409
+ if pos in anchor_haps[anchor_idx].consensus:
2410
+ n_shared += 1
2411
+ if anchor_haps[anchor_idx].consensus[pos] == allele:
2412
+ n_match += 1
2413
+ # (read_idx, n_agree, n_disagree, n_total)
2414
+ anchor_to_reads[anchor_idx].append((i, n_match, n_shared - n_match, n_shared))
2415
+
2416
+ # ---- Step 3: Build rescued haplotypes only for anchors that are not already present
2417
+ # and have at least one uniquely assigned read.
2418
+ rescued_any = False
2419
+ new_haplotypes = []
2420
+ # Index of each rescued haplotype's statistic, so its recorded weight can be corrected
2421
+ # to the post-scaling value the window actually carries.
2422
+ new_hap_stat_idx: list[int] = []
2423
+
2424
+ for anchor_idx, anchor in enumerate(anchor_haps):
2425
+ anchor_already_present = False
2426
+ for existing in existing_consensuses:
2427
+ n_shared = 0
2428
+ n_match = 0
2429
+ for pos in window.snv_pos:
2430
+ if pos in anchor.consensus and pos in existing:
2431
+ n_shared += 1
2432
+ if anchor.consensus[pos] == existing[pos]:
2433
+ n_match += 1
2434
+ if n_shared >= min_shared:
2435
+ distance = 1.0 - (n_match / n_shared) if n_shared > 0 else 1.0
2436
+ if distance <= max_distance:
2437
+ anchor_already_present = True
2438
+ break
2439
+
2440
+ if anchor_already_present:
2441
+ continue
2442
+
2443
+ matching_read_info = anchor_to_reads.get(anchor_idx, [])
2444
+ n_matching_junk = len(matching_read_info)
2445
+
2446
+ if n_matching_junk >= 1:
2447
+ new_consensus = {
2448
+ pos: anchor.consensus[pos]
2449
+ for pos in window.snv_pos
2450
+ if pos in anchor.consensus
2451
+ }
2452
+
2453
+ if new_consensus:
2454
+ rescued_weight = max(
2455
+ n_matching_junk / len(reads),
2456
+ self.config.rescued_min_weight,
2457
+ )
2458
+
2459
+ donor_timepoint = anchor_samples[anchor_idx]
2460
+ new_hap = Haplotype(
2461
+ consensus=new_consensus,
2462
+ weight=rescued_weight,
2463
+ supporting_reads=n_matching_junk,
2464
+ confidence=0.8,
2465
+ track_id=None,
2466
+ rescued_from=donor_timepoint,
2467
+ )
2468
+ new_haplotypes.append(new_hap)
2469
+
2470
+ new_hap_stat_idx.append(len(self.rescue_statistics))
2471
+ self.rescue_statistics.append(
2472
+ RescueStatistic(
2473
+ sample=current_sample,
2474
+ rescued_timepoint=current_sample,
2475
+ contig=window.contig,
2476
+ window_start=window.start,
2477
+ track_id=f"rescued_from_{donor_timepoint}",
2478
+ was_rescued=True,
2479
+ original_weight=0.0,
2480
+ rescued_weight=rescued_weight,
2481
+ donor_timepoint=donor_timepoint,
2482
+ anchor_distance=0.0,
2483
+ n_shared_with_anchor=len(new_consensus),
2484
+ n_mismatched_with_anchor=0,
2485
+ reason=f"rescued_from_junk({n_matching_junk}_reads)",
2486
+ )
2487
+ )
2488
+ rescued_any = True
2489
+
2490
+ logging.debug(
2491
+ f" Rescued haplotype from {donor_timepoint}: "
2492
+ f"{n_matching_junk} junk reads, weight={rescued_weight:.3f}"
2493
+ )
2494
+
2495
+ if not rescued_any:
2496
+ self.rescue_statistics.append(
2497
+ RescueStatistic(
2498
+ sample=current_sample,
2499
+ rescued_timepoint=current_sample,
2500
+ contig=window.contig,
2501
+ window_start=window.start,
2502
+ track_id="window",
2503
+ was_rescued=False,
2504
+ original_weight=junk_weight,
2505
+ rescued_weight=junk_weight,
2506
+ donor_timepoint="",
2507
+ anchor_distance=-1.0,
2508
+ n_shared_with_anchor=0,
2509
+ n_mismatched_with_anchor=0,
2510
+ reason="no_anchor_matches_junk",
2511
+ )
2512
+ )
2513
+ return window_result
2514
+
2515
+ # Add rescued haplotypes and rebuild gamma/pi
2516
+ haplotypes.extend(new_haplotypes)
2517
+ n_haps_new = len(haplotypes)
2518
+ k_eff_new = n_haps_new + 1
2519
+
2520
+ # Redistribute weight: take from junk only, never more than available, so original
2521
+ # haplotypes are not zeroed when total_rescued_weight would exceed old junk weight.
2522
+ old_junk_weight = pi[junk_idx]
2523
+ available_from_junk = max(0.0, old_junk_weight - _MIN_JUNK_WEIGHT)
2524
+
2525
+ total_rescued_weight = sum(h.weight for h in new_haplotypes)
2526
+ if total_rescued_weight > available_from_junk and total_rescued_weight > 0:
2527
+ # Scale down rescued weights so they sum to available_from_junk (preserve ratios).
2528
+ scale_rescued = available_from_junk / total_rescued_weight
2529
+ for h in new_haplotypes:
2530
+ h.weight *= scale_rescued
2531
+ total_rescued_weight = available_from_junk
2532
+ # Report what the haplotype ends up with, not what it asked for.
2533
+ for h, stat_idx in zip(new_haplotypes, new_hap_stat_idx):
2534
+ self.rescue_statistics[stat_idx].rescued_weight = h.weight
2535
+
2536
+ new_junk_weight = max(_MIN_JUNK_WEIGHT, old_junk_weight - total_rescued_weight)
2537
+
2538
+ # Build new pi: original haplotypes scaled to fill (1 - total_rescued - new_junk).
2539
+ pi_new = np.zeros(k_eff_new)
2540
+ non_junk_before = 1.0 - old_junk_weight
2541
+ non_junk_after = 1.0 - total_rescued_weight - new_junk_weight
2542
+ scale = (non_junk_after / non_junk_before) if non_junk_before > 0 else 0.0
2543
+ scale = max(0.0, scale) # avoid negative if floating point
2544
+ for k in range(n_haps):
2545
+ pi_new[k] = pi[k] * scale
2546
+ for k, new_hap in enumerate(new_haplotypes):
2547
+ pi_new[n_haps + k] = new_hap.weight
2548
+ pi_new[-1] = new_junk_weight
2549
+ pi_new = pi_new / pi_new.sum()
2550
+
2551
+ # Update haplotype weights
2552
+ for k, hap in enumerate(haplotypes):
2553
+ hap.weight = pi_new[k]
2554
+
2555
+ # Recompute gamma with new haplotypes
2556
+ gamma_new = self._recompute_gamma(window, haplotypes, pi_new)
2557
+
2558
+ # Recompute assignments
2559
+ post = PostProcessor(self.config)
2560
+ assignments = post.assign_reads(reads, gamma_new)
2561
+
2562
+ for k, hap in enumerate(haplotypes):
2563
+ hap.supporting_reads = int(
2564
+ (gamma_new[:, k] >= self.config.assign_confidence_threshold).sum()
2565
+ )
2566
+
2567
+ n_reads_examined, reads_within_mismatch_per_hap = _compute_read_mismatch_counts(
2568
+ window, haplotypes, self.config.identity_distance
2569
+ )
2570
+
2571
+ return WindowResult(
2572
+ window=window,
2573
+ haplotypes=haplotypes,
2574
+ gamma=gamma_new,
2575
+ pi=pi_new,
2576
+ log_likelihood=window_result.log_likelihood,
2577
+ assignments=assignments,
2578
+ converged=window_result.converged,
2579
+ iterations=window_result.iterations,
2580
+ n_reads_examined=n_reads_examined,
2581
+ reads_within_mismatch_per_hap=reads_within_mismatch_per_hap,
2582
+ )
2583
+
2584
+ def _recompute_gamma(
2585
+ self, window: Window, haplotypes: list[Haplotype], pi: np.ndarray
2586
+ ) -> np.ndarray:
2587
+ """Recompute gamma with fixed pi (E-step only)."""
2588
+ reads = window.reads
2589
+ n_reads = len(reads)
2590
+ n_haps = len(haplotypes)
2591
+ k_eff = n_haps + 1
2592
+ junk_idx = n_haps
2593
+
2594
+ gamma = np.zeros((n_reads, k_eff))
2595
+
2596
+ # Scored through the same two helpers the EM uses. A rescued haplotype takes the DONOR's
2597
+ # footprint, so this is exactly where a footprint-asymmetric likelihood would do the most
2598
+ # damage - the rescued component is guaranteed a different site set from the resident ones.
2599
+ snv_set = set(window.snv_pos)
2600
+ p_div = self.config.junk_divergence_rate
2601
+ default_q = self.config.default_base_quality
2602
+
2603
+ for i, read in enumerate(reads):
2604
+ logp_k = np.full(k_eff, -np.inf)
2605
+ support = _read_support(read, snv_set)
2606
+
2607
+ for k in range(n_haps):
2608
+ log_prob = _log_prob_read_hap(
2609
+ read, haplotypes[k].consensus, support, default_q
2610
+ )
2611
+ if log_prob is not None:
2612
+ logp_k[k] = np.log(pi[k] + 1e-12) + log_prob
2613
+
2614
+ logp_k[junk_idx] = np.log(pi[junk_idx] + 1e-12) + _log_prob_read_junk(
2615
+ read, support, window.ref_alleles, p_div, default_q
2616
+ )
2617
+
2618
+ log_sum = logsumexp(logp_k)
2619
+ if np.isneginf(log_sum):
2620
+ gamma[i, junk_idx] = 1.0
2621
+ else:
2622
+ gamma[i, :] = np.exp(logp_k - log_sum)
2623
+
2624
+ return gamma
2625
+
2626
+ def rescue_low_abundance(
2627
+ self,
2628
+ results_by_timepoint: dict[str, list[WindowResult]],
2629
+ only_sample: str | None = None,
2630
+ ) -> dict[str, list[WindowResult]]:
2631
+ """Rescue low-abundance haplotypes across timepoints.
2632
+
2633
+ ``only_sample`` restricts rescue to one sample; other samples still feed the anchor
2634
+ panel, which needs only their ``.haplotypes``, so their reads/gamma may be offloaded.
2635
+ Calling once per sample in iteration order equals the all-samples call (rescue mutates
2636
+ weights in place either way).
2637
+ """
2638
+ if len(results_by_timepoint) < 2:
2639
+ return results_by_timepoint
2640
+
2641
+ # Group WindowResults by genomic window so we can compare across timepoints.
2642
+ windows_by_position: dict[tuple, dict[str, WindowResult]] = defaultdict(dict)
2643
+
2644
+ for sample_id, window_results in results_by_timepoint.items():
2645
+ for wr in window_results:
2646
+ key = (wr.window.contig, wr.window.start, wr.window.end)
2647
+ windows_by_position[key][sample_id] = wr
2648
+
2649
+ # Diagnostic summary: how many anchors and junk reads exist overall.
2650
+ n_windows_with_multiple_timepoints = 0
2651
+ total_junk_reads = 0
2652
+ total_reads = 0
2653
+ n_anchors = 0
2654
+
2655
+ for _window_key, sample_results in windows_by_position.items():
2656
+ if len(sample_results) >= 2:
2657
+ n_windows_with_multiple_timepoints += 1
2658
+ for _sample_id, wr in sample_results.items():
2659
+ # Works whether or not gamma is resident (offloaded samples carry the
2660
+ # scalar summary instead).
2661
+ n_reads, junk_reads = wr.junk_read_counts()
2662
+ total_reads += n_reads
2663
+ total_junk_reads += junk_reads
2664
+ n_anchors += sum(1 for h in wr.haplotypes if h.weight >= self.config.min_weight_for_anchor)
2665
+
2666
+ junk_pct = 100 * total_junk_reads / total_reads if total_reads > 0 else 0
2667
+ logging.info(
2668
+ f" Rescue diagnostics: {len(windows_by_position)} window positions, "
2669
+ f"{n_windows_with_multiple_timepoints} shared across >=2 timepoints, "
2670
+ f"{n_anchors} anchors, {total_junk_reads}/{total_reads} junk reads ({junk_pct:.1f}%)"
2671
+ )
2672
+
2673
+ # Rescue each window position independently.
2674
+ rescued_results: dict[str, list[WindowResult]] = defaultdict(list)
2675
+
2676
+ for _window_key, sample_results in windows_by_position.items():
2677
+ for sample_id, wr in sample_results.items():
2678
+ if only_sample is not None and sample_id != only_sample:
2679
+ continue
2680
+ # Build anchor panel excluding the current sample to avoid self-rescue.
2681
+ anchor_haps, anchor_samples = self.build_anchor_panel_for_key(
2682
+ sample_results, exclude_sample=sample_id
2683
+ )
2684
+ rescued_wr = self.rescue_window_result(
2685
+ wr, anchor_haps, anchor_samples, sample_results, sample_id
2686
+ )
2687
+ rescued_results[sample_id].append(rescued_wr)
2688
+
2689
+ return dict(rescued_results)
2690
+
2691
+ def process_window(
2692
+ window: Window, config: HaplotyperConfig = DEFAULT_CONFIG, n_timepoints_seen: int = 1
2693
+ ) -> WindowResult:
2694
+ """Process a single window through the full pipeline."""
2695
+ post = PostProcessor(config)
2696
+
2697
+ # 0) Resolving-depth floor. Windows are CREATED at min_reads_for_rescue, but de-novo
2698
+ # phasing needs more reads to separate haplotypes; below the floor emit a junk-only
2699
+ # result so the trajectory carries a gap, not a manufactured abundance of 1.0.
2700
+ if len(window.reads) < config.min_reads_per_window:
2701
+ n_reads = len(window.reads)
2702
+ gamma = np.ones((n_reads, 1))
2703
+ pi = np.array([1.0])
2704
+ n_reads_examined, reads_within_mismatch_per_hap = _compute_read_mismatch_counts(
2705
+ window, [], config.identity_distance
2706
+ )
2707
+ return WindowResult(
2708
+ window=window,
2709
+ haplotypes=[],
2710
+ gamma=gamma,
2711
+ pi=pi,
2712
+ log_likelihood=-np.inf,
2713
+ assignments=post.assign_reads(window.reads, gamma),
2714
+ converged=True,
2715
+ iterations=0,
2716
+ n_reads_examined=n_reads_examined,
2717
+ reads_within_mismatch_per_hap=reads_within_mismatch_per_hap,
2718
+ )
2719
+
2720
+ # 1) Initialize haplotypes via read clustering on the overlap graph.
2721
+ initializer = GraphInitializer(config)
2722
+ initial_haps, cluster_sizes = initializer.get_initial_haplotypes(window)
2723
+
2724
+ if not initial_haps:
2725
+ # No clustering signal -> junk-only result (gamma = ones).
2726
+ n_reads = len(window.reads)
2727
+ gamma = np.ones((n_reads, 1))
2728
+ pi = np.array([1.0])
2729
+ assignments = post.assign_reads(window.reads, gamma)
2730
+
2731
+ n_reads_examined, reads_within_mismatch_per_hap = _compute_read_mismatch_counts(
2732
+ window, [], config.identity_distance
2733
+ )
2734
+ return WindowResult(
2735
+ window=window,
2736
+ haplotypes=[],
2737
+ gamma=gamma,
2738
+ pi=pi,
2739
+ log_likelihood=-np.inf,
2740
+ assignments=assignments,
2741
+ converged=True,
2742
+ iterations=0,
2743
+ n_reads_examined=n_reads_examined,
2744
+ reads_within_mismatch_per_hap=reads_within_mismatch_per_hap,
2745
+ )
2746
+
2747
+ # 2) EM haplotyping: refine haplotype consensus and weights.
2748
+ em = EMHaplotyper(window, initial_haps, cluster_sizes, config)
2749
+ haplotypes, gamma, pi, log_lik, converged, iterations = em.run()
2750
+
2751
+ if not haplotypes:
2752
+ # EM pruned all haplotypes; keep the (junk) assignments.
2753
+ assignments = post.assign_reads(window.reads, gamma)
2754
+ n_reads_examined, reads_within_mismatch_per_hap = _compute_read_mismatch_counts(
2755
+ window, [], config.identity_distance
2756
+ )
2757
+ return WindowResult(
2758
+ window=window,
2759
+ haplotypes=[],
2760
+ gamma=gamma,
2761
+ pi=pi,
2762
+ log_likelihood=log_lik,
2763
+ assignments=assignments,
2764
+ converged=converged,
2765
+ iterations=iterations,
2766
+ n_reads_examined=n_reads_examined,
2767
+ reads_within_mismatch_per_hap=reads_within_mismatch_per_hap,
2768
+ )
2769
+
2770
+ # 3) Post-processing: merge near-duplicate haplotypes with 1-SNP guard.
2771
+ n_after_em = len(haplotypes)
2772
+ merged_haps, final_gamma, final_pi = post.merge_similar_haplotypes(
2773
+ haplotypes, gamma, pi, window, n_timepoints_seen
2774
+ )
2775
+
2776
+ # STAGE COUNTS. K is set by Louvain, EM can only PRUNE it, this merge can only SHRINK it
2777
+ # further. Logging all three separates "Louvain found less structure" from "the merge
2778
+ # collapsed it", which the post-hoc tables cannot distinguish.
2779
+ logging.debug(
2780
+ "stage_counts\t%s\t%d\t%d\t%d\t%d\t%d",
2781
+ window.contig, window.start, len(window.reads),
2782
+ len(initial_haps), n_after_em, len(merged_haps),
2783
+ )
2784
+
2785
+ # 3b) No invariant-site pruning here: construction keeps every position, pruning is a
2786
+ # comparison-time concern. variable_marker_positions() computes the marker set at the
2787
+ # widest scope available and the linking code filters against it, so nothing is
2788
+ # destroyed before the scope is known.
2789
+
2790
+ assignments = post.assign_reads(window.reads, final_gamma)
2791
+
2792
+ n_reads_examined, reads_within_mismatch_per_hap = _compute_read_mismatch_counts(
2793
+ window, merged_haps, config.identity_distance
2794
+ )
2795
+
2796
+ result = WindowResult(
2797
+ window=window,
2798
+ haplotypes=merged_haps,
2799
+ gamma=final_gamma,
2800
+ pi=final_pi,
2801
+ log_likelihood=log_lik,
2802
+ assignments=assignments,
2803
+ converged=converged,
2804
+ iterations=iterations,
2805
+ n_reads_examined=n_reads_examined,
2806
+ reads_within_mismatch_per_hap=reads_within_mismatch_per_hap,
2807
+ )
2808
+
2809
+ return result
2810
+
2811
+
2812
+
2813
+ # =============================================================================
2814
+ # SPLIT MOLECULES: re-assembly and the BREAK marker
2815
+ # =============================================================================
2816
+
2817
+ # Allele values at a breakpoint site: a read crossing with a continuous alignment carries
2818
+ # CONTINUOUS; one split there carries BREAK_PREFIX + the resume coordinate, so different
2819
+ # events at one left coordinate stay distinct alleles. Same shape as INS<len>/DEL<len>.
2820
+ CONTINUOUS = "CONT"
2821
+ BREAK_PREFIX = "BRK"
2822
+
2823
+
2824
+ def _merge_split_reads(
2825
+ reads: list[Read],
2826
+ config: HaplotyperConfig = DEFAULT_CONFIG,
2827
+ snv_set: set[int] | None = None,
2828
+ ) -> tuple[list[Read], set[int]]:
2829
+ """Re-assemble split alignments into one Read each, and report the breakpoints.
2830
+
2831
+ A molecule the aligner emits as a primary plus supplementary alignments (a divergent
2832
+ cassette, insertion, rearrangement) is ONE molecule, so its segments merge back into a
2833
+ single Read. Two consequences:
2834
+
2835
+ 1. The merged read carries alleles from both sides of the break, so the EM assigns the
2836
+ whole molecule to one haplotype instead of several fragments.
2837
+ 2. The break becomes a positive identity marker (``BRK<resume_pos>`` vs ``CONT``), a
2838
+ discriminating allele like any other, which is why SVs are not excluded from identity.
2839
+
2840
+ The breakpoint is anchored at the LAST aligned position of the preceding segment, or the
2841
+ nearest earlier position that is not a called variant site (pass *snv_set* to enable the
2842
+ check; the anchor is written unconditionally and would otherwise clobber a real allele).
2843
+ Returns the merged reads and the set of breakpoint positions. History: docs/design/core.md.
2844
+ """
2845
+ by_molecule: dict[str, list[Read]] = defaultdict(list)
2846
+ for r in reads:
2847
+ by_molecule[r.id].append(r)
2848
+
2849
+ called = snv_set if snv_set is not None else frozenset()
2850
+ merged: list[Read] = []
2851
+ breaks: set[int] = set()
2852
+ n_anchors_dropped = 0
2853
+ qual = config.default_base_quality
2854
+
2855
+ for segs in by_molecule.values():
2856
+ if len(segs) == 1:
2857
+ merged.append(segs[0])
2858
+ continue
2859
+ segs.sort(key=lambda r: (r.ref_start, r.ref_end))
2860
+ # Captured before `whole` (which IS segs[0]) has its own span widened below.
2861
+ spans = [(s.ref_start, s.ref_end) for s in segs]
2862
+ whole = segs[0]
2863
+ for seg in segs[1:]:
2864
+ whole.alleles.update(seg.alleles)
2865
+ whole.quals.update(seg.quals)
2866
+ # Set the break markers AFTER the union so they cannot be overwritten by a
2867
+ # later segment that happens to have a call at the same position.
2868
+ for prev, nxt in zip(segs, segs[1:]): # noqa: B905
2869
+ if nxt.ref_start <= prev.ref_end:
2870
+ continue # overlapping segments: no gap, nothing to mark
2871
+ # Walk back inside the preceding segment to an anchor no variant was called at.
2872
+ # Anywhere in that segment carries the same meaning, so shifting keeps the marker.
2873
+ anchor = prev.ref_end - 1
2874
+ while anchor in called and anchor > prev.ref_start:
2875
+ anchor -= 1
2876
+ if anchor in called:
2877
+ n_anchors_dropped += 1
2878
+ continue
2879
+ whole.alleles[anchor] = f"{BREAK_PREFIX}{nxt.ref_start}"
2880
+ whole.quals[anchor] = qual
2881
+ breaks.add(anchor)
2882
+ whole.ref_start = min(s for s, _ in spans)
2883
+ whole.ref_end = max(e for _, e in spans)
2884
+ # The per-segment spans, which the outer span no longer describes.
2885
+ whole.segments = spans
2886
+ merged.append(whole)
2887
+
2888
+ # A read spanning a breakpoint with an unbroken alignment is evidence AGAINST the event,
2889
+ # not absence of evidence; without this only the broken strain carries a call and the
2890
+ # marker cannot discriminate. Read.covers, not the outer span, so a molecule's own
2891
+ # unaligned gap is not falsely marked "no break here". Detail: docs/design/core.md.
2892
+ for pos in breaks:
2893
+ for r in merged:
2894
+ if pos in r.alleles or not r.covers(pos):
2895
+ continue
2896
+ r.alleles[pos] = CONTINUOUS
2897
+ r.quals[pos] = qual
2898
+
2899
+ if n_anchors_dropped:
2900
+ logging.debug(
2901
+ f" _merge_split_reads: {n_anchors_dropped} breakpoint anchors dropped "
2902
+ f"(no free position in the preceding segment)"
2903
+ )
2904
+
2905
+ return merged, breaks
2906
+
2907
+
2908
+ # =============================================================================
2909
+ # IDENTITY: marker set + the shared gate stack
2910
+ # =============================================================================
2911
+
2912
+
2913
+ def supported_marker_positions(
2914
+ observations,
2915
+ site_type: dict[int, str] | None = None,
2916
+ config: HaplotyperConfig = DEFAULT_CONFIG,
2917
+ ) -> frozenset[int]:
2918
+ """Identity markers that real, replicated reads support.
2919
+
2920
+ ``observations`` yields ``(sample, consensus, reads)`` - one per window-haplotype. A
2921
+ position is a candidate when it holds >1 allele anywhere. An allele is kept if it reaches
2922
+ ``marker_min_reads`` reads OR ``marker_min_frac`` of a sample's reads at that position, in
2923
+ ``marker_min_samples`` samples - counted per allele, so the two need not co-occur in one
2924
+ sample (a swept position is fixed within each sample). A position survives when >= 2 alleles
2925
+ do. Returned as a frozenset (consumers only test membership or intersect).
2926
+ """
2927
+ # position -> sample -> allele -> reads
2928
+ seen: dict[int, dict[str, dict[str, float]]] = defaultdict(
2929
+ lambda: defaultdict(lambda: defaultdict(float)))
2930
+ for sample, consensus, reads in observations:
2931
+ for pos, base in consensus.items():
2932
+ seen[pos][sample][base] += reads
2933
+
2934
+ keep: set[int] = set()
2935
+ for pos, per_sample in seen.items():
2936
+ qualifying: Counter = Counter()
2937
+ for alleles in per_sample.values():
2938
+ total = sum(alleles.values())
2939
+ if not total:
2940
+ continue
2941
+ for base, n in alleles.items():
2942
+ # Reads OR frequency, not both: requiring both denied a 2-5% strain any
2943
+ # discriminating marker. Read support is independent evidence an allele is real.
2944
+ if n >= config.marker_min_reads or n / total >= config.marker_min_frac:
2945
+ qualifying[base] += 1
2946
+ if sum(1 for c in qualifying.values() if c >= config.marker_min_samples) >= 2:
2947
+ keep.add(pos)
2948
+
2949
+ if config.exclude_sv_from_identity and site_type:
2950
+ keep -= {pos for pos in keep if site_type.get(pos) == "sv"}
2951
+ return frozenset(keep)
2952
+
2953
+
2954
+ def variable_marker_positions(
2955
+ consensuses: Iterable[dict[int, str]],
2956
+ site_type: dict[int, str] | None = None,
2957
+ config: HaplotyperConfig = DEFAULT_CONFIG,
2958
+ ) -> set[int]:
2959
+ """Positions usable as identity markers, computed over *consensuses*: a position is a
2960
+ marker only if >= 2 distinct alleles appear across the whole collection (a position where
2961
+ every haplotype agrees carries no identity information yet inflates n_shared).
2962
+
2963
+ Call at the widest scope available: window linking -> every haplotype in that sample/contig;
2964
+ the cross-sample merge -> every haplotype in every sample, that contig.
2965
+
2966
+ SVs are identity markers (exclude_sv_from_identity defaults False): an invertible element's
2967
+ two orientations are two entities trading frequency, the flip trajectory. Flag measures only.
2968
+ """
2969
+ seen: dict[int, set[str]] = defaultdict(set)
2970
+ for consensus in consensuses:
2971
+ for pos, base in consensus.items():
2972
+ seen[pos].add(base)
2973
+
2974
+ markers = {pos for pos, alleles in seen.items() if len(alleles) > 1}
2975
+ if config.exclude_sv_from_identity and site_type:
2976
+ markers -= {pos for pos in markers if site_type.get(pos) == "sv"}
2977
+ return markers
2978
+
2979
+
2980
+ def consensus_footprint(
2981
+ consensus: dict[int, str], region: tuple[int, int] | None = None
2982
+ ) -> tuple[int, int]:
2983
+ """First and last position a consensus covers, optionally clipped to *region*.
2984
+
2985
+ Returned as (lo, hi) with hi < lo when nothing falls inside the region, so callers test
2986
+ emptiness without a second pass. Avoids materialising a set (called once per haplotype per batch).
2987
+ """
2988
+ if region is None:
2989
+ return (min(consensus), max(consensus)) if consensus else (1, 0)
2990
+ lo_r, hi_r = region
2991
+ lo = hi = None
2992
+ for p in consensus:
2993
+ if lo_r <= p <= hi_r:
2994
+ if lo is None or p < lo:
2995
+ lo = p
2996
+ if hi is None or p > hi:
2997
+ hi = p
2998
+ return (lo, hi) if lo is not None else (1, 0)
2999
+
3000
+
3001
+ @dataclass
3002
+ class GateResult:
3003
+ """Outcome of one identity comparison. ``reason`` tells a measurement hole from a real
3004
+ genotypic wall:
3005
+
3006
+ ``"linked"`` passed every gate
3007
+ ``"failed_no_evidence"`` too few shared markers, or too little physical overlap - a
3008
+ DROPOUT. Nothing was shown to differ.
3009
+ ``"failed_mismatch"`` enough shared markers, but the alleles genuinely disagree - a
3010
+ candidate recombination breakpoint.
3011
+ """
3012
+
3013
+ passed: bool
3014
+ reason: str
3015
+ rate: float
3016
+ n_shared: int
3017
+ n_diff: int
3018
+
3019
+
3020
+ def compare_consensus(
3021
+ a: dict[int, str],
3022
+ b: dict[int, str],
3023
+ markers: set[int],
3024
+ config: HaplotyperConfig = DEFAULT_CONFIG,
3025
+ min_shared: int | None = None,
3026
+ region: tuple[int, int] | None = None,
3027
+ min_cospan_frac: float | None = None,
3028
+ max_rate: float | None = None,
3029
+ a_span: tuple[int, int] | None = None,
3030
+ b_span: tuple[int, int] | None = None,
3031
+ ) -> GateResult:
3032
+ """Apply the identity gate stack to two consensus dicts.
3033
+
3034
+ Gates, in order: footprints overlap by >= ``min_entity_overlap_bp`` (and >= ``min_cospan_frac``
3035
+ of ``region``); shared markers >= ``min_shared``; mismatch rate over shared markers <=
3036
+ ``identity_distance``. The verdict rests only on discriminating markers; the overlap gate asks
3037
+ how much sequence both covered, not where the markers fall.
3038
+
3039
+ ``a_span``/``b_span`` are precomputed footprints; pass them when comparing many pairs.
3040
+ """
3041
+ if min_shared is None:
3042
+ min_shared = config.min_shared_markers
3043
+ if min_cospan_frac is None:
3044
+ min_cospan_frac = config.min_cosupported_span_frac
3045
+ if max_rate is None:
3046
+ max_rate = config.identity_distance
3047
+
3048
+ def _restrict(positions):
3049
+ if region is None:
3050
+ # already a set from the & below; copying it was pure overhead
3051
+ return positions if isinstance(positions, set) else set(positions)
3052
+ lo, hi = region
3053
+ return {p for p in positions if lo <= p <= hi}
3054
+
3055
+ shared = _restrict(a.keys() & b.keys() & markers)
3056
+ n_shared = len(shared)
3057
+
3058
+ # How much sequence both haplotypes actually cover: their footprints' intersection,
3059
+ # independent of where the markers sit (the marker-subset span would penalise loci where
3060
+ # variation clusters, which is backwards). Hoist the footprint out of a pairwise loop.
3061
+ lo_a, hi_a = a_span if a_span is not None else consensus_footprint(a, region)
3062
+ lo_b, hi_b = b_span if b_span is not None else consensus_footprint(b, region)
3063
+ overlap = (min(hi_a, hi_b) - max(lo_a, lo_b)) if (hi_a >= lo_a and hi_b >= lo_b) else 0
3064
+ if overlap < config.min_entity_overlap_bp:
3065
+ return GateResult(False, "failed_no_evidence", 1.0, n_shared, 0)
3066
+ if region is not None:
3067
+ lo, hi = region
3068
+ if hi > lo and overlap < min_cospan_frac * (hi - lo):
3069
+ return GateResult(False, "failed_no_evidence", 1.0, n_shared, 0)
3070
+
3071
+ # ...and was any of it informative? Separate question, separate gate.
3072
+ if n_shared < min_shared:
3073
+ return GateResult(False, "failed_no_evidence", 1.0, n_shared, 0)
3074
+
3075
+ n_diff = sum(1 for p in shared if a[p] != b[p])
3076
+ rate = n_diff / n_shared
3077
+ if rate > max_rate:
3078
+ return GateResult(False, "failed_mismatch", rate, n_shared, n_diff)
3079
+ return GateResult(True, "linked", rate, n_shared, n_diff)
3080
+
3081
+
3082
+ def link_windows(
3083
+ results: list[WindowResult], config: HaplotyperConfig = DEFAULT_CONFIG
3084
+ ) -> list[WindowResult]:
3085
+ """Link haplotypes across windows into tracks, on consensus and on shared reads.
3086
+
3087
+ Overlapping windows share SNV positions and are linked (same track_id) when their consensus
3088
+ agrees on the shared SNVs and their within-window shares are compatible. With
3089
+ ``link_window_reach`` above 1, NON-overlapping windows within the reach are also linked:
3090
+ they call disjoint positions, so consensus agreement is undefined and the evidence is
3091
+ ``link_min_shared_reads`` shared reads plus reciprocal best match.
3092
+
3093
+ The abundance check is an ELIMINATOR, never an indicator: two windows in one sample are the
3094
+ same timepoint, so a genuine share disagreement means they are not one entity. Agreement
3095
+ earns no credit and cannot rescue a failed identity gate. Run on RAW COUNTS. It applies to
3096
+ both paths and is the only veto on the read path.
3097
+
3098
+ Modifies haplotypes in-place, setting their track_id. Reach horizon / quantisation detail:
3099
+ docs/design/core.md.
3100
+ """
3101
+ # Deferred: strainphase.coherence imports HaplotyperConfig from this module, so a
3102
+ # top-level import here would be circular. The cost is one lookup per call.
3103
+ from strainphase.coherence import abundance_coherent
3104
+
3105
+ # This pass re-derives every mismatch it records, so it owns the list rather than
3106
+ # appending: the longitudinal driver calls link_windows again after rescue, and an
3107
+ # append-only list would duplicate an unrescued window's first-pass rows.
3108
+ for wr in results:
3109
+ wr.link_mismatches.clear()
3110
+
3111
+ if len(results) < 2:
3112
+ # Single window: each haplotype is its own track.
3113
+ track_counter = 0
3114
+ for wr in results:
3115
+ for hap in wr.haplotypes:
3116
+ track_counter += 1
3117
+ hap.track_id = f"T{track_counter:04d}"
3118
+ return results
3119
+
3120
+ # Sort by genomic coordinate so adjacent windows are compared in order.
3121
+ sorted_results = sorted(results, key=lambda wr: wr.window.start)
3122
+
3123
+ # Marker set at the widest scope here: every haplotype in this sample/contig. Positions
3124
+ # where all haplotypes agree, and SV sites, are excluded. Construction no longer prunes.
3125
+ site_type_all: dict[int, str] = {}
3126
+ for wr in sorted_results:
3127
+ site_type_all.update(wr.window.site_type)
3128
+ markers = variable_marker_positions(
3129
+ (hap.consensus for wr in sorted_results for hap in wr.haplotypes),
3130
+ site_type_all,
3131
+ config,
3132
+ )
3133
+
3134
+ # Build graph: nodes = (window_idx, hap_idx); edges = linkable haplotype pairs.
3135
+ graph = nx.Graph() # Undirected for connected components
3136
+
3137
+ for i, wr in enumerate(sorted_results):
3138
+ for j in range(len(wr.haplotypes)):
3139
+ graph.add_node((i, j))
3140
+
3141
+ debug_records = 0
3142
+
3143
+ def record_debug(wr: WindowResult, entry: dict):
3144
+ nonlocal debug_records
3145
+ if not config.linking_debug:
3146
+ return
3147
+ if debug_records >= config.linking_debug_max_records:
3148
+ return
3149
+ wr.linking_debug.append(entry)
3150
+ debug_records += 1
3151
+
3152
+ # Connect haplotypes in overlapping windows.
3153
+ for i in range(len(sorted_results) - 1):
3154
+ curr_wr = sorted_results[i]
3155
+ curr_snvs = set(curr_wr.window.snv_pos)
3156
+
3157
+ # Check next few windows. Overlapping ones are compared on consensus; beyond the
3158
+ # overlap, `link_window_reach` decides how far the READ path may still reach.
3159
+ horizon = max(2, config.link_window_reach)
3160
+ for k in range(i + 1, min(i + 1 + horizon, len(sorted_results))):
3161
+ next_wr = sorted_results[k]
3162
+
3163
+ overlapping = next_wr.window.start < curr_wr.window.end
3164
+ if not overlapping:
3165
+ # Reads can bridge a disjoint pair only within the reach (reach 1 admits none);
3166
+ # k only increases, so nothing beyond this one can link either.
3167
+ if config.link_window_reach <= 1 or (k - i) > config.link_window_reach:
3168
+ break
3169
+
3170
+ if overlapping:
3171
+ next_snvs = set(next_wr.window.snv_pos)
3172
+ shared_snvs = list(curr_snvs & next_snvs)
3173
+
3174
+ # Window-level overlap only; the per-haplotype check is below.
3175
+ if len(shared_snvs) < config.min_shared_snvs_for_link:
3176
+ continue
3177
+
3178
+ # The region shared by the two windows; the co-supported span gate is
3179
+ # measured as a fraction of it.
3180
+ region = (
3181
+ max(curr_wr.window.start, next_wr.window.start),
3182
+ min(curr_wr.window.end, next_wr.window.end) - 1,
3183
+ )
3184
+ else:
3185
+ # Disjoint windows: no shared region or position, so the pair loop below
3186
+ # takes the read-only path.
3187
+ region = None
3188
+
3189
+ # Evaluate candidate pairings before linking. Full gate stack: shared markers,
3190
+ # co-supported span >= 25% of the region, rate <= identity_distance.
3191
+ candidates: list[tuple[int, int, float, int]] = []
3192
+
3193
+ # Non-junk read count per window - the denominator the abundance eliminator
3194
+ # tests against. Same definition build_window_tables uses for `total_reads`.
3195
+ def _nonjunk(wr) -> int:
3196
+ if wr.gamma is None or wr.gamma.size == 0:
3197
+ return 0
3198
+ junk = wr.gamma.shape[1] - 1
3199
+ return int(wr.gamma.shape[0] - (wr.gamma[:, junk] >= 0.5).sum())
3200
+
3201
+ n_curr, n_next = _nonjunk(curr_wr), _nonjunk(next_wr)
3202
+
3203
+ # Reads backing each haplotype, for the shared-read ranking. best_hap is the argmax
3204
+ # regardless of confidence (near-identical strains leave most reads below threshold).
3205
+ def _hap_reads(wr) -> dict[int, set]:
3206
+ out: dict[int, set] = {}
3207
+ for a in getattr(wr, "assignments", None) or []:
3208
+ k = a.get("best_hap", a.get("hap_id"))
3209
+ if k is None:
3210
+ continue
3211
+ out.setdefault(int(k), set()).add(a.get("read_id"))
3212
+ return out
3213
+
3214
+ reads_i, reads_j = _hap_reads(curr_wr), _hap_reads(next_wr)
3215
+ # union of reads placed in each window, for the coverage-invariant link gate:
3216
+ # a hap's "continuing reads" = its reads that also appear in the other window.
3217
+ reads_i_all = set().union(*reads_i.values()) if reads_i else _EMPTY_READS
3218
+ reads_j_all = set().union(*reads_j.values()) if reads_j else _EMPTY_READS
3219
+
3220
+ # per-haplotype footprints, clipped to the shared region, hoisted out of the
3221
+ # pairwise loop (see consensus_footprint)
3222
+ span_i = (
3223
+ [consensus_footprint(h.consensus, region) for h in curr_wr.haplotypes]
3224
+ if overlapping else []
3225
+ )
3226
+ span_j = (
3227
+ [consensus_footprint(h.consensus, region) for h in next_wr.haplotypes]
3228
+ if overlapping else []
3229
+ )
3230
+ for hi, hap_i in enumerate(curr_wr.haplotypes):
3231
+ for hj, hap_j in enumerate(next_wr.haplotypes):
3232
+ # Shared reads are needed by BOTH paths (ranking score on the consensus
3233
+ # path, sole evidence on the read path), so hoist the intersection here.
3234
+ shared_reads = len(
3235
+ reads_i.get(hi, _EMPTY_READS) & reads_j.get(hj, _EMPTY_READS)
3236
+ )
3237
+ if not overlapping:
3238
+ # NON-OVERLAPPING PAIR: disjoint positions, so consensus agreement is
3239
+ # undefined. A read carried by a haplotype in both windows is the only
3240
+ # evidence they are one lineage, so it must stand on its own count.
3241
+ need = config.link_min_shared_reads
3242
+ if config.link_shared_read_frac > 0.0:
3243
+ # Also require a fraction of each hap's OWN continuing reads, so the
3244
+ # bar scales with depth for abundant strains, floor for rare ones.
3245
+ cont_i = len(reads_i.get(hi, _EMPTY_READS) & reads_j_all)
3246
+ cont_j = len(reads_j.get(hj, _EMPTY_READS) & reads_i_all)
3247
+ need = max(need, int(np.ceil(config.link_shared_read_frac * min(cont_i, cont_j))))
3248
+ if shared_reads < need:
3249
+ continue
3250
+ gate = None
3251
+ score = -float(shared_reads)
3252
+ n_shared_out = 0
3253
+ else:
3254
+ gate = compare_consensus(
3255
+ hap_i.consensus,
3256
+ hap_j.consensus,
3257
+ markers,
3258
+ config,
3259
+ min_shared=config.min_shared_markers,
3260
+ region=region,
3261
+ max_rate=config.identity_distance,
3262
+ a_span=span_i[hi],
3263
+ b_span=span_j[hj],
3264
+ )
3265
+ if not gate.passed:
3266
+ if gate.reason == "failed_mismatch":
3267
+ curr_wr.link_mismatches.append(
3268
+ {
3269
+ "contig": curr_wr.window.contig,
3270
+ "window_a": curr_wr.window.start,
3271
+ "hap_a_idx": hi,
3272
+ "window_b": next_wr.window.start,
3273
+ "hap_b_idx": hj,
3274
+ "rate": round(gate.rate, 6),
3275
+ "n_shared": gate.n_shared,
3276
+ "n_diff": gate.n_diff,
3277
+ }
3278
+ )
3279
+ continue
3280
+ # Rank by shared reads (lower is better for unique_best): consensus has
3281
+ # already vetoed, and where two candidates are byte-identical shared reads
3282
+ # discriminate. Falls back to the consensus rate when no assignments exist.
3283
+ score = -float(shared_reads) if (reads_i or reads_j) else gate.rate
3284
+ n_shared_out = gate.n_shared
3285
+ # Abundance is an eliminator, never an indicator (see docstring): a genuine
3286
+ # share disagreement in one sample means the pair is not one entity, however
3287
+ # well the alleles match. Agreement never scores. Run on raw counts.
3288
+ if not abundance_coherent(
3289
+ [(hap_i.supporting_reads, n_curr),
3290
+ (hap_j.supporting_reads, n_next)], config
3291
+ ).coherent:
3292
+ record_debug(curr_wr, {
3293
+ "contig": curr_wr.window.contig,
3294
+ "window_start": curr_wr.window.start,
3295
+ "next_window_start": next_wr.window.start,
3296
+ "hap_i": hi, "hap_j": hj,
3297
+ "decision": "refused",
3298
+ "reason": "incompatible_abundance",
3299
+ })
3300
+ # Propagate, don't just trace: recording the refusal lets the
3301
+ # cross-sample merge inherit it instead of re-testing the pair.
3302
+ curr_wr.link_abundance_refusals.append(
3303
+ {
3304
+ "contig": curr_wr.window.contig,
3305
+ "window_a": curr_wr.window.start,
3306
+ "hap_a_idx": hi,
3307
+ "window_b": next_wr.window.start,
3308
+ "hap_b_idx": hj,
3309
+ }
3310
+ )
3311
+ continue
3312
+ candidates.append((hi, hj, score, n_shared_out))
3313
+
3314
+ if not candidates:
3315
+ if config.linking_debug:
3316
+ record_debug(
3317
+ curr_wr,
3318
+ {
3319
+ "contig": curr_wr.window.contig,
3320
+ "window_start": curr_wr.window.start,
3321
+ "window_end": curr_wr.window.end,
3322
+ "next_window_start": next_wr.window.start,
3323
+ "next_window_end": next_wr.window.end,
3324
+ "decision": "no_candidates",
3325
+ "reason": "no_pairs_within_distance_and_shared_snvs",
3326
+ },
3327
+ )
3328
+ continue
3329
+
3330
+ # Track unique best matches for each haplotype on both sides.
3331
+ best_for_i: dict[int, list[tuple[float, int, int]]] = {}
3332
+ best_for_j: dict[int, list[tuple[float, int, int]]] = {}
3333
+ for hi, hj, dist, n_shared in candidates:
3334
+ best_for_i.setdefault(hi, []).append((dist, hj, n_shared))
3335
+ best_for_j.setdefault(hj, []).append((dist, hi, n_shared))
3336
+
3337
+ def unique_best(
3338
+ matches: dict[int, list[tuple[float, int, int]]],
3339
+ ) -> dict[int, tuple[int, float, int]]:
3340
+ unique: dict[int, tuple[int, float, int]] = {}
3341
+ for idx, options in matches.items():
3342
+ options.sort(key=lambda x: x[0])
3343
+ best_dist, best_partner, best_shared = options[0]
3344
+ bests = [opt for opt in options if opt[0] == best_dist]
3345
+ # Skip ambiguous ties (including multiple perfect matches).
3346
+ if len(bests) == 1:
3347
+ unique[idx] = (best_partner, best_dist, best_shared)
3348
+ return unique
3349
+
3350
+ unique_i = unique_best(best_for_i)
3351
+ unique_j = unique_best(best_for_j)
3352
+
3353
+ if config.linking_debug:
3354
+ for hi, options in best_for_i.items():
3355
+ options_sorted = sorted(options, key=lambda x: x[0])
3356
+ best_dist, best_hj, best_shared = options_sorted[0]
3357
+ second_dist = options_sorted[1][0] if len(options_sorted) > 1 else None
3358
+ bests = [opt for opt in options_sorted if opt[0] == best_dist]
3359
+ if len(bests) != 1:
3360
+ record_debug(
3361
+ curr_wr,
3362
+ {
3363
+ "contig": curr_wr.window.contig,
3364
+ "window_start": curr_wr.window.start,
3365
+ "window_end": curr_wr.window.end,
3366
+ "next_window_start": next_wr.window.start,
3367
+ "next_window_end": next_wr.window.end,
3368
+ "hap_i": hi,
3369
+ "best_hap_j": best_hj,
3370
+ "best_dist": round(best_dist, 6),
3371
+ "second_best_dist": round(second_dist, 6) if second_dist is not None else None,
3372
+ "n_shared_best": best_shared,
3373
+ "decision": "skip",
3374
+ "reason": "ambiguous_tie",
3375
+ "tie_count": len(bests),
3376
+ },
3377
+ )
3378
+
3379
+ # Link only if the best match is mutual (unique on both sides).
3380
+ for hi, (hj, _dist, _n_shared) in unique_i.items():
3381
+ if hj in unique_j and unique_j[hj][0] == hi:
3382
+ graph.add_edge((i, hi), (k, hj))
3383
+ if config.linking_debug:
3384
+ record_debug(
3385
+ curr_wr,
3386
+ {
3387
+ "contig": curr_wr.window.contig,
3388
+ "window_start": curr_wr.window.start,
3389
+ "window_end": curr_wr.window.end,
3390
+ "next_window_start": next_wr.window.start,
3391
+ "next_window_end": next_wr.window.end,
3392
+ "hap_i": hi,
3393
+ "hap_j": hj,
3394
+ "decision": "link",
3395
+ "reason": "unique_best_mutual",
3396
+ },
3397
+ )
3398
+ elif config.linking_debug:
3399
+ record_debug(
3400
+ curr_wr,
3401
+ {
3402
+ "contig": curr_wr.window.contig,
3403
+ "window_start": curr_wr.window.start,
3404
+ "window_end": curr_wr.window.end,
3405
+ "next_window_start": next_wr.window.start,
3406
+ "next_window_end": next_wr.window.end,
3407
+ "hap_i": hi,
3408
+ "hap_j": hj,
3409
+ "decision": "skip",
3410
+ "reason": "not_reciprocal_best",
3411
+ },
3412
+ )
3413
+
3414
+ # Connected components correspond to tracks across windows.
3415
+ components = list(nx.connected_components(graph))
3416
+
3417
+ # Assign a track_id to each haplotype in a component.
3418
+ for track_idx, component in enumerate(components):
3419
+ track_id = f"T{track_idx + 1:04d}"
3420
+ for w_idx, h_idx in component:
3421
+ sorted_results[w_idx].haplotypes[h_idx].track_id = track_id
3422
+
3423
+ logging.debug(
3424
+ f"Linked {sum(len(wr.haplotypes) for wr in sorted_results)} haplotypes "
3425
+ f"into {len(components)} tracks"
3426
+ )
3427
+
3428
+ return sorted_results
3429
+
3430
+
3431
+ def process_contig(
3432
+ bam_path: str,
3433
+ vcf_path: str,
3434
+ contig_id: str,
3435
+ contig_length: int,
3436
+ config: HaplotyperConfig = DEFAULT_CONFIG,
3437
+ sample_id: str | None = None,
3438
+ vcf_sample_name: str | None = None,
3439
+ pool: Pool | None = None,
3440
+ sv_sidecar_path: str | None = None,
3441
+ offload_reads: bool = False,
3442
+ ) -> list[WindowResult]:
3443
+ """Process all windows in a contig and link haplotypes across windows.
3444
+
3445
+ If ``sv_sidecar_path`` is given (see :mod:`strainphase.sv_encoding`), structural variants
3446
+ are merged in as pseudo-sites and co-phased with SNVs; the "present" allele is the unique
3447
+ event ID (a locus with two events is multi-allelic). ``None`` reproduces SNV/indel-only behavior.
3448
+ """
3449
+ # 1) Load SNVs and indels for this contig from the VCF.
3450
+ (
3451
+ snv_pos, ref_alleles, depth, af, site_type, site_kinds, del_span, ins_len
3452
+ ) = load_snvs(vcf_path, contig_id, vcf_sample_name, config)
3453
+
3454
+ # 1b) Merge SV pseudo-sites from the sidecar (if provided). Anchors that
3455
+ # collide with a real variant are dropped to avoid clobbering (caveat 7).
3456
+ sv_support = None
3457
+ if sv_sidecar_path:
3458
+ from strainphase.sv_encoding import _RECONCILE_MAX_SPAN, load_sv_sidecar_for_contig
3459
+
3460
+ # reconcile may move an anchor by up to _RECONCILE_MAX_SPAN, and a read is credited only
3461
+ # if its span brackets the anchor within _SV_ANCHOR_PAD; if the former exceeds the latter,
3462
+ # reconciling silently costs present-calls. The assert enforces the coupling.
3463
+ assert _RECONCILE_MAX_SPAN <= _SV_ANCHOR_PAD, (
3464
+ f"sv_encoding._RECONCILE_MAX_SPAN ({_RECONCILE_MAX_SPAN}) exceeds "
3465
+ f"core._SV_ANCHOR_PAD ({_SV_ANCHOR_PAD}); reconciled anchors can fall "
3466
+ "outside the span that credits a read with the event"
3467
+ )
3468
+ sv_pos, sv_ref, sv_stype, sv_support = load_sv_sidecar_for_contig(
3469
+ sv_sidecar_path, contig_id
3470
+ )
3471
+ n_added = n_collision = 0
3472
+ for p in sv_pos:
3473
+ if p in ref_alleles:
3474
+ n_collision += 1
3475
+ sv_support.pop(p, None)
3476
+ continue
3477
+ snv_pos.append(p)
3478
+ ref_alleles[p] = sv_ref[p] # "N" placeholder; SV sites are scored by event id
3479
+ site_type[p] = sv_stype[p]
3480
+ site_kinds[p] = frozenset({sv_stype[p]})
3481
+ n_added += 1
3482
+ if n_added or n_collision:
3483
+ logging.info(
3484
+ f"Contig {contig_id}: merged {n_added} SV pseudo-sites "
3485
+ f"({n_collision} dropped for colliding with a called variant)"
3486
+ )
3487
+
3488
+ if not snv_pos:
3489
+ logging.warning(f"No variants found for contig {contig_id}")
3490
+ return []
3491
+
3492
+ # 2) Create overlapping windows with lazy read loading. An ITERATOR: windows are pulled
3493
+ # from the BAM a batch at a time, so the whole contig's reads are never resident at once.
3494
+ window_iter = iter_windows_lazy(
3495
+ bam_path,
3496
+ contig_id,
3497
+ contig_length,
3498
+ snv_pos,
3499
+ ref_alleles,
3500
+ config,
3501
+ sample_id,
3502
+ site_type=site_type,
3503
+ site_kinds=site_kinds,
3504
+ del_span=del_span,
3505
+ ins_len=ins_len,
3506
+ sv_support=sv_support,
3507
+ )
3508
+
3509
+ # 3) Process windows (parallel if a pool is supplied or n_workers > 1). Batching serves
3510
+ # memory, not scheduling: pool.map over the full window list keeps both copies of every
3511
+ # window/result alive in the parent; batches cap that transient at batch_size windows.
3512
+ n_workers = config.n_workers
3513
+ own_pool = None
3514
+ if pool is not None:
3515
+ active_pool, n_pool_workers = pool, getattr(pool, "_processes", 1)
3516
+ elif n_workers > 1:
3517
+ own_pool = active_pool = make_worker_pool(n_workers, config)
3518
+ n_pool_workers = n_workers
3519
+ else:
3520
+ active_pool, n_pool_workers = None, 1
3521
+
3522
+ batch_size = max(1, n_pool_workers * max(1, config.window_batch_factor))
3523
+ results: list[WindowResult] = []
3524
+ n_windows = 0
3525
+ try:
3526
+ for batch in _batched(window_iter, batch_size):
3527
+ if n_windows == 0:
3528
+ # Logged on dispatch, not completion: shows the run is alive on a slow contig
3529
+ # (the total is not known up front - windows arrive from an iterator).
3530
+ logging.info(
3531
+ f"Processing windows on {contig_id} with {n_pool_workers} shared "
3532
+ f"workers in batches of {batch_size}"
3533
+ )
3534
+ n_windows += len(batch)
3535
+ if active_pool is not None and (len(batch) > 1 or n_windows > 1):
3536
+ chunksize = max(1, len(batch) // n_pool_workers)
3537
+ batch_results = active_pool.map(
3538
+ _process_window_wrapper, batch, chunksize=chunksize
3539
+ )
3540
+ else:
3541
+ batch_results = [process_window(w, config) for w in batch]
3542
+ # Release each window's read payload (~97% of a WindowResult) as its EM finishes,
3543
+ # keeping id-only stand-ins in gamma-row order; neither link_windows nor a
3544
+ # read-partition consumer needs the alleles again here. OFF by default: the
3545
+ # longitudinal caller manages its own spill/rescue, which re-read alleles.
3546
+ if offload_reads:
3547
+ for wr in batch_results:
3548
+ _detach_reads(wr)
3549
+ results.extend(batch_results)
3550
+ # Drop this batch's Window references before the next batch; the results still hold
3551
+ # their own window (rescue needs the reads), but the input list must not pin a copy.
3552
+ batch.clear()
3553
+ finally:
3554
+ if own_pool is not None:
3555
+ own_pool.close()
3556
+ own_pool.join()
3557
+
3558
+ if not results:
3559
+ logging.warning(f"No valid windows for contig {contig_id}")
3560
+ return []
3561
+
3562
+ logging.info(f"Processed {n_windows} windows on {contig_id}")
3563
+
3564
+ # 4) Link haplotypes across overlapping windows into tracks.
3565
+ results = link_windows(results, config)
3566
+
3567
+ return results
3568
+
3569
+
3570
+ def _batched(iterable: Iterable, n: int) -> Iterator[list]:
3571
+ """Yield successive lists of up to *n* items. Local stand-in for
3572
+ itertools.batched (3.12+) so this runs on the cluster's interpreter."""
3573
+ batch: list = []
3574
+ for item in iterable:
3575
+ batch.append(item)
3576
+ if len(batch) >= n:
3577
+ yield batch
3578
+ batch = []
3579
+ if batch:
3580
+ yield batch
3581
+
3582
+
3583
+ _WORKER_CONFIG: HaplotyperConfig | None = None
3584
+
3585
+
3586
+ def _init_worker(config: HaplotyperConfig) -> None:
3587
+ """Pool initializer: stash config in a module global so workers can read it
3588
+ without paying pickle cost per task."""
3589
+ global _WORKER_CONFIG
3590
+ _WORKER_CONFIG = config
3591
+
3592
+
3593
+ def _process_window_wrapper(window: Window) -> WindowResult:
3594
+ """Wrapper for process_window. Reads config from the worker-local global
3595
+ set by _init_worker, avoiding per-task config pickling."""
3596
+ assert _WORKER_CONFIG is not None, "Worker pool was not initialized with a config"
3597
+ return process_window(window, _WORKER_CONFIG)
3598
+
3599
+
3600
+ def make_worker_pool(n_workers: int, config: HaplotyperConfig) -> Pool:
3601
+ """Create a multiprocessing Pool whose workers are pre-initialized with
3602
+ `config`. Reuse this pool across many process_contig calls to avoid
3603
+ paying spawn/import overhead per contig."""
3604
+ return Pool(n_workers, initializer=_init_worker, initargs=(config,))
3605
+
3606
+
3607
+ # =============================================================================
3608
+ # RESULTS EXPORT
3609
+ # =============================================================================
3610
+
3611
+
3612
+ def results_to_dataframe(results: dict[str, list[WindowResult]]) -> list[dict]:
3613
+ """Convert results to track-based records for a DataFrame: one row per track, grouping
3614
+ haplotypes by track_id and computing span_start/span_end across all its windows.
3615
+ """
3616
+ records = []
3617
+
3618
+ for contig_id, window_results in results.items():
3619
+ tracks: dict[str, list[tuple[WindowResult, int, Haplotype]]] = defaultdict(list)
3620
+
3621
+ for wr in window_results:
3622
+ for k, hap in enumerate(wr.haplotypes):
3623
+ track_id = hap.track_id or f"unlinked_{wr.window.start}_{k}"
3624
+ tracks[track_id].append((wr, k, hap))
3625
+
3626
+ # Build one record per track
3627
+ for track_id, members in tracks.items():
3628
+ # Window span (fallback if no consensus SNVs)
3629
+ window_span_start = min(wr.window.start for wr, _, _ in members)
3630
+ window_span_end = max(wr.window.end for wr, _, _ in members)
3631
+ n_windows = len(members)
3632
+
3633
+ # Merge consensus across all windows (weighted voting)
3634
+ position_votes: dict[int, dict[str, float]] = defaultdict(lambda: defaultdict(float))
3635
+ total_weight = 0.0
3636
+ total_reads = 0
3637
+ confidences = []
3638
+
3639
+ window_abundances = []
3640
+ window_read_weights = []
3641
+
3642
+ for _wr, _k, hap in members:
3643
+ total_weight += hap.weight
3644
+ total_reads += hap.supporting_reads
3645
+ confidences.append(hap.confidence)
3646
+
3647
+ for pos, base in hap.consensus.items():
3648
+ position_votes[pos][base] += hap.weight
3649
+
3650
+ # Per-window abundance (conditioned on non-junk), or NO MEASUREMENT: a window
3651
+ # with no/short pi or all-junk did not measure this track at 0, it did not
3652
+ # measure it. Counting those as 0.0 dropped a track from 0.87 to 0.50.
3653
+ pi_vec = _wr.pi
3654
+ if pi_vec is None or len(pi_vec) <= _k:
3655
+ continue
3656
+ denom = 1.0 - float(pi_vec[-1])
3657
+ if denom <= 0:
3658
+ continue
3659
+ wa = max(0.0, min(1.0, float(pi_vec[_k]) / denom))
3660
+ junk_col = _wr.gamma.shape[1] - 1
3661
+ n_junk = int((_wr.gamma[:, junk_col] >= 0.5).sum())
3662
+ n_nonjunk = max(_wr.n_reads_examined - n_junk, 0)
3663
+ window_abundances.append(wa)
3664
+ window_read_weights.append(n_nonjunk)
3665
+
3666
+ merged_consensus = {}
3667
+ for pos, votes in position_votes.items():
3668
+ best_base = max(votes.keys(), key=lambda b: votes[b])
3669
+ merged_consensus[pos] = best_base
3670
+
3671
+ # Span: first to last consensus SNV position (fallback to window span)
3672
+ if merged_consensus:
3673
+ span_start = min(merged_consensus.keys())
3674
+ span_end = max(merged_consensus.keys())
3675
+ else:
3676
+ span_start = window_span_start
3677
+ span_end = window_span_end
3678
+
3679
+ # Get sample from first window (all should be same)
3680
+ sample = members[0][0].window.sample
3681
+
3682
+ # Pooled over reads, not averaged over windows (a mean of per-window ratios weights
3683
+ # a 5-read window like a 40-read one - the estimator documented elsewhere as wrong).
3684
+ # NaN, not 0.0, when no window measured the track: a consumer can drop a NaN.
3685
+ total_window_reads = sum(window_read_weights)
3686
+ if total_window_reads > 0:
3687
+ mean_weight = (
3688
+ sum(a * w for a, w in zip(window_abundances, window_read_weights))
3689
+ / total_window_reads
3690
+ )
3691
+ elif window_abundances:
3692
+ # Measured, but no window has any non-junk read to weight by.
3693
+ mean_weight = sum(window_abundances) / len(window_abundances)
3694
+ else:
3695
+ mean_weight = float("nan")
3696
+
3697
+ records.append(
3698
+ {
3699
+ "contig": contig_id,
3700
+ "sample": sample,
3701
+ "track_id": track_id,
3702
+ "span_start": span_start,
3703
+ "span_end": span_end,
3704
+ "span_bp": span_end - span_start,
3705
+ "n_windows": n_windows,
3706
+ "n_snvs": len(merged_consensus),
3707
+ "mean_weight": mean_weight,
3708
+ "total_supporting_reads": total_reads,
3709
+ "mean_confidence": np.mean(confidences) if confidences else 0.0,
3710
+ "consensus": "|".join(
3711
+ f"{pos}:{base}" for pos, base in sorted(merged_consensus.items())
3712
+ ),
3713
+ }
3714
+ )
3715
+
3716
+ # Sort by contig, then by span_start
3717
+ records.sort(key=lambda r: (r["contig"], r["span_start"]))
3718
+
3719
+ return records