Debian Codegraph @

src/util.h

raw symbols SCIP
1 #ifndef UTIL_H
2 #define UTIL_H
3
4 #include <boost/multi_array.hpp>
5 #include <boost/unordered_map.hpp>
6 #include <boost/algorithm/string.hpp>
7 #include <boost/iostreams/filtering_streambuf.hpp>
8 #include <boost/iostreams/copy.hpp>
9 #include <boost/iostreams/filter/gzip.hpp>
10 #include <htslib/sam.h>
11 #include <sstream>
12 #include <math.h>
13
14 #include "edlib.h"
15 #include "tags.h"
16
17
18 namespace torali
19 {
20
21 #ifndef LAST_BIN
22 #define LAST_BIN 65535
23 #endif
24
25 #ifndef MAX_CN
26 #define MAX_CN 10
27 #endif
28
29 struct LibraryInfo {
30 int32_t rs;
31 int32_t median;
32 int32_t mad;
33 int32_t minNormalISize;
34 int32_t minISizeCutoff;
35 int32_t maxNormalISize;
36 int32_t maxISizeCutoff;
37 uint32_t abnormal_pairs;
38
39 LibraryInfo() : rs(0), median(0), mad(0), minNormalISize(0), minISizeCutoff(0), maxNormalISize(0), maxISizeCutoff(0), abnormal_pairs(0) {}
40 };
41
42 struct CNV {
43 int32_t chr;
44 int32_t start;
45 int32_t end;
46 int32_t ciposlow;
47 int32_t ciposhigh;
48 int32_t ciendlow;
49 int32_t ciendhigh;
50 int32_t qval;
51 double cn;
52 double mappable;
53 double sd;
54
55
56 CNV() : chr(0), start(0), end(0), ciposlow(0), ciposhigh(0), ciendlow(0), ciendhigh(0), qval(0), cn(-1), mappable(0), sd(1) {}
57 CNV(int32_t const c, int32_t const s, int32_t const e, int32_t const cil, int32_t const cih, int32_t const cel, int32_t ceh, double const estcn, double const mp) : chr(c), start(s), end(e), ciposlow(cil), ciposhigh(cih), ciendlow(cel), ciendhigh(ceh), qval(0), cn(estcn), mappable(mp), sd(1) {}
58
59 bool operator<(const CNV& sv2) const {
60 return ((chr<sv2.chr) || ((chr==sv2.chr) && (start<sv2.start)) || ((chr==sv2.chr) && (start==sv2.start) && (end<sv2.end)) || ((chr==sv2.chr) && (start==sv2.start) && (end==sv2.end) && (cn < sv2.cn)));
61 }
62 };
63
64 // Read count struct
65 struct ReadCount {
66 int32_t leftRC;
67 int32_t rc;
68 int32_t rightRC;
69
70 ReadCount() {}
71 ReadCount(int32_t l, int32_t m, int32_t r) : leftRC(l), rc(m), rightRC(r) {}
72 };
73
74 template<typename TValue>
75 inline TValue
76 medianVector(std::vector<TValue>& v) {
77 std::size_t n = v.size() / 2;
78 std::nth_element(v.begin(), v.begin() + n, v.end());
79 return v[n];
80 }
81
82 inline uint32_t
83 infixStart(EdlibAlignResult const& cigar) {
84 int32_t tIdx = cigar.endLocations[0];
85 for (int32_t i = 0; i < cigar.alignmentLength; i++) {
86 if (cigar.alignment[i] != EDLIB_EDOP_INSERT) tIdx--;
87 }
88 if (tIdx >= 0) return tIdx + 1;
89 else return 0;
90 }
91
92 inline uint32_t
93 infixEnd(EdlibAlignResult const& cigar) {
94 return cigar.endLocations[0];
95 }
96
97 inline void
98 printAlignmentPretty(std::string const& query, std::string const& target, EdlibAlignMode const modeCode, EdlibAlignResult const& align) {
99 int32_t tIdx = -1;
100 int32_t qIdx = -1;
101 if (modeCode == EDLIB_MODE_HW) {
102 tIdx = align.endLocations[0];
103 for (int32_t i = 0; i < align.alignmentLength; i++) {
104 if (align.alignment[i] != EDLIB_EDOP_INSERT) tIdx--;
105 }
106 }
107 std::cerr << std::endl;
108 for (int start = 0; start < align.alignmentLength; start += 50) {
109 std::cerr << "T: ";
110 int32_t startTIdx = -1;
111 for (int32_t j = start; ((j < start + 50) && (j < align.alignmentLength)); ++j) {
112 if (align.alignment[j] == EDLIB_EDOP_INSERT) std::cerr << "-";
113 else std::cerr << target[++tIdx];
114 if (j == start) startTIdx = tIdx;
115 }
116 std::cerr << " (" << std::max(startTIdx, 0) << " - " << tIdx << ")" << std::endl;
117
118 // match / mismatch
119 std::cerr << (" ");
120 for (int32_t j = start; j < start + 50 && j < align.alignmentLength; j++) {
121 if (align.alignment[j] == EDLIB_EDOP_MATCH) std::cerr << "|";
122 else std::cerr << " ";
123 }
124 std::cerr << std::endl;
125
126 // query
127 std::cerr << "Q: ";
128 int32_t startQIdx = qIdx;
129 for (int32_t j = start; j < start + 50 && j < align.alignmentLength; j++) {
130 if (align.alignment[j] == EDLIB_EDOP_DELETE) std::cerr << "-";
131 else std::cerr << query[++qIdx];
132 if (j == start) startQIdx = qIdx;
133 }
134 std::cerr << " ("<< std::max(startQIdx, 0) << " - " << qIdx << ")" << std::endl;
135 std::cerr << std::endl;
136 }
137 }
138
139 inline void
140 printAlignment(std::string const& seqI, std::string const& seqJ, EdlibAlignMode const modeCode, EdlibAlignResult const& cigar) {
141 int32_t tIdx = -1;
142 int32_t qIdx = -1;
143 uint32_t missingEnd = 0;
144 uint32_t missingStart = 0;
145 if ((modeCode == EDLIB_MODE_HW) || (modeCode == EDLIB_MODE_SHW)) {
146 tIdx = cigar.endLocations[0];
147 if (tIdx < (int32_t) seqJ.size()) missingEnd = seqJ.size() - tIdx - 1;
148 for (int32_t i = 0; i < cigar.alignmentLength; i++) {
149 if (cigar.alignment[i] != EDLIB_EDOP_INSERT) tIdx--;
150 }
151 if (tIdx >= 0) missingStart = tIdx + 1;
152 if (missingStart) {
153 for (uint32_t j = 0; j < missingStart; ++j) std::cerr << '-';
154 }
155 }
156 // seqI
157 for (int32_t j = 0; j < cigar.alignmentLength; ++j) {
158 if (cigar.alignment[j] == EDLIB_EDOP_DELETE) std::cerr << '-';
159 else std::cerr << seqI[++qIdx];
160 }
161 // infix alignment, fix end
162 if ((modeCode == EDLIB_MODE_HW) || (modeCode == EDLIB_MODE_SHW)) {
163 if (missingEnd) {
164 for (uint32_t j = 0; j < missingEnd; ++j) std::cerr << '-';
165 }
166 }
167 std::cerr << std::endl;
168 // infix alignment, fix start
169 if ((modeCode == EDLIB_MODE_HW) || (modeCode == EDLIB_MODE_SHW)) {
170 if (missingStart) {
171 for (uint32_t j = 0; j < missingStart; ++j) std::cerr << seqJ[j];
172 }
173 }
174 // seqJ
175 for (int32_t j = 0; j < cigar.alignmentLength; ++j) {
176 if (cigar.alignment[j] == EDLIB_EDOP_INSERT) std::cerr << '-';
177 else std::cerr << seqJ[++tIdx];
178 }
179 // infix alignment, fix end
180 if ((modeCode == EDLIB_MODE_HW) || (modeCode == EDLIB_MODE_SHW)) {
181 if (missingEnd) {
182 for (uint32_t j = 0; j < missingEnd; ++j) std::cerr << seqJ[++tIdx];
183 }
184 }
185 std::cerr << std::endl;
186 }
187
188 template<typename TConfig>
189 inline void
190 checkSampleNames(TConfig& c) {
191 uint32_t ucount = 0;
192 std::set<std::string> snames;
193 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
194 while (snames.find(c.sampleName[file_c]) != snames.end()) {
195 std::cerr << "Warning: Duplicate sample names: " << c.sampleName[file_c] << std::endl;
196 c.sampleName[file_c] += "_" + boost::lexical_cast<std::string>(ucount++);
197 std::cerr << "Warning: Changing sample name to " << c.sampleName[file_c] << std::endl;
198 }
199 snames.insert(c.sampleName[file_c]);
200 }
201 }
202
203 // Decode Orientation
204 inline int32_t
205 _decodeOrientation(std::string const& value) {
206 if (value=="3to3") return 0;
207 else if (value=="5to5") return 1;
208 else if (value=="3to5") return 2;
209 else if (value=="5to3") return 3;
210 else return 4;
211 }
212
213 // Decode Orientation
214 inline int32_t
215 _decodeOrientation(std::string const& value, std::string const& svt) {
216 if (svt == "BND") {
217 if (value=="3to3") return DELLY_SVT_TRANS + 0;
218 else if (value=="5to5") return DELLY_SVT_TRANS + 1;
219 else if (value=="3to5") return DELLY_SVT_TRANS + 2;
220 else if (value=="5to3") return DELLY_SVT_TRANS + 3;
221 else return -1;
222 } else if (svt == "CNV") {
223 return 9;
224 } else {
225 if (value=="3to3") return 0;
226 else if (value=="5to5") return 1;
227 else if (value=="3to5") return 2;
228 else if (value=="5to3") return 3;
229 else return 4;
230 }
231 }
232
233
234 // Deletions
235 inline std::string
236 _addID(int32_t const svt) {
237 if (svt == 0) return "INV";
238 else if (svt == 1) return "INV";
239 else if (svt == 2) return "DEL";
240 else if (svt == 3) return "DUP";
241 else if (svt == 4) return "INS";
242 else if (svt == 9) return "CNV";
243 else return "BND";
244 }
245
246 inline std::string
247 _addAlleles(std::string const& ref, std::string const& alt) {
248 return ref + "," + alt;
249 }
250
251 inline std::string
252 _addAlleles(std::string const& ref, std::string const& chr2, StructuralVariantRecord const& sv, int32_t const svt) {
253 if (_translocation(svt)) {
254 uint8_t ct = _getSpanOrientation(svt);
255 if (ct == 0) {
256 return ref + "," + ref + "]" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "]";
257 } else if (ct == 1) {
258 return ref + "," + "[" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "[" + ref;
259 } else if (ct == 2) {
260 return ref + "," + ref + "[" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "[";
261 } else if (ct == 3) {
262 return ref + "," + "]" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "]" + ref;
263 } else {
264 return ref + ",<" + _addID(svt) + ">";
265 }
266 } else return ref + ",<" + _addID(svt) + ">";
267 }
268
269
270 // Add Orientation
271 inline std::string
272 _addOrientation(int32_t const svt) {
273 uint8_t ct = _getSpanOrientation(svt);
274 if (ct==0) return "3to3";
275 else if (ct==1) return "5to5";
276 else if (ct==2) return "3to5";
277 else if (ct==3) return "5to3";
278 else return "NtoN";
279 }
280
281 inline bool
282 is_gz(boost::filesystem::path const& f) {
283 std::ifstream bfile(f.string().c_str(), std::ios_base::binary | std::ios::ate);
284 bfile.seekg(0, std::ios::beg);
285 char byte1;
286 bfile.read(&byte1, 1);
287 char byte2;
288 bfile.read(&byte2, 1);
289 bfile.close();
290 if ((byte1 == '\x1F') && (byte2 == '\x8B')) return true;
291 else return false;
292 }
293
294 // Output directory/file checks
295 inline bool
296 _outfileValid(boost::filesystem::path const& outfile) {
297 try {
298 boost::filesystem::path outdir;
299 if (outfile.has_parent_path()) outdir = outfile.parent_path();
300 else outdir = boost::filesystem::current_path();
301 if (!boost::filesystem::exists(outdir)) {
302 std::cerr << "Output directory does not exist: " << outdir << std::endl;
303 return false;
304 } else {
305 boost::filesystem::file_status s = boost::filesystem::status(outdir);
306 boost::filesystem::ofstream file(outfile.string());
307 file.close();
308 if (!(boost::filesystem::exists(outfile) && boost::filesystem::is_regular_file(outfile))) {
309 std::cerr << "Fail to open output file " << outfile.string() << std::endl;
310 std::cerr << "Output directory permissions: " << s.permissions() << std::endl;
311 return false;
312 } else {
313 boost::filesystem::remove(outfile.string());
314 }
315 }
316 } catch (boost::filesystem::filesystem_error const& e) {
317 std::cerr << e.what() << std::endl;
318 return false;
319 }
320 return true;
321 }
322
323
324 template<typename TConfig>
325 inline bool
326 _alternateAlignments(TConfig& c, std::vector<boost::filesystem::path>& align, std::vector<boost::filesystem::path>& genome) {
327 std::ifstream altfile(c.altfile.string().c_str());
328 if (altfile.good()) {
329 std::string line;
330 while(std::getline(altfile, line)) {
331 if (!line.empty()) {
332 typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
333 boost::char_separator<char> sep("\t");
334 Tokenizer tokens(line, sep);
335 uint32_t ct = 0;
336 for(Tokenizer::iterator tokIter = tokens.begin(); tokIter!=tokens.end(); ++tokIter, ++ct) {
337 boost::filesystem::path ft(*tokIter);
338 if (!(boost::filesystem::exists(ft) && boost::filesystem::is_regular_file(ft) && boost::filesystem::file_size(ft))) {
339 if (ct==0) std::cerr << "Alternate alignment file is missing: " << ft.string() << std::endl;
340 else if (ct==1) std::cerr << "Genome file is missing: " << ft.string() << std::endl;
341 return false;
342 }
343 if (ct == 0) align.push_back(ft);
344 else if (ct == 1) genome.push_back(ft);
345 }
346 if (ct < 2) {
347 std::cerr << "Alternate alignment config file needs 2 columns '<align.bam> <genome.fa>' for each alternate alignment." << std::endl;
348 return false;
349 }
350 }
351 }
352 altfile.close();
353 return true;
354 }
355 std::cerr << "Config file does not exist: " << c.altfile.string() << std::endl;
356 return false;
357 }
358
359 template<typename TConfig>
360 inline bool
361 _checkAlternateAlignments(TConfig& c) {
362 std::vector<boost::filesystem::path> align;
363 std::vector<boost::filesystem::path> genome;
364 return _alternateAlignments(c, align, genome);
365 }
366
367 template<typename TConfig>
368 inline bool
369 _svTypesToCompute(TConfig& c, std::string const& svtype) {
370 if (svtype == "ALL") return true;
371 else {
372 typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
373 boost::char_separator<char> sep(",");
374 Tokenizer tokens(svtype, sep);
375 for(Tokenizer::iterator tokIter = tokens.begin(); tokIter!=tokens.end(); ++tokIter) {
376 if (*tokIter == "DEL") {
377 c.svtset.insert(2);
378 } else if (*tokIter == "INS") {
379 c.svtset.insert(4);
380 } else if (*tokIter == "DUP") {
381 c.svtset.insert(3);
382 } else if (*tokIter == "INV") {
383 c.svtset.insert(0);
384 c.svtset.insert(1);
385 } else if (*tokIter == "INV_3to3") {
386 c.svtset.insert(0);
387 } else if (*tokIter == "INV_5to5") {
388 c.svtset.insert(1);
389 } else if (*tokIter == "BND") {
390 c.svtset.insert(DELLY_SVT_TRANS + 0);
391 c.svtset.insert(DELLY_SVT_TRANS + 1);
392 c.svtset.insert(DELLY_SVT_TRANS + 2);
393 c.svtset.insert(DELLY_SVT_TRANS + 3);
394 } else if (*tokIter == "BND_3to3") {
395 c.svtset.insert(DELLY_SVT_TRANS + 0);
396 } else if (*tokIter == "BND_5to5") {
397 c.svtset.insert(DELLY_SVT_TRANS + 1);
398 } else if (*tokIter == "BND_3to5") {
399 c.svtset.insert(DELLY_SVT_TRANS + 2);
400 } else if (*tokIter == "BND_5to3") {
401 c.svtset.insert(DELLY_SVT_TRANS + 3);
402 } else {
403 return false;
404 }
405 }
406 }
407 return true;
408 }
409
410 template<typename TConfig>
411 inline void
412 _selectedRefIndices(TConfig& c, bam_hdr_t const* hdr, std::string const& chrNames) {
413 std::map<std::string, int32_t> all;
414 for(int32_t refIndex=0; refIndex < hdr->n_targets; ++refIndex) {
415 all.insert(std::make_pair(std::string(hdr->target_name[refIndex]), refIndex));
416 }
417
418 typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
419 boost::char_separator<char> sep(",");
420 Tokenizer tokens(chrNames, sep);
421 for(Tokenizer::iterator tokIter = tokens.begin(); tokIter!=tokens.end(); ++tokIter) {
422 if (all.find(*tokIter) != all.end()) c.refIdx.insert(all[*tokIter]);
423 }
424 }
425
426 inline uint32_t sequenceLength(bam1_t const* rec) {
427 const uint32_t* cigar = bam_get_cigar(rec);
428 uint32_t slen = 0;
429 for (uint32_t i = 0; i < rec->core.n_cigar; ++i)
430 if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF) || (bam_cigar_op(cigar[i]) == BAM_CINS) || (bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) || (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP)) slen += bam_cigar_oplen(cigar[i]);
431 return slen;
432 }
433
434 inline int32_t
435 readLength(bam1_t const* rec) {
436 //int32_t slen = rec->core.l_qseq; # Incorrect for seq. with hard-clips
437 return sequenceLength(rec);
438 }
439
440 inline uint32_t alignmentLength(bam1_t const* rec) {
441 const uint32_t* cigar = bam_get_cigar(rec);
442 uint32_t alen = 0;
443 for (uint32_t i = 0; i < rec->core.n_cigar; ++i)
444 if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF) || (bam_cigar_op(cigar[i]) == BAM_CDEL) || (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP)) alen += bam_cigar_oplen(cigar[i]);
445 return alen;
446 }
447
448 inline uint32_t halfAlignmentLength(bam1_t const* rec) {
449 return (alignmentLength(rec) / 2);
450 }
451
452 inline std::size_t hash_pair(bam1_t* rec) {
453 std::size_t seed = hash_string(bam_get_qname(rec));
454 boost::hash_combine(seed, rec->core.tid);
455 boost::hash_combine(seed, rec->core.pos);
456 boost::hash_combine(seed, rec->core.mtid);
457 boost::hash_combine(seed, rec->core.mpos);
458 return seed;
459 }
460
461 inline std::size_t hash_pair_mate(bam1_t* rec) {
462 std::size_t seed = hash_string(bam_get_qname(rec));
463 boost::hash_combine(seed, rec->core.mtid);
464 boost::hash_combine(seed, rec->core.mpos);
465 boost::hash_combine(seed, rec->core.tid);
466 boost::hash_combine(seed, rec->core.pos);
467 return seed;
468 }
469
470 inline std::size_t hash_sr(bam1_t* rec) {
471 const char* q = bam_get_qname(rec);
472 std::size_t seed = hash_string(q);
473 std::string_view qn(q);
474 std::size_t prehash = boost::hash_range(qn.begin(), qn.end());
475 boost::hash_combine(seed, prehash);
476 if ((rec->core.flag & BAM_FREAD1) && (seed > 0)) --seed;
477 return seed;
478 }
479
480 inline std::size_t hash_lr(bam1_t* rec) {
481 boost::hash<std::string> string_hash;
482 std::string qname = bam_get_qname(rec);
483 std::size_t seed = hash_string(qname.c_str());
484 boost::hash_combine(seed, string_hash(qname));
485 return seed;
486 }
487
488 inline std::size_t hash_lr(std::string const& qname) {
489 boost::hash<std::string> string_hash;
490 std::size_t seed = hash_string(qname.c_str());
491 boost::hash_combine(seed, string_hash(qname));
492 return seed;
493 }
494
495 inline void
496 reverseComplement(std::string& sequence) {
497 std::string rev = boost::to_upper_copy(std::string(sequence.rbegin(), sequence.rend()));
498 std::size_t i = 0;
499 for(std::string::iterator revIt = rev.begin(); revIt != rev.end(); ++revIt, ++i) {
500 switch (*revIt) {
501 case 'A': sequence[i]='T'; break;
502 case 'C': sequence[i]='G'; break;
503 case 'G': sequence[i]='C'; break;
504 case 'T': sequence[i]='A'; break;
505 case 'N': sequence[i]='N'; break;
506 default: break;
507 }
508 }
509 }
510
511 inline double
512 entropy(std::string const& st) {
513 typedef double TPrecision;
514 std::vector<char> stvec(st.begin(), st.end());
515 std::set<char> alphabet(stvec.begin(), stvec.end());
516 TPrecision ent = 0;
517 for(std::set<char>::const_iterator c = alphabet.begin(); c != alphabet.end(); ++c) {
518 int ctr = 0;
519 for (std::vector<char>::const_iterator s = stvec.begin(); s != stvec.end(); ++s)
520 if (*s == *c) ++ctr;
521 TPrecision freq = (TPrecision) ctr / (TPrecision) stvec.size();
522 ent += (freq) * std::log2(freq);
523 }
524 return -ent;
525 }
526
527
528 inline uint32_t
529 setMinChrLen(bam_hdr_t const* hdr, double const xx) {
530 uint32_t minChrLen = 0;
531 std::vector<uint32_t> chrlen(hdr->n_targets, 0);
532 uint64_t genomelen = 0;
533 for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
534 chrlen[refIndex] = hdr->target_len[refIndex];
535 genomelen += hdr->target_len[refIndex];
536 }
537 std::sort(chrlen.begin(), chrlen.end(), std::greater<uint32_t>());
538 uint64_t cumsum = 0;
539 for(uint32_t i = 0; i < chrlen.size(); ++i) {
540 cumsum += chrlen[i];
541 minChrLen = chrlen[i];
542 if (cumsum > genomelen * xx) break;
543 }
544 return minChrLen;
545 }
546
547 inline bool
548 isBamCram(std::string const& path) {
549 htsFile *hts_fp = hts_open(path.c_str(), "r");
550 if (hts_fp != NULL) {
551 std::string ext = std::string(hts_format_file_extension(hts_get_format(hts_fp)));
552 hts_close(hts_fp);
553 if ((ext == "bam") || (ext == "cram")) return true;
554 }
555 return false;
556 }
557
558 template<typename TConfig>
559 inline bool
560 chrNoData(TConfig const& c, uint32_t const refIndex, hts_idx_t const* idx) {
561 // Check we have mapped reads on this chromosome
562 std::string suffix("cram");
563 std::string str(c.bamFile.string());
564 if ((str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0)) return false;
565 uint64_t mapped = 0;
566 uint64_t unmapped = 0;
567 hts_idx_get_stat(idx, refIndex, &mapped, &unmapped);
568 if (mapped) return false;
569 else return true;
570 }
571
572 inline void
573 getSMTag(std::string const& header, std::string const& fileName, std::string& sampleName) {
574 std::set<std::string> smIdentifiers;
575 std::string delimiters("\n");
576 typedef std::vector<std::string> TStrParts;
577 TStrParts lines;
578 boost::split(lines, header, boost::is_any_of(delimiters));
579 TStrParts::const_iterator itH = lines.begin();
580 TStrParts::const_iterator itHEnd = lines.end();
581 bool rgPresent = false;
582 for(;itH!=itHEnd; ++itH) {
583 if (itH->find("@RG")==0) {
584 std::string delim("\t");
585 TStrParts keyval;
586 boost::split(keyval, *itH, boost::is_any_of(delim));
587 TStrParts::const_iterator itKV = keyval.begin();
588 TStrParts::const_iterator itKVEnd = keyval.end();
589 for(;itKV != itKVEnd; ++itKV) {
590 size_t sp = itKV->find(":");
591 if (sp != std::string::npos) {
592 std::string field = itKV->substr(0, sp);
593 if (field == "SM") {
594 rgPresent = true;
595 std::string rgSM = itKV->substr(sp+1);
596 smIdentifiers.insert(rgSM);
597 }
598 }
599 }
600 }
601 }
602 if (!rgPresent) {
603 sampleName = fileName;
604 } else if (smIdentifiers.size() == 1) {
605 sampleName = *(smIdentifiers.begin());
606 } else if (smIdentifiers.size() > 1) {
607 sampleName = *(smIdentifiers.begin());
608 std::cerr << "Warning: Multiple sample names (@RG:SM) present in the BAM file!" << std::endl;
609 }
610 }
611
612 template<typename TConfig, typename TRegionsGenome>
613 inline int32_t
614 _parseExcludeIntervals(TConfig const& c, bam_hdr_t* hdr, TRegionsGenome& validRegions) {
615 typedef typename TRegionsGenome::value_type TChrIntervals;
616 typedef typename TChrIntervals::interval_type TIVal;
617
618 validRegions.resize(hdr->n_targets);
619 TRegionsGenome exclg;
620 exclg.resize(hdr->n_targets);
621 std::vector<bool> validChr;
622 validChr.resize(hdr->n_targets, true);
623 if (c.hasExcludeFile) {
624 std::ifstream chrFile(c.exclude.string().c_str(), std::ifstream::in);
625 if (chrFile.is_open()) {
626 while (chrFile.good()) {
627 std::string chrFromFile;
628 getline(chrFile, chrFromFile);
629 typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
630 boost::char_separator<char> sep(" \t,;");
631 Tokenizer tokens(chrFromFile, sep);
632 Tokenizer::iterator tokIter = tokens.begin();
633 if (tokIter!=tokens.end()) {
634 std::string chrName = *tokIter++;
635 int32_t tid = bam_name2id(hdr, chrName.c_str());
636 if (tid >= 0) {
637 if (tokIter!=tokens.end()) {
638 int32_t start = 0;
639 try {
640 start = boost::lexical_cast<int32_t>(*tokIter++);
641 } catch (boost::bad_lexical_cast&) {
642 std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
643 std::cerr << "Offending line: " << chrFromFile << std::endl;
644 return false;
645 }
646 if (tokIter!=tokens.end()) {
647 int32_t end = start + 1;
648 try {
649 end = boost::lexical_cast<int32_t>(*tokIter++);
650 } catch (boost::bad_lexical_cast&) {
651 std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
652 std::cerr << "Offending line: " << chrFromFile << std::endl;
653 return false;
654 }
655 if (start < end) {
656 exclg[tid].insert(TIVal::right_open(start, end));
657 } else {
658 std::cerr << "Exclude file needs to be in tab-delimited format (chr, start, end) and start < end." << std::endl;
659 std::cerr << "Offending line: " << chrFromFile << std::endl;
660 return false;
661 }
662 } else {
663 std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
664 std::cerr << "Offending line: " << chrFromFile << std::endl;
665 return false;
666 }
667 } else validChr[tid] = false; // Exclude entire chromosome
668 }
669 }
670 }
671 chrFile.close();
672 }
673 }
674 // Create the valid regions
675 for (int32_t i = 0; i<hdr->n_targets; ++i) {
676 if (!validChr[i]) continue;
677 uint32_t istart = 0;
678 for(typename TChrIntervals::iterator it = exclg[i].begin(); it != exclg[i].end(); ++it) {
679 if (istart + 1 < it->lower()) validRegions[i].insert(TIVal::right_open(istart, it->lower() - 1));
680 istart = it->upper();
681 }
682 if (istart + 1 < hdr->target_len[i]) validRegions[i].insert(TIVal::right_open(istart, hdr->target_len[i]));
683 }
684 exclg.clear();
685 return true;
686 }
687
688 template<typename TIterator, typename TValue>
689 inline void
690 getMedian(TIterator begin, TIterator end, TValue& median)
691 {
692 std::nth_element(begin, begin + (end - begin) / 2, end);
693 median = *(begin + (end - begin) / 2);
694 }
695
696 template<typename TVector, typename TPercentile, typename TValue>
697 inline void
698 getPercentile(TVector& vec, TPercentile p, TValue& percentile)
699 {
700 std::nth_element(vec.begin(), vec.begin() + int((vec.size() * p)), vec.end());
701 percentile = *(vec.begin() + int(vec.size() * p));
702 }
703
704
705 template<typename TConfig>
706 inline int32_t
707 getVariability(TConfig const&, std::vector<LibraryInfo> const& lib) {
708 int32_t overallVariability = 0;
709 for(uint32_t libIdx = 0; libIdx < lib.size(); ++libIdx) {
710 if (lib[libIdx].maxNormalISize > overallVariability) overallVariability = lib[libIdx].maxNormalISize;
711 if (lib[libIdx].rs > overallVariability) overallVariability = lib[libIdx].rs;
712 }
713 return overallVariability;
714 }
715
716
717 template<typename TConfig, typename TValidRegion, typename TSampleLibrary>
718 inline void
719 getLibraryParams(TConfig const& c, TValidRegion const& validRegions, TSampleLibrary& sampleLib) {
720 typedef typename TValidRegion::value_type TChrIntervals;
721
722 // Open file handles
723 typedef std::vector<samFile*> TSamFile;
724 typedef std::vector<hts_idx_t*> TIndex;
725 typedef std::vector<bam_hdr_t*> TSamHeader;
726 TSamFile samfile(c.files.size());
727 TIndex idx(c.files.size());
728 TSamHeader hdr(c.files.size());
729 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
730 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
731 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
732 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
733 hdr[file_c] = sam_hdr_read(samfile[file_c]);
734 }
735
736 // Iterate all samples
737 for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
738 uint32_t maxAlignmentsScreened=10000000;
739 uint32_t maxNumAlignments=1000000;
740 uint32_t minNumAlignments=1000;
741 uint32_t alignmentCount=0;
742 uint32_t processedNumPairs = 0;
743 uint32_t processedNumReads = 0;
744 uint32_t rplus = 0;
745 uint32_t nonrplus = 0;
746 typedef std::vector<uint32_t> TSizeVector;
747 TSizeVector vecISize;
748 TSizeVector readSize;
749 readSize.reserve(minNumAlignments);
750 vecISize.reserve(minNumAlignments);
751
752 // Collect insert sizes
753 bool libCharacterized = false;
754 for(uint32_t refIndex=0; refIndex < (uint32_t) hdr[file_c]->n_targets; ++refIndex) {
755 if (validRegions[refIndex].empty()) continue;
756 for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); ((vRIt != validRegions[refIndex].end()) && (!libCharacterized)); ++vRIt) {
757 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, vRIt->lower(), vRIt->upper());
758 bam1_t* rec = bam_init1();
759 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
760 if (!(rec->core.flag & BAM_FREAD2) && (rec->core.l_qseq < 65000)) {
761 if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
762 if ((alignmentCount > maxAlignmentsScreened) || ((processedNumReads >= maxNumAlignments) && (processedNumPairs == 0)) || (processedNumPairs >= maxNumAlignments)) {
763 // Paired-end library with enough pairs
764 libCharacterized = true;
765 break;
766 }
767 ++alignmentCount;
768
769 // Single-end
770 if (processedNumReads < maxNumAlignments) {
771 readSize.push_back(rec->core.l_qseq);
772 ++processedNumReads;
773 }
774
775 // Paired-end
776 if ((rec->core.flag & BAM_FPAIRED) && !(rec->core.flag & BAM_FMUNMAP) && (rec->core.tid==rec->core.mtid)) {
777 if (processedNumPairs < maxNumAlignments) {
778 vecISize.push_back(abs(rec->core.isize));
779 if (getSVType(rec) == 2) ++rplus;
780 else ++nonrplus;
781 ++processedNumPairs;
782 }
783 }
784 }
785 }
786 bam_destroy1(rec);
787 hts_itr_destroy(iter);
788 if (libCharacterized) break;
789 }
790 if (libCharacterized) break;
791 }
792
793 // Get library parameters
794 if (processedNumReads >= minNumAlignments) {
795 std::sort(readSize.begin(), readSize.end());
796 sampleLib[file_c].rs = readSize[readSize.size() / 2];
797 }
798 if (processedNumPairs >= minNumAlignments) {
799 std::sort(vecISize.begin(), vecISize.end());
800 int32_t median = vecISize[vecISize.size() / 2];
801 std::vector<uint32_t> absDev;
802 for(uint32_t i = 0; i < vecISize.size(); ++i) absDev.push_back(std::abs((int32_t) vecISize[i] - median));
803 std::sort(absDev.begin(), absDev.end());
804 int32_t mad = absDev[absDev.size() / 2];
805
806 // Get default library orientation
807 if ((median >= 50) && (median<=100000)) {
808 if (rplus < nonrplus) {
809 std::cerr << "Warning: Sample has a non-default paired-end layout! File: " << c.files[file_c].string() << std::endl;
810 std::cerr << "The expected paired-end orientation is ---Read1---> <---Read2--- which is the default illumina paired-end layout." << std::endl;
811
812 } else {
813 sampleLib[file_c].median = median;
814 sampleLib[file_c].mad = mad;
815 sampleLib[file_c].maxNormalISize = median + (c.madNormalCutoff * mad);
816 sampleLib[file_c].minNormalISize = median - (c.madNormalCutoff * mad);
817 if (sampleLib[file_c].minNormalISize < 0) sampleLib[file_c].minNormalISize=0;
818 sampleLib[file_c].maxISizeCutoff = median + (c.madCutoff * mad);
819 sampleLib[file_c].minISizeCutoff = median - (c.madCutoff * mad);
820
821 // Deletion insert-size sanity checks
822 sampleLib[file_c].maxISizeCutoff = std::max(sampleLib[file_c].maxISizeCutoff, 2*sampleLib[file_c].rs);
823 sampleLib[file_c].maxISizeCutoff = std::max(sampleLib[file_c].maxISizeCutoff, 500);
824
825 if (sampleLib[file_c].minISizeCutoff < 0) sampleLib[file_c].minISizeCutoff=0;
826 }
827 }
828 }
829 }
830
831 // Clean-up
832 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
833 bam_hdr_destroy(hdr[file_c]);
834 hts_idx_destroy(idx[file_c]);
835 sam_close(samfile[file_c]);
836 }
837 }
838
839
840 }
841
842 #endif