-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlib.rs
More file actions
1908 lines (1717 loc) · 70.4 KB
/
lib.rs
File metadata and controls
1908 lines (1717 loc) · 70.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod error;
pub mod params;
pub mod align;
pub mod chimeric;
pub mod cpu;
pub mod genome;
pub mod index;
pub mod io;
pub mod junction;
pub mod mapq;
pub mod quant;
pub mod stats;
use log::info;
use crate::params::{Parameters, RunMode};
/// Top-level dispatcher. Called from `main()` after CLI parsing.
pub fn run(params: &Parameters) -> anyhow::Result<()> {
params.validate()?;
info!("rustar-aligner {}", env!("CARGO_PKG_VERSION"));
info!("{}", env!("VERSION_BODY"));
info!("{}", cpu::cpu_detected_line());
if let Some(hint) = cpu::upgrade_hint() {
info!("{hint}");
}
info!("runMode: {}", params.run_mode);
info!("runThreadN: {}", params.run_thread_n);
match params.run_mode {
RunMode::GenomeGenerate => genome_generate(params),
RunMode::AlignReads => align_reads(params),
}
}
fn genome_generate(params: &Parameters) -> anyhow::Result<()> {
use index::GenomeIndex;
info!("genomeDir: {}", params.genome_dir.display());
info!(
"genomeFastaFiles: {:?}",
params
.genome_fasta_files
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
);
info!("Building genome index...");
let index = GenomeIndex::build(params)?;
info!("Writing index files to {}...", params.genome_dir.display());
index.write(¶ms.genome_dir, params)?;
info!("Genome generation complete!");
Ok(())
}
/// Trait for alignment output writers (SAM or BAM).
/// `finish` flushes/sorts/closes the output; default is a no-op for streaming writers.
trait AlignmentWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error>;
fn finish(&mut self) -> Result<(), error::Error> {
Ok(())
}
}
/// Null writer that discards all output (for two-pass mode pass 1)
struct NullWriter;
impl AlignmentWriter for NullWriter {
fn write_batch(
&mut self,
_batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
Ok(()) // Discard all records
}
}
impl AlignmentWriter for crate::io::sam::SamWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
}
impl AlignmentWriter for crate::io::bam::BamWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
fn finish(&mut self) -> Result<(), error::Error> {
self.finish()
}
}
impl AlignmentWriter for crate::io::bam::SortedBamWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
fn finish(&mut self) -> Result<(), error::Error> {
self.finish()
}
}
impl AlignmentWriter for crate::io::sam::SamStdoutWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
}
impl AlignmentWriter for crate::io::bam::BamStdoutWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
fn finish(&mut self) -> Result<(), error::Error> {
self.finish()
}
}
impl AlignmentWriter for crate::io::bam::SortedBamStdoutWriter {
fn write_batch(
&mut self,
batch: &[noodles::sam::alignment::record_buf::RecordBuf],
) -> Result<(), error::Error> {
self.write_batch(batch)
}
fn finish(&mut self) -> Result<(), error::Error> {
self.finish()
}
}
fn align_reads(params: &Parameters) -> anyhow::Result<()> {
use crate::index::GenomeIndex;
use crate::params::TwopassMode;
use std::sync::Arc;
let time_start = chrono::Local::now();
info!("Starting read alignment...");
// Configure Rayon thread pool based on --runThreadN
if params.run_thread_n > 1 {
rayon::ThreadPoolBuilder::new()
.num_threads(params.run_thread_n)
.build_global()
.map_err(|e| {
error::Error::Parameter(format!("Failed to configure thread pool: {}", e))
})?;
info!("Using {} threads for alignment", params.run_thread_n);
} else {
info!("Using single-threaded mode");
}
// Validate read files
if params.read_files_in.is_empty() {
anyhow::bail!("No read files specified (--readFilesIn)");
}
// 1. Load genome index
info!("Loading genome index from {}", params.genome_dir.display());
let index = Arc::new(GenomeIndex::load(¶ms.genome_dir, params)?);
info!(
"Loaded {} chromosomes, {} bases",
index.genome.n_chr_real, index.genome.n_genome
);
// Redefine window parameters based on genome size (STAR's Genome_genomeLoad.cpp)
let mut params = params.clone();
params.redefine_window_params(index.genome.n_genome);
// Build gene-count context if --quantMode GeneCounts was requested.
// GTF requirement is already validated in params.validate().
let quant_ctx: Option<std::sync::Arc<crate::quant::QuantContext>> =
if params.quant_gene_counts() {
let gtf_path = params.sjdb_gtf_file.as_ref().unwrap();
info!(
"quantMode GeneCounts: building gene annotation from {}",
gtf_path.display()
);
let ctx = crate::quant::QuantContext::build(
gtf_path,
&index.genome,
¶ms.sjdb_gtf_feature_exon,
¶ms.sjdb_gtf_chr_prefix,
¶ms.sjdb_gtf_tag_exon_parent_gene,
)?;
Some(std::sync::Arc::new(ctx))
} else {
None
};
// Use the transcriptome index loaded alongside the genome (populated
// from transcriptInfo.tab / exonInfo.tab / geneInfo.tab at load time
// — see GenomeIndex::load). Only wire it through to the pipeline when
// `--quantMode TranscriptomeSAM` is requested.
let tr_idx: Option<std::sync::Arc<crate::quant::transcriptome::TranscriptomeIndex>> =
if params.quant_transcriptome_sam() {
let tr = index.transcriptome.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"--quantMode TranscriptomeSAM requires a GTF-aware index; \
re-run genomeGenerate with --sjdbGTFfile or pass --sjdbGTFfile \
at alignReads so transcriptInfo.tab can be (re)built"
)
})?;
info!(
"quantMode TranscriptomeSAM: using {} transcripts from genome index",
tr.n_transcripts()
);
Some(std::sync::Arc::new(tr.clone()))
} else {
None
};
let time_map_start = chrono::Local::now();
// 2. Dispatch based on two-pass mode
let stats = match params.twopass_mode {
TwopassMode::None => {
info!("Running single-pass alignment");
run_single_pass(&index, ¶ms, quant_ctx.as_ref(), tr_idx.as_ref())?
}
TwopassMode::Basic => {
info!("Running two-pass alignment mode");
run_two_pass(&index, ¶ms, quant_ctx.as_ref(), tr_idx.as_ref())?
}
};
let time_finish = chrono::Local::now();
// Write Log.final.out
let log_path = params.out_file_name_prefix.join("Log.final.out");
if let Some(parent) = log_path.parent() {
std::fs::create_dir_all(parent)?;
}
stats.write_log_final(&log_path, time_start, time_map_start, time_finish)?;
info!("Wrote {}", log_path.display());
// Write ReadsPerGene.out.tab if quantMode GeneCounts was requested.
if let Some(ref ctx) = quant_ctx {
let quant_path = params.out_file_name_prefix.join("ReadsPerGene.out.tab");
ctx.counts.write_output(&quant_path, &ctx.gene_ann)?;
info!("Wrote {}", quant_path.display());
}
info!("Alignment complete!");
Ok(())
}
/// Run single-pass alignment (original logic)
fn run_single_pass(
index: &std::sync::Arc<crate::index::GenomeIndex>,
params: &Parameters,
quant_ctx: Option<&std::sync::Arc<crate::quant::QuantContext>>,
tr_idx: Option<&std::sync::Arc<crate::quant::transcriptome::TranscriptomeIndex>>,
) -> anyhow::Result<std::sync::Arc<crate::stats::AlignmentStats>> {
use crate::io::bam::{BamWriter, SortedBamWriter};
use crate::io::sam::SamWriter;
use crate::params::OutSamFormat;
use std::sync::Arc;
// Initialize statistics collectors
let stats = Arc::new(crate::stats::AlignmentStats::new());
let sj_stats = Arc::new(crate::junction::SpliceJunctionStats::new());
// Clone the quant Arc so each dispatch call can own a reference.
let quant = quant_ctx.map(Arc::clone);
let tr = tr_idx.map(Arc::clone);
// Open transcriptome BAM writer if requested.
let mut tr_writer: Option<BamWriter> = if let Some(tidx) = tr.as_ref() {
let path = params
.out_file_name_prefix
.join("Aligned.toTranscriptome.out.bam");
info!("Writing transcriptome BAM to {}", path.display());
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
Some(BamWriter::create_transcriptome(&path, tidx, params)?)
} else {
None
};
// Create unmapped FASTQ writers if --outReadsUnmapped Fastx
use crate::io::fastq::UnmappedFastqWriter;
use crate::params::OutReadsUnmapped;
let is_paired = params.read_files_in.len() == 2;
let mut unmapped_w1: Option<UnmappedFastqWriter> =
if params.out_reads_unmapped == OutReadsUnmapped::Fastx {
let path = params.out_file_name_prefix.join("Unmapped.out.mate1");
info!("Writing unmapped reads to {}", path.display());
Some(UnmappedFastqWriter::create(&path)?)
} else {
None
};
let mut unmapped_w2: Option<UnmappedFastqWriter> =
if params.out_reads_unmapped == OutReadsUnmapped::Fastx && is_paired {
let path = params.out_file_name_prefix.join("Unmapped.out.mate2");
info!("Writing unmapped mate2 reads to {}", path.display());
Some(UnmappedFastqWriter::create(&path)?)
} else {
None
};
// 4. Route to SAM or BAM output based on --outSAMtype / --outStd
use crate::params::{OutSamSortOrder, OutStd};
let out_type = params
.out_sam_type()
.map_err(|e| anyhow::anyhow!("Invalid --outSAMtype: {}", e))?;
// Build boxed writer — stdout takes precedence over file output.
let mut writer: Box<dyn AlignmentWriter> = match params.out_std {
OutStd::Sam => {
info!("Writing SAM to stdout (--outStd SAM)");
Box::new(crate::io::sam::SamStdoutWriter::create(
&index.genome,
params,
)?)
}
OutStd::BamUnsorted => {
info!("Writing unsorted BAM to stdout (--outStd BAM_Unsorted)");
Box::new(crate::io::bam::BamStdoutWriter::create(
&index.genome,
params,
)?)
}
OutStd::BamSortedByCoordinate => {
info!("Writing coordinate-sorted BAM to stdout (--outStd BAM_SortedByCoordinate)");
Box::new(crate::io::bam::SortedBamStdoutWriter::create(
&index.genome,
params,
)?)
}
OutStd::None => match out_type.format {
OutSamFormat::Sam => {
let output_path = params.out_file_name_prefix.join("Aligned.out.sam");
info!("Writing SAM to {}", output_path.display());
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
Box::new(SamWriter::create(&output_path, &index.genome, params)?)
}
OutSamFormat::Bam => {
let sorted = out_type.sort_order == Some(OutSamSortOrder::SortedByCoordinate);
let output_path = if sorted {
params
.out_file_name_prefix
.join("Aligned.sortedByCoord.out.bam")
} else {
params.out_file_name_prefix.join("Aligned.out.bam")
};
info!("Writing BAM to {}", output_path.display());
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
if sorted {
Box::new(SortedBamWriter::create(
&output_path,
&index.genome,
params,
)?)
} else {
Box::new(BamWriter::create(&output_path, &index.genome, params)?)
}
}
OutSamFormat::None => {
anyhow::bail!("Output format 'None' not yet implemented");
}
},
};
// Align reads through the boxed writer.
match params.read_files_in.len() {
1 => align_reads_single_end(
params,
index,
writer.as_mut(),
&stats,
&sj_stats,
quant.as_ref(),
tr.as_ref(),
tr_writer.as_mut(),
unmapped_w1.as_mut(),
),
2 => align_reads_paired_end(
params,
index,
writer.as_mut(),
&stats,
&sj_stats,
quant.as_ref(),
tr.as_ref(),
tr_writer.as_mut(),
unmapped_w1.as_mut(),
unmapped_w2.as_mut(),
),
n => anyhow::bail!("Invalid number of read files: {} (expected 1 or 2)", n),
}?;
writer.finish()?;
// Flush transcriptome BAM.
if let Some(ref mut w) = tr_writer {
w.finish()?;
}
// 5. Write SJ.out.tab file
let sj_output_path = params.out_file_name_prefix.join("SJ.out.tab");
if !sj_stats.is_empty() {
info!(
"Writing splice junction statistics to {}",
sj_output_path.display()
);
sj_stats.write_output(&sj_output_path, &index.genome, params)?;
}
// 6. Print summary
stats.print_summary();
Ok(stats)
}
/// Run two-pass alignment mode
fn run_two_pass(
index: &std::sync::Arc<crate::index::GenomeIndex>,
params: &Parameters,
quant_ctx: Option<&std::sync::Arc<crate::quant::QuantContext>>,
tr_idx: Option<&std::sync::Arc<crate::quant::transcriptome::TranscriptomeIndex>>,
) -> anyhow::Result<std::sync::Arc<crate::stats::AlignmentStats>> {
use std::sync::Arc;
// PASS 1: Junction discovery (no quant counting in pass 1)
info!("Two-pass mode: Pass 1 - Junction discovery");
let (sj_stats_pass1, novel_junctions) = run_pass1(index, params)?;
// Write SJ.pass1.out.tab
let pass1_path = params.out_file_name_prefix.join("SJ.pass1.out.tab");
// Create output directory if it doesn't exist
if let Some(parent) = pass1_path.parent() {
std::fs::create_dir_all(parent)?;
}
info!("Writing pass 1 junctions to {}", pass1_path.display());
sj_stats_pass1.write_output(&pass1_path, &index.genome, params)?;
info!(
"Pass 1 discovered {} novel junctions",
novel_junctions.len()
);
// Insert novel junctions into DB
let mut merged_index = (**index).clone();
merged_index
.junction_db
.insert_novel(novel_junctions.clone());
info!(
"Merged junction DB: {} total junctions",
merged_index.junction_db.len()
);
// PASS 2: Re-alignment with merged DB (quant counts happen here)
info!("Two-pass mode: Pass 2 - Re-alignment");
let stats = run_single_pass(&Arc::new(merged_index), params, quant_ctx, tr_idx)?;
Ok(stats)
}
/// Run pass 1 of two-pass mode (junction discovery)
fn run_pass1(
index: &std::sync::Arc<crate::index::GenomeIndex>,
params: &Parameters,
) -> anyhow::Result<(
crate::junction::SpliceJunctionStats,
Vec<(
crate::junction::NovelJunctionKey,
crate::junction::JunctionInfo,
)>,
)> {
use std::sync::Arc;
let stats = Arc::new(crate::stats::AlignmentStats::new());
let sj_stats = Arc::new(crate::junction::SpliceJunctionStats::new());
// Modify params to limit reads for pass 1
let mut params_pass1 = params.clone();
if params.twopass1_reads_n >= 0 {
params_pass1.read_map_number = params.twopass1_reads_n;
info!("Pass 1 will align {} reads", params.twopass1_reads_n);
} else {
info!("Pass 1 will align all reads");
}
// Create NullWriter (discard SAM/BAM output in pass 1)
let mut null_writer = NullWriter;
// Align reads (single-end or paired-end); no quant counting in pass 1
match params.read_files_in.len() {
1 => align_reads_single_end(
¶ms_pass1,
index,
&mut null_writer,
&stats,
&sj_stats,
None,
None,
None,
None,
)?,
2 => align_reads_paired_end(
¶ms_pass1,
index,
&mut null_writer,
&stats,
&sj_stats,
None,
None,
None,
None,
None,
)?,
n => anyhow::bail!("Invalid number of read files: {} (expected 1 or 2)", n),
}
info!("Pass 1 aligned {} reads", stats.total_reads());
// Filter novel junctions
let novel_junctions = crate::junction::filter_novel_junctions(&sj_stats, params);
// Return ownership of sj_stats
let sj_stats = Arc::try_unwrap(sj_stats).unwrap_or_else(|arc| (*arc).clone());
Ok((sj_stats, novel_junctions))
}
/// Reverse-complement an encoded read (A=0,C=1,G=2,T=3,N=4). Shared by the
/// SE and PE transcriptome builders for the STAR `Read1[2]` soft-clip path.
fn rc_encode(seq: &[u8]) -> Vec<u8> {
seq.iter()
.rev()
.map(|&b| crate::io::fastq::complement_base(b))
.collect()
}
/// Pick a random primary-hit index and compute the MAPQ for a set of
/// transcriptome projections. Shared by the SE and PE builders.
fn pick_primary_and_mapq(
n_alignments: usize,
n_for_mapq: usize,
read_name: &str,
params: &Parameters,
) -> (usize, u8) {
use crate::align::read_align::per_read_seed;
use crate::mapq::calculate_mapq;
use rand::{Rng, SeedableRng, rngs::StdRng};
let mut rng = StdRng::seed_from_u64(per_read_seed(params.run_rng_seed, read_name));
let primary_hit = rng.gen_range(0..n_alignments);
let mapq = calculate_mapq(n_alignments.max(n_for_mapq), params.out_sam_mapq_unique);
(primary_hit, mapq)
}
/// Per-read metadata for BySJout disk-buffered mode.
/// SAM records are written to a temp file; only small metadata stays in memory.
struct BySJReadMeta {
/// Number of SAM records written to the temp file for this read.
n_sam_records: u32,
/// Junction keys from primary alignment. Empty if unmapped or no junctions.
junction_keys: Vec<crate::junction::SjKey>,
/// Chimeric alignments — kept in memory because they're rare (~0.1% of reads).
chimeric_alns: Vec<crate::chimeric::ChimericAlignment>,
/// Transcriptome SAM records (kept in memory — optional feature).
transcriptome_records: Vec<noodles::sam::alignment::record_buf::RecordBuf>,
}
/// Helper struct to hold alignment results from parallel processing
struct AlignmentBatchResults {
sam_records: crate::io::sam::BufferedSamRecords,
chimeric_alns: Vec<crate::chimeric::ChimericAlignment>,
/// Junction keys from the primary (best) alignment for BySJout filtering.
/// Empty if unmapped or no junctions.
primary_junction_keys: Vec<crate::junction::SjKey>,
/// Transcriptome-space SAM records for `--quantMode TranscriptomeSAM`.
/// Empty unless that mode is enabled.
transcriptome_records: Vec<noodles::sam::alignment::record_buf::RecordBuf>,
/// Unmapped reads for `--outReadsUnmapped Fastx` (name, encoded_seq, qual).
/// mate1 file (also used for SE). Empty unless that mode is enabled.
unmapped_mate1: Vec<(String, Vec<u8>, Vec<u8>)>,
/// Unmapped mate2 reads (PE only). Empty unless outReadsUnmapped=Fastx.
unmapped_mate2: Vec<(String, Vec<u8>, Vec<u8>)>,
}
/// Build transcriptome-space records for a single-end read. Projects every
/// surviving genome-space alignment onto all compatible transcripts, picks one
/// projected alignment at random as the primary (seeded by `per_read_seed`),
/// and emits SAM records with the transcriptome header.
#[allow(clippy::too_many_arguments)]
fn build_transcriptome_records_se(
transcripts: &[crate::align::transcript::Transcript],
read_name: &str,
read_seq: &[u8],
read_qual: &[u8],
genome: &crate::genome::Genome,
tr_idx: &crate::quant::transcriptome::TranscriptomeIndex,
params: &Parameters,
n_for_mapq: usize,
) -> Result<Vec<noodles::sam::alignment::record_buf::RecordBuf>, error::Error> {
use crate::io::sam::SamWriter;
use crate::quant::transcriptome::filter_and_project;
if transcripts.is_empty() || tr_idx.n_transcripts() == 0 {
return Ok(Vec::new());
}
let mode = params.quant_transcriptome_sam_output;
let lread = read_seq.len() as u32;
// STAR passes the RC read to soft-clip extension on reverse-strand
// alignments (`Read1[2]`); we mirror that here.
let rc = rc_encode(read_seq);
let mut projected_all: Vec<crate::align::transcript::Transcript> = Vec::new();
for aln in transcripts {
let bases: &[u8] = if aln.is_reverse { &rc } else { read_seq };
projected_all.extend(filter_and_project(
aln, bases, genome, tr_idx, lread, mode, params,
));
}
if projected_all.is_empty() {
return Ok(Vec::new());
}
let (primary_hit, mapq) =
pick_primary_and_mapq(projected_all.len(), n_for_mapq, read_name, params);
SamWriter::build_transcriptome_records(
read_name,
read_seq,
read_qual,
&projected_all,
mapq,
params,
primary_hit,
)
}
/// Paired-end version of `build_transcriptome_records_se`.
///
/// For each `PairedAlignment`, project mate1 and mate2 onto all transcripts
/// and keep only transcripts where both mates project successfully. Emit one
/// SAM record per projected pair per mate (2 records per projected hit, in
/// mate1-then-mate2 order).
#[allow(clippy::too_many_arguments)]
fn build_transcriptome_records_pe<'a, I>(
both_mapped: I,
read_name: &str,
m1_seq: &[u8],
m1_qual: &[u8],
m2_seq: &[u8],
m2_qual: &[u8],
genome: &crate::genome::Genome,
tr_idx: &crate::quant::transcriptome::TranscriptomeIndex,
params: &Parameters,
n_for_mapq: usize,
) -> Result<Vec<noodles::sam::alignment::record_buf::RecordBuf>, error::Error>
where
I: IntoIterator<Item = &'a crate::align::read_align::PairedAlignment>,
{
use crate::io::sam::SamWriter;
use crate::quant::transcriptome::filter_and_project;
use std::collections::HashMap;
if tr_idx.n_transcripts() == 0 {
return Ok(Vec::new());
}
let mode = params.quant_transcriptome_sam_output;
let lread1 = m1_seq.len() as u32;
let lread2 = m2_seq.len() as u32;
let m1_rc = rc_encode(m1_seq);
let m2_rc = rc_encode(m2_seq);
// For each both-mapped pair, project each mate onto transcripts and pair
// up projections that land on the same transcript.
let mut all_projected: Vec<(
crate::align::transcript::Transcript,
crate::align::transcript::Transcript,
)> = Vec::new();
for pair in both_mapped {
let m1 = &pair.mate1_transcript;
let m2 = &pair.mate2_transcript;
let m1_bases: &[u8] = if m1.is_reverse { &m1_rc } else { m1_seq };
let m2_bases: &[u8] = if m2.is_reverse { &m2_rc } else { m2_seq };
let proj_m1 = filter_and_project(m1, m1_bases, genome, tr_idx, lread1, mode, params);
let proj_m2 = filter_and_project(m2, m2_bases, genome, tr_idx, lread2, mode, params);
let mut by_tr1: HashMap<usize, Vec<&crate::align::transcript::Transcript>> = HashMap::new();
for p in &proj_m1 {
by_tr1.entry(p.chr_idx).or_default().push(p);
}
for p2 in &proj_m2 {
if let Some(p1s) = by_tr1.get(&p2.chr_idx) {
for p1 in p1s {
all_projected.push(((*p1).clone(), p2.clone()));
}
}
}
}
if all_projected.is_empty() {
return Ok(Vec::new());
}
let n_alignments = all_projected.len();
let (primary_hit, mapq) = pick_primary_and_mapq(n_alignments, n_for_mapq, read_name, params);
// Build one record per mate per projected pair in a single call each,
// then stamp paired flags and interleave as mate1, mate2, mate1, mate2…
let (p1s, p2s): (Vec<_>, Vec<_>) = all_projected.into_iter().unzip();
let mut rec1s = SamWriter::build_transcriptome_records(
read_name,
m1_seq,
m1_qual,
&p1s,
mapq,
params,
primary_hit,
)?;
let mut rec2s = SamWriter::build_transcriptome_records(
read_name,
m2_seq,
m2_qual,
&p2s,
mapq,
params,
primary_hit,
)?;
use noodles::sam::alignment::record::Flags;
for r in rec1s.iter_mut() {
*r.flags_mut() |= Flags::SEGMENTED | Flags::FIRST_SEGMENT;
}
for r in rec2s.iter_mut() {
*r.flags_mut() |= Flags::SEGMENTED | Flags::LAST_SEGMENT;
}
let mut out: Vec<noodles::sam::alignment::record_buf::RecordBuf> =
Vec::with_capacity(n_alignments * 2);
for (r1, r2) in rec1s.into_iter().zip(rec2s) {
out.push(r1);
out.push(r2);
}
Ok(out)
}
/// Extract SjKey junction identifiers from a transcript's CIGAR.
/// Used to check if a read's junctions survive outSJfilter* for BySJout mode.
fn extract_junction_keys(
transcript: &crate::align::transcript::Transcript,
index: &crate::index::GenomeIndex,
) -> Vec<crate::junction::SjKey> {
use crate::align::score::AlignmentScorer;
use crate::align::transcript::CigarOp;
let scorer = AlignmentScorer::from_params_minimal();
let mut keys = Vec::new();
let mut genome_pos = transcript.genome_start;
for op in &transcript.cigar {
match op {
CigarOp::RefSkip(len) => {
let intron_len = *len;
let intron_start = genome_pos + 1;
let intron_end = genome_pos + intron_len as u64;
let motif = scorer.detect_splice_motif(genome_pos, intron_len, &index.genome);
let strand = match motif.implied_strand() {
Some('+') => 1u8,
Some('-') => 2u8,
_ => 0u8,
};
let encoded_motif = crate::junction::encode_motif(motif);
keys.push(crate::junction::SjKey {
chr_idx: transcript.chr_idx,
intron_start,
intron_end,
strand,
motif: encoded_motif,
});
genome_pos += intron_len as u64;
}
CigarOp::Match(len) | CigarOp::Equal(len) | CigarOp::Diff(len) => {
genome_pos += *len as u64;
}
CigarOp::Del(len) => {
genome_pos += *len as u64;
}
CigarOp::Ins(_) | CigarOp::SoftClip(_) | CigarOp::HardClip(_) => {}
}
}
keys
}
/// Align single-end reads
#[allow(clippy::too_many_arguments)]
fn align_reads_single_end<W: AlignmentWriter + ?Sized>(
params: &Parameters,
index: &std::sync::Arc<crate::index::GenomeIndex>,
writer: &mut W,
stats: &std::sync::Arc<crate::stats::AlignmentStats>,
sj_stats: &std::sync::Arc<crate::junction::SpliceJunctionStats>,
quant_ctx: Option<&std::sync::Arc<crate::quant::QuantContext>>,
tr_idx: Option<&std::sync::Arc<crate::quant::transcriptome::TranscriptomeIndex>>,
mut tr_writer: Option<&mut crate::io::bam::BamWriter>,
mut unmapped_writer: Option<&mut crate::io::fastq::UnmappedFastqWriter>,
) -> anyhow::Result<()> {
use crate::align::read_align::align_read;
use crate::io::fastq::{FastqReader, clip_read};
use crate::io::sam::{BufferedSamRecords, SamWriter};
use crate::params::OutFilterType;
use rayon::prelude::*;
use std::sync::Arc;
let quant = quant_ctx.map(Arc::clone);
let tr = tr_idx.map(Arc::clone);
let read_file = ¶ms.read_files_in[0];
info!("Reading single-end from {}", read_file.display());
let mut reader = FastqReader::open(read_file, params.read_files_command.as_deref())?;
// Create chimeric output writer if enabled
let mut chimeric_writer = if params.chim_segment_min > 0 && params.chim_out_junctions() {
use crate::chimeric::ChimericJunctionWriter;
let prefix = params.out_file_name_prefix.to_str().unwrap_or(".");
info!(
"Chimeric detection enabled (chimSegmentMin={})",
params.chim_segment_min
);
Some(ChimericJunctionWriter::new(prefix)?)
} else {
None
};
let stats = Arc::clone(stats);
let sj_stats = Arc::clone(sj_stats);
let mut read_count = 0u64;
let max_reads = if params.read_map_number < 0 {
u64::MAX
} else {
params.read_map_number as u64
};
let batch_size = 10000;
let clip5p = params.clip5p_nbases as usize;
let clip3p = params.clip3p_nbases as usize;
let max_multimaps = params.out_filter_multimap_nmax as usize;
let output_unmapped = params.out_sam_unmapped != params::OutSamUnmapped::None;
let write_unmapped_fastq = params.out_reads_unmapped == params::OutReadsUnmapped::Fastx;
let by_sjout = params.out_filter_type == OutFilterType::BySJout;
let rg_id_owned = params.primary_rg_id()?;
// BySJout disk buffer: SAM records written to a temp file; only compact metadata kept in RAM.
// For 100M reads this avoids ~60 GB of Vec<RecordBuf> in memory.
let bysj_temp = if by_sjout {
info!("outFilterType=BySJout: disk-buffering reads for post-alignment junction filtering");
let tf = tempfile::NamedTempFile::new()
.map_err(|e| anyhow::anyhow!("BySJout: failed to create temp file: {}", e))?;
Some(tf)
} else {
None
};
let (bysj_sam_header, mut bysj_temp_writer) = if let Some(ref tf) = bysj_temp {
let write_file = tf
.reopen()
.map_err(|e| anyhow::anyhow!("BySJout: temp file reopen error: {}", e))?;
let (hdr, w) = crate::io::sam::create_bysj_writer(write_file, &index.genome, params)?;
(Some(hdr), Some(w))
} else {
(None, None)
};
let mut bysj_meta: Vec<BySJReadMeta> = Vec::new();
info!("Aligning reads...");
loop {
// Sequential FASTQ reading (unavoidable bottleneck)
let batch = reader.read_batch(batch_size)?;
if batch.is_empty() {
break;
}
// Check max reads limit
let reads_to_process = if read_count + batch.len() as u64 > max_reads {
(max_reads - read_count) as usize
} else {
batch.len()
};
let batch_to_process = &batch[..reads_to_process];
// Parallel alignment processing
let batch_results: Vec<Result<AlignmentBatchResults, error::Error>> = batch_to_process
.par_iter()
.map(|read| {
#[allow(clippy::needless_borrow)]
let index = Arc::clone(&index);
#[allow(clippy::needless_borrow)]
let stats = Arc::clone(&stats);
#[allow(clippy::needless_borrow)]
let sj_stats = Arc::clone(&sj_stats);
let quant = quant.as_ref().map(Arc::clone);
// Apply clipping
let (clipped_seq, clipped_qual) =
clip_read(&read.sequence, &read.quality, clip5p, clip3p);
let mut buffer = BufferedSamRecords::new();
let mut chimeric_alns = Vec::new();
let tr_local = tr.as_ref().map(Arc::clone);
// Record read bases for Log.final.out
stats.record_read_bases(clipped_seq.len() as u64);
// Skip if read is too short after clipping
if clipped_seq.is_empty() {
stats.record_alignment(0, max_multimaps);
stats.record_unmapped_reason(crate::stats::UnmappedReason::Other);
if let Some(ref q) = quant {
q.counts.count_se_read(&[], 0, &q.gene_ann);
}
if output_unmapped {
let record = SamWriter::build_unmapped_record(
&read.name,
&clipped_seq,
&clipped_qual,
rg_id_owned.as_deref(),
)?;
buffer.push(record);
}
let unmapped_m1 = if write_unmapped_fastq {
vec![(read.name.clone(), clipped_seq.clone(), clipped_qual.clone())]
} else {
Vec::new()
};
return Ok(AlignmentBatchResults {
sam_records: buffer,
chimeric_alns,
primary_junction_keys: Vec::new(),
transcriptome_records: Vec::new(),
unmapped_mate1: unmapped_m1,
unmapped_mate2: Vec::new(),
});
}
// Align read (CPU-intensive, pure function)
let (transcripts, chimeric_results, n_for_mapq, unmapped_reason) =
align_read(&clipped_seq, &read.name, &index, params)?;
// Collect chimeric alignments if enabled
if params.chim_segment_min > 0 {
chimeric_alns.extend(chimeric_results);
if !chimeric_alns.is_empty() {
stats.record_chimeric();
}
}
// Record stats (atomic, lock-free)
// For too-many-loci, n_for_mapq carries the true loci count
// while transcripts is empty
let n_for_stats = if transcripts.is_empty() && n_for_mapq > 0 {
n_for_mapq // too-many-loci: use true count for stats
} else {
transcripts.len()
};
stats.record_alignment(n_for_stats, max_multimaps);
if transcripts.is_empty() && unmapped_reason.is_some() {