-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathread_align.rs
More file actions
2173 lines (1998 loc) · 78.3 KB
/
read_align.rs
File metadata and controls
2173 lines (1998 loc) · 78.3 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
/// Read alignment driver function
use crate::align::score::{AlignmentScorer, SpliceMotif};
use crate::align::seed::Seed;
use crate::align::stitch::{
PE_SPACER_BASE, cluster_seeds, finalize_transcript, split_combined_wt, stitch_seeds_core,
stitch_seeds_with_jdb_debug,
};
use crate::align::transcript::{Exon, Transcript};
use crate::error::Error;
use crate::index::GenomeIndex;
use crate::params::{IntronMotifFilter, IntronStrandFilter, Parameters};
use crate::stats::UnmappedReason;
use rand::{SeedableRng, rngs::StdRng, seq::SliceRandom};
use std::hash::{DefaultHasher, Hash, Hasher};
/// Derive a deterministic per-read RNG seed from `run_rng_seed` + the read name.
///
/// STAR seeds `std::mt19937` once per chunk/thread (`runRNGseed*(iChunk+1)`),
/// then advances the state sequentially per read. rustar-aligner parallelises per-read
/// via rayon, so we instead fold the read name into the seed — this keeps tie
/// breaks reproducible regardless of thread count while still honoring the
/// user's `--runRNGseed` value.
pub(crate) fn per_read_seed(run_rng_seed: u64, read_name: &str) -> u64 {
let mut hasher = DefaultHasher::new();
read_name.hash(&mut hasher);
run_rng_seed.wrapping_mul(hasher.finish().wrapping_add(1))
}
/// Shuffle the prefix of `items` whose `score_fn` equals the first element's score.
///
/// Mirrors STAR's `ReadAlign_multMapSelect` / `funPrimaryAlignMark`: best-scoring
/// alignments are randomized so primary selection (index 0) is not biased by
/// upstream sort order. Non-tied elements are left alone.
fn shuffle_tied_prefix<T>(items: &mut [T], score_fn: impl Fn(&T) -> i32, seed: u64) {
let Some(first) = items.first() else {
return;
};
let best = score_fn(first);
let tied = items.iter().take_while(|t| score_fn(t) == best).count();
if tied < 2 {
return;
}
items[..tied].shuffle(&mut StdRng::seed_from_u64(seed));
}
/// Result of aligning a single read: (transcripts, chimeric_alignments, n_for_mapq, unmapped_reason)
pub type AlignReadResult = (
Vec<Transcript>,
Vec<crate::chimeric::ChimericAlignment>,
usize,
Option<UnmappedReason>,
);
/// Paired-end alignment result
#[derive(Debug, Clone)]
pub struct PairedAlignment {
/// Transcript for mate1
pub mate1_transcript: Transcript,
/// Transcript for mate2
pub mate2_transcript: Transcript,
/// Read positions for mate1 in transcript (start, end)
pub mate1_region: (usize, usize),
/// Read positions for mate2 in transcript (start, end)
pub mate2_region: (usize, usize),
/// Whether this is a proper pair (same chr, concordant orientation, distance)
pub is_proper_pair: bool,
/// Signed insert size (TLEN) - genomic distance between mate starts
pub insert_size: i32,
/// Combined pair score: sum of per-mate finalized scores (each includes genomic length penalty).
/// Used for multi-mapper score-range ranking and mappedFilter quality check.
pub combined_wt_score: i32,
/// Combined coverage: sum of exon read spans from both mates.
/// Mirrors STAR's nMatch check in mappedFilter.
pub combined_n_match: u32,
}
impl PairedAlignment {
/// Build a STAR-style combined two-mate `Transcript` for transcriptome
/// projection.
///
/// Matches STAR's single-`Transcript`-per-pair model: mate1 exons with
/// `i_frag = 0`, then mate2 exons rewritten to `i_frag = 1`. Only
/// meaningful for pairs on the same chromosome and strand — both are
/// invariants of a `PairedAlignment` (checked in `try_pair_transcripts`).
///
/// The returned transcript's `cigar` is empty: transcriptome BAM
/// emission generates per-mate CIGARs from the split exon list rather
/// than consuming a combined one.
pub fn combined_transcript_for_projection(&self) -> Transcript {
let m1 = &self.mate1_transcript;
let m2 = &self.mate2_transcript;
let mut exons: Vec<Exon> = Vec::with_capacity(m1.exons.len() + m2.exons.len());
for e in &m1.exons {
let mut ee = e.clone();
ee.i_frag = 0;
exons.push(ee);
}
for e in &m2.exons {
let mut ee = e.clone();
ee.i_frag = 1;
exons.push(ee);
}
Transcript {
chr_idx: m1.chr_idx,
genome_start: m1.genome_start.min(m2.genome_start),
genome_end: m1.genome_end.max(m2.genome_end),
is_reverse: m1.is_reverse,
exons,
cigar: Vec::new(),
score: m1.score + m2.score,
n_mismatch: m1.n_mismatch + m2.n_mismatch,
n_gap: m1.n_gap + m2.n_gap,
n_junction: m1.n_junction + m2.n_junction,
junction_motifs: Vec::new(),
junction_annotated: Vec::new(),
read_seq: Vec::new(),
}
}
}
/// Result of paired-end alignment, covering all mapping outcomes.
#[derive(Debug, Clone)]
pub enum PairedAlignmentResult {
/// Both mates mapped and paired successfully
BothMapped(Box<PairedAlignment>),
/// Only one mate mapped; rescue failed or was not attempted for the other
HalfMapped {
/// Transcript of the mapped mate
mapped_transcript: Transcript,
/// true = mate1 is the mapped mate, false = mate2 is mapped
mate1_is_mapped: bool,
},
}
/// Align a read to the genome.
///
/// # Algorithm
/// 1. Find seeds (exact matches) using MMP search
/// 2. Cluster seeds by genomic proximity
/// 3. Stitch seeds within each cluster using DP
/// 4. Filter transcripts by quality thresholds
/// 5. Sort by score and limit to top N
/// 6. Detect chimeric alignments if enabled
///
/// # Arguments
/// * `read_seq` - Read sequence (encoded as 0=A, 1=C, 2=G, 3=T)
/// * `read_name` - Read name (needed for chimeric output)
/// * `index` - Genome index
/// * `params` - User parameters
///
/// # Returns
/// Tuple of (transcripts, chimeric alignments, n_for_mapq, unmapped_reason):
/// - transcripts: sorted by score (best first)
/// - chimeric alignments: sorted by score (best first)
/// - n_for_mapq: effective alignment count for MAPQ calculation (max of transcript count
/// and valid cluster count, to avoid undercounting from coordinate dedup on tandem repeats)
/// - unmapped_reason: `Some(reason)` if no alignments produced, `None` if mapped
pub fn align_read(
read_seq: &[u8],
read_name: &str,
index: &GenomeIndex,
params: &Parameters,
) -> Result<AlignReadResult, Error> {
let debug_read = !params.read_name_filter.is_empty() && read_name == params.read_name_filter;
// Step 1: Find seeds (seedMapMin from params)
let min_seed_length = params.seed_map_min;
let seeds = Seed::find_seeds(
read_seq,
index,
min_seed_length,
params,
if debug_read { read_name } else { "" },
)?;
if debug_read {
let total_positions: usize = seeds.iter().map(|s| s.sa_end - s.sa_start).sum();
eprintln!(
"[DEBUG {}] Seeds: {} seeds, {} total SA positions, read_len={}",
read_name,
seeds.len(),
total_positions,
read_seq.len()
);
let n_lr = seeds.iter().filter(|s| !s.search_rc).count();
let n_rl = seeds.iter().filter(|s| s.search_rc).count();
eprintln!(
" {} seeds total: {} L→R (sparse), {} R→L (sparse)",
seeds.len(),
n_lr,
n_rl
);
for (i, s) in seeds.iter().enumerate() {
let n_loci = s.sa_end - s.sa_start;
eprintln!(
" seed[{}]: read_pos={}, len={}, n_loci={}, search_rc={}, sa=[{},{})",
i, s.read_pos, s.length, n_loci, s.search_rc, s.sa_start, s.sa_end
);
}
}
if seeds.is_empty() {
if debug_read {
eprintln!("[DEBUG {}] No seeds found — unmapped", read_name);
}
return Ok((Vec::new(), Vec::new(), 0, Some(UnmappedReason::Other)));
}
// Step 2: Cluster seeds (STAR's bin-based windowing)
// seed_per_window_nmax capacity eviction is handled inside cluster_seeds()
let clusters = cluster_seeds(&seeds, index, params, read_seq.len(), debug_read);
if debug_read {
eprintln!(
"[DEBUG {}] Clusters: {} clusters",
read_name,
clusters.len()
);
for (i, cluster) in clusters.iter().enumerate() {
let chr_name = if cluster.chr_idx < index.genome.chr_name.len() {
&index.genome.chr_name[cluster.chr_idx]
} else {
"unknown"
};
eprintln!(
" cluster[{}]: chr={}, is_reverse={}, seeds={}, anchor_bin={}",
i,
chr_name,
cluster.is_reverse,
cluster.alignments.len(),
cluster.anchor_bin,
);
for (j, wa) in cluster.alignments.iter().enumerate() {
let chr_pos = wa.genome_pos.saturating_sub(
if cluster.chr_idx < index.genome.chr_start.len() {
index.genome.chr_start[cluster.chr_idx]
} else {
0
},
) + 1; // 1-based
eprintln!(
" wa[{}]: read_pos={}, len={}, genome_pos={} ({}:{}), n_rep={}, is_anchor={}",
j,
wa.read_pos,
wa.length,
wa.genome_pos,
chr_name,
chr_pos,
wa.n_rep,
wa.is_anchor
);
if j >= 5 {
eprintln!(
" ... ({} more WA entries)",
cluster.alignments.len() - j - 1
);
break;
}
}
}
}
if clusters.is_empty() {
if debug_read {
eprintln!("[DEBUG {}] No clusters — unmapped", read_name);
}
return Ok((Vec::new(), Vec::new(), 0, Some(UnmappedReason::Other)));
}
// Cap total clusters (alignWindowsPerReadNmax)
let mut clusters = clusters;
clusters.truncate(params.align_windows_per_read_nmax);
// NOTE: STAR's winReadCoverageRelativeMin filter is long-reads-only
// (#ifdef COMPILE_FOR_LONG_READS in stitchPieces.cpp). Standard STAR
// does NOT filter clusters by seed coverage. Removed to match STAR.
// Step 2b: Detect chimeric alignments from multi-cluster seeds (Tier 2)
let mut chimeric_alignments = Vec::new();
if params.chim_segment_min > 0 && clusters.len() > 1 {
use crate::chimeric::ChimericDetector;
let detector = ChimericDetector::new(params);
chimeric_alignments
.extend(detector.detect_from_multi_clusters(&clusters, read_seq, read_name, index)?);
}
// Step 3: Stitch seeds within each cluster
let scorer = AlignmentScorer::from_params(params);
let mut transcripts = Vec::new();
// Collect all raw (pre-dedup) transcripts for chimericDetectionOld (Tier 1).
let mut all_raw_transcripts: Vec<crate::align::transcript::Transcript> = Vec::new();
// Use junction DB for annotation-aware scoring if available
let junction_db = if index.junction_db.is_empty() {
None
} else {
Some(&index.junction_db)
};
for (ci, cluster) in clusters.iter().enumerate() {
let debug_name = if debug_read { read_name } else { "" };
let cluster_transcripts = stitch_seeds_with_jdb_debug(
cluster,
read_seq,
index,
&scorer,
junction_db,
params.align_transcripts_per_window_nmax,
debug_name,
)?;
if debug_read {
eprintln!(
"[DEBUG {}] Cluster[{}]: {} transcripts from DP",
read_name,
ci,
cluster_transcripts.len()
);
for (ti, t) in cluster_transcripts.iter().enumerate().take(5) {
let chr_name = if t.chr_idx < index.genome.chr_name.len() {
&index.genome.chr_name[t.chr_idx]
} else {
"unknown"
};
let cigar_str: String = t.cigar.iter().map(|op| format!("{}", op)).collect();
eprintln!(
" transcript[{}]: chr={}:{}-{} ({}) score={} mm={} junctions={} cigar={}",
ti,
chr_name,
t.genome_start,
t.genome_end,
if t.is_reverse { "-" } else { "+" },
t.score,
t.n_mismatch,
t.n_junction,
cigar_str
);
}
}
if params.chim_segment_min > 0 {
all_raw_transcripts.extend(cluster_transcripts.iter().cloned());
}
transcripts.extend(cluster_transcripts);
}
// Step 4a: Deduplicate and score-range filter — BEFORE quality filters.
// STAR order: multMapSelect (score-range) → mappedFilter (quality gates).
// Doing quality filters first is wrong: it can remove the high-scoring primary,
// leaving a lower-scoring secondary that then passes as the "best" alignment.
// Deduplicate transcripts with identical genomic coordinates AND CIGAR.
transcripts.sort_by(|a, b| {
(
a.chr_idx,
a.genome_start,
a.genome_end,
a.is_reverse,
&a.cigar,
)
.cmp(&(
b.chr_idx,
b.genome_start,
b.genome_end,
b.is_reverse,
&b.cigar,
))
.then_with(|| b.score.cmp(&a.score))
});
transcripts.dedup_by(|a, b| {
a.chr_idx == b.chr_idx
&& a.genome_start == b.genome_start
&& a.genome_end == b.genome_end
&& a.is_reverse == b.is_reverse
&& a.cigar == b.cigar
});
// Sort by score descending (deterministic tie-breaking).
transcripts.sort_by(|a, b| {
b.score
.cmp(&a.score)
.then_with(|| a.n_junction.cmp(&b.n_junction))
.then_with(|| a.chr_idx.cmp(&b.chr_idx))
.then_with(|| a.genome_start.cmp(&b.genome_start))
.then_with(|| a.is_reverse.cmp(&b.is_reverse))
});
// Randomize primary among best-scoring ties (ReadAlign_multMapSelect.cpp:71-79).
shuffle_tied_prefix(
&mut transcripts,
|t| t.score,
per_read_seed(params.run_rng_seed, read_name),
);
// Score-range filter: keep only alignments within outFilterMultimapScoreRange of the best.
// (STAR's multMapSelect step — must run before quality filters.)
if !transcripts.is_empty() {
let max_score = transcripts[0].score;
let score_threshold = max_score - params.out_filter_multimap_score_range;
transcripts.retain(|t| t.score >= score_threshold);
}
// Multimap count check: too many loci → unmapped.
if transcripts.len() > params.out_filter_multimap_nmax as usize {
let n_loci = transcripts.len();
transcripts.clear();
return Ok((
transcripts,
chimeric_alignments,
n_loci,
Some(UnmappedReason::TooManyLoci),
));
}
// Step 4: Quality filters (STAR's mappedFilter — runs after score-range selection).
// STAR uses (Lread-1) for relative thresholds and casts to integer
// (ReadAlign_mappedFilter.cpp lines 8-9)
let read_length = read_seq.len() as f64;
let lread_m1 = (read_seq.len() as f64) - 1.0;
// Log filtering statistics
let pre_filter_count = transcripts.len();
let mut filter_reasons = std::collections::HashMap::new();
transcripts.retain(|t| {
// Absolute score threshold
if t.score < params.out_filter_score_min {
*filter_reasons.entry("score_min").or_insert(0) += 1;
return false;
}
// Relative score threshold: STAR casts to intScore (i32)
if t.score < (params.out_filter_score_min_over_lread * lread_m1) as i32 {
*filter_reasons.entry("score_min_relative").or_insert(0) += 1;
return false;
}
// Absolute mismatch count
if t.n_mismatch > params.out_filter_mismatch_nmax {
*filter_reasons.entry("mismatch_max").or_insert(0) += 1;
log::debug!(
"Filtered {}: {} mismatches > {} max (read_len={}, score={})",
read_name,
t.n_mismatch,
params.out_filter_mismatch_nmax,
read_length,
t.score
);
return false;
}
// Relative mismatch count (mismatches / read_length)
let mismatch_rate = t.n_mismatch as f64 / read_length;
if mismatch_rate > params.out_filter_mismatch_nover_lmax {
*filter_reasons.entry("mismatch_rate").or_insert(0) += 1;
log::debug!(
"Filtered {}: {:.1}% mismatch rate > {:.1}% max ({}/{} bases, score={})",
read_name,
mismatch_rate * 100.0,
params.out_filter_mismatch_nover_lmax * 100.0,
t.n_mismatch,
read_length,
t.score
);
return false;
}
// Absolute matched bases
let n_matched = t.n_matched();
if n_matched < params.out_filter_match_nmin {
*filter_reasons.entry("match_min").or_insert(0) += 1;
return false;
}
// Relative matched bases: STAR casts to uint (u32)
if n_matched < (params.out_filter_match_nmin_over_lread * lread_m1) as u32 {
*filter_reasons.entry("match_min_relative").or_insert(0) += 1;
return false;
}
// Junction motif filtering
match params.out_filter_intron_motifs {
IntronMotifFilter::None => {
// Accept all motifs
}
IntronMotifFilter::RemoveNoncanonical => {
// Reject if any junction is non-canonical
if t.junction_motifs.contains(&SpliceMotif::NonCanonical) {
*filter_reasons.entry("noncanonical_junction").or_insert(0) += 1;
return false;
}
}
IntronMotifFilter::RemoveNoncanonicalUnannotated => {
// Only reject if a non-canonical junction is NOT annotated in GTF
if t.junction_motifs
.iter()
.zip(t.junction_annotated.iter())
.any(|(m, annotated)| *m == SpliceMotif::NonCanonical && !annotated)
{
*filter_reasons
.entry("noncanonical_unannotated_junction")
.or_insert(0) += 1;
return false;
}
}
}
// Intron strand consistency filtering (outFilterIntronStrands)
// STAR's RemoveInconsistentStrands removes transcripts that have junctions
// with mixed intron strand (some imply + strand, some imply - strand).
// This handles chimeric/impossible transcripts spanning both strands.
// Note: a reverse-strand read CAN have + strand motifs (antisense reads
// from + strand genes in unstranded RNA-seq) — this is valid and STAR
// keeps such reads. Only mixed-strand within one transcript is filtered.
if params.out_filter_intron_strands == IntronStrandFilter::RemoveInconsistentStrands {
let mut has_plus = false;
let mut has_minus = false;
for motif in &t.junction_motifs {
match motif.implied_strand() {
Some('+') => has_plus = true,
Some('-') => has_minus = true,
None => {}
_ => {}
}
}
if has_plus && has_minus {
*filter_reasons.entry("inconsistent_strand").or_insert(0) += 1;
return false;
}
}
true
});
// Log filtering summary if anything was filtered
if pre_filter_count > transcripts.len() {
let filtered = pre_filter_count - transcripts.len();
log::debug!(
"Read {}: Filtered {}/{} transcripts: {:?}",
read_name,
filtered,
pre_filter_count,
filter_reasons
);
}
if debug_read {
eprintln!(
"[DEBUG {}] After quality filters: {}/{} transcripts remain (reasons: {:?})",
read_name,
transcripts.len(),
pre_filter_count,
filter_reasons
);
}
// Step 3b: chimericDetectionOld (Tier 1) — STAR-faithful post-stitching transcript-pair search.
// Uses the best post-dedup transcript as the primary segment and searches all raw transcripts
// (pre-dedup, from all clusters) for the best complementary partner.
if params.chim_segment_min > 0
&& !all_raw_transcripts.is_empty()
&& let Some(tr_best) = transcripts.first()
{
use crate::chimeric::detect_chimeric_old;
let chims = detect_chimeric_old(
&all_raw_transcripts,
tr_best,
read_seq,
read_name,
params,
index,
)?;
chimeric_alignments.extend(chims);
}
// Step 3c: Soft-clip re-mapping (Phase 12.2) — try to align soft-clipped bases when
// detect_chimeric_old found no chimeric partner in the existing transcript pool.
if params.chim_segment_min > 0
&& chimeric_alignments.is_empty()
&& let Some(tr_best) = transcripts.first()
{
use crate::chimeric::ChimericDetector;
let detector = ChimericDetector::new(params);
if let Some(chim) = detector.detect_from_soft_clips(tr_best, read_seq, read_name, index)? {
chimeric_alignments.push(chim);
}
}
// Step 3d: Tier 3 — re-seed outer uncovered read regions of each chimeric pair (Phase 17.10).
// Extends 2-segment chimeras toward multi-junction fusions by seeding the read bases
// that lie outside both chimeric segments.
if params.chim_segment_min > 0 && !chimeric_alignments.is_empty() {
use crate::chimeric::ChimericDetector;
let detector = ChimericDetector::new(params);
let mut tier3 = Vec::new();
for chim in &chimeric_alignments {
let extras =
detector.detect_from_chimeric_residuals(chim, read_seq, read_name, index)?;
tier3.extend(extras);
}
chimeric_alignments.extend(tier3);
}
// Note: STAR sometimes finds 2 equivalent indel placements in homopolymer runs
// via its recursive stitcher's seed exploration (NH=2 instead of NH=1 for ~5 reads).
// Generating equivalents post-hoc causes more harm than good (41 false NH=2 vs 5 fixed).
// The root cause is jR scanning placing insertions at different positions — fixing that
// would be a better approach than post-hoc enumeration.
// Step 6: Filter chimeric alignments
if params.chim_segment_min > 0 {
chimeric_alignments.retain(|chim| {
chim.meets_min_segment_length(params.chim_segment_min)
&& chim.meets_min_score(params.chim_score_min)
});
}
// n_for_mapq = transcripts.len() after dedup and filtering.
// Multi-transcript DP (Phase 16.10) produces multiple transcripts per window
// for tandem repeats (e.g. rDNA), yielding correct NH → correct MAPQ.
let n_for_mapq = transcripts.len();
if debug_read {
eprintln!(
"[DEBUG {}] Final: {} transcripts, n_for_mapq={}",
read_name,
transcripts.len(),
n_for_mapq
);
for (i, t) in transcripts.iter().enumerate() {
let chr_name = if t.chr_idx < index.genome.chr_name.len() {
&index.genome.chr_name[t.chr_idx]
} else {
"unknown"
};
let cigar_str: String = t.cigar.iter().map(|op| format!("{}", op)).collect();
eprintln!(
" FINAL[{}]: chr={}:{}-{} ({}) score={} mm={} junctions={} cigar={}",
i,
chr_name,
t.genome_start,
t.genome_end,
if t.is_reverse { "-" } else { "+" },
t.score,
t.n_mismatch,
t.n_junction,
cigar_str
);
}
}
let unmapped_reason = if transcripts.is_empty() {
// Transcripts were generated by DP but all filtered out
Some(UnmappedReason::TooShort)
} else {
None
};
Ok((
transcripts,
chimeric_alignments,
n_for_mapq,
unmapped_reason,
))
}
type PairedAlignResult = (
Vec<PairedAlignmentResult>,
Vec<crate::chimeric::ChimericAlignment>,
usize,
Option<UnmappedReason>,
);
/// Align paired-end reads using STAR's combined-read approach.
///
/// # Algorithm
/// 1. Build combined read: [mate1_seq | PE_SPACER_BASE | RC(mate2_seq)]
/// 2. Seed each fragment (mate1_seq and RC(mate2_seq)) independently with per-fragment Nstart
/// 3. Tag seeds with mate_id (0=mate1, 1=mate2); adjust read_pos to combined-read coords
/// 4. Cluster and stitch combined seeds → WorkingTranscripts spanning both mates
/// 5. Split each WT by mate_id → finalize each half → pair
/// 6. Decision tree: dedup → score-range → TooManyLoci → quality filter
/// 7. Half-mapped fallback from single-mate WTs
///
/// # Arguments
/// * `mate1_seq` - First mate sequence (encoded)
/// * `mate2_seq` - Second mate sequence (encoded)
/// * `index` - Genome index
/// * `params` - Parameters (includes alignMatesGapMax)
///
/// # Returns
/// Tuple of (paired alignment results, n_for_mapq, unmapped_reason)
pub fn align_paired_read(
mate1_seq: &[u8],
mate2_seq: &[u8],
read_name: &str,
index: &GenomeIndex,
params: &Parameters,
) -> Result<PairedAlignResult, Error> {
let len1 = mate1_seq.len();
let len2 = mate2_seq.len();
let debug_pe = !params.read_name_filter.is_empty() && read_name == params.read_name_filter;
let scorer = AlignmentScorer::from_params(params);
let junction_db = if index.junction_db.is_empty() {
None
} else {
Some(&index.junction_db)
};
let debug_name: &str = if debug_pe { read_name } else { "" };
// Build combined read: [mate1_seq | PE_SPACER_BASE | RC(mate2_seq)]
// STAR ReadAlign_oneRead.cpp: Read1[0][readLength[0]] = MARK_FRAG_SPACER_BASE
let rc_mate2: Vec<u8> = mate2_seq
.iter()
.rev()
.map(|&b| if b < 4 { 3 - b } else { b })
.collect();
let mut combined_read = Vec::with_capacity(len1 + 1 + len2);
combined_read.extend_from_slice(mate1_seq);
combined_read.push(PE_SPACER_BASE);
combined_read.extend_from_slice(&rc_mate2);
let combined_len = combined_read.len();
// STAR-faithful per-fragment seeding: seed each mate fragment separately using
// the fragment length for Nstart/Lstart, then merge into combined_read coords.
// STAR uses qualitySplit() starting positions based on fragment length (e.g. 150bp
// → Nstart=4, Lstart=37, starts={0,37,74,111}), NOT the combined length (301bp
// → Nstart=7, starts={0,43,...,129,...}). Using combined length creates a spurious
// start at position 129 (between mates) that can produce anchors widening windows
// beyond STAR's range, causing window overflow and eviction of valid 7M exon seeds.
let mut combined_seeds = Seed::find_seeds(
&combined_read[..len1],
index,
params.seed_map_min,
params,
debug_name,
)?;
let mut m2_seeds = Seed::find_seeds(
&combined_read[len1 + 1..],
index,
params.seed_map_min,
params,
if debug_pe { debug_name } else { "" },
)?;
for s in &mut m2_seeds {
s.read_pos += len1 + 1;
}
combined_seeds.extend(m2_seeds);
// mate_id: positions 0..len1 → mate1(0); positions len1+1.. → RC(mate2)(1).
for s in &mut combined_seeds {
s.mate_id = u8::from(s.read_pos >= len1);
}
// Cluster combined seeds using the combined read length
let clusters = cluster_seeds(&combined_seeds, index, params, combined_len, debug_pe);
// PE chimeric pre-pass: intra-mate multi-cluster detection (Tier 2).
// Split clusters by mate_id and run per-mate chimeric detection, mirroring SE behavior.
let mut pe_chimeric: Vec<crate::chimeric::ChimericAlignment> = Vec::new();
if params.chim_segment_min > 0 && clusters.len() >= 2 {
use crate::chimeric::ChimericDetector;
let mate1_clusters: Vec<_> = clusters
.iter()
.filter(|c| c.alignments.iter().all(|wa| wa.mate_id == 0))
.cloned()
.collect();
// Mate2 clusters: adjust read_pos to be relative to mate2_seq (subtract len1+1)
let mate2_clusters: Vec<_> = clusters
.iter()
.filter(|c| c.alignments.iter().all(|wa| wa.mate_id == 1))
.map(|c| {
let mut c2 = c.clone();
for wa in &mut c2.alignments {
wa.read_pos -= len1 + 1;
}
c2
})
.collect();
let detector = ChimericDetector::new(params);
if mate1_clusters.len() >= 2 {
pe_chimeric.extend(detector.detect_from_multi_clusters(
&mate1_clusters,
mate1_seq,
read_name,
index,
)?);
}
if mate2_clusters.len() >= 2 {
pe_chimeric.extend(detector.detect_from_multi_clusters(
&mate2_clusters,
mate2_seq,
read_name,
index,
)?);
}
pe_chimeric.retain(|c| {
c.meets_min_segment_length(params.chim_segment_min)
&& c.meets_min_score(params.chim_score_min)
});
}
// Combined score threshold: use len1+len2 as denominator
let combined_score_threshold =
(params.out_filter_score_min_over_lread * (len1 + len2) as f64) as i32;
let mut joint_pairs: Vec<PairedAlignment> = Vec::new();
let mut single_mate1_transcripts: Vec<Transcript> = Vec::new();
let mut single_mate2_transcripts: Vec<Transcript> = Vec::new();
// All finalized mate transcripts (from both joint pairs and single-mate WTs) used
// as the search pool for chimericDetectionOld (Tier 1) on each mate independently.
let mut all_m1_transcripts: Vec<Transcript> = Vec::new();
let mut all_m2_transcripts: Vec<Transcript> = Vec::new();
// Stitch combined clusters, split WTs by mate_id, finalize each half
for cluster in clusters.iter().take(params.align_windows_per_read_nmax) {
let (wts, stitch_cluster, stitch_is_reverse, stitch_read) = stitch_seeds_core(
cluster,
&combined_read,
index,
&scorer,
junction_db,
params.align_transcripts_per_window_nmax,
params.align_mates_gap_max.into(),
debug_name,
)?;
for wt in &wts {
let split_result =
split_combined_wt(wt, len1, len2, stitch_is_reverse, scorer.align_intron_min);
if let Some((m1_wt, m2_wt)) = split_result {
let (m1_read_slice, m1_orig_rev, m2_read_slice, m2_orig_rev) = if stitch_is_reverse
{
// stitch_read = [mate2(0..len2) | SPACER | RC(mate1)(len2+1..)]
(
&stitch_read[len2 + 1..], // RC(mate1_seq)
true, // mate1 5' at right in RC
&stitch_read[..len2], // mate2_seq
false, // mate2 5' at left
)
} else {
// stitch_read = [mate1(0..len1) | SPACER | RC(mate2)(len1+1..)]
(
&stitch_read[..len1], // mate1_seq
false, // mate1 5' at left
&stitch_read[len1 + 1..], // RC(mate2_seq)
true, // mate2 5' at right in RC
)
};
// Suppress inner-side extensions for each mate.
// Inner = 3' end: right for forward (orig_is_rev=false), left for reverse.
let Some(mut t1) = finalize_transcript(
&m1_wt,
m1_read_slice,
index,
&scorer,
&stitch_cluster,
m1_orig_rev,
m1_orig_rev, // no_left_ext = inner for reverse (orig_is_rev=true)
!m1_orig_rev, // no_right_ext = inner for forward (orig_is_rev=false)
) else {
continue;
};
let Some(mut t2) = finalize_transcript(
&m2_wt,
m2_read_slice,
index,
&scorer,
&stitch_cluster,
m2_orig_rev,
m2_orig_rev, // no_left_ext = inner for reverse (orig_is_rev=true)
!m2_orig_rev, // no_right_ext = inner for forward (orig_is_rev=false)
) else {
continue;
};
if stitch_is_reverse {
t1.is_reverse = true;
t2.is_reverse = false;
} else {
t1.is_reverse = false;
t2.is_reverse = true;
}
t1.read_seq = mate1_seq.to_vec();
t2.read_seq = mate2_seq.to_vec();
if params.chim_segment_min > 0 {
all_m1_transcripts.push(t1.clone());
all_m2_transcripts.push(t2.clone());
}
let combined_span =
t1.genome_end.max(t2.genome_end) - t1.genome_start.min(t2.genome_start);
let combined_wt_score = wt.score + scorer.genomic_length_penalty(combined_span);
if let Some(pair) = try_pair_transcripts(
&t1,
&t2,
len1,
len2,
params,
combined_score_threshold,
combined_wt_score,
) {
joint_pairs.push(pair);
}
} else {
// Single-mate WT: save for half-mapped fallback
let all_m1 = wt.exons.iter().all(|e| e.mate_id == 0);
let all_m2 = wt.exons.iter().all(|e| e.mate_id == 1);
if all_m1 {
let (read_slice, orig_rev) = if stitch_is_reverse {
(&stitch_read[len2 + 1..], true)
} else {
(&stitch_read[..len1], false)
};
if let Some(mut t) = finalize_transcript(
wt,
read_slice,
index,
&scorer,
&stitch_cluster,
orig_rev,
false,
false,
) {
t.is_reverse = stitch_is_reverse;
t.read_seq = mate1_seq.to_vec();
if params.chim_segment_min > 0 {
all_m1_transcripts.push(t.clone());
}
single_mate1_transcripts.push(t);
}
} else if all_m2 {
let (read_slice, orig_rev) = if stitch_is_reverse {
(&stitch_read[..len2], false)
} else {
(&stitch_read[len1 + 1..], true)
};
if let Some(mut t) = finalize_transcript(
wt,
read_slice,
index,
&scorer,
&stitch_cluster,
orig_rev,
false,
false,
) {
t.is_reverse = !stitch_is_reverse;
t.read_seq = mate2_seq.to_vec();
if params.chim_segment_min > 0 {
all_m2_transcripts.push(t.clone());
}
single_mate2_transcripts.push(t);
}
}
}
}
}
// --- Decision tree: dedup, score-filter, quality-filter, then half-mapped fallback ---
// Step 1: position dedup — remove exact (chr, mate1_pos, mate2_pos, strand, CIGAR) duplicates.
// Run dedup BEFORE score-range filter so the backup pool is already deduplicated.
// (STAR's ordering is multMapSelect → dedup, but dedup before multMapSelect is equivalent
// since removing exact duplicates doesn't change the best score.)
joint_pairs.sort_by(|a, b| {
let pos_cmp = (
a.mate1_transcript.chr_idx,
a.mate1_transcript.genome_start,
a.mate1_transcript.is_reverse,
a.mate2_transcript.genome_start,
a.mate2_transcript.is_reverse,
)
.cmp(&(
b.mate1_transcript.chr_idx,
b.mate1_transcript.genome_start,
b.mate1_transcript.is_reverse,
b.mate2_transcript.genome_start,
b.mate2_transcript.is_reverse,
));
if pos_cmp != std::cmp::Ordering::Equal {
return pos_cmp;
}
b.combined_wt_score
.cmp(&a.combined_wt_score)
.then_with(|| a.mate1_transcript.cigar.cmp(&b.mate1_transcript.cigar))
.then_with(|| a.mate2_transcript.cigar.cmp(&b.mate2_transcript.cigar))
});
joint_pairs.dedup_by(|a, b| {
a.mate1_transcript.chr_idx == b.mate1_transcript.chr_idx
&& a.mate1_transcript.genome_start == b.mate1_transcript.genome_start
&& a.mate1_transcript.is_reverse == b.mate1_transcript.is_reverse
&& a.mate1_transcript.cigar == b.mate1_transcript.cigar
&& a.mate2_transcript.genome_start == b.mate2_transcript.genome_start