Debian Codegraph @

bcftools/vcfcall.c.pysam.c

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