Debian Codegraph @

src/BamReader.cpp

raw symbols SCIP
1 #include "SeqLib/BamReader.h"
2
3 //#define DEBUG_WALKER 1
4
5 namespace SeqLib {
6
7 // set the bam region
8 bool _Bam::SetRegion(const GenomicRegion& gp) {
9
10 // mark it "open" again, may be new reads here
11 mark_for_closure = false;
12
13 //HTS set region
14 if ( (fp->format.format == 4 || fp->format.format == 6) && !idx) // BAM (4) or CRAM (6)
15 idx = SharedIndex(sam_index_load(fp.get(), m_in.c_str()), idx_delete());
16
17 if (!idx) {
18 if (m_in != "-")
19 std::cerr << "Failed to load index for " << m_in << ". Rebuild samtools index" << std::endl;
20 else
21 std::cerr << "Random access with SetRegion not available for STDIN reading (no index file)" << std::endl;
22 return false;
23 }
24
25 if (gp.chr >= m_hdr.NumSequences()) {
26 std::cerr << "Failed to set region on " << gp << ". Chr ID is bigger than n_targets=" << m_hdr.NumSequences() << std::endl;
27 return false;
28 }
29
30 // should work for BAM or CRAM
31 hts_itr = SeqPointer<hts_itr_t>(sam_itr_queryi(idx.get(), gp.chr, gp.pos1, gp.pos2), hts_itr_delete());
32
33 if (!hts_itr) {
34 std::cerr << "Error: Failed to set region: " << gp << std::endl;
35 return false;
36 }
37
38 return true;
39 }
40
41 void BamReader::Reset() {
42 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b)
43 b->second.reset();
44 m_region = GRC();
45 }
46
47 bool BamReader::Reset(const std::string& f) {
48
49 // cant reset what we don't have
50 if (!m_bams.count(f))
51 return false;
52 m_bams[f].reset();
53 return true;
54 }
55
56 bool BamReader::Close() {
57
58 bool success = true;
59 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b)
60 success = success && b->second.close();
61 return success;
62 }
63
64 bool BamReader::Close(const std::string& f) {
65
66 // cant close what we don't have
67 if (!m_bams.count(f))
68 return false;
69
70 return m_bams[f].close();
71 }
72
73 /* SharedHTSFile BamReader::GetHTSFile () const {
74 if (!m_bams.size())
75 throw std::runtime_error("No BAMs have been opened yet");
76 return m_bams.begin()->second.fp;
77 }
78
79 SharedHTSFile BamReader::GetHTSFile(const std::string& f) const {
80 _BamMap::const_iterator ff = m_bams.find(f);
81 if (ff == m_bams.end())
82 throw std::runtime_error("File " + f + " has not been opened yet");
83 return ff->second.fp;
84 }
85
86
87 bool BamReader::SetPreloadedIndex(SharedIndex& i) {
88 if (!m_bams.size())
89 return false;
90 m_bams.begin()->second.set_index(i);
91 return true;
92 }
93
94 bool BamReader::SetPreloadedIndex(const std::string& f, SharedIndex& i) {
95 if (!m_bams.count(f))
96 return false;
97 m_bams[f].set_index(i);
98 return true;
99 }
100
101 */
102
103 bool BamReader::SetRegion(const GenomicRegion& g) {
104 m_region.clear();
105 m_region.add(g);
106
107 bool success = true;
108 if (m_region.size()) {
109 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b) {
110 b->second.m_region = &m_region;
111 b->second.m_region_idx = 0; // set to the begining
112 success = success && b->second.SetRegion(m_region[0]);
113 }
114 return success;
115 }
116
117 return false;
118
119 }
120
121 bool BamReader::SetMultipleRegions(const GRC& grc)
122 {
123 if (grc.size() == 0) {
124 std::cerr << "Warning: Trying to set an empty bam region" << std::endl;
125 return false;
126 }
127
128 m_region = grc;
129
130 // go through and start all the BAMs at the first region
131 bool success = true;
132 if (m_region.size()) {
133 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b) {
134 b->second.m_region = &m_region;
135 b->second.m_region_idx = 0; // set to the begining
136 success = success && b->second.SetRegion(m_region[0]);
137 }
138 return success;
139 }
140
141 return false;
142 }
143
144 bool BamReader::Open(const std::string& bam) {
145
146 // dont open same bam twice
147 if (m_bams.count(bam))
148 return false;
149
150 _Bam new_bam(bam);
151 if (!m_cram_reference.empty()) new_bam.m_cram_reference = m_cram_reference;
152 new_bam.m_region = &m_region;
153 bool success = new_bam.open_BAM_for_reading(pool);
154 m_bams.insert(std::pair<std::string, _Bam>(bam, new_bam));
155 return success;
156 }
157
158 bool BamReader::Open(const std::vector<std::string>& bams) {
159
160 bool pass = true;
161 for (std::vector<std::string>::const_iterator i = bams.begin(); i != bams.end(); ++i)
162 pass = pass && Open(*i);
163 return pass;
164 }
165
166 BamReader::BamReader() {}
167
168 std::string BamReader::HeaderConcat() const {
169 std::stringstream ss;
170 for (_BamMap::const_iterator i = m_bams.begin(); i != m_bams.end(); ++i)
171 ss << i->second.m_hdr.AsString();
172 return ss.str();
173
174 }
175
176 bool BamReader::SetThreadPool(ThreadPool p) {
177 if (!p.IsOpen())
178 return false;
179 pool = p;
180 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b)
181 b->second.set_pool(p);
182 return true;
183 }
184
185 BamHeader BamReader::Header() const {
186 if (m_bams.size())
187 return m_bams.begin()->second.m_hdr;
188 return BamHeader();
189 }
190
191 bool _Bam::open_BAM_for_reading(SeqLib::ThreadPool t) {
192
193 // HTS open the reader
194 fp = SharedHTSFile(hts_open(m_in.c_str(), "r"), htsFile_delete());
195
196 // connect the thread pool (may already be done, but its ok
197 set_pool(t);
198
199 // open cram reference
200 if (!m_cram_reference.empty()) {
201 int ret = hts_set_fai_filename(fp.get(), m_cram_reference.c_str());
202 if (ret < 0)
203 throw std::invalid_argument("Could not read reference genome " + m_cram_reference + " for CRAM opt");
204 }
205
206 // check if opening failed
207 if (!fp)
208 return false;
209
210 // read the header and create a BamHeader
211 bam_hdr_t * hdr = sam_hdr_read(fp.get());
212 m_hdr = BamHeader(hdr); // calls BamHeader(bam_hdr_t), makes a copy
213
214 // deallocate the memory we just made
215 if (hdr)
216 bam_hdr_destroy(hdr);
217
218 // if BAM header opening failed, return false
219 if (!m_hdr.get())
220 return false;
221
222 // everything worked
223 return true;
224
225 }
226
227 void BamReader::SetCramReference(const std::string& ref) {
228 m_cram_reference = ref;
229 for (_BamMap::iterator b = m_bams.begin(); b != m_bams.end(); ++b)
230 b->second.m_cram_reference = ref;
231 }
232
233 bool BamReader::GetNextRecord(BamRecord& r) {
234
235 // shortcut if we have only a single bam
236 if (m_bams.size() == 1) {
237
238 if (m_bams.begin()->second.fp.get() == NULL || m_bams.begin()->second.mark_for_closure) // cant read if not opened
239 return false;
240
241 // try and get the next read
242 int32_t status = m_bams.begin()->second.load_read(r);
243 if (status >= 0)
244 return true;
245 if (status == -1) {
246 // didn't find anything, clear it
247 m_bams.begin()->second.mark_for_closure = true;
248 return false;
249 }
250
251 // run time error
252 std::stringstream ss;
253 ss << "sam_read1 return status: " << status << " file: " << m_bams.begin()->first;
254 throw std::runtime_error(ss.str());
255 return false;
256 }
257
258 // loop the files and load the next read
259 // for the one that was emptied last
260 for (_BamMap::iterator bam = m_bams.begin(); bam != m_bams.end(); ++bam) {
261
262 _Bam *tb = &(bam->second);
263
264 // if marked, then don't even try on this BAM
265 if (tb->mark_for_closure)
266 continue;
267
268 // skip un-opened BAMs
269 if (tb->fp.get() == NULL)
270 continue;
271
272 // if next read is not marked as empty, skip to next
273 if (!tb->empty)
274 continue;
275
276 // load the next read
277 int32_t status = tb->load_read(r);
278 if (status == -1) {
279 // can't load, so mark for closing
280 tb->empty = true;
281 tb->mark_for_closure = true; // no more reads in this BAM
282 continue;
283 } else if (status < 0) { // error sent back from sam_read1
284 // run time error
285 std::stringstream ss;
286 ss << "sam_read1 return status: " << status << " file: " << bam->first;
287 throw std::runtime_error(ss.str());
288 }
289
290 }
291
292 // for multiple bams, choose the one to return
293 // sort based on chr and left-most alignment pos. Same as samtools
294 int min_chr = INT_MAX;
295 int min_pos = INT_MAX;
296 _BamMap::iterator hit;
297 bool found = false; // did we find a valid read
298
299 for (_BamMap::iterator bam = m_bams.begin();
300 bam != m_bams.end(); ++bam) {
301
302 // dont check if already marked for removal or doesnt need new read
303 if (bam->second.empty || bam->second.mark_for_closure)
304 continue;
305
306 found = true;
307 if (bam->second.next_read.ChrID() < min_chr || // check if read in this BAM is lowest
308 (bam->second.next_read.Position() < min_pos && bam->second.next_read.ChrID() == min_chr)) {
309 min_pos = bam->second.next_read.Position();
310 min_chr = bam->second.next_read.ChrID();
311 hit = bam; // read is lowest, so mark this BAM as having the hit
312 }
313 }
314
315 // mark the one we just found as empty
316 if (found) {
317 r = hit->second.next_read; // read is lowest, so assign
318 hit->second.empty = true; // mark as empty, so we fill this slot again
319 }
320
321 return found;
322 }
323
324 std::string BamReader::PrintRegions() const {
325
326 std::stringstream ss;
327 //for (GRC::const_iterator r = m_region.begin(); r != m_region.end(); ++r)
328 // ss << *r << std::endl;
329 return(ss.str());
330
331 }
332
333 int32_t _Bam::load_read(BamRecord& r) {
334
335 // allocated the memory
336 bam1_t* b = bam_init1();
337 int32_t valid = -1; // start with EOF return code
338
339 if (hts_itr.get() == NULL) {
340 valid = sam_read1(fp.get(), m_hdr.get_(), b);
341
342 if (valid < 0) {
343
344 #ifdef DEBUG_WALKER
345 std::cerr << "ended reading on null hts_itr" << std::endl;
346 #endif
347 //goto endloop;
348 bam_destroy1(b);
349 return valid;
350 }
351 } else {
352
353 //changed to sam from hts_itr_next
354 // move to next region of bam
355 valid = sam_itr_next(fp.get(), hts_itr.get(), b);
356 }
357
358 if (valid < 0) { // read still not found
359 do {
360
361 #ifdef DEBUG_WALKER
362 std::cerr << "Failed read, trying next region. Moving counter to " << m_region_idx << " of " << m_region.size() << " FP: " << fp_htsfile << " hts_itr " << std::endl;
363 #endif
364 // try next region, return if no others to try
365 ++m_region_idx; // increment to next region
366 if (m_region_idx >= m_region->size()) {
367 bam_destroy1(b);
368 return valid;
369 }
370 //goto endloop;
371
372 // next region exists, try it
373 SetRegion(m_region->at(m_region_idx));
374 valid = sam_itr_next(fp.get(), hts_itr.get(), b);
375 } while (valid <= 0); // keep trying regions until works
376 }
377
378 // if we got here, then we found a read in this BAM
379 empty = false;
380 next_read.assign(b); // assign the shared_ptr for the bam1_t
381 r = next_read;
382
383 return valid;
384 }
385
386 std::ostream& operator<<(std::ostream& out, const BamReader& b)
387 {
388 for(_BamMap::const_iterator bam = b.m_bams.begin(); bam != b.m_bams.end(); ++bam)
389 out << ":" << bam->second.GetFileName() << std::endl;
390
391 if (b.m_region.size() && b.m_region.size() < 20) {
392 out << " ------- BamReader Regions ----------" << std::endl;;
393 //for (GRC::const_iterator r = b.m_region.begin(); r != b.m_region.end(); ++r)
394 // out << *i << std::endl;
395 }
396 else if (b.m_region.size() >= 20) {
397 int wid = 0;
398 //for (GRC::const_iterator r = b.m_region.begin(); r != b.m_region.end(); ++r)
399 // wid += r->Width();
400 out << " ------- BamReader Regions ----------" << std::endl;;
401 out << " -- " << b.m_region.size() << " regions covering " << AddCommas(wid) << " bp of sequence" << std::endl;
402 }
403 else
404 out << " - BamReader - Walking whole genome -" << std::endl;
405
406 out << " ------------------------------------";
407 return out;
408 }
409
410 }