Debian Codegraph @

src/merge.h

raw symbols SCIP
1 #ifndef MERGE_H
2 #define MERGE_H
3
4 #define BOOST_UUID_RANDOM_PROVIDER_FORCE_POSIX
5
6 #include <iostream>
7 #include <fstream>
8 #include <boost/unordered_map.hpp>
9 #include <boost/graph/adjacency_list.hpp>
10 #include <boost/graph/connected_components.hpp>
11 #include <boost/program_options/cmdline.hpp>
12 #include <boost/program_options/options_description.hpp>
13 #include <boost/program_options/parsers.hpp>
14 #include <boost/program_options/variables_map.hpp>
15 #include <boost/uuid/uuid.hpp>
16 #include <boost/uuid/uuid_generators.hpp>
17 #include <boost/uuid/uuid_io.hpp>
18 #include <boost/date_time/posix_time/posix_time.hpp>
19 #include <boost/date_time/gregorian/gregorian.hpp>
20 #include <boost/iostreams/stream.hpp>
21 #include <boost/iostreams/stream_buffer.hpp>
22 #include <boost/iostreams/device/file.hpp>
23 #include <boost/iostreams/filtering_stream.hpp>
24 #include <boost/iostreams/filter/zlib.hpp>
25 #include <boost/iostreams/filter/gzip.hpp>
26 #include <boost/icl/interval_map.hpp>
27 #include <boost/filesystem.hpp>
28 #include <boost/tokenizer.hpp>
29 #include <htslib/sam.h>
30 #include <htslib/vcf.h>
31
32 #include "tags.h"
33 #include "version.h"
34 #include "util.h"
35 #include "modvcf.h"
36
37
38 namespace torali
39 {
40
41
42 struct MergeConfig {
43 bool filterForPass;
44 bool filterForPrecise;
45 bool cnvMode;
46 uint32_t chunksize;
47 uint32_t svcounter;
48 uint32_t bpoffset;
49 uint32_t minsize;
50 uint32_t maxsize;
51 uint32_t coverage;
52 int32_t qualthres;
53 float recoverlap;
54 float vaf;
55 boost::filesystem::path outfile;
56 std::vector<boost::filesystem::path> files;
57 };
58
59 struct IntervalScore {
60 uint32_t start;
61 uint32_t end;
62 int32_t score;
63
64 IntervalScore(uint32_t s, uint32_t e, int32_t c) : start(s), end(e), score(c) {}
65
66 bool operator<(const IntervalScore& s2) const {
67 return ((start < s2.start) || ((start == s2.start) && (end < s2.end)));
68 }
69 };
70
71 template<typename TPos>
72 double recOverlap(TPos const s1, TPos const e1, TPos const s2, TPos const e2) {
73 if ((e1 < s2) || (s1 > e2)) return 0;
74 double lenA = (double) (e1-s1);
75 if (lenA <= 0) return 0;
76 double lenB = (double) (e2-s2);
77 if (lenB <= 0) return 0;
78 double overlapLen = double(std::min(e1, e2) - std::max(s1, s2));
79 if (overlapLen <= 0) return 0;
80 return (overlapLen / std::max(lenA, lenB));
81 }
82
83
84 template<typename TGenomeIntervals, typename TContigMap>
85 void _fillIntervalMap(MergeConfig const& c, TGenomeIntervals& iScore, TContigMap& cMap, int32_t const svtin) {
86 typedef typename TGenomeIntervals::value_type TIntervalScores;
87 typedef typename TIntervalScores::value_type IntervalScore;
88
89 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
90 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Reading input VCF/BCF files" << std::endl;
91
92
93 boost::unordered_map<int32_t, std::string> refmap;
94 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
95 htsFile* ifile = bcf_open(c.files[file_c].string().c_str(), "r");
96 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
97 bcf1_t* rec = bcf_init();
98
99 int32_t nsvend = 0;
100 int32_t* svend = NULL;
101 int32_t ninslen = 0;
102 int32_t* inslen = NULL;
103 int32_t nct = 0;
104 char* ct = NULL;
105 int32_t nsvt = 0;
106 char* svt = NULL;
107 while (bcf_read(ifile, hdr, rec) == 0) {
108 bcf_unpack(rec, BCF_UN_INFO);
109 // Check PASS
110 bool pass = true;
111 if (c.filterForPass) pass = (bcf_has_filter(hdr, rec, const_cast<char*>("PASS"))==1);
112 if (!pass) continue;
113
114 // Correct SV type
115 int32_t recsvt = -1;
116 if (bcf_get_info_string(hdr, rec, "SVTYPE", &svt, &nsvt) > 0) {
117 if (bcf_get_info_string(hdr, rec, "CT", &ct, &nct) > 0) recsvt = _decodeOrientation(std::string(ct), std::string(svt));
118 else recsvt = _decodeOrientation(std::string("NA"), std::string(svt));
119 }
120 if (recsvt != svtin) continue;
121
122 // Correct size?
123 std::string chrName(bcf_hdr_id2name(hdr, rec->rid));
124 uint32_t tid = cMap[chrName];
125 uint32_t svStart = rec->pos;
126 uint32_t svEnd = rec->pos + 2;
127 if (bcf_get_info_int32(hdr, rec, "END", &svend, &nsvend) > 0) svEnd = *svend;
128 if (recsvt == 4) {
129 // Insertion
130 uint32_t inslenVal = 0;
131 if (bcf_get_info_int32(hdr, rec, "INSLEN", &inslen, &ninslen) > 0) inslenVal = *inslen;
132 if ((inslenVal < c.minsize) || (inslenVal > c.maxsize)) continue;
133 svEnd = svStart + inslenVal; // To enable reciprocal overlap
134 } else {
135 // Other intra-chr SV
136 if ((svEnd - svStart < c.minsize) || (svEnd - svStart > c.maxsize)) continue;
137 }
138
139 // Precise?
140 bool precise = false;
141 if (bcf_get_info_flag(hdr, rec, "PRECISE", 0, 0) > 0) precise=true;
142 if ((c.filterForPrecise) && (!precise)) continue;
143
144 // Quality threshold
145 if (rec->qual < c.qualthres) continue;
146
147 // Variant allele frequency filter
148 if ((c.vaf > 0) || (c.coverage > 0)) {
149 float maxvaf = 0;
150 uint32_t maxcov = 0;
151 bcf_unpack(rec, BCF_UN_ALL);
152 int ndv = 0;
153 int32_t* dv = NULL;
154 int ndr = 0;
155 int32_t* dr = NULL;
156 int nrv = 0;
157 int32_t* rv = NULL;
158 int nrr = 0;
159 int32_t* rr = NULL;
160 int ngt = 0;
161 int32_t* gt = NULL;
162 bcf_get_format_int32(hdr, rec, "DV", &dv, &ndv);
163 bcf_get_format_int32(hdr, rec, "DR", &dr, &ndr);
164 bcf_get_format_int32(hdr, rec, "RV", &rv, &nrv);
165 bcf_get_format_int32(hdr, rec, "RR", &rr, &nrr);
166 bcf_get_format_int32(hdr, rec, "GT", &gt, &ngt);
167 for(int32_t i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
168 if ((bcf_gt_allele(gt[i*2]) != -1) && (bcf_gt_allele(gt[i*2 + 1]) != -1)) {
169 uint32_t supportsum = 0;
170 if (precise) supportsum = rr[i] + rv[i];
171 else supportsum = dr[i] + dv[i];
172 if (supportsum > 0) {
173 double vaf = 0;
174 if (precise) vaf = (double) rv[i] / (double) supportsum;
175 else vaf = (double) dv[i] / (double) supportsum;
176 if (vaf > maxvaf) maxvaf = vaf;
177 if (supportsum > maxcov) maxcov = supportsum;
178 }
179 }
180 }
181 // Debug
182 //std::cerr << maxcov << '\t' << maxvaf << std::endl;
183 if (dv != NULL) free(dv);
184 if (dr != NULL) free(dr);
185 if (rv != NULL) free(rv);
186 if (rr != NULL) free(rr);
187 if (gt != NULL) free(gt);
188 if (recsvt != 9) {
189 if ((maxvaf < c.vaf) || (maxcov < c.coverage)) continue;
190 }
191 }
192 // Store the interval
193 //std::cerr << tid << ',' << svStart << ',' << svEnd << ',' << rec->qual << std::endl;
194 iScore[tid].push_back(IntervalScore(svStart, svEnd, rec->qual));
195 }
196 if (svend != NULL) free(svend);
197 if (inslen != NULL) free(inslen);
198 if (ct != NULL) free(ct);
199 if (svt != NULL) free(svt);
200 bcf_hdr_destroy(hdr);
201 bcf_close(ifile);
202 bcf_destroy(rec);
203 }
204 }
205
206 template<typename TGenomeIntervals>
207 void _processIntervalMap(MergeConfig const& c, TGenomeIntervals const& iScore, TGenomeIntervals& iSelected, int32_t const svtin) {
208 typedef typename TGenomeIntervals::value_type TIntervalScores;
209 typedef typename TIntervalScores::value_type IntervalScore;
210
211 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
212 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Merging SVs" << std::endl;
213
214 unsigned int seqId = 0;
215 for(typename TGenomeIntervals::const_iterator iG = iScore.begin(); iG != iScore.end(); ++iG, ++seqId) {
216 typedef std::vector<bool> TIntervalSelector;
217 TIntervalSelector keepInterval;
218 keepInterval.resize(iG->size(), true);
219 typename TIntervalSelector::iterator iK = keepInterval.begin();
220 for(typename TIntervalScores::const_iterator iS = iG->begin(); iS != iG->end(); ++iS, ++iK) {
221 typename TIntervalScores::const_iterator iSNext = iS;
222 typename TIntervalSelector::iterator iKNext = iK;
223 ++iSNext; ++iKNext;
224 for(; iSNext != iG->end(); ++iSNext, ++iKNext) {
225 if (iSNext->start - iS->start > c.bpoffset) break;
226 else {
227 if (((iSNext->end > iS->end) && (iSNext->end - iS->end < c.bpoffset)) || ((iSNext->end <= iS->end) &&(iS->end - iSNext->end < c.bpoffset))) {
228 if ((_translocation(svtin)) || (recOverlap(iS->start, iS->end, iSNext->start, iSNext->end) >= c.recoverlap)) {
229 if (iS->score < iSNext->score) *iK = false;
230 else if (iSNext ->score < iS->score) *iKNext = false;
231 else {
232 if (iS->start < iSNext->start) *iKNext = false;
233 else if (iS->end < iSNext->end) *iKNext = false;
234 else *iK = false;
235 }
236 }
237 }
238 }
239 }
240 if (*iK) iSelected[seqId].push_back(IntervalScore(iS->start, iS->end, iS->score));
241 }
242 }
243 }
244
245 template<typename TGenomeIntervals, typename TContigMap>
246 void _outputSelectedIntervals(MergeConfig& c, TGenomeIntervals const& iSelected, TContigMap& cMap, int32_t const svtin) {
247 typedef typename TGenomeIntervals::value_type TIntervalScores;
248 typedef typename TIntervalScores::value_type IntervalScore;
249
250 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
251 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Filtering SVs" << std::endl;
252
253 // Open output VCF file
254 std::string fmtout = "wb";
255 if (c.outfile.string() == "-") fmtout = "w";
256 htsFile *fp = hts_open(c.outfile.string().c_str(), fmtout.c_str());
257 bcf_hdr_t *hdr_out = bcf_hdr_init("w");
258
259 // Write VCF header
260 boost::gregorian::date today = now.date();
261 std::string datestr("##fileDate=");
262 datestr += boost::gregorian::to_iso_string(today);
263 bcf_hdr_append(hdr_out, datestr.c_str());
264 bcf_hdr_append(hdr_out, "##ALT=<ID=DEL,Description=\"Deletion\">");
265 bcf_hdr_append(hdr_out, "##ALT=<ID=DUP,Description=\"Duplication\">");
266 bcf_hdr_append(hdr_out, "##ALT=<ID=INV,Description=\"Inversion\">");
267 bcf_hdr_append(hdr_out, "##ALT=<ID=BND,Description=\"Translocation\">");
268 bcf_hdr_append(hdr_out, "##ALT=<ID=INS,Description=\"Insertion\">");
269 bcf_hdr_append(hdr_out, "##FILTER=<ID=LowQual,Description=\"Poor quality and insufficient number of PEs and SRs.\">");
270 bcf_hdr_append(hdr_out, "##INFO=<ID=CIEND,Number=2,Type=Integer,Description=\"PE confidence interval around END\">");
271 bcf_hdr_append(hdr_out, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"PE confidence interval around POS\">");
272 bcf_hdr_append(hdr_out, "##INFO=<ID=CHR2,Number=1,Type=String,Description=\"Chromosome for POS2 coordinate in case of an inter-chromosomal translocation\">");
273 bcf_hdr_append(hdr_out, "##INFO=<ID=POS2,Number=1,Type=Integer,Description=\"Genomic position for CHR2 in case of an inter-chromosomal translocation\">");
274 bcf_hdr_append(hdr_out, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the structural variant\">");
275 bcf_hdr_append(hdr_out, "##INFO=<ID=PE,Number=1,Type=Integer,Description=\"Paired-end support of the structural variant\">");
276 bcf_hdr_append(hdr_out, "##INFO=<ID=MAPQ,Number=1,Type=Integer,Description=\"Median mapping quality of paired-ends\">");
277 bcf_hdr_append(hdr_out, "##INFO=<ID=SRMAPQ,Number=1,Type=Integer,Description=\"Median mapping quality of split-reads\">");
278 bcf_hdr_append(hdr_out, "##INFO=<ID=SR,Number=1,Type=Integer,Description=\"Split-read support\">");
279 bcf_hdr_append(hdr_out, "##INFO=<ID=SRQ,Number=1,Type=Float,Description=\"Split-read consensus alignment quality\">");
280 bcf_hdr_append(hdr_out, "##INFO=<ID=CONSENSUS,Number=1,Type=String,Description=\"Split-read consensus sequence\">");
281 bcf_hdr_append(hdr_out, "##INFO=<ID=CONSBP,Number=1,Type=Integer,Description=\"Consensus SV breakpoint position\">");
282 bcf_hdr_append(hdr_out, "##INFO=<ID=CE,Number=1,Type=Float,Description=\"Consensus sequence entropy\">");
283 bcf_hdr_append(hdr_out, "##INFO=<ID=CT,Number=1,Type=String,Description=\"Paired-end signature induced connection type\">");
284 bcf_hdr_append(hdr_out, "##INFO=<ID=SVLEN,Number=1,Type=Integer,Description=\"Insertion length for SVTYPE=INS.\">");
285 bcf_hdr_append(hdr_out, "##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description=\"Imprecise structural variation\">");
286 bcf_hdr_append(hdr_out, "##INFO=<ID=PRECISE,Number=0,Type=Flag,Description=\"Precise structural variation\">");
287 bcf_hdr_append(hdr_out, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">");
288 bcf_hdr_append(hdr_out, "##INFO=<ID=SVMETHOD,Number=1,Type=String,Description=\"Type of approach used to detect SV\">");
289 bcf_hdr_append(hdr_out, "##INFO=<ID=INSLEN,Number=1,Type=Integer,Description=\"Predicted length of the insertion\">");
290 bcf_hdr_append(hdr_out, "##INFO=<ID=HOMLEN,Number=1,Type=Integer,Description=\"Predicted microhomology length using a max. edit distance of 2\">");
291
292 // Add reference contigs
293 uint32_t numseq = 0;
294 typedef std::map<uint32_t, std::string> TReverseMap;
295 TReverseMap rMap;
296 for(typename TContigMap::iterator cIt = cMap.begin(); cIt != cMap.end(); ++cIt, ++numseq) rMap[cIt->second] = cIt->first;
297 for(typename TReverseMap::iterator rIt = rMap.begin(); rIt != rMap.end(); ++rIt) {
298 std::string refname("##contig=<ID=");
299 refname += rIt->second + ">";
300 bcf_hdr_append(hdr_out, refname.c_str());
301 }
302 bcf_hdr_add_sample(hdr_out, NULL);
303 if (bcf_hdr_write(fp, hdr_out) != 0) std::cerr << "Error: Failed to write BCF header!" << std::endl;
304
305 // Duplicate filter (identical start, end, score values)
306 typedef std::pair<uint32_t, uint32_t> TStartEnd;
307 typedef std::set<TStartEnd> TIntervalSet;
308 typedef std::vector<TIntervalSet> TGenomicIntervalSet;
309 TGenomicIntervalSet gis(numseq);
310
311 // Parse input VCF files
312 bcf1_t *rout = bcf_init();
313 typedef std::vector<htsFile*> THtsFile;
314 typedef std::vector<bcf_hdr_t*> TBcfHeader;
315 typedef std::vector<bcf1_t*> TBcfRecord;
316 typedef std::vector<bool> TEof;
317 THtsFile ifile(c.files.size());
318 TBcfHeader hdr(c.files.size());
319 TBcfRecord rec(c.files.size());
320 TEof eof(c.files.size());
321 uint32_t allEOF = 0;
322 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
323 ifile[file_c] = bcf_open(c.files[file_c].string().c_str(), "r");
324 hdr[file_c] = bcf_hdr_read(ifile[file_c]);
325 if (bcf_hdr_set_samples(hdr[file_c], NULL, false) != 0) std::cerr << "Error: Failed to set sample information!" << std::endl;
326 rec[file_c] = bcf_init();
327 if (bcf_read(ifile[file_c], hdr[file_c], rec[file_c]) == 0) {
328 bcf_unpack(rec[file_c], BCF_UN_INFO);
329 eof[file_c] = false;
330 } else {
331 ++allEOF;
332 eof[file_c] = true;
333 }
334 }
335
336 int32_t nsvend = 0;
337 int32_t* svend = NULL;
338 int32_t npe = 0;
339 int32_t* pe = NULL;
340 int32_t nsr = 0;
341 int32_t* sr = NULL;
342 int32_t ninslen = 0;
343 int32_t* inslen = NULL;
344 int32_t npos2 = 0;
345 int32_t* pos2 = NULL;
346 int32_t nconsbp = 0;
347 int32_t* consbp = NULL;
348 int32_t nhomlen = 0;
349 int32_t* homlen = NULL;
350 int32_t nmapq = 0;
351 int32_t* mapq = NULL;
352 int32_t nsrmapq = 0;
353 int32_t* srmapq = NULL;
354 int32_t nsrq = 0;
355 float* srq = NULL;
356 int32_t nct = 0;
357 char* ct = NULL;
358 int32_t nsvt = 0;
359 char* svt = NULL;
360 int32_t nchr2 = 0;
361 char* chr2 = NULL;
362 int32_t ncipos = 0;
363 int32_t* cipos = NULL;
364 int32_t nciend = 0;
365 int32_t* ciend = NULL;
366 int32_t nce = 0;
367 float* ce = NULL;
368 int32_t ncons = 0;
369 char* cons = NULL;
370 while (allEOF < c.files.size()) {
371 // Find next sorted record
372 int32_t idx = -1;
373 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
374 if (!eof[file_c]) {
375 if ((idx < 0) || (rec[idx]->rid > rec[file_c]->rid) || ((rec[idx]->rid == rec[file_c]->rid) && (rec[idx]->pos > rec[file_c]->pos))) idx = file_c;
376 }
377 }
378
379 // Correct SV type
380 int32_t recsvt = -1;
381 if ((bcf_get_info_string(hdr[idx], rec[idx], "SVTYPE", &svt, &nsvt) > 0) && (bcf_get_info_string(hdr[idx], rec[idx], "CT", &ct, &nct) > 0)) recsvt = _decodeOrientation(std::string(ct), std::string(svt));
382 if (recsvt == svtin) {
383 // Check PASS
384 bool pass = true;
385 if (c.filterForPass) pass = (bcf_has_filter(hdr[idx], rec[idx], const_cast<char*>("PASS"))==1);
386
387 // Check PRECISE
388 bool precise = false;
389 bool passPrecise = true;
390 if (bcf_get_info_flag(hdr[idx], rec[idx], "PRECISE", 0, 0) > 0) precise=true;
391 if ((c.filterForPrecise) && (!precise)) passPrecise = false;
392
393 // Check PASS and precise
394 if ((rec[idx]->qual >= c.qualthres) && (passPrecise) && (pass)) {
395 // Correct size
396 std::string chrName(bcf_hdr_id2name(hdr[idx], rec[idx]->rid));
397 uint32_t tid = cMap[chrName];
398 uint32_t svStart = rec[idx]->pos;
399 uint32_t svEnd = svStart + 1;
400 uint32_t tmpSvEnd = 0;
401 if (bcf_get_info_int32(hdr[idx], rec[idx], "END", &svend, &nsvend) > 0) svEnd = *svend;
402 unsigned int inslenVal = 0;
403 if (bcf_get_info_int32(hdr[idx], rec[idx], "INSLEN", &inslen, &ninslen) > 0) inslenVal = *inslen;
404 if (recsvt == 4) {
405 tmpSvEnd = svEnd;
406 svEnd = svStart + inslenVal; // To enable reciprocal overlap
407 }
408
409 // Parse INFO fields
410 if ((std::string(svt) == "BND") || ((std::string(svt) == "INS") && (inslenVal >= c.minsize) && (inslenVal <= c.maxsize)) || ((std::string(svt) != "BND") && (std::string(svt) != "INS") && (svEnd - svStart >= c.minsize) && (svEnd - svStart <= c.maxsize))) {
411 unsigned int peSupport = 0;
412 if (bcf_get_info_int32(hdr[idx], rec[idx], "PE", &pe, &npe) > 0) peSupport = *pe;
413 unsigned int srSupport = 0;
414 if (bcf_get_info_int32(hdr[idx], rec[idx], "SR", &sr, &nsr) > 0) srSupport = *sr;
415 // Remove this line
416 //if (srSupport > 0) precise = true;
417
418 int32_t peMapQuality = 0;
419 if (bcf_get_info_int32(hdr[idx], rec[idx], "MAPQ", &mapq, &nmapq) > 0) peMapQuality = *mapq;
420 int32_t srMapQuality = 0;
421 if (bcf_get_info_int32(hdr[idx], rec[idx], "SRMAPQ", &srmapq, &nsrmapq) > 0) srMapQuality = *srmapq;
422 std::string chr2Name = chrName;
423 int32_t pos2val = 0;
424 if (bcf_get_info_string(hdr[idx], rec[idx], "CHR2", &chr2, &nchr2) > 0) {
425 chr2Name = std::string(chr2);
426 if (bcf_get_info_int32(hdr[idx], rec[idx], "POS2", &pos2, &npos2) > 0) pos2val = *pos2;
427 //mtid = cMap[chr2Name];
428 }
429 int32_t score = rec[idx]->qual;
430
431 // Is this a selected interval
432 typename TIntervalScores::const_iterator iter = std::lower_bound(iSelected[tid].begin(), iSelected[tid].end(), IntervalScore(svStart, svEnd, score));
433 bool foundInterval = false;
434 for(; (iter != iSelected[tid].end()) && (iter->start == svStart); ++iter) {
435 if ((iter->start == svStart) && (iter->end == svEnd) && (iter->score == score)) {
436 // Duplicate?
437 if (gis[tid].find(std::make_pair(svStart, svEnd)) == gis[tid].end()) {
438 foundInterval = true;
439 gis[tid].insert(std::make_pair(svStart, svEnd));
440 }
441 break;
442 }
443 }
444 if (foundInterval) {
445 // Fetch missing INFO fields
446 unsigned int homlenVal = 0;
447 if (bcf_get_info_int32(hdr[idx], rec[idx], "HOMLEN", &homlen, &nhomlen) > 0) homlenVal = *homlen;
448 bcf_get_info_int32(hdr[idx], rec[idx], "CIPOS", &cipos, &ncipos);
449 bcf_get_info_int32(hdr[idx], rec[idx], "CIEND", &ciend, &nciend);
450 float srAlignQuality = 0;
451 if (bcf_get_info_float(hdr[idx], rec[idx], "SRQ", &srq, &nsrq) > 0) srAlignQuality = *srq;
452
453 std::string consStr;
454 float ceVal = 0;
455 int32_t consBpVal = 0;
456 if (precise) {
457 if (bcf_get_info_float(hdr[idx], rec[idx], "CE", &ce, &nce) > 0) ceVal = *ce;
458 if (bcf_get_info_string(hdr[idx], rec[idx], "CONSENSUS", &cons, &ncons) > 0) consStr = boost::to_upper_copy(std::string(cons));
459 if (bcf_get_info_int32(hdr[idx], rec[idx], "CONSBP", &consbp, &nconsbp) > 0) consBpVal = *consbp;
460 }
461
462 // Create new record
463 rout->rid = bcf_hdr_name2id(hdr_out, chrName.c_str());
464 rout->pos = rec[idx]->pos;
465 rout->qual = rec[idx]->qual;
466 std::string id;
467 if (c.files.size() == 1) id = std::string(rec[idx]->d.id); // Within one VCF file IDs are unique
468 else {
469 id += _addID(svtin);
470 std::string padNumber = boost::lexical_cast<std::string>(c.svcounter++);
471 padNumber.insert(padNumber.begin(), 8 - padNumber.length(), '0');
472 id += padNumber;
473 }
474 bcf_update_id(hdr_out, rout, id.c_str());
475 std::string refAllele = rec[idx]->d.allele[0];
476 std::string altAllele = rec[idx]->d.allele[1];
477 std::string alleles = refAllele + "," + altAllele;
478 bcf_update_alleles_str(hdr_out, rout, alleles.c_str());
479 int32_t tmppass = bcf_hdr_id2int(hdr_out, BCF_DT_ID, "PASS");
480 bcf_update_filter(hdr_out, rout, &tmppass, 1);
481
482 // Add INFO fields
483 if (precise) bcf_update_info_flag(hdr_out, rout, "PRECISE", NULL, 1);
484 else bcf_update_info_flag(hdr_out, rout, "IMPRECISE", NULL, 1);
485 bcf_update_info_string(hdr_out, rout, "SVTYPE", _addID(svtin).c_str());
486 std::string dellyVersion("EMBL.DELLYv");
487 dellyVersion += dellyVersionNumber;
488 bcf_update_info_string(hdr_out,rout, "SVMETHOD", dellyVersion.c_str());
489 if (recsvt == 4) bcf_update_info_int32(hdr_out, rout, "END", &tmpSvEnd, 1);
490 else bcf_update_info_int32(hdr_out, rout, "END", &svEnd, 1);
491 if (svtin >= DELLY_SVT_TRANS) {
492 bcf_update_info_string(hdr_out,rout, "CHR2", chr2Name.c_str());
493 bcf_update_info_int32(hdr_out, rout, "POS2", &pos2val, 1);
494 }
495 if (svtin == 4) {
496 bcf_update_info_int32(hdr_out, rout, "SVLEN", &inslenVal, 1);
497 }
498 bcf_update_info_int32(hdr_out, rout, "PE", &peSupport, 1);
499 int32_t tmpi = peMapQuality;
500 bcf_update_info_int32(hdr_out, rout, "MAPQ", &tmpi, 1);
501 bcf_update_info_string(hdr_out, rout, "CT", _addOrientation(svtin).c_str());
502 bcf_update_info_int32(hdr_out, rout, "CIPOS", cipos, 2);
503 bcf_update_info_int32(hdr_out, rout, "CIEND", ciend, 2);
504 if (precise) {
505 tmpi = srMapQuality;
506 bcf_update_info_int32(hdr_out, rout, "SRMAPQ", &tmpi, 1);
507 bcf_update_info_int32(hdr_out, rout, "INSLEN", &inslenVal, 1);
508 bcf_update_info_int32(hdr_out, rout, "HOMLEN", &homlenVal, 1);
509 bcf_update_info_int32(hdr_out, rout, "SR", &srSupport, 1);
510 bcf_update_info_float(hdr_out, rout, "SRQ", &srAlignQuality, 1);
511 if (consStr.size()) {
512 bcf_update_info_string(hdr_out, rout, "CONSENSUS", consStr.c_str());
513 bcf_update_info_float(hdr_out, rout, "CE", &ceVal, 1);
514 bcf_update_info_int32(hdr_out, rout, "CONSBP", &consBpVal, 1);
515 }
516 }
517
518 // Write record
519 bcf_write1(fp, hdr_out, rout);
520 bcf_clear1(rout);
521 //std::cerr << bcf_hdr_id2name(hdr[idx], tid) << '\t' << svStart << '\t' << svEnd << std::endl;
522 }
523 }
524 }
525 }
526
527 // Fetch next record
528 if (bcf_read(ifile[idx], hdr[idx], rec[idx]) == 0) bcf_unpack(rec[idx], BCF_UN_INFO);
529 else {
530 ++allEOF;
531 eof[idx] = true;
532 }
533 }
534 if (svend != NULL) free(svend);
535 if (pe != NULL) free(pe);
536 if (sr != NULL) free(sr);
537 if (homlen != NULL) free(homlen);
538 if (inslen != NULL) free(inslen);
539 if (pos2 != NULL) free(pos2);
540 if (consbp != NULL) free(consbp);
541 if (mapq != NULL) free(mapq);
542 if (srmapq != NULL) free(srmapq);
543 if (ct != NULL) free(ct);
544 if (srq != NULL) free(srq);
545 if (svt != NULL) free(svt);
546 if (chr2 != NULL) free(chr2);
547 if (cipos != NULL) free(cipos);
548 if (ciend != NULL) free(ciend);
549 if (ce != NULL) free(ce);
550 if (cons != NULL) free(cons);
551
552 // Clean-up
553 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
554 bcf_hdr_destroy(hdr[file_c]);
555 bcf_close(ifile[file_c]);
556 bcf_destroy(rec[file_c]);
557 }
558
559 // Close VCF file
560 bcf_destroy(rout);
561 bcf_hdr_destroy(hdr_out);
562 hts_close(fp);
563
564 // Build index
565 if (c.outfile.string() != "-") bcf_index_build(c.outfile.string().c_str(), 14);
566 }
567
568
569
570 template<typename TGenomeIntervals, typename TContigMap>
571 void _outputSelectedIntervalsCNVs(MergeConfig& c, TGenomeIntervals const& iSelected, TContigMap& cMap) {
572 typedef typename TGenomeIntervals::value_type TIntervalScores;
573 typedef typename TIntervalScores::value_type IntervalScore;
574
575 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
576 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Filtering SVs" << std::endl;
577
578 // Open output VCF file
579 std::string fmtout = "wb";
580 if (c.outfile.string() == "-") fmtout = "w";
581 htsFile *fp = hts_open(c.outfile.string().c_str(), fmtout.c_str());
582 bcf_hdr_t *hdr_out = bcf_hdr_init("w");
583
584 // Write VCF header
585 boost::gregorian::date today = now.date();
586 std::string datestr("##fileDate=");
587 datestr += boost::gregorian::to_iso_string(today);
588 bcf_hdr_append(hdr_out, datestr.c_str());
589 bcf_hdr_append(hdr_out, "##ALT=<ID=CNV,Description=\"copy-number variants\">");
590 bcf_hdr_append(hdr_out, "##FILTER=<ID=LowQual,Description=\"Poor quality copy-number variant\">");
591 bcf_hdr_append(hdr_out, "##INFO=<ID=CIEND,Number=2,Type=Integer,Description=\"Confidence interval around END\">");
592 bcf_hdr_append(hdr_out, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"Confidence interval around POS\">");
593 bcf_hdr_append(hdr_out, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the copy-number variant\">");
594 bcf_hdr_append(hdr_out, "##INFO=<ID=MP,Number=1,Type=Float,Description=\"Mappable fraction of CNV\">");
595 bcf_hdr_append(hdr_out, "##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description=\"Imprecise copy-number variant\">");
596 bcf_hdr_append(hdr_out, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">");
597 bcf_hdr_append(hdr_out, "##INFO=<ID=SVMETHOD,Number=1,Type=String,Description=\"Type of approach used to detect CNV\">");
598
599 // Add reference contigs
600 uint32_t numseq = 0;
601 typedef std::map<uint32_t, std::string> TReverseMap;
602 TReverseMap rMap;
603 for(typename TContigMap::iterator cIt = cMap.begin(); cIt != cMap.end(); ++cIt, ++numseq) rMap[cIt->second] = cIt->first;
604 for(typename TReverseMap::iterator rIt = rMap.begin(); rIt != rMap.end(); ++rIt) {
605 std::string refname("##contig=<ID=");
606 refname += rIt->second + ">";
607 bcf_hdr_append(hdr_out, refname.c_str());
608 }
609 bcf_hdr_add_sample(hdr_out, NULL);
610 if (bcf_hdr_write(fp, hdr_out) != 0) std::cerr << "Error: Failed to write BCF header!" << std::endl;
611
612 // Duplicate filter (identical start, end, score values)
613 typedef std::pair<uint32_t, uint32_t> TStartEnd;
614 typedef std::set<TStartEnd> TIntervalSet;
615 typedef std::vector<TIntervalSet> TGenomicIntervalSet;
616 TGenomicIntervalSet gis(numseq);
617
618 // Parse input VCF files
619 bcf1_t *rout = bcf_init();
620 typedef std::vector<htsFile*> THtsFile;
621 typedef std::vector<bcf_hdr_t*> TBcfHeader;
622 typedef std::vector<bcf1_t*> TBcfRecord;
623 typedef std::vector<bool> TEof;
624 THtsFile ifile(c.files.size());
625 TBcfHeader hdr(c.files.size());
626 TBcfRecord rec(c.files.size());
627 TEof eof(c.files.size());
628 uint32_t allEOF = 0;
629 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
630 ifile[file_c] = bcf_open(c.files[file_c].string().c_str(), "r");
631 hdr[file_c] = bcf_hdr_read(ifile[file_c]);
632 if (bcf_hdr_set_samples(hdr[file_c], NULL, false) != 0) std::cerr << "Error: Failed to set sample information!" << std::endl;
633 rec[file_c] = bcf_init();
634 if (bcf_read(ifile[file_c], hdr[file_c], rec[file_c]) == 0) {
635 bcf_unpack(rec[file_c], BCF_UN_INFO);
636 eof[file_c] = false;
637 } else {
638 ++allEOF;
639 eof[file_c] = true;
640 }
641 }
642
643 int32_t nsvend = 0;
644 int32_t* svend = NULL;
645 int32_t nmp = 0;
646 float* mp = NULL;
647 int32_t nsvt = 0;
648 char* svt = NULL;
649 int32_t ncipos = 0;
650 int32_t* cipos = NULL;
651 int32_t nciend = 0;
652 int32_t* ciend = NULL;
653 while (allEOF < c.files.size()) {
654 // Find next sorted record
655 int32_t idx = -1;
656 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
657 if (!eof[file_c]) {
658 if ((idx < 0) || (rec[idx]->rid > rec[file_c]->rid) || ((rec[idx]->rid == rec[file_c]->rid) && (rec[idx]->pos > rec[file_c]->pos))) idx = file_c;
659 }
660 }
661
662 // Correct SV type
663 int32_t recsvt = -1;
664 if (bcf_get_info_string(hdr[idx], rec[idx], "SVTYPE", &svt, &nsvt) > 0) recsvt = _decodeOrientation(std::string("NA"), std::string(svt));
665 // CNV ?
666 if (recsvt == 9) {
667 // Check PASS
668 bool pass = true;
669 if (c.filterForPass) pass = (bcf_has_filter(hdr[idx], rec[idx], const_cast<char*>("PASS"))==1);
670
671 // Check PRECISE
672 bool precise = false;
673 bool passPrecise = true;
674 if (bcf_get_info_flag(hdr[idx], rec[idx], "PRECISE", 0, 0) > 0) precise=true;
675 if ((c.filterForPrecise) && (!precise)) passPrecise = false;
676
677 // Check PASS and precise
678 if ((rec[idx]->qual >= c.qualthres) && (passPrecise) && (pass)) {
679 // Correct size
680 std::string chrName(bcf_hdr_id2name(hdr[idx], rec[idx]->rid));
681 uint32_t tid = cMap[chrName];
682 uint32_t svStart = rec[idx]->pos;
683 uint32_t svEnd = svStart + 1;
684 if (bcf_get_info_int32(hdr[idx], rec[idx], "END", &svend, &nsvend) > 0) svEnd = *svend;
685
686 // Parse INFO fields
687 if ((svEnd - svStart >= c.minsize) && (svEnd - svStart <= c.maxsize)) {
688 int32_t score = rec[idx]->qual;
689
690 // Is this a selected interval
691 typename TIntervalScores::const_iterator iter = std::lower_bound(iSelected[tid].begin(), iSelected[tid].end(), IntervalScore(svStart, svEnd, score));
692 bool foundInterval = false;
693 for(; (iter != iSelected[tid].end()) && (iter->start == svStart); ++iter) {
694 if ((iter->start == svStart) && (iter->end == svEnd) && (iter->score == score)) {
695 // Duplicate?
696 if (gis[tid].find(std::make_pair(svStart, svEnd)) == gis[tid].end()) {
697 foundInterval = true;
698 gis[tid].insert(std::make_pair(svStart, svEnd));
699 }
700 break;
701 }
702 }
703 if (foundInterval) {
704 // Fetch missing INFO fields
705 bcf_get_info_int32(hdr[idx], rec[idx], "CIPOS", &cipos, &ncipos);
706 bcf_get_info_int32(hdr[idx], rec[idx], "CIEND", &ciend, &nciend);
707 float mpval = 0;
708 if (bcf_get_info_float(hdr[idx], rec[idx], "MP", &mp, &nmp) > 0) mpval = *mp;
709
710 // Create new record
711 rout->rid = bcf_hdr_name2id(hdr_out, chrName.c_str());
712 rout->pos = rec[idx]->pos;
713 rout->qual = rec[idx]->qual;
714 std::string id;
715 if (c.files.size() == 1) id = std::string(rec[idx]->d.id); // Within one VCF file IDs are unique
716 else {
717 id += _addID(recsvt);
718 std::string padNumber = boost::lexical_cast<std::string>(c.svcounter++);
719 padNumber.insert(padNumber.begin(), 8 - padNumber.length(), '0');
720 id += padNumber;
721 }
722 bcf_update_id(hdr_out, rout, id.c_str());
723 std::string refAllele = rec[idx]->d.allele[0];
724 std::string altAllele = rec[idx]->d.allele[1];
725 std::string alleles = refAllele + "," + altAllele;
726 bcf_update_alleles_str(hdr_out, rout, alleles.c_str());
727 int32_t tmppass = bcf_hdr_id2int(hdr_out, BCF_DT_ID, "PASS");
728 bcf_update_filter(hdr_out, rout, &tmppass, 1);
729
730 // Add INFO fields
731 if (precise) bcf_update_info_flag(hdr_out, rout, "PRECISE", NULL, 1);
732 else bcf_update_info_flag(hdr_out, rout, "IMPRECISE", NULL, 1);
733 bcf_update_info_string(hdr_out, rout, "SVTYPE", _addID(recsvt).c_str());
734 std::string dellyVersion("EMBL.DELLYv");
735 dellyVersion += dellyVersionNumber;
736 bcf_update_info_string(hdr_out,rout, "SVMETHOD", dellyVersion.c_str());
737 bcf_update_info_int32(hdr_out, rout, "END", &svEnd, 1);
738 bcf_update_info_int32(hdr_out, rout, "CIPOS", cipos, 2);
739 bcf_update_info_int32(hdr_out, rout, "CIEND", ciend, 2);
740 bcf_update_info_float(hdr_out, rout, "MP", &mpval, 1);
741
742 // Write record
743 bcf_write1(fp, hdr_out, rout);
744 bcf_clear1(rout);
745 //std::cerr << bcf_hdr_id2name(hdr[idx], tid) << '\t' << svStart << '\t' << svEnd << std::endl;
746 }
747 }
748 }
749 }
750
751 // Fetch next record
752 if (bcf_read(ifile[idx], hdr[idx], rec[idx]) == 0) bcf_unpack(rec[idx], BCF_UN_INFO);
753 else {
754 ++allEOF;
755 eof[idx] = true;
756 }
757 }
758 if (svend != NULL) free(svend);
759 if (mp != NULL) free(mp);
760 if (svt != NULL) free(svt);
761 if (cipos != NULL) free(cipos);
762 if (ciend != NULL) free(ciend);
763
764 // Clean-up
765 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
766 bcf_hdr_destroy(hdr[file_c]);
767 bcf_close(ifile[file_c]);
768 bcf_destroy(rec[file_c]);
769 }
770
771 // Close VCF file
772 bcf_destroy(rout);
773 bcf_hdr_destroy(hdr_out);
774 hts_close(fp);
775
776 // Build index
777 if (c.outfile.string() != "-") bcf_index_build(c.outfile.string().c_str(), 14);
778 }
779
780 inline void
781 mergeBCFs(MergeConfig& c, std::vector<boost::filesystem::path> const& cts) {
782 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
783 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Merging SV types" << std::endl;
784
785 // Parse temporary input VCF files
786 typedef std::vector<htsFile*> THtsFile;
787 typedef std::vector<bcf_hdr_t*> TBcfHeader;
788 typedef std::vector<bcf1_t*> TBcfRecord;
789 typedef std::vector<bool> TEof;
790 THtsFile ifile(cts.size());
791 TBcfHeader hdr(cts.size());
792 TBcfRecord rec(cts.size());
793 TEof eof(cts.size());
794 uint32_t allEOF = 0;
795 for(unsigned int file_c = 0; file_c < cts.size(); ++file_c) {
796 ifile[file_c] = bcf_open(cts[file_c].string().c_str(), "r");
797 hdr[file_c] = bcf_hdr_read(ifile[file_c]);
798 rec[file_c] = bcf_init();
799 if (bcf_read(ifile[file_c], hdr[file_c], rec[file_c]) == 0) {
800 bcf_unpack(rec[file_c], BCF_UN_INFO);
801 eof[file_c] = false;
802 } else {
803 ++allEOF;
804 eof[file_c] = true;
805 }
806 }
807
808 // Open output VCF file
809 std::string fmtout = "wb";
810 if (c.outfile.string() == "-") fmtout = "w";
811 htsFile *fp = hts_open(c.outfile.string().c_str(), fmtout.c_str());
812 bcf_hdr_t *hdr_out = bcf_hdr_dup(hdr[0]);
813 if (bcf_hdr_write(fp, hdr_out) != 0) std::cerr << "Error: Failed to write BCF header!" << std::endl;
814
815 // Merge files
816 while (allEOF < cts.size()) {
817 // Find next sorted record
818 int32_t idx = -1;
819 for(unsigned int file_c = 0; file_c < cts.size(); ++file_c) {
820 if (!eof[file_c]) {
821 if ((idx < 0) || (rec[idx]->rid > rec[file_c]->rid) || ((rec[idx]->rid == rec[file_c]->rid) && (rec[idx]->pos > rec[file_c]->pos))) idx = file_c;
822 }
823 }
824
825 // Write record
826 bcf_write1(fp, hdr_out, rec[idx]);
827
828 // Fetch next record
829 if (bcf_read(ifile[idx], hdr[idx], rec[idx]) == 0) bcf_unpack(rec[idx], BCF_UN_INFO);
830 else {
831 ++allEOF;
832 eof[idx] = true;
833 }
834 }
835
836 // Clean-up
837 for(unsigned int file_c = 0; file_c < cts.size(); ++file_c) {
838 bcf_hdr_destroy(hdr[file_c]);
839 bcf_close(ifile[file_c]);
840 bcf_destroy(rec[file_c]);
841 }
842
843 // Close VCF file
844 bcf_hdr_destroy(hdr_out);
845 hts_close(fp);
846
847 // Build index
848 if (c.outfile.string() != "-") bcf_index_build(c.outfile.string().c_str(), 14);
849
850 // End
851 now = boost::posix_time::second_clock::local_time();
852 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] Done." << std::endl;
853 }
854
855 inline int
856 mergeRun(MergeConfig& c, int32_t const svt) {
857
858 // All files may use a different set of chromosomes
859 typedef std::map<std::string, uint32_t> TContigMap;
860 TContigMap contigMap;
861 uint32_t numseq = 0;
862 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
863 htsFile* ifile = bcf_open(c.files[file_c].string().c_str(), "r");
864 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
865 int nseq=0;
866 const char** seqnames = bcf_hdr_seqnames(hdr, &nseq);
867 for(int32_t i = 0; i<nseq;++i) {
868 std::string chrName(bcf_hdr_id2name(hdr, i));
869 if (contigMap.find(chrName) == contigMap.end()) contigMap[chrName] = numseq++;
870 }
871 if (seqnames!=NULL) free(seqnames);
872 bcf_hdr_destroy(hdr);
873 bcf_close(ifile);
874 }
875
876 // Interval maps
877 typedef std::vector<IntervalScore> TIntervalScores;
878 typedef std::vector<TIntervalScores> TGenomeIntervals;
879 TGenomeIntervals iScore;
880 iScore.resize(numseq, TIntervalScores());
881 _fillIntervalMap(c, iScore, contigMap, svt);
882 for(uint32_t i = 0; i<numseq; ++i) std::sort(iScore[i].begin(), iScore[i].end());
883
884 // Filter intervals
885 TGenomeIntervals iSelected;
886 iSelected.resize(numseq, TIntervalScores());
887 _processIntervalMap(c, iScore, iSelected, svt);
888 iScore.clear();
889 for(uint32_t i = 0; i<numseq; ++i) std::sort(iSelected[i].begin(), iSelected[i].end());
890
891 // Output best intervals
892 if (svt == 9) _outputSelectedIntervalsCNVs(c, iSelected, contigMap);
893 else _outputSelectedIntervals(c, iSelected, contigMap, svt);
894
895 // End
896 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
897 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] Done." << std::endl;
898
899 return 0;
900 }
901
902 int merge(int argc, char **argv) {
903 MergeConfig c;
904 c.svcounter = 1;
905
906 // Define generic options
907 boost::program_options::options_description generic("Generic options");
908 generic.add_options()
909 ("help,?", "show help message")
910 ("outfile,o", boost::program_options::value<boost::filesystem::path>(&c.outfile), "Merged SV BCF output file")
911 ("quality,y", boost::program_options::value<int32_t>(&c.qualthres)->default_value(200), "min. SV site quality")
912 ("chunks,u", boost::program_options::value<uint32_t>(&c.chunksize)->default_value(500), "max. chunk size to merge groups of BCF files")
913 ("vaf,a", boost::program_options::value<float>(&c.vaf)->default_value(0.15), "min. fractional ALT support")
914 ("coverage,v", boost::program_options::value<uint32_t>(&c.coverage)->default_value(5), "min. coverage")
915 ("minsize,m", boost::program_options::value<uint32_t>(&c.minsize)->default_value(0), "min. SV size")
916 ("maxsize,n", boost::program_options::value<uint32_t>(&c.maxsize)->default_value(1000000), "max. SV size")
917 ("cnvmode,e", "Merge delly CNV files")
918 ("precise,c", "Filter sites for PRECISE")
919 ("pass,p", "Filter sites for PASS")
920 ;
921
922 // Define overlap options
923 boost::program_options::options_description overlap("Overlap options");
924 overlap.add_options()
925 ("bp-offset,b", boost::program_options::value<uint32_t>(&c.bpoffset)->default_value(1000), "max. breakpoint offset")
926 ("rec-overlap,r", boost::program_options::value<float>(&c.recoverlap)->default_value(0.8), "min. reciprocal overlap")
927 ;
928
929 // Define hidden options
930 boost::program_options::options_description hidden("Hidden options");
931 hidden.add_options()
932 ("input-file", boost::program_options::value< std::vector<boost::filesystem::path> >(&c.files), "input file")
933 ;
934 boost::program_options::positional_options_description pos_args;
935 pos_args.add("input-file", -1);
936
937 // Set the visibility
938 boost::program_options::options_description cmdline_options;
939 cmdline_options.add(generic).add(overlap).add(hidden);
940 boost::program_options::options_description visible_options;
941 visible_options.add(generic).add(overlap);
942 boost::program_options::variables_map vm;
943 boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
944 boost::program_options::notify(vm);
945
946
947 // Check command line arguments
948 if ((vm.count("help")) || (!vm.count("input-file"))) {
949 std::cerr << std::endl;
950 std::cerr << "Usage: delly " << argv[0] << " [OPTIONS] [<sample1.bcf> <sample2.bcf> ... | <list_of_bcf_files.txt>]" << std::endl;
951 std::cerr << visible_options << "\n";
952 return 0;
953 }
954
955 // Filter for PASS
956 if (vm.count("pass")) c.filterForPass = true;
957 else c.filterForPass = false;
958
959 // Filter for PRECISE
960 if (vm.count("precise")) c.filterForPrecise = true;
961 else c.filterForPrecise = false;
962
963 // Merge CNVs
964 if (vm.count("cnvmode")) c.cnvMode = true;
965 else c.cnvMode = false;
966
967 // Check output files
968 if (!vm.count("outfile")) c.outfile = "-";
969 else {
970 if (c.outfile.string() != "-") {
971 if (!_outfileValid(c.outfile)) return 1;
972 if (!_outfileValid(boost::filesystem::path(c.outfile.string() + ".csi"))) return 1;
973 }
974 }
975
976 // Show cmd
977 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
978 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] ";
979 std::cerr << "delly ";
980 for(int i=0; i<argc; ++i) { std::cerr << argv[i] << ' '; }
981 std::cerr << std::endl;
982
983 // Check chunksize
984 if (c.chunksize < 100) c.chunksize = 100;
985
986 // Check input BCF files
987 if (c.files.size() == 1) {
988 // Single file: VCF/BCF or list of files?
989 if (!(boost::filesystem::exists(c.files[0]) && boost::filesystem::is_regular_file(c.files[0]) && boost::filesystem::file_size(c.files[0]))) {
990 std::cerr << "Input file list " << c.files[0].string() << " is missing!" << std::endl;
991 return 1;
992 }
993 htsFile* inf = bcf_open(c.files[0].string().c_str(), "r");
994 if (inf != NULL) {
995 bcf_hdr_t* header = NULL;
996 header = bcf_hdr_read(inf);
997 if (header == NULL) {
998 std::cerr << "Assuming input is a list of BCF files" << std::endl;
999 std::string fname = c.files[0].string();
1000 c.files.clear();
1001 std::ifstream lf(fname.c_str());
1002 if (lf.good()) {
1003 std::string line;
1004 while(std::getline(lf, line)) {
1005 if (!line.empty()) {
1006 if (line.at(line.length() - 1) == '\r' ) {
1007 line = line.substr(0, line.length() - 1);
1008 }
1009 c.files.push_back(line);
1010 }
1011 }
1012 lf.close();
1013 }
1014 } else {
1015 bcf_hdr_destroy(header);
1016 }
1017 }
1018 bcf_close(inf);
1019 }
1020 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
1021 htsFile* ifile = bcf_open(c.files[file_c].string().c_str(), "r");
1022 if (!ifile) {
1023 std::cerr << "Fail to load " << c.files[file_c].string() << "!" << std::endl;
1024 return 1;
1025 }
1026 bcf_close(ifile);
1027 }
1028
1029 // Determine optimal chunksize
1030 if (c.files.size() > c.chunksize) {
1031 int32_t bestChunkSize = c.chunksize;
1032 int32_t bestBinSize = 0;
1033 for(uint32_t i = 50; i < c.chunksize; ++i) {
1034 int32_t chunks = ((c.files.size() - 1) / i);
1035 int32_t lastBin = c.files.size() - chunks * i;
1036 if (lastBin > bestBinSize) {
1037 bestBinSize = lastBin;
1038 bestChunkSize = i;
1039 }
1040 }
1041 c.chunksize = bestChunkSize;
1042 }
1043
1044 // Run merging
1045 int32_t minSVT = 0;
1046 int32_t maxSVT = 9;
1047 if (c.cnvMode) {
1048 minSVT = 9;
1049 maxSVT = 10;
1050 }
1051 boost::filesystem::path oldPath = c.outfile;
1052 std::vector<boost::filesystem::path> svtCollect(maxSVT);
1053 for(int32_t svt = minSVT; svt < maxSVT; ++svt) {
1054 boost::uuids::uuid uuid = boost::uuids::random_generator()();
1055 std::string filename = "svt" + boost::lexical_cast<std::string>(svt) + "_" + boost::lexical_cast<std::string>(uuid) + ".bcf";
1056 svtCollect[svt] = filename;
1057 if (c.files.size() <= c.chunksize) {
1058 // Merge in one go
1059 c.outfile = svtCollect[svt];
1060 mergeRun(c, svt);
1061 } else {
1062 // Merge in chunks
1063 std::vector<boost::filesystem::path> fileRestore = c.files;
1064 uint32_t chunks = ((c.files.size() - 1) / c.chunksize) + 1;
1065 std::vector<boost::filesystem::path> chunkCollect(chunks);
1066 for(uint32_t ic = 0; ic < chunks; ++ic) {
1067 boost::uuids::uuid uuid2 = boost::uuids::random_generator()();
1068 std::string chunkfile = "chunk" + boost::lexical_cast<std::string>(ic) + "_" + boost::lexical_cast<std::string>(uuid2) + ".bcf";
1069 chunkCollect[ic] = chunkfile;
1070 c.files.clear();
1071 for(uint32_t k = ic * c.chunksize; ((k < ((ic+1) * c.chunksize)) && (k < fileRestore.size())); ++k) c.files.push_back(fileRestore[k]);
1072 c.outfile = chunkCollect[ic];
1073 mergeRun(c, svt);
1074 }
1075 // Merge chunks
1076 c.files = chunkCollect;
1077 c.outfile = svtCollect[svt];
1078 // Reset VAF and coverage because these are site lists!
1079 float vafStore = c.vaf;
1080 uint32_t coverageStore = c.coverage;
1081 c.vaf = 0;
1082 c.coverage = 0;
1083 mergeRun(c, svt);
1084 c.vaf = vafStore;
1085 c.coverage = coverageStore;
1086 // Clean-up
1087 for(uint32_t ic = 0; ic < chunks; ++ic) {
1088 boost::filesystem::remove(chunkCollect[ic]);
1089 boost::filesystem::remove(boost::filesystem::path(chunkCollect[ic].string() + ".csi"));
1090 }
1091 c.files = fileRestore;
1092 }
1093 }
1094
1095 // Merge temporary files
1096 c.outfile = oldPath;
1097 if (c.cnvMode) {
1098 // Copy
1099 boost::filesystem::copy_file(svtCollect[9], c.outfile);
1100 boost::filesystem::copy_file(boost::filesystem::path(svtCollect[9].string() + ".csi"), boost::filesystem::path(c.outfile.string() + ".csi"));
1101 // Delete
1102 boost::filesystem::remove(svtCollect[9]);
1103 boost::filesystem::remove(boost::filesystem::path(svtCollect[9].string() + ".csi"));
1104 } else {
1105 mergeBCFs(c, svtCollect);
1106 for(int32_t svt = minSVT; svt < maxSVT; ++svt) {
1107 boost::filesystem::remove(svtCollect[svt]);
1108 boost::filesystem::remove(boost::filesystem::path(svtCollect[svt].string() + ".csi"));
1109 }
1110 }
1111 return 0;
1112 }
1113
1114 }
1115
1116 #endif
1117