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.
 
 
 

219 lines
7.0 KiB

  1. /*
  2. This file is part of BioD.
  3. Copyright (C) 2012 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. /// $(P Each BAM file contains reads aligned to different reference sequences.)
  21. /// $(P These sequences have unique identifiers in BAM file, starting from 0.
  22. /// Unmapped reads are associated with id = -1.)
  23. /// $(P If BAI file is available, fast region queries are available, that is,
  24. /// getting all reads that overlap given region. This is achieved via $(D opSlice) method.)
  25. ///
  26. /// Example:
  27. /// -----------------------------
  28. /// import bio.bam.reader, std.stdio;
  29. /// ...
  30. /// auto bam = new BamReader("file.bam");
  31. /// auto refseq = bam["chr17"];
  32. /// writeln(refseq.name, " - length ", refseq.length);
  33. /// foreach (read; refseq[1234 .. 5678])
  34. /// if (read.cigar.length > 1)
  35. /// writeln(read.name, " ", read.cigarString());
  36. /// -----------------------------
  37. module bio.bam.reference;
  38. public import bio.bam.referenceinfo;
  39. import bio.bam.readrange;
  40. import bio.bam.randomaccessmanager;
  41. import bio.core.bgzf.virtualoffset;
  42. import std.stream;
  43. import std.exception;
  44. import std.array;
  45. ///
  46. struct ReferenceSequence {
  47. /// Name
  48. string name() @property const {
  49. return _info.name;
  50. }
  51. /// Length in base pairs
  52. int length() @property const {
  53. return _info.length;
  54. }
  55. /// Reference ID
  56. int id() @property const {
  57. return _ref_id;
  58. }
  59. /// Get alignments overlapping [start, end) region.
  60. /// $(BR)
  61. /// Coordinates are 0-based.
  62. auto opSlice(uint start, uint end) {
  63. enforce(start < end, "start must be less than end");
  64. enforce(_manager !is null, "random access is not available");
  65. return _manager.getReads(_ref_id, start, end);
  66. }
  67. /// Get all alignments for this reference
  68. auto opSlice() {
  69. return opSlice(0, length);
  70. }
  71. private alias typeof(opSlice().front) Read;
  72. private Read _first_read() @property {
  73. return opSlice().front.dup;
  74. }
  75. /// Virtual offset at which reads, aligned to this reference, start in BAM file.
  76. /// If there are no reads aligned to this reference, returns virtual
  77. /// offset of the EOF block if it's presented, or the end of file.
  78. bio.core.bgzf.virtualoffset.VirtualOffset startVirtualOffset() {
  79. auto reads = opSlice();
  80. if (reads.empty) {
  81. return _manager.eofVirtualOffset();
  82. }
  83. return reads.front.start_virtual_offset;
  84. }
  85. /// Virtual offset before which reads, aligned to this reference, stop.
  86. /// If there are no reads aligned to this reference, returns virtual
  87. /// offset of the EOF block if it's presented, or the end of file.
  88. bio.core.bgzf.virtualoffset.VirtualOffset endVirtualOffset() {
  89. if (opSlice().empty) {
  90. return _manager.eofVirtualOffset();
  91. }
  92. auto ioffsets = _manager.getBai().indices[_ref_id].ioffsets[];
  93. assert(ioffsets.length > 0);
  94. // Try to get startVirtualOffset of the next reference presented in the file.
  95. for (auto r = _ref_id + 1; r < _manager.getBai().indices.length; ++r) {
  96. auto reads = _manager.getReads(r, 0, uint.max);
  97. if (reads.empty) {
  98. continue;
  99. } else {
  100. return reads.front.start_virtual_offset;
  101. }
  102. }
  103. // However, this approach fails if there are unmapped reads coming after
  104. // this reference. We cannot just return _manager.eofVirtualOffset.
  105. auto last_offset = ioffsets[$ - 1];
  106. auto stream = _manager.createStreamStartingFrom(last_offset);
  107. auto last_few_reads = bamReadRange!withOffsets(stream, null);
  108. VirtualOffset result;
  109. assert(!last_few_reads.empty);
  110. foreach (read; last_few_reads) {
  111. result = read.end_virtual_offset;
  112. }
  113. return result;
  114. }
  115. /// First position on the reference overlapped by reads (0-based)
  116. /// $(BR)
  117. /// Returns -1 if set of reads is empty.
  118. int firstPosition() {
  119. auto reads = opSlice();
  120. if (reads.empty) {
  121. return -1;
  122. }
  123. return reads.front.position;
  124. }
  125. /// Last position on the reference overlapped by reads (0-based)
  126. /// $(BR)
  127. /// Returns -1 if set of reads is empty.
  128. int lastPosition() {
  129. // The key idea is
  130. // 1) use last offset from linear index
  131. // 2) loop through all remaining reads starting from there
  132. auto ioffsets = _manager.getBai().indices[_ref_id].ioffsets[];
  133. long index = ioffsets.length - 1;
  134. debug {
  135. int reads_processed = 0;
  136. }
  137. while (index >= 0) {
  138. auto offset = ioffsets[cast(size_t)index];
  139. auto stream = _manager.createStreamStartingFrom(offset);
  140. auto reads = bamReadRange(stream, null);
  141. int last_position = int.min;
  142. foreach (read; reads) {
  143. debug {
  144. reads_processed += 1;
  145. }
  146. if (read.ref_id != _ref_id) {
  147. break;
  148. }
  149. if (read.position == -1) {
  150. continue;
  151. }
  152. auto end_pos = read.position + read.basesCovered();
  153. if (end_pos > last_position)
  154. last_position = end_pos;
  155. }
  156. if (last_position != int.min) {
  157. debug {
  158. import std.stdio;
  159. stderr.writeln("[debug] ReferenceSequence.lastPosition() processed ",
  160. reads_processed, " reads");
  161. }
  162. return last_position - 1;
  163. }
  164. --index;
  165. }
  166. return firstPosition();
  167. }
  168. this(RandomAccessManager manager, int ref_id, ReferenceSequenceInfo info) {
  169. _manager = manager;
  170. _ref_id = ref_id;
  171. _info = info;
  172. }
  173. private:
  174. RandomAccessManager _manager;
  175. int _ref_id;
  176. ReferenceSequenceInfo _info;
  177. }