-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstitch.rs
More file actions
3420 lines (3129 loc) · 128 KB
/
stitch.rs
File metadata and controls
3420 lines (3129 loc) · 128 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
//! Seed clustering and stitching via dynamic programming
use crate::align::score::AlignmentScorer;
use crate::align::seed::Seed;
use crate::align::transcript::{CigarOpExt as _, Transcript};
use crate::index::GenomeIndex;
use noodles::sam::alignment::record::cigar;
/// STAR's MARK_FRAG_SPACER_BASE (IncludeDefine.h:174).
/// Separates mate1 and mate2 fragments in the combined PE read.
pub(crate) const PE_SPACER_BASE: u8 = 11;
/// Count mismatches in an alignment by comparing read sequence to genome sequence.
///
/// The read sequence is always in forward orientation. For reverse-strand alignments,
/// the genome is accessed at `pos + n_genome` (the reverse-complement region) rather
/// than reverse-complementing the read.
///
/// # Arguments
/// * `read_seq` - Read sequence in forward orientation (encoded as 0=A, 1=C, 2=G, 3=T, 4=N)
/// * `cigar_ops` - CIGAR operations
/// * `genome_start` - Starting position in genome (decoded SA position, WITHOUT n_genome offset)
/// * `read_start` - Starting position in read
/// * `index` - Genome index (contains genome sequence)
/// * `is_reverse` - Whether this is a reverse-strand alignment
///
/// # Returns
/// Number of mismatched bases (excluding N bases)
/// Count mismatches in a simple region (no CIGAR, just read vs genome)
fn count_mismatches_in_region(
read_seq: &[u8],
read_start: usize,
genome_start: u64,
length: usize,
index: &GenomeIndex,
is_reverse: bool,
) -> u32 {
let genome_offset = if is_reverse { index.genome.n_genome } else { 0 };
let mut n_mismatch = 0u32;
for i in 0..length {
let read_pos = read_start + i;
if read_pos >= read_seq.len() {
break;
}
let read_base = read_seq[read_pos];
if let Some(genome_base) = index
.genome
.get_base(genome_start + i as u64 + genome_offset)
&& read_base != genome_base
&& read_base != 4
&& genome_base != 4
{
n_mismatch += 1;
}
}
n_mismatch
}
/// Score a region base-by-base, skipping N in read or genome (STAR behavior).
///
/// Mirrors STAR's stitchAlignToTranscript.cpp loop:
/// `if (G[ii]<4 && R[ii]<4) { if match: Score+=scoreMatch; else: Score-=scoreMatch; }`
///
/// Returns `(score, n_mismatch)`. N positions contribute 0 to score (neither +1 nor -1).
fn score_region(
read_seq: &[u8],
read_start: usize,
genome_start: u64,
length: usize,
index: &GenomeIndex,
is_reverse: bool,
) -> (i32, u32) {
let genome_offset = if is_reverse { index.genome.n_genome } else { 0 };
let mut score = 0i32;
let mut n_mismatch = 0u32;
for i in 0..length {
let read_pos = read_start + i;
if read_pos >= read_seq.len() {
break;
}
let read_base = read_seq[read_pos];
let Some(genome_base) = index
.genome
.get_base(genome_start + i as u64 + genome_offset)
else {
break;
};
// N in read or genome: skip, no score contribution (STAR: `if (G<4 && R<4)`)
if read_base >= 4 || genome_base >= 4 {
continue;
}
if read_base == genome_base {
score += 1;
} else {
score -= 1;
n_mismatch += 1;
}
}
(score, n_mismatch)
}
fn count_mismatches(
read_seq: &[u8],
cigar_ops: &[cigar::Op],
genome_start: u64,
read_start: usize,
index: &GenomeIndex,
is_reverse: bool,
) -> u32 {
use cigar::op::Kind;
// Add n_genome offset for reverse-strand genome access
let genome_offset = if is_reverse { index.genome.n_genome } else { 0 };
let mut n_mismatch = 0u32;
let mut read_pos = read_start;
let mut genome_pos = genome_start;
for op in cigar_ops {
match op.kind() {
Kind::Match | Kind::SequenceMatch | Kind::SequenceMismatch => {
for _i in 0..op.len() {
if read_pos < read_seq.len() {
let read_base = read_seq[read_pos];
if let Some(genome_base) = index.genome.get_base(genome_pos + genome_offset)
&& read_base != genome_base
&& read_base != 4
&& genome_base != 4
{
n_mismatch += 1;
}
}
read_pos += 1;
genome_pos += 1;
}
}
Kind::Insertion | Kind::SoftClip => {
read_pos += op.len();
}
Kind::Deletion | Kind::Skip => {
genome_pos += op.len() as u64;
}
Kind::HardClip | Kind::Pad => {}
}
}
n_mismatch
}
/// Result of extending an alignment into flanking regions
#[derive(Debug, Clone)]
struct ExtendResult {
/// How far the extension reached (bases)
extend_len: usize,
/// Maximum score achieved during extension
max_score: i32,
/// Number of mismatches in the extended region
n_mismatch: u32,
}
/// Extend alignment from a boundary into flanking sequence, mirroring STAR's extendAlign().
///
/// Walks base-by-base from the alignment boundary, scoring +1 match / -1 mismatch,
/// tracking the maximum-score extension point. Stops when total mismatches exceed
/// `min(p_mm_max * total_length, n_mm_max)`.
///
/// # Arguments
/// * `read_seq` - Full read sequence (encoded)
/// * `read_start` - Boundary position in read (where extension begins)
/// * `genome_start` - Corresponding genome position (WITHOUT n_genome offset)
/// * `direction` - +1 for rightward extension, -1 for leftward
/// * `max_extend` - Maximum distance to extend (to read boundary)
/// * `n_mm_prev` - Mismatches already in the aligned portion
/// * `len_prev` - Length of the already-aligned portion
/// * `n_mm_max` - outFilterMismatchNmax (absolute max mismatches)
/// * `p_mm_max` - outFilterMismatchNoverLmax (max mismatch ratio)
/// * `index` - Genome index
/// * `is_reverse` - Whether this is a reverse-strand alignment
#[allow(clippy::too_many_arguments)]
fn extend_alignment(
read_seq: &[u8],
read_start: usize,
genome_start: u64,
direction: i32,
max_extend: usize,
n_mm_prev: u32,
len_prev: usize,
n_mm_max: u32,
p_mm_max: f64,
index: &GenomeIndex,
is_reverse: bool,
) -> ExtendResult {
if max_extend == 0 {
return ExtendResult {
extend_len: 0,
max_score: 0,
n_mismatch: 0,
};
}
let genome_offset = if is_reverse { index.genome.n_genome } else { 0 };
let mut score: i32 = 0;
let mut max_score: i32 = 0;
let mut best_len: usize = 0;
let mut best_mm: u32 = 0;
let mut n_mm = 0u32;
for i in 0..max_extend {
// Calculate read and genome positions based on direction
let read_pos = if direction > 0 {
read_start + i
} else {
// Leftward: read_start is exclusive boundary, go backwards
if read_start < 1 + i {
break;
}
read_start - 1 - i
};
if read_pos >= read_seq.len() {
break;
}
let genome_pos = if direction > 0 {
genome_start + i as u64
} else {
if genome_start < 1 + i as u64 {
break;
}
genome_start - 1 - i as u64
};
// Get genome base (with strand offset)
let Some(genome_base) = index.genome.get_base(genome_pos + genome_offset) else {
break;
};
// Stop at chromosome boundary (padding = 5)
if genome_base == 5 {
break;
}
let read_base = read_seq[read_pos];
// Stop at PE fragment spacer base (STAR: MARK_FRAG_SPACER_BASE, extendAlign.cpp:63)
if read_base == PE_SPACER_BASE {
break;
}
// Skip N bases (no score impact, matches STAR behavior)
if read_base == 4 || genome_base == 4 {
continue;
}
if read_base == genome_base {
// MATCH — only record new max on match (STAR behavior)
score += 1;
if score > max_score {
let total_mm = n_mm_prev + n_mm;
// STAR uses double comparisons throughout (extendAlign.cpp)
let record_limit_f = (p_mm_max * (len_prev + i + 1) as f64).min(n_mm_max as f64);
if total_mm as f64 <= record_limit_f {
max_score = score;
best_len = i + 1;
best_mm = n_mm;
}
}
} else {
// MISMATCH — check break BEFORE incrementing nMM (STAR behavior)
// Break uses full extension length max_extend, not current position i+1
let total_mm = n_mm_prev + n_mm;
// STAR uses double comparisons throughout (extendAlign.cpp)
let break_limit_f =
(p_mm_max * (len_prev.saturating_add(max_extend)) as f64).min(n_mm_max as f64);
if total_mm as f64 >= break_limit_f {
break;
}
n_mm += 1;
score -= 1;
}
}
// Only accept extension if it has positive score
if max_score > 0 {
ExtendResult {
extend_len: best_len,
max_score,
n_mismatch: best_mm,
}
} else {
ExtendResult {
extend_len: 0,
max_score: 0,
n_mismatch: 0,
}
}
}
/// A Window Alignment entry — equivalent to STAR's WA[iW][iA] array.
///
/// Each entry represents one seed at one specific genome position within a window.
/// During seed assignment, verify_match_at_position() confirms the actual match length.
/// The DP reads these entries directly (no SA range re-expansion needed).
#[derive(Debug, Clone)]
pub struct WindowAlignment {
/// Index into the seeds array (for DP expansion to identify the originating seed)
pub seed_idx: usize,
/// Read start position (STAR: WA_rStart)
pub read_pos: usize,
/// Verified match length at this specific position (STAR: WA_Length)
pub length: usize,
/// Forward-strand genome position (STAR: WA_gStart)
pub genome_pos: u64,
/// Raw SA position (for genome base access in DP — reverse strand uses sa_pos + n_genome)
pub sa_pos: u64,
/// SA range size of the originating seed (STAR: WA_Nrep) — for scoring
pub n_rep: usize,
/// Whether this entry is an anchor (protected from capacity eviction)
pub is_anchor: bool,
/// Mate ID: 0=mate1, 1=mate2, 2=SE (STAR: PC[iP][PC_iFrag] / WA[iW][iS][WA_iFrag])
pub mate_id: u8,
/// Pre-computed extension score estimate (STAR: scoreSeedBest[iS] base case).
/// = length + left_ext_score + right_ext_score (in stitch coords, forward strand).
/// Computed in stitch_seeds_core after dedup/sort. Default: length as i32.
pub pre_ext_score: i32,
}
/// A cluster of seeds mapping to the same genomic region
#[derive(Debug, Clone)]
pub struct SeedCluster {
/// Window Alignment entries — seed positions assigned to this window (STAR's WA array)
pub alignments: Vec<WindowAlignment>,
/// Chromosome index
pub chr_idx: usize,
/// Genomic start (leftmost position, forward coords, from actual seed positions)
pub genome_start: u64,
/// Genomic end (rightmost position, forward coords, from actual seed positions)
pub genome_end: u64,
/// Strand (false = forward, true = reverse)
pub is_reverse: bool,
/// Anchor seed index (in the seeds array)
pub anchor_idx: usize,
/// Anchor genomic bin (anchor_pos >> win_bin_nbits) for MAPQ window counting
pub anchor_bin: u64,
}
/// Cluster seeds using STAR's bin-based windowing algorithm.
///
/// # Algorithm (faithful to STAR's `createExtendWindowsWithAlign` + `assignAlignToWindow`)
/// 1. Identify anchor seeds (SA range ≤ max_loci_for_anchor)
/// 2. Create windows from anchor positions using `winBin[(strand, bin)]` lookup:
/// - If bin already has a window → assign anchor to it, skip creation
/// - Else scan left/right for nearby windows → merge or create new
/// 3. Extend windows by ±win_flank_nbins on each side
/// 4. Assign ALL seeds to windows with overlap dedup + capacity eviction
/// 5. Build SeedCluster output
///
/// # Arguments
/// * `seeds` - All seeds found in the read
/// * `index` - Genome index
/// * `params` - Parameters (windowing params: winBinNbits, winAnchorDistNbins, winFlankNbins,
/// winAnchorMultimapNmax, seedPerWindowNmax, seedMapMin)
///
/// # Returns
/// Vector of seed clusters, one per window with assigned seeds
pub fn cluster_seeds(
seeds: &[Seed],
index: &GenomeIndex,
params: &crate::params::Parameters,
read_len: usize,
_debug: bool,
) -> Vec<SeedCluster> {
use std::collections::HashMap;
let win_bin_nbits = params.win_bin_nbits;
let win_anchor_dist_nbins = params.win_anchor_dist_nbins;
let win_flank_nbins = params.win_flank_nbins;
let max_loci_for_anchor = params.win_anchor_multimap_nmax;
let win_anchor_multimap_nmax = params.win_anchor_multimap_nmax;
let seed_per_window_nmax = params.seed_per_window_nmax;
let min_seed_length = params.seed_map_min;
let anchor_set: Vec<bool> = seeds
.iter()
.map(|seed| {
let n_loci = seed.sa_end - seed.sa_start;
n_loci > 0 && n_loci <= max_loci_for_anchor
})
.collect();
// Phase 1: Identify anchor seeds (few genomic positions → high specificity)
// STAR: only seeds with Nrep <= winAnchorMultimapNmax create windows.
let anchor_indices: Vec<usize> = anchor_set
.iter()
.enumerate()
.filter(|(_, is_anchor)| **is_anchor)
.map(|(i, _)| i)
.collect();
// No fallback: matches STAR behavior where reads with no anchors are unmapped.
// MMP search now narrows SA ranges from both ends (max_mappable_length),
// so seeds have accurate loci counts and anchor classification is correct.
if anchor_indices.is_empty() {
return Vec::new();
}
// Phase 2: Create windows from anchor positions
// (matches STAR's createExtendWindowsWithAlign)
struct Window {
bin_start: u64,
bin_end: u64,
chr_idx: usize,
is_reverse: bool,
anchor_idx: usize,
alignments: Vec<WindowAlignment>,
// Tight bounds from actual seed positions
actual_start: u64,
actual_end: u64,
alive: bool, // false = merged into another window (STAR kills merged windows)
// STAR's WALrec: persistent minimum non-anchor length threshold.
// Non-anchor seeds shorter than this are rejected early (before capacity check).
// Updated during capacity eviction. Matches STAR's assignAlignToWindow behavior.
wa_lrec: usize,
}
let mut windows: Vec<Window> = Vec::new();
// winBin: (strand, bin) → window_index
// Chromosome is implicit since bins are from absolute forward positions
let mut win_bin: HashMap<(bool, u64), usize> = HashMap::new();
for &anchor_idx in &anchor_indices {
let anchor = &seeds[anchor_idx];
let n_loci = anchor.sa_end - anchor.sa_start;
// Skip anchors with too many loci (STAR: winAnchorMultimapNmax)
if n_loci > win_anchor_multimap_nmax {
continue;
}
for (sa_pos, strand) in anchor.genome_positions(index) {
// STAR uses MMP length directly without per-position verification.
// All SA positions in the range match for the full MMP length by definition.
let length = anchor.length;
if length < min_seed_length {
continue;
}
let forward_pos = index.sa_pos_to_forward(sa_pos, strand, length);
let chr_idx = match index.genome.position_to_chr(forward_pos) {
Some(info) => info.0,
None => continue,
};
let anchor_bin = forward_pos >> win_bin_nbits;
// STAR's stitchPieces: Phase 1 creates windows from anchor positions
// but does NOT populate WA entries. After flank extension, nWA is reset
// to 0 (line 115), then Phase 3 re-assigns ALL seeds through
// assignAlignToWindow. We match this by not adding entries here.
// Check if this bin already has a window (STAR: skip creation, just assign)
if let Some(&win_idx) = win_bin.get(&(strand, anchor_bin)) {
let window = &mut windows[win_idx];
if window.alive && window.chr_idx == chr_idx {
window.actual_start = window.actual_start.min(forward_pos);
window.actual_end = window.actual_end.max(forward_pos + length as u64);
continue;
}
}
// Scan LEFT for existing window to merge with
let mut merge_left: Option<usize> = None;
for scan_bin in
(anchor_bin.saturating_sub(win_anchor_dist_nbins as u64)..anchor_bin).rev()
{
if let Some(&win_idx) = win_bin.get(&(strand, scan_bin)) {
let w = &windows[win_idx];
if w.alive && w.chr_idx == chr_idx {
merge_left = Some(win_idx);
break;
}
}
}
// Scan RIGHT for existing window to merge with
let mut merge_right: Option<usize> = None;
for scan_bin in (anchor_bin + 1)..=(anchor_bin + win_anchor_dist_nbins as u64) {
if let Some(&win_idx) = win_bin.get(&(strand, scan_bin)) {
let w = &windows[win_idx];
if w.alive && w.chr_idx == chr_idx {
merge_right = Some(win_idx);
break;
}
}
}
match (merge_left, merge_right) {
(Some(left_idx), Some(right_idx)) if left_idx != right_idx => {
// Merge both windows: extend left window to cover right + anchor
let right_window = &windows[right_idx];
let new_bin_end = right_window.bin_end.max(anchor_bin);
let new_actual_start = right_window.actual_start.min(forward_pos);
let new_actual_end = right_window.actual_end.max(forward_pos + length as u64);
// Kill right window
windows[right_idx].alive = false;
// Extend left window
let left_window = &mut windows[left_idx];
left_window.bin_start = left_window.bin_start.min(anchor_bin);
left_window.bin_end = left_window.bin_end.max(new_bin_end);
left_window.actual_start = left_window.actual_start.min(new_actual_start);
left_window.actual_end = left_window.actual_end.max(new_actual_end);
// Update winBin for all bins from left to right
for bin in left_window.bin_start..=left_window.bin_end {
win_bin.insert((strand, bin), left_idx);
}
}
(Some(idx), _) | (_, Some(idx)) => {
// Merge with one existing window
let window = &mut windows[idx];
window.bin_start = window.bin_start.min(anchor_bin);
window.bin_end = window.bin_end.max(anchor_bin);
window.actual_start = window.actual_start.min(forward_pos);
window.actual_end = window.actual_end.max(forward_pos + length as u64);
// Update winBin for newly covered bins
for bin in window.bin_start..=window.bin_end {
win_bin.insert((strand, bin), idx);
}
}
_ => {
// No merge: create new window
let new_idx = windows.len();
win_bin.insert((strand, anchor_bin), new_idx);
windows.push(Window {
bin_start: anchor_bin,
bin_end: anchor_bin,
chr_idx,
is_reverse: strand,
anchor_idx,
alignments: Vec::new(),
actual_start: forward_pos,
actual_end: forward_pos + length as u64,
alive: true,
wa_lrec: 0,
});
}
}
}
}
if windows.iter().all(|w| !w.alive) {
return Vec::new();
}
// Phase 3: Extend windows by ±win_flank_nbins (matches STAR's flanking extension)
// Update winBin for newly covered bins
for (win_idx, window) in windows.iter_mut().enumerate() {
if !window.alive {
continue;
}
let old_start = window.bin_start;
let old_end = window.bin_end;
let new_start = old_start.saturating_sub(win_flank_nbins as u64);
let new_end = old_end + win_flank_nbins as u64;
window.bin_start = new_start;
window.bin_end = new_end;
let strand = window.is_reverse;
for bin in new_start..old_start {
win_bin.entry((strand, bin)).or_insert(win_idx);
}
for bin in (old_end + 1)..=new_end {
win_bin.entry((strand, bin)).or_insert(win_idx);
}
}
// Phase 4: Assign ALL seeds to windows (matches STAR's stitchPieces Phase 3).
// STAR resets nWA=0 after window creation, then re-assigns ALL seeds (including
// anchors) through assignAlignToWindow. We match this by not pre-loading anchors
// in Phase 2 and processing all seeds here through the same capacity logic.
//
// STAR processes all pieces in a sorted pass (rStart asc, length desc for ties).
// This sorting ensures that when two seeds overlap on the same diagonal, the longer
// one enters the window first and blocks the shorter one via overlap detection —
// preventing window capacity overflow from many short copies on the same diagonal.
//
// We replicate this by: (1) collecting all candidates per window, (2) pre-deduping
// overlapping entries per diagonal (longest wins, shorter blocked before processing),
// then (3) processing survivors in original discovery order. This achieves the same
// overlap suppression without globally reordering seeds across windows.
// Per-window candidate entries collected before sorting.
struct WinCandidate {
seed_idx: usize,
sa_pos: u64,
forward_pos: u64,
length: usize,
n_loci: usize,
is_anchor: bool,
ps_rstart: usize, // positive-strand read start (sort key)
mate_id: u8, // STAR: iFrag (overlap dedup must respect fragment boundaries)
}
let mut win_candidates: Vec<Vec<WinCandidate>> =
(0..windows.len()).map(|_| Vec::new()).collect();
for (seed_idx, seed) in seeds.iter().enumerate() {
let n_loci = seed.sa_end - seed.sa_start;
if n_loci == 0 {
continue;
}
let is_anchor_seed = anchor_set[seed_idx];
for (sa_pos, strand) in seed.genome_positions(index) {
let length = seed.length;
if length < min_seed_length {
continue;
}
let forward_pos = index.sa_pos_to_forward(sa_pos, strand, length);
let chr_idx = match index.genome.position_to_chr(forward_pos) {
Some(info) => info.0,
None => {
continue;
}
};
let seed_bin = forward_pos >> win_bin_nbits;
let win_idx = match win_bin.get(&(strand, seed_bin)) {
Some(&idx) if windows[idx].alive && windows[idx].chr_idx == chr_idx => idx,
_ => {
continue;
}
};
let ps_rstart = if windows[win_idx].is_reverse {
read_len - (length + seed.read_pos)
} else {
seed.read_pos
};
win_candidates[win_idx].push(WinCandidate {
seed_idx,
sa_pos,
forward_pos,
length,
n_loci,
is_anchor: is_anchor_seed,
ps_rstart,
mate_id: seed.mate_id,
});
}
}
// Pre-dedup overlapping diagonals (order-independent, length wins):
// Two candidate entries on the same diagonal with overlapping read ranges represent
// the same alignment position — keep only the longest. This is what STAR achieves
// via sorted-order overlap detection (longer seed enters first, shorter blocked).
// Pre-computing this dedup ensures correct results regardless of discovery order,
// fixing window capacity overflow without changing capacity-eviction behavior
// for other reads (seeds on unique diagonals are unaffected).
//
// After pre-dedup, Phase 4 processes survivors in original discovery order.
// The overlap detection in the main Phase 4 loop below is still present but will
// never find an overlap (since pre-dedup already resolved all of them). It serves
// as a safety net for any edge cases not covered by pre-dedup.
let win_n = windows.len();
let mut win_blocked: Vec<Vec<bool>> = (0..win_n)
.map(|i| vec![false; win_candidates[i].len()])
.collect();
for win_idx in 0..win_n {
let candidates = &win_candidates[win_idx];
if candidates.is_empty() {
continue;
}
// Sort indices by length descending so that the longest entry per diagonal
// is processed first (and blocks shorter overlapping entries on the same diagonal).
let mut by_len: Vec<usize> = (0..candidates.len()).collect();
by_len.sort_by(|&a, &b| candidates[b].length.cmp(&candidates[a].length));
// For each (diagonal, mate_id) pair, track accepted [ps_rstart, ps_rend) ranges.
// STAR's assignAlignToWindow checks aFrag==WA[iA][WA_iFrag] before overlap test:
// seeds from different fragments are never treated as overlapping duplicates.
let mut diag_ranges: HashMap<(i64, u8), Vec<(usize, usize)>> = HashMap::new();
for &ci in &by_len {
let cand = &candidates[ci];
let diag = cand.forward_pos as i64 - cand.ps_rstart as i64;
let ps_rend = cand.ps_rstart + cand.length;
let key = (diag, cand.mate_id);
let blocked = diag_ranges.get(&key).is_some_and(|ranges| {
ranges.iter().any(|&(rs, re)| {
(cand.ps_rstart >= rs && cand.ps_rstart < re) || (ps_rend >= rs && ps_rend < re)
})
});
if blocked {
win_blocked[win_idx][ci] = true;
} else {
diag_ranges
.entry(key)
.or_default()
.push((cand.ps_rstart, ps_rend));
}
}
}
// Process each window's candidates in original discovery order,
// skipping pre-dedup-blocked entries.
let mut too_many_anchors = false; // STAR: MARKER_TOO_MANY_ANCHORS_PER_WINDOW
'outer: for win_idx in 0..win_n {
if !windows[win_idx].alive {
continue;
}
for (ci, cand) in win_candidates[win_idx].iter().enumerate() {
if win_blocked[win_idx][ci] {
continue; // blocked by a longer overlapping entry on same diagonal
}
let seed_idx = cand.seed_idx;
let seed = &seeds[seed_idx];
let length = cand.length;
let forward_pos = cand.forward_pos;
let sa_pos = cand.sa_pos;
let n_loci = cand.n_loci;
let is_anchor_seed = cand.is_anchor;
let new_ps_rstart = cand.ps_rstart;
let new_ps_rend = new_ps_rstart + length;
let window = &mut windows[win_idx];
// STAR's WALrec early rejection (assignAlignToWindow line 20):
// Non-anchor seeds shorter than the persistent minimum are rejected
// before overlap check. Uses strict < (not <=).
if !is_anchor_seed && length < window.wa_lrec {
continue;
}
// Safety-net overlap detection: after pre-dedup, no overlapping entries
// should remain. This check handles any edge cases and matches STAR's
// assignAlignToWindow overlap logic for correctness.
// STAR checks aFrag==WA[iA][WA_iFrag] before overlap test — seeds from
// different mate fragments are never merged.
let new_mate_id = cand.mate_id;
let new_diag = forward_pos as i64 - new_ps_rstart as i64;
let mut overlap_idx = None;
for (i, wa) in window.alignments.iter().enumerate() {
if wa.mate_id != new_mate_id {
continue; // STAR: only merge seeds from the same fragment
}
let wa_ps_rstart = if window.is_reverse {
read_len - (wa.length + wa.read_pos)
} else {
wa.read_pos
};
let wa_ps_rend = wa_ps_rstart + wa.length;
let wa_diag = wa.genome_pos as i64 - wa_ps_rstart as i64;
if new_diag == wa_diag
&& ((new_ps_rstart >= wa_ps_rstart && new_ps_rstart < wa_ps_rend)
|| (new_ps_rend >= wa_ps_rstart && new_ps_rend < wa_ps_rend))
{
overlap_idx = Some(i);
break;
}
}
if let Some(oi) = overlap_idx {
if length > window.alignments[oi].length {
window.alignments.remove(oi);
let insert_pos = window.alignments.partition_point(|wa| {
let wa_ps = if window.is_reverse {
read_len - (wa.length + wa.read_pos)
} else {
wa.read_pos
};
wa_ps < new_ps_rstart
});
window.alignments.insert(
insert_pos,
WindowAlignment {
seed_idx,
read_pos: seed.read_pos,
length,
genome_pos: forward_pos,
sa_pos,
n_rep: n_loci,
is_anchor: is_anchor_seed,
mate_id: seed.mate_id,
pre_ext_score: length as i32,
},
);
}
continue;
}
// Capacity check (seedPerWindowNmax) with anchor protection
if window.alignments.len() >= seed_per_window_nmax {
// Find min length of non-anchor entries (STAR: recalculate WALrec)
let min_non_anchor_len = window
.alignments
.iter()
.filter(|wa| !wa.is_anchor)
.map(|wa| wa.length)
.min()
.unwrap_or(usize::MAX);
// Update persistent threshold
window.wa_lrec = min_non_anchor_len;
// STAR uses strict < for rejection (not <=): entries equal to
// the minimum CAN enter and trigger eviction+replacement.
if length < min_non_anchor_len && !is_anchor_seed {
continue; // New entry too short
}
// Evict shortest non-anchor entries (STAR: WA_Length <= WALrec)
window
.alignments
.retain(|wa| wa.is_anchor || wa.length > min_non_anchor_len);
if window.alignments.len() >= seed_per_window_nmax {
// STAR: MARKER_TOO_MANY_ANCHORS_PER_WINDOW → nW=0, abort entire read
too_many_anchors = true;
break 'outer;
}
}
// STAR's addition condition: if (aAnchor || aLength > WALrec[iW])
// Non-anchor entries must be STRICTLY longer than wa_lrec to be added.
if !is_anchor_seed && length <= window.wa_lrec {
continue;
}
// Insert in sorted order by positive-strand read start (matches
// STAR's assignAlignToWindow lines 107-115 sorted insertion).
window.actual_start = window.actual_start.min(forward_pos);
window.actual_end = window.actual_end.max(forward_pos + length as u64);
let insert_pos = window.alignments.partition_point(|wa| {
let wa_ps = if window.is_reverse {
read_len - (wa.length + wa.read_pos)
} else {
wa.read_pos
};
wa_ps < new_ps_rstart
});
window.alignments.insert(
insert_pos,
WindowAlignment {
seed_idx,
read_pos: seed.read_pos,
length,
genome_pos: forward_pos,
sa_pos,
n_rep: n_loci,
is_anchor: is_anchor_seed,
mate_id: seed.mate_id,
pre_ext_score: length as i32,
},
);
}
}
// STAR: if any window hit MARKER_TOO_MANY_ANCHORS_PER_WINDOW, abort entire read
if too_many_anchors {
return Vec::new();
}
// Phase 5: Build SeedCluster output
let mut clusters = Vec::with_capacity(windows.len());
for window in &windows {
if !window.alive || window.alignments.is_empty() {
continue;
}
clusters.push(SeedCluster {
alignments: window.alignments.clone(),
chr_idx: window.chr_idx,
genome_start: window.actual_start,
genome_end: window.actual_end,
is_reverse: window.is_reverse,
anchor_idx: window.anchor_idx,
anchor_bin: window.bin_start,
});
}
clusters
}
/// Lightweight exon block for in-progress transcript during recursion
#[derive(Debug, Clone)]
pub(crate) struct ExonBlock {
pub(crate) read_start: usize, // 0-based inclusive
pub(crate) read_end: usize, // 0-based exclusive
pub(crate) genome_start: u64, // SA coordinate space (raw sa_pos)
pub(crate) genome_end: u64, // SA coordinate space (exclusive)
/// Mate ID: 0=mate1, 1=mate2, 2=SE (STAR: EX_iFrag)
pub(crate) mate_id: u8,
}
/// In-progress transcript during recursive search (cheap to clone)
#[derive(Debug, Clone)]
pub(crate) struct WorkingTranscript {
pub(crate) exons: Vec<ExonBlock>,
pub(crate) score: i32,
pub(crate) n_mismatch: u32,
pub(crate) n_gap: u32,
pub(crate) n_junction: u32,
pub(crate) junction_motifs: Vec<crate::align::score::SpliceMotif>,
pub(crate) junction_annotated: Vec<bool>,
/// Per-junction repeat lengths (jjL, jjR) for overhang check at finalization.
/// STAR's shiftSJ[isj][0] and shiftSJ[isj][1].
pub(crate) junction_shifts: Vec<(u32, u32)>,
pub(crate) n_anchor: u32,
// Tight bounds for extension at finalization
pub(crate) read_start: usize,
pub(crate) read_end: usize,
pub(crate) genome_start: u64,
pub(crate) genome_end: u64,
}
impl WorkingTranscript {
fn new() -> Self {
WorkingTranscript {
exons: Vec::new(),
score: 0,
n_mismatch: 0,
n_gap: 0,
n_junction: 0,
junction_motifs: Vec::new(),
junction_annotated: Vec::new(),
junction_shifts: Vec::new(),
n_anchor: 0,
read_start: 0,
read_end: 0,
genome_start: 0,
genome_end: 0,
}
}
}
/// Fill the gap between the last exon in a WorkingTranscript and the next WA entry.
/// Returns None if stitching fails (mismatch limit, overhang too short, etc.).
/// Matches STAR's stitchAlignToTranscript.cpp logic.
#[allow(clippy::too_many_arguments)]
fn stitch_align_to_transcript(
wt: &WorkingTranscript,
wa: &WindowAlignment,
read_seq: &[u8],
index: &GenomeIndex,
scorer: &AlignmentScorer,
cluster: &SeedCluster,
junction_db: Option<&crate::junction::SpliceJunctionDb>,
align_mates_gap_max: u64,
_debug_name: &str,
) -> Option<WorkingTranscript> {
let last_exon = wt.exons.last().unwrap();
// Mate-boundary detection: STAR canonSJ[iex] = -3 (stitchAlignToTranscript.cpp:402)
// When crossing from mate1 to mate2 (or vice versa), skip junction scoring and
// check alignMatesGapMax instead.
let last_mate = last_exon.mate_id;
let is_mate_boundary = wa.mate_id != last_mate && wa.mate_id != 2 && last_mate != 2;
if is_mate_boundary {
// STAR allows at most ONE mate-boundary crossing per combined PE transcript.
// stitchAlignToTranscript.cpp returns -1000007/-1000008 for the 3rd+ seed when
// mates overlap (genome positions interleaved), naturally limiting WTs to 2 exons.
// rustar-aligner's overlap-trimming allows continued stitching, inflating combined_n_match.
// Fix: if the WT already has exons from BOTH mates, a second crossing is invalid.
let has_m0 = wt.exons.iter().any(|e| e.mate_id == 0);
let has_m1 = wt.exons.iter().any(|e| e.mate_id == 1);
if has_m0 && has_m1 {
return None;
}
// STAR condition (stitchAlignToTranscript.cpp:352):
// gBstart + trA->exons[0][EX_R] + nBasesMax >= trA->exons[0][EX_G] || EX_G < EX_R
// For forward clusters: checked in forward genome space.
// For reverse clusters: checked in STAR's encoded genome space, then converted to
// rustar-aligner's forward-position representation (Phase 16.27 convention).
if cluster.is_reverse {
// Reverse cluster: stitch_read = RC(combined) = [mate2|SPACER|RC(mate1)].
// wt.exons[0] is the first mate2 exon; wa is the new mate1 seed.
// Recover mate1's position in the original combined read [mate1|SPACER|RC(mate2)]:
// combined_start_mate1 = combined_len - stitch_pos_mate1 - len_mate1
// STAR's encoded-space reject condition (converted to forward-position arithmetic):
// combined_start_mate1 < len_mate2_exon - len_mate1 + (P_mate2 - P_mate1)
let combined_start_mate1 =
(read_seq.len() as i64) - (wa.read_pos as i64) - (wa.length as i64);
let first_exon = &wt.exons[0];
let len_mate2_exon = (first_exon.read_end - first_exon.read_start) as i64;
let len_mate1 = wa.length as i64;
let p_diff = first_exon.genome_start as i64 - wa.sa_pos as i64; // P_mate2 - P_mate1