Debian Codegraph @

bcftools/vcfcall.c

raw symbols SCIP
1 /* vcfcall.c -- SNP/indel variant calling from VCF/BCF.
2
3 Copyright (C) 2013-2024 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE. */
24
25 #include <stdarg.h>
26 #include <string.h>
27 #include <strings.h>
28 #include <assert.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <getopt.h>
32 #include <math.h>
33 #include <htslib/vcf.h>
34 #include <time.h>
35 #include <stdarg.h>
36 #include <htslib/kfunc.h>
37 #include <htslib/synced_bcf_reader.h>
38 #include <htslib/khash_str2int.h>
39 #include <ctype.h>
40 #include "bcftools.h"
41 #include "call.h"
42 #include "prob1.h"
43 #include "ploidy.h"
44 #include "gvcf.h"
45 #include "regidx.h"
46 #include "vcfbuf.h"
47
48 void error(const char *format, ...);
49
50 #define CF_NO_GENO 1
51 #define CF_INS_MISSED (1<<1)
52 #define CF_CCALL (1<<2)
53 // (1<<3)
54 // (1<<4)
55 // (1<<5)
56 #define CF_ACGT_ONLY (1<<6)
57 #define CF_QCALL (1<<7)
58 #define CF_ADJLD (1<<8)
59 #define CF_NO_INDEL (1<<9)
60 #define CF_ANNO_MAX (1<<10)
61 #define CF_MCALL (1<<11)
62 #define CF_PAIRCALL (1<<12)
63 #define CF_QCNT (1<<13)
64 #define CF_INDEL_ONLY (1<<14)
65
66 typedef struct
67 {
68 tgt_als_t *als;
69 int nmatch_als, ibuf;
70 }
71 rec_tgt_t;
72
73 typedef struct
74 {
75 int flag; // combination of CF_* flags above
76 int output_type, n_threads, record_cmd_line, clevel;
77 htsFile *bcf_in, *out_fh;
78 char *bcf_fname, *output_fname;
79 char **samples; // for subsampling and ploidy
80 int nsamples, *samples_map; // mapping from output sample names to original VCF
81 char *regions, *targets; // regions to process
82 int regions_is_file, targets_is_file, regions_overlap;
83 regidx_t *tgt_idx;
84 regitr_t *tgt_itr, *tgt_itr_prev, *tgt_itr_tmp;
85 vcfbuf_t *vcfbuf;
86
87 char *samples_fname;
88 int samples_is_file;
89 int *sample2sex; // mapping for ploidy. If negative, interpreted as -1*ploidy
90 int *sex2ploidy, *sex2ploidy_prev, nsex;
91 ploidy_t *ploidy;
92 gvcf_t *gvcf;
93
94 bcf1_t *missed_line;
95 call_t aux; // parameters and temporary data
96 kstring_t str;
97
98 int argc;
99 char **argv;
100 char *index_fn;
101 int write_index;
102
103 // int flag, prior_type, n1, n_sub, *sublist, n_perm;
104 // uint32_t *trio_aux;
105 // char *prior_file, **subsam;
106 // uint8_t *ploidy;
107 // double theta, pref, indel_frac, min_smpl_frac, min_lrt;
108 // Permutation tests
109 // int n_perm, *seeds;
110 // double min_perm_p;
111 // void *bed;
112 }
113 args_t;
114
115 static char **add_sample(void *name2idx, char **lines, int *nlines, int *mlines, char *name, char sex, int *ith)
116 {
117 int ret = khash_str2int_get(name2idx, name, ith);
118 if ( ret==0 ) return lines;
119
120 hts_expand(char*,(*nlines+1),*mlines,lines);
121 int len = strlen(name);
122 lines[*nlines] = (char*) malloc(len+3);
123 memcpy(lines[*nlines],name,len);
124 lines[*nlines][len] = ' ';
125 lines[*nlines][len+1] = sex;
126 lines[*nlines][len+2] = 0;
127 *ith = *nlines;
128 (*nlines)++;
129 khash_str2int_set(name2idx, strdup(name), *ith);
130 return lines;
131 }
132
133 typedef struct
134 {
135 const char *alias, *about, *ploidy;
136 }
137 ploidy_predef_t;
138
139 static ploidy_predef_t ploidy_predefs[] =
140 {
141 { .alias = "GRCh37",
142 .about = "Human Genome reference assembly GRCh37 / hg19",
143 .ploidy =
144 "X 1 60000 M 1\n"
145 "X 2699521 154931043 M 1\n"
146 "Y 1 59373566 M 1\n"
147 "Y 1 59373566 F 0\n"
148 "MT 1 16569 M 1\n"
149 "MT 1 16569 F 1\n"
150 "chrX 1 60000 M 1\n"
151 "chrX 2699521 154931043 M 1\n"
152 "chrY 1 59373566 M 1\n"
153 "chrY 1 59373566 F 0\n"
154 "chrM 1 16569 M 1\n"
155 "chrM 1 16569 F 1\n"
156 "* * * M 2\n"
157 "* * * F 2\n"
158 },
159 { .alias = "GRCh38",
160 .about = "Human Genome reference assembly GRCh38 / hg38",
161 .ploidy =
162 "X 1 9999 M 1\n"
163 "X 2781480 155701381 M 1\n"
164 "Y 1 57227415 M 1\n"
165 "Y 1 57227415 F 0\n"
166 "MT 1 16569 M 1\n"
167 "MT 1 16569 F 1\n"
168 "chrX 1 9999 M 1\n"
169 "chrX 2781480 155701381 M 1\n"
170 "chrY 1 57227415 M 1\n"
171 "chrY 1 57227415 F 0\n"
172 "chrM 1 16569 M 1\n"
173 "chrM 1 16569 F 1\n"
174 "* * * M 2\n"
175 "* * * F 2\n"
176 },
177 { .alias = "X",
178 .about = "Treat male samples as haploid and female as diploid regardless of the chromosome name",
179 .ploidy =
180 "* * * M 1\n"
181 "* * * F 2\n"
182 },
183 { .alias = "Y",
184 .about = "Treat male samples as haploid and female as no-copy, regardless of the chromosome name",
185 .ploidy =
186 "* * * M 1\n"
187 "* * * F 0\n"
188 },
189 { .alias = "1",
190 .about = "Treat all samples as haploid",
191 .ploidy =
192 "* * * * 1\n"
193 },
194 { .alias = "2",
195 .about = "Treat all samples as diploid",
196 .ploidy =
197 "* * * * 2\n"
198 },
199 {
200 .alias = NULL,
201 .about = NULL,
202 .ploidy = NULL,
203 }
204 };
205
206 // only 5 columns are required and the first is ignored:
207 // ignored,sample,father(or 0),mother(or 0),sex(1=M,2=F)
208 static char **parse_ped_samples(call_t *call, char **vals, int nvals, int *nsmpl)
209 {
210 int i, j, mlines = 0, nlines = 0;
211 kstring_t str = {0,0,0}, fam_str = {0,0,0};
212 void *name2idx = khash_str2int_init();
213 char **lines = NULL;
214 for (i=0; i<nvals; i++)
215 {
216 str.l = 0;
217 kputs(vals[i], &str);
218 char *col_ends[5], *tmp = str.s;
219 j = 0;
220 while ( *tmp && j<5 )
221 {
222 if ( isspace(*tmp) )
223 {
224 *tmp = 0;
225 ++tmp;
226 while ( isspace(*tmp) ) tmp++; // allow multiple spaces
227 col_ends[j] = tmp-1;
228 j++;
229 continue;
230 }
231 tmp++;
232 }
233 if ( j<4 ) break;
234
235 char sex;
236 if ( col_ends[3][1]=='1' ) sex = 'M';
237 else if ( col_ends[3][1]=='2' ) sex = 'F';
238 else break;
239
240 lines = add_sample(name2idx, lines, &nlines, &mlines, col_ends[0]+1, sex, &j);
241 if ( strcmp(col_ends[1]+1,"0") && strcmp(col_ends[2]+1,"0") ) // father and mother
242 {
243 call->nfams++;
244 hts_expand(family_t, call->nfams, call->mfams, call->fams);
245 family_t *fam = &call->fams[call->nfams-1];
246 fam_str.l = 0;
247 ksprintf(&fam_str,"father=%s, mother=%s, child=%s", col_ends[1]+1,col_ends[2]+1,col_ends[0]+1);
248 fam->name = strdup(fam_str.s);
249
250 if ( !khash_str2int_has_key(name2idx, col_ends[1]+1) )
251 lines = add_sample(name2idx, lines, &nlines, &mlines, col_ends[1]+1, 'M', &fam->sample[FATHER]);
252 if ( !khash_str2int_has_key(name2idx, col_ends[2]+1) )
253 lines = add_sample(name2idx, lines, &nlines, &mlines, col_ends[2]+1, 'F', &fam->sample[MOTHER]);
254
255 khash_str2int_get(name2idx, col_ends[0]+1, &fam->sample[CHILD]);
256 khash_str2int_get(name2idx, col_ends[1]+1, &fam->sample[FATHER]);
257 khash_str2int_get(name2idx, col_ends[2]+1, &fam->sample[MOTHER]);
258 }
259 }
260 free(str.s);
261 free(fam_str.s);
262 khash_str2int_destroy_free(name2idx);
263
264 if ( i!=nvals ) return NULL; // not a ped file
265
266 *nsmpl = nlines;
267 return lines;
268 }
269
270
271 /*
272 * Reads sample names and their ploidy (optional) from a file.
273 * Alternatively, if no such file exists, the file name is interpreted
274 * as a comma-separated list of samples. When ploidy is not present,
275 * the default ploidy 2 is assumed.
276 */
277 static void set_samples(args_t *args, const char *fn, int is_file)
278 {
279 int i, nlines;
280 char **lines = hts_readlist(fn, is_file, &nlines);
281 if ( !lines ) error("Could not read the file: %s\n", fn);
282
283 int nsmpls;
284 char **smpls = parse_ped_samples(&args->aux, lines, nlines, &nsmpls);
285 if ( smpls )
286 {
287 for (i=0; i<nlines; i++) free(lines[i]);
288 free(lines);
289 lines = smpls;
290 nlines = nsmpls;
291 }
292 else if ( is_file )
293 fprintf(stderr,"Note: could not parse as PED: %s\n",fn);
294
295 args->samples_map = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr)); // for subsetting
296 args->sample2sex = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr));
297 int dflt_sex_id = ploidy_nsex(args->ploidy) - 1;
298 for (i=0; i<bcf_hdr_nsamples(args->aux.hdr); i++) args->sample2sex[i] = dflt_sex_id;
299
300 int *old2new = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr));
301 for (i=0; i<bcf_hdr_nsamples(args->aux.hdr); i++) old2new[i] = -1;
302
303 int nsmpl = 0, map_needed = 0;
304 for (i=0; i<nlines; i++)
305 {
306 char *ss = lines[i];
307 while ( *ss && isspace(*ss) ) ss++;
308 if ( !*ss ) error("Could not parse: %s\n", lines[i]);
309 if ( *ss=='#' ) continue;
310 char *se = ss;
311 while ( *se && !isspace(*se) ) se++;
312 char x = *se, *xptr = se; *se = 0;
313
314 int ismpl = bcf_hdr_id2int(args->aux.hdr, BCF_DT_SAMPLE, ss);
315 if ( ismpl < 0 ) { fprintf(stderr,"Warning: No such sample in the VCF: %s\n",ss); continue; }
316 if ( old2new[ismpl] != -1 ) { fprintf(stderr,"Warning: The sample is listed multiple times: %s\n",ss); continue; }
317
318 ss = se+(x != '\0');
319 while ( *ss && isspace(*ss) ) ss++;
320 if ( !*ss ) ss = "2"; // default ploidy
321 se = ss;
322 while ( *se && !isspace(*se) ) se++;
323 if ( se==ss ) { *xptr = x; error("Could not parse: \"%s\"\n", lines[i]); }
324
325 if ( ss[1]==0 && (ss[0]=='0' || ss[0]=='1' || ss[0]=='2') )
326 args->sample2sex[nsmpl] = -1*(ss[0]-'0');
327 else
328 args->sample2sex[nsmpl] = ploidy_add_sex(args->ploidy, ss);
329
330 if ( ismpl!=nsmpl ) map_needed = 1;
331 args->samples_map[nsmpl] = ismpl;
332 old2new[ismpl] = nsmpl;
333 nsmpl++;
334 }
335
336 for (i=0; i<args->aux.nfams; i++)
337 {
338 int j, nmiss = 0;
339 family_t *fam = &args->aux.fams[i];
340 for (j=0; j<3; j++)
341 {
342 fam->sample[i] = old2new[fam->sample[i]];
343 if ( fam->sample[i]<0 ) nmiss++;
344 }
345 assert( nmiss==0 || nmiss==3 );
346 }
347 free(old2new);
348
349 if ( !map_needed ) { free(args->samples_map); args->samples_map = NULL; }
350
351 args->nsamples = nsmpl;
352 args->samples = lines;
353 }
354
355 static void init_missed_line(args_t *args)
356 {
357 int i;
358 for (i=0; i<bcf_hdr_nsamples(args->aux.hdr); i++)
359 {
360 args->aux.gts[i*2] = bcf_gt_missing;
361 args->aux.gts[i*2+1] = bcf_int32_vector_end;
362 }
363 args->missed_line = bcf_init1();
364 bcf_update_genotypes(args->aux.hdr, args->missed_line, args->aux.gts, 2*bcf_hdr_nsamples(args->aux.hdr));
365 bcf_float_set_missing(args->missed_line->qual);
366 }
367
368 static int tgt_parse(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr)
369 {
370 char *ss = (char*) line;
371 while ( *ss && isspace(*ss) ) ss++;
372 if ( !*ss ) { fprintf(stderr,"Could not parse the line: %s\n", line); return -2; }
373 if ( *ss=='#' ) return -1; // skip comments
374
375 char *se = ss;
376 while ( *se && !isspace(*se) ) se++;
377
378 *chr_beg = ss;
379 *chr_end = se-1;
380
381 if ( !*se ) { fprintf(stderr,"Could not parse the line: %s\n", line); return -2; }
382
383 ss = se+1;
384 *beg = strtod(ss, &se);
385 if ( ss==se ) { fprintf(stderr,"Could not parse tab line: %s\n", line); return -2; }
386 if ( *beg==0 ) { fprintf(stderr,"Could not parse tab line, expected 1-based coordinate: %s\n", line); return -2; }
387 (*beg)--;
388 *end = *beg;
389
390 if ( !usr ) return 0; // allele information not required
391
392 ss = se+1;
393 tgt_als_t *als = (tgt_als_t*)payload;
394 als->used = 0;
395 als->n = 0;
396 als->allele = NULL;
397 while ( *ss )
398 {
399 se = ss;
400 while ( *se && *se!=',' && !isspace(*se) ) se++;
401 als->n++;
402 als->allele = (char**)realloc(als->allele,als->n*sizeof(*als->allele));
403 als->allele[als->n-1] = (char*)malloc(se-ss+1);
404 memcpy(als->allele[als->n-1],ss,se-ss);
405 als->allele[als->n-1][se-ss] = 0;
406 ss = se+1;
407 if ( !*se || isspace(*se) ) break;
408 }
409 if ( als->n<2 ) error("Unable to parse the -T file; expected CHROM\\tPOS\\tREF,ALT with -C alleles but found instead:\n\t%s\n",line);
410 return 0;
411 }
412 static void tgt_free(void *payload)
413 {
414 tgt_als_t *als = (tgt_als_t*)payload;
415 int i;
416 for (i=0; i<als->n; i++) free(als->allele[i]);
417 free(als->allele);
418 }
419 static void tgt_flush_region(args_t *args, char *chr, uint32_t beg, uint32_t end)
420 {
421 if ( !regidx_overlap(args->tgt_idx, chr,beg,end,args->tgt_itr_tmp) ) return;
422 while ( regitr_overlap(args->tgt_itr_tmp) )
423 {
424 if ( args->tgt_itr_tmp->beg < beg ) continue;
425
426 tgt_als_t *tgt_als = &regitr_payload(args->tgt_itr_tmp,tgt_als_t);
427 if ( tgt_als->used ) continue;
428
429 args->missed_line->rid = bcf_hdr_name2id(args->aux.hdr,chr);
430 args->missed_line->pos = args->tgt_itr_tmp->beg;
431 bcf_unpack(args->missed_line,BCF_UN_ALL);
432 bcf_update_alleles(args->aux.hdr, args->missed_line, (const char**)tgt_als->allele, tgt_als->n);
433 tgt_als->used = 1;
434 if ( bcf_write1(args->out_fh, args->aux.hdr, args->missed_line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname);
435 }
436 }
437 static void tgt_flush(args_t *args, bcf1_t *rec)
438 {
439 if ( rec )
440 {
441 char *chr = (char*)bcf_seqname(args->aux.hdr,rec);
442
443 if ( !args->tgt_itr_prev ) // first record
444 tgt_flush_region(args,chr,0,rec->pos-1);
445
446 else if ( strcmp(chr,args->tgt_itr_prev->seq) ) // first record on a new chromosome
447 {
448 tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg+1,REGIDX_MAX);
449 tgt_flush_region(args,chr,0,rec->pos-1);
450 }
451 else // another record on the same chromosome
452 tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg,rec->pos-1);
453 }
454 else
455 {
456 // flush everything
457 if ( args->tgt_itr_prev )
458 tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg,REGIDX_MAX);
459
460 int i, nchr = 0;
461 char **chr = regidx_seq_names(args->tgt_idx, &nchr);
462 for (i=0; i<nchr; i++)
463 tgt_flush_region(args,chr[i],0,REGIDX_MAX);
464 }
465 }
466 inline static int is_indel(int nals, char **als)
467 {
468 // This is mpileup output, we can make some assumption:
469 // - no MNPs
470 // - "<*>" is not present at indels sites and there are no other symbolic alleles than <*>
471 if ( als[1][0]=='<' ) return 0;
472
473 int i;
474 for (i=0; i<nals; i++)
475 {
476 if ( als[i][0]=='<' ) continue;
477 if ( als[i][1] ) return 1;
478 }
479 return 0;
480 }
481 bcf1_t *next_line(args_t *args)
482 {
483 bcf1_t *rec = NULL;
484 if ( !args->vcfbuf )
485 {
486 while ( bcf_sr_next_line(args->aux.srs) )
487 {
488 rec = args->aux.srs->readers[0].buffer[0];
489 if ( args->aux.srs->errnum || rec->errcode ) error("Error: could not parse the input VCF\n");
490 if ( args->tgt_idx )
491 {
492 if ( !regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec),rec->pos,rec->pos,args->tgt_itr) ) continue;
493
494 // For backward compatibility: require the exact position, not an interval overlap
495 int pos_match = 0;
496 while ( regitr_overlap(args->tgt_itr) )
497 {
498 if ( args->tgt_itr->beg != rec->pos ) continue;
499 pos_match = 1;
500 break;
501 }
502 if ( !pos_match ) continue;
503 }
504 if ( args->samples_map ) bcf_subset(args->aux.hdr, rec, args->nsamples, args->samples_map);
505 bcf_unpack(rec, BCF_UN_STR);
506 return rec;
507 }
508 return NULL;
509 }
510
511 // If we are here,-C alleles was given and vcfbuf and tgt_idx are set
512
513 // Fill the buffer with duplicate lines
514 int vcfbuf_full = 1;
515 int nbuf = vcfbuf_nsites(args->vcfbuf);
516 bcf1_t *rec0 = NULL, *recN = NULL;
517 if ( nbuf==0 ) vcfbuf_full = 0;
518 else if ( nbuf==1 )
519 {
520 vcfbuf_full = 0;
521 rec0 = vcfbuf_peek(args->vcfbuf, 0);
522 }
523 else
524 {
525 rec0 = vcfbuf_peek(args->vcfbuf, 0);
526 recN = vcfbuf_peek(args->vcfbuf, nbuf-1);
527 if ( rec0->rid == recN->rid && rec0->pos == recN->pos ) vcfbuf_full = 0;
528 }
529 if ( !vcfbuf_full )
530 {
531 while ( bcf_sr_next_line(args->aux.srs) )
532 {
533 rec = args->aux.srs->readers[0].buffer[0];
534 if ( args->aux.srs->errnum || rec->errcode ) error("Error: could not parse the input VCF\n");
535 if ( !regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec),rec->pos,rec->pos,args->tgt_itr) ) continue;
536 // as above: require the exact position, not an interval overlap
537 int exact_match = 0;
538 while ( regitr_overlap(args->tgt_itr) )
539 {
540 if ( args->tgt_itr->beg != rec->pos ) continue;
541 exact_match = 1;
542 break;
543 }
544 if ( !exact_match ) continue;
545
546 if ( args->samples_map ) bcf_subset(args->aux.hdr, rec, args->nsamples, args->samples_map);
547 bcf_unpack(rec, BCF_UN_STR);
548 if ( !rec0 ) rec0 = rec;
549 recN = rec;
550 args->aux.srs->readers[0].buffer[0] = vcfbuf_push(args->vcfbuf, rec);
551 if ( rec0->rid!=recN->rid || rec0->pos!=recN->pos ) break;
552 }
553 }
554
555 nbuf = vcfbuf_nsites(args->vcfbuf);
556 int n, i,j;
557 for (n=nbuf; n>1; n--)
558 {
559 recN = vcfbuf_peek(args->vcfbuf, n-1);
560 if ( rec0->rid==recN->rid && rec0->pos==recN->pos ) break;
561 }
562 if ( n==0 )
563 {
564 assert( !nbuf );
565 return NULL;
566 }
567
568 // Find the VCF and tab record with the best matching combination of alleles, prioritize
569 // records of the same type (snp vs indel)
570 rec_tgt_t rec_tgt;
571 memset(&rec_tgt,0,sizeof(rec_tgt));
572 regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec0),rec0->pos,rec0->pos,args->tgt_itr);
573 regitr_t *tmp_itr = regitr_init(args->tgt_idx);
574 for (i=0; i<n; i++)
575 {
576 regitr_copy(tmp_itr, args->tgt_itr);
577 rec = vcfbuf_peek(args->vcfbuf, i);
578 int rec_indel = is_indel(rec->n_allele, rec->d.allele) ? 1 : -1;
579 while ( regitr_overlap(tmp_itr) )
580 {
581 if ( tmp_itr->beg != rec->pos ) continue;
582 tgt_als_t *als = &regitr_payload(tmp_itr,tgt_als_t);
583 if ( als->used ) continue;
584 int nmatch_als = 0;
585 vcmp_t *vcmp = vcmp_init();
586 int ret = vcmp_set_ref(vcmp, rec->d.allele[0], als->allele[0]);
587 if ( ret==0 )
588 {
589 nmatch_als++;
590 if ( rec->n_allele > 1 && als->n > 1 )
591 {
592 for (j=1; j<als->n; j++)
593 {
594 if ( vcmp_find_allele(vcmp, rec->d.allele+1, rec->n_allele-1, als->allele[j])>=0 ) nmatch_als++;
595 }
596 }
597 }
598 int als_indel = is_indel(als->n, als->allele) ? 1 : -1;
599 nmatch_als *= rec_indel*als_indel;
600 if ( nmatch_als > rec_tgt.nmatch_als || !rec_tgt.als )
601 {
602 rec_tgt.nmatch_als = nmatch_als;
603 rec_tgt.als = als;
604 rec_tgt.ibuf = i;
605 }
606 vcmp_destroy(vcmp);
607 }
608 }
609 regitr_destroy(tmp_itr);
610
611 args->aux.tgt_als = rec_tgt.als;
612 if ( rec_tgt.als ) rec_tgt.als->used = 1;
613
614 rec = vcfbuf_remove(args->vcfbuf, rec_tgt.ibuf);
615 return rec;
616 }
617
618 static void init_data(args_t *args)
619 {
620 args->aux.srs = bcf_sr_init();
621
622 // Open files for input and output, initialize structures
623 if ( args->targets )
624 {
625 args->tgt_idx = regidx_init(args->targets, tgt_parse, args->aux.flag&CALL_CONSTR_ALLELES ? tgt_free : (regidx_free_f) NULL, sizeof(tgt_als_t), args->aux.flag&CALL_CONSTR_ALLELES ? args : NULL);
626 args->tgt_itr = regitr_init(args->tgt_idx);
627 args->tgt_itr_tmp = regitr_init(args->tgt_idx);
628 }
629
630 if ( args->regions )
631 {
632 bcf_sr_set_opt(args->aux.srs,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
633 if ( bcf_sr_set_regions(args->aux.srs, args->regions, args->regions_is_file)<0 )
634 error("Failed to read the regions: %s\n", args->regions);
635 }
636
637 if ( !bcf_sr_add_reader(args->aux.srs, args->bcf_fname) )
638 error("Failed to read from %s: %s\n", !strcmp("-",args->bcf_fname)?"standard input":args->bcf_fname,bcf_sr_strerror(args->aux.srs->errnum));
639 args->aux.hdr = bcf_sr_get_header(args->aux.srs,0);
640
641 int i;
642 if ( args->samples_fname )
643 {
644 set_samples(args, args->samples_fname, args->samples_is_file);
645 if ( args->aux.flag&CALL_CONSTR_TRIO )
646 {
647 if ( 3*args->aux.nfams!=args->nsamples ) error("Expected only trios in %s, sorry!\n", args->samples_fname);
648 fprintf(stderr,"Detected %d samples in %d trio families\n", args->nsamples,args->aux.nfams);
649 }
650 }
651 if ( args->ploidy )
652 {
653 args->nsex = ploidy_nsex(args->ploidy);
654 args->sex2ploidy = (int*) calloc(args->nsex,sizeof(int));
655 args->sex2ploidy_prev = (int*) calloc(args->nsex,sizeof(int));
656 if ( !args->nsamples )
657 {
658 args->nsamples = bcf_hdr_nsamples(args->aux.hdr);
659 args->sample2sex = (int*) malloc(sizeof(int)*args->nsamples);
660 for (i=0; i<args->nsamples; i++) args->sample2sex[i] = args->nsex - 1;
661 }
662 }
663 if ( args->nsamples )
664 {
665 args->aux.ploidy = (uint8_t*) malloc(args->nsamples);
666 for (i=0; i<args->nsamples; i++) args->aux.ploidy[i] = ploidy_max(args->ploidy);
667 for (i=0; i<args->nsex; i++) args->sex2ploidy_prev[i] = ploidy_max(args->ploidy);
668 for (i=0; i<args->nsamples; i++)
669 if ( args->sample2sex[i] >= args->nsex ) args->sample2sex[i] = args->nsex - 1;
670 }
671
672 if ( args->gvcf )
673 {
674 int id = bcf_hdr_id2int(args->aux.hdr,BCF_DT_ID,"DP");
675 if ( id<0 || !bcf_hdr_idinfo_exists(args->aux.hdr,BCF_HL_FMT,id) ) error("--gvcf output mode requires FORMAT/DP tag, which is not present in the input header\n");
676 gvcf_update_header(args->gvcf, args->aux.hdr);
677 }
678
679 if ( args->samples_map )
680 {
681 args->aux.hdr = bcf_hdr_subset(bcf_sr_get_header(args->aux.srs,0), args->nsamples, args->samples, args->samples_map);
682 if ( !args->aux.hdr ) error("Error occurred while subsetting samples\n");
683 for (i=0; i<args->nsamples; i++)
684 if ( args->samples_map[i]<0 ) error("No such sample: %s\n", args->samples[i]);
685 if ( !bcf_hdr_nsamples(args->aux.hdr) ) error("No matching sample found\n");
686 }
687 else
688 {
689 args->aux.hdr = bcf_hdr_dup(bcf_sr_get_header(args->aux.srs,0));
690 if ( args->samples )
691 {
692 for (i=0; i<args->nsamples; i++)
693 if ( bcf_hdr_id2int(args->aux.hdr,BCF_DT_SAMPLE,args->samples[i])<0 )
694 error("No such sample: %s\n", args->samples[i]);
695 }
696 }
697
698 if ( args->aux.flag & CALL_CONSTR_ALLELES )
699 {
700 args->vcfbuf = vcfbuf_init(args->aux.hdr, 0);
701 vcfbuf_set(args->vcfbuf,VCFBUF_DUMMY,1);
702 }
703
704 char wmode[8];
705 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
706 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
707 if ( args->out_fh == NULL ) error("Error: cannot write to \"%s\": %s\n", args->output_fname, strerror(errno));
708 if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads);
709
710 if ( args->flag & CF_QCALL )
711 return;
712
713 if ( args->flag & CF_MCALL )
714 mcall_init(&args->aux);
715
716 if ( args->flag & CF_CCALL )
717 ccall_init(&args->aux);
718
719 bcf_hdr_remove(args->aux.hdr, BCF_HL_INFO, "QS");
720 bcf_hdr_remove(args->aux.hdr, BCF_HL_INFO, "I16");
721
722 if (args->record_cmd_line) bcf_hdr_append_version(args->aux.hdr, args->argc, args->argv, "bcftools_call");
723 if ( bcf_hdr_write(args->out_fh, args->aux.hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname);
724 if ( init_index2(args->out_fh,args->aux.hdr,args->output_fname,
725 &args->index_fn, args->write_index)<0 )
726 error("Error: failed to initialise index for %s\n",args->output_fname);
727
728 if ( args->flag&CF_INS_MISSED ) init_missed_line(args);
729 }
730
731 static void destroy_data(args_t *args)
732 {
733 if ( args->vcfbuf ) vcfbuf_destroy(args->vcfbuf);
734 if ( args->tgt_idx )
735 {
736 regidx_destroy(args->tgt_idx);
737 regitr_destroy(args->tgt_itr);
738 regitr_destroy(args->tgt_itr_tmp);
739 if ( args->tgt_itr_prev ) regitr_destroy(args->tgt_itr_prev);
740 }
741 if ( args->flag & CF_CCALL ) ccall_destroy(&args->aux);
742 else if ( args->flag & CF_MCALL ) mcall_destroy(&args->aux);
743 else if ( args->flag & CF_QCALL ) qcall_destroy(&args->aux);
744 int i;
745 if ( args->samples )
746 {
747 for (i=0; i<args->nsamples; i++) free(args->samples[i]);
748 }
749 if ( args->aux.fams )
750 {
751 for (i=0; i<args->aux.nfams; i++) free(args->aux.fams[i].name);
752 free(args->aux.fams);
753 }
754 if ( args->missed_line ) bcf_destroy(args->missed_line);
755 ploidy_destroy(args->ploidy);
756 free(args->sex2ploidy);
757 free(args->sex2ploidy_prev);
758 free(args->samples);
759 free(args->samples_map);
760 free(args->sample2sex);
761 free(args->aux.ploidy);
762 free(args->str.s);
763 if ( args->gvcf ) gvcf_destroy(args->gvcf);
764 bcf_hdr_destroy(args->aux.hdr);
765 if ( args->write_index )
766 {
767 if ( bcf_idx_save(args->out_fh)<0 )
768 {
769 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout");
770 error("Error: cannot write to index %s\n", args->index_fn);
771 }
772 free(args->index_fn);
773 }
774 if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
775 bcf_sr_destroy(args->aux.srs);
776 }
777
778 void parse_novel_rate(args_t *args, const char *str)
779 {
780 if ( sscanf(str,"%le,%le,%le",&args->aux.trio_Pm_SNPs,&args->aux.trio_Pm_del,&args->aux.trio_Pm_ins)==3 ) // explicit for all
781 {
782 args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs;
783 args->aux.trio_Pm_del = 1 - args->aux.trio_Pm_del;
784 args->aux.trio_Pm_ins = 1 - args->aux.trio_Pm_ins;
785 }
786 else if ( sscanf(str,"%le,%le",&args->aux.trio_Pm_SNPs,&args->aux.trio_Pm_del)==2 ) // dynamic for indels
787 {
788 args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs;
789 args->aux.trio_Pm_ins = -1; // negative value for dynamic calculation
790 }
791 else if ( sscanf(str,"%le",&args->aux.trio_Pm_SNPs)==1 ) // same for all
792 {
793 args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs;
794 args->aux.trio_Pm_del = -1;
795 args->aux.trio_Pm_ins = -1;
796 }
797 else error("Could not parse --novel-rate %s\n", str);
798 }
799
800 static void list_annotations(FILE *fp)
801 {
802 fprintf(fp,
803 "\n"
804 "Optional INFO annotations available with -m (\"INFO/\" prefix is optional):\n"
805 " INFO/PV4 .. P-values for strand bias, baseQ bias, mapQ bias and tail distance bias (Number=4,Type=Float)\n"
806 "\n"
807 "Optional FORMAT annotations available with -m (\"FORMAT/\" prefix is optional):\n"
808 " FORMAT/GQ .. Phred-scaled genotype quality (Number=1,Type=Integer)\n"
809 " FORMAT/GP .. Phred-scaled genotype posterior probabilities (Number=G,Type=Float)\n"
810 "\n");
811 }
812
813 static int parse_output_tags(const char *str)
814 {
815 int flag = 0;
816 const char *ss = str;
817 while ( *ss )
818 {
819 const char *se = ss;
820 while ( *se && *se!=',' ) se++;
821 if ( !strncasecmp(ss,"GQ",se-ss) || !strncasecmp(ss,"FORMAT/GQ",se-ss) || !strncasecmp(ss,"FMT/GQ",se-ss) ) flag |= CALL_FMT_GQ;
822 else if ( !strncasecmp(ss,"GP",se-ss) || !strncasecmp(ss,"FORMAT/GP",se-ss) || !strncasecmp(ss,"FMT/GP",se-ss) ) flag |= CALL_FMT_GP;
823 else if ( !strncasecmp(ss,"PV4",se-ss) || !strncasecmp(ss,"INFO/PV4",se-ss) ) flag |= CALL_FMT_PV4;
824 else
825 {
826 fprintf(stderr,"Could not parse \"%s\"\n", str);
827 exit(1);
828 }
829 if ( !*se ) break;
830 ss = se + 1;
831 }
832 return flag;
833 }
834
835 static void set_ploidy(args_t *args, bcf1_t *rec)
836 {
837 ploidy_query(args->ploidy,(char*)bcf_seqname(args->aux.hdr,rec),rec->pos,args->sex2ploidy,NULL,NULL);
838
839 int i;
840 for (i=0; i<args->nsex; i++)
841 if ( args->sex2ploidy[i]!=args->sex2ploidy_prev[i] ) break;
842
843 if ( i==args->nsex ) return; // ploidy same as previously
844
845 for (i=0; i<args->nsamples; i++)
846 {
847 if ( args->sample2sex[i]<0 )
848 args->aux.ploidy[i] = -1*args->sample2sex[i];
849 else
850 args->aux.ploidy[i] = args->sex2ploidy[args->sample2sex[i]];
851 }
852 int *tmp = args->sex2ploidy; args->sex2ploidy = args->sex2ploidy_prev; args->sex2ploidy_prev = tmp;
853 }
854
855 ploidy_t *init_ploidy(char *alias)
856 {
857 const ploidy_predef_t *pld = ploidy_predefs;
858
859 int detailed = 0, len = strlen(alias);
860 if ( alias[len-1]=='?' ) { detailed = 1; alias[len-1] = 0; }
861
862 while ( pld->alias && strcasecmp(alias,pld->alias) ) pld++;
863
864 if ( !pld->alias )
865 {
866 fprintf(stderr,"\nPRE-DEFINED PLOIDY FILES\n\n");
867 fprintf(stderr," * Columns are: CHROM,FROM,TO,SEX,PLOIDY\n");
868 fprintf(stderr," * Coordinates are 1-based inclusive.\n");
869 fprintf(stderr," * A '*' means any value not otherwise defined.\n\n");
870 pld = ploidy_predefs;
871 while ( pld->alias )
872 {
873 fprintf(stderr,"%s\n .. %s\n\n", pld->alias,pld->about);
874 if ( detailed )
875 fprintf(stderr,"%s\n", pld->ploidy);
876 pld++;
877 }
878 fprintf(stderr,"Run as --ploidy <alias> (e.g. --ploidy GRCh37).\n");
879 fprintf(stderr,"To see the detailed ploidy definition, append a question mark (e.g. --ploidy GRCh37?).\n");
880 fprintf(stderr,"\n");
881 exit(-1);
882 }
883 else if ( detailed )
884 {
885 fprintf(stderr,"%s", pld->ploidy);
886 exit(-1);
887 }
888 return ploidy_init_string(pld->ploidy,2);
889 }
890
891 static void usage(args_t *args)
892 {
893 fprintf(stderr, "\n");
894 fprintf(stderr, "About: SNP/indel variant calling from VCF/BCF. To be used in conjunction with bcftools mpileup.\n");
895 fprintf(stderr, " This command replaces the former \"bcftools view\" caller. Some of the original\n");
896 fprintf(stderr, " functionality has been temporarily lost in the process of transition to htslib,\n");
897 fprintf(stderr, " but will be added back on popular demand. The original calling model can be\n");
898 fprintf(stderr, " invoked with the -c option.\n");
899 fprintf(stderr, "Usage: bcftools call [options] <in.vcf.gz>\n");
900 fprintf(stderr, "\n");
901 fprintf(stderr, "File format options:\n");
902 fprintf(stderr, " --no-version Do not append version and command line to the header\n");
903 fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n");
904 fprintf(stderr, " -O, --output-type b|u|z|v Output type: 'b' compressed BCF; 'u' uncompressed BCF; 'z' compressed VCF; 'v' uncompressed VCF [v]\n");
905 fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
906 fprintf(stderr, " --ploidy ASSEMBLY[?] Predefined ploidy, 'list' to print available settings, append '?' for details [2]\n");
907 fprintf(stderr, " --ploidy-file FILE Space/tab-delimited list of CHROM,FROM,TO,SEX,PLOIDY\n");
908 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
909 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
910 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
911 fprintf(stderr, " -s, --samples LIST List of samples to include [all samples]\n");
912 fprintf(stderr, " -S, --samples-file FILE PED file or a file with an optional column with sex (see man page for details) [all samples]\n");
913 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
914 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
915 fprintf(stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
916 fprintf(stderr, "\n");
917 fprintf(stderr, "Input/output options:\n");
918 fprintf(stderr, " -A, --keep-alts Keep all possible alternate alleles at variant sites\n");
919 fprintf(stderr, " -*, --keep-unseen-allele Keep the unobserved allele <*> or <NON_REF>\n");
920 fprintf(stderr, " -a, --annotate LIST Optional tags to output (lowercase allowed); '?' to list available tags\n");
921 fprintf(stderr, " -F, --prior-freqs AN,AC Use prior allele frequencies, determined from these pre-filled tags\n");
922 fprintf(stderr, " -G, --group-samples FILE|- Group samples by population (file with \"sample\\tgroup\") or \"-\" for single-sample calling.\n");
923 fprintf(stderr, " This requires FORMAT/QS or other Number=R,Type=Integer tag such as FORMAT/AD\n");
924 fprintf(stderr, " --group-samples-tag TAG The tag to use with -G, by default FORMAT/QS and FORMAT/AD are checked automatically\n");
925 fprintf(stderr, " -g, --gvcf INT,[...] Group non-variant sites into gVCF blocks by minimum per-sample DP\n");
926 fprintf(stderr, " -i, --insert-missed Output also sites missed by mpileup but present in -T\n");
927 fprintf(stderr, " -M, --keep-masked-ref Keep sites with masked reference allele (REF=N)\n");
928 fprintf(stderr, " -V, --skip-variants TYPE Skip indels/snps\n");
929 fprintf(stderr, " -v, --variants-only Output variant sites only\n");
930 fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
931 fprintf(stderr, "\n");
932 fprintf(stderr, "Consensus/variant calling options:\n");
933 fprintf(stderr, " -c, --consensus-caller The original calling method (conflicts with -m)\n");
934 fprintf(stderr, " -C, --constrain STR One of: alleles, trio (see manual)\n");
935 fprintf(stderr, " -m, --multiallelic-caller Alternative model for multiallelic and rare-variant calling (conflicts with -c)\n");
936 fprintf(stderr, " -n, --novel-rate FLOAT,[...] Likelihood of novel mutation for constrained trio calling, see man page for details [1e-8,1e-9,1e-9]\n");
937 fprintf(stderr, " -p, --pval-threshold FLOAT Variant if P(ref|D)<FLOAT with -c [0.5]\n");
938 fprintf(stderr, " -P, --prior FLOAT Mutation rate (use bigger for greater sensitivity), use with -m [1.1e-3]\n");
939 fprintf(stderr, "\n");
940 fprintf(stderr, "Example:\n");
941 fprintf(stderr, " # See also http://samtools.github.io/bcftools/howtos/variant-calling.html\n");
942 fprintf(stderr, " bcftools mpileup -Ou -f reference.fa alignments.bam | bcftools call -mv -Ob -o calls.bcf\n");
943
944 // todo (and more)
945 // fprintf(stderr, "\nContrast calling and association test options:\n");
946 // fprintf(stderr, " -1 INT number of group-1 samples [0]\n");
947 // fprintf(stderr, " -C FLOAT posterior contrast for LRT<FLOAT and P(ref|D)<0.5 [%g]\n", args->aux.min_lrt);
948 // fprintf(stderr, " -U INT number of permutations for association testing (effective with -1) [0]\n");
949 // fprintf(stderr, " -X FLOAT only perform permutations for P(chi^2)<FLOAT [%g]\n", args->aux.min_perm_p);
950 fprintf(stderr, "\n");
951 exit(-1);
952 }
953
954 int main_vcfcall(int argc, char *argv[])
955 {
956 char *ploidy_fname = NULL, *ploidy = NULL;
957 args_t args;
958 memset(&args, 0, sizeof(args_t));
959 args.argc = argc; args.argv = argv;
960 args.aux.prior_type = -1;
961 args.aux.indel_frac = -1;
962 args.aux.theta = 1.1e-3;
963 args.aux.pref = 0.5;
964 args.aux.min_perm_p = 0.01;
965 args.aux.min_lrt = 1;
966 args.flag = CF_ACGT_ONLY;
967 args.output_fname = "-";
968 args.output_type = FT_VCF;
969 args.n_threads = 0;
970 args.record_cmd_line = 1;
971 args.aux.trio_Pm_SNPs = 1 - 1e-8;
972 args.aux.trio_Pm_ins = args.aux.trio_Pm_del = 1 - 1e-9;
973 args.regions_overlap = 1;
974 args.clevel = -1;
975
976 int c;
977 static struct option loptions[] =
978 {
979 {"help",no_argument,NULL,'h'},
980 {"format-fields",required_argument,NULL,'f'},
981 {"annotate",required_argument,NULL,'a'},
982 {"prior-freqs",required_argument,NULL,'F'},
983 {"gvcf",required_argument,NULL,'g'},
984 {"group-samples",required_argument,NULL,'G'},
985 {"group-samples-tag",required_argument,NULL,3},
986 {"output",required_argument,NULL,'o'},
987 {"output-type",required_argument,NULL,'O'},
988 {"regions",required_argument,NULL,'r'},
989 {"regions-file",required_argument,NULL,'R'},
990 {"regions-overlap",required_argument,NULL,4},
991 {"samples",required_argument,NULL,'s'},
992 {"samples-file",required_argument,NULL,'S'},
993 {"targets",required_argument,NULL,'t'},
994 {"targets-file",required_argument,NULL,'T'},
995 {"threads",required_argument,NULL,9},
996 {"keep-alts",no_argument,NULL,'A'},
997 {"keep-unseen-allele",no_argument,NULL,'*'},
998 {"insert-missed",no_argument,NULL,'i'},
999 {"skip-Ns",no_argument,NULL,'N'}, // now the new default
1000 {"keep-masked-refs",no_argument,NULL,'M'},
1001 {"skip-variants",required_argument,NULL,'V'},
1002 {"variants-only",no_argument,NULL,'v'},
1003 {"consensus-caller",no_argument,NULL,'c'},
1004 {"constrain",required_argument,NULL,'C'},
1005 {"multiallelic-caller",no_argument,NULL,'m'},
1006 {"pval-threshold",required_argument,NULL,'p'},
1007 {"prior",required_argument,NULL,'P'},
1008 {"novel-rate",required_argument,NULL,'n'},
1009 {"ploidy",required_argument,NULL,1},
1010 {"ploidy-file",required_argument,NULL,2},
1011 {"chromosome-X",no_argument,NULL,'X'},
1012 {"chromosome-Y",no_argument,NULL,'Y'},
1013 {"no-version",no_argument,NULL,8},
1014 {"write-index",optional_argument,NULL,'W'},
1015 {NULL,0,NULL,0}
1016 };
1017
1018 char *tmp = NULL;
1019 while ((c = getopt_long(argc, argv, "h?o:O:r:R:s:S:t:T:A*NMV:vcmp:C:n:P:f:a:ig:XYF:G:W::", loptions, NULL)) >= 0)
1020 {
1021 switch (c)
1022 {
1023 case 2 : ploidy_fname = optarg; break;
1024 case 1 : ploidy = optarg; break;
1025 case 'X': ploidy = "X"; fprintf(stderr,"Warning: -X will be deprecated, please use --ploidy instead.\n"); break;
1026 case 'Y': ploidy = "Y"; fprintf(stderr,"Warning: -Y will be deprecated, please use --ploidy instead.\n"); break;
1027 case 'G': args.aux.sample_groups = optarg; break;
1028 case 3 : args.aux.sample_groups_tag = optarg; break;
1029 case 'f': fprintf(stderr,"Warning: -f, --format-fields will be deprecated, please use -a, --annotate instead.\n");
1030 case 'a':
1031 if (optarg[0]=='?') { list_annotations(stderr); return 1; }
1032 args.aux.output_tags |= parse_output_tags(optarg);
1033 break;
1034 case 'M': args.flag &= ~CF_ACGT_ONLY; break; // keep sites where REF is N
1035 case 'N': args.flag |= CF_ACGT_ONLY; break; // omit sites where first base in REF is N (the new default)
1036 case 'A': args.aux.flag |= CALL_KEEPALT; break;
1037 case '*': args.aux.flag |= CALL_KEEP_UNSEEN; break;
1038 case 'c': args.flag |= CF_CCALL; break; // the original EM based calling method
1039 case 'i': args.flag |= CF_INS_MISSED; break;
1040 case 'v': args.aux.flag |= CALL_VARONLY; break;
1041 case 'F':
1042 args.aux.prior_AN = optarg;
1043 args.aux.prior_AC = strchr(optarg,',');
1044 if ( !args.aux.prior_AC ) error("Expected two tags with -F (e.g. AN,AC), got \"%s\"\n",optarg);
1045 *args.aux.prior_AC = 0;
1046 args.aux.prior_AC++;
1047 break;
1048 case 'g':
1049 args.gvcf = gvcf_init(optarg);
1050 if ( !args.gvcf ) error("Could not parse: --gvcf %s\n", optarg);
1051 break;
1052 case 'o': args.output_fname = optarg; break;
1053 case 'O':
1054 switch (optarg[0]) {
1055 case 'b': args.output_type = FT_BCF_GZ; break;
1056 case 'u': args.output_type = FT_BCF; break;
1057 case 'z': args.output_type = FT_VCF_GZ; break;
1058 case 'v': args.output_type = FT_VCF; break;
1059 default:
1060 {
1061 args.clevel = strtol(optarg,&tmp,10);
1062 if ( *tmp || args.clevel<0 || args.clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1063 }
1064 }
1065 if ( optarg[1] )
1066 {
1067 args.clevel = strtol(optarg+1,&tmp,10);
1068 if ( *tmp || args.clevel<0 || args.clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
1069 }
1070 break;
1071 case 'C':
1072 if ( !strcasecmp(optarg,"alleles") ) args.aux.flag |= CALL_CONSTR_ALLELES;
1073 else if ( !strcasecmp(optarg,"trio") ) args.aux.flag |= CALL_CONSTR_TRIO;
1074 else error("Unknown argument to -C: \"%s\"\n", optarg);
1075 break;
1076 case 'V':
1077 if ( !strcasecmp(optarg,"snps") ) args.flag |= CF_INDEL_ONLY;
1078 else if ( !strcasecmp(optarg,"indels") ) args.flag |= CF_NO_INDEL;
1079 else error("Unknown skip category \"%s\" (-S argument must be \"snps\" or \"indels\")\n", optarg);
1080 break;
1081 case 'm': args.flag |= CF_MCALL; break; // multiallelic calling method
1082 case 'p':
1083 args.aux.pref = strtod(optarg,&tmp);
1084 if ( *tmp ) error("Could not parse: --pval-threshold %s\n", optarg);
1085 break;
1086 case 'P': args.aux.theta = strtod(optarg,&tmp);
1087 if ( *tmp ) error("Could not parse, expected float argument: -P %s\n", optarg);
1088 break;
1089 case 'n': parse_novel_rate(&args,optarg); break;
1090 case 'r': args.regions = optarg; break;
1091 case 'R': args.regions = optarg; args.regions_is_file = 1; break;
1092 case 't': args.targets = optarg; break;
1093 case 'T': args.targets = optarg; args.targets_is_file = 1; break;
1094 case 's': args.samples_fname = optarg; break;
1095 case 'S': args.samples_fname = optarg; args.samples_is_file = 1; break;
1096 case 9 : args.n_threads = strtol(optarg, 0, 0); break;
1097 case 8 : args.record_cmd_line = 0; break;
1098 case 4 :
1099 args.regions_overlap = parse_overlap_option(optarg);
1100 if ( args.regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1101 break;
1102 case 'W':
1103 if (!(args.write_index = write_index_parse(optarg)))
1104 error("Unsupported index format '%s'\n", optarg);
1105 break;
1106 default: usage(&args);
1107 }
1108 }
1109 // Sanity check options and initialize
1110 if ( ploidy_fname ) args.ploidy = ploidy_init(ploidy_fname, 2);
1111 else if ( ploidy ) args.ploidy = init_ploidy(ploidy);
1112
1113 if ( optind>=argc )
1114 {
1115 if ( !isatty(fileno((FILE *)stdin)) ) args.bcf_fname = "-"; // reading from stdin
1116 else usage(&args);
1117 }
1118 else args.bcf_fname = argv[optind++];
1119
1120 if ( !ploidy_fname && !ploidy )
1121 {
1122 if ( !args.samples_is_file ) fprintf(stderr,"Note: none of --samples-file, --ploidy or --ploidy-file given, assuming all sites are diploid\n");
1123 args.ploidy = ploidy_init_string("* * * 0 0\n* * * 1 1\n* * * 2 2\n",2);
1124 }
1125
1126 if ( !args.ploidy ) error("Could not initialize ploidy\n");
1127 if ( (args.flag & CF_CCALL ? 1 : 0) + (args.flag & CF_MCALL ? 1 : 0) + (args.flag & CF_QCALL ? 1 : 0) > 1 ) error("Only one of -c or -m options can be given\n");
1128 if ( !(args.flag & CF_CCALL) && !(args.flag & CF_MCALL) && !(args.flag & CF_QCALL) ) error("Expected -c or -m option\n");
1129 if ( (args.flag & CF_CCALL ? 1: 0) && args.gvcf ) error("gvcf -g option not functional with -c calling mode yet\n");
1130 if ( args.aux.n_perm && args.aux.ngrp1_samples<=0 ) error("Expected -1 with -U\n"); // not sure about this, please fix
1131 if ( args.aux.flag & CALL_CONSTR_ALLELES )
1132 {
1133 if ( !args.targets ) error("Expected -t or -T with \"-C alleles\"\n");
1134 if ( !(args.flag & CF_MCALL) ) error("The \"-C alleles\" mode requires -m\n");
1135 }
1136 if ( args.flag & CF_INS_MISSED && !(args.aux.flag&CALL_CONSTR_ALLELES) ) error("The -i option requires -C alleles\n");
1137 if ( args.aux.flag&CALL_VARONLY && args.gvcf ) error("The two options cannot be combined: --variants-only and --gvcf\n");
1138 if ( args.aux.sample_groups && !(args.flag & CF_MCALL) ) error("The -G feature is supported only with the -m calling mode\n");
1139 init_data(&args);
1140
1141 bcf1_t *bcf_rec;
1142 while ( (bcf_rec = next_line(&args)) )
1143 {
1144 // Skip duplicate positions with all matching `-C alleles -T` used up
1145 if ( args.aux.flag&CALL_CONSTR_ALLELES && !args.aux.tgt_als ) continue;
1146
1147 // Skip unwanted sites
1148 int i, is_indel = bcf_is_snp(bcf_rec) ? 0 : 1;
1149 if ( (args.flag & CF_INDEL_ONLY) && !is_indel ) continue;
1150 if ( (args.flag & CF_NO_INDEL) && is_indel ) continue;
1151 if ( (args.flag & CF_ACGT_ONLY) && (bcf_rec->d.allele[0][0]=='N' || bcf_rec->d.allele[0][0]=='n') ) continue; // REF[0] is 'N'
1152
1153 // Which allele is symbolic? All SNPs should have it, but not indels
1154 args.aux.unseen = 0;
1155 for (i=1; i<bcf_rec->n_allele; i++)
1156 {
1157 if ( bcf_rec->d.allele[i][0]=='X' ) { args.aux.unseen = i; break; } // old X
1158 if ( bcf_rec->d.allele[i][0]=='<' )
1159 {
1160 if ( bcf_rec->d.allele[i][1]=='X' && bcf_rec->d.allele[i][2]=='>' ) { args.aux.unseen = i; break; } // old <X>
1161 if ( bcf_rec->d.allele[i][1]=='*' && bcf_rec->d.allele[i][2]=='>' ) { args.aux.unseen = i; break; } // new <*>
1162 }
1163 }
1164 int is_ref = (bcf_rec->n_allele==1 || (bcf_rec->n_allele==2 && args.aux.unseen>0)) ? 1 : 0;
1165
1166 if ( is_ref && args.aux.flag&CALL_VARONLY )
1167 continue;
1168
1169 bcf_unpack(bcf_rec, BCF_UN_ALL);
1170 if ( args.nsex ) set_ploidy(&args, bcf_rec);
1171
1172 // Various output modes: QCall output (todo)
1173 if ( args.flag & CF_QCALL )
1174 {
1175 qcall(&args.aux, bcf_rec);
1176 continue;
1177 }
1178
1179 if ( args.flag & CF_INS_MISSED )
1180 {
1181 tgt_flush(&args,bcf_rec);
1182 if ( !args.tgt_itr_prev ) args.tgt_itr_prev = regitr_init(args.tgt_idx);
1183 regitr_copy(args.tgt_itr_prev, args.tgt_itr);
1184 }
1185
1186 // Calling modes which output VCFs
1187 int ret;
1188 if ( args.flag & CF_MCALL )
1189 ret = mcall(&args.aux, bcf_rec);
1190 else
1191 ret = ccall(&args.aux, bcf_rec);
1192 if ( ret==-1 ) error("Something is wrong\n");
1193 else if ( ret==-2 ) continue; // skip the site
1194
1195 // Normal output
1196 if ( (args.aux.flag & CALL_VARONLY) && ret==0 && !args.gvcf ) continue; // not a variant
1197 if ( args.gvcf )
1198 bcf_rec = gvcf_write(args.gvcf, args.out_fh, args.aux.hdr, bcf_rec, ret==1?1:0);
1199 if ( bcf_rec && bcf_write1(args.out_fh, args.aux.hdr, bcf_rec)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args.output_fname);
1200 }
1201 if ( args.gvcf ) gvcf_write(args.gvcf, args.out_fh, args.aux.hdr, NULL, 0);
1202 if ( args.flag & CF_INS_MISSED ) tgt_flush(&args,NULL);
1203 destroy_data(&args);
1204 return 0;
1205 }
1206