1 /*
2     This file is part of BioD.
3     Copyright (C) 2012-2013    Artem Tarasov <lomereiter@gmail.com>
4 
5     Permission is hereby granted, free of charge, to any person obtaining a
6     copy of this software and associated documentation files (the "Software"),
7     to deal in the Software without restriction, including without limitation
8     the rights to use, copy, modify, merge, publish, distribute, sublicense,
9     and/or sell copies of the Software, and to permit persons to whom the
10     Software is furnished to do so, subject to the following conditions:
11 
12     The above copyright notice and this permission notice shall be included in
13     all copies or substantial portions of the Software.
14 
15     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20     FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21     DEALINGS IN THE SOFTWARE.
22 
23 */
24 module bio.std.hts.sam.reader;
25 //
26 import bio.std.hts.bam.abstractreader;
27 import bio.std.hts.sam.header;
28 import bio.std.hts.bam.read;
29 import bio.std.hts.bam.reference;
30 import bio.std.hts.bam.referenceinfo;
31 import bio.core.utils.outbuffer;
32 import bio.core.utils.range;
33 
34 import bio.core.utils.bylinefast;
35 alias ByLineFast _LineRange;
36 
37 version(DigitalMars) {
38     import bio.std.hts.sam.utils.recordparser;
39 } else {
40     import bio.std.hts.sam.utils.fastrecordparser;
41 }
42 
43 import std.stdio;
44 import std.array;
45 import std..string;
46 import std.range;
47 import std.algorithm;
48 import std.typecons;
49 import std.parallelism;
50 import std.process;
51 import std.exception;
52 import core.stdc..string;
53 
54 BamRead _parseSamRecord(Tuple!(char[], SamReader, OutBuffer) t) {
55     auto r = parseAlignmentLine(cast(string)t[0], t[1]._header, t[2]);
56     BamRead result;
57     if (t[1]._seqprocmode) {
58         result = r;
59     } else {
60         auto storage = uninitializedArray!(ubyte[])(r.raw_data.length);
61         storage[] = r.raw_data[];
62         result.raw_data = storage;
63     }
64     result.associateWithReader(t[1]);
65     return result;
66 }
67 
68 private {
69     extern(C) size_t lseek(int, size_t, int);
70     bool isSeekable(ref File file) {
71         return lseek(file.fileno(), 0, 0) != ~0;
72     }
73 }
74 
75 ///
76 class SamReader : IBamSamReader {
77 
78     private {
79         version(gzippedSamSupport) {
80         void checkGunzip() {
81             auto gunzip = executeShell("gunzip -V");
82             if (gunzip.status != 0)
83                 throw new Exception("gunzip is not installed on this system, can't read gzipped SAM");
84         }
85 
86         File openSamFile(string filename) {
87             if (filename.length < 4)
88                 throw new Exception("invalid name for SAM file: " ~ filename);
89             if (filename[$ - 3 .. $] == ".gz") {
90                 checkGunzip();
91                 auto pipe = pipeShell("gunzip -c " ~ filename);
92                 return pipe.stdout;
93             } else if (filename[$ - 4 .. $] == ".bam") {
94                 throw new Exception("SAM reader can't read BAM file " ~ filename);
95             } else {
96                 return File(filename);
97             }
98         }
99 
100         } else {
101 
102         File openSamFile(string filename) {
103             if (filename[$ - 4 .. $] == ".bam") {
104                 throw new Exception("SAM reader can't read BAM file " ~ filename);
105             } else {
106                 return File(filename);
107             }
108         }
109 
110         }
111     }
112 
113     ///
114     this(string filename) {
115         _file = openSamFile(filename);
116         _filename = filename;
117         _seekable = _file.isSeekable();
118         _initializeStream();
119     }
120 
121     ///
122     bio.std.hts.sam.header.SamHeader header() @property {
123         return _header;
124     }
125 
126     ///
127     const(bio.std.hts.bam.referenceinfo.ReferenceSequenceInfo)[] reference_sequences() @property const {
128         return _reference_sequences;
129     }
130 
131     ///
132     bool hasReference(string reference) {
133         return null != (reference in _reference_sequence_dict);
134     }
135 
136     ///
137     bio.std.hts.bam.reference.ReferenceSequence opIndex(string ref_name) {
138         enforce(hasReference(ref_name), "Reference with name " ~ ref_name ~ " is not present in the header");
139         auto ref_id = _reference_sequence_dict[ref_name];
140         return ReferenceSequence(null, ref_id, _reference_sequences[ref_id]);
141     }
142 
143     /// Reads in SAM file.
144     auto reads() @property {
145 
146         _LineRange lines = _lines;
147         if (_seekable) {
148             if (_filename !is null) {
149                 auto file = openSamFile(_filename);
150                 lines = ByLineFast(file);
151             } else {
152                 _file.seek(0);
153                 lines = ByLineFast(_file);
154             }
155             auto dummy = lines.front;
156             for (int i = 0; i < _lines_to_skip; i++)
157                 lines.popFront();
158         }
159 
160         auto b = new OutBuffer(262144);
161         return lines.zip(repeat(this), repeat(b)).map!_parseSamRecord();
162     }
163 
164     ///
165     void assumeSequentialProcessing() {
166         _seqprocmode = true;
167     }
168 
169     ///
170     std.range.InputRange!(bio.std.hts.bam.read.BamRead) allReads() @property {
171         return inputRangeObject(reads);
172     }
173 
174     /// Filename
175     string filename() @property const {
176         return _filename;
177     }
178 private:
179 
180     File _file;
181     bool _seekable;
182     string _filename;
183     _LineRange _lines;
184     ulong _lines_to_skip;
185 
186     bool _seqprocmode;
187 
188     SamHeader _header;
189     ReferenceSequenceInfo[] _reference_sequences;
190     int[string] _reference_sequence_dict;
191 
192     void _initializeStream() {
193         auto header = Appender!(char[])();
194 
195         _lines = ByLineFast(_file);
196 
197         while (!_lines.empty) {
198             auto line = _lines.front;
199             if (line.length > 0 && line[0] == '@') {
200                 header.put(line);
201                 header.put('\n');
202                 _lines_to_skip += 1;
203                 _lines.popFront();
204             } else {
205                 break;
206             }
207         }
208 
209         import core.memory;
210         GC.disable();
211         _header = new SamHeader(cast(string)(header.data));
212         GC.enable();
213 
214         _reference_sequences = new ReferenceSequenceInfo[_header.sequences.length];
215         foreach (sq; _header.sequences) {
216             auto seq = ReferenceSequenceInfo(sq.name, sq.length);
217             auto n = cast(int)_reference_sequences.length;
218             _reference_sequence_dict[sq.name] = n;
219             _reference_sequences[_header.getSequenceIndex(seq.name)] = seq;
220         }
221     }
222 }