Repository navigation
Expand file tree
/
Copy pathmap-algo.c
More file actions
1389 lines (1290 loc) · 51.4 KB
/
Copy pathmap-algo.c
File metadata and controls
1389 lines (1290 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "mbpriv.h"
#include "kalloc.h"
#include "kommon.h"
#include "ksort.h"
#include "regime.h"
#ifdef MB_HAVE_B2
#include "b2idx.h"
#endif
#define key_128x(a) ((a).x)
KRADIX_SORT_INIT(mb128x, mb128_t, key_128x, 8)
// Narrowed key-width variants for radix_sort. The klib radix does one 8-bit pass
// per key byte, so declaring the true key width skips passes over always-zero high
// bytes. Both bounds below are structural, not workload-dependent:
// _b5: keys that are concatenated-reference coordinates, bounded by the index
// length (< 2^40, i.e. references up to ~1 Tbp).
// _b4: keys that are a non-negative int32 chain score stored in a uint64 (< 2^32).
KRADIX_SORT_INIT(mb128x_b5, mb128_t, key_128x, 5)
KRADIX_SORT_INIT(mb128x_b4, mb128_t, key_128x, 4)
#define key_64(a) (a)
KRADIX_SORT_INIT(mb64, uint64_t, key_64, 8)
/*****************
* Index loading *
*****************/
mb_idx_t *mb_idx_load(const char *prefix, int32_t is_meth)
{
char *buf;
mb_idx_t *idx = 0;
l2b_t *l2b;
mb_bwt_t *bwt;
buf = kom_calloc(char, strlen(prefix) + 10);
strcat(strcpy(buf, prefix), ".l2b");
l2b = l2b_load(buf);
if (l2b == 0) goto end_idx_load;
if (is_meth) strcat(strcpy(buf, prefix), ".meth.mbw");
else strcat(strcpy(buf, prefix), ".mbw");
bwt = mb_bwt_load(buf);
if (bwt == 0) {
l2b_destroy(l2b);
goto end_idx_load;
}
mb_bwt_cache(bwt, 10); // TODO: don't hard code this
idx = kom_calloc(mb_idx_t, 1);
idx->is_meth = !!is_meth, idx->l2b = l2b, idx->bwt = bwt;
end_idx_load:
free(buf);
return idx;
}
mb_idx_t *mb_idx_load_mmap(const char *prefix, int32_t is_meth, int preload)
{
char *buf;
mb_idx_t *idx = 0;
l2b_t *l2b;
mb_bwt_t *bwt;
buf = kom_calloc(char, strlen(prefix) + 10);
strcat(strcpy(buf, prefix), ".l2b");
l2b = l2b_load_mmap(buf, preload);
if (l2b == 0) goto end_idx_load_mmap;
if (is_meth) strcat(strcpy(buf, prefix), ".meth.mbw");
else strcat(strcpy(buf, prefix), ".mbw");
bwt = mb_bwt_load_mmap(buf, preload);
if (bwt == 0) {
l2b_destroy(l2b);
goto end_idx_load_mmap;
}
mb_bwt_cache(bwt, 10); // TODO: don't hard code this
idx = kom_calloc(mb_idx_t, 1);
idx->is_meth = !!is_meth, idx->l2b = l2b, idx->bwt = bwt;
end_idx_load_mmap:
free(buf);
return idx;
}
#ifdef MB_HAVE_B2
/* Load an index backed by the bwa-mem2/bwa-mem3 cp_occ FM-index (b2idx.cpp)
* instead of minibwa's native BWT. idx->bwt is left NULL (see seed.c's
* idx->b2 dispatch) and idx->b2 holds the opaque cp_occ handle. is_meth is
* not yet supported on this backend (SR/PE only).
*
* Reference layer (idx->l2b): prefer minibwa's own <prefix>.l2b when it is
* present -- loading it is a cheap slurp (~1s on hg38). Only when it is absent
* fall back to Phase-2 reconstruction, rebuilding the reference in memory from
* the bwa-mem3 index's own layer (<prefix>.pac/.amb/.ann, via mb_b2_load_bns +
* l2b_from_bns). Reconstruction is byte-identical to the real .l2b (task-4
* test/report) but loops over the entire 2N packed reference, which costs ~8.5s
* on hg38 -- so it is worth avoiding whenever the .l2b already exists (the
* common case: bwa-mem2/3 indexes are usually built alongside minibwa's). The
* fallback keeps the cp_occ backend fully functional with no .l2b at all
* ("reference purity"). Downstream mapping only ever sees idx->l2b.
* Returns NULL on any failure, freeing anything already allocated. */
static mb_idx_t *mb_idx_load_b2(const char *prefix, int32_t is_meth)
{
mb_idx_t *idx = 0;
void *b2, *bns;
uint8_t *pac;
int64_t l_pac;
l2b_t *l2b;
char fn_l2b[1024];
if (is_meth) return 0; /* not supported by the cp_occ backend yet */
b2 = mb_b2_load(prefix);
if (!b2) return 0;
snprintf(fn_l2b, sizeof fn_l2b, "%s.l2b", prefix);
l2b = l2b_load(fn_l2b); /* fast path: co-located .l2b present */
if (!l2b) { /* .l2b absent -> Phase-2 reconstruction from the cp_occ index's bns/pac */
if (mb_b2_load_bns(prefix, &bns, &pac, &l_pac) != 0) { mb_b2_destroy(b2); return 0; }
l2b = l2b_from_bns(bns, pac, l_pac);
mb_b2_free_bns(bns, pac); /* l2b_from_bns deep-copies; bns/pac not needed anymore */
if (!l2b) { mb_b2_destroy(b2); return 0; }
}
idx = kom_calloc(mb_idx_t, 1);
idx->l2b = l2b; idx->b2 = b2; idx->bwt = 0; idx->is_meth = 0;
return idx;
}
#endif
/* Load an index for a specific SA regime `rg` (see regime.h). The .l2b is
* loaded per `use_mmap` as usual. For the .mbw:
* - bundled SA (rg->sa_path[0]==0): loaded normally via mb_bwt_load[_mmap],
* same as mb_idx_load/mb_idx_load_mmap.
* - sidecar SA (rg->sa_path[0]!=0): `use_mmap` is ignored and the BWT is
* always heap-loaded (mb_bwt_load_nosa), then the sidecar SA is attached
* with mb_bwt_load_sa. This is required because mb_bwt_load_sa refuses
* to attach a heap-allocated SA to an mmap-loaded BWT (mb_bwt_destroy
* only frees bwt->sa when bwt->mmap==0, so mixing the two would either
* leak the sidecar SA or double-free/munmap it); forcing the heap path
* keeps a single, consistent owner for every allocation in `bwt`.
* MB_BACKEND_CP_OCC regimes route to mb_idx_load_b2 (compile-optional,
* requires MB_HAVE_B2); without it, a cp_occ regime never reaches here
* because mb_regime_discover never offers one.
* Returns NULL on any failure, freeing anything already allocated. */
mb_idx_t *mb_idx_load_regime(const char *prefix, const mb_regime_t *rg, int use_mmap, int preload)
{
char *buf;
mb_idx_t *idx = 0;
l2b_t *l2b;
mb_bwt_t *bwt = 0;
if (rg->backend == MB_BACKEND_CP_OCC) {
#ifdef MB_HAVE_B2
return mb_idx_load_b2(prefix, /*is_meth=*/0);
#else
return 0; /* unreachable: discovery never offers cp_occ without MB_HAVE_B2 */
#endif
}
buf = kom_calloc(char, strlen(prefix) + 16); /* room for ".meth.mbw" */
strcat(strcpy(buf, prefix), ".l2b");
l2b = use_mmap? l2b_load_mmap(buf, preload) : l2b_load(buf);
if (!l2b) { free(buf); return 0; }
/* A meth regime loads the converted <prefix>.meth.mbw; a normal one <prefix>.mbw.
* A meth index is always bundled (no sidecars), so it takes the bundled path. */
strcat(strcpy(buf, prefix), rg->is_meth? ".meth.mbw" : ".mbw");
if (rg->sa_path[0] == 0) { /* bundled SA */
bwt = use_mmap? mb_bwt_load_mmap(buf, preload) : mb_bwt_load(buf);
} else { /* sidecar SA: force heap-load to preserve the single mmap-owner free invariant */
bwt = mb_bwt_load_nosa(buf);
if (bwt && mb_bwt_load_sa(bwt, rg->sa_path) != 0) { mb_bwt_destroy(bwt); bwt = 0; }
}
free(buf);
if (!bwt) { l2b_destroy(l2b); return 0; }
mb_bwt_cache(bwt, 10); // TODO: don't hard code this
idx = kom_calloc(mb_idx_t, 1);
idx->l2b = l2b; idx->bwt = bwt; idx->is_meth = rg->is_meth; /* preserve meth selection */
return idx;
}
int mb_idx_set_alt(mb_idx_t *idx, const char *fn)
{
if (idx == 0 || idx->l2b == 0) return -1;
return l2b_set_alt(idx->l2b, fn);
}
int mb_idx_set_alt_auto(mb_idx_t *idx, const char *prefix)
{
char *buf;
int ret;
if (idx == 0 || idx->l2b == 0) return -1;
buf = kom_calloc(char, strlen(prefix) + 5);
strcat(strcpy(buf, prefix), ".alt");
ret = l2b_set_alt(idx->l2b, buf); /* -1 (ENOENT) if absent — the common case */
free(buf);
return ret;
}
/* Reference (target) span the hit's CIGAR consumes, as a half-open interval on
* h->tid. Post-DP (h->p != NULL) this walks the CIGAR's reference-consuming ops
* (M/=/X/D/N) starting at h->ts; pre-DP (h->p == NULL) it falls back to the
* coarse chain interval [ts,te). Either way the footprint starts at h->ts. */
static void mb_hit_footprint(const mb_hit_t *h, int64_t *fp_st, int64_t *fp_en)
{
*fp_st = h->ts;
if (h->p != 0 && h->p->n_cigar > 0) {
int64_t pos = h->ts;
int32_t k;
for (k = 0; k < h->p->n_cigar; ++k) {
uint32_t op = h->p->cigar[k] & 0xf, len = h->p->cigar[k] >> 4;
if (op == MB_CIGAR_MATCH || op == MB_CIGAR_EQ_MATCH || op == MB_CIGAR_X_MISMATCH ||
op == MB_CIGAR_DEL || op == MB_CIGAR_N_SKIP)
pos += len;
}
*fp_en = pos;
} else {
*fp_en = h->te;
}
if (*fp_en <= *fp_st) *fp_en = *fp_st + 1; /* guard against a degenerate span */
}
mb_place_t mb_hit_place(const l2b_t *l2b, const mb_hit_t *h)
{
mb_place_t pl;
int64_t fp_st, fp_en;
const l2b_ctg_t *ctg;
uint32_t b;
int64_t en = 0; /* max over lifted PRIMARY outputs (cosmetic lifted_en) */
mb_hit_footprint(h, &fp_st, &fp_en);
/* Non-ALT hit (or no .alt loaded / no lift blocks): identity passthrough.
* One sub-placement at the hit's own position; representative fields are
* byte-identical to the pre-multi-interval baseline so non-ALT grouping is
* unchanged. */
if (!h->is_alt || h->tid < 0 || h->tid >= (int64_t)l2b->n_ctg ||
!l2b->ctg[h->tid].is_alt || l2b->ctg[h->tid].n_lift == 0) {
pl.pri_tid = h->tid;
pl.lifted_st = fp_st;
pl.lifted_en = fp_en;
pl.rev = h->rev;
pl.liftable = 1;
pl.n_subpl = 1;
pl.subpl[0].st = fp_st;
pl.subpl[0].pri_tid = h->tid;
pl.subpl[0].rev = h->rev;
return pl;
}
/* ALT hit: lift the footprint through the .alt span-lift. We walk the lift
* blocks: a reverse block maps alt_st to the HIGH primary coordinate (not the
* low one), and the footprint may begin/end in a hole (a gap between blocks).
* Rather than min/max-COLLAPSING every overlapping block into a single span
* (which inflates the placement by an SV-scale indel and drags the grouping
* key thousands of bp from a breakpoint-spanning twin), we record ONE
* sub-placement per overlapping block: subpl[k].st is that block's
* representative (min) lifted primary coordinate. A breakpoint-spanning ALT
* hit thus keeps a sub-interval AT each side of the breakpoint, so it can
* still co-locate with its primary twin via the matching one. Each block
* carries its OWN (pri_tid, rev): a multi-contig/mixed-strand ALT scaffold
* (which the old single-interval code flagged liftable=0 and dropped) now
* yields per-block sub-placements that co-locate only with a primary hit
* sharing that block's (pri_tid, rev) -- safe, and strictly more recoverable. */
ctg = &l2b->ctg[h->tid];
pl.n_subpl = 0;
for (b = 0; b < ctg->n_lift; ++b) {
const l2b_lift_t *blk = &ctg->lift[b];
int64_t a_lo, a_hi; /* clamped ALT endpoints inside the footprint */
int64_t p0, p1, blk_st;
int64_t pt0, pt1; uint64_t pp0, pp1; uint8_t rv0, rv1;
uint8_t blk_rev;
if ((int64_t)blk->alt_en <= fp_st || (int64_t)blk->alt_st >= fp_en)
continue; /* block does not overlap the footprint */
a_lo = (int64_t)blk->alt_st > fp_st ? (int64_t)blk->alt_st : fp_st;
a_hi = (int64_t)blk->alt_en < fp_en ? (int64_t)blk->alt_en : fp_en;
a_hi -= 1; /* inclusive last liftable ALT base in this block */
if (a_hi < a_lo) continue;
if (!l2b_lift(l2b, h->tid, (uint64_t)a_lo, &pt0, &pp0, &rv0)) continue;
if (!l2b_lift(l2b, h->tid, (uint64_t)a_hi, &pt1, &pp1, &rv1)) continue;
p0 = (int64_t)pp0; p1 = (int64_t)pp1;
blk_st = p0 < p1 ? p0 : p1; /* block's representative (min) lifted start */
/* MB_MAX_SUBPL spill: a footprint over a normal .alt CIGAR overlaps only a
* couple of blocks, but a pathologically fragmented region could exceed the
* cap. Keep the FIRST MB_MAX_SUBPL blocks and drop the rest. Dropping a
* candidate sub-interval can only REMOVE a possible co-location, never add a
* spurious one, so the cap is safe for paralog isolation. */
if (pl.n_subpl >= MB_MAX_SUBPL) break;
blk_rev = (uint8_t)(rv0 ^ h->rev);
pl.subpl[pl.n_subpl].st = blk_st;
pl.subpl[pl.n_subpl].pri_tid = pt0;
pl.subpl[pl.n_subpl].rev = blk_rev;
++pl.n_subpl;
/* Track the max lifted primary coordinate for the cosmetic lifted_en. */
if (pl.n_subpl == 1) en = blk_st;
if (p0 > en) en = p0;
if (p1 > en) en = p1;
}
if (pl.n_subpl == 0) {
/* Entire footprint falls in holes -> ALT-specific; own group. */
pl.pri_tid = h->tid;
pl.lifted_st = fp_st;
pl.lifted_en = fp_en;
pl.rev = h->rev;
pl.liftable = 0;
return pl;
}
/* Representative fields come from subpl[0] (back-compat); lifted_en is the max
* over sub-placements (cosmetic -- no decision reads it). */
pl.pri_tid = pl.subpl[0].pri_tid;
pl.lifted_st = pl.subpl[0].st;
pl.lifted_en = en + 1; /* half-open upper bound */
pl.rev = pl.subpl[0].rev;
pl.liftable = 1;
return pl;
}
/* Multi-interval co-location test (SV-breakpoint-aware grouping primitive).
*
* Two placements co-locate iff BOTH are liftable AND there exists a pair of
* sub-placements (one from each) that share a primary contig and strand and whose
* representative lifted starts are within lift_tol bp. This generalizes the old
* scalar "|Δlifted_st| <= lift_tol on the single collapsed interval" test:
* - A breakpoint-spanning ALT hit (multiple sub-placements straddling an
* SV-scale indel) co-locates with its primary twin via the matching
* sub-interval, instead of being dragged away by a min/max-collapsed span.
* - PARALOG SAFETY: co-location still requires a SHARED (pri_tid, rev, |Δst|<=tol)
* sub-interval. Two distinct primary loci have single, far-apart
* sub-placements and therefore never co-locate -- the multi-interval change
* can ONLY let an ALT hit join the group of a primary at one of its own lifted
* positions; it can NOT merge two primary loci. (Non-ALT hits carry exactly
* one sub-placement at their own position, so two primaries reduce to the
* original scalar test.)
*
* O(n_subpl_a * n_subpl_b), each bounded by MB_MAX_SUBPL. */
int mb_places_colocate(const mb_place_t *a, const mb_place_t *b, int lift_tol)
{
int i, j;
if (!a->liftable || !b->liftable) return 0;
for (i = 0; i < a->n_subpl; ++i) {
for (j = 0; j < b->n_subpl; ++j) {
int64_t d;
if (a->subpl[i].pri_tid != b->subpl[j].pri_tid) continue;
if (a->subpl[i].rev != b->subpl[j].rev) continue;
d = a->subpl[i].st - b->subpl[j].st;
if (d < 0) d = -d;
if (d <= lift_tol) return 1;
}
}
return 0;
}
/* Does ALT contig `alt_tid`'s .alt mapping cover primary position `pos` on
* `pri_tid`? An ALT contig is, by GRCh38 construction, an alternate of a
* specific primary REGION; its lift blocks (with internal indel gaps) span
* [min pri_st, max pri_en) on each primary contig they touch. Containment is
* tested in that OVERALL span (gaps included) so a position that falls in an
* .alt deletion gap -- or whose ALT twin lifts there through an insertion hole
* -- is still recognized as inside the ALT's primary region. This is the
* .alt-established correspondence used to fold an ALT twin onto a primary hit
* the per-base lift could not co-locate (mb_reconcile_alt step 2b). */
static int mb_alt_covers_primary(const l2b_t *l2b, int64_t alt_tid, int64_t pri_tid, int64_t pos)
{
const l2b_ctg_t *ctg;
uint32_t b;
int64_t lo = -1, hi = -1;
if (alt_tid < 0 || alt_tid >= (int64_t)l2b->n_ctg) return 0;
ctg = &l2b->ctg[alt_tid];
if (!ctg->is_alt || ctg->n_lift == 0) return 0;
for (b = 0; b < ctg->n_lift; ++b) {
const l2b_lift_t *blk = &ctg->lift[b];
if (blk->pri_tid != pri_tid) continue;
if (lo < 0 || (int64_t)blk->pri_st < lo) lo = (int64_t)blk->pri_st;
if (hi < 0 || (int64_t)blk->pri_en > hi) hi = (int64_t)blk->pri_en;
}
if (lo < 0) return 0; /* contig does not map to pri_tid */
return pos >= lo && pos < hi;
}
void mb_idx_destroy(mb_idx_t *idx)
{
if (idx == 0) return;
mb_bwt_destroy(idx->bwt);
#ifdef MB_HAVE_B2
if (idx->b2) mb_b2_destroy(idx->b2);
#endif
l2b_destroy(idx->l2b);
free(idx);
}
const char *mb_idx_ctg_name(const mb_idx_t *idx, int32_t tid)
{
return tid >= 0 && tid < idx->l2b->n_ctg? idx->l2b->ctg[tid].name : 0;
}
int64_t mb_idx_ctg_len(const mb_idx_t *idx, int32_t tid)
{
return tid >= 0 && tid < idx->l2b->n_ctg? idx->l2b->ctg[tid].len : -1;
}
/*****************
* Thread buffer *
*****************/
struct mb_tbuf_s {
void *km;
};
mb_tbuf_t *mb_tbuf_init(int no_kalloc)
{
mb_tbuf_t *b;
b = kom_calloc(mb_tbuf_t, 1);
if (!no_kalloc) b->km = km_init();
return b;
}
void *mb_tbuf_km(mb_tbuf_t *b)
{
return b->km;
}
void mb_tbuf_destroy(mb_tbuf_t *b)
{
if (b->km) km_destroy(b->km);
free(b);
}
int32_t mb_tbuf_reset(mb_tbuf_t *b, int64_t max_blk_sz)
{
km_stat_t kmst;
int64_t max_sz = max_blk_sz < 1U<<28? max_blk_sz : 1U<<28;
if (b->km == 0) return 0;
km_stat(b->km, &kmst);
assert(kmst.n_blocks == kmst.n_cores);
if (kmst.largest > max_sz || kmst.capacity > max_sz * 2) {
km_destroy(b->km);
b->km = km_init();
return 1;
}
return 0;
}
/************************
* Basic hit operations *
************************/
int32_t mb_cal_mblen(int32_t n, const mb_anchor_t *a, int32_t *blen_)
{
int32_t i;
int64_t mlen, blen;
*blen_ = 0;
if (n <= 0) return 0;
mlen = blen = a[0].len;
for (i = 1; i < n; ++i) {
int span = a[i].len;
int tl = (int32_t)a[i].tpos - (int32_t)a[i-1].tpos;
int ql = (int32_t)a[i].qpos - (int32_t)a[i-1].qpos;
blen += tl > ql? tl : ql;
mlen += tl > span && ql > span? span : tl < ql? tl : ql;
}
*blen_ = blen;
return mlen;
}
static void mb_cal_fuzzy_len(mb_hit_t *r, const mb_anchor_t *a)
{
r->mlen = mb_cal_mblen(r->cnt, &a[r->as], &r->blen);
}
static inline void mb_hit_set_coor(mb_hit_t *r, int32_t qlen, const l2b_t *l2b, const mb_anchor_t *a)
{ // NB: r->as and r->cnt MUST BE set correctly for this function to work
int32_t k = r->as;
const mb_anchor_t *ak0 = &a[k];
const mb_anchor_t *ak1 = &a[k + r->cnt - 1];
r->tid = ak0->sid>>1, r->rev = ak0->sid&1;
r->ts = ak0->tpos + 1 - ak0->len;
r->te = ak1->tpos + 1;
if (!r->rev) { // forward strand
r->qs = ak0->qpos + 1 - ak0->len;
r->qe = ak1->qpos + 1;
} else { // reverse strand
r->qs = qlen - (ak1->qpos + 1);
r->qe = qlen - (ak0->qpos + 1 - ak0->len);
}
mb_cal_fuzzy_len(r, a);
}
int32_t mb_cal_high_cov(void *km, int32_t n, const mb_sai_t *sai, int32_t max_occ)
{
int32_t i, n_hi = 0, hi_st, hi_en, hi_cov;
uint64_t *b;
for (i = 0; i < n; ++i)
if (sai[i].size > max_occ)
++n_hi;
if (n_hi == 0) return 0;
b = Kmalloc(km, uint64_t, n_hi);
for (i = 0, n_hi = 0; i < n; ++i)
if (sai[i].size > max_occ)
b[n_hi++] = sai[i].info;
radix_sort_mb64(b, b + n_hi);
hi_st = b[0]>>32, hi_en = (int32_t)b[0], hi_cov = 0;
for (i = 1; i < n_hi; ++i) {
int32_t st = b[i]>>32, en = (int32_t)b[i];
if (st > hi_en) {
hi_cov += hi_en - hi_st;
hi_st = st, hi_en = en;
} else hi_en = hi_en > en? hi_en : en;
}
hi_cov += hi_en - hi_st;
kfree(km, b);
return hi_cov;
}
void mb_sync_high_cov(int32_t n, mb_hit_t *h)
{
int32_t i, max_frac = 0;
for (i = 0; i < n; ++i)
max_frac = max_frac > h[i].frac_high? max_frac : h[i].frac_high;
for (i = 0; i < n; ++i)
h[i].frac_high = max_frac;
}
mb_hit_t *mb_gen_hit(void *km, uint32_t hash, int qlen, const l2b_t *l2b, int n_u, uint64_t *u, mb_anchor_t *a)
{ // convert chains to hits
mb128_t *z, tmp;
mb_hit_t *r;
int i, k;
if (n_u <= 0) return 0;
// sort by score
z = Kmalloc(km, mb128_t, n_u);
for (i = k = 0; i < n_u; ++i) {
uint32_t h;
h = (uint32_t)mb_hash64((mb_hash64(a[k].tpos) + mb_hash64(a[k].qpos)) ^ hash);
z[i].x = u[i] ^ h; // u[i] -- higher 32 bits: chain score; lower 32 bits: number of anchors
z[i].y = (uint64_t)k << 32 | (int32_t)u[i];
k += (int32_t)u[i];
}
radix_sort_mb128x(z, z + n_u);
for (i = 0; i < n_u>>1; ++i) // reverse, s.t. larger score first
tmp = z[i], z[i] = z[n_u-1-i], z[n_u-1-i] = tmp;
// populate r[]
r = (mb_hit_t*)calloc(n_u, sizeof(mb_hit_t));
for (i = 0; i < n_u; ++i) {
mb_hit_t *ri = &r[i];
ri->id = i;
ri->parent = MB_PARENT_UNSET;
ri->score = ri->score0 = z[i].x >> 32;
ri->hash = (uint32_t)z[i].x;
ri->cnt = (int32_t)z[i].y;
ri->as = z[i].y >> 32;
mb_hit_set_coor(ri, qlen, l2b, a);
ri->is_alt = l2b->ctg[ri->tid].is_alt;
}
kfree(km, z);
return r;
}
void mb_split_hit(mb_hit_t *r, mb_hit_t *r2, int n, int qlen, mb_anchor_t *a, const l2b_t *l2b)
{
if (n <= 0 || n >= r->cnt) return;
*r2 = *r;
r2->id = -1;
r2->sam_pri = 0;
r2->p = 0;
r2->split_inv = 0;
r2->cnt = r->cnt - n;
r2->score = (int32_t)(r->score * ((float)r2->cnt / r->cnt) + .499);
r2->as = r->as + n;
if (r->parent == r->id) r2->parent = MB_PARENT_TMP_PRI;
mb_hit_set_coor(r2, qlen, l2b, a);
r->cnt -= r2->cnt;
r->score -= r2->score;
mb_hit_set_coor(r, qlen, l2b, a);
r->split |= 1, r2->split |= 2;
}
void mb_sync_hits(void *km, int n_regs, mb_hit_t *regs)
{
int *tmp, i, max_id = -1, n_tmp;
if (n_regs <= 0) return;
for (i = 0; i < n_regs; ++i)
max_id = max_id > regs[i].id? max_id : regs[i].id;
n_tmp = max_id + 1;
tmp = (int*)kmalloc(km, n_tmp * sizeof(int));
for (i = 0; i < n_tmp; ++i) tmp[i] = -1;
for (i = 0; i < n_regs; ++i)
if (regs[i].id >= 0) tmp[regs[i].id] = i;
for (i = 0; i < n_regs; ++i) {
mb_hit_t *r = ®s[i];
r->id = i;
if (r->parent == MB_PARENT_TMP_PRI)
r->parent = i;
else if (r->parent >= 0 && tmp[r->parent] >= 0)
r->parent = tmp[r->parent];
else r->parent = MB_PARENT_UNSET;
}
kfree(km, tmp);
mb_set_sam_pri(n_regs, regs, 0); // this flag will be overwritten later anyway
}
/**********************************
* Set primary and secondary hits *
**********************************/
static int update_sub(mb_hit_t *ri, mb_hit_t *rp, float mask_level, int mask_len, int sub_diff, int uncov_len)
{
int si = ri->qs, ei = ri->qe, sj = rp->qs, ej = rp->qe, min, max, ol;
if (ej <= si || sj >= ei) return 0;
min = ej - sj < ei - si? ej - sj : ei - si;
max = ej - sj > ei - si? ej - sj : ei - si;
ol = ej <= si || sj >= ei? 0 : (ej < ei? ej : ei) - (sj > si? sj : si);
if ((double)ol / min - (double)uncov_len / max > mask_level && uncov_len <= mask_len) {
int cnt_sub = 0, sci = ri->score;
ri->parent = rp->parent;
rp->subsc = rp->subsc > sci? rp->subsc : sci;
if (rp->p && ri->p && (rp->tid != ri->tid || rp->ts != ri->ts || rp->te != ri->te || ol != min)) { // the last condition excludes identical hits after DP
sci = ri->p->dp_max;
rp->p->dp_max2 = rp->p->dp_max2 > sci? rp->p->dp_max2 : sci;
if (rp->p->dp_max - ri->p->dp_max <= sub_diff) cnt_sub = 1;
}
if (cnt_sub) ++rp->n_sub;
return 1;
} else return 0;
}
void mb_set_parent(void *km, float mask_level, int mask_len, int n, mb_hit_t *r, int sub_diff, int hard_mask_level)
{ // TODO: re-examine the logic for variable-length seeds
int i, j, k, *w;
uint64_t *cov;
if (n <= 0) return;
for (i = 0; i < n; ++i) r[i].id = i;
cov = Kmalloc(km, uint64_t, n);
w = Kmalloc(km, int, n);
w[0] = 0, r[0].parent = 0;
for (i = 1, k = 1; i < n; ++i) {
mb_hit_t *ri = &r[i];
int si = ri->qs, ei = ri->qe, n_cov = 0, uncov_len = 0, max_ol, max_j, n_par = 0;
if (hard_mask_level) goto skip_uncov;
for (j = 0; j < k; ++j) {
const mb_hit_t *rp = &r[w[j]];
int sj = rp->qs, ej = rp->qe;
if (ej <= si || sj >= ei) continue;
if (sj < si) sj = si;
if (ej > ei) ej = ei;
cov[n_cov++] = (uint64_t)sj<<32 | ej;
}
if (n_cov == 0) {
goto add_primary;
} else {
int j, x = si;
radix_sort_mb64(cov, cov + n_cov);
for (j = 0; j < n_cov; ++j) {
if ((int)(cov[j]>>32) > x) uncov_len += (cov[j]>>32) - x;
x = (int32_t)cov[j] > x? (int32_t)cov[j] : x;
}
if (ei > x) uncov_len += ei - x;
}
skip_uncov:
for (j = 0, max_ol = 0, max_j = -1; j < k; ++j) { // find the parent with the maximum overlap
const mb_hit_t *rp = &r[w[j]];
int sj = rp->qs, ej = rp->qe;
int ol = ej <= si || sj >= ei? 0 : (ej < ei? ej : ei) - (sj > si? sj : si);
if (max_ol < ol) max_ol = ol, max_j = j;
}
if (max_j >= 0) {
n_par += update_sub(ri, &r[w[max_j]], mask_level, mask_len, sub_diff, uncov_len);
for (j = 0; j < k && n_par == 0; ++j) // if no parent found on the longest overlap, try more
n_par += update_sub(ri, &r[w[j]], mask_level, mask_len, sub_diff, uncov_len);
}
add_primary:
if (n_par == 0) w[k++] = i, ri->parent = i, ri->n_sub = 0;
}
kfree(km, cov);
kfree(km, w);
}
/* Mark the SAM primary among the group representatives (parent==id).
*
* Selection is per-read: the 5'-most representative (smallest query start) when
* is_primary5 is set, otherwise the first representative by index. The pairing
* pass does not disambiguate the primary here -- upstream sets sam_pri on the
* pair-chosen endpoint separately (see the paired branch in pe.c). */
int32_t mb_set_sam_pri(int32_t n, mb_hit_t *r, int32_t is_primary5)
{
int32_t i, new_pri, n_pri = 0, min_i = -1, min_qs = -1, first_i = -1;
if (n <= 0) return -1;
for (i = 0; i < n; ++i) {
r[i].sam_pri = 0;
if (r[i].id != r[i].parent) continue;
if (++n_pri == 1) first_i = i;
if (min_qs < 0 || r[i].qs < min_qs)
min_i = i, min_qs = r[i].qs;
}
assert(n_pri > 0);
new_pri = is_primary5? min_i : first_i;
r[new_pri].sam_pri = 1;
return new_pri;
}
/* Check whether hit r co-locates with any of the n_kept placements in kpl[].
* Co-location is the multi-interval test (mb_places_colocate): any sub-interval
* of r matches any sub-interval of a kept placement (same pri_tid, rev,
* |Δst| <= lift_tol). */
static int mb_place_matches_any(const l2b_t *l2b, const mb_hit_t *r,
const mb_place_t *kpl, int n_kept, int lift_tol)
{
mb_place_t pl;
int j;
if (n_kept == 0) return 0;
pl = mb_hit_place(l2b, r); /* coarse: r->p may be NULL (pre-DP) */
if (!pl.liftable) return 0;
for (j = 0; j < n_kept; ++j)
if (mb_places_colocate(&kpl[j], &pl, lift_tol)) return 1;
return 0;
}
void mb_select_sub(void *km, float pri_ratio, int min_diff, int best_n, int *n_, mb_hit_t *r,
const l2b_t *l2b, int lift_tol)
{
if (pri_ratio > 0.0f && *n_ > 0) {
int i, k, n = *n_, n_2nd = 0;
uint8_t *keep = Kcalloc(km, uint8_t, n);
/* Pass 1: existing keep logic, plus record each kept hit's lifted placement
* so pass 2 can find kept primaries that sit at higher indices than their
* ALT twins. */
mb_place_t *kept_pl = 0;
int n_kept = 0;
/* The survival guard below can only fire on an ALT hit, and hit->is_alt is
* copied from l2b->ctg[tid].is_alt -- so with no .alt loaded no hit is ever
* ALT, kept_pl is written but never read, and every mb_hit_place() call is
* wasted. Gating on the contig count keeps that cost off the common path;
* `l2b` itself is the sequence index and is always present. */
const int use_lift = l2b && l2b->n_alt_ctg > 0;
if (use_lift) kept_pl = Kmalloc(km, mb_place_t, n); /* worst-case: all kept */
for (i = 0; i < n; ++i) {
int p = r[i].parent;
if (p == i || r[i].inv) {
keep[i] = 1;
} else if ((r[i].score >= r[p].score * pri_ratio || r[i].score + min_diff >= r[p].score) && n_2nd < best_n) {
if (!(r[i].qs == r[p].qs && r[i].qe == r[p].qe && r[i].tid == r[p].tid && r[i].ts == r[p].ts && r[i].te == r[p].te))
keep[i] = 1, ++n_2nd;
}
if (use_lift && keep[i]) {
/* Record non-ALT primaries too: their "lifted" placement is their own
* position, which is exactly the target co-location ALT twins must match. */
mb_place_t pl = mb_hit_place(l2b, &r[i]);
if (pl.liftable) kept_pl[n_kept++] = pl;
}
}
/* Pass 2 (survival guard): for each not-yet-kept ALT hit, force-keep it
* if its lifted placement co-locates with any already-kept hit. This is
* intentionally generous: over-keeping is cheap; the authoritative grouping
* happens later. Never make this tolerance tighter than MB_LIFT_TOL. */
if (use_lift) {
/* --dbg-no-alt-survive ablates just this guard (testing), so a fixture
* can assert the RED state (twin dropped) as well as the GREEN one. */
int ablate = (kom_dbg_flag & MB_DBG_NO_ALT_SURVIVE) != 0;
if (!ablate) for (i = 0; i < n; ++i) {
if (!keep[i] && r[i].is_alt) {
if (mb_place_matches_any(l2b, &r[i], kept_pl, n_kept, lift_tol))
keep[i] = 1;
}
}
kfree(km, kept_pl);
}
for (i = k = 0; i < n; ++i) {
if (keep[i]) r[k++] = r[i];
else if (r[i].p) free(r[i].p); // r->p is libc-allocated; free here before the pointer is lost
}
kfree(km, keep);
if (k != n) mb_sync_hits(km, k, r);
*n_ = k;
}
}
/* True iff any hit is from an ALT contig. The reconciliation pass is gated on
* this so non-ALT reads (and any reference with no .alt loaded) pay nothing. */
int mb_any_alt(int n_hit, const mb_hit_t *hit)
{
int i;
for (i = 0; i < n_hit; ++i)
if (hit[i].is_alt) return 1;
return 0;
}
/* Two hits' DP-adjusted scores (dp_max if extended, else the chaining score). */
static inline int32_t mb_hit_dpscore(const mb_hit_t *h)
{
return h->p ? h->p->dp_max : h->score;
}
/* Query spans [qs,qe) of two hits overlap (share at least one query base).
* Non-overlapping spans are chimeric segments of the read, not competitors for
* the same locus, so they must NOT contribute to one another's suboptimal. */
static inline int mb_qspan_overlap(const mb_hit_t *a, const mb_hit_t *b)
{
return a->qs < b->qe && b->qs < a->qe;
}
/* Post-extension liftover-group reconciliation (the heart of the ALT feature).
*
* Surviving hits are grouped by their lifted PLACEMENT (same pri_tid, same
* strand on primary, and |Δlifted_st| <= MB_LIFT_TOL). Each group represents
* one primary locus; an ALT twin and the primary hit it lifts onto land in the
* SAME group. Within a group the representative (the surviving "primary" hit,
* parent==id) is the highest-DP-scoring member; the others become subordinates
* (parent := rep->id) so mb_set_sam_pri/mb_set_mapq treat them as secondary.
*
* The MAPQ-critical step is recomputing the group-scoped suboptimal fields so a
* read's MAPQ reflects the second-best GROUP, not an ALT twin of its own locus.
* subsc / n_sub / dp_max2 were written by the :778/:784 mb_set_parent run as
* running maxima/accumulators; here we ZERO them on every (post-grouping)
* representative and recompute over representatives ONLY:
* - dp_max2 = best OTHER-group rep dp_max whose query span overlaps this rep
* - subsc = that competing score
* - n_sub = count of other-group reps within sub_diff of this rep
* Intra-group members contribute nothing. A hit promoted from subordinate to
* representative by the new grouping is zeroed too: it still carries stale
* numbers from when it was a child under the old parent.
*
* @param l2b span-lift index (.alt loaded; used by mb_hit_place)
* @param n_hit number of surviving hits
* @param hit the hits (modified in place: parent, subsc, n_sub, dp_max2)
* @param sub_diff score window for counting near-tied competing groups (n_sub);
* matches the value passed to mb_set_parent in the driver.
*/
void mb_reconcile_alt(void *km, const l2b_t *l2b, int n_hit, mb_hit_t *hit, int sub_diff, int lift_tol)
{
mb_place_t *pl;
int *grp; /* group id (union-find style, flattened) per hit */
int *rep; /* representative hit index per hit (== own index if rep) */
int i, j;
if (n_hit <= 0) return;
/* Per-thread kalloc arena (lock-free); NOT libc malloc -- on ALT-heavy WGS
* this runs per read across all worker threads, and routing it through the
* shared allocator serialized them on the mimalloc arena lock (threads parked
* in __ulock_wait, parallelism 8.8x->6.8x). Kmalloc/kfree on km is the
* codebase convention and is contention-free. (km==NULL falls back to libc
* via the kalloc macros, preserving the MB_F_NO_KALLOC path.) */
pl = Kmalloc(km, mb_place_t, n_hit);
grp = Kmalloc(km, int, n_hit);
rep = Kmalloc(km, int, n_hit);
/* Graceful on allocation failure: with km!=NULL the arena aborts on OOM, but
* the km==NULL (MB_F_NO_KALLOC) path falls back to libc malloc which can
* return NULL -- return rather than deref. kfree() is NULL-safe. */
if (!pl || !grp || !rep) { kfree(km, pl); kfree(km, grp); kfree(km, rep); return; }
/* 1. lifted placement of every hit. */
for (i = 0; i < n_hit; ++i)
pl[i] = mb_hit_place(l2b, &hit[i]);
/* 2. group by lifted placement via transitive close-up: for each co-locating
* pair in different groups, unite the groups -- but only after an all-cross-
* pairs guard (the t/u loops below) confirms EVERY member pair co-locates AND
* query-overlaps, which is what stops chimeric segments and paralogs from
* drifting together. Unliftable hits never match and stay singletons.
*
* Complexity: the guard makes a single merge O(n_hit^2), so the loop is
* O(n_hit^4) in the worst case, NOT O(n_hit^2). In practice it stays near
* O(n_hit^2): (a) n_hit is small -- default max_occ/out_n subsampling caps the
* surviving hits, and even a 40-copy segdup measured n_hit=41; (b) the
* `grp[j]==grp[i]` short-circuit skips within-group pairs, and hits of one
* read that co-locate also query-overlap, so they merge on first contact and
* collapse to one group instead of re-triggering the guard. A true union-
* find would drop the exponent but cannot express the all-cross-pairs guard
* (it unites on a single edge), so it would merge groups this must keep apart.
* If a profile ever shows this hot, cap n_hit rather than change the grouping
* semantics. */
for (i = 0; i < n_hit; ++i) grp[i] = i; /* initially own group */
for (i = 0; i < n_hit; ++i) {
if (!pl[i].liftable) continue;
for (j = 0; j < i; ++j) {
if (!pl[j].liftable) continue;
if (grp[j] == grp[i]) continue;
if (mb_places_colocate(&pl[i], &pl[j], lift_tol)) {
/* Candidate merge of i's group (old) into j's group (neu).
* Two hits are the SAME read alignment on primary vs ALT only
* if they CO-LOCATE (share a lifted sub-interval: same pri_tid,
* same strand, |Δst| <= MB_LIFT_TOL) AND their query spans
* overlap. Grouping is by transitive relabel for clarity, but
* transitivity can drift: A~B and B~C may collapse A,C even when
* A,C do not co-locate or have disjoint query spans (chimeric
* segments). Guard by requiring EVERY cross-pair between the two
* groups to satisfy BOTH conditions before uniting them. The
* sub-interval co-location requirement preserves paralog safety:
* a breakpoint-spanning ALT hit joins via its matching
* sub-interval, but two distinct primary loci (single, far-apart
* sub-placements) still never share one. */
int old = grp[i], neu = grp[j], t, u, ok = 1;
for (t = 0; t < n_hit && ok; ++t) {
if (grp[t] != old) continue;
for (u = 0; u < n_hit; ++u) {
if (grp[u] != neu) continue;
if (!mb_qspan_overlap(&hit[t], &hit[u])
|| !mb_places_colocate(&pl[t], &pl[u], lift_tol)) {
ok = 0; break;
}
}
}
if (ok) {
/* merge i's group into j's group: relabel every member. */
for (t = 0; t < n_hit; ++t)
if (grp[t] == old) grp[t] = neu;
}
}
}
}
/* 2b. ALT-ALTERNATE fold-in (placement-based, via the .alt correspondence).
*
* The per-base lift in step 2 groups an ALT twin with its primary only where
* the lift is EXACT. It fails when an .alt-internal structural indel
* displaces the ALT twin's lifted placement beyond lift_tol, or drops the ALT
* footprint into an insertion HOLE (unliftable) -- leaving the ALT twin as a
* co-equal group representative that both steals the SAM-primary slot (read
* placed on the ALT contig) and dilutes the primary's MAPQ to 0. Recognize,
* via the .alt RECORD (this ALT contig is an alternate of a specific primary
* region), that an ALT hit which (a) shares read bases with a non-ALT hit
* -- same fragment, not a chimeric segment -- and (b) whose contig maps over
* that non-ALT hit's primary locus, is an ALTERNATE PLACEMENT of that locus.
* Fold its whole group into the non-ALT hit&
8
#039;s g
7E28
roup.
*
* Applied ONLY to an ALT hit whose group has NO non-ALT member (the exact
* lift already failed to co-locate it). Paralog-safe: only ALT-vs-non-ALT
* folds; two genuine primary loci are both non-ALT and never merge here, so a
* truly ambiguous multi-mapper keeps MAPQ 0. This does NOT discard ALT hits
* categorically -- an ALT hit with no overlapping primary (a read genuinely
* from an ALT-only region) stays an independent representative. */
{
uint8_t *grp_has_pri = Kcalloc(km, uint8_t, n_hit);
if (grp_has_pri) {
for (i = 0; i < n_hit; ++i)
if (!hit[i].is_alt) grp_has_pri[grp[i]] = 1;
for (i = 0; i < n_hit; ++i) {
if (!hit[i].is_alt) continue; /* fold ALT hits only */
if (grp_has_pri[grp[i]]) continue; /* already grouped with a primary */
for (j = 0; j < n_hit; ++j) {
int old, neu, t;
if (hit[j].is_alt) continue; /* into a non-ALT hit */
if (grp[j] == grp[i]) continue;
if (!mb_qspan_overlap(&hit[i], &hit[j])) continue;
if (!mb_alt_covers_primary(l2b, hit[i].tid, pl[j].pri_tid, pl[j].lifted_st))
continue;
old = grp[i]; neu = grp[j];
for (t = 0; t < n_hit; ++t) if (grp[t] == old) grp[t] = neu;
grp_has_pri[grp[i]] = 1;
break;
}
}
kfree(km, grp_has_pri);
}
}
/* 3. representative per group -- determined AFTER the new grouping. Within a
* group every member is the SAME primary locus, so the primary-assembly
* (non-ALT) member is the representative the read is reported on: an ALT
* copy is an ALTERNATE of this locus, never a "better" locus, so a non-ALT
* member outranks an ALT member REGARDLESS of DP score. DP score (then
* larger hash) decides only between members of the same is_alt class. */
for (i = 0; i < n_hit; ++i) rep[i] = grp[i]; /* seed with the label index */
for (i = 0; i < n_hit; ++i) {
int g = grp[i], r = rep[g];
int32_t si = mb_hit_dpscore(&hit[i]), sr = mb_hit_dpscore(&hit[r]);
int better;
if (hit[i].is_alt != hit[r].is_alt) better = (!hit[i].is_alt); /* prefer non-ALT */
else if (si != sr) better = (si > sr);
else better = (hit[i].hash > hit[r].hash);
if (better) rep[g] = i;
}
/* 4a. wire subordinates to their group's representative. */
for (i = 0; i < n_hit; ++i) {
int r = rep[grp[i]];
hit[i].parent = hit[r].id; /* reps get parent==id (r==i) automatically */
}
/* 4b. ZERO the suboptimal fields on every post-grouping representative
* (including ones promoted from subordinate) before recomputing -- the
* :778/:784 run left running maxima/accumulators that must be RESET. */
for (i = 0; i < n_hit; ++i) {
if (rep[grp[i]] != i) continue; /* representatives only */
hit[i].subsc = 0;
hit[i].n_sub = 0;
if (hit[i].p) hit[i].p->dp_max2 = 0;
}
/* 4c. recompute over REPRESENTATIVES ONLY: each rep's suboptimal comes from
* other GROUPS' reps whose query span overlaps it (chimeric, i.e.
* non-overlapping, segments are not competitors). Intra-group members
* contribute nothing because we only ever compare distinct reps. */
for (i = 0; i < n_hit; ++i) {
mb_hit_t *ri = &hit[i];
if (rep[grp[i]] != i) continue; /* ri is a representative */
for (j = 0; j < n_hit; ++j) {
mb_hit_t *rj;
int32_t sj;
if (rep[grp[j]] != j) continue; /* rj is a representative */