Debian Codegraph @

SeqLib/GenomicRegionCollection.cpp

raw symbols SCIP
1 #include "SeqLib/GenomicRegionCollection.h"
2
3 #include <iostream>
4 #include <sstream>
5 #include <fstream>
6 #include <cassert>
7 #include <set>
8 #include <stdexcept>
9 #include <algorithm>
10 #include <zlib.h>
11
12 #define GZBUFFER 65472
13
14 //#define DEBUG_OVERLAPS 1
15
16 namespace SeqLib {
17
18 template<class T>
19 GenomicRegionCollection<T>::GenomicRegionCollection(int width, int ovlp, const HeaderSequenceVector& h) {
20
21 idx = 0;
22 allocate_grc();
23
24 // undefined otherwise
25 if (width <= ovlp)
26 throw std::invalid_argument("Width should be > ovlp");
27
28 size_t chr = 0;
29 for (HeaderSequenceVector::const_iterator i = h.begin(); i != h.end(); ++i) {
30
31 T gr;
32 gr.chr = chr;
33 gr.pos1 = 0;
34 gr.pos2 = i->Length;
35 ++chr;
36
37 if (width >= gr.Width()) {
38 m_grv->push_back(gr);
39 continue;
40 }
41
42 int32_t start = gr.pos1;
43 int32_t end = gr.pos1 + width;
44
45 // region is smaller than width
46 if ( end > gr.pos2 ) {
47 std::cerr << "GenomicRegionCollection constructor: GenomicRegion is smaller than bin width" << std::endl;
48 return;
49 }
50
51 // loop through the sizes until done
52 while (end <= gr.pos2) {
53 T tg;
54 tg.chr = gr.chr;
55 tg.pos1 = start;
56 tg.pos2 = end;
57 m_grv->push_back(tg);
58 end += width - ovlp; // make the new one
59 start += width - ovlp;
60 }
61 assert(m_grv->size() > 0);
62
63
64 }
65 }
66
67 template<class T>
68 void GenomicRegionCollection<T>::CoordinateSort() {
69
70 if (m_grv) {
71 std::sort(m_grv->begin(), m_grv->end());
72 m_sorted = true;
73 }
74 }
75
76 template<class T>
77 void GenomicRegionCollection<T>::Shuffle() {
78 std::random_shuffle ( m_grv->begin(), m_grv->end() );
79 }
80
81 template<class T>
82 void GenomicRegionCollection<T>::SortAndStretchRight(int max) {
83
84 if (!m_grv->size())
85 return;
86
87 CoordinateSort();
88
89 if (max > 0 && max < m_grv->back().pos2)
90 throw std::out_of_range("GenomicRegionCollection::SortAndStrech Can't stretch to max, as we are already past max.");
91
92 for (size_t i = 0; i < m_grv->size() - 1; ++i)
93 m_grv->at(i).pos2 = m_grv->at(i+1).pos1 - 1;
94
95 if (max > 0)
96 m_grv->back().pos2 = max;
97
98 }
99
100 template<class T>
101 void GenomicRegionCollection<T>::SortAndStretchLeft(int min) {
102
103 if (!m_grv->size())
104 return;
105
106 CoordinateSort();
107
108 if (min >= 0 && min < m_grv->begin()->pos1)
109 throw std::out_of_range("GenomicRegionCollection::SortAndStrechLeft - Can't stretch to min, as we are already below min");
110
111 if (min >= 0)
112 m_grv->at(0).pos1 = min;
113
114 for (size_t i = 1; i < m_grv->size(); ++i)
115 m_grv->at(i).pos1 = m_grv->at(i-1).pos2 + 1;
116
117 }
118
119 template<class T>
120 bool GenomicRegionCollection<T>::ReadBED(const std::string & file, const BamHeader& hdr) {
121
122 m_sorted = false;
123 idx = 0;
124
125 gzFile fp = NULL;
126 fp = strcmp(file.c_str(), "-")? gzopen(file.c_str(), "r") : gzdopen(fileno(stdin), "r");
127
128 if (file.empty() || !fp) {
129 std::cerr << "BED file not readable: " << file << std::endl;
130 return false;
131 }
132
133 // http://www.lemoda.net/c/gzfile-read/
134 while (1) {
135
136 int err;
137 char buffer[GZBUFFER];
138 gzgets(fp, buffer, GZBUFFER);
139 int bytes_read = strlen(buffer);
140
141 // get one line
142 if (bytes_read < GZBUFFER - 1) {
143 if (gzeof (fp)) break;
144 else {
145 const char * error_string;
146 error_string = gzerror (fp, &err);
147 if (err) {
148 fprintf (stderr, "Error: %s.\n", error_string);
149 exit (EXIT_FAILURE);
150 }
151 }
152 }
153
154 // prepare to loop through each field of BED line
155 //size_t counter = 0;
156 std::string chr, pos1, pos2;
157 std::string line(buffer);
158 std::istringstream iss_line(line);
159 std::string val;
160 if (line.find("#") != std::string::npos)
161 continue;
162
163 // read first three BED columns
164 iss_line >> chr >> pos1 >> pos2;
165
166 // construct the GenomicRegion
167 T gr(chr, pos1, pos2, hdr);
168
169 if (gr.chr >= 0)
170 m_grv->push_back(gr);
171 }
172
173 return true;
174 }
175
176 template<class T>
177 bool GenomicRegionCollection<T>::ReadVCF(const std::string & file, const BamHeader& hdr) {
178
179 m_sorted = false;
180 idx = 0;
181
182 gzFile fp = NULL;
183 fp = strcmp(file.c_str(), "-")? gzopen(file.c_str(), "r") : gzdopen(fileno(stdin), "r");
184
185 if (file.empty() || !fp) {
186 std::cerr << "VCF file not readable: " << file << std::endl;
187 return false;
188 }
189
190 // http://www.lemoda.net/c/gzfile-read/
191 while (1) {
192
193 int err;
194 char buffer[GZBUFFER];
195 gzgets(fp, buffer, GZBUFFER);
196 int bytes_read = strlen(buffer);
197
198 // get one line
199 if (bytes_read < GZBUFFER - 1) {
200 if (gzeof (fp)) break;
201 else {
202 const char * error_string;
203 error_string = gzerror (fp, &err);
204 if (err) {
205 fprintf (stderr, "Error: %s.\n", error_string);
206 exit (EXIT_FAILURE);
207 }
208 }
209 }
210
211 // prepare to loop through each field of BED line
212 std::string chr, pos;
213 std::string line(buffer);
214 std::istringstream iss_line(line);
215 std::string val;
216 if (line.empty() || line.at(0) == '#')
217 continue;
218
219 // read first two columnes
220 iss_line >> chr >> pos;
221
222 // construct the GenomicRegion
223 T gr;
224 try {
225 gr = T(chr, pos, pos, hdr);
226 } catch (...) {
227 std::cerr << "...Could not parse pos: " << pos << std::endl << std::endl
228 << "...on line " << line << std::endl;
229
230 }
231 if (gr.chr >= 0)
232 m_grv->push_back(gr);
233 }
234
235 return true;
236 }
237
238 template<class T>
239 GenomicRegionCollection<T>::GenomicRegionCollection(const std::string &file, const BamHeader& hdr) {
240
241 allocate_grc();
242
243 idx = 0;
244
245 // check if it's samtools-style file
246 if (file.find(":") != std::string::npos) {
247 m_sorted = true; // only one, so sorted
248 m_grv->push_back(T(file, hdr));
249 return;
250 }
251
252 // BED file
253 if (file.find(".bed") != std::string::npos)
254 ReadBED(file, hdr);
255 // VCF file
256 else if (file.find(".vcf") != std::string::npos)
257 ReadVCF(file, hdr);
258 else // default is BED file
259 ReadBED(file, hdr);
260
261 }
262
263 // reduce a set of GenomicRegions into the minium overlapping set (same as GenomicRanges "reduce")
264 template <class T>
265 void GenomicRegionCollection<T>::MergeOverlappingIntervals() {
266
267 // make the list
268 std::list<T> intervals(m_grv->begin(), m_grv->end());
269
270 intervals.sort();
271 typename std::list<T>::iterator inext(intervals.begin());
272 ++inext;
273 for (typename std::list<T>::iterator i(intervals.begin()), iend(intervals.end()); inext != iend;) {
274 if((i->pos2 >= inext->pos1) && (i->chr == inext->chr)) // change >= to > to not overlap touching intervals (eg [4,5][5,6])
275 {
276 if(i->pos2 >= inext->pos2) intervals.erase(inext++);
277 else if(i->pos2 < inext->pos2)
278 { i->pos2 = inext->pos2; intervals.erase(inext++); }
279 }
280 else { ++i; ++inext; }
281 }
282
283 // move it over to a grv
284 m_grv->clear(); // clear the old data
285
286 // c++11
287 //std::vector<T> v{ std::make_move_iterator(std::begin(intervals)),
288 // std::make_move_iterator(std::end(intervals)) };
289 //m_grv->insert(m_grv->end(), v.begin(), v.end());
290
291 // non c++11
292 //std::vector<T> v;
293 // v.push_back(std::make_move_iterator(std::begin(intervals)));
294 //v.push_back(std::make_move_iterator(std::end(intervals)));
295 //std::vector<T> v{ std::make_move_iterator(std::begin(intervals)),
296 // std::make_move_iterator(std::end(intervals)) };
297 //m_grv->insert(m_grv->end(), v.begin(), v.end());
298 //m_grv->reserve(intervals.size());
299 //m_grv->append(intervals.begin(), intervals.end());
300 m_grv->insert(m_grv->end(), intervals.begin(), intervals.end());
301
302 // clear the old interval tree
303 m_tree->clear();
304 }
305
306 template <class T>
307 GenomicRegionVector GenomicRegionCollection<T>::AsGenomicRegionVector() const {
308 GenomicRegionVector gg;
309 for (typename std::vector<T>::const_iterator i = m_grv->begin(); i != m_grv->end(); ++i)
310 gg.push_back(GenomicRegion(i->chr, i->pos1, i->pos2, i->strand));
311 return gg;
312 }
313
314 template <class T>
315 void GenomicRegionCollection<T>::CreateTreeMap() {
316
317 if (!m_grv->size())
318 return;
319
320 // sort the genomic intervals
321 if (!m_sorted)
322 CoordinateSort();
323
324 // loop through and make the intervals for each chromosome
325 GenomicIntervalMap map;
326 for (size_t i = 0; i < m_grv->size(); ++i) {
327 map[m_grv->at(i).chr].push_back(GenomicInterval(m_grv->at(i).pos1, m_grv->at(i).pos2, i));
328 }
329
330 // for each chr, make the tree from the intervals
331 //for (auto it : map) {
332 for (GenomicIntervalMap::iterator it = map.begin(); it != map.end(); ++it) {
333 GenomicIntervalTreeMap::iterator ff = m_tree->find(it->first);
334 if (ff != m_tree->end())
335 ff->second = GenomicIntervalTree(it->second);
336 else
337 m_tree->insert(std::pair<int, GenomicIntervalTree>(it->first, GenomicIntervalTree(it->second)));
338 //old //m_tree[it.first] = GenomicIntervalTree(it.second);
339 }
340
341 }
342
343 template<class T>
344 int GenomicRegionCollection<T>::TotalWidth() const {
345 int wid = 0;
346 for (typename std::vector<T>::const_iterator i = m_grv->begin(); i != m_grv->end(); ++i)
347 // for (auto& i : *m_grv)
348 wid += i->Width();
349 return wid;
350 }
351
352 // divide a region into pieces of width and overlaps
353 template<class T>
354 GenomicRegionCollection<T>::GenomicRegionCollection(int width, int ovlp, const T &gr) {
355
356 idx = 0;
357 allocate_grc();
358
359 // undefined otherwise
360 if (width <= ovlp)
361 throw std::invalid_argument("Width should be > ovlp");
362 if (width >= gr.Width()) {
363 m_grv->push_back(gr);
364 return;
365 }
366
367 int32_t start = gr.pos1;
368 int32_t end = gr.pos1 + width;
369
370 // region is smaller than width
371 if ( end > gr.pos2 ) {
372 std::cerr << "GenomicRegionCollection constructor: GenomicRegion is smaller than bin width" << std::endl;
373 return;
374 }
375
376 // loop through the sizes until done
377 while (end <= gr.pos2) {
378 m_grv->push_back(T(gr.chr, start, end));
379 end += width - ovlp; // make the new one
380 start += width - ovlp;
381 }
382 assert(m_grv->size() > 0);
383
384 // finish the last one if we need to
385 if (m_grv->back().pos2 != gr.pos2) {
386 start = m_grv->back().pos2 - ovlp; //width;
387 end = gr.pos2;
388 m_grv->push_back(T(gr.chr, start, end));
389 }
390
391 m_sorted = true;
392
393 }
394
395 template<class T>
396 size_t GenomicRegionCollection<T>::CountOverlaps(const T &gr) const {
397
398 if (m_tree->size() == 0 && m_grv->size() != 0)
399 {
400 std::cerr << "!!!!!! WARNING: Trying to find overlaps on empty tree. Need to run this->createTreeMap() somewhere " << std::endl;
401 return 0;
402 }
403
404 GenomicIntervalVector giv;
405
406 GenomicIntervalTreeMap::const_iterator ff = m_tree->find(gr.chr);
407 if (ff == m_tree->end())
408 return 0;
409 ff->second.findOverlapping(gr.pos1, gr.pos2, giv);
410 return (giv.size());
411 }
412
413 template<class T>
414 template<class K>
415 bool GenomicRegionCollection<T>::OverlapSameInterval(const K &gr1, const K &gr2) const {
416
417 // events on diff chr do not overlap same bin
418 if (gr1.chr != gr2.chr)
419 return false;
420
421 if (m_tree->size() == 0 && m_grv->size() != 0) {
422 std::cerr << "!!!!!! WARNING: Trying to find overlaps on empty tree. Need to run this->createTreeMap() somewhere " << std::endl;
423 return false;
424 }
425
426 GenomicIntervalTreeMap::const_iterator ff1 = m_tree->find(gr1.chr);
427 GenomicIntervalTreeMap::const_iterator ff2 = m_tree->find(gr2.chr);
428 if (ff1 == m_tree->end() || ff2 == m_tree->end())
429 return false;
430
431 // do the interval tree query
432 GenomicIntervalVector giv1, giv2;
433 ff1->second.findOverlapping(gr1.pos1, gr1.pos2, giv1);
434 ff2->second.findOverlapping(gr2.pos1, gr2.pos2, giv2);
435
436 if (!giv1.size() || !giv2.size())
437 return false;
438
439 // each one only overlapped one element
440 if (giv1.size() == 1 && giv2.size() == 1)
441 return (giv1[0].value == giv2[0].value);
442
443 // make a set of the possible starts
444 SeqHashSet<int> vals;
445 // for (auto& i : giv1)
446 for (GenomicIntervalVector::iterator i = giv1.begin(); i != giv1.end(); ++i)
447 vals.insert(i->value);
448
449 // loop the other side and see if they mix
450 for (GenomicIntervalVector::iterator i = giv2.begin(); i != giv2.end(); ++i)
451 if (vals.count(i->value))
452 return true;
453
454 return false;
455
456 }
457
458 template<class T>
459 std::string GenomicRegionCollection<T>::AsBEDString(const BamHeader& h) const {
460
461 if (m_grv->size() == 0)
462 return std::string();
463
464 std::stringstream ss;
465 //for (auto& i : *m_grv)
466 for (typename std::vector<T>::const_iterator i = m_grv->begin(); i != m_grv->end(); ++i)
467 ss << i->ChrName(h) << "\t" << i->pos1 << "\t" << i->pos2 << "\t" << i->strand << std::endl;
468
469 return ss.str();
470
471 }
472
473 template<class T>
474 void GenomicRegionCollection<T>::Concat(const GenomicRegionCollection<T>& g)
475 {
476 if (!g.size())
477 return;
478 m_sorted = false;
479 m_grv->insert(m_grv->end(), g.m_grv->begin(), g.m_grv->end());
480 }
481
482 template<class T>
483 GenomicRegionCollection<T>::GenomicRegionCollection() {
484 idx = 0;
485 allocate_grc();
486 }
487
488 template<class T>
489 GenomicRegionCollection<T>::~GenomicRegionCollection() {
490 }
491
492
493 template<class T>
494 void GenomicRegionCollection<T>::allocate_grc() {
495 m_sorted = false;
496 m_grv = SeqPointer<std::vector<T> >(new std::vector<T>()) ;
497 m_tree = SeqPointer<GenomicIntervalTreeMap>(new GenomicIntervalTreeMap()) ;
498 }
499
500 template<class T>
501 GenomicRegionCollection<T>::GenomicRegionCollection(const BamRecordVector& brv) {
502 idx = 0;
503
504 allocate_grc();
505
506 //for (auto& i : brv)
507 for (BamRecordVector::const_iterator i = brv.begin(); i != brv.end(); ++i)
508 m_grv->push_back(GenomicRegion(i->ChrID(), i->Position(), i->PositionEnd()));
509
510 }
511
512 template<class T>
513 const T& GenomicRegionCollection<T>::at(size_t i) const
514 {
515 if (i >= m_grv->size())
516 throw 20;
517 return m_grv->at(i);
518 }
519
520
521 // this is query
522 template<class T>
523 template<class K>
524 std::vector<int> GenomicRegionCollection<T>::FindOverlappedIntervals(const K& gr, bool ignore_strand) const {
525
526 if (m_tree->size() == 0 && m_grv->size() != 0)
527 throw std::logic_error("Need to run CreateTreeMap to make the interval tree before doing range queries");
528
529 // which chr (if any) are common between query and subject
530 GenomicIntervalTreeMap::const_iterator ff = m_tree->find(gr.chr);
531
532 std::vector<int> output;
533
534 //must as least share a chromosome
535 if (ff == m_tree->end())
536 return output;
537
538 // get the subject hits
539 GenomicIntervalVector giv;
540 ff->second.findOverlapping(gr.pos1, gr.pos2, giv);
541
542 for (GenomicIntervalVector::const_iterator i = giv.begin(); i != giv.end(); ++i)
543 if (ignore_strand || m_grv->at(i->value).strand == gr.strand)
544 output.push_back(i->value);
545
546 return output;
547
548 }
549
550 template<class T>
551 template<class K>
552 size_t GenomicRegionCollection<T>::FindOverlapWidth(const K& gr, bool ignore_strand) const {
553
554 SeqLib::GRC out = FindOverlaps<K>(gr, ignore_strand);
555 if (!out.size())
556 return 0;
557
558 // make sure merged down
559 out.MergeOverlappingIntervals();
560
561 size_t val = 0;
562 for (size_t i = 0; i < out.size(); ++i)
563 val += out[i].Width();
564
565 return val;
566 }
567
568 // this is query
569 template<class T>
570 template<class K>
571 GenomicRegionCollection<GenomicRegion> GenomicRegionCollection<T>::FindOverlaps(const K& gr, bool ignore_strand) const
572 {
573
574 GenomicRegionCollection<GenomicRegion> output;
575
576 if (m_tree->size() == 0 && m_grv->size() != 0)
577 throw std::logic_error("Need to run CreateTreeMap to make the interval tree before doing range queries");
578
579 // which chr (if any) are common between query and subject
580 GenomicIntervalTreeMap::const_iterator ff = m_tree->find(gr.chr);
581
582 //must as least share a chromosome
583 if (ff == m_tree->end())
584 return output;
585
586 // get the subject hits
587 GenomicIntervalVector giv;
588 ff->second.findOverlapping(gr.pos1, gr.pos2, giv);
589
590 #ifdef DEBUG_OVERLAPS
591 std::cerr << "ff->second.intervals.size() " << ff->second.intervals.size() << std::endl;
592 for (auto& k : ff->second.intervals)
593 std::cerr << " intervals " << k.start << " to " << k.stop << " value " << k.value << std::endl;
594 std::cerr << "GIV NUMBER OF HITS " << giv.size() << " for query " << gr << std::endl;
595 #endif
596
597 // loop through the hits and define the GenomicRegion
598 for (GenomicIntervalVector::const_iterator j = giv.begin(); j != giv.end(); ++j) {
599 //for (auto& j : giv) { // giv points to positions on subject
600 if (ignore_strand || (m_grv->at(j->value).strand == gr.strand) ) {
601 #ifdef DEBUG_OVERLAPS
602 std::cerr << "find overlaps hit " << j->start << " " << j->stop << " -- " << j->value << std::endl;
603 #endif
604 output.add(GenomicRegion(gr.chr, std::max(static_cast<int32_t>(j->start), gr.pos1), std::min(static_cast<int32_t>(j->stop), gr.pos2)));
605 }
606 }
607
608 return output;
609
610 }
611
612 // this is query
613 template<class T>
614 template<class K>
615 GenomicRegionCollection<GenomicRegion> GenomicRegionCollection<T>::FindOverlaps(const GenomicRegionCollection<K>& subject, std::vector<int32_t>& query_id, std::vector<int32_t>& subject_id, bool ignore_strand) const
616 {
617
618 GenomicRegionCollection<GenomicRegion> output;
619 if (subject.NumTree() == 0 && subject.size() != 0) {
620 std::cerr << "!!!!!! findOverlaps: WARNING: Trying to find overlaps on empty tree. Need to run this->createTreeMap() somewhere " << std::endl;
621 return output;
622 }
623
624 // we loop through query, so want it to be smaller
625 if (subject.size() < m_grv->size() && m_grv->size() - subject.size() > 20)
626 std::cerr << "findOverlaps warning: Suggest switching query and subject for efficiency." << std::endl;
627
628 #ifdef DEBUG_OVERLAPS
629 std::cerr << "OVERLAP SUBJECT: " << std::endl;
630 for (auto& i : subject)
631 std::cerr << i << std::endl;
632 #endif
633
634 // loop through the query GRanges (this) and overlap with subject
635 for (size_t i = 0; i < m_grv->size(); ++i)
636 {
637 // which chr (if any) are common between query and subject
638 GenomicIntervalTreeMap::const_iterator ff = subject.GetTree()->find(m_grv->at(i).chr);
639
640 GenomicIntervalVector giv;
641
642 #ifdef DEBUG_OVERLAPS
643 std::cerr << "TRYING OVERLAP ON QUERY " << m_grv->at(i) << std::endl;
644 #endif
645 //must as least share a chromosome
646 if (ff != m_tree->end())
647 {
648 // get the subject hits
649 ff->second.findOverlapping(m_grv->at(i).pos1, m_grv->at(i).pos2, giv);
650
651 #ifdef DEBUG_OVERLAPS
652 std::cerr << "ff->second.intervals.size() " << ff->second.intervals.size() << std::endl;
653 for (auto& k : ff->second.intervals)
654 std::cerr << " intervals " << k.start << " to " << k.stop << " value " << k.value << std::endl;
655 std::cerr << "GIV NUMBER OF HITS " << giv.size() << " for query " << m_grv->at(i) << std::endl;
656 #endif
657 // loop through the hits and define the GenomicRegion
658 for (GenomicIntervalVector::const_iterator j = giv.begin(); j != giv.end(); ++j) {
659 //for (auto& j : giv) { // giv points to positions on subject
660 if (ignore_strand || (subject.at(j->value).strand == m_grv->at(i).strand) ) {
661 query_id.push_back(i);
662 subject_id.push_back(j->value);
663 #ifdef DEBUG_OVERLAPS
664 std::cerr << "find overlaps hit " << j->start << " " << j->stop << " -- " << j->value << std::endl;
665 #endif
666 output.add(GenomicRegion(m_grv->at(i).chr, std::max(static_cast<int32_t>(j->start), m_grv->at(i).pos1), std::min(static_cast<int32_t>(j->stop), m_grv->at(i).pos2)));
667 }
668 }
669 }
670 }
671
672 return output;
673
674 }
675
676
677 template<class T>
678 GenomicRegionCollection<T>::GenomicRegionCollection(const T& gr)
679 {
680 m_sorted = true;
681 idx = 0;
682 allocate_grc();
683 m_grv->push_back(gr);
684 }
685
686 template<class T>
687 template<class K>
688 GRC GenomicRegionCollection<T>::Intersection(const GenomicRegionCollection<K>& subject, bool ignore_strand) const
689 {
690 std::vector<int32_t> sub, que;
691 GRC out;
692 if (subject.size() > this->size()) // do most efficient ordering
693 out = this->FindOverlaps<K>(subject, que, sub, ignore_strand);
694 else
695 out = subject.FindOverlaps(*this, que, sub, ignore_strand);
696 return out;
697 }
698
699 template<class T>
700 void GenomicRegionCollection<T>::Pad(int v)
701 {
702 //for (auto& i : *m_grv)
703 for (typename std::vector<T>::iterator i = m_grv->begin(); i != m_grv->end(); ++i)
704 i->Pad(v);
705 }
706
707 }
708