You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

553 lines
19 KiB

  1. /*
  2. This file is part of BioD.
  3. Copyright (C) 2012-2013 Artem Tarasov <lomereiter@gmail.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a
  5. copy of this software and associated documentation files (the "Software"),
  6. to deal in the Software without restriction, including without limitation
  7. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. and/or sell copies of the Software, and to permit persons to whom the
  9. Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  17. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  18. DEALINGS IN THE SOFTWARE.
  19. */
  20. /// Writing a script/tool for processing BAM data often starts this way:
  21. ///
  22. /// ------------------------
  23. /// import bio.bam.reader;
  24. ///
  25. /// void main(string[] args) {
  26. /// auto bam = new BamReader(args[1]); // open BAM file
  27. /// foreach (read; bam.reads) { // iterate through its reads
  28. /// if (read.is_unmapped)
  29. /// continue; // maybe skip unmapped ones
  30. /// ...
  31. /// }
  32. /// }
  33. /// ------------------------
  34. ///
  35. /// Or, if a specific interval on the reference sequence is to be explored:
  36. /// ------------------------
  37. /// import bio.bam.pileup;
  38. /// ...
  39. /// auto reads = bam["chr7"][50_000 .. 60_000]; // BAI index is required
  40. /// foreach (column; makePileup(reads)) { ... } // see $(PMODULE pileup) docs
  41. /// ------------------------
  42. module bio.bam.reader;
  43. import bio.bam.abstractreader;
  44. public import bio.sam.header;
  45. public import bio.bam.reference;
  46. public import bio.bam.read;
  47. public import bio.bam.tagvalue;
  48. public import bio.bam.readrange;
  49. import bio.bam.randomaccessmanager;
  50. import bio.bam.baifile;
  51. import bio.bam.bai.indexing;
  52. import bio.core.utils.range;
  53. import bio.core.utils.stream;
  54. public import bio.core.bgzf.blockrange;
  55. public import bio.core.bgzf.inputstream;
  56. public import bio.core.bgzf.virtualoffset;
  57. import std.system;
  58. import std.stdio;
  59. import std.algorithm;
  60. import std.range;
  61. import std.conv;
  62. import std.exception;
  63. import std.parallelism;
  64. import std.array;
  65. import core.stdc.stdio;
  66. import std.string;
  67. /**
  68. BAM file reader, featuring parallel decompression of BGZF blocks.
  69. */
  70. class BamReader : IBamSamReader {
  71. /**
  72. Creates reader associated with file or stream.
  73. (If stream constructor is used, no random access is possible.)
  74. $(BR)
  75. Optionally, task pool can be specified.
  76. It will be used to unpack BGZF blocks in parallel.
  77. Example:
  78. -------------------------------------------
  79. import std.parallelism, bio.bam.reader;
  80. void main() {
  81. auto pool = new TaskPool(4); // use 4 threads
  82. scope (exit) pool.finish(); // don't forget!
  83. auto bam = new BamReader("file.bam", pool);
  84. ...
  85. }
  86. -------------------------------------------
  87. */
  88. this(std.stream.Stream stream,
  89. std.parallelism.TaskPool task_pool = std.parallelism.taskPool) {
  90. _source_stream = new EndianStream(stream, Endian.littleEndian);
  91. _task_pool = task_pool;
  92. if (stream.seekable) {
  93. _stream_is_seekable = true;
  94. }
  95. initializeStreams();
  96. auto magic = _bam.readString(4);
  97. enforce(magic == "BAM\1", "Invalid file format: expected BAM\\1");
  98. readSamHeader();
  99. readReferenceSequencesInfo();
  100. // right after construction, we are at the beginning
  101. // of the list of reads
  102. if (_stream_is_seekable) {
  103. _reads_start_voffset = _decompressed_stream.virtualTell();
  104. }
  105. }
  106. /// ditto
  107. this(string filename, std.parallelism.TaskPool task_pool) {
  108. _filename = filename;
  109. _source_stream = getNativeEndianSourceStream();
  110. this(_source_stream, task_pool);
  111. }
  112. /// ditto
  113. this(string filename) {
  114. this(filename, std.parallelism.taskPool);
  115. }
  116. /**
  117. True if BAI file was found for this BAM file.
  118. This is necessary for any random-access operations.
  119. $(BR)
  120. Looks for files in the same directory which filename
  121. is either the file name of BAM file with '.bai' appended,
  122. or with the last extension replaced with '.bai'
  123. (that is, for $(I file.bam) paths $(I file.bai) and
  124. $(I file.bam.bai) will be checked)
  125. */
  126. bool has_index() @property {
  127. return _random_access_manager.found_index_file;
  128. }
  129. /**
  130. Creates BAI file. If $(I overwrite) is false, it won't touch
  131. existing index if it is already found.
  132. */
  133. void createIndex(bool overwrite = false) {
  134. if (has_index && !overwrite)
  135. return;
  136. Stream stream = new BufferedFile(filename ~ ".bai", FileMode.OutNew);
  137. scope(exit) stream.close();
  138. bio.bam.bai.indexing.createIndex(this, stream);
  139. _bai_status = BaiStatus.notInitialized;
  140. _rndaccssmgr = null;
  141. }
  142. /** Filename, if the object was created via file name constructor,
  143. $(D null) otherwise.
  144. */
  145. string filename() @property const {
  146. return _filename;
  147. }
  148. /// If file ends with EOF block, returns virtual offset of the start of EOF block.
  149. /// Otherwise, returns virtual offset of the physical end of file.
  150. bio.core.bgzf.virtualoffset.VirtualOffset eofVirtualOffset() {
  151. return _random_access_manager.eofVirtualOffset();
  152. }
  153. /// Get BGZF block at a given file offset.
  154. bio.core.bgzf.block.BgzfBlock getBgzfBlockAt(ulong offset) {
  155. return _random_access_manager.getBgzfBlockAt(offset);
  156. }
  157. /**
  158. Returns: SAM header of the BAM file
  159. */
  160. bio.sam.header.SamHeader header() @property {
  161. if (_header is null) {
  162. synchronized {
  163. if (_header is null) {
  164. _header = new SamHeader(_headertext);
  165. _headertext = null;
  166. }
  167. }
  168. }
  169. return _header;
  170. }
  171. /**
  172. Returns: information about reference sequences
  173. */
  174. const(bio.bam.referenceinfo.ReferenceSequenceInfo)[] reference_sequences() @property const {
  175. return _reference_sequences;
  176. }
  177. /**
  178. Range of all alignment records in the file.
  179. $(BR)
  180. Element type of the returned range depends on the policy.
  181. Default one is $(DPREF2 bam, readrange, withoutOffsets),
  182. in this case range element type is $(DPREF2 bam, read, BamRead).
  183. $(BR)
  184. The other option is $(DPREF2 bam, readrange, withOffsets),
  185. which allows to track read virtual offsets in the file.
  186. In this case range element type is $(DPREF2 bam, readrange, BamReadBlock).
  187. Example:
  188. ----------------------------------
  189. import bio.bam.readrange;
  190. ...
  191. auto bam = new BamReader("file.bam");
  192. auto reads = bam.reads!withOffsets();
  193. writeln(reads.front.start_virtual_offset);
  194. ----------------------------------
  195. */
  196. auto reads(alias IteratePolicy=bio.bam.readrange.withoutOffsets)() @property {
  197. auto _decompressed_stream = getDecompressedBamReadStream();
  198. return bamReadRange!IteratePolicy(_decompressed_stream, this);
  199. }
  200. static struct ReadsWithProgressResult(alias IteratePolicy, R, S) {
  201. this(R range, S stream, void delegate(lazy float p) progressBarFunc) {
  202. _range = range;
  203. _stream = stream;
  204. _progress_bar_func = progressBarFunc;
  205. }
  206. static if (__traits(identifier, IteratePolicy) == "withOffsets") {
  207. auto front() @property {
  208. return _range.front;
  209. }
  210. } else static if (__traits(identifier, IteratePolicy) == "withoutOffsets") {
  211. auto front() @property {
  212. return _range.front.read;
  213. }
  214. } else static assert(0, __traits(identifier, IteratePolicy));
  215. bool empty() @property {
  216. return _range.empty;
  217. }
  218. void popFront() {
  219. _bytes_read += _range.front.read.size_in_bytes;
  220. _range.popFront();
  221. if (_progress_bar_func !is null) {
  222. _progress_bar_func(min(1.0,
  223. cast(float)_bytes_read / (_stream.compressed_file_size *
  224. _stream.average_compression_ratio)));
  225. }
  226. }
  227. private R _range;
  228. private S _stream;
  229. private size_t _bytes_read;
  230. private void delegate(lazy float p) _progress_bar_func;
  231. }
  232. /**
  233. Returns: range of all reads in the file, calling $(I progressBarFunc)
  234. for each read.
  235. $(BR)
  236. $(I progressBarFunc) will be called
  237. each time next alignment is read, with the argument being a number from [0.0, 1.0],
  238. which is estimated progress percentage.
  239. $(BR)
  240. Notice that $(I progressBarFunc) takes $(D lazy) argument,
  241. so that the number of relatively expensive float division operations
  242. can be controlled by user.
  243. Example:
  244. ------------------------------------
  245. import std.functional, std.stdio, bio.bam.reader;
  246. void progress(lazy float p) {
  247. static uint n;
  248. if (++n % 63 == 0) writeln(p); // prints progress after every 63 records
  249. }
  250. ...
  251. foreach (read; bam.readsWithProgress(toDelegate(&progress))) {
  252. ...
  253. }
  254. ------------------------------------
  255. */
  256. auto readsWithProgress(alias IteratePolicy=bio.bam.readrange.withoutOffsets)
  257. (void delegate(lazy float p) progressBarFunc)
  258. {
  259. auto _decompressed_stream = getDecompressedBamReadStream();
  260. auto reads_with_offsets = bamReadRange!withOffsets(_decompressed_stream, this);
  261. alias ReadsWithProgressResult!(IteratePolicy,
  262. typeof(reads_with_offsets), IChunkInputStream) Result;
  263. return Result(reads_with_offsets, _decompressed_stream, progressBarFunc);
  264. }
  265. /// Part of IBamSamReader interface
  266. std.range.InputRange!(bio.bam.read.BamRead) allReads() @property {
  267. return inputRangeObject(reads!withoutOffsets());
  268. }
  269. /**
  270. Returns: the read which starts at a given virtual offset.
  271. */
  272. bio.bam.read.BamRead getReadAt(bio.core.bgzf.virtualoffset.VirtualOffset offset) {
  273. enforce(_random_access_manager !is null);
  274. return _random_access_manager.getReadAt(offset);
  275. }
  276. /**
  277. Returns: all reads located between two virtual offsets in the BAM file.
  278. $(BR)
  279. First offset must point to the start of an alignment record,
  280. and be strictly less than the second one.
  281. $(BR)
  282. For decompression, the task pool specified at the construction is used.
  283. */
  284. auto getReadsBetween(bio.core.bgzf.virtualoffset.VirtualOffset from,
  285. bio.core.bgzf.virtualoffset.VirtualOffset to) {
  286. enforce(from < to, "First offset must be strictly less than second");
  287. enforce(_stream_is_seekable, "Stream is not seekable");
  288. return _random_access_manager.getReadsBetween(from, to);
  289. }
  290. /**
  291. Get BAI chunks containing all reads that overlap specified region.
  292. */
  293. bio.bam.bai.chunk.Chunk[] getChunks(int ref_id, int beg, int end) {
  294. enforce(_random_access_manager !is null);
  295. enforce(beg < end);
  296. return _random_access_manager.getChunks(ref_id, beg, end);
  297. }
  298. /**
  299. Returns reference sequence with id $(I ref_id).
  300. */
  301. bio.bam.reference.ReferenceSequence reference(int ref_id) {
  302. enforce(ref_id < _reference_sequences.length, "Invalid reference index");
  303. return ReferenceSequence(_random_access_manager,
  304. ref_id,
  305. _reference_sequences[ref_id]);
  306. }
  307. /**
  308. Returns reference sequence named $(I ref_name).
  309. Example:
  310. ---------------------------
  311. import std.stdio, bio.bam.reader;
  312. ...
  313. auto bam = new BamReader("file.bam");
  314. writeln(bam["chr2"].length);
  315. ---------------------------
  316. */
  317. bio.bam.reference.ReferenceSequence opIndex(string ref_name) {
  318. enforce(hasReference(ref_name), "Reference with name " ~ ref_name ~ " does not exist");
  319. auto ref_id = _reference_sequence_dict[ref_name];
  320. return reference(ref_id);
  321. }
  322. /**
  323. Check if reference named $(I ref_name) is presented in BAM header.
  324. */
  325. bool hasReference(string ref_name) {
  326. return null != (ref_name in _reference_sequence_dict);
  327. }
  328. /**
  329. Set buffer size for I/O operations. Values less than 4096 are disallowed.
  330. $(BR)
  331. This can help in multithreaded applications when several files are read
  332. simultaneously (e.g. merging).
  333. */
  334. void setBufferSize(size_t buffer_size) {
  335. enforce(buffer_size >= 4096, "Buffer size must be >= 4096 bytes");
  336. _buffer_size = buffer_size;
  337. _random_access_manager.setBufferSize(buffer_size);
  338. }
  339. private:
  340. string _filename; // filename (if available)
  341. Stream _source_stream; // compressed
  342. IChunkInputStream _decompressed_stream; // decompressed
  343. Stream _bam; // decompressed + endian conversion
  344. bool _stream_is_seekable;
  345. // Virtual offset at which alignment records start.
  346. VirtualOffset _reads_start_voffset;
  347. BaiFile _dont_access_me_directly_use_bai_file_for_that;
  348. enum BaiStatus {
  349. notInitialized,
  350. initialized,
  351. fileNotFound
  352. }
  353. BaiStatus _bai_status = BaiStatus.notInitialized;
  354. void initBai() {
  355. if (_bai_status == BaiStatus.notInitialized) {
  356. synchronized {
  357. try {
  358. _dont_access_me_directly_use_bai_file_for_that = BaiFile(_filename);
  359. _bai_status = BaiStatus.initialized;
  360. } catch (Exception e) {
  361. _bai_status = BaiStatus.fileNotFound;
  362. }
  363. }
  364. }
  365. }
  366. // provides access to index file
  367. @property ref BaiFile _bai_file() { // initialized lazily
  368. initBai();
  369. return _dont_access_me_directly_use_bai_file_for_that;
  370. };
  371. RandomAccessManager _rndaccssmgr; // unreadable for a purpose
  372. @property RandomAccessManager _random_access_manager() {
  373. if (_rndaccssmgr is null) {
  374. synchronized {
  375. initBai();
  376. if (_bai_status == BaiStatus.initialized) {
  377. _rndaccssmgr = new RandomAccessManager(this, _bai_file);
  378. } else {
  379. _rndaccssmgr = new RandomAccessManager(this);
  380. }
  381. _rndaccssmgr.setTaskPool(_task_pool);
  382. _rndaccssmgr.setBufferSize(_buffer_size);
  383. }
  384. }
  385. return _rndaccssmgr;
  386. }
  387. SamHeader _header;
  388. string _headertext; // for lazy SAM header parsing
  389. ReferenceSequenceInfo[] _reference_sequences;
  390. int[string] _reference_sequence_dict; /// name -> index mapping
  391. TaskPool _task_pool;
  392. size_t _buffer_size = 8192; // buffer size to be used for I/O
  393. Stream getNativeEndianSourceStream() {
  394. assert(_filename !is null);
  395. Stream file = new bio.core.utils.stream.File(_filename);
  396. return new BufferedStream(file, _buffer_size);
  397. }
  398. Stream getSeekableCompressedStream() {
  399. if (_stream_is_seekable) {
  400. if (_filename !is null) {
  401. auto file = getNativeEndianSourceStream();
  402. version(development)
  403. {
  404. std.stdio.stderr.writeln("[info] file size: ", file.size);
  405. }
  406. return new EndianStream(file, Endian.littleEndian);
  407. } else {
  408. _source_stream.seekSet(0);
  409. return _source_stream;
  410. }
  411. } else {
  412. return null;
  413. }
  414. }
  415. // get decompressed stream out of compressed BAM file
  416. IChunkInputStream getDecompressedStream() {
  417. auto compressed_stream = getSeekableCompressedStream();
  418. auto bgzf_range = (compressed_stream is null) ? BgzfRange(_source_stream) :
  419. BgzfRange(compressed_stream);
  420. version(serial) {
  421. auto chunk_range = map!decompressBgzfBlock(bgzf_range);
  422. } else {
  423. auto chunk_range = _task_pool.map!decompressBgzfBlock(bgzf_range, 24);
  424. }
  425. if (compressed_stream !is null) {
  426. return makeChunkInputStream(chunk_range, cast(size_t)compressed_stream.size);
  427. } else {
  428. return makeChunkInputStream(chunk_range);
  429. }
  430. }
  431. // get decompressed stream starting from the first alignment record
  432. IChunkInputStream getDecompressedBamReadStream() {
  433. auto compressed_stream = getSeekableCompressedStream();
  434. if (compressed_stream !is null) {
  435. enforce(_reads_start_voffset != 0UL);
  436. compressed_stream.seekCur(_reads_start_voffset.coffset);
  437. auto bgzf_range = BgzfRange(compressed_stream);
  438. version(serial) {
  439. auto chunk_range = map!decompressBgzfBlock(bgzf_range);
  440. } else {
  441. auto chunk_range = _task_pool.map!decompressBgzfBlock(bgzf_range, 24);
  442. }
  443. auto sz = compressed_stream.size;
  444. auto stream = makeChunkInputStream(chunk_range, cast(size_t)sz);
  445. stream.readString(_reads_start_voffset.uoffset);
  446. return stream;
  447. } else {
  448. // must be initialized in initializeStreams()
  449. return _decompressed_stream;
  450. }
  451. }
  452. // sets up the streams and ranges
  453. void initializeStreams() {
  454. _decompressed_stream = getDecompressedStream();
  455. _bam = new EndianStream(_decompressed_stream, Endian.littleEndian);
  456. }
  457. // initializes _header
  458. void readSamHeader() {
  459. int l_text;
  460. _bam.read(l_text);
  461. _headertext = to!string(_bam.readString(l_text));
  462. }
  463. // initialize _reference_sequences
  464. void readReferenceSequencesInfo() {
  465. int n_ref;
  466. _bam.read(n_ref);
  467. _reference_sequences = new ReferenceSequenceInfo[n_ref];
  468. foreach (i; 0..n_ref) {
  469. _reference_sequences[i] = ReferenceSequenceInfo(_bam);
  470. // provide mapping Name -> Index
  471. _reference_sequence_dict[_reference_sequences[i].name] = i;
  472. }
  473. }
  474. }