Debian Codegraph @

bcftools/consensus.c

raw symbols SCIP
1 /* The MIT License
2
3 Copyright (c) 2014-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 */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <strings.h>
31 #include <assert.h>
32 #include <errno.h>
33 #include <getopt.h>
34 #include <unistd.h>
35 #include <ctype.h>
36 #include <htslib/vcf.h>
37 #include <htslib/kstring.h>
38 #include <htslib/synced_bcf_reader.h>
39 #include <htslib/kseq.h>
40 #include <htslib/bgzf.h>
41 #include "regidx.h"
42 #include "bcftools.h"
43 #include "rbuf.h"
44 #include "filter.h"
45 #include "smpl_ilist.h"
46
47 // Logic of the filters: include or exclude sites which match the filters?
48 #define FLT_INCLUDE 1
49 #define FLT_EXCLUDE 2
50
51 #define PICK_REF 1
52 #define PICK_ALT 2
53 #define PICK_LONG 4
54 #define PICK_SHORT 8
55 #define PICK_IUPAC 16
56
57 #define TO_UPPER 1
58 #define TO_LOWER 2
59
60 typedef struct
61 {
62 int num; // number of ungapped blocks in this chain
63 int *block_lengths; // length of the ungapped blocks in this chain
64 int *ref_gaps; // length of the gaps on the reference sequence between blocks
65 int *alt_gaps; // length of the gaps on the alternative sequence between blocks
66 int ori_pos;
67 int ref_last_block_ori; // start position on the reference sequence of the following ungapped block (0-based)
68 int alt_last_block_ori; // start position on the alternative sequence of the following ungapped block (0-based)
69 }
70 chain_t;
71
72 #define MASK_LC 1
73 #define MASK_UC 2
74 #define MASK_SKIP(x) (((x)->with!=MASK_LC && (x)->with!=MASK_UC) ? 1 : 0)
75 typedef struct
76 {
77 char *fname, with;
78 regidx_t *idx;
79 regitr_t *itr;
80 }
81 mask_t;
82
83 typedef struct
84 {
85 kstring_t fa_buf; // buffered reference sequence
86 int fa_ori_pos; // start position of the fa_buffer (wrt original sequence)
87 int fa_frz_pos; // protected position to avoid conflicting variants (last pos for SNPs/ins)
88 int fa_mod_off; // position difference of fa_frz_pos in the ori and modified sequence (ins positive)
89 int fa_frz_mod; // the fa_buf offset of the protected fa_frz_pos position, includes the modified sequence
90 int fa_end_pos; // region's end position in the original sequence
91 int fa_length; // region's length in the original sequence (in case end_pos not provided in the FASTA header)
92 int fa_case; // output upper case or lower case: TO_UPPER|TO_LOWER
93 int fa_src_pos; // last genomic coordinate read from the input fasta (0-based)
94 char prev_base; // this is only to validate the REF allele in the VCF - the modified fa_buf cannot be used for inserts following deletions, see 600#issuecomment-383186778
95 int prev_base_pos; // the position of prev_base
96 int prev_is_insert;
97
98 rbuf_t vcf_rbuf;
99 bcf1_t **vcf_buf;
100 int nvcf_buf, rid;
101 char *chr, *chr_prefix;
102
103 mask_t *mask;
104 int nmask;
105
106 int chain_id; // chain_id, to provide a unique ID to each chain in the chain output
107 chain_t *chain; // chain structure to store the sequence of ungapped blocks between the ref and alt sequences
108 // Note that the chain is re-initialised for each chromosome/seq_region
109
110 filter_t *filter;
111 char *filter_str;
112 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
113
114 bcf_srs_t *files;
115 bcf_hdr_t *hdr;
116 FILE *fp_out;
117 FILE *fp_chain;
118 char **argv;
119 int argc, output_iupac, iupac_GTs, haplotype, allele, isample, napplied;
120 uint8_t *iupac_bitmask, *iupac_als;
121 int miupac_bitmask, miupac_als, regions_overlap;
122 char *fname, *ref_fname, *sample, *sample_fname, *output_fname, *mask_fname, *chain_fname, missing_allele, absent_allele;
123 char mark_del, mark_ins, mark_snv;
124 smpl_ilist_t *smpl;
125 }
126 args_t;
127
128 static void destroy_chain(chain_t *chain)
129 {
130 if ( !chain ) return;
131 free(chain->ref_gaps);
132 free(chain->alt_gaps);
133 free(chain->block_lengths);
134 free(chain);
135 }
136 static chain_t* init_chain(chain_t *chain, int ref_ori_pos)
137 {
138 if ( chain ) destroy_chain(chain);
139 chain = (chain_t*) calloc(1,sizeof(chain_t));
140 chain->num = 0;
141 chain->block_lengths = NULL;
142 chain->ref_gaps = NULL;
143 chain->alt_gaps = NULL;
144 chain->ori_pos = ref_ori_pos;
145 chain->ref_last_block_ori = ref_ori_pos;
146 chain->alt_last_block_ori = ref_ori_pos;
147 return chain;
148 }
149
150 static void print_chain(args_t *args)
151 {
152 /*
153 Example chain format (see: https://genome.ucsc.edu/goldenPath/help/chain.html):
154 chain 1 500 + 480 500 1 501 + 480 501 1
155 12 3 1
156 1 0 3
157 484
158
159 chain line is:
160 - chain
161 - score (sum of the length of ungapped block in this case)
162 - ref_seqname (from the fasta header, parsed by htslib)
163 - ref_seqlength (from the fasta header)
164 - ref_strand (+ or -; always + for bcf-consensus)
165 - ref_start (as defined in the fasta header)
166 - ref_end (as defined in the fasta header)
167 - alt_seqname (same as ref_seqname as bcf-consensus only considers SNPs and indels)
168 - alt_seqlength (adjusted to match the length of the alt sequence)
169 - alt_strand (+ or -; always + for bcf-consensus)
170 - alt_start (same as ref_start, as no edits are recorded/applied before that position)
171 - alt_end (adjusted to match the length of the alt sequence)
172 - chain_num (just an auto-increment id)
173
174 the other (sorted) lines are:
175 - length of the ungapped alignment block
176 - gap on the ref sequence between this and the next block (all but the last line)
177 - gap on the alt sequence between this and the next block (all but the last line)
178 */
179 chain_t *chain = args->chain;
180 int n = chain->num;
181 int ref_end_pos = args->fa_length + chain->ori_pos;
182 int last_block_size = ref_end_pos - chain->ref_last_block_ori;
183 int alt_end_pos = chain->alt_last_block_ori + last_block_size;
184 int score = 0;
185 for (n=0; n<chain->num; n++) {
186 score += chain->block_lengths[n];
187 }
188 score += last_block_size;
189 fprintf(args->fp_chain, "chain %d %s %d + %d %d %s %d + %d %d %d\n", score, args->chr, ref_end_pos, chain->ori_pos, ref_end_pos, args->chr, alt_end_pos, chain->ori_pos, alt_end_pos, ++args->chain_id);
190 for (n=0; n<chain->num; n++) {
191 fprintf(args->fp_chain, "%d %d %d\n", chain->block_lengths[n], chain->ref_gaps[n], chain->alt_gaps[n]);
192 }
193 fprintf(args->fp_chain, "%d\n\n", last_block_size);
194 }
195
196 static void push_chain_gap(chain_t *chain, int ref_start, int ref_len, int alt_start, int alt_len)
197 {
198 // fprintf(stderr, "push_chain_gap(chain=%p, ref_start=%d, ref_len=%d, alt_start=%d, alt_len=%d)\n", chain, ref_start, ref_len, alt_start, alt_len);
199 int num = chain->num;
200
201 if (num && ref_start <= chain->ref_last_block_ori) {
202 // In case this variant is back-to-back with the previous one
203 chain->ref_last_block_ori = ref_start + ref_len;
204 chain->alt_last_block_ori = alt_start + alt_len;
205 chain->ref_gaps[num-1] += ref_len;
206 chain->alt_gaps[num-1] += alt_len;
207
208 } else {
209 // Extend the ungapped blocks, store the gap length
210 chain->block_lengths = (int*) realloc(chain->block_lengths, (num + 1) * sizeof(int));
211 chain->ref_gaps = (int*) realloc(chain->ref_gaps, (num + 1) * sizeof(int));
212 chain->alt_gaps = (int*) realloc(chain->alt_gaps, (num + 1) * sizeof(int));
213 chain->block_lengths[num] = ref_start - chain->ref_last_block_ori;
214 chain->ref_gaps[num] = ref_len;
215 chain->alt_gaps[num] = alt_len;
216 // Update the start positions of the next block
217 chain->ref_last_block_ori = ref_start + ref_len;
218 chain->alt_last_block_ori = alt_start + alt_len;
219 // Increment the number of ungapped blocks
220 chain->num++;
221 }
222 }
223
224 static void init_data(args_t *args)
225 {
226 args->files = bcf_sr_init();
227 args->files->require_index = 1;
228 if ( !bcf_sr_add_reader(args->files,args->fname) ) error("Failed to read from %s: %s\n", !strcmp("-",args->fname)?"standard input":args->fname, bcf_sr_strerror(args->files->errnum));
229 args->hdr = args->files->readers[0].header;
230 args->isample = -1;
231 if ( !args->sample )
232 {
233 args->smpl = smpl_ilist_init(args->hdr,NULL,0,SMPL_NONE|SMPL_VERBOSE);
234 if ( !args->smpl->n )
235 {
236 smpl_ilist_destroy(args->smpl);
237 args->smpl = NULL;
238 }
239 }
240 else if ( args->sample && strcmp("-",args->sample) )
241 {
242 args->smpl = smpl_ilist_init(args->hdr,args->sample,0,SMPL_NONE|SMPL_VERBOSE);
243 if ( args->smpl && !args->smpl->n ) error("No matching sample found\n");
244 }
245 else if ( args->sample_fname )
246 {
247 args->smpl = smpl_ilist_init(args->hdr,args->sample_fname,1,SMPL_NONE|SMPL_VERBOSE);
248 if ( args->smpl && !args->smpl->n ) error("No matching sample found\n");
249 }
250 if ( args->smpl )
251 {
252 if ( args->haplotype || args->allele )
253 {
254 if ( args->smpl->n > 1 ) error("Too many samples, only one can be used with -H; check the -s,-S options\n");
255 args->isample = args->smpl->idx[0];
256 }
257 else
258 {
259 args->iupac_GTs = 1;
260 if ( args->smpl->n==1 )
261 fprintf(stderr,"Note: applying IUPAC codes based on FORMAT/GT in sample %s\n",bcf_hdr_int2id(args->hdr,BCF_DT_SAMPLE,args->smpl->idx[0]));
262 else
263 fprintf(stderr,"Note: applying IUPAC codes based on FORMAT/GT in %d samples\n",args->smpl->n);
264 }
265 }
266 else if ( args->output_iupac )
267 fprintf(stderr,"Note: applying IUPAC codes based on REF,ALT%s\n",bcf_hdr_nsamples(args->hdr)?", ignoring samples":"");
268 else
269 fprintf(stderr,"Note: applying REF,ALT variants%s\n",bcf_hdr_nsamples(args->hdr)?", ignoring samples":"");
270 int i;
271 for (i=0; i<args->nmask; i++)
272 {
273 mask_t *mask = &args->mask[i];
274 mask->idx = regidx_init(mask->fname,NULL,NULL,0,NULL);
275 if ( !mask->idx ) error("Failed to initialize mask regions\n");
276 mask->itr = regitr_init(mask->idx);
277 }
278 // In case we want to store the chains
279 if ( args->chain_fname )
280 {
281 args->fp_chain = fopen(args->chain_fname,"w");
282 if ( ! args->fp_chain ) error("Failed to create %s: %s\n", args->chain_fname, strerror(errno));
283 args->chain_id = 0;
284 }
285 rbuf_init(&args->vcf_rbuf, 100);
286 args->vcf_buf = (bcf1_t**) calloc(args->vcf_rbuf.m, sizeof(bcf1_t*));
287 if ( args->output_fname ) {
288 args->fp_out = fopen(args->output_fname,"w");
289 if ( ! args->fp_out ) error("Failed to create %s: %s\n", args->output_fname, strerror(errno));
290 }
291 else args->fp_out = stdout;
292 if ( args->filter_str )
293 args->filter = filter_init(args->hdr, args->filter_str);
294 args->rid = -1;
295 }
296 static void add_mask(args_t *args, char *fname)
297 {
298 args->nmask++;
299 args->mask = (mask_t*)realloc(args->mask,args->nmask*sizeof(*args->mask));
300 mask_t *mask = &args->mask[args->nmask-1];
301 mask->fname = fname;
302 mask->with = 'N';
303 }
304 static void add_mask_with(args_t *args, char *with)
305 {
306 if ( !args->nmask ) error("The --mask-with option must follow --mask\n");
307 mask_t *mask = &args->mask[args->nmask-1];
308 if ( !strcasecmp(with,"uc") ) mask->with = MASK_UC;
309 else if ( !strcasecmp(with,"lc") ) mask->with = MASK_LC;
310 else if ( strlen(with)!=1 ) error("Expected \"lc\", \"uc\", or a single character with the --mask-with option\n");
311 else mask->with = *with;
312 }
313 static void destroy_data(args_t *args)
314 {
315 free(args->iupac_als);
316 free(args->iupac_bitmask);
317 if (args->filter) filter_destroy(args->filter);
318 if ( args->smpl ) smpl_ilist_destroy(args->smpl);
319 bcf_sr_destroy(args->files);
320 int i;
321 for (i=0; i<args->vcf_rbuf.m; i++)
322 if ( args->vcf_buf[i] ) bcf_destroy1(args->vcf_buf[i]);
323 free(args->vcf_buf);
324 free(args->fa_buf.s);
325 free(args->chr);
326 for (i=0; i<args->nmask; i++)
327 {
328 mask_t *mask = &args->mask[i];
329 regidx_destroy(mask->idx);
330 regitr_destroy(mask->itr);
331 }
332 free(args->mask);
333 if ( args->chain_fname )
334 if ( fclose(args->fp_chain) ) error("Close failed: %s\n", args->chain_fname);
335 if ( fclose(args->fp_out) ) error("Close failed: %s\n", args->output_fname);
336 destroy_chain(args->chain);
337 }
338
339 static void init_region(args_t *args, char *line)
340 {
341 char *ss, *se = line;
342 while ( *se && !isspace(*se) && *se!=':' ) se++;
343 hts_pos_t from = 0, to = 0;
344 char tmp = 0, *tmp_ptr = NULL;
345 if ( *se )
346 {
347 tmp = *se; *se = 0; tmp_ptr = se;
348 ss = ++se;
349 from = strtol(ss,&se,10);
350 if ( ss==se || !*se || *se!='-' ) from = 0;
351 else
352 {
353 from--;
354 ss = ++se;
355 to = strtol(ss,&se,10);
356 if ( ss==se || (*se && !isspace(*se)) ) { from = 0; to = 0; }
357 else to--;
358 }
359 }
360 free(args->chr);
361 args->chr = strdup(line);
362 args->rid = bcf_hdr_name2id(args->hdr,line);
363 if ( args->rid<0 ) fprintf(stderr,"Warning: Sequence \"%s\" not in %s\n", line,args->fname);
364 args->prev_base_pos = -1;
365 args->fa_buf.l = 0;
366 args->fa_length = 0;
367 args->fa_end_pos = to; // 0-based
368 args->fa_ori_pos = from; // 0-based
369 args->fa_src_pos = from; // 0-based
370 args->fa_mod_off = 0;
371 args->fa_frz_pos = -1;
372 args->fa_frz_mod = -1;
373 args->fa_case = -1;
374 args->vcf_rbuf.n = 0;
375
376
377 // bcf_sr_set_regions accepts 1-based coordinates
378 kstring_t str = {0,0,0};
379 if ( !from ) from = 1;
380 else from++;
381 #ifndef MAX_CSI_COOR
382 #define MAX_CSI_COOR ((1LL << (14 + 30)) - 1)
383 #endif
384 if ( to==0 ) to = MAX_CSI_COOR - 1;
385 else to++;
386 ksprintf(&str,"%s:%"PRIhts_pos"-%"PRIhts_pos,line,from,to);
387 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
388 bcf_sr_set_regions(args->files,str.s,0);
389 free(str.s);
390
391 if ( tmp_ptr ) *tmp_ptr = tmp;
392 fprintf(args->fp_out,">%s%s\n",args->chr_prefix?args->chr_prefix:"",line);
393 if ( args->chain_fname )
394 args->chain = init_chain(args->chain, args->fa_ori_pos);
395 }
396
397 static bcf1_t **next_vcf_line(args_t *args)
398 {
399 if ( args->vcf_rbuf.n )
400 {
401 int i = rbuf_shift(&args->vcf_rbuf);
402 return &args->vcf_buf[i];
403 }
404 while ( bcf_sr_next_line(args->files) )
405 {
406 if ( args->filter )
407 {
408 int is_ok = filter_test(args->filter, bcf_sr_get_line(args->files,0), NULL);
409 if ( args->filter_logic & FLT_EXCLUDE ) is_ok = is_ok ? 0 : 1;
410 if ( !is_ok ) continue;
411 }
412 return &args->files->readers[0].buffer[0];
413 }
414 return NULL;
415 }
416 static void unread_vcf_line(args_t *args, bcf1_t **rec_ptr)
417 {
418 bcf1_t *rec = *rec_ptr;
419 if ( args->vcf_rbuf.n >= args->vcf_rbuf.m )
420 error("FIXME: too many overlapping records near %s:%"PRId64"\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
421
422 // Insert the new record in the buffer. The line would be overwritten in
423 // the next bcf_sr_next_line call, therefore we need to swap it with an
424 // unused one
425 int i = rbuf_append(&args->vcf_rbuf);
426 if ( !args->vcf_buf[i] ) args->vcf_buf[i] = bcf_init1();
427 bcf1_t *tmp = rec; *rec_ptr = args->vcf_buf[i]; args->vcf_buf[i] = tmp;
428 }
429 static void flush_fa_buffer(args_t *args, int len)
430 {
431 if ( !args->fa_buf.l ) return;
432 int nwr = 0;
433 while ( nwr + 60 <= args->fa_buf.l )
434 {
435 if ( fwrite(args->fa_buf.s+nwr,1,60,args->fp_out) != 60 ) error("Could not write: %s\n", args->output_fname);
436 if ( fwrite("\n",1,1,args->fp_out) != 1 ) error("Could not write: %s\n", args->output_fname);
437 nwr += 60;
438 }
439 if ( nwr )
440 args->fa_ori_pos += nwr;
441
442 args->fa_frz_mod -= nwr;
443
444 if ( len )
445 {
446 // not finished on this chr yet and the buffer cannot be emptied completely
447 if ( nwr && nwr < args->fa_buf.l )
448 memmove(args->fa_buf.s,args->fa_buf.s+nwr,args->fa_buf.l-nwr);
449 args->fa_buf.l -= nwr;
450 return;
451 }
452
453 // empty the whole buffer
454 if ( nwr == args->fa_buf.l ) { args->fa_buf.l = 0; return; }
455
456 if ( fwrite(args->fa_buf.s+nwr,1,args->fa_buf.l - nwr,args->fp_out) != args->fa_buf.l - nwr ) error("Could not write: %s\n", args->output_fname);
457 if ( fwrite("\n",1,1,args->fp_out) != 1 ) error("Could not write: %s\n", args->output_fname);
458
459 args->fa_ori_pos += args->fa_buf.l - nwr - args->fa_mod_off;
460 args->fa_mod_off = 0;
461 args->fa_buf.l = 0;
462 }
463 static void apply_absent(args_t *args, hts_pos_t pos)
464 {
465 if ( !args->fa_buf.l || pos <= args->fa_frz_pos + 1 || pos <= args->fa_ori_pos ) return;
466
467 int ie = pos && pos - args->fa_ori_pos + args->fa_mod_off < args->fa_buf.l ? pos - args->fa_ori_pos + args->fa_mod_off : args->fa_buf.l;
468 int ib = args->fa_frz_mod < 0 ? 0 : args->fa_frz_mod;
469 int i;
470 for (i=ib; i<ie; i++)
471 args->fa_buf.s[i] = args->absent_allele;
472 }
473 static void freeze_ref(args_t *args, bcf1_t *rec)
474 {
475 if ( args->fa_frz_pos >= rec->pos + rec->rlen - 1 ) return;
476 args->fa_frz_pos = rec->pos + rec->rlen - 1;
477 args->fa_frz_mod = rec->pos - args->fa_ori_pos + args->fa_mod_off + rec->rlen;
478 }
479 static char *mark_del(char *ref, int rlen, char *alt, int mark)
480 {
481 char *out = malloc(rlen+1);
482 int i;
483 if ( alt )
484 {
485 int nalt = strlen(alt);
486 for (i=0; i<nalt; i++) out[i] = alt[i];
487 }
488 else // symbolic <DEL>
489 {
490 int nref = strlen(ref);
491 for (i=0; i<nref; i++) out[i] = ref[i];
492 }
493 for (; i<rlen; i++) out[i] = mark;
494 out[rlen] = 0;
495 return out;
496 }
497 static void mark_ins(char *ref, char *alt, char mark)
498 {
499 int i, nref = strlen(ref), nalt = strlen(alt);
500 if ( mark==TO_LOWER )
501 for (i=nref; i<nalt; i++) alt[i] = tolower(alt[i]);
502 else if ( mark==TO_UPPER )
503 for (i=nref; i<nalt; i++) alt[i] = toupper(alt[i]);
504 else if ( mark )
505 for (i=nref; i<nalt; i++) alt[i] = mark;
506 }
507 static void mark_snv(char *ref, char *alt, char mark)
508 {
509 int i, nref = strlen(ref), nalt = strlen(alt);
510 int n = nref < nalt ? nref : nalt;
511 if ( mark==TO_LOWER )
512 {
513 for (i=0; i<n; i++)
514 if ( tolower(ref[i])!=tolower(alt[i]) ) alt[i] = tolower(alt[i]);
515 }
516 else if ( mark==TO_UPPER)
517 {
518 for (i=0; i<n; i++)
519 if ( tolower(ref[i])!=tolower(alt[i]) ) alt[i] = toupper(alt[i]);
520 }
521 else if ( mark==TO_UPPER)
522 {
523 for (i=0; i<n; i++)
524 if ( tolower(ref[i])!=tolower(alt[i]) ) alt[i] = toupper(alt[i]);
525 }
526 else if ( mark )
527 {
528 for (i=0; i<n; i++)
529 if ( tolower(ref[i])!=tolower(alt[i]) ) alt[i] = mark;
530 }
531 }
532 static void iupac_init(args_t *args, bcf1_t *rec)
533 {
534 int i;
535 hts_resize(uint8_t, rec->n_allele, &args->miupac_als, &args->iupac_als, 0);
536 for (i=0; i<args->miupac_als; i++) args->iupac_als[i] = 0;
537 }
538 static int iupac_add_gt(args_t *args, bcf1_t *rec, uint8_t *gt, int ngt)
539 {
540 int i, is_set = 0;
541 for (i=0; i<ngt; i++)
542 {
543 if ( bcf_gt_is_missing(gt[i]) ) continue;
544 if ( gt[i]==(uint8_t)bcf_int8_vector_end ) break;
545 int ial = bcf_gt_allele(gt[i]);
546 if ( ial >= rec->n_allele ) error("Invalid VCF, too few ALT alleles at %s:%"PRId64"\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
547 args->iupac_als[ial] = 1;
548 is_set = 1;
549 }
550 return is_set;
551 }
552 static int iupac_set_allele(args_t *args, bcf1_t *rec)
553 {
554 int i,j, max_len = 0, alt_len = 0, ialt = -1, fallback_alt = -1;
555 for (i=0; i<rec->n_allele; i++)
556 {
557 if ( !args->iupac_als[i] ) continue;
558 if ( fallback_alt <=0 ) fallback_alt = i;
559 int l = strlen(rec->d.allele[i]);
560 for (j=0; j<l; j++)
561 if ( iupac2bitmask(rec->d.allele[i][j]) < 0 ) break;
562 if ( j<l ) continue; // symbolic allele, breakpoint or invalid character in the allele
563 if ( l>max_len )
564 {
565 hts_resize(uint8_t, l, &args->miupac_bitmask, &args->iupac_bitmask, HTS_RESIZE_CLEAR);
566 for (j=max_len; j<l; j++) args->iupac_bitmask[j] = 0;
567 max_len = l;
568 }
569 if ( i>0 && l>alt_len )
570 {
571 alt_len = l;
572 ialt = i;
573 }
574 for (j=0; j<l; j++)
575 args->iupac_bitmask[j] |= iupac2bitmask(rec->d.allele[i][j]);
576 }
577 if ( alt_len > 0 )
578 {
579 for (j=0; j<alt_len; j++) rec->d.allele[ialt][j] = bitmask2iupac(args->iupac_bitmask[j]);
580 return ialt;
581 }
582 if ( fallback_alt >= 0 ) return fallback_alt;
583 return ialt;
584 }
585 static void apply_variant(args_t *args, bcf1_t *rec)
586 {
587 static int warned_haplotype = 0;
588
589 if ( args->absent_allele ) apply_absent(args, rec->pos);
590 if ( rec->n_allele==1 && !args->missing_allele && !args->absent_allele ) { return; }
591
592 int i,j;
593 if ( args->mask )
594 {
595 char *chr = (char*)bcf_hdr_id2name(args->hdr,args->rid);
596 int start = rec->pos;
597 int end = rec->pos + rec->rlen - 1;
598 for (i=0; i<args->nmask; i++)
599 {
600 mask_t *mask = &args->mask[i];
601 if ( MASK_SKIP(mask) && regidx_overlap(mask->idx, chr,start,end,NULL) ) return;
602 }
603 }
604
605 int ialt = 1; // the alternate allele
606 if ( args->iupac_GTs )
607 {
608 bcf_unpack(rec, BCF_UN_FMT);
609 bcf_fmt_t *fmt = bcf_get_fmt(args->hdr, rec, "GT");
610 if ( !fmt ) return;
611 if ( fmt->type!=BCF_BT_INT8 )
612 error("Todo: GT field represented with BCF_BT_INT8, too many alleles at %s:%"PRId64"?\n",bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
613 ialt = -1;
614 int is_set = 0;
615 iupac_init(args,rec);
616 for (i=0; i<args->smpl->n; i++)
617 {
618 uint8_t *ptr = fmt->p + fmt->size*args->smpl->idx[i];
619 is_set += iupac_add_gt(args, rec, ptr, fmt->n);
620 }
621 if ( !is_set && !args->missing_allele ) return;
622 if ( is_set ) ialt = iupac_set_allele(args, rec);
623 }
624 else if ( args->isample >= 0 )
625 {
626 bcf_unpack(rec, BCF_UN_FMT);
627 bcf_fmt_t *fmt = bcf_get_fmt(args->hdr, rec, "GT");
628 if ( !fmt ) return;
629
630 if ( fmt->type!=BCF_BT_INT8 )
631 error("Todo: GT field represented with BCF_BT_INT8, too many alleles at %s:%"PRId64"?\n",bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
632 uint8_t *ptr = fmt->p + fmt->size*args->isample;
633
634 enum { use_hap, use_iupac, pick_one } action = use_hap;
635 if ( args->allele==PICK_IUPAC )
636 {
637 if ( !args->haplotype ) action = use_iupac;
638 if ( !bcf_gt_is_phased(ptr[0]) && !bcf_gt_is_phased(ptr[fmt->n-1]) ) action = use_iupac;
639 }
640 else if ( args->output_iupac ) action = use_iupac;
641 else if ( !args->haplotype ) action = pick_one;
642
643 if ( action==use_hap )
644 {
645 if ( args->haplotype > fmt->n )
646 {
647 if ( bcf_gt_is_missing(ptr[fmt->n-1]) || bcf_gt_is_missing(ptr[0]) )
648 {
649 if ( !args->missing_allele ) return;
650 ialt = -1;
651 }
652 else
653 {
654 if ( !warned_haplotype )
655 {
656 fprintf(stderr, "Can't apply %d-th haplotype at %s:%"PRId64". (This warning is printed only once.)\n", args->haplotype,bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
657 warned_haplotype = 1;
658 }
659 return;
660 }
661 }
662 else
663 {
664 ialt = (int8_t)ptr[args->haplotype-1];
665 if ( bcf_gt_is_missing(ialt) || ialt==bcf_int8_vector_end )
666 {
667 if ( !args->missing_allele ) return;
668 ialt = -1;
669 }
670 else
671 ialt = bcf_gt_allele(ialt);
672 }
673 }
674 else if ( action==use_iupac )
675 {
676 ialt = -1;
677 iupac_init(args,rec);
678 int is_set = iupac_add_gt(args, rec, ptr, fmt->n);
679 if ( !is_set && !args->missing_allele ) return;
680 if ( is_set ) ialt = iupac_set_allele(args, rec);
681 }
682 else
683 {
684 int is_hom = 1;
685 for (i=0; i<fmt->n; i++)
686 {
687 if ( bcf_gt_is_missing(ptr[i]) )
688 {
689 if ( !args->missing_allele ) return; // ignore missing or half-missing genotypes
690 ialt = -1;
691 break;
692 }
693 if ( ptr[i]==(uint8_t)bcf_int8_vector_end ) break;
694 ialt = bcf_gt_allele(ptr[i]);
695 if ( i>0 && ialt!=bcf_gt_allele(ptr[i-1]) ) { is_hom = 0; break; }
696 }
697 if ( !is_hom )
698 {
699 int prev_len = 0, jalt;
700 for (i=0; i<fmt->n; i++)
701 {
702 if ( ptr[i]==(uint8_t)bcf_int8_vector_end ) break;
703 jalt = bcf_gt_allele(ptr[i]);
704 if ( rec->n_allele <= jalt ) error("Broken VCF, too few alts at %s:%"PRId64"\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
705 if ( args->allele & (PICK_LONG|PICK_SHORT) )
706 {
707 int len = jalt==0 ? rec->rlen : strlen(rec->d.allele[jalt]);
708 if ( i==0 ) ialt = jalt, prev_len = len;
709 else if ( len == prev_len )
710 {
711 if ( args->allele & PICK_REF && jalt==0 ) ialt = jalt, prev_len = len;
712 else if ( args->allele & PICK_ALT && ialt==0 ) ialt = jalt, prev_len = len;
713 }
714 else if ( args->allele & PICK_LONG && len > prev_len ) ialt = jalt, prev_len = len;
715 else if ( args->allele & PICK_SHORT && len < prev_len ) ialt = jalt, prev_len = len;
716 }
717 else
718 {
719 if ( args->allele & PICK_REF && jalt==0 ) ialt = jalt;
720 else if ( args->allele & PICK_ALT && ialt==0 ) ialt = jalt;
721 }
722 }
723 }
724 }
725 if ( !ialt )
726 {
727 // ref allele
728 if ( args->absent_allele ) freeze_ref(args,rec);
729 return;
730 }
731 if ( rec->n_allele <= ialt ) error("Broken VCF, too few alts at %s:%"PRId64"\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
732 }
733 else if ( args->output_iupac && rec->n_allele>1 )
734 {
735 int ialt, alen = 0, mlen = 0;
736 for (i=0; i<rec->n_allele; i++)
737 {
738 int l = strlen(rec->d.allele[i]);
739 for (j=0; j<l; j++)
740 if ( iupac2bitmask(rec->d.allele[i][j]) < 0 ) break;
741 if ( j<l ) continue; // symbolic allele, breakpoint or invalid character in the allele
742
743 if ( l > mlen )
744 {
745 hts_expand(uint8_t,l,args->miupac_bitmask,args->iupac_bitmask);
746 for (j=mlen; j<l; j++) args->iupac_bitmask[j] = 0;
747 mlen = l;
748 }
749 if ( i>0 && l>alen )
750 {
751 alen = l;
752 ialt = i;
753 }
754 for (j=0; j<l; j++)
755 args->iupac_bitmask[j] |= iupac2bitmask(rec->d.allele[i][j]);
756 }
757 if ( alen > 0 )
758 for (j=0; j<alen; j++) rec->d.allele[ialt][j] = bitmask2iupac(args->iupac_bitmask[j]);
759 else
760 ialt = 1;
761 }
762
763 if ( rec->n_allele==1 && ialt!=-1 )
764 {
765 // non-missing reference
766 if ( args->absent_allele ) freeze_ref(args,rec);
767 return;
768 }
769 if ( ialt==-1 )
770 {
771 char alleles[4];
772 alleles[0] = rec->d.allele[0][0];
773 alleles[1] = ',';
774 alleles[2] = args->missing_allele;
775 alleles[3] = 0;
776 bcf_update_alleles_str(args->hdr, rec, alleles);
777 ialt = 1;
778 }
779
780 // For some variant types POS+REF refer to the base *before* the event; in such case set trim_beg
781 int trim_beg = 0;
782 int var_type = bcf_get_variant_type(rec,ialt);
783 int var_len = rec->d.var[ialt].n;
784 if ( var_type & VCF_INDEL )
785 {
786 // normally indel starts one base after, but not if the first base of the fa reference is deleted
787 if ( rec->d.allele[0][0] == rec->d.allele[ialt][0] )
788 trim_beg = 1;
789 else
790 trim_beg = 0;
791 }
792 else if ( (var_type & VCF_OTHER) && !strcasecmp(rec->d.allele[ialt],"<DEL>") )
793 {
794 trim_beg = 1;
795 var_len = 1 - rec->rlen;
796 }
797 else if ( (var_type & VCF_OTHER) && !strncasecmp(rec->d.allele[ialt],"<INS",4) ) trim_beg = 1;
798
799 // Overlapping variant?
800 if ( ialt==0 && rec->pos <= args->fa_frz_pos && rec->pos + rec->rlen - 1 > args->fa_frz_pos )
801 {
802 // Applying the reference allele which overlaps a previous deletion. If we are here, it
803 // means it goes beyond the freezed position, hence the record can be trimmed and moved
804 // forward
805 int ntrim = args->fa_frz_pos - rec->pos + 1;
806 int nref = strlen(rec->d.allele[0]);
807 assert( ntrim < nref );
808 rec->pos += ntrim;
809 rec->rlen -= ntrim;
810 memmove(rec->d.allele[0],rec->d.allele[0]+ntrim,nref-ntrim);
811 rec->d.allele[0][nref-ntrim] = 0;
812 }
813 if ( rec->pos <= args->fa_frz_pos )
814 {
815 // Can be still OK iff this is an insertion (and which does not follow another insertion, see #888).
816 // This still may not be enough for more complicated cases with multiple duplicate positions
817 // and other types in between. In such case let the user normalize the VCF and remove duplicates.
818
819 int overlap = 0;
820 if ( rec->pos < args->fa_frz_pos || !trim_beg || var_len==0 || args->prev_is_insert ) overlap = 1;
821
822 if ( overlap )
823 {
824 fprintf(stderr,"The site %s:%"PRId64" overlaps with another variant, skipping...\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
825 return;
826 }
827 }
828
829 char *ref_allele = rec->d.allele[0];
830 char *alt_allele = rec->d.allele[ialt];
831 int rmme_alt = 0;
832
833 int len_diff = 0, alen = 0;
834 int idx = rec->pos - args->fa_ori_pos + args->fa_mod_off; // position of the variant within the modified fasta sequence
835 if ( idx<0 )
836 {
837 if ( alt_allele[0]=='<' ) // symbolic allele
838 {
839 rec->pos -= idx + 1;
840 rec->rlen += idx + 1;
841 idx = -1;
842 }
843 else if ( strlen(ref_allele) < -idx ) // the ref allele is shorter but overlaps the fa sequence? This should never happen
844 {
845 assert(0);
846 fprintf(stderr,"Warning: ignoring overlapping variant starting at %s:%"PRId64"\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
847 return;
848 }
849 else if ( strlen(alt_allele) > -idx ) // the ref allele overlaps the fa and so does the alt allele
850 {
851 rec->pos -= idx;
852 rec->rlen += idx;
853 ref_allele -= idx;
854 alt_allele -= idx;
855 idx = 0;
856 }
857 else // the ref allele overlaps the fa but alt allele does not: trim to leave one base before
858 {
859 rec->pos -= idx + 1;
860 rec->rlen += idx + 1;
861 ref_allele -= idx + 1;
862 alt_allele += strlen(alt_allele) - 1;
863 idx = -1;
864 }
865 }
866 if ( rec->rlen > args->fa_buf.l - idx )
867 {
868 rec->rlen = args->fa_buf.l - idx;
869 if ( alt_allele[0]!='<' )
870 {
871 alen = strlen(alt_allele);
872 if ( alen > rec->rlen )
873 {
874 fprintf(stderr,"Warning: trimming variant \"%s\" starting at %s:%"PRId64"\n", alt_allele,bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
875 alt_allele[rec->rlen] = 0;
876 }
877 }
878 }
879
880 // the variant is beyond the available fasta sequence
881 if ( idx>0 && idx>=args->fa_buf.l ) return;
882
883 // sanity check the reference base
884 if ( alt_allele[0]=='<' )
885 {
886 // TODO: symbolic deletions probably need more work above with PICK_SHORT|PICK_LONG
887
888 if ( strcasecmp(alt_allele,"<DEL>") && strcasecmp(alt_allele,"<*>") && strcasecmp(alt_allele,"<NON_REF>") )
889 error("Symbolic alleles other than <DEL>, <*> or <NON_REF> are currently not supported, e.g. \"%s\" at %s:%"PRId64".\n"
890 "Please use filtering expressions to exclude such sites, for example by running with: -e 'ALT~\"<.*>\"'\n",
891 alt_allele,bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
892 if ( !strcasecmp(alt_allele,"<DEL>") )
893 {
894 static int multibase_ref_del_warned = 0;
895 if ( ref_allele[1]!=0 && !multibase_ref_del_warned )
896 {
897 fprintf(stderr,
898 "Warning: one REF base is expected with <DEL>, assuming the actual deletion starts at POS+1 at %s:%"PRId64".\n"
899 " (This warning is printed only once.)\n", bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
900 multibase_ref_del_warned = 1;
901 }
902 if ( args->mark_del ) // insert dashes instead of delete sequence
903 {
904 alt_allele = mark_del(ref_allele, rec->rlen, NULL, args->mark_del);
905 alen = rec->rlen;
906 len_diff = 0;
907 rmme_alt = 1;
908 }
909 else
910 {
911 len_diff = 1-rec->rlen;
912 alt_allele = ref_allele; // according to VCF spec, the first REF base must precede the event
913 alen = 1;
914 }
915 }
916 else
917 {
918 // <*> or <NON_REF> .. gVCF, evidence for the reference allele throughout the whole block
919 freeze_ref(args,rec);
920 return;
921 }
922 }
923 else if ( idx>=0 && strncasecmp(ref_allele,args->fa_buf.s+idx,rec->rlen) )
924 {
925 // This is hacky, handle a special case: if SNP or an insert follows a deletion (AAC>A, C>CAA),
926 // the reference base in fa_buf is lost and the check fails. We do not keep a buffer
927 // with the original sequence as it should not be necessary, we should encounter max
928 // one base overlap
929
930 int fail = 1;
931 if ( args->prev_base_pos==rec->pos && toupper(ref_allele[0])==toupper(args->prev_base) )
932 {
933 if ( rec->rlen==1 ) fail = 0;
934 else if ( !strncasecmp(ref_allele+1,args->fa_buf.s+idx+1,rec->rlen-1) ) fail = 0;
935 }
936
937 if ( fail )
938 {
939 char tmp = 0;
940 if ( args->fa_buf.l - idx > rec->rlen )
941 {
942 tmp = args->fa_buf.s[idx+rec->rlen];
943 args->fa_buf.s[idx+rec->rlen] = 0;
944 }
945 error(
946 "The fasta sequence does not match the REF allele at %s:%"PRId64":\n"
947 " REF .vcf: [%s]\n"
948 " ALT .vcf: [%s]\n"
949 " REF .fa : [%s]%c%s\n",
950 bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1, ref_allele, alt_allele, args->fa_buf.s+idx,
951 tmp?tmp:' ',tmp?args->fa_buf.s+idx+rec->rlen+1:""
952 );
953 }
954 alen = strlen(alt_allele);
955 len_diff = alen - rec->rlen;
956
957 if ( args->mark_del && len_diff<0 )
958 {
959 alt_allele = mark_del(ref_allele, rec->rlen, alt_allele, args->mark_del);
960 alen = rec->rlen;
961 len_diff = 0;
962 rmme_alt = 1;
963 }
964 }
965 else
966 {
967 alen = strlen(alt_allele);
968 len_diff = alen - rec->rlen;
969
970 if ( args->mark_del && len_diff<0 )
971 {
972 alt_allele = mark_del(ref_allele, rec->rlen, alt_allele, args->mark_del);
973 alen = rec->rlen;
974 len_diff = 0;
975 rmme_alt = 1;
976 }
977 }
978
979 int safe_idx = idx<0 ? 0 : idx; // idx can be negative in case of overlapping deletion
980 args->fa_case = toupper(args->fa_buf.s[safe_idx])==args->fa_buf.s[safe_idx] ? TO_UPPER : TO_LOWER;
981 if ( args->fa_case==TO_UPPER )
982 for (i=0; i<alen; i++) alt_allele[i] = toupper(alt_allele[i]);
983 else
984 for (i=0; i<alen; i++) alt_allele[i] = tolower(alt_allele[i]);
985
986 if ( args->mark_ins && len_diff>0 )
987 mark_ins(ref_allele, alt_allele, args->mark_ins);
988 if ( args->mark_snv )
989 mark_snv(ref_allele, alt_allele, args->mark_snv);
990
991 if ( len_diff <= 0 )
992 {
993 // deletion or same size event
994 assert( args->fa_buf.l >= idx+rec->rlen );
995 args->prev_base = args->fa_buf.s[idx+rec->rlen-1];
996 args->prev_base_pos = rec->pos + rec->rlen - 1;
997 args->prev_is_insert = 0;
998 args->fa_frz_mod = idx + alen;
999
1000 for (i=trim_beg; i<alen; i++)
1001 args->fa_buf.s[idx+i] = alt_allele[i];
1002
1003 if ( len_diff )
1004 memmove(args->fa_buf.s+idx+alen,args->fa_buf.s+idx+rec->rlen,args->fa_buf.l-idx-rec->rlen);
1005 }
1006 else
1007 {
1008 args->prev_is_insert = 1;
1009 args->prev_base_pos = rec->pos;
1010
1011 // insertion
1012 ks_resize(&args->fa_buf, args->fa_buf.l + len_diff);
1013 memmove(args->fa_buf.s + idx + rec->rlen + len_diff, args->fa_buf.s + idx + rec->rlen, args->fa_buf.l - idx - rec->rlen);
1014
1015 // This can get tricky, make sure the bases unchanged by the insertion do not overwrite preceding variants.
1016 // For example, here we want to get TAA:
1017 // POS REF ALT
1018 // 1 C T
1019 // 1 C CAA
1020 int ibeg = 0;
1021 while ( ibeg<alen && ref_allele[ibeg]==alt_allele[ibeg] && rec->pos + ibeg <= args->prev_base_pos ) ibeg++;
1022 for (i=ibeg; i<alen; i++)
1023 args->fa_buf.s[idx+i] = alt_allele[i];
1024
1025 args->fa_frz_mod = idx + alen - ibeg + 1;
1026 }
1027 if (args->chain && len_diff != 0)
1028 {
1029 // If first nucleotide of both REF and ALT are the same... (indels typically include the nucleotide before the variant)
1030 if ( strncasecmp(ref_allele,alt_allele,1) == 0)
1031 {
1032 // ...extend the block by 1 bp: start is 1 bp further and alleles are 1 bp shorter
1033 push_chain_gap(args->chain, rec->pos + 1, rec->rlen - 1, rec->pos + 1 + args->fa_mod_off, alen - 1);
1034 }
1035 else
1036 {
1037 // otherwise, just the coordinates of the variant as given
1038 push_chain_gap(args->chain, rec->pos, rec->rlen, rec->pos + args->fa_mod_off, alen);
1039 }
1040 }
1041 args->fa_buf.l += len_diff;
1042 args->fa_mod_off += len_diff;
1043 args->fa_frz_pos = rec->pos + rec->rlen - 1;
1044 args->napplied++;
1045 if ( rmme_alt ) free(alt_allele);
1046 }
1047
1048
1049 static void mask_region(args_t *args, char *seq, int len)
1050 {
1051 int start = args->fa_src_pos - len;
1052 int end = args->fa_src_pos;
1053 int i;
1054
1055 for (i=0; i<args->nmask; i++)
1056 {
1057 mask_t *mask = &args->mask[i];
1058 if ( !regidx_overlap(mask->idx, args->chr,start,end, mask->itr) ) continue;
1059
1060 int idx_start, idx_end, j;
1061 while ( regitr_overlap(mask->itr) )
1062 {
1063 idx_start = mask->itr->beg - start;
1064 idx_end = mask->itr->end - start;
1065 if ( idx_start < 0 ) idx_start = 0;
1066 if ( idx_end >= len ) idx_end = len - 1;
1067 if ( mask->with==MASK_UC )
1068 for (j=idx_start; j<=idx_end; j++) seq[j] = toupper(seq[j]);
1069 else if ( mask->with==MASK_LC )
1070 for (j=idx_start; j<=idx_end; j++) seq[j] = tolower(seq[j]);
1071 else
1072 for (j=idx_start; j<=idx_end; j++) seq[j] = mask->with;
1073 }
1074 }
1075 }
1076
1077 static void consensus(args_t *args)
1078 {
1079 BGZF *fasta = bgzf_open(args->ref_fname, "r");
1080 if ( !fasta ) error("Error reading %s\n", args->ref_fname);
1081 kstring_t str = {0,0,0};
1082 while ( bgzf_getline(fasta, '\n', &str) > 0 )
1083 {
1084 if ( str.s[0]=='>' )
1085 {
1086 // new sequence encountered
1087 if ( args->chain ) print_chain(args);
1088
1089 // apply all cached variants and variants that might have been missed because of short fasta (see test/consensus.9.*)
1090 bcf1_t **rec_ptr = NULL;
1091 while ( args->rid>=0 && (rec_ptr = next_vcf_line(args)) )
1092 {
1093 bcf1_t *rec = *rec_ptr;
1094 if ( rec->rid!=args->rid || ( args->fa_end_pos && rec->pos > args->fa_end_pos ) ) break;
1095 apply_variant(args, rec);
1096 }
1097 if ( args->absent_allele )
1098 {
1099 int pos = 0;
1100 if ( args->vcf_rbuf.n && args->vcf_buf[args->vcf_rbuf.f]->rid==args->rid )
1101 pos = args->vcf_buf[args->vcf_rbuf.f]->pos;
1102 apply_absent(args, pos);
1103 }
1104 flush_fa_buffer(args, 0);
1105 init_region(args, str.s+1);
1106 continue;
1107 }
1108 args->fa_length += str.l;
1109 args->fa_src_pos += str.l;
1110
1111 // determine if uppercase or lowercase is used in this fasta file
1112 if ( args->fa_case==-1 ) args->fa_case = toupper(str.s[0])==str.s[0] ? 1 : 0;
1113
1114 if ( args->mask ) mask_region(args, str.s, str.l);
1115 kputs(str.s, &args->fa_buf);
1116
1117 bcf1_t **rec_ptr = NULL;
1118 while ( args->rid>=0 && (rec_ptr = next_vcf_line(args)) )
1119 {
1120 bcf1_t *rec = *rec_ptr;
1121
1122 // still the same chr and the same region? if not, fasta buf can be flushed
1123 if ( rec->rid!=args->rid || ( args->fa_end_pos && rec->pos > args->fa_end_pos ) )
1124 {
1125 // save the vcf record until next time and flush
1126 unread_vcf_line(args, rec_ptr);
1127 rec_ptr = NULL;
1128 break;
1129 }
1130
1131 // is the vcf record well beyond cached fasta buffer? if yes, the buf can be flushed
1132 if ( args->fa_ori_pos + args->fa_buf.l - args->fa_mod_off <= rec->pos )
1133 {
1134 unread_vcf_line(args, rec_ptr);
1135 rec_ptr = NULL;
1136 break;
1137 }
1138
1139 // is the cached fasta buffer full enough? if not, read more fasta, no flushing
1140 if ( args->fa_ori_pos + args->fa_buf.l - args->fa_mod_off < rec->pos + rec->rlen )
1141 {
1142 unread_vcf_line(args, rec_ptr);
1143 break;
1144 }
1145 apply_variant(args, rec);
1146 }
1147 if ( !rec_ptr )
1148 {
1149 if ( args->absent_allele ) apply_absent(args, args->fa_ori_pos - args->fa_mod_off + args->fa_buf.l);
1150 flush_fa_buffer(args, 60);
1151 }
1152 }
1153 bcf1_t **rec_ptr = NULL;
1154 while ( args->rid>=0 && (rec_ptr = next_vcf_line(args)) )
1155 {
1156 bcf1_t *rec = *rec_ptr;
1157 if ( rec->rid!=args->rid ) break;
1158 if ( args->fa_end_pos && rec->pos > args->fa_end_pos ) break;
1159 if ( args->fa_ori_pos + args->fa_buf.l - args->fa_mod_off <= rec->pos ) break;
1160 apply_variant(args, rec);
1161 }
1162 if (args->chain) print_chain(args);
1163 if ( args->absent_allele ) apply_absent(args, HTS_POS_MAX);
1164 flush_fa_buffer(args, 0);
1165 bgzf_close(fasta);
1166 free(str.s);
1167 fprintf(stderr,"Applied %d variants\n", args->napplied);
1168 }
1169
1170 static void usage(args_t *args)
1171 {
1172 fprintf(stderr, "\n");
1173 fprintf(stderr, "About: Create consensus sequence by applying VCF variants to a reference fasta\n");
1174 fprintf(stderr, " file. By default, the program will apply all ALT variants. Using the\n");
1175 fprintf(stderr, " --samples (and, optionally, --haplotype) option will apply genotype\n");
1176 fprintf(stderr, " (or haplotype) calls from FORMAT/GT. The program ignores allelic depth\n");
1177 fprintf(stderr, " information, such as INFO/AD or FORMAT/AD.\n");
1178 fprintf(stderr, "Usage: bcftools consensus [OPTIONS] <file.vcf.gz>\n");
1179 fprintf(stderr, "Options:\n");
1180 fprintf(stderr, " -c, --chain FILE Write a chain file for liftover\n");
1181 fprintf(stderr, " -a, --absent CHAR Replace positions absent from VCF with CHAR\n");
1182 fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n");
1183 fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n");
1184 fprintf(stderr, " -H, --haplotype WHICH Choose which allele to use from the FORMAT/GT field, note\n");
1185 fprintf(stderr, " the codes are case-insensitive:\n");
1186 fprintf(stderr, " N: N={1,2,3,..} is the index of the allele from GT, regardless of phasing (e.g. \"2\")\n");
1187 fprintf(stderr, " R: REF allele in het genotypes\n");
1188 fprintf(stderr, " A: ALT allele\n");
1189 fprintf(stderr, " I: IUPAC code for all genotypes\n");
1190 fprintf(stderr, " LR,LA: longer allele and REF/ALT if equal length\n");
1191 fprintf(stderr, " SR,SA: shorter allele and REF/ALT if equal length\n");
1192 fprintf(stderr, " NpIu: index of the allele for phased and IUPAC code for unphased GTs (e.g. \"2pIu\")\n");
1193 fprintf(stderr, " -i, --include EXPR Select sites for which the expression is true (see man page for details)\n");
1194 fprintf(stderr, " -I, --iupac-codes Output IUPAC codes based on FORMAT/GT, use -s/-S to subset samples\n");
1195 fprintf(stderr, " --mark-del CHAR Instead of removing sequence, insert character CHAR for deletions\n");
1196 fprintf(stderr, " --mark-ins uc|lc|CHAR Highlight insertions in uppercase (uc), lowercase (lc), or use CHAR, leaving the rest as is\n");
1197 fprintf(stderr, " --mark-snv uc|lc|CHAR Highlight substitutions in uppercase (uc), lowercase (lc), or use CHAR, leaving the rest as is\n");
1198 fprintf(stderr, " -m, --mask FILE Replace regions according to the next --mask-with option. The default is --mask-with N\n");
1199 fprintf(stderr, " --mask-with CHAR|uc|lc Replace with CHAR (skips overlapping variants); change to uppercase (uc) or lowercase (lc)\n");
1200 fprintf(stderr, " -M, --missing CHAR Output CHAR instead of skipping a missing genotype \"./.\"\n");
1201 fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n");
1202 fprintf(stderr, " -p, --prefix STRING Prefix to add to output sequence names\n");
1203 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1204 fprintf(stderr, " -s, --samples LIST Comma-separated list of samples to include, \"-\" to ignore samples and use REF,ALT\n");
1205 fprintf(stderr, " -S, --samples-file FILE File of samples to include\n");
1206 fprintf(stderr, "Examples:\n");
1207 fprintf(stderr, " # Get the consensus for one region. The fasta header lines are then expected\n");
1208 fprintf(stderr, " # in the form \">chr:from-to\".\n");
1209 fprintf(stderr, " samtools faidx ref.fa 8:11870-11890 | bcftools consensus in.vcf.gz > out.fa\n");
1210 fprintf(stderr, "\n");
1211 fprintf(stderr, " # See also http://samtools.github.io/bcftools/howtos/consensus-sequence.html\n");
1212 fprintf(stderr, "\n");
1213 exit(1);
1214 }
1215
1216 int main_consensus(int argc, char *argv[])
1217 {
1218 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1219 args->argc = argc; args->argv = argv;
1220 args->regions_overlap = 1;
1221
1222 static struct option loptions[] =
1223 {
1224 {"mark-del",required_argument,NULL,1},
1225 {"mark-ins",required_argument,NULL,2},
1226 {"mark-snv",required_argument,NULL,3},
1227 {"mask-with",1,0,4},
1228 {"exclude",required_argument,NULL,'e'},
1229 {"include",required_argument,NULL,'i'},
1230 {"sample",1,0,'s'},
1231 {"samples",1,0,'s'},
1232 {"samples-file",1,0,'S'},
1233 {"iupac-codes",0,0,'I'},
1234 {"haplotype",1,0,'H'},
1235 {"output",1,0,'o'},
1236 {"fasta-ref",1,0,'f'},
1237 {"mask",1,0,'m'},
1238 {"missing",1,0,'M'},
1239 {"absent",1,0,'a'},
1240 {"chain",1,0,'c'},
1241 {"prefix",required_argument,0,'p'},
1242 {"regions-overlap",required_argument,0,5},
1243 {0,0,0,0}
1244 };
1245 int c;
1246 while ((c = getopt_long(argc, argv, "h?s:S:1Ii:e:H:f:o:m:c:M:p:a:",loptions,NULL)) >= 0)
1247 {
1248 switch (c)
1249 {
1250 case 1 : args->mark_del = optarg[0]; break;
1251 case 2 :
1252 if ( !strcasecmp(optarg,"uc") ) args->mark_ins = TO_UPPER;
1253 else if ( !strcasecmp(optarg,"lc") ) args->mark_ins = TO_LOWER;
1254 else if ( !optarg[1] && optarg[0]>32 && optarg[0]<127 ) args->mark_ins = optarg[0];
1255 else error("The argument is not recognised: --mark-ins %s\n",optarg);
1256 break;
1257 case 3 :
1258 if ( !strcasecmp(optarg,"uc") ) args->mark_snv = TO_UPPER;
1259 else if ( !strcasecmp(optarg,"lc") ) args->mark_snv = TO_LOWER;
1260 else if ( !optarg[1] && optarg[0]>32 && optarg[0]<127 ) args->mark_snv = optarg[0];
1261 else error("The argument is not recognised: --mark-snv %s\n",optarg);
1262 break;
1263 case 5 :
1264 args->regions_overlap = parse_overlap_option(optarg);
1265 if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1266 break;
1267 case 'p': args->chr_prefix = optarg; break;
1268 case 's': args->sample = optarg; break;
1269 case 'S': args->sample_fname = optarg; break;
1270 case 'o': args->output_fname = optarg; break;
1271 case 'I': args->output_iupac = 1; break;
1272 case 'e':
1273 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1274 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
1275 case 'i':
1276 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1277 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
1278 case 'f': args->ref_fname = optarg; break;
1279 case 'm': add_mask(args,optarg); break;
1280 case 4 : add_mask_with(args,optarg); break;
1281 case 'a':
1282 args->absent_allele = optarg[0];
1283 if ( optarg[1]!=0 ) error("Expected single character with -a, got \"%s\"\n", optarg);
1284 break;
1285 case 'M':
1286 args->missing_allele = optarg[0];
1287 if ( optarg[1]!=0 ) error("Expected single character with -M, got \"%s\"\n", optarg);
1288 break;
1289 case 'c': args->chain_fname = optarg; break;
1290 case 'H':
1291 if ( !strcasecmp(optarg,"R") ) args->allele |= PICK_REF;
1292 else if ( !strcasecmp(optarg,"A") ) args->allele |= PICK_ALT;
1293 else if ( !strcasecmp(optarg,"L") ) args->allele |= PICK_LONG|PICK_REF;
1294 else if ( !strcasecmp(optarg,"S") ) args->allele |= PICK_SHORT|PICK_REF;
1295 else if ( !strcasecmp(optarg,"LR") ) args->allele |= PICK_LONG|PICK_REF;
1296 else if ( !strcasecmp(optarg,"LA") ) args->allele |= PICK_LONG|PICK_ALT;
1297 else if ( !strcasecmp(optarg,"SR") ) args->allele |= PICK_SHORT|PICK_REF;
1298 else if ( !strcasecmp(optarg,"SA") ) args->allele |= PICK_SHORT|PICK_ALT;
1299 else if ( !strcasecmp(optarg,"I") ) args->allele |= PICK_IUPAC;
1300 else if ( !strcasecmp(optarg,"1pIu") ) args->allele |= PICK_IUPAC, args->haplotype = 1;
1301 else if ( !strcasecmp(optarg,"2pIu") ) args->allele |= PICK_IUPAC, args->haplotype = 2;
1302 else
1303 {
1304 char *tmp;
1305 args->haplotype = strtol(optarg, &tmp, 10);
1306 if ( tmp==optarg || (*tmp && strcasecmp(tmp,"pIu")) ) error("Error: Could not parse \"--haplotype %s\", expected number of number followed with \"pIu\"\n", optarg);
1307 if ( *tmp ) args->allele |= PICK_IUPAC;
1308 if ( args->haplotype <=0 ) error("Error: Expected positive integer with --haplotype\n");
1309 }
1310 break;
1311 default: usage(args); break;
1312 }
1313 }
1314 if ( optind>=argc ) usage(args);
1315 args->fname = argv[optind];
1316
1317 if ( !args->ref_fname && !isatty(fileno((FILE *)stdin)) ) args->ref_fname = "-";
1318 if ( !args->ref_fname ) usage(args);
1319
1320 init_data(args);
1321 consensus(args);
1322 destroy_data(args);
1323 free(args);
1324
1325 return 0;
1326 }
1327
1328