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.
 
 
 

289 lines
9.3 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. module bio.bam.multireader;
  21. import bio.sam.header;
  22. import bio.bam.reader;
  23. import bio.bam.read;
  24. import bio.bam.referenceinfo;
  25. import bio.bam.utils.samheadermerger;
  26. import std.algorithm;
  27. import std.range;
  28. import std.conv;
  29. import std.parallelism;
  30. import std.array;
  31. import std.exception;
  32. import std.typecons;
  33. alias size_t FileId;
  34. // ((BamRead, SamHeaderMerger), (BamRead, SamHeaderMerger)) -> bool
  35. bool compare(T)(const auto ref T r1, const auto ref T r2) {
  36. assert(r1[1] == r2[1]);
  37. auto sorting_order = r1[1].merged_header.sorting_order;
  38. if (sorting_order == SortingOrder.coordinate)
  39. return compareCoordinates(r1[0], r2[0]);
  40. else if (sorting_order == SortingOrder.queryname)
  41. return compareReadNames(r1[0], r2[0]);
  42. else
  43. assert(0);
  44. }
  45. // (BamReader, SamHeaderMerger, FileId) -> [(BamRead, SamHeaderMerger, FileId)]
  46. auto readRange(BamReader reader, SamHeaderMerger merger, FileId index) {
  47. return zip(reader.reads, repeat(merger), repeat(index));
  48. }
  49. // (BamReader, SamHeaderMerger, FileId, int, uint, uint) ->
  50. // [(BamRead, SamHeaderMerger, FileId)]
  51. auto readRange(BamReader reader, SamHeaderMerger merger, FileId index,
  52. int ref_id, uint start, uint end)
  53. {
  54. auto old_ref_id = cast(int)merger.ref_id_reverse_map[index][ref_id];
  55. auto reads = reader.reference(old_ref_id)[start .. end];
  56. return zip(reads, repeat(merger), repeat(index));
  57. }
  58. // ([BamReader], SamHeaderMerger) -> [[(BamRead, SamHeaderMerger, FileId)]]
  59. auto readRanges(BamReader[] readers, SamHeaderMerger merger) {
  60. return readers.zip(repeat(merger), iota(readers.length))
  61. .map!(t => readRange(t[0], t[1], t[2]))();
  62. }
  63. // ([BamReader], SamHeaderMerger, int, uint, uint) ->
  64. // [[BamRead, SamHeaderMerger, FileId)]]
  65. auto readRanges(BamReader[] readers, SamHeaderMerger merger,
  66. int ref_id, uint start, uint end)
  67. {
  68. return readers.zip(repeat(merger), iota(readers.length),
  69. repeat(ref_id), repeat(start), repeat(end))
  70. .map!(t => readRange(t[0], t[1], t[2], t[3], t[4], t[5]))();
  71. }
  72. // tweaks RG and PG tags, and reference sequence ID
  73. // [[(BamRead, SamHeaderMerger, size_t)]] -> [[BamRead]]
  74. auto adjustTags(R)(R reads_with_aux_info, TaskPool pool, size_t bufsize)
  75. if (isInputRange!R)
  76. {
  77. static auto adj(U)(U tpl) { return adjustTags1(tpl[0], tpl[1], tpl[2]); }
  78. return reads_with_aux_info.zip(repeat(pool), repeat(bufsize))
  79. .map!adj().array();
  80. }
  81. // [(BamRead, SamHeaderMerger, size_t)] -> [BamRead]
  82. auto adjustTags1(R)(R reads_with_aux_info, TaskPool pool, size_t bufsize)
  83. if (isInputRange!R)
  84. {
  85. return pool.map!adjustTags(reads_with_aux_info, bufsize);
  86. }
  87. // (BamRead, SamHeaderMerger, size_t) -> (BamRead, SamHeaderMerger)
  88. auto adjustTags(R)(R read_with_aux_info) if (!isInputRange!R) {
  89. auto read = read_with_aux_info[0];
  90. auto merger = read_with_aux_info[1];
  91. auto file_id = read_with_aux_info[2];
  92. with (merger) {
  93. assert(file_id < ref_id_map.length);
  94. auto old_ref_id = read.ref_id;
  95. if (old_ref_id != -1 && old_ref_id in ref_id_map[file_id]) {
  96. auto new_ref_id = to!int(ref_id_map[file_id][old_ref_id]);
  97. if (new_ref_id != old_ref_id)
  98. read.ref_id = new_ref_id;
  99. }
  100. auto program = read["PG"];
  101. if (!program.is_nothing) {
  102. auto pg_str = *(cast(string*)(&program));
  103. if (pg_str in program_id_map[file_id]) {
  104. auto new_pg = program_id_map[file_id][pg_str];
  105. if (new_pg != pg_str)
  106. read["PG"] = new_pg;
  107. }
  108. }
  109. auto read_group = read["RG"];
  110. if (!read_group.is_nothing) {
  111. auto rg_str = *(cast(string*)(&read_group));
  112. if (rg_str in readgroup_id_map[file_id]) {
  113. auto new_rg = readgroup_id_map[file_id][rg_str];
  114. if (new_rg != rg_str)
  115. read["RG"] = new_rg;
  116. }
  117. }
  118. }
  119. return tuple(read, merger);
  120. }
  121. ///
  122. class MultiBamReader {
  123. ///
  124. this(BamReader[] readers) {
  125. _readers = readers;
  126. _merger = new SamHeaderMerger(readers.map!(r => r.header)().array());
  127. auto n_references = _merger.merged_header.sequences.length;
  128. _reference_sequences = new ReferenceSequenceInfo[n_references];
  129. size_t i;
  130. foreach (line; _merger.merged_header.sequences) {
  131. _reference_sequences[i] = ReferenceSequenceInfo(line.name, line.length);
  132. _reference_sequence_dict[line.name] = i++;
  133. }
  134. // TODO: maybe try to guess optimal size, based on the number of files?
  135. setBufferSize(1_048_576);
  136. }
  137. ///
  138. this(string[] filenames) {
  139. this(filenames.map!(fn => new BamReader(fn))().array());
  140. }
  141. ///
  142. this(string[] filenames, std.parallelism.TaskPool task_pool = taskPool) {
  143. this(filenames.zip(repeat(task_pool))
  144. .map!(fn => new BamReader(fn[0], fn[1]))().array());
  145. }
  146. ///
  147. BamReader[] readers() @property {
  148. return _readers;
  149. }
  150. ///
  151. SamHeader header() @property {
  152. return _merger.merged_header;
  153. }
  154. ///
  155. auto reads() @property {
  156. return readRanges(_readers, _merger).adjustTags(task_pool, _adj_bufsz)
  157. .nWayUnion!compare().map!"a[0]"();
  158. }
  159. ///
  160. const(ReferenceSequenceInfo)[] reference_sequences() @property const {
  161. return _reference_sequences;
  162. }
  163. /**
  164. Check if reference named $(I ref_name) is presented in BAM header.
  165. */
  166. bool hasReference(string ref_name) {
  167. return null != (ref_name in _reference_sequence_dict);
  168. }
  169. /**
  170. Returns reference sequence with id $(I ref_id).
  171. */
  172. MultiBamReference reference(int ref_id) {
  173. enforce(ref_id >= 0, "Invalid reference index");
  174. enforce(ref_id < _reference_sequences.length, "Invalid reference index");
  175. return MultiBamReference(_readers, _merger, task_pool, _adj_bufsz,
  176. _reference_sequences[ref_id], ref_id);
  177. }
  178. /**
  179. Returns reference sequence named $(I ref_name).
  180. */
  181. MultiBamReference opIndex(string ref_name) {
  182. enforce(hasReference(ref_name),
  183. "Reference with name " ~ ref_name ~ " does not exist");
  184. auto ref_id = cast(int)_reference_sequence_dict[ref_name];
  185. return reference(ref_id);
  186. }
  187. /// Sets buffer size for all readers (default is 1MB)
  188. void setBufferSize(size_t bytes) {
  189. foreach (reader; _readers)
  190. reader.setBufferSize(bytes);
  191. }
  192. private {
  193. BamReader[] _readers;
  194. SamHeaderMerger _merger;
  195. ReferenceSequenceInfo[] _reference_sequences;
  196. size_t[string] _reference_sequence_dict;
  197. TaskPool _task_pool;
  198. TaskPool task_pool() @property {
  199. if (_task_pool is null)
  200. _task_pool = taskPool;
  201. return _task_pool;
  202. }
  203. size_t _adj_bufsz = 512;
  204. }
  205. }
  206. ///
  207. struct MultiBamReference {
  208. private {
  209. BamReader[] _readers;
  210. SamHeaderMerger _merger;
  211. int _ref_id;
  212. ReferenceSequenceInfo _info;
  213. TaskPool _pool;
  214. size_t _adj_bufsz;
  215. }
  216. this(BamReader[] readers, SamHeaderMerger merger,
  217. TaskPool task_pool, size_t adj_bufsize,
  218. ReferenceSequenceInfo info, int ref_id)
  219. {
  220. _readers = readers;
  221. _merger = merger;
  222. _pool = task_pool;
  223. _adj_bufsz = adj_bufsize;
  224. _ref_id = ref_id;
  225. _info = info;
  226. }
  227. ///
  228. string name() @property const { return _info.name; }
  229. ///
  230. int length() @property const { return _info.length; }
  231. ///
  232. int ref_id() @property const { return _ref_id; }
  233. /// Get alignments overlapping [start, end) region.
  234. /// $(BR)
  235. /// Coordinates are 0-based.
  236. auto opSlice(uint start, uint end) {
  237. enforce(start < end, "start must be less than end");
  238. auto ranges = readRanges(_readers, _merger, ref_id, start, end);
  239. return ranges.adjustTags(_pool, _adj_bufsz)
  240. .nWayUnion!compare().map!"a[0]"();
  241. }
  242. ///
  243. auto opSlice() {
  244. return opSlice(0, length);
  245. }
  246. }