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.
 
 
 

440 lines
15 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. module bio.bam.md.reconstruct;
  21. import bio.bam.read;
  22. import bio.bam.md.core;
  23. import std.conv;
  24. import std.range;
  25. import std.traits;
  26. import std.algorithm;
  27. import std.range;
  28. /// Reconstruct read DNA.
  29. /// Returns lazy sequence.
  30. auto dna(T)(T read)
  31. if(isBamRead!(Unqual!T))
  32. {
  33. debug {
  34. /*
  35. import std.stdio;
  36. stderr.writeln("[dna] processing read ", read.name);
  37. stderr.flush();
  38. */
  39. }
  40. static struct QueryChunk(S) {
  41. S sequence;
  42. CigarOperation operation;
  43. }
  44. static struct QueryChunksResult(R, S) {
  45. this(R ops, S seq) {
  46. _seq = seq;
  47. _ops = ops;
  48. }
  49. auto front() @property {
  50. auto op = _ops.front;
  51. return QueryChunk!S(_seq[0 .. op.length], op);
  52. }
  53. bool empty() @property {
  54. return _ops.empty;
  55. }
  56. void popFront() {
  57. _seq = _seq[_ops.front.length .. _seq.length];
  58. _ops.popFront();
  59. }
  60. private R _ops;
  61. private S _seq;
  62. }
  63. static auto getQueryChunksResult(R, S)(S sequence, R cigar) {
  64. return QueryChunksResult!(R, S)(cigar, sequence);
  65. }
  66. // Get read sequence chunks corresponding to query-consuming operations in read.sequence
  67. static auto queryChunks(ref T read) {
  68. return getQueryChunksResult(read.sequence, filter!"a.is_query_consuming"(read.cigar));
  69. }
  70. auto _read = read;
  71. auto query_chunks = queryChunks(_read);
  72. static struct Result(R, M) {
  73. this(ref T read, R query_sequence, M md_operations) {
  74. debug {
  75. _initial_qseq = to!string(query_sequence);
  76. }
  77. _qseq = query_sequence;
  78. _md = md_operations;
  79. _fetchNextMdOperation();
  80. }
  81. bool empty() @property {
  82. return _empty;
  83. }
  84. /*
  85. MD operations -> match(N) ? consume N characters from query
  86. mismatch(C) ? consume a character from query and replace it with C
  87. deletion(S) ? consume S from MD
  88. */
  89. char front() @property {
  90. final switch (_cur_md_op.type) {
  91. case MdOperationType.Match:
  92. return cast(char)_qseq.front;
  93. case MdOperationType.Mismatch:
  94. return _cur_md_op.mismatch;
  95. case MdOperationType.Deletion:
  96. return cast(char)_cur_md_op.deletion.front;
  97. }
  98. }
  99. private void _fetchNextMdOperation() {
  100. if (_md.empty) {
  101. _empty = true;
  102. return;
  103. }
  104. _cur_md_op = _md.front;
  105. _md.popFront();
  106. }
  107. private bool _qseqIsSuddenlyEmpty() {
  108. if (!_qseq.empty) {
  109. return false;
  110. }
  111. /* MD and CIGAR don't match */
  112. debug {
  113. import std.stdio;
  114. stderr.writeln("Current MD operation: ", _cur_md_op);
  115. stderr.writeln("Query sequence: ", _initial_qseq);
  116. }
  117. return true;
  118. }
  119. void popFront() {
  120. final switch (_cur_md_op.type) {
  121. case MdOperationType.Mismatch:
  122. if (_qseqIsSuddenlyEmpty())
  123. break;
  124. _qseq.popFront();
  125. _fetchNextMdOperation();
  126. break;
  127. case MdOperationType.Match:
  128. if (_qseqIsSuddenlyEmpty())
  129. break;
  130. --_cur_md_op.match;
  131. _qseq.popFront();
  132. if (_cur_md_op.match == 0) {
  133. _fetchNextMdOperation();
  134. }
  135. break;
  136. case MdOperationType.Deletion:
  137. _cur_md_op.deletion.popFront();
  138. if (_cur_md_op.deletion.empty) {
  139. _fetchNextMdOperation();
  140. }
  141. break;
  142. }
  143. }
  144. private {
  145. debug {
  146. string _initial_qseq;
  147. }
  148. R _qseq;
  149. M _md;
  150. bool _empty;
  151. MdOperation _cur_md_op;
  152. }
  153. }
  154. auto md = _read["MD"];
  155. string md_str;
  156. if (!md.is_nothing) {
  157. md_str = cast(string)_read["MD"];
  158. }
  159. static auto getResult(R, M)(ref T read, R query, M md_ops) {
  160. return Result!(R, M)(read, query, md_ops);
  161. }
  162. auto result = getResult(_read,
  163. joiner(map!"a.sequence"(filter!"a.operation.is_reference_consuming"(query_chunks))),
  164. mdOperations(md_str));
  165. debug {
  166. import std.stdio;
  167. if (result.empty) {
  168. stderr.writeln("[dna] empty DNA!");
  169. stderr.writeln(" read name: ", read.name);
  170. stderr.writeln(" read sequence: ", read.sequence);
  171. stderr.writeln(" read CIGAR: ", read.cigarString());
  172. stderr.writeln(" read MD tag: ", read["MD"]);
  173. stderr.flush();
  174. }
  175. }
  176. return result;
  177. }
  178. unittest {
  179. import std.stdio;
  180. writeln("Testing reconstruction of reference from MD tags and CIGAR");
  181. // Test reference reconstruction from MD and CIGAR.
  182. // (Tests are taken from http://davetang.org/muse/2011/01/28/perl-and-sam/)
  183. BamRead read;
  184. read = BamRead("r1",
  185. "CGATACGGGGACATCCGGCCTGCTCCTTCTCACATG",
  186. [CigarOperation(36, 'M')]);
  187. read["MD"] = "1A0C0C0C1T0C0T27";
  188. assert(equal(dna(read), "CACCCCTCTGACATCCGGCCTGCTCCTTCTCACATG"));
  189. read = BamRead("r2",
  190. "GAGACGGGGTGACATCCGGCCTGCTCCTTCTCACAT",
  191. [CigarOperation(6, 'M'),
  192. CigarOperation(1, 'I'),
  193. CigarOperation(29, 'M')]);
  194. read["MD"] = "0C1C0C1C0T0C27";
  195. assert(equal(dna(read), "CACCCCTCTGACATCCGGCCTGCTCCTTCTCACAT"));
  196. read = BamRead("r3",
  197. "AGTGATGGGGGGGTTCCAGGTGGAGACGAGGACTCC",
  198. [CigarOperation(9, 'M'),
  199. CigarOperation(9, 'D'),
  200. CigarOperation(27, 'M')]);
  201. read["MD"] = "2G0A5^ATGATGTCA27";
  202. assert(equal(dna(read), "AGGAATGGGATGATGTCAGGGGTTCCAGGTGGAGACGAGGACTCC"));
  203. read = BamRead("r4",
  204. "AGTGATGGGAGGATGTCTCGTCTGTGAGTTACAGCA",
  205. [CigarOperation(2, 'M'),
  206. CigarOperation(1, 'I'),
  207. CigarOperation(7, 'M'),
  208. CigarOperation(6, 'D'),
  209. CigarOperation(26, 'M')]);
  210. read["MD"] = "3C3T1^GCTCAG26";
  211. assert(equal(dna(read), "AGGCTGGTAGCTCAGGGATGTCTCGTCTGTGAGTTACAGCA"));
  212. }
  213. /**
  214. * Returns lazy sequence of reference bases. If some bases can't be determined from reads,
  215. * they are replaced with 'N'.
  216. *
  217. * Reads must be a range of reads aligned to the same reference sequence, sorted by leftmost
  218. * coordinate.
  219. * Returned reference bases start from the leftmost position of the first read,
  220. * and end at the rightmost position of all the reads.
  221. */
  222. auto dna(R)(R reads)
  223. if (isInputRange!R && isBamRead!(Unqual!(ElementType!R)))
  224. {
  225. static struct Result(F) {
  226. alias Unqual!(ElementType!F) Read;
  227. this(F reads) {
  228. _reads = reads;
  229. if (_reads.empty) {
  230. _empty = true;
  231. return;
  232. }
  233. auto read = _reads.front;
  234. _chunk = dna(read);
  235. _reference_pos = read.position;
  236. _reads.popFront();
  237. }
  238. @property bool empty() {
  239. return _empty;
  240. }
  241. @property char front() {
  242. if (_bases_to_skip > 0) {
  243. return 'N';
  244. }
  245. return _chunk.front;
  246. }
  247. private void setSkipMode(ref Read read) {
  248. _reads.popFront();
  249. _chunk = dna(read);
  250. _bases_to_skip = read.position - _reference_pos;
  251. }
  252. void popFront() {
  253. _reference_pos += 1;
  254. if (_bases_to_skip > 0) {
  255. --_bases_to_skip;
  256. return;
  257. }
  258. _chunk.popFront();
  259. /*
  260. * If current chunk is empty, get the next one.
  261. *
  262. * Here's the reference:
  263. * .........................*.......................................
  264. * _reference_pos (we are here)
  265. * Last chunk ended just now:
  266. * [..........]
  267. * Go through subsequent reads while their leftmost position is
  268. * less or equal to _reference_pos, select the one which covers
  269. * more bases to the right of _reference_pos.
  270. * [...............]
  271. * [....]
  272. * [..........]
  273. * [.........] <- this one is the best
  274. */
  275. if (_chunk.empty) {
  276. if (_reads.empty) {
  277. _empty = true;
  278. return;
  279. }
  280. auto next_read = _reads.front;
  281. if (next_read.position > _reference_pos) {
  282. setSkipMode(next_read);
  283. return;
  284. }
  285. auto best_read = next_read;
  286. // read covers half-open [position .. position + basesCovered) interval
  287. auto best_end_pos = best_read.basesCovered() + best_read.position;
  288. bool found_good = best_end_pos > _reference_pos;
  289. while (true) {
  290. if (_reads.empty) {
  291. if (!found_good) {
  292. _empty = true;
  293. return;
  294. }
  295. break;
  296. }
  297. auto read = _reads.front;
  298. if (read.position > _reference_pos) {
  299. if (!found_good) {
  300. setSkipMode(read);
  301. return;
  302. }
  303. break;
  304. }
  305. auto end_pos = read.basesCovered() + read.position;
  306. if (end_pos > _reference_pos) {
  307. found_good = true;
  308. if (end_pos > best_end_pos) {
  309. best_end_pos = end_pos;
  310. best_read = read;
  311. }
  312. }
  313. _reads.popFront();
  314. }
  315. // If we're here, we've found a good read.
  316. _chunk = dna(best_read);
  317. debug {
  318. /*
  319. import std.stdio;
  320. writeln("_reference_pos = ", _reference_pos,
  321. "; best_read.position = ", best_read.position,
  322. "; _chunk length = ", best_read.basesCovered());
  323. */
  324. }
  325. // However, we need to strip some bases from the left.
  326. popFrontN(_chunk, _reference_pos - best_read.position);
  327. }
  328. }
  329. private size_t _bases_to_skip;
  330. private size_t _reference_pos;
  331. private ReturnType!(dna!Read) _chunk;
  332. private bool _empty = false;
  333. private F _reads;
  334. }
  335. auto nonempty = filter!"a.basesCovered() > 0"(reads);
  336. return Result!(typeof(nonempty))(nonempty);
  337. }
  338. unittest {
  339. // reads are taken from HG00110.chrom20.ILLUMINA.bwa.GBR.exome.20111114.bam
  340. auto r1 = BamRead("r1",
  341. "AGGTTTTGTGAGTGGGACAGTTGCAGCAAAACACAACCATAGGTGCCCATCCACCAAGGCAGGCTCTCCATCTTGCTCAGAGTGGCTCTA",
  342. [CigarOperation(89, 'M'),
  343. CigarOperation(1, 'S')]);
  344. r1.position = 60246;
  345. r1["MD"] = "89";
  346. auto r2 = BamRead("r2",
  347. "TGTGAGTGGGACAGTTGCAGCAAAACACAACCATAGGTGCCCATCCACCAAGGCAGGCTCTCCATCTTGCTCAGAGTGGCTCCAGCCCTT",
  348. [CigarOperation(83, 'M'),
  349. CigarOperation(7, 'S')]);
  350. r2.position = 60252;
  351. r2["MD"] = "82T0";
  352. auto r3 = BamRead("r3",
  353. "CATAGGTGCCCATCCACCAAGGCAGGCTCTCCATCTTGCTCAGAGTGGCTCTAGCCCTTGCTGACTGCTGGGCAGGGAGAGAGCAGAGCT",
  354. [CigarOperation(90, 'M')]);
  355. r3.position = 60283;
  356. r3["MD"] = "90";
  357. auto r4 = BamRead("r4",
  358. "CCCTTGCTGACTGCTGGGCAGGGAGAGAGCAGAGCTAACTTCCTCATGGGACCTGGGTGTGTCTGATCTGTGCACACCACTATCCAACCG",
  359. [CigarOperation(90, 'M')]);
  360. r4.position = 60337;
  361. r4["MD"] = "90";
  362. auto r5 = BamRead("r5",
  363. "GAGGCTCCACCCTGGCCACTCTTGTGTGCACACAGCACAGCCTCTACTGCTACACCTGAGTACTTTGCCAGTGGCCTGGAAGCACTTTGT",
  364. [CigarOperation(90, 'M')]);
  365. r5.position = 60432;
  366. r5["MD"] = "90";
  367. auto reads = [r1, r2, r3, r4, r5];
  368. assert(equal(dna(reads), "AGGTTTTGTGAGTGGGACAGTTGCAGCAAAACACAACCATAGGTGCCCATCCACCAAGGCAGGCTCTCCATCTTGCTCAGAGTGGCTCTAGCCCTTGCTGACTGCTGGGCAGGGAGAGAGCAGAGCTAACTTCCTCATGGGACCTGGGTGTGTCTGATCTGTGCACACCACTATCCAACCGNNNNNGAGGCTCCACCCTGGCCACTCTTGTGTGCACACAGCACAGCCTCTACTGCTACACCTGAGTACTTTGCCAGTGGCCTGGAAGCACTTTGT"));
  369. }