Debian Codegraph @

src/classify.h

raw symbols SCIP
1 #ifndef CLASSIFY_H
2 #define CLASSIFY_H
3
4 #include <iostream>
5 #include <fstream>
6 #include <boost/unordered_map.hpp>
7 #include <boost/graph/adjacency_list.hpp>
8 #include <boost/graph/connected_components.hpp>
9 #include <boost/program_options/cmdline.hpp>
10 #include <boost/program_options/options_description.hpp>
11 #include <boost/program_options/parsers.hpp>
12 #include <boost/program_options/variables_map.hpp>
13 #include <boost/date_time/posix_time/posix_time.hpp>
14 #include <boost/date_time/gregorian/gregorian.hpp>
15 #include <boost/iostreams/stream.hpp>
16 #include <boost/iostreams/stream_buffer.hpp>
17 #include <boost/iostreams/device/file.hpp>
18 #include <boost/iostreams/filtering_stream.hpp>
19 #include <boost/iostreams/filter/zlib.hpp>
20 #include <boost/iostreams/filter/gzip.hpp>
21 #include <boost/icl/interval_map.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/tokenizer.hpp>
24 #include <boost/accumulators/accumulators.hpp>
25 #include <boost/accumulators/statistics.hpp>
26
27 #include <htslib/sam.h>
28 #include <htslib/vcf.h>
29 #include <htslib/tbx.h>
30
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35 #include <zlib.h>
36 #include <stdio.h>
37
38 #include "tags.h"
39 #include "version.h"
40 #include "util.h"
41 #include "modvcf.h"
42
43 namespace torali
44 {
45
46
47 struct ClassifyConfig {
48 bool filterForPass;
49 bool hasSampleFile;
50 int32_t minsize;
51 int32_t maxsize;
52 int32_t qual;
53 uint16_t ploidy;
54 float pgerm;
55 float maxsd;
56 float cn_offset;
57 std::string filter;
58 std::set<std::string> tumorSet;
59 std::set<std::string> controlSet;
60 boost::filesystem::path outfile;
61 boost::filesystem::path samplefile;
62 boost::filesystem::path vcffile;
63 };
64
65
66 template<typename TClassifyConfig>
67 inline int
68 classifyRun(TClassifyConfig const& c) {
69
70 // Load bcf file
71 htsFile* ifile = hts_open(c.vcffile.string().c_str(), "r");
72 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
73
74 // Open output VCF file
75 std::string fmtout = "wb";
76 if (c.outfile.string() == "-") fmtout = "w";
77 htsFile *ofile = hts_open(c.outfile.string().c_str(), fmtout.c_str());
78 bcf_hdr_t *hdr_out = bcf_hdr_dup(hdr);
79 if (c.filter == "somatic") {
80 bcf_hdr_remove(hdr_out, BCF_HL_INFO, "SOMATIC");
81 bcf_hdr_append(hdr_out, "##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description=\"Somatic copy-number variant.\">");
82 bcf_hdr_remove(hdr_out, BCF_HL_INFO, "PGERM");
83 bcf_hdr_append(hdr_out, "##INFO=<ID=PGERM,Number=1,Type=Float,Description=\"Probability of being germline.\">");
84 bcf_hdr_remove(hdr_out, BCF_HL_INFO, "CNDIFF");
85 bcf_hdr_append(hdr_out, "##INFO=<ID=CNDIFF,Number=1,Type=Float,Description=\"Absolute tumor-normal CN difference.\">");
86 } else {
87 bcf_hdr_remove(hdr_out, BCF_HL_INFO, "CNSHIFT");
88 bcf_hdr_append(hdr_out, "##INFO=<ID=CNSHIFT,Number=1,Type=Float,Description=\"Estimated CN shift.\">");
89 bcf_hdr_remove(hdr_out, BCF_HL_INFO, "CNSD");
90 bcf_hdr_append(hdr_out, "##INFO=<ID=CNSD,Number=1,Type=Float,Description=\"Estimated CN standard deviation.\">");
91 }
92 if (bcf_hdr_write(ofile, hdr_out) != 0) std::cerr << "Error: Failed to write BCF header!" << std::endl;
93
94 // VCF fields
95 int32_t nsvend = 0;
96 int32_t* svend = NULL;
97 int32_t nsvt = 0;
98 char* svt = NULL;
99 int ngqval = 0;
100 int32_t* gqval = NULL;
101 int ncnval = 0;
102 int32_t* cnval = NULL;
103 int ncnl = 0;
104 float* cnl = NULL;
105 int nrdcn = 0;
106 float* rdcn = NULL;
107 int nrdsd = 0;
108 float* rdsd = NULL;
109 bool germline = false;
110 if (c.filter == "germline") germline = true;
111
112 // Parse BCF
113 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
114 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Filtering VCF/BCF file" << std::endl;
115 bcf1_t* rec = bcf_init1();
116 while (bcf_read(ifile, hdr, rec) == 0) {
117 bcf_unpack(rec, BCF_UN_INFO);
118
119 // Check SV type
120 bcf_get_info_string(hdr, rec, "SVTYPE", &svt, &nsvt);
121 if (std::string(svt) != "CNV") continue;
122
123 // Check PASS
124 bool pass = true;
125 if (c.filterForPass) pass = (bcf_has_filter(hdr, rec, const_cast<char*>("PASS"))==1);
126 if (!pass) continue;
127
128 // Check size
129 int32_t svStart= rec->pos - 1;
130 bcf_get_info_int32(hdr, rec, "END", &svend, &nsvend);
131 int32_t svEnd = *svend;
132 if (svStart > svEnd) continue;
133 int32_t svlen = svEnd - svStart;
134 if ((svlen < c.minsize) || (svlen > c.maxsize)) continue;
135
136 // Check copy-number
137 bcf_unpack(rec, BCF_UN_ALL);
138 bcf_get_format_int32(hdr, rec, "GQ", &gqval, &ngqval);
139 bcf_get_format_int32(hdr, rec, "CN", &cnval, &ncnval);
140 bcf_get_format_float(hdr, rec, "CNL", &cnl, &ncnl);
141 bcf_get_format_float(hdr, rec, "RDCN", &rdcn, &nrdcn);
142 bcf_get_format_float(hdr, rec, "RDSD", &rdsd, &nrdsd);
143
144 typedef std::pair<float, float> TCnSd;
145 typedef std::vector<TCnSd> TSampleDist;
146 TSampleDist control;
147 TSampleDist tumor;
148 bool invalidCNV = false;
149 for (int i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
150 if ((!std::isfinite(rdcn[i])) || (rdcn[i] == -1)) {
151 invalidCNV = true;
152 break;
153 }
154 if ((germline) || (c.controlSet.find(hdr->samples[i]) != c.controlSet.end())) {
155 // Control or population genomics
156 control.push_back(std::make_pair(rdcn[i], rdsd[i]));
157 } else if ((!germline) && (c.tumorSet.find(hdr->samples[i]) != c.tumorSet.end())) {
158 // Tumor
159 tumor.push_back(std::make_pair(rdcn[i], rdsd[i]));
160 }
161 }
162 if (invalidCNV) continue;
163
164 // Classify
165 if (!germline) {
166 // Somatic mode
167 double bestCnOffset = 0;
168 bool somaticcnv = false;
169 double lowestp = 1;
170 for(uint32_t i = 0; i < tumor.size(); ++i) {
171 bool germcnv = false;
172 double highestprob = 0;
173 double tcnoffset = -1;
174 for(uint32_t k = 0; k < control.size(); ++k) {
175 boost::math::normal s1(control[k].first, control[k].second);
176 double prob1 = boost::math::pdf(s1, tumor[i].first);
177 boost::math::normal s2(tumor[i].first, tumor[i].second);
178 double prob2 = boost::math::pdf(s2, control[k].first);
179 double prob = std::max(prob1, prob2);
180 if (prob > c.pgerm) germcnv = true;
181 else {
182 // Among all controls, take highest p-value (most likely germline CNV)
183 if (prob > highestprob) highestprob = prob;
184 }
185 double cndiff = std::abs(tumor[i].first - control[k].first);
186 if (cndiff < c.cn_offset) germcnv = true;
187 else {
188 // Among all controls, take smallest CN difference
189 if ((tcnoffset == -1) || (cndiff < tcnoffset)) tcnoffset = cndiff;
190 }
191 }
192 // Among all tumors take best CN difference and lowest p-value
193 if (!germcnv) {
194 somaticcnv = true;
195 if ((highestprob < lowestp) && (tcnoffset > bestCnOffset)) {
196 lowestp = highestprob;
197 bestCnOffset = tcnoffset;
198 }
199 }
200 }
201 if (!somaticcnv) continue;
202 _remove_info_tag(hdr_out, rec, "SOMATIC");
203 bcf_update_info_flag(hdr_out, rec, "SOMATIC", NULL, 1);
204 float pgerm = (float) lowestp;
205 _remove_info_tag(hdr_out, rec, "PGERM");
206 bcf_update_info_float(hdr_out, rec, "PGERM", &pgerm, 1);
207 float cndiv = (float) bestCnOffset;
208 _remove_info_tag(hdr_out, rec, "CNDIFF");
209 bcf_update_info_float(hdr_out, rec, "CNDIFF", &cndiv, 1);
210 } else {
211 // Correct CN shift
212 int32_t cnmain = 0;
213 {
214 std::vector<int32_t> cncount(MAX_CN, 0);
215 {
216 bool validsite = true;
217 boost::accumulators::accumulator_set<double, boost::accumulators::features<boost::accumulators::tag::mean, boost::accumulators::tag::variance> > acc;
218 for(uint32_t k = 0; k < control.size(); ++k) {
219 if ((boost::math::isinf(control[k].first)) || (boost::math::isnan(control[k].first))) validsite = false;
220 else acc(boost::math::round(control[k].first) - control[k].first);
221 }
222 if (!validsite) continue;
223 double cnshift = boost::accumulators::mean(acc);
224 float cnshiftval = cnshift;
225 _remove_info_tag(hdr_out, rec, "CNSHIFT");
226 bcf_update_info_float(hdr_out, rec, "CNSHIFT", &cnshiftval, 1);
227 for (int i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
228 rdcn[i] += cnshift;
229 cnval[i] = boost::math::round(rdcn[i]);
230 if ((cnval[i] >= 0) && (cnval[i] < MAX_CN)) ++cncount[cnval[i]];
231 }
232 }
233
234 // Find max CN
235 for(uint32_t i = 1; i < MAX_CN; ++i) {
236 if (cncount[i] > cncount[cnmain]) cnmain = i;
237 }
238 }
239
240 // Calculate SD
241 boost::accumulators::accumulator_set<double, boost::accumulators::features<boost::accumulators::tag::mean, boost::accumulators::tag::variance> > accLocal;
242 for (int i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
243 if (cnval[i] == cnmain) accLocal(rdcn[i]);
244 }
245 double sd = sqrt(boost::accumulators::variance(accLocal));
246 if (sd < 0.025) sd = 0.025;
247 float cnsdval = sd;
248 _remove_info_tag(hdr_out, rec, "CNSD");
249 bcf_update_info_float(hdr_out, rec, "CNSD", &cnsdval, 1);
250 if (cnsdval > c.maxsd) continue;
251
252 // Re-compute CNLs
253 std::vector<std::string> ftarr(bcf_hdr_nsamples(hdr));
254 int32_t altqual = 0;
255 int32_t altcount = 0;
256 for (int i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
257 int32_t qval = _computeCNLs(c, rdcn[i], sd, cnl, gqval, i);
258 if (cnval[i] != c.ploidy) {
259 altqual += qval;
260 ++altcount;
261 }
262 if (gqval[i] < 15) ftarr[i] = "LowQual";
263 else ftarr[i] = "PASS";
264 }
265 if (altcount == 0) continue;
266 altqual /= altcount;
267 if (altqual < c.qual) continue;
268 if (altqual > 10000) altqual = 10000;
269
270 // Update QUAL and FILTER
271 rec->qual = altqual;
272 int32_t tmpi = bcf_hdr_id2int(hdr_out, BCF_DT_ID, "PASS");
273 if (rec->qual < 15) tmpi = bcf_hdr_id2int(hdr_out, BCF_DT_ID, "LowQual");
274 bcf_update_filter(hdr_out, rec, &tmpi, 1);
275
276 // Update GT fields
277 std::vector<const char*> strp(bcf_hdr_nsamples(hdr));
278 std::transform(ftarr.begin(), ftarr.end(), strp.begin(), cstyle_str());
279 bcf_update_format_int32(hdr_out, rec, "CN", cnval, bcf_hdr_nsamples(hdr));
280 bcf_update_format_float(hdr_out, rec, "CNL", cnl, bcf_hdr_nsamples(hdr) * MAX_CN);
281 bcf_update_format_int32(hdr_out, rec, "GQ", gqval, bcf_hdr_nsamples(hdr));
282 bcf_update_format_string(hdr_out, rec, "FT", &strp[0], bcf_hdr_nsamples(hdr));
283 bcf_update_format_float(hdr_out, rec, "RDCN", rdcn, bcf_hdr_nsamples(hdr));
284 }
285 bcf_write1(ofile, hdr_out, rec);
286 }
287 bcf_destroy(rec);
288
289 // Clean-up
290 if (svend != NULL) free(svend);
291 if (svt != NULL) free(svt);
292 if (gqval != NULL) free(gqval);
293 if (cnval != NULL) free(cnval);
294 if (cnl != NULL) free(cnl);
295 if (rdcn != NULL) free(rdcn);
296 if (rdsd != NULL) free(rdsd);
297
298 // Close output VCF
299 bcf_hdr_destroy(hdr_out);
300 hts_close(ofile);
301
302 // Build index
303 if (c.outfile.string() != "-") bcf_index_build(c.outfile.string().c_str(), 14);
304
305 // Close VCF
306 bcf_hdr_destroy(hdr);
307 bcf_close(ifile);
308
309 // End
310 now = boost::posix_time::second_clock::local_time();
311 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] Done." << std::endl;
312
313 return 0;
314 }
315
316
317 int classify(int argc, char **argv) {
318 ClassifyConfig c;
319
320 // Define generic options
321 boost::program_options::options_description generic("Generic options");
322 generic.add_options()
323 ("help,?", "show help message")
324 ("filter,f", boost::program_options::value<std::string>(&c.filter)->default_value("somatic"), "Filter mode (somatic, germline)")
325 ("outfile,o", boost::program_options::value<boost::filesystem::path>(&c.outfile), "Filtered CNV BCF output file")
326 ("minsize,m", boost::program_options::value<int32_t>(&c.minsize)->default_value(1000), "min. CNV size")
327 ("maxsize,n", boost::program_options::value<int32_t>(&c.maxsize)->default_value(500000000), "max. CNV size")
328 ("pass,p", "Filter sites for PASS")
329 ;
330
331 // Define somatic options
332 boost::program_options::options_description somatic("Somatic options");
333 somatic.add_options()
334 ("samples,s", boost::program_options::value<boost::filesystem::path>(&c.samplefile), "Two-column sample file listing sample name and tumor or control")
335 ("pgerm,e", boost::program_options::value<float>(&c.pgerm)->default_value(0.001), "probability germline")
336 ("cn-offset,t", boost::program_options::value<float>(&c.cn_offset)->default_value(0.2), "min. CN offset")
337 ;
338
339 // Define germline options
340 boost::program_options::options_description germline("Germline options");
341 germline.add_options()
342 ("ploidy,y", boost::program_options::value<uint16_t>(&c.ploidy)->default_value(2), "baseline ploidy")
343 ("qual,q", boost::program_options::value<int32_t>(&c.qual)->default_value(50), "min. site quality")
344 ("maxsd,x", boost::program_options::value<float>(&c.maxsd)->default_value(0.15), "max. population SD")
345 ;
346
347 // Define hidden options
348 boost::program_options::options_description hidden("Hidden options");
349 hidden.add_options()
350 ("input-file", boost::program_options::value<boost::filesystem::path>(&c.vcffile), "input file")
351 ;
352 boost::program_options::positional_options_description pos_args;
353 pos_args.add("input-file", -1);
354
355 // Set the visibility
356 boost::program_options::options_description cmdline_options;
357 cmdline_options.add(generic).add(somatic).add(germline).add(hidden);
358 boost::program_options::options_description visible_options;
359 visible_options.add(generic).add(somatic).add(germline);
360 boost::program_options::variables_map vm;
361 boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
362 boost::program_options::notify(vm);
363
364
365 // Check command line arguments
366 if ((vm.count("help")) || (!vm.count("input-file"))) {
367 std::cerr << std::endl;
368 std::cerr << "Usage: delly " << argv[0] << " [OPTIONS] <input.bcf>" << std::endl;
369 std::cerr << visible_options << "\n";
370 return 0;
371 }
372
373 // Filter for PASS
374 if (vm.count("pass")) c.filterForPass = true;
375 else c.filterForPass = false;
376
377 // Check sample file
378 std::set<std::string> tSet;
379 std::set<std::string> cSet;
380 if (c.filter == "somatic") {
381 c.hasSampleFile = true;
382 if (!(boost::filesystem::exists(c.samplefile) && boost::filesystem::is_regular_file(c.samplefile) && boost::filesystem::file_size(c.samplefile))) {
383 std::cerr << "Sample file is missing " << c.samplefile.string() << std::endl;
384 return 1;
385 } else {
386 // Get samples
387 std::ifstream sampleFile(c.samplefile.string().c_str(), std::ifstream::in);
388 if (sampleFile.is_open()) {
389 while (sampleFile.good()) {
390 std::string sampleFromFile;
391 getline(sampleFile, sampleFromFile);
392 typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
393 boost::char_separator<char> sep(",\t ");
394 Tokenizer tokens(sampleFromFile, sep);
395 Tokenizer::iterator tokIter = tokens.begin();
396 if (tokIter != tokens.end()) {
397 std::string sample = *tokIter++;
398 if (tokIter != tokens.end()) {
399 std::string type = *tokIter;
400 if (type == "control") cSet.insert(sample);
401 else if (type == "tumor") tSet.insert(sample);
402 else {
403 std::cerr << "Sample type for " << sample << " is neither tumor nor control" << std::endl;
404 return 1;
405 }
406 }
407 }
408 }
409 sampleFile.close();
410 }
411 if (tSet.empty()) {
412 std::cerr << "No tumor samples specified." << std::endl;
413 return 1;
414 }
415 if (cSet.empty()) {
416 std::cerr << "No control samples specified." << std::endl;
417 return 1;
418 }
419 std::vector<std::string> intersection;
420 std::set_intersection(cSet.begin(), cSet.end(), tSet.begin(), tSet.end(), std::back_inserter(intersection));
421 if (!intersection.empty()) {
422 std::cerr << "Sample " << intersection[0] << " is both a tumor and control sample." << std::endl;
423 return 1;
424 }
425 }
426 } else c.hasSampleFile = false;
427
428 // Check input VCF file
429 if (vm.count("input-file")) {
430 if (!(boost::filesystem::exists(c.vcffile) && boost::filesystem::is_regular_file(c.vcffile) && boost::filesystem::file_size(c.vcffile))) {
431 std::cerr << "Input VCF/BCF file is missing: " << c.vcffile.string() << std::endl;
432 return 1;
433 }
434 htsFile* ifile = bcf_open(c.vcffile.string().c_str(), "r");
435 if (ifile == NULL) {
436 std::cerr << "Fail to open file " << c.vcffile.string() << std::endl;
437 return 1;
438 }
439 hts_idx_t* bcfidx = NULL;
440 tbx_t* tbx = NULL;
441 if (hts_get_format(ifile)->format==vcf) tbx = tbx_index_load(c.vcffile.string().c_str());
442 else bcfidx = bcf_index_load(c.vcffile.string().c_str());
443 if ((bcfidx == NULL) && (tbx == NULL)) {
444 std::cerr << "Fail to open index file for " << c.vcffile.string() << std::endl;
445 return 1;
446 }
447 bcf_hdr_t* hdr = bcf_hdr_read(ifile);
448 if (hdr == NULL) {
449 std::cerr << "Fail to header for " << c.vcffile.string() << std::endl;
450 return 1;
451 }
452 if (!(bcf_hdr_nsamples(hdr)>0)) {
453 std::cerr << "BCF/VCF file has no sample genotypes!" << std::endl;
454 return 1;
455 }
456 // Check sample names
457 if (c.filter == "somatic") {
458 for (int i = 0; i < bcf_hdr_nsamples(hdr); ++i) {
459 if (tSet.find(hdr->samples[i]) != tSet.end()) c.tumorSet.insert(hdr->samples[i]);
460 else if (cSet.find(hdr->samples[i]) != cSet.end()) c.controlSet.insert(hdr->samples[i]);
461 else std::cerr << "Warning: Sample " << hdr->samples[i] << " is missing in sample file." << std::endl;
462 }
463 if (c.tumorSet.empty()) {
464 std::cerr << "No tumor samples specified." << std::endl;
465 return 1;
466 }
467 if (c.controlSet.empty()) {
468 std::cerr << "No control samples specified." << std::endl;
469 return 1;
470 }
471 }
472 bcf_hdr_destroy(hdr);
473 if (bcfidx) hts_idx_destroy(bcfidx);
474 if (tbx) tbx_destroy(tbx);
475 bcf_close(ifile);
476 }
477
478 // Check outfile
479 if (!vm.count("outfile")) c.outfile = "-";
480 else {
481 if (c.outfile.string() != "-") {
482 if (!_outfileValid(c.outfile)) return 1;
483 }
484 }
485
486 // Show cmd
487 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
488 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] ";
489 std::cerr << "delly ";
490 for(int i=0; i<argc; ++i) { std::cerr << argv[i] << ' '; }
491 std::cerr << std::endl;
492
493 return classifyRun(c);
494 }
495
496 }
497
498 #endif