-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathmod.rs
3133 lines (2772 loc) · 106 KB
/
mod.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 2014 Christopher Schröder, Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Module for working with SAM, BAM, and CRAM files.
pub mod buffer;
pub mod ext;
pub mod flags;
pub mod header;
pub mod index;
pub mod pileup;
pub mod record;
#[cfg(feature = "serde_feature")]
pub mod record_serde;
use std::ffi;
use std::os::raw::c_char;
use std::path::Path;
use std::rc::Rc;
use std::slice;
use std::str;
use url::Url;
use crate::errors::{Error, Result};
use crate::htslib;
use crate::tpool::ThreadPool;
use crate::utils::path_as_bytes;
pub use crate::bam::buffer::RecordBuffer;
pub use crate::bam::header::Header;
pub use crate::bam::record::Record;
use hts_sys::{hts_fmt_option, sam_fields};
use std::convert::{TryFrom, TryInto};
use std::mem::MaybeUninit;
/// # Safety
///
/// Implementation for `Read::set_threads` and `Writer::set_threads`.
unsafe fn set_threads(htsfile: *mut htslib::htsFile, n_threads: usize) -> Result<()> {
assert!(n_threads != 0, "n_threads must be > 0");
if htslib::hts_set_threads(htsfile, n_threads as i32) != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
unsafe fn set_thread_pool(htsfile: *mut htslib::htsFile, tpool: &ThreadPool) -> Result<()> {
let mut b = tpool.handle.borrow_mut();
if htslib::hts_set_thread_pool(htsfile, &mut b.inner as *mut _) != 0 {
Err(Error::ThreadPool)
} else {
Ok(())
}
}
/// # Safety
///
/// Set the reference FAI index path in a `htslib::htsFile` struct for reading CRAM format.
pub unsafe fn set_fai_filename<P: AsRef<Path>>(
htsfile: *mut htslib::htsFile,
fasta_path: P,
) -> Result<()> {
let path = if let Some(ext) = fasta_path.as_ref().extension() {
fasta_path
.as_ref()
.with_extension(format!("{}.fai", ext.to_str().unwrap()))
} else {
fasta_path.as_ref().with_extension(".fai")
};
let p: &Path = path.as_ref();
let c_str = ffi::CString::new(p.to_str().unwrap().as_bytes()).unwrap();
if htslib::hts_set_fai_filename(htsfile, c_str.as_ptr()) == 0 {
Ok(())
} else {
Err(Error::BamInvalidReferencePath { path: p.to_owned() })
}
}
/// A trait for a BAM reader with a read method.
pub trait Read: Sized {
/// Read next BAM record into given record.
/// Use this method in combination with a single allocated record to avoid the reallocations
/// occurring with the iterator.
///
/// # Arguments
///
/// * `record` - the record to be filled
///
/// # Returns
///
/// Some(Ok(())) if the record was read and None if no more records to read
///
/// Example:
/// ```
/// use rust_htslib::errors::Error;
/// use rust_htslib::bam::{Read, IndexedReader, Record};
///
/// let mut bam = IndexedReader::from_path(&"test/test.bam").unwrap();
/// bam.fetch((0, 1000, 2000)); // reads on tid 0, from 1000bp to 2000bp
/// let mut record = Record::new();
/// while let Some(result) = bam.read(&mut record) {
/// match result {
/// Ok(_) => {
/// println!("Read sequence: {:?}", record.seq().as_bytes());
/// }
/// Err(_) => panic!("BAM parsing failed...")
/// }
/// }
/// ```
///
/// Consider using [`rc_records`](#tymethod.rc_records) instead.
fn read(&mut self, record: &mut record::Record) -> Option<Result<()>>;
/// Iterator over the records of the seeked region.
/// Note that, while being convenient, this is less efficient than pre-allocating a
/// `Record` and reading into it with the `read` method, since every iteration involves
/// the allocation of a new `Record`.
///
/// This is about 10% slower than record in micro benchmarks.
///
/// Consider using [`rc_records`](#tymethod.rc_records) instead.
fn records(&mut self) -> Records<'_, Self>;
/// Records iterator using an Rc to avoid allocating a Record each turn.
/// This is about 1% slower than the [`read`](#tymethod.read) based API in micro benchmarks,
/// but has nicer ergonomics (and might not actually be slower in your applications).
///
/// Example:
/// ```
/// use rust_htslib::errors::Error;
/// use rust_htslib::bam::{Read, Reader, Record};
/// use rust_htslib::htslib; // for BAM_F*
/// let mut bam = Reader::from_path(&"test/test.bam").unwrap();
///
/// for read in
/// bam.rc_records()
/// .map(|x| x.expect("Failure parsing Bam file"))
/// .filter(|read|
/// read.flags()
/// & (htslib::BAM_FUNMAP
/// | htslib::BAM_FSECONDARY
/// | htslib::BAM_FQCFAIL
/// | htslib::BAM_FDUP) as u16
/// == 0
/// )
/// .filter(|read| !read.is_reverse()) {
/// println!("Found a forward read: {:?}", read.qname());
/// }
///
/// //or to add the read qnames into a Vec
/// let collected: Vec<_> = bam.rc_records().map(|read| read.unwrap().qname().to_vec()).collect();
///
///
/// ```
fn rc_records(&mut self) -> RcRecords<'_, Self>;
/// Iterator over pileups.
fn pileup(&mut self) -> pileup::Pileups<'_, Self>;
/// Return the htsFile struct
fn htsfile(&self) -> *mut htslib::htsFile;
/// Return the header.
fn header(&self) -> &HeaderView;
/// Seek to the given virtual offset in the file
fn seek(&mut self, offset: i64) -> Result<()> {
let htsfile = unsafe { self.htsfile().as_ref() }.expect("bug: null pointer to htsFile");
let ret = match htsfile.format.format {
htslib::htsExactFormat_cram => unsafe {
i64::from(htslib::cram_seek(
htsfile.fp.cram,
offset as libc::off_t,
libc::SEEK_SET,
))
},
_ => unsafe { htslib::bgzf_seek(htsfile.fp.bgzf, offset, libc::SEEK_SET) },
};
if ret == 0 {
Ok(())
} else {
Err(Error::FileSeek)
}
}
/// Report the current virtual offset
fn tell(&self) -> i64 {
// this reimplements the bgzf_tell macro
let htsfile = unsafe { self.htsfile().as_ref() }.expect("bug: null pointer to htsFile");
let bgzf = unsafe { *htsfile.fp.bgzf };
(bgzf.block_address << 16) | (i64::from(bgzf.block_offset) & 0xFFFF)
}
/// Activate multi-threaded BAM read support in htslib. This should permit faster
/// reading of large BAM files.
///
/// Setting `nthreads` to `0` does not change the current state. Note that it is not
/// possible to set the number of background threads below `1` once it has been set.
///
/// # Arguments
///
/// * `n_threads` - number of extra background writer threads to use, must be `> 0`.
fn set_threads(&mut self, n_threads: usize) -> Result<()> {
unsafe { set_threads(self.htsfile(), n_threads) }
}
/// Use a shared thread-pool for writing. This permits controlling the total
/// thread count when multiple readers and writers are working simultaneously.
/// A thread pool can be created with `crate::tpool::ThreadPool::new(n_threads)`
///
/// # Arguments
///
/// * `tpool` - thread pool to use for compression work.
fn set_thread_pool(&mut self, tpool: &ThreadPool) -> Result<()>;
/// If the underlying file is in CRAM format, allows modifying CRAM options.
/// Note that this method does *not* check that the underlying file actually is in CRAM format.
///
/// # Examples
///
/// Set the required fields to RNAME and FLAG,
/// potentially allowing htslib to skip over the rest,
/// resulting in faster iteration:
/// ```
/// use rust_htslib::bam::{Read, Reader};
/// use hts_sys;
/// let mut cram = Reader::from_path(&"test/test_cram.cram").unwrap();
/// cram.set_cram_options(hts_sys::hts_fmt_option_CRAM_OPT_REQUIRED_FIELDS,
/// hts_sys::sam_fields_SAM_RNAME | hts_sys::sam_fields_SAM_FLAG).unwrap();
/// ```
fn set_cram_options(&mut self, fmt_opt: hts_fmt_option, fields: sam_fields) -> Result<()> {
unsafe {
if hts_sys::hts_set_opt(self.htsfile(), fmt_opt, fields) != 0 {
Err(Error::HtsSetOpt)
} else {
Ok(())
}
}
}
}
/// A BAM reader.
#[derive(Debug)]
pub struct Reader {
htsfile: *mut htslib::htsFile,
header: Rc<HeaderView>,
tpool: Option<ThreadPool>,
}
unsafe impl Send for Reader {}
impl Reader {
/// Create a new Reader from path.
///
/// # Arguments
///
/// * `path` - the path to open.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::new(&path_as_bytes(path, true)?)
}
/// Create a new Reader from STDIN.
pub fn from_stdin() -> Result<Self> {
Self::new(b"-")
}
/// Create a new Reader from URL.
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(url.as_str().as_bytes())
}
/// Create a new Reader.
///
/// # Arguments
///
/// * `path` - the path to open. Use "-" for stdin.
fn new(path: &[u8]) -> Result<Self> {
let htsfile = hts_open(path, b"r")?;
let header = unsafe { htslib::sam_hdr_read(htsfile) };
if header.is_null() {
return Err(Error::BamOpen {
target: String::from_utf8_lossy(path).to_string(),
});
}
// Invalidate the `text` representation of the header
unsafe {
let _ = htslib::sam_hdr_line_name(header, b"SQ".as_ptr().cast::<c_char>(), 0);
}
Ok(Reader {
htsfile,
header: Rc::new(HeaderView::new(header)),
tpool: None,
})
}
extern "C" fn pileup_read(
data: *mut ::std::os::raw::c_void,
record: *mut htslib::bam1_t,
) -> i32 {
let mut _self = unsafe { (data as *mut Self).as_mut().unwrap() };
unsafe {
htslib::sam_read1(
_self.htsfile(),
_self.header().inner_ptr() as *mut hts_sys::sam_hdr_t,
record,
)
}
}
/// Iterator over the records between the (optional) virtual offsets `start` and `end`
///
/// # Arguments
///
/// * `start` - Optional starting virtual offset to seek to. Throws an error if it is not
/// a valid virtual offset.
///
/// * `end` - Read until the virtual offset is less than `end`
pub fn iter_chunk(&mut self, start: Option<i64>, end: Option<i64>) -> ChunkIterator<'_, Self> {
if let Some(pos) = start {
self.seek(pos)
.expect("Failed to seek to the starting position");
};
ChunkIterator { reader: self, end }
}
/// Set the reference path for reading CRAM files.
///
/// # Arguments
///
/// * `path` - path to the FASTA reference
pub fn set_reference<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
unsafe { set_fai_filename(self.htsfile, path) }
}
}
impl Read for Reader {
/// Read the next BAM record into the given `Record`.
/// Returns `None` if there are no more records.
///
/// This method is useful if you want to read records as fast as possible as the
/// `Record` can be reused. A more ergonomic approach is to use the [records](Reader::records)
/// iterator.
///
/// # Errors
/// If there are any issues with reading the next record an error will be returned.
///
/// # Examples
///
/// ```
/// use rust_htslib::errors::Error;
/// use rust_htslib::bam::{Read, Reader, Record};
///
/// let mut bam = Reader::from_path(&"test/test.bam")?;
/// let mut record = Record::new();
///
/// // Print the TID of each record
/// while let Some(r) = bam.read(&mut record) {
/// r.expect("Failed to parse record");
/// println!("TID: {}", record.tid())
/// }
/// # Ok::<(), Error>(())
/// ```
fn read(&mut self, record: &mut record::Record) -> Option<Result<()>> {
match unsafe {
htslib::sam_read1(
self.htsfile,
self.header().inner_ptr() as *mut hts_sys::sam_hdr_t,
record.inner_ptr_mut(),
)
} {
-1 => None,
-2 => Some(Err(Error::BamTruncatedRecord)),
-4 => Some(Err(Error::BamInvalidRecord)),
_ => {
record.set_header(Rc::clone(&self.header));
Some(Ok(()))
}
}
}
/// Iterator over the records of the fetched region.
/// Note that, while being convenient, this is less efficient than pre-allocating a
/// `Record` and reading into it with the `read` method, since every iteration involves
/// the allocation of a new `Record`.
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn rc_records(&mut self) -> RcRecords<'_, Self> {
RcRecords {
reader: self,
record: Rc::new(record::Record::new()),
}
}
fn pileup(&mut self) -> pileup::Pileups<'_, Self> {
let _self = self as *const Self;
let itr = unsafe {
htslib::bam_plp_init(
Some(Reader::pileup_read),
_self as *mut ::std::os::raw::c_void,
)
};
pileup::Pileups::new(self, itr)
}
fn htsfile(&self) -> *mut htslib::htsFile {
self.htsfile
}
fn header(&self) -> &HeaderView {
&self.header
}
fn set_thread_pool(&mut self, tpool: &ThreadPool) -> Result<()> {
unsafe { set_thread_pool(self.htsfile(), tpool)? }
self.tpool = Some(tpool.clone());
Ok(())
}
}
impl Drop for Reader {
fn drop(&mut self) {
unsafe {
htslib::hts_close(self.htsfile);
}
}
}
/// Conversion type for start/stop coordinates
/// only public because it's leaked by the conversions
#[doc(hidden)]
pub struct FetchCoordinate(i64);
//the old sam spec
impl From<i32> for FetchCoordinate {
fn from(coord: i32) -> FetchCoordinate {
FetchCoordinate(coord as i64)
}
}
// to support un-annotated literals (type interference fails on those)
impl From<u32> for FetchCoordinate {
fn from(coord: u32) -> FetchCoordinate {
FetchCoordinate(coord as i64)
}
}
//the new sam spec
impl From<i64> for FetchCoordinate {
fn from(coord: i64) -> FetchCoordinate {
FetchCoordinate(coord)
}
}
//what some of our header methods return
impl From<u64> for FetchCoordinate {
fn from(coord: u64) -> FetchCoordinate {
FetchCoordinate(coord.try_into().expect("Coordinate exceeded 2^^63-1"))
}
}
/// Enum for [IndexdReader.fetch()](struct.IndexedReader.html#method.fetch) arguments.
///
/// tids may be converted From<>:
/// * i32 (correct as per spec)
/// * u32 (because of header.tid. Will panic if above 2^31-1).
///
///Coordinates may be (via FetchCoordinate)
/// * i32 (as of the sam v1 spec)
/// * i64 (as of the htslib 'large coordinate' extension (even though they are not supported in BAM)
/// * u32 (because that's what rust literals will default to)
/// * u64 (because of header.target_len(). Will panic if above 2^^63-1).
#[derive(Debug)]
pub enum FetchDefinition<'a> {
/// tid, start, stop,
Region(i32, i64, i64),
/// 'named-reference', start, stop tuple.
RegionString(&'a [u8], i64, i64),
///complete reference. May be i32 or u32 (which panics if above 2^31-')
CompleteTid(i32),
///complete reference by name (&[u8] or &str)
String(&'a [u8]),
/// Every read
All,
/// Only reads with the BAM flag BAM_FUNMAP (which might not be all reads with reference = -1)
Unmapped,
}
impl<'a, X: Into<FetchCoordinate>, Y: Into<FetchCoordinate>> From<(i32, X, Y)>
for FetchDefinition<'a>
{
fn from(tup: (i32, X, Y)) -> FetchDefinition<'a> {
let start: FetchCoordinate = tup.1.into();
let stop: FetchCoordinate = tup.2.into();
FetchDefinition::Region(tup.0, start.0, stop.0)
}
}
impl<'a, X: Into<FetchCoordinate>, Y: Into<FetchCoordinate>> From<(u32, X, Y)>
for FetchDefinition<'a>
{
fn from(tup: (u32, X, Y)) -> FetchDefinition<'a> {
let start: FetchCoordinate = tup.1.into();
let stop: FetchCoordinate = tup.2.into();
FetchDefinition::Region(
tup.0.try_into().expect("Tid exceeded 2^31-1"),
start.0,
stop.0,
)
}
}
//non tuple impls
impl<'a> From<i32> for FetchDefinition<'a> {
fn from(tid: i32) -> FetchDefinition<'a> {
FetchDefinition::CompleteTid(tid)
}
}
impl<'a> From<u32> for FetchDefinition<'a> {
fn from(tid: u32) -> FetchDefinition<'a> {
let tid: i32 = tid.try_into().expect("tid exceeded 2^31-1");
FetchDefinition::CompleteTid(tid)
}
}
impl<'a> From<&'a str> for FetchDefinition<'a> {
fn from(s: &'a str) -> FetchDefinition<'a> {
FetchDefinition::String(s.as_bytes())
}
}
//also accept &[u8;n] literals
impl<'a> From<&'a [u8]> for FetchDefinition<'a> {
fn from(s: &'a [u8]) -> FetchDefinition<'a> {
FetchDefinition::String(s)
}
}
//also accept &[u8;n] literals
impl<'a, T: AsRef<[u8]>> From<&'a T> for FetchDefinition<'a> {
fn from(s: &'a T) -> FetchDefinition<'a> {
FetchDefinition::String(s.as_ref())
}
}
impl<'a, X: Into<FetchCoordinate>, Y: Into<FetchCoordinate>> From<(&'a str, X, Y)>
for FetchDefinition<'a>
{
fn from(tup: (&'a str, X, Y)) -> FetchDefinition<'a> {
let start: FetchCoordinate = tup.1.into();
let stop: FetchCoordinate = tup.2.into();
FetchDefinition::RegionString(tup.0.as_bytes(), start.0, stop.0)
}
}
impl<'a, X: Into<FetchCoordinate>, Y: Into<FetchCoordinate>> From<(&'a [u8], X, Y)>
for FetchDefinition<'a>
{
fn from(tup: (&'a [u8], X, Y)) -> FetchDefinition<'a> {
let start: FetchCoordinate = tup.1.into();
let stop: FetchCoordinate = tup.2.into();
FetchDefinition::RegionString(tup.0, start.0, stop.0)
}
}
//also accept &[u8;n] literals
impl<'a, T: AsRef<[u8]>, X: Into<FetchCoordinate>, Y: Into<FetchCoordinate>> From<(&'a T, X, Y)>
for FetchDefinition<'a>
{
fn from(tup: (&'a T, X, Y)) -> FetchDefinition<'a> {
let start: FetchCoordinate = tup.1.into();
let stop: FetchCoordinate = tup.2.into();
FetchDefinition::RegionString(tup.0.as_ref(), start.0, stop.0)
}
}
#[derive(Debug)]
pub struct IndexedReader {
htsfile: *mut htslib::htsFile,
header: Rc<HeaderView>,
idx: Rc<IndexView>,
itr: Option<*mut htslib::hts_itr_t>,
tpool: Option<ThreadPool>,
}
unsafe impl Send for IndexedReader {}
impl IndexedReader {
/// Create a new Reader from path.
///
/// # Arguments
///
/// * `path` - the path to open.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::new(&path_as_bytes(path, true)?)
}
pub fn from_path_and_index<P: AsRef<Path>>(path: P, index_path: P) -> Result<Self> {
Self::new_with_index_path(
&path_as_bytes(path, true)?,
&path_as_bytes(index_path, true)?,
)
}
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(url.as_str().as_bytes())
}
/// Create a new Reader.
///
/// # Arguments
///
/// * `path` - the path. Use "-" for stdin.
fn new(path: &[u8]) -> Result<Self> {
let htsfile = hts_open(path, b"r")?;
let header = unsafe { htslib::sam_hdr_read(htsfile) };
let c_str = ffi::CString::new(path).unwrap();
let idx = unsafe { htslib::sam_index_load(htsfile, c_str.as_ptr()) };
if idx.is_null() {
Err(Error::BamInvalidIndex {
target: str::from_utf8(path).unwrap().to_owned(),
})
} else {
Ok(IndexedReader {
htsfile,
header: Rc::new(HeaderView::new(header)),
idx: Rc::new(IndexView::new(idx)),
itr: None,
tpool: None,
})
}
}
/// Create a new Reader.
///
/// # Arguments
///
/// * `path` - the path. Use "-" for stdin.
/// * `index_path` - the index path to use
fn new_with_index_path(path: &[u8], index_path: &[u8]) -> Result<Self> {
let htsfile = hts_open(path, b"r")?;
let header = unsafe { htslib::sam_hdr_read(htsfile) };
let c_str_path = ffi::CString::new(path).unwrap();
let c_str_index_path = ffi::CString::new(index_path).unwrap();
let idx = unsafe {
htslib::sam_index_load2(htsfile, c_str_path.as_ptr(), c_str_index_path.as_ptr())
};
if idx.is_null() {
Err(Error::BamInvalidIndex {
target: str::from_utf8(path).unwrap().to_owned(),
})
} else {
Ok(IndexedReader {
htsfile,
header: Rc::new(HeaderView::new(header)),
idx: Rc::new(IndexView::new(idx)),
itr: None,
tpool: None,
})
}
}
/// Define the region from which .read() or .records will retrieve reads.
///
/// Both iterating (with [.records()](trait.Read.html#tymethod.records)) and looping without allocation (with [.read()](trait.Read.html#tymethod.read) are a two stage process:
/// 1. 'fetch' the region of interest
/// 2. iter/loop through the reads.
///
/// Example:
/// ```
/// use rust_htslib::bam::{IndexedReader, Read};
/// let mut bam = IndexedReader::from_path(&"test/test.bam").unwrap();
/// bam.fetch(("chrX", 10000, 20000)); // coordinates 10000..20000 on reference named "chrX"
/// for read in bam.records() {
/// println!("read name: {:?}", read.unwrap().qname());
/// }
/// ```
///
/// The arguments may be anything that can be converted into a FetchDefinition
/// such as
///
/// * fetch(tid: u32) -> fetch everything on this reference
/// * fetch(reference_name: &[u8] | &str) -> fetch everything on this reference
/// * fetch((tid: i32, start: i64, stop: i64)): -> fetch in this region on this tid
/// * fetch((reference_name: &[u8] | &str, start: i64, stop: i64) -> fetch in this region on this tid
/// * fetch(FetchDefinition::All) or fetch(".") -> Fetch overything
/// * fetch(FetchDefinition::Unmapped) or fetch("*") -> Fetch unmapped (as signified by the 'unmapped' flag in the BAM - might be unreliable with some aligners.
///
/// The start / stop coordinates will take i64 (the correct type as of htslib's 'large
/// coordinates' expansion), i32, u32, and u64 (with a possible panic! if the coordinate
/// won't fit an i64).
///
/// `start` and `stop` are zero-based. `start` is inclusive, `stop` is exclusive.
///
/// This replaces the old fetch and fetch_str implementations.
pub fn fetch<'a, T: Into<FetchDefinition<'a>>>(&mut self, fetch_definition: T) -> Result<()> {
//this 'compile time redirect' safes us
//from monomorphing the 'meat' of the fetch function
self._inner_fetch(fetch_definition.into())
}
fn _inner_fetch(&mut self, fetch_definition: FetchDefinition) -> Result<()> {
match fetch_definition {
FetchDefinition::Region(tid, start, stop) => {
self._fetch_by_coord_tuple(tid, start, stop)
}
FetchDefinition::RegionString(s, start, stop) => {
let tid = self.header().tid(s);
match tid {
Some(tid) => self._fetch_by_coord_tuple(tid as i32, start, stop),
None => Err(Error::Fetch),
}
}
FetchDefinition::CompleteTid(tid) => {
let len = self.header().target_len(tid as u32);
match len {
Some(len) => self._fetch_by_coord_tuple(tid, 0, len as i64),
None => Err(Error::Fetch),
}
}
FetchDefinition::String(s) => {
// either a target-name or a samtools style definition
let tid = self.header().tid(s);
match tid {
Some(tid) => {
//'large position' spec says target len must will fit into an i64.
let len: i64 = self.header.target_len(tid).unwrap().try_into().unwrap();
self._fetch_by_coord_tuple(tid as i32, 0, len)
}
None => self._fetch_by_str(s),
}
}
FetchDefinition::All => self._fetch_by_str(b"."),
FetchDefinition::Unmapped => self._fetch_by_str(b"*"),
}
}
fn _fetch_by_coord_tuple(&mut self, tid: i32, beg: i64, end: i64) -> Result<()> {
if let Some(itr) = self.itr {
unsafe { htslib::hts_itr_destroy(itr) }
}
let itr = unsafe { htslib::sam_itr_queryi(self.index().inner_ptr(), tid, beg, end) };
if itr.is_null() {
self.itr = None;
Err(Error::Fetch)
} else {
self.itr = Some(itr);
Ok(())
}
}
fn _fetch_by_str(&mut self, region: &[u8]) -> Result<()> {
if let Some(itr) = self.itr {
unsafe { htslib::hts_itr_destroy(itr) }
}
let rstr = ffi::CString::new(region).unwrap();
let rptr = rstr.as_ptr();
let itr = unsafe {
htslib::sam_itr_querys(
self.index().inner_ptr(),
self.header().inner_ptr() as *mut hts_sys::sam_hdr_t,
rptr,
)
};
if itr.is_null() {
self.itr = None;
Err(Error::Fetch)
} else {
self.itr = Some(itr);
Ok(())
}
}
extern "C" fn pileup_read(
data: *mut ::std::os::raw::c_void,
record: *mut htslib::bam1_t,
) -> i32 {
let _self = unsafe { (data as *mut Self).as_mut().unwrap() };
match _self.itr {
Some(itr) => itr_next(_self.htsfile, itr, record), // read fetched region
None => unsafe {
htslib::sam_read1(
_self.htsfile,
_self.header().inner_ptr() as *mut hts_sys::sam_hdr_t,
record,
)
}, // ordinary reading
}
}
/// Set the reference path for reading CRAM files.
///
/// # Arguments
///
/// * `path` - path to the FASTA reference
pub fn set_reference<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
unsafe { set_fai_filename(self.htsfile, path) }
}
pub fn index(&self) -> &IndexView {
&self.idx
}
// Analogous to slow_idxstats in samtools, see
// https://github.com/samtools/samtools/blob/556c60fdff977c0e6cadc4c2581661f187098b4d/bam_index.c#L140-L199
unsafe fn slow_idxstats(&mut self) -> Result<Vec<(i64, u64, u64, u64)>> {
self.set_cram_options(
hts_sys::hts_fmt_option_CRAM_OPT_REQUIRED_FIELDS,
hts_sys::sam_fields_SAM_RNAME | hts_sys::sam_fields_SAM_FLAG,
)?;
let header = self.header();
let h = header.inner;
let mut ret;
let mut last_tid = -2;
let fp = self.htsfile();
let nref =
usize::try_from(hts_sys::sam_hdr_nref(h)).map_err(|_| Error::NoSequencesInReference)?;
if nref == 0 {
return Ok(vec![]);
}
let mut counts = vec![vec![0; 2]; nref + 1];
let mut bb: hts_sys::bam1_t = MaybeUninit::zeroed().assume_init();
let b = &mut bb as *mut hts_sys::bam1_t;
loop {
ret = hts_sys::sam_read1(fp, h, b);
if ret < 0 {
break;
}
let tid = (*b).core.tid;
if tid >= nref as i32 || tid < -1 {
return Err(Error::InvalidTid { tid });
}
if tid != last_tid {
if (last_tid >= -1) && (counts[tid as usize][0] + counts[tid as usize][1]) > 0 {
return Err(Error::BamUnsorted);
}
last_tid = tid;
}
let idx = if ((*b).core.flag as u32 & hts_sys::BAM_FUNMAP) > 0 {
1
} else {
0
};
counts[(*b).core.tid as usize][idx] += 1;
}
if ret == -1 {
let res = (0..nref)
.map(|i| {
(
i as i64,
header.target_len(i as u32).unwrap(),
counts[i][0],
counts[i][1],
)
})
.chain([(-1, 0, counts[nref][0], counts[nref][1])])
.collect();
Ok(res)
} else {
Err(Error::SlowIdxStats)
}
}
/// Similar to samtools idxstats, this returns a vector of tuples
/// containing the target id, length, number of mapped reads, and number of unmapped reads.
/// The last entry in the vector corresponds to the unmapped reads for the entire file, with
/// the tid set to -1.
pub fn index_stats(&mut self) -> Result<Vec<(i64, u64, u64, u64)>> {
let header = self.header();
let index = self.index();
if index.inner_ptr().is_null() {
panic!("Index is null");
}
// the quick index stats method only works for BAM files, not SAM or CRAM
unsafe {
if (*self.htsfile()).format.format != htslib::htsExactFormat_bam {
return self.slow_idxstats();
}
}
Ok((0..header.target_count())
.map(|tid| {
let (mapped, unmapped) = index.number_mapped_unmapped(tid);
let tlen = header.target_len(tid).unwrap();
(tid as i64, tlen, mapped, unmapped)
})
.chain([(-1, 0, 0, index.number_unmapped())])
.collect::<_>())
}
}
#[derive(Debug)]
pub struct IndexView {
inner: *mut hts_sys::hts_idx_t,
owned: bool,
}
impl IndexView {
fn new(hts_idx: *mut hts_sys::hts_idx_t) -> Self {
Self {
inner: hts_idx,
owned: true,
}
}
#[inline]
pub fn inner(&self) -> &hts_sys::hts_idx_t {
unsafe { self.inner.as_ref().unwrap() }
}
#[inline]
// Pointer to inner hts_idx_t struct
pub fn inner_ptr(&self) -> *const hts_sys::hts_idx_t {
self.inner
}
#[inline]
pub fn inner_mut(&mut self) -> &mut hts_sys::hts_idx_t {
unsafe { self.inner.as_mut().unwrap() }
}
#[inline]
// Mutable pointer to hts_idx_t struct
pub fn inner_ptr_mut(&mut self) -> *mut hts_sys::hts_idx_t {
self.inner
}
/// Get the number of mapped and unmapped reads for a given target id
/// FIXME only valid for BAM, not SAM/CRAM
fn number_mapped_unmapped(&self, tid: u32) -> (u64, u64) {
let (mut mapped, mut unmapped) = (0, 0);
unsafe {
hts_sys::hts_idx_get_stat(self.inner, tid as i32, &mut mapped, &mut unmapped);
}
(mapped, unmapped)
}
/// Get the total number of unmapped reads in the file
/// FIXME only valid for BAM, not SAM/CRAM
fn number_unmapped(&self) -> u64 {
unsafe { hts_sys::hts_idx_get_n_no_coor(self.inner) }
}
}
impl Drop for IndexView {
fn drop(&mut self) {
if self.owned {
unsafe {
htslib::hts_idx_destroy(self.inner);
}
}
}
}
impl Read for IndexedReader {
fn read(&mut self, record: &mut record::Record) -> Option<Result<()>> {
match self.itr {
Some(itr) => {
match itr_next(self.htsfile, itr, &mut record.inner as *mut htslib::bam1_t) {
-1 => None,
-2 => Some(Err(Error::BamTruncatedRecord)),
-4 => Some(Err(Error::BamInvalidRecord)),
_ => {
record.set_header(Rc::clone(&self.header));
Some(Ok(()))
}
}
}
None => None,
}
}
/// Iterator over the records of the fetched region.
/// Note that, while being convenient, this is less efficient than pre-allocating a
/// `Record` and reading into it with the `read` method, since every iteration involves
/// the allocation of a new `Record`.
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn rc_records(&mut self) -> RcRecords<'_, Self> {
RcRecords {