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.
 
 
 

164 lines
5.6 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.writer;
  21. import bio.bam.referenceinfo;
  22. import bio.sam.header;
  23. import bio.bam.constants;
  24. import bio.core.bgzf.outputstream;
  25. import bio.core.utils.stream;
  26. import bio.core.utils.switchendianness;
  27. import std.parallelism;
  28. import std.exception;
  29. import std.stream;
  30. import std.traits;
  31. import std.system;
  32. /** Class for outputting BAM.
  33. $(BR)
  34. Compresses BGZF blocks in parallel.
  35. Tries to write reads so that they don't cross BGZF block borders.
  36. $(BR)
  37. Usage is very simple, see example below.
  38. Example:
  39. --------------------------------------
  40. import bio.bam.writer, bio.bam.reader;
  41. ...
  42. auto src = new BamReader("in.bam");
  43. auto dst = new BamWriter("out.bam", 9); // maximal compression
  44. scope (exit) dst.finish(); // close the stream at exit
  45. dst.writeSamHeader(src.header); // copy header and reference sequence info
  46. dst.writeReferenceSequenceInfo(src.reference_sequences);
  47. foreach (read; src.reads) {
  48. if (read.mapping_quality > 10) // skip low-quality reads
  49. dst.writeRecord(read);
  50. }
  51. --------------------------------------
  52. */
  53. final class BamWriter {
  54. /// Creates new BAM writer outputting to file or $(I stream).
  55. /// Automatically writes BAM magic number (4 bytes).
  56. ///
  57. /// Params:
  58. /// compression_level = compression level, must be in range -1..9
  59. /// task_pool = task pool to use for parallel compression
  60. this(std.stream.Stream stream,
  61. int compression_level=-1,
  62. std.parallelism.TaskPool task_pool=std.parallelism.taskPool)
  63. {
  64. _stream = new BgzfOutputStream(stream, compression_level, task_pool);
  65. writeString(BAM_MAGIC);
  66. }
  67. /// ditto
  68. this(string filename,
  69. int compression_level=-1,
  70. std.parallelism.TaskPool task_pool=std.parallelism.taskPool)
  71. {
  72. auto filestream = new bio.core.utils.stream.File(filename, "wb+");
  73. this(filestream, compression_level, task_pool);
  74. }
  75. package void writeByteArray(const(ubyte[]) array) {
  76. _stream.writeExact(array.ptr, array.length);
  77. }
  78. package void writeString(string str) {
  79. writeByteArray(cast(ubyte[])str);
  80. }
  81. package void writeInteger(T)(T integer) if (isIntegral!T)
  82. {
  83. T num = integer;
  84. static if (T.sizeof != 1) {
  85. if (std.system.endian != Endian.littleEndian) {
  86. switchEndianness(&num, T.sizeof);
  87. }
  88. }
  89. _stream.writeExact(&num, T.sizeof);
  90. }
  91. /// Writes SAM header. Should be called after construction.
  92. void writeSamHeader(bio.sam.header.SamHeader header) {
  93. auto text = header.text;
  94. writeInteger(cast(int)text.length);
  95. writeString(text);
  96. }
  97. /// Writes reference sequence information. Should be called after
  98. /// dumping SAM header. Writer will store this array to use later for
  99. /// resolving read reference IDs to names.
  100. ///
  101. /// Flushes current BGZF block.
  102. void writeReferenceSequenceInfo(const(bio.bam.referenceinfo.ReferenceSequenceInfo)[] reference_sequences)
  103. {
  104. _reference_sequences = reference_sequences;
  105. writeInteger(cast(int)reference_sequences.length);
  106. foreach (sequence; reference_sequences) {
  107. writeInteger(cast(int)(sequence.name.length + 1));
  108. writeString(sequence.name);
  109. writeInteger(cast(ubyte)'\0');
  110. writeInteger(cast(int)sequence.length);
  111. }
  112. _stream.flushCurrentBlock();
  113. }
  114. /// Writes BAM read. Throws exception if read reference ID is out of range.
  115. void writeRecord(R)(R read) {
  116. enforce(read.ref_id == -1 || read.ref_id < _reference_sequences.length,
  117. "Read reference ID is out of range");
  118. auto read_size = read.size_in_bytes;
  119. if (read_size + _current_size > BGZF_BLOCK_SIZE) {
  120. _stream.flushCurrentBlock();
  121. read.write(this);
  122. _current_size = read_size;
  123. } else {
  124. read.write(this);
  125. _current_size += read_size;
  126. }
  127. }
  128. /// Flushes current BGZF block.
  129. void flush() {
  130. _stream.flush();
  131. }
  132. /// Flushes buffer and closes output stream. Adds BAM EOF block automatically.
  133. void finish() {
  134. _stream.close();
  135. }
  136. private {
  137. BgzfOutputStream _stream;
  138. const(ReferenceSequenceInfo)[] _reference_sequences;
  139. size_t _current_size; // number of bytes written to the current BGZF block
  140. }
  141. }