forked from scverse/rustar-aligner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_align.rs
More file actions
1843 lines (1684 loc) · 65.9 KB
/
read_align.rs
File metadata and controls
1843 lines (1684 loc) · 65.9 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::{cluster_seeds, stitch_seeds_with_jdb_debug};
use crate::align::transcript::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 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.
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,
}
/// 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());
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();
// 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
);
}
}
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: Detect chimeric alignments from soft-clips (Tier 1)
if params.chim_segment_min > 0 {
use crate::chimeric::ChimericDetector;
let detector = ChimericDetector::new(params);
for transcript in &transcripts {
if let Some(chim) =
detector.detect_from_soft_clips(transcript, read_seq, read_name, index)?
{
chimeric_alignments.push(chim);
}
}
}
// 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,
))
}
/// Align paired-end reads using per-mate independent seeding and pairwise cluster matching.
///
/// # Algorithm
/// 1. Seed mate1_seq and mate2_seq independently (correct Nstart per mate)
/// 2. Cluster each mate's seeds independently
/// 3. Stitch each mate's clusters independently via stitch_seeds_with_jdb
/// 4. Pair compatible transcripts (same chr, opposite strand, within alignMatesGapMax)
/// 5. Score-range filter → TooManyLoci check → dedup → quality filter
/// 6. If no pairs: rescue as HalfMapped using single-mate transcripts
///
/// # 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<(Vec<PairedAlignmentResult>, usize, Option<UnmappedReason>), 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)
};
// Per-mate seeding: each mate seeded with its own Nstart positions.
// mate2_seq (forward orientation) gives Nstart 0,37,74,112 in legitimate 5'-sequence,
// avoiding adapter-RC contamination that RC(mate2) seeds at positions 0,37,74 would hit.
// mate2 reverse-cluster transcripts (is_reverse=true) = mate2 on - strand (FR pairs).
// mate2 forward-cluster transcripts (is_reverse=false) = mate2 on + strand (RF pairs).
let s1 = Seed::find_seeds(mate1_seq, index, params.seed_map_min, params, "")?;
let s2 = Seed::find_seeds(mate2_seq, index, params.seed_map_min, params, "")?;
let mate1_clusters = cluster_seeds(&s1, index, params, len1);
let mate2_clusters = cluster_seeds(&s2, index, params, len2);
if debug_pe {
eprintln!(
"[DEBUG-PE] Per-mate: s1={} s2={} m1_clusters={} m2_clusters={}",
s1.len(),
s2.len(),
mate1_clusters.len(),
mate2_clusters.len()
);
for (i, c) in mate1_clusters.iter().enumerate() {
eprintln!(
" m1_cluster[{}]: rev={} chr={} seeds={}",
i,
c.is_reverse,
c.chr_idx,
c.alignments.len()
);
}
for (i, c) in mate2_clusters.iter().enumerate() {
eprintln!(
" m2_cluster[{}]: rev={} chr={} seeds={}",
i,
c.is_reverse,
c.chr_idx,
c.alignments.len()
);
}
}
// Stitch each mate's clusters independently.
// For mate2 reverse clusters: stitch_seeds_with_jdb internally uses RC(mate2_seq) as
// stitch_read and sets transcript.is_reverse=true + transcript.read_seq=mate2_seq.
// This correctly represents mate2 on - strand for FR pairs without explicit RC handling.
let debug_name: &str = if debug_pe { read_name } else { "" };
let mut mate1_transcripts: Vec<Transcript> = Vec::new();
for cluster in mate1_clusters
.iter()
.take(params.align_windows_per_read_nmax)
{
let ts = stitch_seeds_with_jdb_debug(
cluster,
mate1_seq,
index,
&scorer,
junction_db,
params.align_transcripts_per_window_nmax,
debug_name,
)?;
mate1_transcripts.extend(ts);
}
let mut mate2_transcripts: Vec<Transcript> = Vec::new();
for cluster in mate2_clusters
.iter()
.take(params.align_windows_per_read_nmax)
{
let ts = stitch_seeds_with_jdb_debug(
cluster,
mate2_seq,
index,
&scorer,
junction_db,
params.align_transcripts_per_window_nmax,
debug_name,
)?;
mate2_transcripts.extend(ts);
}
// Combined score threshold: use len1+len2 as denominator (matches STAR's combined Lread-1).
let combined_score_threshold =
(params.out_filter_score_min_over_lread * (len1 + len2) as f64) as i32;
// Pair compatible transcripts (opposite strand, same chr, within alignMatesGapMax)
let mut joint_pairs: Vec<PairedAlignment> = Vec::new();
for t1 in &mate1_transcripts {
for t2 in &mate2_transcripts {
if let Some(pair) =
try_pair_transcripts(t1, t2, len1, len2, params, combined_score_threshold)
{
joint_pairs.push(pair);
}
}
}
if debug_pe {
eprintln!(
"[DEBUG-PE] After pairing: pairs={} m1_ts={} m2_ts={}",
joint_pairs.len(),
mate1_transcripts.len(),
mate2_transcripts.len()
);
for (i, pa) in joint_pairs.iter().enumerate() {
eprintln!(
" pair[{}]: M1 chr={} pos={} rev={} score={} | M2 chr={} pos={} rev={} score={} | combined={}",
i,
pa.mate1_transcript.chr_idx,
pa.mate1_transcript.genome_start,
pa.mate1_transcript.is_reverse,
pa.mate1_transcript.score,
pa.mate2_transcript.chr_idx,
pa.mate2_transcript.genome_start,
pa.mate2_transcript.is_reverse,
pa.mate2_transcript.score,
pa.combined_wt_score
);
}
}
// --- Decision tree: score-filter, dedup, quality-filter, then half-mapped fallback ---
// Step 1: score-range filter (STAR's multMapSelect).
if !joint_pairs.is_empty() {
let best_score = joint_pairs
.iter()
.map(|pa| pa.combined_wt_score)
.max()
.unwrap_or(0);
let score_threshold = best_score - params.out_filter_multimap_score_range;
joint_pairs.retain(|pa| pa.combined_wt_score >= score_threshold);
}
// Step 2: TooManyLoci check using pre-dedup count.
if joint_pairs.len() > params.out_filter_multimap_nmax as usize {
return Ok((Vec::new(), 0, Some(UnmappedReason::TooManyLoci)));
}
// Step 3: position dedup — remove exact (chr, mate1_pos, mate2_pos, strand, CIGAR) duplicates.
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
&& a.mate2_transcript.is_reverse == b.mate2_transcript.is_reverse
&& a.mate2_transcript.cigar == b.mate2_transcript.cigar
});
// Post-finalization mate2-exon-subset dedup.
{
use crate::align::transcript::Exon;
let exons_subset = |b: &[Exon], a: &[Exon]| -> bool {
let total_b: u32 = b.iter().map(|e| (e.read_end - e.read_start) as u32).sum();
if total_b == 0 {
return false;
}
let mut covered = 0u32;
for be in b {
let b_diag = be.genome_start as i64 - be.read_start as i64;
for ae in a {
let a_diag = ae.genome_start as i64 - ae.read_start as i64;
if a_diag == b_diag {
let r_start = be.read_start.max(ae.read_start);
let r_end = be.read_end.min(ae.read_end);
if r_start < r_end {
covered += (r_end - r_start) as u32;
}
}
}
}
covered == total_b
};
let n = joint_pairs.len();
let mut keep = vec![true; n];
for i in 0..n {
if !keep[i] {
continue;
}
for j in 0..n {
if i == j || !keep[j] {
continue;
}
let same_pos = joint_pairs[i].mate1_transcript.chr_idx
== joint_pairs[j].mate1_transcript.chr_idx
&& joint_pairs[i].mate1_transcript.genome_start
== joint_pairs[j].mate1_transcript.genome_start
&& joint_pairs[i].mate1_transcript.genome_end
== joint_pairs[j].mate1_transcript.genome_end
&& joint_pairs[i].mate1_transcript.is_reverse
== joint_pairs[j].mate1_transcript.is_reverse
&& joint_pairs[i].mate2_transcript.genome_start
== joint_pairs[j].mate2_transcript.genome_start
&& joint_pairs[i].mate2_transcript.is_reverse
== joint_pairs[j].mate2_transcript.is_reverse;
if same_pos
&& joint_pairs[i].combined_wt_score < joint_pairs[j].combined_wt_score
&& exons_subset(
&joint_pairs[i].mate2_transcript.exons,
&joint_pairs[j].mate2_transcript.exons,
)
{
keep[i] = false;
break;
}
}
}
joint_pairs = joint_pairs
.into_iter()
.enumerate()
.filter(|(i, _)| keep[*i])
.map(|(_, p)| p)
.collect();
}
joint_pairs.sort_by(|a, b| {
b.combined_wt_score
.cmp(&a.combined_wt_score)
.then_with(|| a.mate1_transcript.chr_idx.cmp(&b.mate1_transcript.chr_idx))
.then_with(|| {
a.mate1_transcript
.genome_start
.cmp(&b.mate1_transcript.genome_start)
})
.then_with(|| {
a.mate1_transcript
.is_reverse
.cmp(&b.mate1_transcript.is_reverse)
})
});
// Randomize primary among best-scoring pairs (STAR's funPrimaryAlignMark).
shuffle_tied_prefix(
&mut joint_pairs,
|pa| pa.combined_wt_score,
per_read_seed(params.run_rng_seed, read_name),
);
// Step 4: quality filter (mappedFilter).
filter_paired_transcripts(&mut joint_pairs, params);
if !joint_pairs.is_empty() {
let pe_mapq_n = joint_pairs.len().max(1);
let results = joint_pairs
.into_iter()
.map(|pa| PairedAlignmentResult::BothMapped(Box::new(pa)))
.collect();
return Ok((results, pe_mapq_n, None));
}
// Half-mapped fallback: report the best-scoring single-mate transcript.
// Apply per-mate quality threshold (outFilterScoreMinOverLread * (len - 1)).
let thresh1 = ((params.out_filter_score_min_over_lread * (len1 as f64 - 1.0)) as i32)
.max(params.out_filter_score_min);
let thresh2 = ((params.out_filter_score_min_over_lread * (len2 as f64 - 1.0)) as i32)
.max(params.out_filter_score_min);
let best_m1 = mate1_transcripts
.into_iter()
.filter(|t| t.score >= thresh1)
.max_by_key(|t| t.score);
let best_m2 = mate2_transcripts
.into_iter()
.filter(|t| t.score >= thresh2)
.max_by_key(|t| t.score);
match (best_m1, best_m2) {
(Some(t1), None) => Ok((
vec![PairedAlignmentResult::HalfMapped {
mapped_transcript: t1,
mate1_is_mapped: true,
}],
1,
None,
)),
(None, Some(t2)) => Ok((
vec![PairedAlignmentResult::HalfMapped {
mapped_transcript: t2,
mate1_is_mapped: false,
}],
1,
None,
)),
(Some(t1), Some(t2)) => {
// Both have single-mate alignments but couldn't form a valid pair.
// Report the higher-scoring mate as half-mapped.
if t1.score >= t2.score {
Ok((
vec![PairedAlignmentResult::HalfMapped {
mapped_transcript: t1,
mate1_is_mapped: true,
}],
1,
None,
))
} else {
Ok((
vec![PairedAlignmentResult::HalfMapped {
mapped_transcript: t2,
mate1_is_mapped: false,
}],
1,
None,
))
}
}
(None, None) => Ok((Vec::new(), 0, Some(UnmappedReason::TooShort))),
}
}
/// Attempt to pair two per-mate transcripts into a PairedAlignment.
///
/// Returns `None` if the mates are incompatible (same strand, different chr, too far, etc.).
fn try_pair_transcripts(
t1: &Transcript,
t2: &Transcript,
len1: usize,
len2: usize,
params: &Parameters,
combined_score_threshold: i32,
) -> Option<PairedAlignment> {
// Must be same chromosome
if t1.chr_idx != t2.chr_idx {
return None;
}
// Must be opposite strands (FR or RF)
if t1.is_reverse == t2.is_reverse {
return None;
}
// Determine left mate (smaller genome_start) and right mate for distance/consistency checks
let (left, right) = if t1.genome_start <= t2.genome_start {
(t1, t2)
} else {
(t2, t1)
};
// Reject degenerate pairs (right ends before left starts → negative insert)
if right.genome_end <= left.genome_start {
return None;
}
// Genomic span check: use alignMatesGapMax if set, else fall back to win_bin_window_dist
// (STAR's effective limit when alignMatesGapMax=0 is the window distance ~589kb)
let span = right.genome_end - left.genome_start;
let max_span = if params.align_mates_gap_max > 0 {
params.align_mates_gap_max as u64
} else {
params.win_bin_window_dist()
};
if span > max_span {
return None;
}
// Combined score: sum of per-mate finalized scores (each already includes per-mate span penalty)
let combined_wt_score = t1.score + t2.score;
// SCORE-GATE: reject pairs where score is below the absolute floor
if combined_wt_score + params.out_filter_multimap_score_range < combined_score_threshold {
return None;
}
// Junction consistency in overlap region
if !pe_junctions_consistent(left, right) {
return None;