Debian Codegraph @

src/coral.h

raw symbols SCIP
1 #ifndef CORAL_H
2 #define CORAL_H
3
4 #include <limits>
5
6 #include <boost/icl/split_interval_map.hpp>
7 #include <boost/dynamic_bitset.hpp>
8 #include <boost/unordered_map.hpp>
9 #include <boost/date_time/posix_time/posix_time.hpp>
10 #include <boost/date_time/gregorian/gregorian.hpp>
11 #include <boost/math/special_functions/round.hpp>
12
13 #include <htslib/sam.h>
14 #include <htslib/faidx.h>
15
16 #include "bed.h"
17 #include "scan.h"
18 #include "gcbias.h"
19 #include "cnv.h"
20 #include "version.h"
21
22 namespace torali
23 {
24
25 struct CountDNAConfig {
26 bool adaptive;
27 bool hasStatsFile;
28 bool hasBedFile;
29 bool hasScanFile;
30 bool noScanWindowSelection;
31 bool segmentation;
32 bool hasGenoFile;
33 bool hasVcfFile;
34 uint32_t nchr;
35 uint32_t meanisize;
36 uint32_t window_size;
37 uint32_t window_offset;
38 uint32_t scanWindow;
39 uint32_t minChrLen;
40 uint32_t minCnvSize;
41 uint16_t minQual;
42 uint16_t mad;
43 float ploidy;
44 float ctrlPloidy;
45 float expectedCN;
46 float purity;
47 float exclgc;
48 float uniqueToTotalCovRatio;
49 float fracWindow;
50 float fragmentUnique;
51 float controlMaf;
52 float stringency;
53 float cn_offset;
54 std::string sampleName;
55 boost::filesystem::path vcffile;
56 boost::filesystem::path genofile;
57 boost::filesystem::path outfile;
58 boost::filesystem::path covfile;
59 boost::filesystem::path genome;
60 boost::filesystem::path statsFile;
61 boost::filesystem::path mapFile;
62 boost::filesystem::path bamFile;
63 boost::filesystem::path bedFile;
64 boost::filesystem::path scanFile;
65 std::set<int32_t> refIdx;
66 };
67
68 struct CountDNAConfigLib {
69 uint16_t madCutoff;
70 uint16_t madNormalCutoff;
71 boost::filesystem::path genome;
72 std::vector<boost::filesystem::path> files;
73 };
74
75 template<typename TConfig>
76 inline int32_t
77 bamCount(TConfig const& c, LibraryInfo const& li, std::vector<GcBias> const& gcbias, std::pair<uint32_t, uint32_t> const& gcbound) {
78 // Load bam file
79 samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
80 hts_set_fai_filename(samfile, c.genome.string().c_str());
81 hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
82 bam_hdr_t* hdr = sam_hdr_read(samfile);
83
84 // BED regions
85 typedef std::set<std::pair<uint32_t, uint32_t> > TChrIntervals;
86 typedef std::vector<TChrIntervals> TRegionsGenome;
87 TRegionsGenome bedRegions;
88 if (c.hasBedFile) {
89 if (!_parsePotOverlappingIntervals(c.bedFile.string(), c.hasBedFile, hdr, bedRegions)) {
90 std::cerr << "Couldn't parse BED intervals. Do the chromosome names match?" << std::endl;
91 return 1;
92 }
93 }
94
95 // Parse BAM file
96 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
97 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Count fragments" << std::endl;
98
99 // Open output files
100 boost::iostreams::filtering_ostream dataOut;
101 if (!c.covfile.empty()) {
102 dataOut.push(boost::iostreams::gzip_compressor());
103 dataOut.push(boost::iostreams::file_sink(c.covfile.c_str(), std::ios_base::out | std::ios_base::binary));
104 dataOut << "chr\tstart\tend\t" << c.sampleName << "_mappable\t" << c.sampleName << "_logR\t" << c.sampleName << "_CN" << std::endl;
105 }
106
107 // CNVs
108 std::vector<CNV> cnvs;
109 if (c.hasGenoFile) parseVcfCNV(c, hdr, cnvs);
110
111 // SVs for breakpoint refinement
112 typedef std::vector<SVBreakpoint> TChrBreakpoints;
113 typedef std::vector<TChrBreakpoints> TGenomicBreakpoints;
114 TGenomicBreakpoints svbp(c.nchr, TChrBreakpoints());
115 if (c.hasVcfFile) {
116 std::vector<StructuralVariantRecord> svs;
117 vcfParse(c, hdr, svs);
118 for(uint32_t i = 0; i < svs.size(); ++i) {
119 svbp[svs[i].chr].push_back(SVBreakpoint(svs[i].svStart, svs[i].ciposlow, svs[i].ciposhigh, svs[i].mapq));
120 svbp[svs[i].chr2].push_back(SVBreakpoint(svs[i].svEnd, svs[i].ciendlow, svs[i].ciendhigh, svs[i].mapq));
121 }
122 for (uint32_t i = 0; i < svbp.size(); ++i) sort(svbp[i].begin(), svbp[i].end());
123 }
124
125 // Iterate chromosomes
126 faidx_t* faiMap = fai_load(c.mapFile.string().c_str());
127 faidx_t* faiRef = fai_load(c.genome.string().c_str());
128 for(int32_t refIndex=0; refIndex < (int32_t) hdr->n_targets; ++refIndex) {
129 if ((!c.hasGenoFile) && (chrNoData(c, refIndex, idx))) continue;
130
131 // Haploid chromosome?
132 float chrCtrlPloidy = c.ctrlPloidy;
133 float chrPloidy = c.ploidy;
134 if (c.refIdx.find(refIndex) != c.refIdx.end()) {
135 chrCtrlPloidy = c.ctrlPloidy - 1;
136 chrPloidy = c.ploidy - 1;
137 }
138
139 // Check presence in mappability map
140 std::string tname(hdr->target_name[refIndex]);
141 int32_t seqlen = faidx_seq_len(faiMap, tname.c_str());
142 if (seqlen == - 1) continue;
143 else seqlen = -1;
144 char* seq = faidx_fetch_seq(faiMap, tname.c_str(), 0, faidx_seq_len(faiMap, tname.c_str()), &seqlen);
145
146 // Check presence in reference
147 seqlen = faidx_seq_len(faiRef, tname.c_str());
148 if (seqlen == - 1) continue;
149 else seqlen = -1;
150 char* ref = faidx_fetch_seq(faiRef, tname.c_str(), 0, faidx_seq_len(faiRef, tname.c_str()), &seqlen);
151
152 // Get GC and Mappability
153 std::vector<uint16_t> uniqContent(hdr->target_len[refIndex], 0);
154 std::vector<uint16_t> gcContent(hdr->target_len[refIndex], 0);
155 {
156 // Mappability map
157 typedef boost::dynamic_bitset<> TBitSet;
158 TBitSet uniq(hdr->target_len[refIndex], false);
159 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
160 if (seq[i] == 'C') uniq[i] = 1;
161 }
162
163 // GC map
164 typedef boost::dynamic_bitset<> TBitSet;
165 TBitSet gcref(hdr->target_len[refIndex], false);
166 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
167 if ((ref[i] == 'c') || (ref[i] == 'C') || (ref[i] == 'g') || (ref[i] == 'G')) gcref[i] = 1;
168 }
169
170 // Sum across fragment
171 int32_t halfwin = (int32_t) (c.meanisize / 2);
172 int32_t usum = 0;
173 int32_t gcsum = 0;
174 for(int32_t pos = halfwin; pos < (int32_t) hdr->target_len[refIndex] - halfwin; ++pos) {
175 if (pos == halfwin) {
176 for(int32_t i = pos - halfwin; i<=pos+halfwin; ++i) {
177 usum += uniq[i];
178 gcsum += gcref[i];
179 }
180 } else {
181 usum -= uniq[pos - halfwin - 1];
182 gcsum -= gcref[pos - halfwin - 1];
183 usum += uniq[pos + halfwin];
184 gcsum += gcref[pos + halfwin];
185 }
186 gcContent[pos] = gcsum;
187 uniqContent[pos] = usum;
188 }
189 }
190
191 // Coverage track
192 typedef uint16_t TCount;
193 uint32_t maxCoverage = std::numeric_limits<TCount>::max();
194 typedef std::vector<TCount> TCoverage;
195 TCoverage cov(hdr->target_len[refIndex], 0);
196
197 {
198 // Mate map
199 typedef boost::unordered_map<std::size_t, bool> TMateMap;
200 TMateMap mateMap;
201
202 // Count reads
203 hts_itr_t* iter = sam_itr_queryi(idx, refIndex, 0, hdr->target_len[refIndex]);
204 bam1_t* rec = bam_init1();
205 int32_t lastAlignedPos = 0;
206 std::set<std::size_t> lastAlignedPosReads;
207 while (sam_itr_next(samfile, iter, rec) >= 0) {
208 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP | BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) continue;
209 if (rec->core.qual < c.minQual) continue;
210 if ((rec->core.flag & BAM_FPAIRED) && ((rec->core.flag & BAM_FMUNMAP) || (rec->core.tid != rec->core.mtid))) continue;
211
212 int32_t midPoint = rec->core.pos + halfAlignmentLength(rec);
213 if (rec->core.flag & BAM_FPAIRED) {
214 // Clean-up the read store for identical alignment positions
215 if (rec->core.pos > lastAlignedPos) {
216 lastAlignedPosReads.clear();
217 lastAlignedPos = rec->core.pos;
218 }
219
220 if ((rec->core.pos < rec->core.mpos) || ((rec->core.pos == rec->core.mpos) && (lastAlignedPosReads.find(hash_string(bam_get_qname(rec))) == lastAlignedPosReads.end()))) {
221 // First read
222 lastAlignedPosReads.insert(hash_string(bam_get_qname(rec)));
223 std::size_t hv = hash_pair(rec);
224 mateMap[hv] = true;
225 continue;
226 } else {
227 // Second read
228 std::size_t hv = hash_pair_mate(rec);
229 if ((mateMap.find(hv) == mateMap.end()) || (!mateMap[hv])) continue; // Mate discarded
230 mateMap[hv] = false;
231 }
232
233 // update midpoint
234 int32_t isize = (rec->core.pos + alignmentLength(rec)) - rec->core.mpos;
235 if ((li.minNormalISize < isize) && (isize < li.maxNormalISize)) midPoint = rec->core.mpos + (int32_t) (isize/2);
236 }
237
238 // Count fragment
239 if ((midPoint >= 0) && (midPoint < (int32_t) hdr->target_len[refIndex]) && (cov[midPoint] < maxCoverage - 1)) ++cov[midPoint];
240 }
241 // Clean-up
242 if (seq != NULL) free(seq);
243 if (ref != NULL) free(ref);
244 bam_destroy1(rec);
245 hts_itr_destroy(iter);
246 }
247
248 // CNV discovery
249 if (!c.hasGenoFile) {
250 // Call CNVs
251 std::vector<CNV> chrcnv;
252 callCNVs(c, gcbound, gcContent, uniqContent, gcbias, cov, hdr, refIndex, chrcnv);
253
254 // Merge adjacent CNVs lacking read-depth shift
255 mergeCNVs(c, chrcnv, cnvs);
256
257 // Refine breakpoints
258 if (c.hasVcfFile) breakpointRefinement(c, gcbound, gcContent, uniqContent, gcbias, cov, hdr, refIndex, svbp, cnvs);
259 }
260
261 // CNV genotyping
262 genotypeCNVs(c, gcbound, gcContent, uniqContent, gcbias, cov, hdr, refIndex, cnvs);
263
264 // BED File (target intervals)
265 if (c.hasBedFile) {
266 if (c.adaptive) {
267 // Merge overlapping BED entries
268 TChrIntervals citv;
269 _mergeOverlappingBedEntries(bedRegions[refIndex], citv);
270
271 // Tile merged intervals
272 double covsum = 0;
273 double expcov = 0;
274 //double obsexp = 0;
275 uint32_t winlen = 0;
276 uint32_t start = 0;
277 bool endOfWindow = true;
278 typename TChrIntervals::iterator it = citv.begin();
279 if (it != citv.end()) start = it->first;
280 while(endOfWindow) {
281 endOfWindow = false;
282 for(it = citv.begin(); ((it != citv.end()) && (!endOfWindow)); ++it) {
283 if ((it->first < it->second) && (it->second <= hdr->target_len[refIndex])) {
284 if (start >= it->second) {
285 if (start == it->second) {
286 // Special case
287 typename TChrIntervals::iterator itNext = it;
288 ++itNext;
289 if (itNext != citv.end()) start = itNext->first;
290 }
291 continue;
292 }
293 for(uint32_t pos = it->first; ((pos < it->second) && (!endOfWindow)); ++pos) {
294 if (pos < start) continue;
295 if ((gcContent[pos] > gcbound.first) && (gcContent[pos] < gcbound.second) && (uniqContent[pos] >= c.fragmentUnique * c.meanisize)) {
296 covsum += cov[pos];
297 //obsexp += gcbias[gcContent[pos]].obsexp;
298 expcov += gcbias[gcContent[pos]].coverage;
299 ++winlen;
300 if (winlen == c.window_size) {
301 //obsexp /= (double) winlen;
302 // Normalized counts: double count = ((double) covsum / obsexp ) * (double) c.window_size / (double) winlen;
303 double cn = chrPloidy;
304 double logR = 0;
305 if (expcov > 0) {
306 cn = (c.expectedCN * covsum / expcov - chrCtrlPloidy * (1 - c.purity)) / c.purity;
307 logR = std::log2(covsum / expcov);
308 }
309 if (!c.covfile.empty()) dataOut << std::string(hdr->target_name[refIndex]) << "\t" << start << "\t" << (pos + 1) << "\t" << winlen << "\t" << logR << "\t" << cn << std::endl;
310 // reset
311 covsum = 0;
312 expcov = 0;
313 //obsexp = 0;
314 winlen = 0;
315 if (c.window_offset == c.window_size) {
316 // Move on
317 start = pos + 1;
318 endOfWindow = true;
319 } else {
320 // Rewind
321 for(typename TChrIntervals::iterator sit = citv.begin(); ((sit != citv.end()) && (!endOfWindow)); ++sit) {
322 if ((sit->first < sit->second) && (sit->second <= hdr->target_len[refIndex])) {
323 if (start >= sit->second) continue;
324 for(uint32_t k = sit->first; ((k < sit->second) && (!endOfWindow)); ++k) {
325 if (k < start) continue;
326 if ((gcContent[k] > gcbound.first) && (gcContent[k] < gcbound.second) && (uniqContent[k] >= c.fragmentUnique * c.meanisize)) {
327 ++winlen;
328 if (winlen == c.window_offset) {
329 start = k + 1;
330 winlen = 0;
331 endOfWindow = true;
332 }
333 }
334 }
335 }
336 }
337 }
338 }
339 }
340 }
341 }
342 }
343 }
344 } else {
345 // Fixed Window Length
346 for(typename TChrIntervals::iterator it = bedRegions[refIndex].begin(); it != bedRegions[refIndex].end(); ++it) {
347 if ((it->first < it->second) && (it->second <= hdr->target_len[refIndex])) {
348 double covsum = 0;
349 double expcov = 0;
350 //double obsexp = 0;
351 uint32_t winlen = 0;
352 for(uint32_t pos = it->first; pos < it->second; ++pos) {
353 if ((gcContent[pos] > gcbound.first) && (gcContent[pos] < gcbound.second) && (uniqContent[pos] >= c.fragmentUnique * c.meanisize)) {
354 covsum += cov[pos];
355 //obsexp += gcbias[gcContent[pos]].obsexp;
356 expcov += gcbias[gcContent[pos]].coverage;
357 ++winlen;
358 }
359 }
360 if (winlen >= c.fracWindow * (it->second - it->first)) {
361 //obsexp /= (double) winlen;
362 // Normalized counts: double count = ((double) covsum / obsexp ) * (double) (it->second - it->first) / (double) winlen;
363 double cn = chrPloidy;
364 double logR = 0;
365 if (expcov > 0) {
366 cn = (c.expectedCN * covsum / expcov - chrCtrlPloidy * (1 - c.purity)) / c.purity;
367 logR = std::log2(covsum / expcov);
368 }
369 if (!c.covfile.empty()) dataOut << std::string(hdr->target_name[refIndex]) << "\t" << it->first << "\t" << it->second << "\t" << winlen << "\t" << logR << "\t" << cn << std::endl;
370 } else {
371 if (!c.covfile.empty()) dataOut << std::string(hdr->target_name[refIndex]) << "\t" << it->first << "\t" << it->second << "\tNA\tNA\tNA" << std::endl;
372 }
373 }
374 }
375 }
376 } else {
377 // Genome-wide
378 if (c.adaptive) {
379 double covsum = 0;
380 double expcov = 0;
381 //double obsexp = 0;
382 uint32_t winlen = 0;
383 uint32_t start = 0;
384 uint32_t pos = 0;
385 while(pos < hdr->target_len[refIndex]) {
386 if ((gcContent[pos] > gcbound.first) && (gcContent[pos] < gcbound.second) && (uniqContent[pos] >= c.fragmentUnique * c.meanisize)) {
387 covsum += cov[pos];
388 //obsexp += gcbias[gcContent[pos]].obsexp;
389 expcov += gcbias[gcContent[pos]].coverage;
390 ++winlen;
391 if (winlen == c.window_size) {
392 //obsexp /= (double) winlen;
393 // Normalized counts: double count = ((double) covsum / obsexp ) * (double) c.window_size / (double) winlen;
394 double cn = chrPloidy;
395 double logR = 0;
396 if (expcov > 0) {
397 cn = (c.expectedCN * covsum / expcov - chrCtrlPloidy * (1 - c.purity)) / c.purity;
398 logR = std::log2(covsum / expcov);
399 }
400 if (!c.covfile.empty()) dataOut << std::string(hdr->target_name[refIndex]) << "\t" << start << "\t" << (pos + 1) << "\t" << winlen << "\t" << logR << "\t" << cn << std::endl;
401 // reset
402 covsum = 0;
403 expcov = 0;
404 //obsexp = 0;
405 winlen = 0;
406 if (c.window_offset == c.window_size) {
407 // Move on
408 start = pos + 1;
409 } else {
410 // Rewind
411 for(uint32_t k = start; k < hdr->target_len[refIndex]; ++k) {
412 if ((gcContent[k] > gcbound.first) && (gcContent[k] < gcbound.second) && (uniqContent[k] >= c.fragmentUnique * c.meanisize)) {
413 ++winlen;
414 if (winlen == c.window_offset) {
415 start = k + 1;
416 pos = k;
417 winlen = 0;
418 break;
419 }
420 }
421 }
422 }
423 }
424 }
425 ++pos;
426 }
427 } else {
428 // Fixed windows (genomic tiling)
429 for(uint32_t start = 0; start < hdr->target_len[refIndex]; start = start + c.window_offset) {
430 if (start + c.window_size < hdr->target_len[refIndex]) {
431 double covsum = 0;
432 double expcov = 0;
433 //double obsexp = 0;
434 uint32_t winlen = 0;
435 for(uint32_t pos = start; pos < start + c.window_size; ++pos) {
436 if ((gcContent[pos] > gcbound.first) && (gcContent[pos] < gcbound.second) && (uniqContent[pos] >= c.fragmentUnique * c.meanisize)) {
437 covsum += cov[pos];
438 //obsexp += gcbias[gcContent[pos]].obsexp;
439 expcov += gcbias[gcContent[pos]].coverage;
440 ++winlen;
441 }
442 }
443 if (winlen >= c.fracWindow * c.window_size) {
444 //obsexp /= (double) winlen;
445 // Normalized counts: double count = ((double) covsum / obsexp ) * (double) c.window_size / (double) winlen;
446 double cn = chrPloidy;
447 double logR = 0;
448 if (expcov > 0) {
449 cn = (c.expectedCN * covsum / expcov - chrCtrlPloidy * (1 - c.purity)) / c.purity;
450 logR = std::log2(covsum / expcov);
451 }
452 if (!c.covfile.empty()) dataOut << std::string(hdr->target_name[refIndex]) << "\t" << start << "\t" << (start + c.window_size) << "\t" << winlen << "\t" << logR << "\t" << cn << std::endl;
453 }
454 }
455 }
456 }
457 }
458 }
459
460 // Sort CNVs
461 sort(cnvs.begin(), cnvs.end());
462
463 // Genotype CNVs
464 cnvVCF(c, cnvs);
465
466 // clean-up
467 fai_destroy(faiRef);
468 fai_destroy(faiMap);
469 bam_hdr_destroy(hdr);
470 hts_idx_destroy(idx);
471 sam_close(samfile);
472 if (!c.covfile.empty()) {
473 dataOut.pop();
474 dataOut.pop();
475 }
476
477 return 0;
478 }
479
480
481 int coral(int argc, char **argv) {
482 CountDNAConfig c;
483 std::string haploidChr;
484
485 // Parameter
486 boost::program_options::options_description generic("Generic options");
487 generic.add_options()
488 ("help,?", "show help message")
489 ("genome,g", boost::program_options::value<boost::filesystem::path>(&c.genome), "genome file")
490 ("quality,q", boost::program_options::value<uint16_t>(&c.minQual)->default_value(10), "min. mapping quality")
491 ("mappability,m", boost::program_options::value<boost::filesystem::path>(&c.mapFile), "input mappability map")
492 ("outfile,o", boost::program_options::value<boost::filesystem::path>(&c.outfile), "BCF output file")
493 ("covfile,c", boost::program_options::value<boost::filesystem::path>(&c.covfile), "gzipped coverage file")
494 ;
495
496 boost::program_options::options_description cnv("CNV calling");
497 cnv.add_options()
498 ("sdrd,x", boost::program_options::value<float>(&c.stringency)->default_value(2), "min. SD read-depth shift")
499 ("cn-offset,t", boost::program_options::value<float>(&c.cn_offset)->default_value(0.1), "min. CN offset")
500 ("cnv-size,z", boost::program_options::value<uint32_t>(&c.minCnvSize)->default_value(1000), "min. CNV size")
501 ("svfile,l", boost::program_options::value<boost::filesystem::path>(&c.vcffile), "delly SV file for breakpoint refinement")
502 ("vcffile,v", boost::program_options::value<boost::filesystem::path>(&c.genofile), "input VCF/BCF file for re-genotyping")
503 ("segmentation,u", "copy-number segmentation")
504 ;
505
506 boost::program_options::options_description cancer("Ploidy/purity correction");
507 cancer.add_options()
508 ("ploidy,y", boost::program_options::value<float>(&c.ploidy)->default_value(2), "sample ploidy")
509 ("purity,p", boost::program_options::value<float>(&c.purity)->default_value(1), "sample purity [0.1, 1]")
510 ("ctrl-ploidy", boost::program_options::value<float>(&c.ctrlPloidy)->default_value(2), "control ploidy")
511 ("haploid-chr", boost::program_options::value<std::string>(&haploidChr), "haploid chromosomes, e.g. chrX,chrY")
512 ;
513
514 boost::program_options::options_description window("Read-depth windows");
515 window.add_options()
516 ("window-size,i", boost::program_options::value<uint32_t>(&c.window_size)->default_value(10000), "window size")
517 ("window-offset,j", boost::program_options::value<uint32_t>(&c.window_offset)->default_value(10000), "window offset")
518 ("bed-intervals,b", boost::program_options::value<boost::filesystem::path>(&c.bedFile), "input BED file")
519 ("fraction-window,k", boost::program_options::value<float>(&c.fracWindow)->default_value(0.25), "min. callable window fraction [0,1]")
520 ("adaptive-windowing,a", "use mappable bases for adaptive window size")
521 ;
522
523 boost::program_options::options_description gcopt("GC fragment normalization");
524 gcopt.add_options()
525 ("scan-window,w", boost::program_options::value<uint32_t>(&c.scanWindow)->default_value(10000), "scanning window size")
526 ("fraction-unique,f", boost::program_options::value<float>(&c.uniqueToTotalCovRatio)->default_value(0.8), "uniqueness filter for scan windows [0,1]")
527 ("scan-regions,r", boost::program_options::value<boost::filesystem::path>(&c.scanFile), "scanning regions in BED format")
528 ("mad-cutoff,d", boost::program_options::value<uint16_t>(&c.mad)->default_value(3), "median + 3 * mad count cutoff")
529 ("no-window-selection,n", "no scan window selection")
530 ("percentile", boost::program_options::value<float>(&c.exclgc)->default_value(0.0005), "excl. extreme GC fraction")
531 ;
532
533 boost::program_options::options_description hidden("Hidden options");
534 hidden.add_options()
535 ("input-file", boost::program_options::value<boost::filesystem::path>(&c.bamFile), "input bam file")
536 ("fragment", boost::program_options::value<float>(&c.fragmentUnique)->default_value(0.97), "min. fragment uniqueness [0,1]")
537 ("statsfile,s", boost::program_options::value<boost::filesystem::path>(&c.statsFile), "gzipped stats output file (optional)")
538 ;
539
540 boost::program_options::positional_options_description pos_args;
541 pos_args.add("input-file", -1);
542
543 // Set the visibility
544 boost::program_options::options_description cmdline_options;
545 cmdline_options.add(generic).add(cnv).add(cancer).add(window).add(gcopt).add(hidden);
546 boost::program_options::options_description visible_options;
547 visible_options.add(generic).add(cnv).add(cancer).add(window).add(gcopt);
548
549 // Parse command-line
550 boost::program_options::variables_map vm;
551 boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
552 boost::program_options::notify(vm);
553
554 // Check command line arguments
555 if ((vm.count("help")) || (!vm.count("input-file")) || (!vm.count("genome")) || (!vm.count("mappability"))) {
556 std::cerr << std::endl;
557 std::cerr << "Usage: delly " << argv[0] << " [OPTIONS] -g <genome.fa> -m <genome.map> <aligned.bam>" << std::endl;
558 std::cerr << visible_options << "\n";
559 return 1;
560 }
561
562 // Show cmd
563 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
564 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] ";
565 std::cerr << "delly ";
566 for(int i=0; i<argc; ++i) { std::cerr << argv[i] << ' '; }
567 std::cerr << std::endl;
568
569 // Stats file
570 if (vm.count("statsfile")) c.hasStatsFile = true;
571 else c.hasStatsFile = false;
572
573 // BED intervals
574 if (vm.count("bed-intervals")) c.hasBedFile = true;
575 else c.hasBedFile = false;
576
577 // Scan regions
578 if (vm.count("scan-regions")) c.hasScanFile = true;
579 else c.hasScanFile = false;
580
581 // Scan window selection
582 if (vm.count("no-window-selection")) c.noScanWindowSelection = true;
583 else c.noScanWindowSelection = false;
584
585 // Adaptive windowing
586 if (vm.count("adaptive-windowing")) c.adaptive = true;
587 else c.adaptive = false;
588
589 // Purity
590 if (c.purity > 1) c.purity = 1;
591 if (c.purity < 0.1) c.purity = 0.1;
592
593 // Expected ploidy
594 c.expectedCN = c.purity * c.ploidy + (1.0 - c.purity) * c.ctrlPloidy;
595
596 // Segmentation
597 if (vm.count("segmentation")) c.segmentation = true;
598 else c.segmentation = false;
599
600 // Check window size
601 if (c.window_offset > c.window_size) c.window_offset = c.window_size;
602 if (c.window_size == 0) c.window_size = 1;
603 if (c.window_offset == 0) c.window_offset = 1;
604
605 // Check input VCF file (CNV genotyping)
606 if (vm.count("vcffile")) {
607 if (!(boost::filesystem::exists(c.genofile) && boost::filesystem::is_regular_file(c.genofile) && boost::filesystem::file_size(c.genofile))) {
608 std::cerr << "Input VCF/BCF file is missing: " << c.genofile.string() << std::endl;
609 return 1;
610 }
611 htsFile* ifile = bcf_open(c.genofile.string().c_str(), "r");
612 if (ifile == NULL) {
613 std::cerr << "Fail to open file " << c.genofile.string() << std::endl;
614 return 1;
615 }
616 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
617 if (hdr == NULL) {
618 std::cerr << "Fail to open index file " << c.genofile.string() << std::endl;
619 return 1;
620 }
621 bcf_hdr_destroy(hdr);
622 bcf_close(ifile);
623 c.hasGenoFile = true;
624 } else c.hasGenoFile = false;
625
626 // Check input VCF file (delly SV file)
627 if (vm.count("svfile")) {
628 if (!(boost::filesystem::exists(c.vcffile) && boost::filesystem::is_regular_file(c.vcffile) && boost::filesystem::file_size(c.vcffile))) {
629 std::cerr << "Input VCF/BCF file is missing: " << c.vcffile.string() << std::endl;
630 return 1;
631 }
632 htsFile* ifile = bcf_open(c.vcffile.string().c_str(), "r");
633 if (ifile == NULL) {
634 std::cerr << "Fail to open file " << c.vcffile.string() << std::endl;
635 return 1;
636 }
637 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
638 if (hdr == NULL) {
639 std::cerr << "Fail to open index file " << c.vcffile.string() << std::endl;
640 return 1;
641 }
642 bcf_hdr_destroy(hdr);
643 bcf_close(ifile);
644 c.hasVcfFile = true;
645 } else c.hasVcfFile = false;
646
647 // Check outfile
648 if (!vm.count("outfile")) c.outfile = "-";
649 else {
650 if (c.outfile.string() != "-") {
651 if (!_outfileValid(c.outfile)) return 1;
652 }
653 }
654
655 // Check bam file
656 LibraryInfo li;
657 if (!(boost::filesystem::exists(c.bamFile) && boost::filesystem::is_regular_file(c.bamFile) && boost::filesystem::file_size(c.bamFile))) {
658 std::cerr << "Alignment file is missing: " << c.bamFile.string() << std::endl;
659 return 1;
660 } else {
661 // Get scan regions
662 typedef boost::icl::interval_set<uint32_t> TChrIntervals;
663 typedef typename TChrIntervals::interval_type TIVal;
664 typedef std::vector<TChrIntervals> TRegionsGenome;
665 TRegionsGenome scanRegions;
666
667 // Open BAM file
668 samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
669 if (samfile == NULL) {
670 std::cerr << "Fail to open file " << c.bamFile.string() << std::endl;
671 return 1;
672 }
673 hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
674 if (idx == NULL) {
675 if (bam_index_build(c.bamFile.string().c_str(), 0) != 0) {
676 std::cerr << "Fail to open index for " << c.bamFile.string() << std::endl;
677 return 1;
678 }
679 }
680 bam_hdr_t* hdr = sam_hdr_read(samfile);
681 if (hdr == NULL) {
682 std::cerr << "Fail to open header for " << c.bamFile.string() << std::endl;
683 return 1;
684 }
685 c.nchr = hdr->n_targets;
686 c.minChrLen = setMinChrLen(hdr, 0.95);
687 std::string sampleName = "unknown";
688 getSMTag(std::string(hdr->text), c.bamFile.stem().string(), sampleName);
689 c.sampleName = sampleName;
690
691 // Check special chromosomes
692 if (haploidChr.size()) _selectedRefIndices(c, hdr, haploidChr);
693
694 // Check matching chromosome names
695 faidx_t* faiRef = fai_load(c.genome.string().c_str());
696 faidx_t* faiMap = fai_load(c.mapFile.string().c_str());
697 uint32_t mapFound = 0;
698 uint32_t refFound = 0;
699 for(int32_t refIndex=0; refIndex < hdr->n_targets; ++refIndex) {
700 std::string tname(hdr->target_name[refIndex]);
701 if (faidx_has_seq(faiMap, tname.c_str())) ++mapFound;
702 if (faidx_has_seq(faiRef, tname.c_str())) ++refFound;
703 else {
704 std::cerr << "Warning: BAM chromosome " << tname << " not present in reference genome!" << std::endl;
705 }
706 }
707 fai_destroy(faiRef);
708 fai_destroy(faiMap);
709 if (!mapFound) {
710 std::cerr << "Mappability map chromosome naming disagrees with BAM file!" << std::endl;
711 return 1;
712 }
713 if (!refFound) {
714 std::cerr << "Reference genome chromosome naming disagrees with BAM file!" << std::endl;
715 return 1;
716 }
717
718 // Estimate library params
719 if (c.hasScanFile) {
720 if (!_parseBedIntervals(c.scanFile.string(), c.hasScanFile, hdr, scanRegions)) {
721 std::cerr << "Warning: Couldn't parse BED intervals. Do the chromosome names match?" << std::endl;
722 return 1;
723 }
724 } else {
725 scanRegions.resize(hdr->n_targets);
726 for (int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
727 scanRegions[refIndex].insert(TIVal::right_open(0, hdr->target_len[refIndex]));
728 }
729 }
730 typedef std::vector<LibraryInfo> TSampleLibrary;
731 TSampleLibrary sampleLib(1, LibraryInfo());
732 CountDNAConfigLib dellyConf;
733 dellyConf.genome = c.genome;
734 dellyConf.files.push_back(c.bamFile);
735 dellyConf.madCutoff = 9;
736 dellyConf.madNormalCutoff = c.mad;
737 getLibraryParams(dellyConf, scanRegions, sampleLib);
738 li = sampleLib[0];
739 if (!li.median) {
740 li.median = 250;
741 li.mad = 15;
742 li.minNormalISize = 0;
743 li.maxNormalISize = 400;
744 }
745 c.meanisize = ((int32_t) (li.median / 2)) * 2 + 1;
746
747 // Clean-up
748 bam_hdr_destroy(hdr);
749 hts_idx_destroy(idx);
750 sam_close(samfile);
751 }
752
753 // GC bias estimation
754 typedef std::pair<uint32_t, uint32_t> TGCBound;
755 TGCBound gcbound;
756 std::vector<GcBias> gcbias(c.meanisize + 1, GcBias());
757 {
758 // Scan genomic windows
759 typedef std::vector<ScanWindow> TWindowCounts;
760 typedef std::vector<TWindowCounts> TGenomicWindowCounts;
761 TGenomicWindowCounts scanCounts(c.nchr, TWindowCounts());
762 scan(c, li, scanCounts);
763
764 // Check coverage
765 {
766 std::vector<uint32_t> sampleScanVec;
767 for(uint32_t i = 0; i < scanCounts.size(); ++i) {
768 for(uint32_t j = 0; j < scanCounts[i].size(); ++j) {
769 sampleScanVec.push_back(scanCounts[i][j].cov);
770 }
771 if (sampleScanVec.size() > 1000000) break;
772 }
773 std::sort(sampleScanVec.begin(), sampleScanVec.end());
774 if (sampleScanVec.empty()) {
775 std::cerr << "Not enough windows!" << std::endl;
776 return 1;
777 }
778 if (sampleScanVec[sampleScanVec.size()/2] < 5) {
779 std::cerr << "Please increase the window size. Coverage is too low!" << std::endl;
780 return 1;
781 }
782 }
783
784 // Select stable windows
785 selectWindows(c, scanCounts);
786
787 // Estimate GC bias
788 gcBias(c, scanCounts, li, gcbias, gcbound);
789
790 // Statistics output
791 if (c.hasStatsFile) {
792 // Open stats file
793 boost::iostreams::filtering_ostream statsOut;
794 statsOut.push(boost::iostreams::gzip_compressor());
795 statsOut.push(boost::iostreams::file_sink(c.statsFile.string().c_str(), std::ios_base::out | std::ios_base::binary));
796
797 // Library Info
798 statsOut << "LP\t" << li.rs << ',' << li.median << ',' << li.mad << ',' << li.minNormalISize << ',' << li.maxNormalISize << std::endl;
799
800 // Scan window summry
801 samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
802 bam_hdr_t* hdr = sam_hdr_read(samfile);
803 statsOut << "SW\tchrom\tstart\tend\tselected\tcoverage\tuniqcov" << std::endl;
804 for(uint32_t refIndex = 0; refIndex < (uint32_t) hdr->n_targets; ++refIndex) {
805 for(uint32_t i = 0; i < scanCounts[refIndex].size(); ++i) {
806 statsOut << "SW\t" << hdr->target_name[refIndex] << '\t' << scanCounts[refIndex][i].start << '\t' << scanCounts[refIndex][i].end << '\t' << scanCounts[refIndex][i].select << '\t' << scanCounts[refIndex][i].cov << '\t' << scanCounts[refIndex][i].uniqcov << std::endl;
807 }
808 }
809 bam_hdr_destroy(hdr);
810 sam_close(samfile);
811
812 // GC bias summary
813 statsOut << "GC\tgcsum\tsample\treference\tpercentileSample\tpercentileReference\tfractionSample\tfractionReference\tobsexp\tmeancoverage" << std::endl;
814 for(uint32_t i = 0; i < gcbias.size(); ++i) statsOut << "GC\t" << i << "\t" << gcbias[i].sample << "\t" << gcbias[i].reference << "\t" << gcbias[i].percentileSample << "\t" << gcbias[i].percentileReference << "\t" << gcbias[i].fractionSample << "\t" << gcbias[i].fractionReference << "\t" << gcbias[i].obsexp << "\t" << gcbias[i].coverage << std::endl;
815 statsOut << "BoundsGC\t" << gcbound.first << "," << gcbound.second << std::endl;
816 statsOut.pop();
817 statsOut.pop();
818 }
819 }
820
821 // Count reads
822 if (bamCount(c, li, gcbias, gcbound)) {
823 std::cerr << "Read counting error!" << std::endl;
824 return 1;
825 }
826
827 // Done
828 now = boost::posix_time::second_clock::local_time();
829 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Done." << std::endl;
830
831 return 0;
832 }
833
834
835 }
836
837 #endif