Debian Codegraph @

bcftools/consensus.c.pysam.c

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