-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.rs
1654 lines (1428 loc) · 55 KB
/
main.rs
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
// Copyright (c) 2020 10x Genomics, Inc. All rights reserved.
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::create_dir;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::panic;
use std::path::{Path, PathBuf};
use std::str;
use std::str::FromStr;
use anyhow::{anyhow, Context, Error};
use docopt::Docopt;
use flate2::write::GzEncoder;
use itertools::Itertools;
use regex::Regex;
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use rust_htslib::bam::record::{Aux, Record};
use rust_htslib::bam::{self, Read};
use shardio::helper::ThreadProxyWriter;
use shardio::SortKey;
use shardio::{ShardReader, ShardWriter};
mod bx_index;
mod locus;
mod rpcache;
#[cfg(test)]
mod fastq_reader;
use bx_index::BxListIter;
use rpcache::RpCache;
const VERSION: &str = env!("CARGO_PKG_VERSION");
const USAGE: &str = "
10x Genomics BAM to FASTQ converter.
Tool for converting 10x BAMs produced by Cell Ranger or Long Ranger back to
FASTQ files that can be used as inputs to re-run analysis. The FASTQ files
emitted by the tool should contain the same set of sequences that were
input to the original pipeline run, although the order will not be
preserved. The FASTQs will be emitted into a directory structure that is
compatible with the directories created by the 'mkfastq' tool.
10x BAMs produced by Long Ranger v2.1+ and Cell Ranger v1.2+ contain header
fields that permit automatic conversion to the correct FASTQ sequences.
Older 10x pipelines require one of the arguments listed below to indicate
which pipeline created the BAM.
NOTE: BAMs created by non-10x pipelines are unlikely to work correctly,
unless all the relevant tags have been recreated.
NOTE: BAM produced by the BASIC and ALIGNER pipeline from Long Ranger 2.1.2 and earlier
are not compatible with bamtofastq
NOTE: BAM files created by CR < 1.3 do not have @RG headers, so bamtofastq will use the GEM well
annotations attached to the CB (cell barcode) tag to split data from multiple input libraries.
Reads without a valid barcode do not carry the CB tag and will be dropped. These reads would
not be included in any valid cell.
Usage:
bamtofastq [options] <bam> <output-path>
bamtofastq (-h | --help)
Options:
--nthreads=<n> Threads to use for reading BAM file [default: 4]
--locus=<locus> Optional. Only include read pairs mapping to locus. Use chrom:start-end format.
--reads-per-fastq=N Number of reads per FASTQ chunk [default: 50000000]
--relaxed Skip unpaired or duplicated reads instead of throwing an error.
--gemcode Convert a BAM produced from GemCode data (Longranger 1.0 - 1.3)
--lr20 Convert a BAM produced by Longranger 2.0
--cr11 Convert a BAM produced by Cell Ranger 1.0-1.1
--bx-list=L Only include BX values listed in text file L. Requires BX-sorted and index BAM file (see Long Ranger support for details).
--traceback Print full traceback if an error occurs.
-h --help Show this screen.
";
/*
== Dev Notes ==
This code has bunch of special cases to workaround deficiences of the BAM files produced by older pipelines,
before we started enforcing the notion that BAM files should be easily convertible back to the original
FASTQ data that was input. Once these older pipelines & chemistries are out of service, the code could
be made considerably simpler.
1) Workaround for CR < 1.3: there are no RG headers or RG tags, so we can't accurately get back to
per-Gem Group FASTQs, which is important because multi-gem-group experiments are common. If we don't
have RG headers, we will set up files for 20 gem groups, and use the gem-group suffix on the CB tag to
determine the Gem group. Reads without a CB tag will get dropped.
*/
// (r1, r2, i1, i2)
type OutPaths = (PathBuf, PathBuf, Option<PathBuf>, Option<PathBuf>);
// (rg, fq1, fq2, fq_i1, fq_i2)
type FormattedReadPair = (
Option<Rg>,
FqRecord,
FqRecord,
Option<FqRecord>,
Option<FqRecord>,
);
#[derive(Debug, Deserialize, Clone)]
pub struct Args {
arg_bam: String,
arg_output_path: String,
flag_nthreads: usize,
flag_locus: Option<String>,
flag_bx_list: Option<String>,
flag_reads_per_fastq: usize,
flag_gemcode: bool,
flag_lr20: bool,
flag_cr11: bool,
flag_traceback: bool,
flag_relaxed: bool,
}
/// A Fastq record ready to be written
#[derive(Debug, Serialize, Deserialize, PartialEq, PartialOrd, Eq, Ord)]
struct FqRecord {
#[serde(with = "serde_bytes")]
head: Vec<u8>,
#[serde(with = "serde_bytes")]
seq: Vec<u8>,
#[serde(with = "serde_bytes")]
qual: Vec<u8>,
}
/// Which read in a pair we have
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
enum ReadNum {
R1,
R2,
}
/// Internally serialized read. Used for re-uniting discordant read pairs
#[derive(Debug, Serialize, Deserialize, PartialOrd, Ord, Eq, PartialEq)]
struct SerFq {
read_group: Option<Rg>,
#[serde(with = "serde_bytes")]
header_key: Vec<u8>,
rec: FqRecord,
read_num: ReadNum,
i1: Option<FqRecord>,
i2: Option<FqRecord>,
}
struct SerFqSort;
impl SortKey<SerFq> for SerFqSort {
type Key = Vec<u8>;
fn sort_key(t: &SerFq) -> Cow<Vec<u8>> {
Cow::Borrowed(&t.header_key)
}
}
/// Entry in the conversion spec from a BAM record back to a read.
/// Each read can be composed of data from a pair of tags (tag w/ sequence, tag w/ qual),
/// or a fixed-length sequence of Ns (with a default QV), or the sequence in the read.
#[derive(Clone, Debug, PartialEq, Eq)]
enum SpecEntry {
Tags(String, String),
Ns(usize),
Read,
}
type Rg = (String, u32);
/// Spec for converting from a BAM record back to reads. Empty vector indicates that this read doesn't exist
/// in the output. The i1 and i2 reads should be buildable from tags in the R1 read.
#[derive(Clone, Debug)]
struct FormatBamRecords {
rg_spec: HashMap<String, Rg>,
r1_spec: Vec<SpecEntry>,
r2_spec: Vec<SpecEntry>,
i1_spec: Vec<SpecEntry>,
i2_spec: Vec<SpecEntry>,
rename: Option<Vec<String>>,
order: [u32; 4],
}
pub fn complement(b: u8) -> u8 {
match b {
b'A' => b'T',
b'C' => b'G',
b'G' => b'C',
b'T' => b'A',
b'N' => b'N',
_ => panic!("unrecognized"),
}
}
/// Class that can convert a BAM record into Fastq sequences, given some conversion specs
impl FormatBamRecords {
/// Read the conversion spec from the special @CO 10x_bam_to_fastq tags in the BAM header
pub fn from_headers<R: bam::Read>(reader: &R) -> Option<FormatBamRecords> {
let mut spec = Self::parse_spec(reader);
let rgs = Self::parse_rgs(reader);
let seq_names = Self::parse_seq_names(reader);
if spec.is_empty() {
None
} else {
Some(FormatBamRecords {
rg_spec: rgs,
r1_spec: spec.remove("R1").unwrap(),
r2_spec: spec.remove("R2").unwrap(),
i1_spec: spec.remove("I1").unwrap_or_else(Vec::new),
i2_spec: spec.remove("I2").unwrap_or_else(Vec::new),
rename: seq_names,
order: [1, 3, 2, 4],
})
}
}
/// hard-coded spec for gemcode BAM files
pub fn gemcode<R: bam::Read>(reader: &R) -> FormatBamRecords {
FormatBamRecords {
rg_spec: Self::parse_rgs(reader),
r1_spec: vec![SpecEntry::Read],
r2_spec: vec![SpecEntry::Read],
i1_spec: vec![SpecEntry::Tags("BC".to_string(), "QT".to_string())],
i2_spec: vec![SpecEntry::Tags("RX".to_string(), "QX".to_string())],
rename: Some(vec![
"R1".to_string(),
"R3".to_string(),
"I1".to_string(),
"R2".to_string(),
]),
order: [1, 4, 2, 3],
}
}
// hard-coded specs for longranger 2.0 BAM files
pub fn lr20<R: bam::Read>(reader: &R) -> FormatBamRecords {
FormatBamRecords {
rg_spec: Self::parse_rgs(reader),
r1_spec: vec![
SpecEntry::Tags("RX".to_string(), "QX".to_string()),
SpecEntry::Ns(7),
SpecEntry::Read,
],
r2_spec: vec![SpecEntry::Read],
i1_spec: vec![SpecEntry::Tags("BC".to_string(), "QT".to_string())],
i2_spec: vec![],
rename: None,
order: [1, 3, 2, 0],
}
}
// hard-coded specs for cellranger 1.0-1.1 BAM files
pub fn cr11<R: bam::Read>(reader: &R) -> FormatBamRecords {
FormatBamRecords {
rg_spec: Self::parse_rgs(reader),
r1_spec: vec![SpecEntry::Read],
r2_spec: vec![SpecEntry::Tags("UR".to_string(), "UQ".to_string())],
i1_spec: vec![SpecEntry::Tags("CR".to_string(), "CQ".to_string())],
i2_spec: vec![SpecEntry::Tags("BC".to_string(), "QT".to_string())],
rename: Some(vec![
"R1".to_string(),
"R3".to_string(),
"R2".to_string(),
"I1".to_string(),
]),
order: [1, 4, 3, 2],
}
}
fn parse_rgs<R: bam::Read>(reader: &R) -> HashMap<String, Rg> {
let text = String::from_utf8(Vec::from(reader.header().as_bytes())).unwrap();
let mut rg_items = HashMap::new();
for l in text.lines() {
if l.starts_with("@RG") {
let r = Self::parse_rg_line(l);
if let Some((id, rg, lane)) = r {
rg_items.insert(id, (rg, lane));
};
}
}
if rg_items.is_empty() {
println!("WARNING: no @RG (read group) headers found in BAM file. Splitting data by the GEM well marked in the corrected barcode tag.");
println!("Reads without a corrected barcode will not appear in output FASTQs");
// No RG items in header -- invent a set fixed set of RGs
// each observed Gem group in the BAM file will get mapped to these.
for i in 1..100 {
let name = format!("gemgroup{:03}", i);
rg_items.insert(name.clone(), (name, 0));
}
}
rg_items
}
fn parse_rg_line(line: &str) -> Option<(String, String, u32)> {
let mut entries = line.split('\t');
let _ = entries.next(); // consume @RG entry
let mut tags = HashMap::new();
for entry in entries {
let mut parts = entry.splitn(2, ':');
let tag = parts.next().unwrap();
let val = parts.next().unwrap();
tags.insert(tag.to_string(), val.to_string());
}
if tags.contains_key("ID") {
let v = tags.remove("ID").unwrap();
let vv = &v;
let mut parts = vv.rsplitn(2, ':');
let lane = parts.next().unwrap();
let rg = match parts.next() {
Some(v) => v.to_string(),
None => return None,
};
match u32::from_str(lane) {
Ok(n) => Some((v.clone(), rg, n)),
Err(_) => {
// Handle case in ALIGNER pipeline prior to 2.1.3 -- samtools merge would append a unique identifier to each RG ID tags
// Detect this condition and remove from lane
let re = Regex::new(r"^([0-9]+)-[0-9A-F]+$").unwrap();
let cap = re.captures(lane);
cap.map(|capture| {
let lane_u32 = u32::from_str(capture.get(1).unwrap().as_str()).unwrap();
(v.clone(), rg, lane_u32)
})
}
}
} else {
None
}
}
/// Parse the specs from BAM headers if available
fn parse_spec<R: bam::Read>(reader: &R) -> HashMap<String, Vec<SpecEntry>> {
// Example header line:
// @CO 10x_bam_to_fastq:R1(RX:QX,TR:TQ,SEQ:QUAL)
let re = Regex::new(r"@CO\t10x_bam_to_fastq:(\S+)\((\S+)\)").unwrap();
let text = String::from_utf8(Vec::from(reader.header().as_bytes())).unwrap();
text.lines()
.into_iter()
.filter_map(|l| {
re.captures(l).map(|c| {
let read = c.get(1).unwrap().as_str().to_string();
let tag_list = c.get(2).unwrap().as_str();
let spec_entries = tag_list
.split(',')
.into_iter()
.map(|el| {
if el == "SEQ:QUAL" {
SpecEntry::Read
} else {
let (rtag, qtag) =
el.split(':').map(ToString::to_string).next_tuple().unwrap();
SpecEntry::Tags(rtag, qtag)
}
})
.collect();
(read, spec_entries)
})
})
.collect()
}
// Example header line:
// @CO 10x_bam_to_fastq_seqnames:R1,R3,I1,R2
// In this case, the @CO header lines marked R1, R2, I1, I2 will
// be used to write reads to output files R1, R3, I1, and R2, respectively
fn parse_seq_names<R: bam::Read>(reader: &R) -> Option<Vec<String>> {
let text = String::from_utf8(Vec::from(reader.header().as_bytes())).unwrap();
let re = Regex::new(r"@CO\t10x_bam_to_fastq_seqnames:(\S+)").unwrap();
for l in text.lines() {
if let Some(c) = re.captures(l) {
let mut seq_names = Vec::new();
let names = c.get(1).unwrap().as_str().split(',');
for name in names {
seq_names.push(name.to_string());
}
return Some(seq_names);
}
}
None
}
fn try_get_rg(&self, rec: &Record) -> Option<Rg> {
let rg = rec.aux(b"RG");
match rg {
Ok(Aux::String(s)) => {
let key = String::from_utf8(Vec::from(s)).unwrap();
self.rg_spec.get(&key).cloned()
}
Ok(..) => panic!(
"invalid type of RG header. record: {}",
str::from_utf8(rec.qname()).unwrap()
),
Err(_) => None,
}
}
pub fn find_rg(&self, rec: &Record) -> Option<Rg> {
let main_rg_tag = self.try_get_rg(rec);
if main_rg_tag.is_some() {
main_rg_tag
} else {
let emit = |tag| {
let corrected_bc = String::from_utf8(Vec::from(tag)).unwrap();
let mut parts = (&corrected_bc).split('-');
let _ = parts.next();
match parts.next() {
Some(v) => {
match u32::from_str(v) {
Ok(v) => {
//println!("got gg: {}", v);
let name = format!("gemgroup{:03}", v);
self.rg_spec.get(&name).cloned()
}
_ => None,
}
}
_ => None,
}
};
// Workaround for early CR 1.1 and 1.2 data
// Attempt to extract the gem group out of the corrected barcode tag (CB)
if let Ok(Aux::String(s)) = rec.aux(b"CB") {
return emit(s);
}
// Workaround for GemCode (Long Ranger 1.3) data
// Attempt to extract the gem group out of the corrected barcode tag (BX)
if let Ok(Aux::String(s)) = rec.aux(b"BX") {
return emit(s);
}
None
}
}
/// Convert a BAM record to a Fq record, for internal caching
pub fn bam_rec_to_ser(&self, rec: &Record) -> Result<SerFq, Error> {
Ok(
match (rec.is_first_in_template(), rec.is_last_in_template()) {
(true, false) => SerFq {
header_key: rec.qname().to_vec(),
read_group: self.find_rg(rec),
read_num: ReadNum::R1,
rec: self
.bam_rec_to_fq(rec, &self.r1_spec, self.order[0])
.unwrap(),
i1: if !self.i1_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i1_spec, self.order[2])?)
} else {
None
},
i2: if !self.i2_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i2_spec, self.order[3])?)
} else {
None
},
},
(false, true) => SerFq {
header_key: rec.qname().to_vec(),
read_group: self.find_rg(rec),
read_num: ReadNum::R2,
rec: self
.bam_rec_to_fq(rec, &self.r2_spec, self.order[1])
.unwrap(),
i1: if !self.i1_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i1_spec, self.order[2])?)
} else {
None
},
i2: if !self.i2_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i2_spec, self.order[3])?)
} else {
None
},
},
_ => {
let e = anyhow!(
"Not a valid read pair: {}, {}",
rec.is_first_in_template(),
rec.is_last_in_template()
);
return Err(e);
}
},
)
}
fn fetch_tag(rec: &Record, tag: &str, last_tag: bool, dest: &mut Vec<u8>) -> Result<(), Error> {
match rec.aux(tag.as_bytes()) {
Ok(Aux::String(s)) => dest.extend_from_slice(s.as_bytes()),
// old BAM files have single-char strings as Char
Ok(Aux::Char(c)) => dest.push(c),
Err(_) => {
if last_tag {
return Ok(());
}
let e = anyhow!(
"BAM record missing tag: {:?} on read {:?}. You do not appear to have an original 10x BAM file.\nIf you downloaded this BAM file from SRA, you likely need to download the 'Original Format' version of the BAM available for most 10x datasets.",
tag,
str::from_utf8(rec.qname()).unwrap()
);
return Err(e);
}
Ok(tag_val) => {
let e = anyhow!("Invalid BAM record: read: {:?} unexpected tag type. Expected string for {:?}, got {:?}.\n You do not appear to have the original 10x BAM file. If you downloaded this BAM file from SRA, you likely need to download the 'Original Format' version of the BAM available for most 10x datasets.", str::from_utf8(rec.qname()).unwrap(), tag, tag_val);
return Err(e);
}
}
Ok(())
}
/// Convert a BAM record to Fq record ready to be written
pub fn bam_rec_to_fq(
&self,
rec: &Record,
spec: &[SpecEntry],
read_number: u32,
) -> Result<FqRecord, Error> {
let mut head = Vec::new();
head.extend_from_slice(rec.qname());
let head_suffix = format!(" {}:N:0:0", read_number);
head.extend(head_suffix.as_bytes());
// Reconstitute read and QVs
let mut read = Vec::new();
let mut qv = Vec::new();
for (idx, item) in spec.iter().enumerate() {
// It OK for the final tag in the spec to be missing from the read
let last_item = idx == spec.len() - 1;
match *item {
// Data from a tag
SpecEntry::Tags(ref read_tag, ref qv_tag) => {
Self::fetch_tag(rec, read_tag, last_item, &mut read)?;
Self::fetch_tag(rec, qv_tag, last_item, &mut qv)?;
}
// Just hardcode some Ns -- for cases where we didn't retain the required data
SpecEntry::Ns(len) => {
for _ in 0..len {
read.push(b'N');
qv.push(b'J');
}
}
SpecEntry::Read => {
// The underlying read
let mut seq = rec.seq().as_bytes();
let mut qual: Vec<u8> = rec.qual().iter().map(|x| x + 33).collect();
if rec.is_reverse() {
seq.reverse();
for b in seq.iter_mut() {
*b = complement(*b);
}
qual.reverse();
}
read.extend(seq);
qv.extend(qual);
}
}
}
let fq_rec = FqRecord {
head,
seq: read,
qual: qv,
};
Ok(fq_rec)
}
pub fn format_read_pair(
&self,
r1_rec: &Record,
r2_rec: &Record,
) -> Result<FormattedReadPair, Error> {
let r1 = self.bam_rec_to_fq(r1_rec, &self.r1_spec, self.order[0])?;
let r2 = self.bam_rec_to_fq(r2_rec, &self.r2_spec, self.order[1])?;
let i1 = if !self.i1_spec.is_empty() {
Some(self.bam_rec_to_fq(r1_rec, &self.i1_spec, self.order[2])?)
} else {
None
};
let i2 = if !self.i2_spec.is_empty() {
Some(self.bam_rec_to_fq(r1_rec, &self.i2_spec, self.order[3])?)
} else {
None
};
let rg = self.find_rg(r1_rec);
Ok((rg, r1, r2, i1, i2))
}
pub fn format_read(&self, rec: &Record) -> Result<FormattedReadPair, Error> {
let r1 = self.bam_rec_to_fq(rec, &self.r1_spec, self.order[0])?;
let r2 = self.bam_rec_to_fq(rec, &self.r2_spec, self.order[1])?;
let i1 = if !self.i1_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i1_spec, self.order[2])?)
} else {
None
};
let i2 = if !self.i2_spec.is_empty() {
Some(self.bam_rec_to_fq(rec, &self.i2_spec, self.order[3])?)
} else {
None
};
let rg = self.find_rg(rec);
Ok((rg, r1, r2, i1, i2))
}
/// A spec implies double-ended reads if both the R1 and R2 reads generate different BAM records.
/// If not the R1 and R2 sequences can be derived from a single BAM entry.
pub fn is_double_ended(&self) -> bool {
self.r1_spec.contains(&SpecEntry::Read) && self.r2_spec.contains(&SpecEntry::Read)
}
}
type Bgw = ThreadProxyWriter<BufWriter<GzEncoder<File>>>;
struct FastqManager {
writers: HashMap<Rg, FastqWriter>,
out_path: PathBuf,
}
impl FastqManager {
pub fn new(
out_path: &Path,
formatter: FormatBamRecords,
_sample_name: String,
reads_per_fastq: usize,
) -> FastqManager {
// Take the read groups and generate read group paths
let mut sample_def_paths = HashMap::new();
let mut writers = HashMap::new();
for (_, &(ref _samp, lane)) in formatter.rg_spec.iter() {
let samp = _samp.clone();
let path = sample_def_paths.entry(samp).or_insert_with(|| {
let suffix = _samp.replace(":", "_");
//create_dir(&samp_path).expect("couldn't create output directory");
out_path.join(suffix)
});
let writer = FastqWriter::new(
path,
formatter.clone(),
"bamtofastq".to_string(),
lane,
reads_per_fastq,
);
writers.insert((_samp.clone(), lane), writer);
}
FastqManager {
writers,
out_path: out_path.to_path_buf(),
}
}
pub fn write(
&mut self,
rg: &Option<Rg>,
r1: &FqRecord,
r2: &FqRecord,
i1: &Option<FqRecord>,
i2: &Option<FqRecord>,
) {
if let &Some(ref rg) = rg {
self.writers.get_mut(rg).map(|w| w.write(r1, r2, i1, i2));
}
}
pub fn total_written(&self) -> usize {
self.writers.iter().map(|(_, w)| w.total_written).sum()
}
pub fn paths(&self) -> Vec<(PathBuf, PathBuf, Option<PathBuf>, Option<PathBuf>)> {
let mut r = Vec::new();
for (_, w) in self.writers.iter() {
r.extend(w.path_sets.clone());
}
r
}
}
/// Open Fastq files being written to
struct FastqWriter {
formatter: FormatBamRecords,
out_path: PathBuf,
sample_name: String,
lane: u32,
r1: Option<Bgw>,
r2: Option<Bgw>,
i1: Option<Bgw>,
i2: Option<Bgw>,
chunk_written: usize,
total_written: usize,
n_chunks: usize,
reads_per_fastq: usize,
path_sets: Vec<(PathBuf, PathBuf, Option<PathBuf>, Option<PathBuf>)>,
}
/// Write sets of Fastq records to the open Fastq files
impl FastqWriter {
pub fn new(
out_path: &Path,
formatter: FormatBamRecords,
sample_name: String,
lane: u32,
reads_per_fastq: usize,
) -> FastqWriter {
FastqWriter {
formatter,
out_path: out_path.to_path_buf(),
sample_name,
lane,
r1: None,
r2: None,
i1: None,
i2: None,
n_chunks: 0,
total_written: 0,
chunk_written: 0,
reads_per_fastq,
path_sets: vec![],
}
}
fn get_paths(
out_path: &Path,
sample_name: &str,
lane: u32,
n_files: usize,
formatter: &FormatBamRecords,
) -> (PathBuf, PathBuf, Option<PathBuf>, Option<PathBuf>) {
if formatter.rename.is_none() {
let r1 = out_path.join(format!(
"{}_S1_L{:03}_R1_{:03}.fastq.gz",
sample_name,
lane,
n_files + 1
));
let r2 = out_path.join(format!(
"{}_S1_L{:03}_R2_{:03}.fastq.gz",
sample_name,
lane,
n_files + 1
));
let i1 = out_path.join(format!(
"{}_S1_L{:03}_I1_{:03}.fastq.gz",
sample_name,
lane,
n_files + 1
));
let i2 = out_path.join(format!(
"{}_S1_L{:03}_I2_{:03}.fastq.gz",
sample_name,
lane,
n_files + 1
));
(
r1,
r2,
if !formatter.i1_spec.is_empty() {
Some(i1)
} else {
None
},
if !formatter.i2_spec.is_empty() {
Some(i2)
} else {
None
},
)
} else {
let new_read_names = formatter.rename.as_ref().unwrap();
let r1 = out_path.join(format!(
"{}_S1_L{:03}_{}_{:03}.fastq.gz",
sample_name,
lane,
new_read_names[0],
n_files + 1
));
let r2 = out_path.join(format!(
"{}_S1_L{:03}_{}_{:03}.fastq.gz",
sample_name,
lane,
new_read_names[1],
n_files + 1
));
let i1 = out_path.join(format!(
"{}_S1_L{:03}_{}_{:03}.fastq.gz",
sample_name,
lane,
new_read_names[2],
n_files + 1
));
let i2 = out_path.join(format!(
"{}_S1_L{:03}_{}_{:03}.fastq.gz",
sample_name,
lane,
new_read_names[3],
n_files + 1
));
(
r1,
r2,
if !formatter.i1_spec.is_empty() {
Some(i1)
} else {
None
},
if !formatter.i2_spec.is_empty() {
Some(i2)
} else {
None
},
)
}
}
pub fn write_rec(w: &mut Bgw, rec: &FqRecord) -> Result<(), Error> {
w.write_all(b"@")?;
w.write_all(&rec.head)?;
w.write_all(b"\n")?;
w.write_all(&rec.seq)?;
w.write_all(b"\n+\n")?;
w.write_all(&rec.qual)?;
w.write_all(b"\n")?;
Ok(())
}
pub fn try_write_rec(w: &mut Option<Bgw>, rec: &Option<FqRecord>) -> Result<(), Error> {
if let Some(ref mut w) = w {
if let Some(r) = rec {
FastqWriter::write_rec(w, r)?;
} else {
panic!("setup error");
}
};
Ok(())
}
pub fn try_write_rec2(w: &mut Option<Bgw>, rec: &FqRecord) -> Result<(), Error> {
if let Some(ref mut w) = w {
FastqWriter::write_rec(w, rec)?;
};
Ok(())
}
/// Write a set of fastq records
fn write(
&mut self,
r1: &FqRecord,
r2: &FqRecord,
i1: &Option<FqRecord>,
i2: &Option<FqRecord>,
) -> Result<(), Error> {
if self.total_written == 0 {
// Create the output dir if needed:
let _ = create_dir(&self.out_path);
self.cycle_writers();
}
FastqWriter::try_write_rec2(&mut self.r1, r1)?;
FastqWriter::try_write_rec2(&mut self.r2, r2)?;
FastqWriter::try_write_rec(&mut self.i1, i1)?;
FastqWriter::try_write_rec(&mut self.i2, i2)?;
self.total_written += 1;
self.chunk_written += 1;
if self.chunk_written >= self.reads_per_fastq {
self.cycle_writers()
}
Ok(())
}
/// Open up a fresh output chunk
fn cycle_writers(&mut self) {
let paths = Self::get_paths(
&self.out_path,
&self.sample_name,
self.lane,
self.n_chunks,
&self.formatter,
);
self.r1 = Some(Self::open_gzip_writer(&paths.0));
self.r2 = Some(Self::open_gzip_writer(&paths.1));
self.i1 = paths.2.as_ref().map(Self::open_gzip_writer);
self.i2 = paths.3.as_ref().map(Self::open_gzip_writer);
self.n_chunks += 1;
self.chunk_written = 0;
self.path_sets.push(paths);
}
fn open_gzip_writer<P: AsRef<Path>>(path: P) -> ThreadProxyWriter<BufWriter<GzEncoder<File>>> {
let f = File::create(path).unwrap();
let gz = GzEncoder::new(f, flate2::Compression::fast());
ThreadProxyWriter::new(BufWriter::with_capacity(1 << 22, gz), 1 << 19)
}
}
fn main() {
set_panic_handler();
std::env::set_var("RUST_BACKTRACE", "1");
println!("bamtofastq v{}", VERSION);
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let traceback = args.flag_traceback;
let res = go(args, None);
if let Err(ref e) = res {
println!("bamtofastq error: {}\n", e);
println!("If this error is unexpected, contact [email protected] for assistance. Please re-run with --traceback and include stack trace with an error report");
if traceback {
println!("see below for more details:");
println!("==========================");
println!("{}\n{}", e, e.backtrace());
};
::std::process::exit(1);
}
}
fn set_panic_handler() {
panic::set_hook(Box::new(move |info| {
let backtrace = backtrace::Backtrace::new();
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &**s,
None => "Box<Any>",
},
};
let msg = match info.location() {
Some(location) => format!(
"bamtofastq failed unexpectedly. Please contact [email protected] with the following information: '{}' {}:{}:\n{:?}",
msg,
location.file(),
location.line(),
backtrace
),
None => format!("bamtofastq failed unexpectedly. Please contact [email protected] with the following information: '{}':\n{:?}", msg, backtrace),
};
println!("{}", msg);
}));
}
pub fn go(args: Args, cache_size: Option<usize>) -> Result<Vec<OutPaths>, Error> {