Debian Codegraph @

src/delly.h

raw symbols SCIP
1 #ifndef DELLY_H
2 #define DELLY_H
3
4
5 #include <iostream>
6 #include <fstream>
7
8 #include <boost/container/flat_set.hpp>
9 #include <boost/unordered_map.hpp>
10 #include <boost/program_options/cmdline.hpp>
11 #include <boost/program_options/options_description.hpp>
12 #include <boost/program_options/parsers.hpp>
13 #include <boost/program_options/variables_map.hpp>
14 #include <boost/date_time/posix_time/posix_time.hpp>
15 #include <boost/date_time/gregorian/gregorian.hpp>
16 #include <boost/math/special_functions/pow.hpp>
17 #include <boost/icl/split_interval_map.hpp>
18 #include <boost/tokenizer.hpp>
19 #include <boost/functional/hash.hpp>
20 #include <boost/filesystem/path.hpp>
21 #include <boost/filesystem/fstream.hpp>
22 #include <boost/filesystem.hpp>
23
24 #include <htslib/faidx.h>
25 #include <htslib/vcf.h>
26 #include <htslib/sam.h>
27
28 #include "threadpool.h"
29 #include "version.h"
30 #include "util.h"
31 #include "bolog.h"
32 #include "tags.h"
33 #include "coverage.h"
34 #include "msa.h"
35 #include "split.h"
36 #include "shortpe.h"
37 #include "modvcf.h"
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <zlib.h>
43 #include <stdio.h>
44
45 namespace torali
46 {
47
48 // Config arguments
49 struct Config {
50 uint16_t minMapQual;
51 uint16_t minTraQual;
52 uint16_t minGenoQual;
53 uint16_t madCutoff;
54 uint16_t madNormalCutoff;
55 int32_t nchr;
56 int32_t minimumFlankSize;
57 int32_t indelsize;
58 int32_t minConsWindow;
59 uint32_t graphPruning;
60 uint32_t minRefSep;
61 uint32_t maxReadSep;
62 uint32_t minClip;
63 uint32_t maxGenoReadCount;
64 uint32_t minCliqueSize;
65 uint32_t maxThreads;
66 uint32_t maxReadPerSV;
67 float flankQuality;
68 bool hasExcludeFile;
69 bool hasVcfFile;
70 bool hasDumpFile;
71 std::set<int32_t> svtset;
72 DnaScore<int> aliscore;
73 boost::filesystem::path outfile;
74 boost::filesystem::path vcffile;
75 boost::filesystem::path genome;
76 boost::filesystem::path exclude;
77 boost::filesystem::path dumpfile;
78 std::vector<boost::filesystem::path> files;
79 std::vector<std::string> sampleName;
80 };
81
82
83 template<typename TConfigStruct>
84 inline int dellyRun(TConfigStruct& c) {
85 #ifdef PROFILE
86 ProfilerStart("delly.prof");
87 #endif
88
89 // Collect all promising structural variants
90 typedef std::vector<StructuralVariantRecord> TVariants;
91 TVariants svs;
92
93 // Open header
94 samFile* samfile = sam_open(c.files[0].string().c_str(), "r");
95 bam_hdr_t* hdr = sam_hdr_read(samfile);
96
97 // Exclude intervals
98 typedef boost::icl::interval_set<uint32_t> TChrIntervals;
99 typedef std::vector<TChrIntervals> TRegionsGenome;
100 TRegionsGenome validRegions;
101 if (!_parseExcludeIntervals(c, hdr, validRegions)) {
102 std::cerr << "Delly couldn't parse exclude intervals!" << std::endl;
103 bam_hdr_destroy(hdr);
104 sam_close(samfile);
105 return 1;
106 }
107
108 // Debug code
109 //for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
110 //for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); vRIt != validRegions[refIndex].end(); ++vRIt) {
111 //std::cerr << std::string(hdr->target_name[refIndex]) << "\t" << vRIt->lower() << "\t" << vRIt->upper() << std::endl;
112 //}
113 //}
114
115 // Create library objects
116 typedef std::vector<LibraryInfo> TSampleLibrary;
117 TSampleLibrary sampleLib(c.files.size(), LibraryInfo());
118 getLibraryParams(c, validRegions, sampleLib);
119 for(uint32_t i = 0; i<sampleLib.size(); ++i) {
120 if (sampleLib[i].rs == 0) {
121 std::cerr << "Sample has not enough data to estimate library parameters! File: " << c.files[i].string() << std::endl;
122 bam_hdr_destroy(hdr);
123 sam_close(samfile);
124 return 1;
125 }
126 }
127
128 // SV Discovery
129 if (!c.hasVcfFile) {
130 // Split-read SVs
131 typedef std::vector<StructuralVariantRecord> TVariants;
132 TVariants srSVs;
133
134 // SR Store
135 {
136 typedef std::pair<int32_t, std::size_t> TPosRead;
137 typedef boost::unordered_map<TPosRead, int32_t> TPosReadSV;
138 typedef std::vector<TPosReadSV> TGenomicPosReadSV;
139 TGenomicPosReadSV srStore(c.nchr, TPosReadSV());
140 scanPEandSR(c, validRegions, svs, srSVs, srStore, sampleLib);
141
142 // Assemble split-read calls
143 assembleSplitReads(c, validRegions, srStore, srSVs);
144 }
145
146 // Sort and merge PE and SR calls
147 mergeSort(svs, srSVs);
148 } else vcfParse(c, hdr, svs);
149 // Clean-up
150 bam_hdr_destroy(hdr);
151 sam_close(samfile);
152
153 // Re-number SVs
154 sort(svs.begin(), svs.end());
155 uint32_t cliqueCount = 0;
156 for(typename TVariants::iterator svIt = svs.begin(); svIt != svs.end(); ++svIt, ++cliqueCount) svIt->id = cliqueCount;
157
158 // Annotate junction reads
159 typedef std::vector<JunctionCount> TSVJunctionMap;
160 typedef std::vector<TSVJunctionMap> TSampleSVJunctionMap;
161 TSampleSVJunctionMap jctMap;
162
163 // Annotate spanning coverage
164 typedef std::vector<SpanningCount> TSVSpanningMap;
165 typedef std::vector<TSVSpanningMap> TSampleSVSpanningMap;
166 TSampleSVSpanningMap spanMap;
167
168 // Annotate coverage
169 typedef std::vector<ReadCount> TSVReadCount;
170 typedef std::vector<TSVReadCount> TSampleSVReadCount;
171 TSampleSVReadCount rcMap;
172
173 // SV Genotyping
174 if (!svs.empty()) annotateCoverage(c, sampleLib, svs, rcMap, jctMap, spanMap);
175
176 // VCF output
177 vcfOutput(c, svs, jctMap, rcMap, spanMap);
178
179 // Output library statistics
180 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
181 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Sample statistics" << std::endl;
182 for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
183 std::cerr << "Sample:" << c.sampleName[file_c] << ",ReadSize=" << sampleLib[file_c].rs << ",Median=" << sampleLib[file_c].median << ",MAD=" << sampleLib[file_c].mad << ",UniqueDiscordantPairs=" << sampleLib[file_c].abnormal_pairs << std::endl;
184 }
185
186 #ifdef PROFILE
187 ProfilerStop();
188 #endif
189
190 // End
191 now = boost::posix_time::second_clock::local_time();
192 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] Done." << std::endl;;
193 return 0;
194 }
195
196
197 int delly(int argc, char **argv) {
198 Config c;
199 c.madNormalCutoff = 5;
200
201 // Define generic options
202 std::string svtype;
203 boost::program_options::options_description generic("Generic options");
204 generic.add_options()
205 ("help,?", "show help message")
206 ("svtype,t", boost::program_options::value<std::string>(&svtype)->default_value("ALL"), "SV type to compute [DEL, INS, DUP, INV, BND, ALL]")
207 ("genome,g", boost::program_options::value<boost::filesystem::path>(&c.genome), "genome fasta file")
208 ("exclude,x", boost::program_options::value<boost::filesystem::path>(&c.exclude), "file with regions to exclude")
209 ("outfile,o", boost::program_options::value<boost::filesystem::path>(&c.outfile), "BCF output file")
210 ("threads,h", boost::program_options::value<uint32_t>(&c.maxThreads)->default_value(4), "number of threads")
211 ;
212
213 boost::program_options::options_description disc("Discovery options");
214 disc.add_options()
215 ("map-qual,q", boost::program_options::value<uint16_t>(&c.minMapQual)->default_value(1), "min. paired-end (PE) mapping quality")
216 ("qual-tra,r", boost::program_options::value<uint16_t>(&c.minTraQual)->default_value(20), "min. PE quality for translocation")
217 ("mad-cutoff,s", boost::program_options::value<uint16_t>(&c.madCutoff)->default_value(9), "insert size cutoff, median+s*MAD (deletions only)")
218 ("minclip,c", boost::program_options::value<uint32_t>(&c.minClip)->default_value(25), "min. clipping length")
219 ("min-clique-size,z", boost::program_options::value<uint32_t>(&c.minCliqueSize)->default_value(2), "min. PE/SR clique size")
220 ("minrefsep,m", boost::program_options::value<uint32_t>(&c.minRefSep)->default_value(25), "min. reference separation")
221 ("maxreadsep,n", boost::program_options::value<uint32_t>(&c.maxReadSep)->default_value(40), "max. read separation")
222 ("max-reads,p", boost::program_options::value<uint32_t>(&c.maxReadPerSV)->default_value(20), "max. reads for consensus computation")
223 ;
224
225 boost::program_options::options_description geno("Genotyping options");
226 geno.add_options()
227 ("vcffile,v", boost::program_options::value<boost::filesystem::path>(&c.vcffile), "input VCF/BCF file for genotyping")
228 ("geno-qual,u", boost::program_options::value<uint16_t>(&c.minGenoQual)->default_value(5), "min. mapping quality for genotyping")
229 ("dump,d", boost::program_options::value<boost::filesystem::path>(&c.dumpfile), "gzipped output file for SV-reads (optional)")
230 ("max-geno-count,a", boost::program_options::value<uint32_t>(&c.maxGenoReadCount)->default_value(250), "max. number of reads aligned for SR genotyping")
231 ;
232
233 // Define hidden options
234 boost::program_options::options_description hidden("Hidden options");
235 hidden.add_options()
236 ("input-file", boost::program_options::value< std::vector<boost::filesystem::path> >(&c.files), "input file")
237 ("pruning,j", boost::program_options::value<uint32_t>(&c.graphPruning)->default_value(1000), "PE graph pruning cutoff")
238 ("cons-window,w", boost::program_options::value<int32_t>(&c.minConsWindow)->default_value(100), "consensus window")
239 ;
240
241 boost::program_options::positional_options_description pos_args;
242 pos_args.add("input-file", -1);
243
244 // Set the visibility
245 boost::program_options::options_description cmdline_options;
246 cmdline_options.add(generic).add(disc).add(geno).add(hidden);
247 boost::program_options::options_description visible_options;
248 visible_options.add(generic).add(disc).add(geno);
249 boost::program_options::variables_map vm;
250 boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
251 boost::program_options::notify(vm);
252
253 // Check command line arguments
254 if ((vm.count("help")) || (!vm.count("input-file")) || (!vm.count("genome"))) {
255 std::cerr << std::endl;
256 std::cerr << "Usage: delly " << argv[0] << " [OPTIONS] -g <ref.fa> <sample1.sort.bam> <sample2.sort.bam> ..." << std::endl;
257 std::cerr << visible_options << "\n";
258 return 0;
259 }
260
261 // SV types to compute?
262 if (!_svTypesToCompute(c, svtype)) {
263 std::cerr << "Please specify a valid SV type, i.e., -t INV or -t DEL,INV without spaces." << std::endl;
264 return 1;
265 }
266
267 // Check threads
268 c.maxThreads = std::min<std::size_t>(std::max<std::size_t>(1, c.maxThreads), std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1);
269
270 // Dump PE and SR support?
271 if (vm.count("dump")) c.hasDumpFile = true;
272 else c.hasDumpFile = false;
273
274 // Clique size
275 if (c.minCliqueSize < 2) c.minCliqueSize = 2;
276
277 // Check quality cuts
278 if (c.minMapQual > c.minTraQual) c.minTraQual = c.minMapQual;
279
280 // Check reference
281 if (!(boost::filesystem::exists(c.genome) && boost::filesystem::is_regular_file(c.genome) && boost::filesystem::file_size(c.genome))) {
282 std::cerr << "Reference file is missing: " << c.genome.string() << std::endl;
283 return 1;
284 } else {
285 faidx_t* fai = fai_load(c.genome.string().c_str());
286 if (fai == NULL) {
287 if (fai_build(c.genome.string().c_str()) == -1) {
288 std::cerr << "Fail to open genome fai index for " << c.genome.string() << std::endl;
289 return 1;
290 } else fai = fai_load(c.genome.string().c_str());
291 }
292 fai_destroy(fai);
293 }
294
295 // Check input files
296 c.sampleName.resize(c.files.size());
297 c.nchr = 0;
298 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
299 if (!(boost::filesystem::exists(c.files[file_c]) && boost::filesystem::is_regular_file(c.files[file_c]) && boost::filesystem::file_size(c.files[file_c]))) {
300 std::cerr << "Alignment file is missing: " << c.files[file_c].string() << std::endl;
301 return 1;
302 }
303 samFile* samfile = sam_open(c.files[file_c].string().c_str(), "r");
304 if (samfile == NULL) {
305 std::cerr << "Fail to open file " << c.files[file_c].string() << std::endl;
306 return 1;
307 }
308 hts_idx_t* idx = sam_index_load(samfile, c.files[file_c].string().c_str());
309 if (idx == NULL) {
310 std::cerr << "Fail to open index for " << c.files[file_c].string() << std::endl;
311 return 1;
312 }
313 bam_hdr_t* hdr = sam_hdr_read(samfile);
314 if (hdr == NULL) {
315 std::cerr << "Fail to open header for " << c.files[file_c].string() << std::endl;
316 return 1;
317 }
318 if (!c.nchr) c.nchr = hdr->n_targets;
319 else {
320 if (c.nchr != hdr->n_targets) {
321 std::cerr << "BAM files have different number of chromosomes!" << std::endl;
322 return 1;
323 }
324 }
325 faidx_t* fai = fai_load(c.genome.string().c_str());
326 for(int32_t refIndex=0; refIndex < hdr->n_targets; ++refIndex) {
327 std::string tname(hdr->target_name[refIndex]);
328 if (!faidx_has_seq(fai, tname.c_str())) {
329 std::cerr << "BAM file chromosome " << hdr->target_name[refIndex] << " is NOT present in your reference file " << c.genome.string() << std::endl;
330 return 1;
331 }
332 }
333 fai_destroy(fai);
334 std::string sampleName = "unknown";
335 getSMTag(std::string(hdr->text), c.files[file_c].stem().string(), sampleName);
336 c.sampleName[file_c] = sampleName;
337 bam_hdr_destroy(hdr);
338 hts_idx_destroy(idx);
339 sam_close(samfile);
340 }
341 checkSampleNames(c);
342
343 // Check exclude file
344 if (vm.count("exclude")) {
345 if (!(boost::filesystem::exists(c.exclude) && boost::filesystem::is_regular_file(c.exclude) && boost::filesystem::file_size(c.exclude))) {
346 std::cerr << "Exclude file is missing: " << c.exclude.string() << std::endl;
347 return 1;
348 }
349 c.hasExcludeFile = true;
350 } else c.hasExcludeFile = false;
351
352 // Check input VCF file
353 if (vm.count("vcffile")) {
354 if (!(boost::filesystem::exists(c.vcffile) && boost::filesystem::is_regular_file(c.vcffile) && boost::filesystem::file_size(c.vcffile))) {
355 std::cerr << "Input VCF/BCF file is missing: " << c.vcffile.string() << std::endl;
356 return 1;
357 }
358 htsFile* ifile = bcf_open(c.vcffile.string().c_str(), "r");
359 if (ifile == NULL) {
360 std::cerr << "Fail to open file " << c.vcffile.string() << std::endl;
361 return 1;
362 }
363 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
364 if (hdr == NULL) {
365 std::cerr << "Fail to open index file " << c.vcffile.string() << std::endl;
366 return 1;
367 }
368 bcf_hdr_destroy(hdr);
369 bcf_close(ifile);
370 c.hasVcfFile = true;
371 } else c.hasVcfFile = false;
372
373 // Check outfile
374 if (!vm.count("outfile")) c.outfile = "-";
375 else {
376 if (c.outfile.string() != "-") {
377 if (!_outfileValid(c.outfile)) return 1;
378 }
379 }
380
381 // Show cmd
382 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
383 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] ";
384 std::cerr << "delly ";
385 for(int i=0; i<argc; ++i) { std::cerr << argv[i] << ' '; }
386 std::cerr << std::endl;
387
388 // Always ignore reads of mapping quality <5 for genotyping, otherwise het. is more likely!
389 if (c.minGenoQual<5) c.minGenoQual=5;
390
391 // Run main program
392 c.aliscore = DnaScore<int>(5, -4, -10, -1);
393 c.flankQuality = 0.95;
394 c.minimumFlankSize = 13;
395 c.indelsize = 1000;
396 return dellyRun(c);
397 }
398
399 }
400
401 #endif