Debian Codegraph @

bcftools/vcfnorm.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfnorm.c -- Left-align and normalize indels.
4
5 Copyright (C) 2013-2024 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include <stdio.h>
28 #include <strings.h>
29 #include <unistd.h>
30 #include <getopt.h>
31 #include <assert.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <inttypes.h>
38 #include <htslib/vcf.h>
39 #include <htslib/synced_bcf_reader.h>
40 #include <htslib/faidx.h>
41 #include <htslib/khash_str2int.h>
42 #include "bcftools.h"
43 #include "rbuf.h"
44 #include "abuf.h"
45 #include "gff.h"
46 #include "regidx.h"
47 #include "filter.h"
48
49 #define CHECK_REF_EXIT 1
50 #define CHECK_REF_WARN 2
51 #define CHECK_REF_SKIP 4
52 #define CHECK_REF_FIX 8
53
54 #define MROWS_SPLIT 1
55 #define MROWS_MERGE 2
56
57 // Logic of the filters: include or exclude sites which match the filters?
58 #define FLT_INCLUDE 1
59 #define FLT_EXCLUDE 2
60
61 // for -m+, mapping from allele indexes of a single input record
62 // to allele indexes of output record
63 typedef struct
64 {
65 int nals, mals, *map;
66 }
67 map_t;
68
69 // primitive comparison of two records' alleles via hashes; normalized alleles assumed
70 typedef struct
71 {
72 int n; // number of alleles
73 char *ref, *alt;
74 void *hash; // str2int hash
75 }
76 cmpals1_t;
77
78 typedef struct
79 {
80 cmpals1_t *cmpals;
81 int ncmpals, mcmpals;
82 }
83 cmpals_t;
84
85 typedef struct
86 {
87 char *tseq, *seq;
88 int mseq;
89 bcf1_t **lines, **tmp_lines, **mrows, *mrow_out;
90 int ntmp_lines, mtmp_lines, nmrows, mmrows, mrows_first;
91 map_t *maps; // mrow map for each buffered record
92 char **als;
93 int mmaps, nals, mals;
94 uint8_t *tmp_arr1, *tmp_arr2, *diploid;
95 int32_t *int32_arr;
96 int ntmp_arr1, ntmp_arr2, nint32_arr;
97 kstring_t *tmp_str;
98 kstring_t *tmp_als, *tmp_sym, tmp_kstr;
99 int ntmp_als, ntmp_sym;
100 rbuf_t rbuf;
101 int buf_win; // maximum distance between two records to consider
102 int aln_win; // the realignment window size (maximum repeat size)
103 bcf_srs_t *files; // using the synced reader only for -r option
104 bcf_hdr_t *hdr, *out_hdr;
105 cmpals_t cmpals_in, cmpals_out;
106 faidx_t *fai;
107 struct { int tot, set, swap; } nref;
108 char **argv, *output_fname, *ref_fname, *vcf_fname, *region, *targets;
109 int argc, rmdup, output_type, n_threads, check_ref, strict_filter, do_indels, clevel;
110 int nchanged, nskipped, nsplit, njoined, ntotal, nfilter, mrows_op, mrows_collapse, parsimonious;
111 int record_cmd_line, force, force_warned, keep_sum_ad;
112 abuf_t *abuf;
113 abuf_opt_t atomize;
114 int use_star_allele, ma_use_ref_allele;
115 char *old_rec_tag;
116 htsFile *out;
117 char *index_fn;
118 int write_index, gff_verbosity;
119 int right_align;
120 char *gff_fname;
121 gff_t *gff;
122 regidx_t *idx_tscript;
123 regitr_t *itr_tscript;
124 int (*cmp_func)(const void *aptr, const void *bptr);
125 char *filter_str;
126 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
127 int filter_pass;
128 filter_t *filter;
129 }
130 args_t;
131
132 static inline int replace_iupac_codes(char *seq, int nseq)
133 {
134 // Replace ambiguity codes with N for now, it awaits to be seen what the VCF spec codifies in the end
135 int i, n = 0;
136 for (i=0; i<nseq; i++)
137 {
138 char c = toupper(seq[i]);
139 if ( c!='A' && c!='C' && c!='G' && c!='T' && c!='N' ) { seq[i] = 'N'; n++; }
140 }
141 return n;
142 }
143 static inline int has_non_acgtn(char *seq, int nseq)
144 {
145 char *end = seq + nseq;
146 while ( *seq && seq<end )
147 {
148 char c = toupper(*seq);
149 if ( c!='A' && c!='C' && c!='G' && c!='T' && c!='N' ) return 1;
150 seq++;
151 }
152 return 0;
153 }
154
155 static void seq_to_upper(char *seq, int len)
156 {
157 int i;
158 if ( len )
159 for (i=0; i<len; i++) seq[i] = nt_to_upper(seq[i]);
160 else
161 for (i=0; seq[i]; i++) seq[i] = nt_to_upper(seq[i]);
162 }
163
164 static void fix_ref(args_t *args, bcf1_t *line)
165 {
166 bcf_unpack(line, BCF_UN_STR);
167 int reflen = strlen(line->d.allele[0]);
168 int i,j, maxlen = reflen, len;
169 for (i=1; i<line->n_allele; i++)
170 {
171 int len = strlen(line->d.allele[i]);
172 if ( maxlen < len ) maxlen = len;
173 }
174
175 char *ref = faidx_fetch_seq(args->fai, (char*)bcf_seqname(args->hdr,line), line->pos, line->pos+maxlen-1, &len);
176 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
177 replace_iupac_codes(ref,len);
178
179 args->nref.tot++;
180
181 // is the REF different? If not, we are done
182 if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
183
184 // is the REF allele missing?
185 if ( reflen==1 && line->d.allele[0][0]=='.' )
186 {
187 line->d.allele[0][0] = ref[0];
188 args->nref.set++;
189 free(ref);
190 bcf_update_alleles(args->out_hdr,line,(const char**)line->d.allele,line->n_allele);
191 return;
192 }
193
194 // does REF or ALT contain non-standard bases?
195 int has_non_acgtn = 0;
196 for (i=0; i<line->n_allele; i++)
197 {
198 if ( line->d.allele[i][0]=='<' ) continue;
199 has_non_acgtn += replace_iupac_codes(line->d.allele[i],strlen(line->d.allele[i]));
200 }
201 if ( has_non_acgtn )
202 {
203 args->nref.set++;
204 bcf_update_alleles(args->out_hdr,line,(const char**)line->d.allele,line->n_allele);
205 if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
206 }
207
208 // does the REF allele contain N's ?
209 int fix = 0;
210 for (i=0; i<reflen; i++)
211 {
212 if ( line->d.allele[0][i]!='N' ) continue;
213 if ( ref[i]=='N' ) continue;
214 line->d.allele[0][i] = ref[i];
215 fix++;
216 for (j=1; j<line->n_allele; j++)
217 {
218 int len = strlen(line->d.allele[j]);
219 if ( len <= i || line->d.allele[j][i]!='N' ) continue;
220 line->d.allele[j][i] = ref[i];
221 fix++;
222 }
223 }
224 if ( fix )
225 {
226 args->nref.set++;
227 bcf_update_alleles(args->out_hdr,line,(const char**)line->d.allele,line->n_allele);
228 if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
229 }
230
231
232 // is it swapped?
233 for (i=1; i<line->n_allele; i++)
234 {
235 int len = strlen(line->d.allele[i]);
236 if ( !strncasecmp(line->d.allele[i],ref,len) ) break;
237 }
238
239 kstring_t str = {0,0,0};
240 if ( i==line->n_allele ) // none of the alternate alleles matches the reference
241 {
242 args->nref.set++;
243 kputsn(ref,reflen,&str);
244 for (i=1; i<line->n_allele; i++)
245 {
246 kputc(',',&str);
247 kputs(line->d.allele[i],&str);
248 }
249 bcf_update_alleles_str(args->out_hdr,line,str.s);
250 free(ref);
251 free(str.s);
252 return;
253 }
254
255 // one of the alternate alleles matches the reference, assume it's a simple swap
256 kputs(line->d.allele[i],&str);
257 for (j=1; j<line->n_allele; j++)
258 {
259 kputc(',',&str);
260 if ( j==i )
261 kputs(line->d.allele[0],&str);
262 else
263 kputs(line->d.allele[j],&str);
264 }
265 bcf_update_alleles_str(args->out_hdr,line,str.s);
266 args->nref.swap++;
267 free(ref);
268 free(str.s);
269
270 // swap genotypes
271 int ntmp = args->ntmp_arr1 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
272 int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr1, &ntmp);
273 args->ntmp_arr1 = ntmp * sizeof(int32_t);
274 int32_t *gts = (int32_t*) args->tmp_arr1;
275 int ni = 0;
276 for (j=0; j<ngts; j++)
277 {
278 if ( gts[j]==bcf_gt_unphased(0) ) { gts[j] = bcf_gt_unphased(i); ni++; }
279 else if ( gts[j]==bcf_gt_phased(0) ) { gts[j] = bcf_gt_phased(i); ni++; }
280 else if ( gts[j]==bcf_gt_unphased(i) ) gts[j] = bcf_gt_unphased(0);
281 else if ( gts[j]==bcf_gt_phased(i) ) gts[j] = bcf_gt_phased(0);
282 }
283 bcf_update_genotypes(args->out_hdr,line,gts,ngts);
284
285 // update AC
286 int nac = bcf_get_info_int32(args->hdr, line, "AC", &args->tmp_arr1, &ntmp);
287 args->ntmp_arr1 = ntmp * sizeof(int32_t);
288 if ( i <= nac )
289 {
290 int32_t *ac = (int32_t*)args->tmp_arr1;
291 ac[i-1] = ni;
292 bcf_update_info_int32(args->out_hdr, line, "AC", ac, nac);
293 }
294 }
295
296 static void fix_dup_alt(args_t *args, bcf1_t *line)
297 {
298 // update alleles, create a mapping between old and new indexes
299 hts_expand(uint8_t,line->n_allele,args->ntmp_arr1,args->tmp_arr1);
300 args->tmp_arr1[0] = 0; // ref always unchanged
301
302 int i, j, nals = line->n_allele, nals_ori = line->n_allele;
303 for (i=1, j=1; i<line->n_allele; i++)
304 {
305 if ( strcasecmp(line->d.allele[0],line->d.allele[i]) )
306 {
307 args->tmp_arr1[i] = j++;
308 continue;
309 }
310 args->tmp_arr1[i] = 0;
311 nals--;
312 }
313 for (i=1, j=1; i<line->n_allele; i++)
314 {
315 if ( !args->tmp_arr1[i] ) continue;
316 line->d.allele[j++] = line->d.allele[i];
317 }
318 bcf_update_alleles(args->out_hdr, line, (const char**)line->d.allele, nals);
319
320
321 // update genotypes
322 int ntmp = args->ntmp_arr2 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
323 int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr2, &ntmp);
324 args->ntmp_arr2 = ntmp * sizeof(int32_t);
325 int32_t *gts = (int32_t*) args->tmp_arr2;
326 int changed = 0;
327 for (i=0; i<ngts; i++)
328 {
329 if ( bcf_gt_is_missing(gts[i]) || gts[i]==bcf_int32_vector_end ) continue;
330 int ial = bcf_gt_allele(gts[i]);
331 if ( ial<nals_ori && ial==args->tmp_arr1[ial] ) continue;
332 int ial_new = ial<nals_ori ? args->tmp_arr1[ial] : 0;
333 gts[i] = bcf_gt_is_phased(gts[i]) ? bcf_gt_phased(ial_new) : bcf_gt_unphased(ial_new);
334 changed = 1;
335 }
336 if ( changed ) bcf_update_genotypes(args->out_hdr,line,gts,ngts);
337 }
338
339 static void set_old_rec_tag(args_t *args, bcf1_t *dst, bcf1_t *src, int ialt)
340 {
341 if ( !args->old_rec_tag ) return;
342
343 // only update if the tag is not present already, there can be multiple normalization steps
344 int i, id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, args->old_rec_tag);
345 bcf_unpack(dst, BCF_UN_INFO);
346 for (i=0; i<dst->n_info; i++)
347 {
348 bcf_info_t *inf = &dst->d.info[i];
349 if ( inf && inf->key == id ) return;
350 }
351
352 args->tmp_kstr.l = 0;
353 ksprintf(&args->tmp_kstr,"%s|%"PRIhts_pos"|%s|",bcf_seqname(args->hdr,src),src->pos+1,src->d.allele[0]);
354 for (i=1; i<src->n_allele; i++)
355 {
356 kputs(src->d.allele[i],&args->tmp_kstr);
357 if ( i+1<src->n_allele ) kputc(',',&args->tmp_kstr);
358 }
359 if ( ialt>0 )
360 {
361 kputc('|',&args->tmp_kstr);
362 kputw(ialt,&args->tmp_kstr);
363 }
364 if ( (bcf_update_info_string(args->out_hdr, dst, args->old_rec_tag, args->tmp_kstr.s))!=0 )
365 error("An error occurred while updating INFO/%s\n",args->old_rec_tag);
366 }
367
368 static int is_left_align(args_t *args, bcf1_t *line)
369 {
370 if ( args->right_align ) return 0;
371 if ( !args->gff ) return 1;
372 const char *chr = bcf_seqname(args->hdr,line);
373 if ( !strncasecmp("chr",chr,3) ) chr += 3; // strip 'chr' prefix, that's what we requested the GFF reader to do
374 if ( !regidx_overlap(args->idx_tscript,chr,line->pos,line->pos+line->rlen, args->itr_tscript) ) return 1;
375
376 // if there are two conflicting overlapping transcripts, go with the default left-alignment
377 int has_fwd = 0;
378 while ( regitr_overlap(args->itr_tscript) )
379 {
380 gf_tscript_t *tr = regitr_payload(args->itr_tscript, gf_tscript_t*);
381 if ( tr->strand==STRAND_FWD ) has_fwd = 1;
382 if ( tr->strand==STRAND_REV ) return 1;
383 }
384 // either no hit at all (then left-align) or everything was on fwd strand (then right-align)
385 return has_fwd ? 0 : 1;
386 }
387 static hts_pos_t realign_left(args_t *args, bcf1_t *line)
388 {
389 // trim from right
390 char *ref = NULL;
391 int i;
392 hts_pos_t nref=0, new_pos = line->pos;
393 kstring_t *als = args->tmp_als;
394 while (1)
395 {
396 // is the rightmost base identical in all alleles?
397 int min_len = als[0].l;
398 for (i=1; i<line->n_allele; i++)
399 {
400 if ( toupper(als[0].s[ als[0].l-1 ]) != toupper(als[i].s[ als[i].l-1 ]) ) break;
401 if ( als[i].l < min_len ) min_len = als[i].l;
402 }
403 if ( i!=line->n_allele ) break; // there are differences, cannot be trimmed
404 if ( min_len<=1 && new_pos==0 ) break;
405
406 int pad_from_left = 0;
407 for (i=0; i<line->n_allele; i++) // trim all alleles
408 {
409 als[i].l--;
410 if ( !als[i].l ) pad_from_left = 1;
411 }
412 if ( pad_from_left )
413 {
414 // extend all alleles to the left by aln_win bases (unless close to the chr start).
415 // Extra bases will be trimmed from the left after this loop is done
416 int npad = new_pos >= args->aln_win ? args->aln_win : new_pos;
417 free(ref);
418 ref = faidx_fetch_seq64(args->fai, bcf_seqname(args->hdr,line), new_pos-npad, new_pos-1, &nref);
419 if ( !ref ) error("faidx_fetch_seq64 failed at %s:%"PRId64"\n", bcf_seqname(args->hdr,line), (int64_t) new_pos-npad+1);
420 replace_iupac_codes(ref,nref);
421 for (i=0; i<line->n_allele; i++)
422 {
423 ks_resize(&als[i], als[i].l + npad);
424 if ( als[i].l ) memmove(als[i].s+npad,als[i].s,als[i].l);
425 memcpy(als[i].s,ref,npad);
426 als[i].l += npad;
427 }
428 new_pos -= npad;
429 }
430 }
431 free(ref);
432
433 // trim from left
434 int ntrim_left = 0;
435 while (1)
436 {
437 // is the first base identical in all alleles?
438 int min_len = als[0].l - ntrim_left;
439 for (i=1; i<line->n_allele; i++)
440 {
441 if ( toupper(als[0].s[ntrim_left]) != toupper(als[i].s[ntrim_left]) ) break;
442 if ( min_len > als[i].l - ntrim_left ) min_len = als[i].l - ntrim_left;
443 }
444 if ( i!=line->n_allele || min_len<=1 ) break; // there are differences, cannot be trimmed
445 ntrim_left++;
446 }
447 if ( ntrim_left )
448 {
449 for (i=0; i<line->n_allele; i++)
450 {
451 memmove(als[i].s,als[i].s+ntrim_left,als[i].l-ntrim_left);
452 als[i].l -= ntrim_left;
453 }
454 new_pos += ntrim_left;
455 }
456 return new_pos;
457 }
458
459 static hts_pos_t realign_right(args_t *args, bcf1_t *line)
460 {
461 char *ref = NULL;
462 int i;
463 hts_pos_t new_pos = line->pos, nref = 0;
464 kstring_t *als = args->tmp_als;
465
466 // trim from left
467 int ntrim_left = 0, npad_right = line->rlen, has_indel = 0;
468 while (1)
469 {
470 // is the leftmost base identical in all alleles?
471 int min_len = als[0].l - ntrim_left;
472 for (i=1; i<line->n_allele; i++)
473 {
474 if ( als[0].l!=als[i].l ) has_indel = 1;
475 if ( toupper(als[0].s[ntrim_left]) != toupper(als[i].s[ntrim_left]) ) break;
476 if ( min_len > als[i].l - ntrim_left ) min_len = als[i].l - ntrim_left;
477 }
478 if ( i!=line->n_allele ) break; // there are differences, cannot be trimmed further
479
480 ntrim_left++;
481 if ( min_len<=1 ) // pad from the right
482 {
483 free(ref);
484 ref = faidx_fetch_seq64(args->fai, bcf_seqname(args->hdr,line), line->pos + npad_right, line->pos + npad_right + args->aln_win, &nref);
485 if ( !ref ) error("faidx_fetch_seq64 failed at %s:%"PRIhts_pos"\n",bcf_seqname(args->hdr,line), new_pos + ntrim_left);
486 npad_right += args->aln_win;
487 replace_iupac_codes(ref,nref);
488 for (i=0; i<line->n_allele; i++) kputs(ref, &als[i]);
489 }
490 }
491 ntrim_left -= has_indel;
492 if ( ntrim_left > 0 )
493 {
494 for (i=0; i<line->n_allele; i++)
495 {
496 memmove(als[i].s, als[i].s + ntrim_left, als[i].l - ntrim_left);
497 als[i].l -= ntrim_left;
498 }
499 new_pos += ntrim_left;
500 }
501 free(ref);
502
503 // trim from right
504 while (1)
505 {
506 // is the last base identical in all alleles?
507 int min_len = als[0].l;
508 for (i=1; i<line->n_allele; i++)
509 {
510 if ( toupper(als[0].s[ als[0].l-1 ]) != toupper(als[i].s[ als[i].l-1 ]) ) break;
511 if ( min_len > als[i].l ) min_len = als[i].l;
512 }
513 if ( i!=line->n_allele || min_len<=1 ) break; // there are differences, cannot be trimmed more
514 for (i=0; i<line->n_allele; i++) { als[i].l--; als[i].s[als[i].l]=0; }
515 }
516 return new_pos;
517 }
518
519 #define ERR_DUP_ALLELE -2
520 #define ERR_REF_MISMATCH -1
521 #define ERR_OK 0
522 #define ERR_SYMBOLIC 1
523 #define ERR_SPANNING_DELETION 2
524
525 static int realign(args_t *args, bcf1_t *line)
526 {
527 bcf_unpack(line, BCF_UN_STR);
528
529 // Sanity check REF
530 int i, nref, reflen = strlen(line->d.allele[0]);
531 char *ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos, line->pos+reflen-1, &nref);
532 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", args->hdr->id[BCF_DT_CTG][line->rid].key, (int64_t) line->pos+1);
533 seq_to_upper(ref,0);
534 replace_iupac_codes(ref,nref); // any non-ACGT character in fasta ref is replaced with N
535
536 // does VCF REF contain non-standard bases?
537 if ( has_non_acgtn(line->d.allele[0],reflen) )
538 {
539 if ( args->check_ref==CHECK_REF_EXIT )
540 error("Non-ACGTN reference allele at %s:%"PRId64" .. REF_SEQ:'%s' vs VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,ref,line->d.allele[0]);
541 if ( args->check_ref & CHECK_REF_WARN )
542 fprintf(bcftools_stderr,"NON_ACGTN_REF\t%s\t%"PRId64"\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[0]);
543 free(ref);
544 return ERR_REF_MISMATCH;
545 }
546 if ( strcasecmp(ref,line->d.allele[0]) )
547 {
548 if ( args->check_ref==CHECK_REF_EXIT )
549 error("Reference allele mismatch at %s:%"PRId64" .. REF_SEQ:'%s' vs VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,ref,line->d.allele[0]);
550 if ( args->check_ref & CHECK_REF_WARN )
551 fprintf(bcftools_stderr,"REF_MISMATCH\t%s\t%"PRId64"\t%s\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[0],ref);
552 free(ref);
553 return ERR_REF_MISMATCH;
554 }
555 free(ref);
556 ref = NULL;
557
558 if ( line->n_allele == 1 ) // a REF
559 {
560 if ( line->rlen > 1 )
561 {
562 line->d.allele[0][1] = 0;
563 bcf_update_alleles(args->out_hdr,line,(const char**)line->d.allele,line->n_allele);
564 }
565 return ERR_OK;
566 }
567 if ( bcf_get_variant_types(line)==VCF_BND ) return ERR_SYMBOLIC; // breakend, not an error
568
569 // make a copy of each allele for trimming
570 hts_expand0(kstring_t,line->n_allele,args->ntmp_als,args->tmp_als); // the actual sequence to realign
571 hts_expand0(kstring_t,line->n_allele,args->ntmp_sym,args->tmp_sym); // the original symbolic allele strings to output
572 kstring_t *als = args->tmp_als;
573 kstring_t *sym = args->tmp_sym;
574 int symbolic_alts = 1;
575 for (i=0; i<line->n_allele; i++)
576 {
577 sym[i].l = 0;
578 if ( line->d.allele[i][0]=='<' )
579 {
580 // symbolic allele, only <DEL.*> and <DUP.*> will be realigned
581 // TODO: there should be check for symbolic allele length. If too big, perhaps should not attempt realignment
582 int32_t sv_len = 0;
583 if ( !strncmp("<DEL",line->d.allele[i],4) ) sv_len = -line->rlen;
584 else if ( !strncmp("<DUP",line->d.allele[i],4) )
585 {
586 if ( bcf_get_info_int32(args->hdr,line,"SVLEN",&args->int32_arr,&args->nint32_arr)==1 ) sv_len = args->int32_arr[0];
587 }
588 if ( !sv_len ) return ERR_SYMBOLIC;
589
590 als[i].l = 0;
591 if ( sv_len<0 )
592 {
593 // del, expand REF and replace ALT, for example, replace "REF=C ALT=<DEL>" with "REF=CAT ALT=C"
594 if ( nref < line->rlen )
595 {
596 free(ref);
597 reflen = line->rlen;
598 ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos, line->pos+reflen-1, &nref);
599 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", args->hdr->id[BCF_DT_CTG][line->rid].key, (int64_t) line->pos+1);
600 seq_to_upper(ref,0);
601 replace_iupac_codes(ref,nref); // any non-ACGT character in fasta ref is replaced with N
602 als[0].l = 0;
603 kputs(ref, &als[0]);
604 }
605 kputsn(als[0].s,1,&als[i]);
606 }
607 else // sv_len>0
608 {
609 // dup, replace "REF=C ALT=<DUP>" with "REF=C ALT=CAT"
610 free(ref);
611 ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos, line->pos+sv_len, &nref);
612 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", args->hdr->id[BCF_DT_CTG][line->rid].key, (int64_t) line->pos+1);
613 seq_to_upper(ref,0);
614 replace_iupac_codes(ref,nref); // any non-ACGT character in fasta ref is replaced with N
615 kputs(ref,&als[i]);
616 }
617 kputs(line->d.allele[i],&sym[i]); // preserve the symbolic allele string
618 continue;
619 }
620 if ( i>0 ) symbolic_alts = 0;
621 if ( line->d.allele[i][0]=='*' ) return ERR_SPANNING_DELETION; // spanning deletion
622 if ( has_non_acgtn(line->d.allele[i],line->shared.l) )
623 {
624 if ( args->check_ref==CHECK_REF_EXIT )
625 error("Non-ACGTN alternate allele at %s:%"PRId64" .. VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[i]);
626 if ( args->check_ref & CHECK_REF_WARN )
627 fprintf(bcftools_stderr,"NON_ACGTN_ALT\t%s\t%"PRId64"\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[i]);
628 return ERR_REF_MISMATCH;
629 }
630
631 als[i].l = 0;
632 kputs(line->d.allele[i], &als[i]);
633 seq_to_upper(als[i].s,0);
634
635 if ( i>0 && als[i].l==als[0].l && !strcasecmp(als[0].s,als[i].s) ) return ERR_DUP_ALLELE;
636 }
637 free(ref);
638 ref = NULL;
639
640 // which direction are we aligning?
641 int left_align = is_left_align(args, line);
642
643 hts_pos_t new_pos;
644 if ( left_align )
645 new_pos = realign_left(args, line);
646 else
647 new_pos = realign_right(args, line);
648
649 // Have the alleles changed? Consider <DEL> could have expanded the REF allele. In that
650 // case it must be trimmed, however the new REF length must reflect the entire length.
651 als[0].s[ als[0].l ] = 0; // for strcmp to work
652 int new_reflen = strlen(als[0].s);
653 if ( symbolic_alts )
654 {
655 als[0].l = 1;
656 als[0].s[ als[0].l ] = 0;
657 }
658 if ( new_pos==line->pos && !strcasecmp(line->d.allele[0],als[0].s) ) return ERR_OK;
659
660 set_old_rec_tag(args, line, line, 0);
661
662 // Create new block of alleles and update
663 args->tmp_kstr.l = 0;
664 for (i=0; i<line->n_allele; i++)
665 {
666 if (i>0) kputc(',',&args->tmp_kstr);
667 if ( sym[i].l ) kputs(sym[i].s,&args->tmp_kstr);
668 else kputsn(als[i].s,als[i].l,&args->tmp_kstr);
669 }
670 args->tmp_kstr.s[ args->tmp_kstr.l ] = 0;
671 bcf_update_alleles_str(args->out_hdr,line,args->tmp_kstr.s);
672 args->nchanged++;
673
674 // Update INFO/END if necessary
675 if ( (new_pos!=line->pos || reflen!=new_reflen) && bcf_get_info_int32(args->hdr, line, "END", &args->int32_arr, &args->nint32_arr)==1 )
676 {
677 // bcf_update_alleles_str() messed up rlen because line->pos changed. This will be fixed by bcf_update_info_int32()
678 line->pos = new_pos;
679 args->int32_arr[0] = line->pos + new_reflen;
680 bcf_update_info_int32(args->out_hdr, line, "END", args->int32_arr, 1);
681 }
682 line->pos = new_pos;
683
684 return ERR_OK;
685 }
686
687 static void split_info_numeric(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
688 {
689 #define BRANCH_NUMERIC(type,type_t,is_vector_end,is_missing) \
690 { \
691 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
692 int ntmp = args->ntmp_arr1 / sizeof(type_t); \
693 int ret = bcf_get_info_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
694 args->ntmp_arr1 = ntmp * sizeof(type_t); \
695 assert( ret>0 ); \
696 type_t *vals = (type_t*) args->tmp_arr1; \
697 int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
698 if ( len==BCF_VL_A ) \
699 { \
700 if ( ret!=src->n_allele-1 ) \
701 { \
702 if ( args->force && !args->force_warned ) \
703 { \
704 fprintf(bcftools_stderr, \
705 "Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
706 " (This warning is printed only once.)\n", \
707 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele-1,ret); \
708 args->force_warned = 1; \
709 } \
710 if ( args->force ) \
711 { \
712 bcf_update_info_##type(args->out_hdr,dst,tag,NULL,0); \
713 return; \
714 } \
715 error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d. Use --force to proceed anyway.\n", \
716 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele-1,ret); \
717 } \
718 bcf_update_info_##type(args->out_hdr,dst,tag,vals+ialt,1); \
719 } \
720 else if ( len==BCF_VL_R ) \
721 { \
722 if ( ret!=src->n_allele ) \
723 { \
724 if ( args->force && !args->force_warned ) \
725 { \
726 fprintf(bcftools_stderr, \
727 "Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
728 " (This warning is printed only once.)\n", \
729 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele,ret); \
730 args->force_warned = 1; \
731 } \
732 if ( args->force ) \
733 { \
734 bcf_update_info_##type(args->out_hdr,dst,tag,NULL,0); \
735 return; \
736 } \
737 error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d. Use --force to proceed anyway.\n", \
738 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele,ret); \
739 } \
740 if ( args->keep_sum_ad >= 0 && args->keep_sum_ad==info->key ) \
741 { \
742 int j; \
743 for (j=1; j<info->len; j++) \
744 if ( j!=ialt+1 && !(is_missing) && !(is_vector_end) ) vals[0] += vals[j]; \
745 vals[1] = vals[ialt+1]; \
746 } \
747 else \
748 { \
749 if ( ialt!=0 ) vals[1] = vals[ialt+1]; \
750 } \
751 bcf_update_info_##type(args->out_hdr,dst,tag,vals,2); \
752 } \
753 else if ( len==BCF_VL_G ) \
754 { \
755 if ( ret!=src->n_allele*(src->n_allele+1)/2 ) \
756 { \
757 if ( args->force && !args->force_warned ) \
758 { \
759 fprintf(bcftools_stderr, \
760 "Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
761 " (This warning is printed only once.)\n", \
762 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,ret); \
763 args->force_warned = 1; \
764 } \
765 if ( args->force ) \
766 { \
767 bcf_update_info_##type(args->out_hdr,dst,tag,NULL,0); \
768 return; \
769 } \
770 error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d. Use --force to proceed anyway.\n", \
771 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,ret); \
772 } \
773 if ( ialt!=0 ) \
774 { \
775 vals[1] = vals[bcf_alleles2gt(0,ialt+1)]; \
776 vals[2] = vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
777 } \
778 bcf_update_info_##type(args->out_hdr,dst,tag,vals,3); \
779 } \
780 else \
781 bcf_update_info_##type(args->out_hdr,dst,tag,vals,ret); \
782 }
783 switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
784 {
785 case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, vals[j]==bcf_int32_vector_end, vals[j]==bcf_int32_missing); break;
786 case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_is_vector_end(vals[j]), bcf_float_is_missing(vals[j])); break;
787 }
788 #undef BRANCH_NUMERIC
789 }
790 // Find nth field in a comma-separated list in src and move it to dst.
791 // The dst and src memory areas may overlap, end points just after the last valid src
792 // character.
793 // On success returns pointer to the end of the parsed field and increments ndst by the
794 // number of memmoved characters. Returns NULL if the field was not found.
795 static inline char *string_move_nth(char *dst, char *src, char *end, int nth, size_t *ndst)
796 {
797 if ( src>=end ) return NULL;
798 char *ss = src, *se = src;
799 int j = 0;
800 while ( *se && se<(end) )
801 {
802 if ( *se==',' )
803 {
804 if ( j==nth ) break;
805 j++;
806 ss = se+1;
807 }
808 se++;
809 }
810 if ( j!=nth ) return NULL;
811 if ( ss>=end ) return NULL;
812 if ( !*ss ) return NULL;
813
814 int n = se - ss;
815 memmove((dst),ss,n);
816 *ndst += n;
817 return se;
818 }
819
820 static void split_info_string(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
821 {
822 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
823 int ret = bcf_get_info_string(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
824 assert( ret>0 );
825
826 kstring_t str;
827 str.m = args->ntmp_arr1;
828 str.l = ret;
829 str.s = (char*) args->tmp_arr1;
830
831 int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
832 if ( len==BCF_VL_A )
833 {
834 char *end = str.s + str.l;
835 char *tmp = str.s;
836 str.l = 0;
837 tmp = string_move_nth(str.s,tmp,end,ialt,&str.l);
838 if ( !tmp ) str.l = 1, str.s[0] = '.';
839 kputc_(0,&str);
840 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
841 }
842 else if ( len==BCF_VL_R )
843 {
844 char *end = str.s + str.l;
845 char *tmp = str.s;
846 str.l = 0;
847 tmp = string_move_nth(str.s,tmp,end,0,&str.l);
848 if ( tmp )
849 {
850 kputc_(',',&str);
851 tmp = string_move_nth(str.s+str.l,tmp+1,end,ialt,&str.l); // ialt is 0-based index to ALT
852 }
853 if ( !tmp ) str.l = 1, str.s[0] = '.';
854 kputc_(0,&str);
855 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
856 }
857 else if ( len==BCF_VL_G )
858 {
859 int i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
860 char *end = str.s + str.l;
861 char *tmp = str.s;
862 str.l = 0;
863 tmp = string_move_nth(str.s,tmp,end,0,&str.l);
864 if ( tmp )
865 {
866 kputc_(',',&str);
867 tmp = string_move_nth(str.s+str.l,tmp+1,end,i0a-1,&str.l);
868 }
869 if ( tmp )
870 {
871 kputc_(',',&str);
872 tmp = string_move_nth(str.s+str.l,tmp+1,end,iaa-i0a-1,&str.l);
873 }
874 if ( !tmp ) str.l = 1, str.s[0] = '.';
875 kputc_(0,&str);
876 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
877 }
878 else
879 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
880 if ( args->ntmp_arr1 < str.m )
881 {
882 args->ntmp_arr1 = str.m;
883 args->tmp_arr1 = (uint8_t*)str.s;
884 }
885 }
886 static void split_info_flag(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
887 {
888 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
889 int ret = bcf_get_info_flag(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
890 bcf_update_info_flag(args->out_hdr,dst,tag,NULL,ret);
891 }
892
893 static void split_format_genotype(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
894 {
895 int ntmp = args->ntmp_arr1 / 4;
896 int ngts = bcf_get_genotypes(args->hdr,src,&args->tmp_arr1,&ntmp);
897 args->ntmp_arr1 = ntmp * 4;
898 assert( ngts >0 );
899
900 int32_t *gt = (int32_t*) args->tmp_arr1;
901 int i, j, nsmpl = bcf_hdr_nsamples(args->hdr);
902 ngts /= nsmpl;
903 for (i=0; i<nsmpl; i++)
904 {
905 for (j=0; j<ngts; j++)
906 {
907 if ( gt[j]==bcf_int32_vector_end ) break;
908 if ( bcf_gt_is_missing(gt[j]) ) continue; // missing allele: leave as is
909 if ( bcf_gt_allele(gt[j])==0 ) continue; // ref && `--multi-overlaps 0`: leave as is
910 if ( bcf_gt_allele(gt[j])==ialt+1 )
911 gt[j] = bcf_gt_unphased(1) | bcf_gt_is_phased(gt[j]); // set to first ALT
912 else if ( args->ma_use_ref_allele )
913 gt[j] = bcf_gt_unphased(0) | bcf_gt_is_phased(gt[j]); // set to REF
914 else
915 gt[j] = bcf_gt_missing | bcf_gt_is_phased(gt[j]); // set to missing
916 }
917 gt += ngts;
918 }
919 bcf_update_genotypes(args->out_hdr,dst,args->tmp_arr1,ngts*nsmpl);
920 }
921 static void split_format_numeric(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
922 {
923 #define BRANCH_NUMERIC(type,type_t,is_vector_end,is_missing,set_vector_end,set_missing) \
924 { \
925 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id); \
926 int ntmp = args->ntmp_arr1 / sizeof(type_t); \
927 int nvals = bcf_get_format_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
928 args->ntmp_arr1 = ntmp * sizeof(type_t); \
929 assert( nvals>0 ); \
930 type_t *vals = (type_t *) args->tmp_arr1; \
931 int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id); \
932 int i,j, nsmpl = bcf_hdr_nsamples(args->hdr); \
933 if ( nvals==nsmpl ) /* all values are missing */ \
934 { \
935 bcf_update_format_##type(args->out_hdr,dst,tag,vals,nsmpl); \
936 return; \
937 } \
938 if ( len==BCF_VL_A ) \
939 { \
940 if ( nvals!=(src->n_allele-1)*nsmpl ) \
941 { \
942 if ( args->force && !args->force_warned ) \
943 { \
944 fprintf(bcftools_stderr, \
945 "Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
946 " (This warning is printed only once.)\n", \
947 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
948 args->force_warned = 1; \
949 } \
950 if ( args->force ) \
951 { \
952 bcf_update_format_##type(args->out_hdr,dst,tag,NULL,0); \
953 return; \
954 } \
955 error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Use --force to proceed anyway.\n", \
956 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
957 } \
958 nvals /= nsmpl; \
959 type_t *src_vals = vals, *dst_vals = vals; \
960 for (i=0; i<nsmpl; i++) \
961 { \
962 int idst = 0; \
963 int isrc = ialt; \
964 if ( is_missing || is_vector_end ) set_missing; \
965 else dst_vals[idst] = src_vals[isrc]; \
966 dst_vals += 1; \
967 src_vals += nvals; \
968 } \
969 bcf_update_format_##type(args->out_hdr,dst,tag,vals,nsmpl); \
970 } \
971 else if ( len==BCF_VL_R ) \
972 { \
973 if ( nvals!=src->n_allele*nsmpl ) \
974 { \
975 if ( args->force && !args->force_warned ) \
976 { \
977 fprintf(bcftools_stderr, \
978 "Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
979 " (This warning is printed only once.)\n", \
980 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
981 args->force_warned = 1; \
982 } \
983 if ( args->force ) \
984 { \
985 bcf_update_format_##type(args->out_hdr,dst,tag,NULL,0); \
986 return; \
987 } \
988 error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Use --force to proceed anyway.\n", \
989 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*nsmpl,nvals); \
990 } \
991 nvals /= nsmpl; \
992 type_t *src_vals = vals, *dst_vals = vals; \
993 if ( args->keep_sum_ad >= 0 && args->keep_sum_ad==fmt->id ) \
994 { \
995 for (i=0; i<nsmpl; i++) \
996 { \
997 dst_vals[0] = src_vals[0]; \
998 for (j=1; j<nvals; j++) \
999 { \
1000 int isrc = j; \
1001 if ( j!=ialt+1 && !(is_missing) && !(is_vector_end) ) dst_vals[0] += src_vals[j]; \
1002 } \
1003 int isrc = ialt + 1; \
1004 int idst = 1; \
1005 if ( is_vector_end ) set_missing; \
1006 else dst_vals[idst] = src_vals[isrc]; \
1007 dst_vals += 2; \
1008 src_vals += nvals; \
1009 } \
1010 } \
1011 else \
1012 { \
1013 for (i=0; i<nsmpl; i++) \
1014 { \
1015 dst_vals[0] = src_vals[0]; \
1016 int isrc = ialt + 1; \
1017 int idst = 1; \
1018 if ( is_vector_end ) set_missing; \
1019 else dst_vals[idst] = src_vals[isrc]; \
1020 dst_vals += 2; \
1021 src_vals += nvals; \
1022 } \
1023 } \
1024 bcf_update_format_##type(args->out_hdr,dst,tag,vals,nsmpl*2); \
1025 } \
1026 else if ( len==BCF_VL_G ) \
1027 { \
1028 if ( nvals!=src->n_allele*(src->n_allele+1)/2*nsmpl && nvals!=src->n_allele*nsmpl ) \
1029 { \
1030 if ( args->force && !args->force_warned ) \
1031 { \
1032 fprintf(bcftools_stderr, \
1033 "Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
1034 " (This warning is printed only once.)\n", \
1035 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
1036 args->force_warned = 1; \
1037 } \
1038 if ( args->force ) \
1039 { \
1040 bcf_update_format_##type(args->out_hdr,dst,tag,NULL,0); \
1041 return; \
1042 } \
1043 error("Error at %s:%"PRId64", the tag %s has wrong number of fields. Use --force to proceed anyway.\n", \
1044 bcf_seqname(args->hdr,src),(int64_t) src->pos+1,bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id)); \
1045 } \
1046 nvals /= nsmpl; \
1047 int all_haploid = nvals==src->n_allele ? 1 : 0; \
1048 type_t *src_vals = vals, *dst_vals = vals; \
1049 for (i=0; i<nsmpl; i++) \
1050 { \
1051 int haploid = all_haploid; \
1052 if ( !haploid ) \
1053 { \
1054 int j; \
1055 for (j=0; j<nvals; j++) \
1056 { \
1057 int isrc = j; \
1058 if ( is_vector_end ) break; \
1059 } \
1060 if ( j!=nvals ) haploid = 1; \
1061 } \
1062 dst_vals[0] = src_vals[0]; \
1063 if ( haploid ) \
1064 { \
1065 dst_vals[1] = src_vals[ialt+1]; \
1066 if ( !all_haploid ) { int idst = 2; set_vector_end; } \
1067 } \
1068 else \
1069 { \
1070 dst_vals[1] = src_vals[bcf_alleles2gt(0,ialt+1)]; \
1071 dst_vals[2] = src_vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
1072 } \
1073 dst_vals += all_haploid ? 2 : 3; \
1074 src_vals += nvals; \
1075 } \
1076 bcf_update_format_##type(args->out_hdr,dst,tag,vals,all_haploid ? nsmpl*2 : nsmpl*3); \
1077 } \
1078 else \
1079 bcf_update_format_##type(args->out_hdr,dst,tag,vals,nvals); \
1080 }
1081 switch (bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id))
1082 {
1083 case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, src_vals[isrc]==bcf_int32_vector_end, src_vals[isrc]==bcf_int32_missing, dst_vals[idst]=bcf_int32_vector_end, dst_vals[idst]=bcf_int32_missing); break;
1084 case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_is_vector_end(src_vals[isrc]), bcf_float_is_missing(src_vals[isrc]), bcf_float_set_vector_end(dst_vals[idst]), bcf_float_set_missing(src_vals[idst])); break;
1085 }
1086 #undef BRANCH_NUMERIC
1087 }
1088 static void squeeze_format_char(char *str, int src_blen, int dst_blen, int n)
1089 {
1090 int i, isrc = 0, idst = 0;
1091 for (i=0; i<n; i++)
1092 {
1093 memmove(str+idst,str+isrc,dst_blen);
1094 idst += dst_blen;
1095 isrc += src_blen;
1096 }
1097 }
1098 // ialt is 0-based index to ALT
1099 static void split_format_string(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
1100 {
1101 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
1102 int ret = bcf_get_format_char(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
1103 if ( !ret ) return; // all values can be empty, leave out the tag, no need to panic
1104 assert( ret>0 );
1105
1106 int nsmpl = bcf_hdr_nsamples(args->hdr);
1107 int blen = ret/nsmpl; // per-sample field length
1108 assert( blen>0 );
1109
1110 kstring_t str;
1111 str.m = args->ntmp_arr1;
1112 str.s = (char*) args->tmp_arr1;
1113 str.l = ret;
1114
1115 int tag_len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id);
1116 if ( tag_len==BCF_VL_A )
1117 {
1118 int i, maxlen = 0;
1119 char *ptr = str.s;
1120 for (i=0; i<nsmpl; i++)
1121 {
1122 char *tmp = ptr;
1123 char *end = ptr + blen;
1124 size_t len = 0;
1125 tmp = string_move_nth(ptr,tmp,end,ialt,&len);
1126 if ( !tmp ) ptr[0] = '.', len = 1;
1127 if ( maxlen < len ) maxlen = len;
1128 while (len<blen) ptr[len++] = 0;
1129 ptr += blen;
1130 }
1131 if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
1132 bcf_update_format_char(args->out_hdr,dst,tag,str.s,nsmpl*maxlen);
1133 }
1134 else if ( tag_len==BCF_VL_R )
1135 {
1136 int i, maxlen = 0;
1137 char *ptr = str.s;
1138 for (i=0; i<nsmpl; i++)
1139 {
1140 char *tmp = ptr;
1141 char *end = ptr + blen;
1142 size_t len = 0;
1143 tmp = string_move_nth(ptr,tmp,end,0,&len);
1144 if ( tmp )
1145 {
1146 ptr[len++] = ',';
1147 tmp = string_move_nth(ptr+len,tmp+1,end,ialt,&len);
1148 }
1149 if ( !tmp ) ptr[0] = '.', len = 1;
1150 if ( maxlen < len ) maxlen = len;
1151 while (len<blen) ptr[len++] = 0;
1152 ptr += blen;
1153 }
1154 if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
1155 bcf_update_format_char(args->out_hdr,dst,tag,str.s,nsmpl*maxlen);
1156 }
1157 else if ( tag_len==BCF_VL_G )
1158 {
1159 int i, maxlen = 0, i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
1160 char *ptr = str.s;
1161 for (i=0; i<nsmpl; i++)
1162 {
1163 char *se = ptr, *sx = ptr+blen;
1164 int nfields = 1;
1165 while ( *se && se<sx )
1166 {
1167 if ( *se==',' ) nfields++;
1168 se++;
1169 }
1170 if ( nfields==1 && se-ptr==1 && *ptr=='.' ) continue; // missing value
1171 if ( nfields!=src->n_allele*(src->n_allele+1)/2 && nfields!=src->n_allele )
1172 {
1173 if ( args->force && !args->force_warned )
1174 {
1175 fprintf(bcftools_stderr,
1176 "Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d or %d, found %d. Removing the field.\n"
1177 " (This warning is printed only once.)\n",
1178 tag,bcf_seqname(args->hdr,src),(int64_t)src->pos+1,src->n_allele*(src->n_allele+1)/2,src->n_allele,nfields);
1179 args->force_warned = 1;
1180 }
1181 if ( args->force )
1182 {
1183 bcf_update_format_char(args->out_hdr,dst,tag,NULL,0);
1184 return;
1185 }
1186 error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d or %d, found %d. Use --force to proceed anyway.\n",
1187 tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,src->n_allele,nfields);
1188 }
1189
1190 char *tmp = ptr;
1191 char *end = ptr + blen;
1192 size_t len = 0;
1193 tmp = string_move_nth(ptr,tmp,end,0,&len);
1194 if ( nfields==src->n_allele ) // haploid
1195 {
1196 if ( tmp )
1197 {
1198 ptr[len++] = ',';
1199 tmp = string_move_nth(ptr+len,tmp+1,end,ialt,&len);
1200 }
1201 }
1202 else // diploid
1203 {
1204 if ( tmp )
1205 {
1206 ptr[len++] = ',';
1207 tmp = string_move_nth(ptr+len,tmp+1,end,i0a-1,&len);
1208 }
1209 if ( tmp )
1210 {
1211 ptr[len++] = ',';
1212 tmp = string_move_nth(ptr+len,tmp+1,end,iaa-i0a-1,&len);
1213 }
1214 }
1215 if ( !tmp ) ptr[0] = '.', len = 1;
1216 if ( maxlen < len ) maxlen = len;
1217 while (len<blen) ptr[len++] = 0;
1218 ptr += blen;
1219 }
1220 if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
1221 bcf_update_format_char(args->out_hdr,dst,tag,str.s,nsmpl*maxlen);
1222 }
1223 else
1224 bcf_update_format_char(args->out_hdr,dst,tag,str.s,str.l);
1225 }
1226
1227 static void split_multiallelic_to_biallelics(args_t *args, bcf1_t *line)
1228 {
1229 int i;
1230
1231 bcf_unpack(line, BCF_UN_ALL);
1232
1233 // Init the target biallelic lines
1234 args->ntmp_lines = line->n_allele-1;
1235 if ( args->mtmp_lines < args->ntmp_lines )
1236 {
1237 args->tmp_lines = (bcf1_t **)realloc(args->tmp_lines,sizeof(bcf1_t*)*args->ntmp_lines);
1238 for (i=args->mtmp_lines; i<args->ntmp_lines; i++)
1239 args->tmp_lines[i] = NULL;
1240 args->mtmp_lines = args->ntmp_lines;
1241 }
1242 kstring_t tmp = {0,0,0};
1243 kputs(line->d.allele[0], &tmp);
1244 kputc(',', &tmp);
1245 int rlen = tmp.l;
1246 int gt_id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"GT");
1247 for (i=0; i<args->ntmp_lines; i++) // for each ALT allele
1248 {
1249 if ( !args->tmp_lines[i] ) args->tmp_lines[i] = bcf_init1();
1250 bcf1_t *dst = args->tmp_lines[i];
1251 bcf_clear(dst);
1252
1253 dst->rid = line->rid;
1254 dst->pos = line->pos;
1255 dst->qual = line->qual;
1256
1257 // Not quite sure how to handle IDs, they can be assigned to a specific
1258 // ALT. For now we leave the ID unchanged for all.
1259 bcf_update_id(args->out_hdr, dst, line->d.id ? line->d.id : ".");
1260
1261 tmp.l = rlen;
1262 kputs(line->d.allele[i+1],&tmp);
1263 bcf_update_alleles_str(args->out_hdr,dst,tmp.s);
1264
1265 if ( line->d.n_flt ) bcf_update_filter(args->hdr, dst, line->d.flt, line->d.n_flt);
1266
1267 int j;
1268 for (j=0; j<line->n_info; j++)
1269 {
1270 bcf_info_t *info = &line->d.info[j];
1271 int type = bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key);
1272 if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_info_numeric(args, line, info, i, dst);
1273 else if ( type==BCF_HT_FLAG ) split_info_flag(args, line, info, i, dst);
1274 else split_info_string(args, line, info, i, dst);
1275 }
1276 set_old_rec_tag(args, dst, line, i + 1); // 1-based indexes
1277
1278 dst->n_sample = line->n_sample;
1279 for (j=0; j<line->n_fmt; j++)
1280 {
1281 bcf_fmt_t *fmt = &line->d.fmt[j];
1282 int type = bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id);
1283 if ( fmt->id==gt_id ) split_format_genotype(args, line, fmt, i, dst);
1284 else if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_format_numeric(args, line, fmt, i, dst);
1285 else split_format_string(args, line, fmt, i, dst);
1286 }
1287 }
1288 free(tmp.s);
1289 }
1290
1291 // Enlarge FORMAT array containing nsmpl samples each with nals_ori values
1292 // to accommodate nvals values for each sample, filling the gaps with missing
1293 // values. Works also for INFO arrays, with nsmpl set to 1.
1294 #define ENLARGE_ARRAY(type_t,set_missing,arr,narr_bytes,nsmpl,nvals_ori,nvals) \
1295 { \
1296 int nbytes_new = (nsmpl)*(nvals)*sizeof(type_t); \
1297 hts_expand(uint8_t,nbytes_new,narr_bytes,arr); \
1298 int ismpl, k; \
1299 for (ismpl=nsmpl-1; ismpl>=0; ismpl--) \
1300 { \
1301 type_t *dst_ptr = ((type_t*)arr) + ismpl*(nvals); \
1302 type_t *src_ptr = ((type_t*)arr) + ismpl*nvals_ori; \
1303 memmove(dst_ptr,src_ptr,sizeof(type_t)*nvals_ori); \
1304 for (k=nvals_ori; k<nvals; k++) set_missing; \
1305 } \
1306 }
1307 static void merge_info_numeric(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
1308 {
1309 #define BRANCH_NUMERIC(type,type_t,set_missing,is_vector_end) \
1310 { \
1311 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
1312 int ntmp = args->ntmp_arr1 / sizeof(type_t); \
1313 int nvals_ori = bcf_get_info_##type(args->hdr,lines[0],tag,&args->tmp_arr1,&ntmp); \
1314 args->ntmp_arr1 = ntmp * sizeof(type_t); \
1315 assert( nvals_ori>0 ); \
1316 type_t *vals = (type_t*) args->tmp_arr1, *vals2; \
1317 int i,k,len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
1318 if ( len==BCF_VL_A ) \
1319 { \
1320 if (nvals_ori!=lines[0]->n_allele - 1) \
1321 error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele-1); \
1322 int nvals = dst->n_allele - 1; \
1323 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
1324 vals = (type_t*) args->tmp_arr1; \
1325 for (i=1; i<nlines; i++) \
1326 { \
1327 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1328 int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1329 if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
1330 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1331 if (nvals2!=lines[i]->n_allele-1) \
1332 error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1333 vals2 = (type_t*) args->tmp_arr2; \
1334 for (k=0; k<nvals2; k++) \
1335 { \
1336 if ( is_vector_end ) break; \
1337 vals[ args->maps[i].map[k+1] - 1 ] = vals2[k]; \
1338 } \
1339 } \
1340 bcf_update_info_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals); \
1341 } \
1342 else if ( len==BCF_VL_R ) \
1343 { \
1344 if (nvals_ori!=lines[0]->n_allele) \
1345 error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele); \
1346 int nvals = dst->n_allele; \
1347 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
1348 vals = (type_t*) args->tmp_arr1; \
1349 for (i=1; i<nlines; i++) \
1350 { \
1351 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1352 int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1353 if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
1354 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1355 if (nvals2!=lines[i]->n_allele) \
1356 error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1357 vals2 = (type_t*) args->tmp_arr2; \
1358 for (k=0; k<nvals2; k++) \
1359 { \
1360 if ( is_vector_end ) break; \
1361 vals[ args->maps[i].map[k] ] = vals2[k]; \
1362 } \
1363 } \
1364 bcf_update_info_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals); \
1365 } \
1366 else if ( len==BCF_VL_G ) \
1367 { \
1368 /* expecting diploid gt in INFO */ \
1369 if (nvals_ori!=lines[0]->n_allele*(lines[0]->n_allele+1)/2) { \
1370 fprintf(bcftools_stderr, "todo: merge Number=G INFO fields for haploid sites\n"); \
1371 error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele*(lines[0]->n_allele+1)/2); \
1372 } \
1373 int nvals = dst->n_allele*(dst->n_allele+1)/2; \
1374 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
1375 vals = (type_t*) args->tmp_arr1; \
1376 for (i=1; i<nlines; i++) \
1377 { \
1378 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1379 int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1380 if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
1381 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1382 if (nvals2!=lines[i]->n_allele*(lines[i]->n_allele+1)/2) \
1383 error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1384 vals2 = (type_t*) args->tmp_arr2; \
1385 int ia,ib; \
1386 k = 0; \
1387 for (ia=0; ia<lines[i]->n_allele; ia++) \
1388 { \
1389 for (ib=0; ib<=ia; ib++) \
1390 { \
1391 if ( is_vector_end ) break; \
1392 int l = bcf_alleles2gt(args->maps[i].map[ia],args->maps[i].map[ib]); \
1393 vals[l] = vals2[k]; \
1394 k++; \
1395 } \
1396 } \
1397 } \
1398 bcf_update_info_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals); \
1399 } \
1400 else \
1401 bcf_update_info_##type(args->out_hdr,dst,tag,vals,nvals_ori); \
1402 }
1403 switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
1404 {
1405 case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, dst_ptr[k]=bcf_int32_missing, vals2[k]==bcf_int32_vector_end); break;
1406 case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_set_missing(dst_ptr[k]), bcf_float_is_vector_end(vals2[k])); break;
1407 }
1408 #undef BRANCH_NUMERIC
1409 }
1410 static void merge_info_flag(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
1411 {
1412 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
1413 int ret = bcf_get_info_flag(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
1414 bcf_update_info_flag(args->out_hdr,dst,tag,NULL,ret);
1415 }
1416 int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst); // see vcfmerge.c
1417 static void merge_info_string(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
1418 {
1419 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
1420
1421 kstring_t str;
1422 str.m = args->ntmp_arr1;
1423 str.l = 0;
1424 str.s = (char*) args->tmp_arr1;
1425
1426 int i, j, len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
1427 if ( len==BCF_VL_A || len==BCF_VL_R )
1428 {
1429 int jfrom = len==BCF_VL_A ? 1 : 0;
1430 kputc('.',&str);
1431 for (i=jfrom+1; i<dst->n_allele; i++) kputs(",.",&str);
1432 for (i=0; i<nlines; i++)
1433 {
1434 bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
1435 if (!src) continue;
1436 for (j=jfrom; j<lines[i]->n_allele; j++)
1437 copy_string_field((char*)src->vptr, j-jfrom, src->len, &str, args->maps[i].map[j]-jfrom);
1438 }
1439 str.s[str.l] = 0;
1440 args->tmp_arr1 = (uint8_t*) str.s;
1441 args->ntmp_arr1 = str.m;
1442 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
1443 }
1444 else if ( len==BCF_VL_G )
1445 {
1446 int ngts = dst->n_allele*(dst->n_allele+1)/2;
1447 kputc('.',&str);
1448 for (i=1; i<ngts; i++) kputs(",.",&str);
1449 for (i=0; i<nlines; i++)
1450 {
1451 bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
1452 if (!src) continue;
1453 int iori, jori, kori = 0;
1454 for (iori=0; iori<lines[i]->n_allele; iori++)
1455 {
1456 int inew = args->maps[i].map[iori];
1457 for (jori=0; jori<=iori; jori++)
1458 {
1459 int jnew = args->maps[i].map[jori];
1460 int knew = bcf_alleles2gt(inew,jnew);
1461 copy_string_field((char*)src->vptr,kori,src->len,&str,knew);
1462 kori++;
1463 }
1464 }
1465 }
1466 str.s[str.l] = 0;
1467 args->tmp_arr1 = (uint8_t*) str.s;
1468 args->ntmp_arr1 = str.m;
1469 bcf_update_info_string(args->out_hdr,dst,tag,str.s);
1470 }
1471 else
1472 {
1473 bcf_get_info_string(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
1474 bcf_update_info_string(args->out_hdr,dst,tag,args->tmp_arr1);
1475 }
1476 }
1477 static int gt_array_grow_ploidy(args_t *args, uint8_t **tmp_arr, int *ntmp_arr, int ngt_ori, int ngt_new, int nsmpl)
1478 {
1479 *ntmp_arr = 4*ngt_new*nsmpl;
1480 int32_t *ptr = (int32_t*)realloc(*tmp_arr,*ntmp_arr);
1481 if ( !ptr ) error("Error: failed to allocate %d bytes\n",*ntmp_arr);
1482 *tmp_arr = (uint8_t*) ptr;
1483
1484 int i,j;
1485 for (i=nsmpl-1; i>=0; i--)
1486 {
1487 int32_t *src = ptr + i*ngt_ori;
1488 int32_t *dst = ptr + i*ngt_new;
1489 for (j=ngt_new; j>ngt_ori; j--) dst[j-1] = bcf_int32_vector_end;
1490 for (j=ngt_ori; j>0; j--) dst[j-1] = src[j-1];
1491 }
1492 return ngt_new;
1493 }
1494 static void merge_format_genotype(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
1495 {
1496 // reusing int8_t arrays as int32_t arrays
1497 int ntmp = args->ntmp_arr1 / 4;
1498 int ngts = bcf_get_genotypes(args->hdr,lines[0],&args->tmp_arr1,&ntmp);
1499 args->ntmp_arr1 = ntmp * 4;
1500 assert( ngts >0 );
1501
1502 int nsmpl = bcf_hdr_nsamples(args->hdr);
1503 ngts /= nsmpl;
1504
1505 int i, j, k,k2;
1506 for (i=1; i<nlines; i++)
1507 {
1508 int ntmp2 = args->ntmp_arr2 / 4;
1509 int ngts2 = bcf_get_genotypes(args->hdr,lines[i],&args->tmp_arr2,&ntmp2);
1510 args->ntmp_arr2 = ntmp2 * 4;
1511 ngts2 /= nsmpl;
1512 int ploidy_changed = ngts - ngts2;
1513 if ( ngts < ngts2 ) ngts = gt_array_grow_ploidy(args,&args->tmp_arr1,&args->ntmp_arr1,ngts,ngts2,nsmpl);
1514 if ( ngts > ngts2 ) ngts2 = gt_array_grow_ploidy(args,&args->tmp_arr2,&args->ntmp_arr2,ngts2,ngts,nsmpl);
1515
1516 int32_t *gt = (int32_t*) args->tmp_arr1; // the first, destination line
1517 int32_t *gt2 = (int32_t*) args->tmp_arr2; // one of the subsequent lines, i.e. the source line
1518 for (j=0; j<nsmpl; j++)
1519 {
1520 // Take each source allele and apply to the first line. We try to preserve the order and phasing and we
1521 // never overwrite with ref allele
1522 for (k2=0; k2<ngts2; k2++)
1523 {
1524 if ( gt2[k2]==bcf_int32_vector_end )
1525 {
1526 if ( ploidy_changed && bcf_gt_is_missing(gt[k2]) ) gt[k2] = bcf_int32_vector_end;
1527 break;
1528 }
1529 if ( bcf_gt_is_missing(gt2[k2]) ) continue; // don't overwrite with missing
1530
1531 // don't overwrite with ref, unless the destination is missing, e.g. "./. + 0/1"
1532 int ial2 = bcf_gt_allele(gt2[k2]);
1533 if ( ial2==0 && !bcf_gt_is_missing(gt[k2]) && gt[k2]!=bcf_int32_vector_end ) continue;
1534 if ( ial2>=args->maps[i].nals ) error("Error at %s:%"PRId64": incorrect allele index %d\n",bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1,ial2);
1535
1536 // The destination allele
1537 int ial = args->maps[i].map[ial2];
1538 if ( gt[k2]==bcf_int32_vector_end || bcf_gt_is_missing(gt[k2]) || !bcf_gt_allele(gt[k2]) )
1539 gt[k2] = (gt[k2]!=bcf_int32_vector_end && bcf_gt_is_phased(gt[k2])) ? bcf_gt_phased(ial) : bcf_gt_unphased(ial);
1540 else
1541 {
1542 // conflict, the first line has non-zero allele, use the old way, possibly disrupt the phasing
1543 for (k=0; k<ngts; k++)
1544 if ( gt[k]==bcf_int32_vector_end || bcf_gt_is_missing(gt[k]) || !bcf_gt_allele(gt[k]) ) break;
1545 if ( k<ngts )
1546 gt[k] = bcf_gt_unphased(ial);
1547 }
1548 }
1549 gt += ngts;
1550 gt2 += ngts;
1551 }
1552 }
1553 bcf_update_genotypes(args->out_hdr,dst,args->tmp_arr1,ngts*nsmpl);
1554 }
1555 static int diploid_to_haploid(int size, int nsmpl, int nals, uint8_t *vals)
1556 {
1557 int i, dsrc = size*nals*(nals+1)/2, ddst = size*nals;
1558 uint8_t *src_ptr = vals + dsrc, *dst_ptr = vals + ddst;
1559 for (i=1; i<nsmpl; i++)
1560 {
1561 memmove(dst_ptr,src_ptr,ddst);
1562 dst_ptr += ddst;
1563 src_ptr += dsrc;
1564 }
1565 return nals;
1566 }
1567 static void merge_format_numeric(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
1568 {
1569 #define BRANCH_NUMERIC(type,type_t,set_missing,is_vector_end,set_vector_end) \
1570 { \
1571 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id); \
1572 int ntmp = args->ntmp_arr1 / sizeof(type_t); \
1573 int nvals_ori = bcf_get_format_##type(args->hdr,lines[0],tag,&args->tmp_arr1,&ntmp); \
1574 args->ntmp_arr1 = ntmp * sizeof(type_t); \
1575 assert( nvals_ori>0 ); \
1576 type_t *vals2, *vals = (type_t *) args->tmp_arr1; \
1577 int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id); \
1578 int i, j, k, nsmpl = bcf_hdr_nsamples(args->hdr); \
1579 nvals_ori /= nsmpl; \
1580 if ( len==BCF_VL_A ) \
1581 { \
1582 int nvals = dst->n_allele - 1; \
1583 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
1584 for (i=1; i<nlines; i++) \
1585 { \
1586 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1587 int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1588 if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
1589 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1590 nvals2 /= nsmpl; \
1591 if (nvals2!=lines[i]->n_allele-1) \
1592 error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1593 vals = (type_t*) args->tmp_arr1; \
1594 vals2 = (type_t*) args->tmp_arr2; \
1595 for (j=0; j<nsmpl; j++) \
1596 { \
1597 for (k=0; k<nvals2; k++) \
1598 { \
1599 if ( is_vector_end ) break; \
1600 vals[ args->maps[i].map[k+1] - 1 ] = vals2[k]; \
1601 } \
1602 vals += nvals; \
1603 vals2 += nvals2; \
1604 } \
1605 } \
1606 bcf_update_format_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
1607 } \
1608 else if ( len==BCF_VL_R ) \
1609 { \
1610 int nvals = dst->n_allele; \
1611 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
1612 for (i=1; i<nlines; i++) \
1613 { \
1614 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1615 int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1616 if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
1617 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1618 nvals2 /= nsmpl; \
1619 if (nvals2!=lines[i]->n_allele) \
1620 error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1621 vals = (type_t*) args->tmp_arr1; \
1622 vals2 = (type_t*) args->tmp_arr2; \
1623 for (j=0; j<nsmpl; j++) \
1624 { \
1625 for (k=0; k<nvals2; k++) \
1626 { \
1627 if ( is_vector_end ) break; \
1628 vals[ args->maps[i].map[k] ] = vals2[k]; \
1629 } \
1630 vals += nvals; \
1631 vals2 += nvals2; \
1632 } \
1633 } \
1634 bcf_update_format_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
1635 } \
1636 else if ( len==BCF_VL_G ) \
1637 { \
1638 /* which samples are diploid */ \
1639 memset(args->diploid,0,nsmpl); \
1640 int all_haploid = 1; \
1641 if ( nvals_ori > lines[0]->n_allele ) /* line possibly diploid */ \
1642 { \
1643 vals2 = (type_t*) args->tmp_arr1; \
1644 int ndiploid = lines[0]->n_allele*(lines[0]->n_allele+1)/2; \
1645 for (i=0; i<nsmpl; i++) \
1646 { \
1647 if ( !args->diploid[i] ) \
1648 { \
1649 for (k=0; k<nvals_ori; k++) if ( is_vector_end ) break; \
1650 if ( k==ndiploid ) { args->diploid[i] = 1; all_haploid = 0; }\
1651 } \
1652 vals2 += nvals_ori; \
1653 } \
1654 } \
1655 int nvals = dst->n_allele*(dst->n_allele+1)/2; \
1656 ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
1657 for (i=1; i<nlines; i++) \
1658 { \
1659 int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
1660 int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
1661 if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
1662 args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
1663 nvals2 /= nsmpl; \
1664 int ndiploid = lines[i]->n_allele*(lines[i]->n_allele+1)/2; \
1665 int line_diploid = nvals2==ndiploid ? 1 : 0; \
1666 if (!(nvals2==1 || nvals2==lines[i]->n_allele || nvals2==lines[i]->n_allele*(lines[i]->n_allele+1)/2)) \
1667 error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
1668 vals = (type_t*) args->tmp_arr1; \
1669 vals2 = (type_t*) args->tmp_arr2; \
1670 for (j=0; j<nsmpl; j++) \
1671 { \
1672 int smpl_diploid = line_diploid; \
1673 if ( smpl_diploid ) \
1674 { \
1675 for (k=0; k<nvals2; k++) if ( is_vector_end ) break; \
1676 if ( k!=ndiploid ) smpl_diploid = 0; \
1677 } \
1678 if ( smpl_diploid && !args->diploid[j] ) { args->diploid[j] = 1; all_haploid = 0; } \
1679 if ( !smpl_diploid ) \
1680 { \
1681 for (k=0; k<lines[i]->n_allele; k++) vals[args->maps[i].map[k]] = vals2[k]; \
1682 } \
1683 else \
1684 { \
1685 k = 0; \
1686 int ia,ib; \
1687 for (ia=0; ia<lines[i]->n_allele; ia++) \
1688 { \
1689 for (ib=0; ib<=ia; ib++) \
1690 { \
1691 int l = bcf_alleles2gt(args->maps[i].map[ia],args->maps[i].map[ib]); \
1692 vals[l] = vals2[k]; \
1693 k++; \
1694 } \
1695 } \
1696 } \
1697 vals += nvals; \
1698 vals2 += nvals2; \
1699 } \
1700 } \
1701 if ( all_haploid ) \
1702 nvals = diploid_to_haploid(sizeof(type_t),nsmpl,dst->n_allele,args->tmp_arr1); \
1703 else \
1704 {\
1705 k = dst->n_allele;\
1706 vals2 = (type_t*) args->tmp_arr1;\
1707 for (i=0; i<nsmpl; i++)\
1708 {\
1709 if ( !args->diploid[i] ) set_vector_end;\
1710 vals2 += nvals;\
1711 }\
1712 }\
1713 bcf_update_format_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
1714 } \
1715 else \
1716 bcf_update_format_##type(args->out_hdr,dst,tag,args->tmp_arr1,nvals_ori*nsmpl); \
1717 }
1718 switch (bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id))
1719 {
1720 case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, dst_ptr[k]=bcf_int32_missing, vals2[k]==bcf_int32_vector_end, vals2[k]=bcf_int32_vector_end); break;
1721 case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_set_missing(dst_ptr[k]), bcf_float_is_vector_end(vals2[k]), bcf_float_set_vector_end(vals2[k])); break;
1722 }
1723 #undef BRANCH_NUMERIC
1724 }
1725 static void merge_format_string(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
1726 {
1727 const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
1728
1729 int i, j, k, len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id);
1730 if ( len!=BCF_VL_A && len!=BCF_VL_R && len!=BCF_VL_G )
1731 {
1732 int nret = bcf_get_format_char(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
1733 bcf_update_format_char(args->out_hdr,dst,tag,args->tmp_arr1,nret);
1734 return;
1735 }
1736
1737 int nsmpl = bcf_hdr_nsamples(args->hdr);
1738 for (i=0; i<nsmpl; i++) args->tmp_str[i].l = 0;
1739
1740 if ( len==BCF_VL_A || len==BCF_VL_R )
1741 {
1742 int jfrom = len==BCF_VL_A ? 1 : 0;
1743 for (i=0; i<nsmpl; i++)
1744 {
1745 kstring_t *tmp = &args->tmp_str[i];
1746 kputc('.',tmp);
1747 for (k=jfrom+1; k<dst->n_allele; k++) kputs(",.",tmp);
1748 }
1749 for (i=0; i<nlines; i++)
1750 {
1751 int nret = bcf_get_format_char(args->hdr,lines[i],tag,&args->tmp_arr1,&args->ntmp_arr1);
1752 if (nret<0) continue; /* format tag does not exist in this record, skip */
1753 nret /= nsmpl;
1754 for (k=0; k<nsmpl; k++)
1755 {
1756 kstring_t *tmp = &args->tmp_str[k];
1757 char *src = (char*)args->tmp_arr1 + k*nret;
1758 for (j=jfrom; j<lines[i]->n_allele; j++)
1759 copy_string_field(src, j-jfrom, nret, tmp, args->maps[i].map[j]-jfrom);
1760 }
1761 }
1762 }
1763 else if ( len==BCF_VL_G )
1764 {
1765 hts_expand(uint8_t,nsmpl,args->ntmp_arr2,args->tmp_arr2);
1766 uint8_t *haploid = args->tmp_arr2;
1767 int nret = bcf_get_format_char(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
1768 nret /= nsmpl;
1769 for (i=0; i<nsmpl; i++)
1770 {
1771 char *ss = (char*)args->tmp_arr1 + i*nret, *se = ss+nret;
1772 int nfields = 1;
1773 while ( *ss && ss<se )
1774 {
1775 if ( *ss==',' ) nfields++;
1776 ss++;
1777 }
1778 if ( nfields==lines[0]->n_allele )
1779 {
1780 haploid[i] = 1;
1781 nfields = dst->n_allele;
1782 }
1783 else if ( nfields==lines[0]->n_allele*(lines[0]->n_allele+1)/2 )
1784 {
1785 haploid[i] = 0;
1786 nfields = dst->n_allele*(dst->n_allele+1)/2;
1787 }
1788 else error("The field %s at %s:%"PRId64" neither diploid nor haploid?\n", tag,bcf_seqname(args->hdr,dst),(int64_t) dst->pos+1);
1789
1790 kstring_t *tmp = &args->tmp_str[i];
1791 kputc('.',tmp);
1792 for (j=1; j<nfields; j++) kputs(",.",tmp);
1793 }
1794 for (i=0; i<nlines; i++)
1795 {
1796 if ( i ) // we already have a copy
1797 {
1798 nret = bcf_get_format_char(args->hdr,lines[i],tag,&args->tmp_arr1,&args->ntmp_arr1);
1799 if (nret<0) continue; /* format tag does not exist in this record, skip */
1800 nret /= nsmpl;
1801 }
1802 for (k=0; k<nsmpl; k++)
1803 {
1804 kstring_t *tmp = &args->tmp_str[k];
1805 char *src = (char*)args->tmp_arr1 + k*nret;
1806 if ( haploid[k] )
1807 {
1808 for (j=0; j<lines[i]->n_allele; j++)
1809 copy_string_field(src,j,nret, tmp, args->maps[i].map[j]);
1810 }
1811 else
1812 {
1813 int iori, jori, kori = 0;
1814 for (iori=0; iori<lines[i]->n_allele; iori++)
1815 {
1816 int inew = args->maps[i].map[iori];
1817 for (jori=0; jori<=iori; jori++)
1818 {
1819 int jnew = args->maps[i].map[jori];
1820 int knew = bcf_alleles2gt(inew,jnew);
1821 copy_string_field(src,kori,nret,tmp,knew);
1822 kori++;
1823 }
1824 }
1825 }
1826 }
1827 }
1828 }
1829 kstring_t str;
1830 str.m = args->ntmp_arr2;
1831 str.l = 0;
1832 str.s = (char*) args->tmp_arr2;
1833
1834 int max_len = 0;
1835 for (i=0; i<nsmpl; i++)
1836 if ( max_len < args->tmp_str[i].l ) max_len = args->tmp_str[i].l;
1837 for (i=0; i<nsmpl; i++)
1838 {
1839 kstring_t *tmp = &args->tmp_str[i];
1840 kputsn(tmp->s,tmp->l,&str);
1841 for (j=tmp->l; j<max_len; j++) kputc('\0',&str);
1842 }
1843 args->ntmp_arr2 = str.m;
1844 args->tmp_arr2 = (uint8_t*)str.s;
1845 bcf_update_format_char(args->out_hdr,dst,tag,str.s,str.l);
1846 }
1847
1848 char **merge_alleles(char **a, int na, int *map, char **b, int *nb, int *mb); // see vcfmerge.c
1849 static void merge_biallelics_to_multiallelic(args_t *args, bcf1_t *dst, bcf1_t **lines, int nlines)
1850 {
1851 int i;
1852 for (i=0; i<nlines; i++)
1853 bcf_unpack(lines[i], BCF_UN_ALL);
1854
1855 dst->rid = lines[0]->rid;
1856 dst->pos = lines[0]->pos;
1857
1858 // take max for QUAL
1859 bcf_float_set_missing(dst->qual);
1860 for (i=0; i<nlines; i++) {
1861 if (bcf_float_is_missing(lines[i]->qual)) continue;
1862 if (bcf_float_is_missing(dst->qual) || dst->qual<lines[i]->qual)
1863 dst->qual = lines[i]->qual;
1864 }
1865
1866 bcf_update_id(args->out_hdr, dst, lines[0]->d.id);
1867
1868 // Merge and set the alleles, create a mapping from source allele indexes to dst idxs
1869 hts_expand0(map_t,nlines,args->mmaps,args->maps); // a mapping for each line
1870 args->nals = args->maps[0].nals = lines[0]->n_allele;
1871 hts_expand(int,args->maps[0].nals,args->maps[0].mals,args->maps[0].map);
1872 hts_expand(char*,args->nals,args->mals,args->als);
1873 for (i=0; i<args->maps[0].nals; i++)
1874 {
1875 args->maps[0].map[i] = i;
1876 args->als[i] = strdup(lines[0]->d.allele[i]);
1877 }
1878 for (i=1; i<nlines; i++)
1879 {
1880 if (lines[i]->d.id[0]!='.' || lines[i]->d.id[1]) bcf_add_id(args->out_hdr, dst, lines[i]->d.id);
1881 args->maps[i].nals = lines[i]->n_allele;
1882 hts_expand(int,args->maps[i].nals,args->maps[i].mals,args->maps[i].map);
1883 args->als = merge_alleles(lines[i]->d.allele, lines[i]->n_allele, args->maps[i].map, args->als, &args->nals, &args->mals);
1884 if ( !args->als ) error("Failed to merge alleles at %s:%"PRId64"\n", bcf_seqname(args->hdr,dst),(int64_t) dst->pos+1);
1885 }
1886 bcf_update_alleles(args->out_hdr, dst, (const char**)args->als, args->nals);
1887 for (i=0; i<args->nals; i++)
1888 {
1889 free(args->als[i]);
1890 args->als[i] = NULL;
1891 }
1892
1893 if ( lines[0]->d.n_flt ) bcf_update_filter(args->out_hdr, dst, lines[0]->d.flt, lines[0]->d.n_flt);
1894 for (i=1; i<nlines; i++) {
1895 int j;
1896 for (j=0; j<lines[i]->d.n_flt; j++) {
1897 // if strict_filter, set FILTER to PASS if any site PASS
1898 // otherwise accumulate FILTERs
1899 if (lines[i]->d.flt[j] == bcf_hdr_id2int(args->hdr, BCF_DT_ID, "PASS")) {
1900 if (args->strict_filter) {
1901 bcf_update_filter(args->out_hdr, dst, lines[i]->d.flt, lines[i]->d.n_flt);
1902 break;
1903 }
1904 else
1905 continue;
1906 }
1907 bcf_add_filter(args->out_hdr, dst, lines[i]->d.flt[j]);
1908 }
1909 }
1910
1911 // merge info
1912 for (i=0; i<lines[0]->n_info; i++)
1913 {
1914 bcf_info_t *info = &lines[0]->d.info[i];
1915 int type = bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key);
1916 if ( type==BCF_HT_INT || type==BCF_HT_REAL ) merge_info_numeric(args, lines, nlines, info, dst);
1917 else if ( type==BCF_HT_FLAG ) merge_info_flag(args, lines, nlines, info, dst);
1918 else merge_info_string(args, lines, nlines, info, dst);
1919 }
1920
1921 // merge format
1922 int gt_id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"GT");
1923 dst->n_sample = lines[0]->n_sample;
1924 for (i=0; i<lines[0]->n_fmt; i++)
1925 {
1926 bcf_fmt_t *fmt = &lines[0]->d.fmt[i];
1927 int type = bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id);
1928 if ( fmt->id==gt_id ) merge_format_genotype(args, lines, nlines, fmt, dst);
1929 else if ( type==BCF_HT_INT || type==BCF_HT_REAL ) merge_format_numeric(args, lines, nlines, fmt, dst);
1930 else merge_format_string(args, lines, nlines, fmt, dst);
1931 }
1932 args->njoined++;
1933 }
1934
1935 #define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
1936 static void mrows_push(args_t *args, bcf1_t **line)
1937 {
1938 int i,m;
1939 if ( !args->nmrows ) args->mrows_first = 0;
1940 args->nmrows++;
1941 m = args->mmrows;
1942 hts_expand(bcf1_t*,args->nmrows,args->mmrows,args->mrows);
1943 for (i=m; i<args->mmrows; i++) args->mrows[i] = bcf_init1();
1944 SWAP(bcf1_t*, args->mrows[args->nmrows-1], *line);
1945
1946 if ( args->mrows_collapse==COLLAPSE_ANY ) return;
1947
1948 // move the line up the sorted list so that the same variant types end up together
1949 int cur_type = bcf_get_variant_types(args->mrows[args->nmrows-1]);
1950 i = args->mrows_first + args->nmrows - 1;
1951 while (i>0)
1952 {
1953 int prev_type = bcf_get_variant_types(args->mrows[i-1]);
1954 if ( prev_type <= cur_type ) break;
1955 bcf1_t *tmp = args->mrows[i-1];
1956 args->mrows[i-1] = args->mrows[i];
1957 args->mrows[i] = tmp;
1958 i--;
1959 }
1960 }
1961 static int mrows_can_flush(args_t *args, bcf1_t *line)
1962 {
1963 if ( !args->nmrows ) return 0;
1964 int ibeg = args->mrows_first;
1965 if ( args->mrows[ibeg]->rid != line->rid ) return 1;
1966 if ( args->mrows[ibeg]->pos != line->pos ) return 1;
1967 return 0;
1968 }
1969 static bcf1_t *mrows_flush(args_t *args)
1970 {
1971 if ( !args->nmrows ) return NULL;
1972
1973 int ibeg = args->mrows_first;
1974
1975 //fprintf(bcftools_stderr,"flush: ibeg=%d n=%d\n",ibeg,args->nmrows);
1976 //int i;
1977 //for (i=ibeg; i<ibeg+args->nmrows; i++)
1978 // fprintf(bcftools_stderr,"\ti=%d type=%d %s %s\n",i,bcf_get_variant_types(args->mrows[i]),args->mrows[i]->d.allele[0],args->mrows[i]->d.allele[1]);
1979
1980 if ( args->nmrows==1 )
1981 {
1982 args->nmrows = 0;
1983 return args->mrows[ibeg];
1984 }
1985
1986 if ( args->mrows_collapse==COLLAPSE_ANY )
1987 {
1988 // merge everything with anything
1989 bcf_clear(args->mrow_out);
1990 merge_biallelics_to_multiallelic(args, args->mrow_out, &args->mrows[ibeg], args->nmrows - ibeg);
1991 args->nmrows = 0;
1992 return args->mrow_out;
1993 }
1994
1995 int j;
1996 int types[] = { VCF_SNP, VCF_MNP, VCF_INDEL, VCF_OTHER, -1 }; // merge everything within the same category
1997 if ( args->mrows_collapse==COLLAPSE_SNPS ) types[1] = -1; // merge SNPs only
1998 else if ( args->mrows_collapse==COLLAPSE_INDELS ) types[0] = VCF_INDEL, types[1] = -1; // merge indels only
1999 for (j=0; types[j]!=-1; j++)
2000 {
2001 int i, type = types[j]; // to keep the compiler happy
2002 for (i=ibeg; i<ibeg+args->nmrows; i++)
2003 {
2004 type = bcf_get_variant_types(args->mrows[i]);
2005 if ( type!=types[j] && type!=VCF_REF ) break;
2006 }
2007 if ( i==ibeg+1 && type!=VCF_REF )
2008 {
2009 // just one line of this type, no merging, but multiple lines of different type follow
2010 args->nmrows--;
2011 args->mrows_first++;
2012 return args->mrows[ibeg];
2013 }
2014 if ( i>ibeg )
2015 {
2016 // more than one line, merging is needed
2017 int nflush = i - ibeg;
2018 bcf_clear(args->mrow_out);
2019 merge_biallelics_to_multiallelic(args, args->mrow_out, &args->mrows[ibeg], nflush);
2020 args->nmrows -= nflush;
2021 args->mrows_first += nflush;
2022 return args->mrow_out;
2023 }
2024 }
2025 args->nmrows--;
2026 args->mrows_first++;
2027 return args->mrows[ibeg];
2028 }
2029 static char *strdup_alt_svlen(args_t *args, bcf1_t *rec, int ial)
2030 {
2031 if ( rec->d.allele[ial][0]!='<' ) return strdup(rec->d.allele[ial]);
2032
2033 int ntmp = args->ntmp_arr1 / sizeof(int32_t);
2034 int n = bcf_get_info_int32(args->hdr, rec, "SVLEN", &args->tmp_arr1, &ntmp);
2035 args->ntmp_arr1 = ntmp * sizeof(int32_t);
2036 int32_t *svlen = (int32_t *) args->tmp_arr1;
2037 if ( n<=0 ) return strdup(rec->d.allele[ial]);
2038
2039 if ( n+1 != rec->n_allele )
2040 {
2041 // there should be as many SVLEN numbers as there are ALT alleles
2042 static int warned = 0;
2043 if ( !warned )
2044 {
2045 fprintf(bcftools_stderr,"TODO: different number of ALT alleles and SVLEN fields %s:%"PRIhts_pos"\n",bcf_seqname(args->hdr,rec),rec->pos+1);
2046 warned = 1;
2047 }
2048 }
2049
2050 kstring_t str = {0,0,0};
2051 ksprintf(&str,"%s.%d",rec->d.allele[ial],svlen[ial-1]);
2052 return str.s;
2053 }
2054 static void cmpals_add(args_t *args, cmpals_t *ca, bcf1_t *rec)
2055 {
2056 ca->ncmpals++;
2057 hts_expand0(cmpals1_t, ca->ncmpals, ca->mcmpals, ca->cmpals);
2058 cmpals1_t *cmpals = ca->cmpals + ca->ncmpals - 1;
2059 free(cmpals->ref);
2060 cmpals->ref = strdup(rec->d.allele[0]);
2061 cmpals->n = rec->n_allele;
2062
2063 if ( rec->n_allele==2 )
2064 {
2065 free(cmpals->alt);
2066 cmpals->alt = strdup_alt_svlen(args,rec,1);
2067 }
2068 else
2069 {
2070 if ( cmpals->hash ) khash_str2int_destroy_free(cmpals->hash);
2071 cmpals->hash = khash_str2int_init();
2072 int i;
2073 for (i=1; i<rec->n_allele; i++)
2074 khash_str2int_inc(cmpals->hash, strdup(rec->d.allele[i]));
2075 }
2076 }
2077 static int cmpals_match(args_t *args, cmpals_t *ca, bcf1_t *rec)
2078 {
2079 int i, j;
2080 char *alt_svlen = rec->n_allele==2 ? strdup_alt_svlen(args,rec,1) : NULL;
2081 for (i=0; i<ca->ncmpals; i++)
2082 {
2083 cmpals1_t *cmpals = ca->cmpals + i;
2084 if ( rec->n_allele != cmpals->n ) continue;
2085
2086 // NB. assuming both are normalized
2087 if ( strcasecmp(rec->d.allele[0], cmpals->ref) ) continue;
2088
2089 // the most frequent case
2090 if ( rec->n_allele==2 )
2091 {
2092 if ( strcasecmp(alt_svlen, cmpals->alt) ) continue;
2093 free(alt_svlen);
2094 return 1;
2095 }
2096
2097 khash_t(str2int) *hash = (khash_t(str2int)*) cmpals->hash;
2098 for (j=1; j<rec->n_allele; j++)
2099 if ( !khash_str2int_has_key(hash, rec->d.allele[j]) ) break;
2100 if ( j<rec->n_allele ) continue;
2101 return 1;
2102 }
2103 free(alt_svlen);
2104 return 0;
2105 }
2106 static void cmpals_reset(cmpals_t *ca) { ca->ncmpals = 0; }
2107 static void cmpals_destroy(cmpals_t *ca)
2108 {
2109 int i;
2110 for (i=0; i<ca->mcmpals; i++)
2111 {
2112 cmpals1_t *cmpals = ca->cmpals + i;
2113 free(cmpals->ref);
2114 free(cmpals->alt);
2115 if ( cmpals->hash ) khash_str2int_destroy_free(cmpals->hash);
2116 }
2117 free(ca->cmpals);
2118 }
2119
2120 static void flush_buffer(args_t *args, htsFile *file, int n)
2121 {
2122 bcf1_t *line;
2123 int i, k;
2124 int prev_rid = -1, prev_pos = -1, prev_type = 0;
2125 for (i=0; i<n; i++)
2126 {
2127 k = rbuf_shift(&args->rbuf);
2128 if ( args->mrows_op==MROWS_MERGE )
2129 {
2130 if ( mrows_can_flush(args, args->lines[k]) )
2131 {
2132 while ( (line=mrows_flush(args)) )
2133 if ( bcf_write1(file, args->out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
2134 }
2135 mrows_push(args, &args->lines[k]);
2136 continue;
2137 }
2138 else if ( args->rmdup )
2139 {
2140 int line_type = bcf_get_variant_types(args->lines[k]);
2141 if ( prev_rid>=0 && prev_rid==args->lines[k]->rid && prev_pos==args->lines[k]->pos )
2142 {
2143 if ( args->rmdup & BCF_SR_PAIR_ANY ) continue; // rmdup by position only
2144 if ( args->rmdup & BCF_SR_PAIR_SNPS && line_type&(VCF_SNP|VCF_MNP) && prev_type&(VCF_SNP|VCF_MNP) ) continue;
2145 if ( args->rmdup & BCF_SR_PAIR_INDELS && line_type&(VCF_INDEL) && prev_type&(VCF_INDEL) ) continue;
2146 if ( args->rmdup & BCF_SR_PAIR_EXACT && cmpals_match(args, &args->cmpals_out, args->lines[k]) ) continue;
2147 }
2148 else
2149 {
2150 prev_rid = args->lines[k]->rid;
2151 prev_pos = args->lines[k]->pos;
2152 prev_type = 0;
2153 if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_reset(&args->cmpals_out);
2154 }
2155 prev_type |= line_type;
2156 if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_add(args,&args->cmpals_out, args->lines[k]);
2157 }
2158 if ( bcf_write1(file, args->out_hdr, args->lines[k])!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
2159 }
2160 if ( args->mrows_op==MROWS_MERGE && !args->rbuf.n )
2161 {
2162 while ( (line=mrows_flush(args)) )
2163 if ( bcf_write1(file, args->out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
2164 }
2165 }
2166
2167 static void init_data(args_t *args)
2168 {
2169 args->hdr = args->files->readers[0].header;
2170 if ( args->keep_sum_ad )
2171 {
2172 args->keep_sum_ad = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"AD");
2173 if ( args->keep_sum_ad < 0 ) error("Error: --keep-sum-ad requested but the tag AD is not present\n");
2174 }
2175 else
2176 args->keep_sum_ad = -1;
2177
2178 args->out_hdr = args->hdr;
2179 if ( args->old_rec_tag )
2180 bcf_hdr_printf(args->out_hdr,"##INFO=<ID=%s,Number=1,Type=String,Description=\"Original variant. Format: CHR|POS|REF|ALT|USED_ALT_IDX\">",args->old_rec_tag);
2181
2182 rbuf_init(&args->rbuf, 100);
2183 args->lines = (bcf1_t**) calloc(args->rbuf.m, sizeof(bcf1_t*));
2184 if ( args->ref_fname )
2185 {
2186 args->fai = fai_load(args->ref_fname);
2187 if ( !args->fai ) error("Failed to load the fai index: %s\n", args->ref_fname);
2188 }
2189 if ( args->mrows_op==MROWS_MERGE )
2190 {
2191 args->mrow_out = bcf_init1();
2192 args->tmp_str = (kstring_t*) calloc(bcf_hdr_nsamples(args->hdr),sizeof(kstring_t));
2193 args->diploid = (uint8_t*) malloc(bcf_hdr_nsamples(args->hdr));
2194 }
2195 if ( args->atomize==SPLIT )
2196 {
2197 args->abuf = abuf_init(args->hdr, SPLIT);
2198 abuf_set_opt(args->abuf, bcf_hdr_t*, BCF_HDR, args->out_hdr);
2199 if ( args->old_rec_tag )
2200 {
2201 abuf_set_opt(args->abuf, const char*, INFO_TAG, args->old_rec_tag);
2202 if ( bcf_hdr_sync(args->out_hdr)!=0 ) error("bcf_hdr_sync failed\n");
2203 }
2204 abuf_set_opt(args->abuf, int, STAR_ALLELE, args->use_star_allele);
2205 }
2206 if ( args->gff_fname )
2207 {
2208 args->gff = gff_init(args->gff_fname);
2209 gff_set(args->gff,verbosity,args->gff_verbosity);
2210 gff_set(args->gff,strip_chr_names,1);
2211 gff_parse(args->gff);
2212 args->idx_tscript = gff_get(args->gff,idx_tscript);
2213 args->itr_tscript = regitr_init(NULL);
2214 }
2215 if ( args->filter_str )
2216 args->filter = filter_init(args->hdr, args->filter_str);
2217 args->filter_pass = 1;
2218
2219 args->out_hdr = bcf_hdr_dup(args->out_hdr);
2220 }
2221
2222 static void destroy_data(args_t *args)
2223 {
2224 if ( args->filter ) filter_destroy(args->filter);
2225 if ( args->gff )
2226 {
2227 gff_destroy(args->gff);
2228 regitr_destroy(args->itr_tscript);
2229 }
2230 cmpals_destroy(&args->cmpals_in);
2231 cmpals_destroy(&args->cmpals_out);
2232 int i;
2233 for (i=0; i<args->rbuf.m; i++)
2234 if ( args->lines[i] ) bcf_destroy1(args->lines[i]);
2235 free(args->lines);
2236 for (i=0; i<args->mtmp_lines; i++)
2237 if ( args->tmp_lines[i] ) bcf_destroy1(args->tmp_lines[i]);
2238 free(args->tmp_lines);
2239 for (i=0; i<args->mmrows; i++)
2240 bcf_destroy1(args->mrows[i]);
2241 free(args->mrows);
2242 for (i=0; i<args->mmaps; i++)
2243 free(args->maps[i].map);
2244 for (i=0; i<args->ntmp_als; i++)
2245 free(args->tmp_als[i].s);
2246 for (i=0; i<args->ntmp_sym; i++)
2247 free(args->tmp_sym[i].s);
2248 free(args->tmp_als);
2249 free(args->tmp_sym);
2250 free(args->tmp_kstr.s);
2251 if ( args->tmp_str )
2252 {
2253 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++) free(args->tmp_str[i].s);
2254 free(args->tmp_str);
2255 }
2256 free(args->maps);
2257 free(args->als);
2258 free(args->int32_arr);
2259 free(args->tmp_arr1);
2260 free(args->tmp_arr2);
2261 free(args->diploid);
2262 if ( args->abuf ) abuf_destroy(args->abuf);
2263 bcf_hdr_destroy(args->out_hdr);
2264 if ( args->mrow_out ) bcf_destroy1(args->mrow_out);
2265 if ( args->fai ) fai_destroy(args->fai);
2266 if ( args->mseq ) free(args->seq);
2267 }
2268
2269
2270 static void normalize_line(args_t *args, bcf1_t *line)
2271 {
2272 if ( args->fai )
2273 {
2274 if ( args->filter_pass && (args->check_ref & CHECK_REF_FIX) ) fix_ref(args, line);
2275 if ( args->do_indels )
2276 {
2277 int ret = args->filter_pass ? realign(args, line) : ERR_OK;
2278
2279 // exclude broken VCF lines
2280 if ( ret==ERR_REF_MISMATCH && args->check_ref & CHECK_REF_SKIP )
2281 {
2282 args->nskipped++;
2283 return;
2284 }
2285 if ( ret==ERR_DUP_ALLELE )
2286 {
2287 if ( args->check_ref & CHECK_REF_FIX )
2288 fix_dup_alt(args, line);
2289 else if ( args->check_ref==CHECK_REF_EXIT )
2290 error("Duplicate alleles at %s:%"PRId64"; run with -cw to turn the error into warning or with -cs to fix.\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
2291 else if ( args->check_ref & CHECK_REF_WARN )
2292 fprintf(bcftools_stderr,"ALT_DUP\t%s\t%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
2293 }
2294 }
2295 }
2296
2297 if ( args->filter_pass && args->atomize==SPLIT ) abuf_push(args->abuf,line);
2298 while (1)
2299 {
2300 if ( args->filter_pass && args->atomize==SPLIT )
2301 {
2302 line = abuf_flush(args->abuf, 0);
2303 if ( !line ) break;
2304 }
2305
2306 // insert into sorted buffer
2307 rbuf_expand0(&args->rbuf,bcf1_t*,args->rbuf.n+1,args->lines);
2308 int i,j;
2309 i = j = rbuf_append(&args->rbuf);
2310 if ( args->lines[i] ) bcf_destroy(args->lines[i]);
2311 args->lines[i] = bcf_dup(line);
2312 while ( rbuf_prev(&args->rbuf,&i) )
2313 {
2314 if ( args->lines[i]->rid==args->lines[j]->rid )
2315 {
2316 bcf_unpack(args->lines[i], BCF_UN_STR);
2317 bcf_unpack(args->lines[j], BCF_UN_STR);
2318 if ( args->cmp_func(&args->lines[i], &args->lines[j]) > 0) SWAP(bcf1_t*, args->lines[i], args->lines[j]);
2319 }
2320 j = i;
2321 }
2322 if ( !args->filter_pass || args->atomize!=SPLIT ) break;
2323 }
2324 }
2325
2326 // return 0 on success, 1 when done
2327 static int split_and_normalize(args_t *args)
2328 {
2329 if ( !bcf_sr_next_line(args->files) ) return 1;
2330
2331 bcf1_t *line = bcf_sr_get_line(args->files,0);
2332 args->ntotal++;
2333
2334 if ( args->filter )
2335 {
2336 args->filter_pass = filter_test(args->filter,line,NULL);
2337 if ( args->filter_logic==FLT_EXCLUDE ) args->filter_pass = args->filter_pass ? 0 : 1;
2338 if ( !args->filter_pass ) args->nfilter++;
2339 }
2340
2341 if ( args->mrows_op!=MROWS_SPLIT || line->n_allele<=2 || !args->filter_pass )
2342 {
2343 // normal operation, no splitting
2344 normalize_line(args, line);
2345 return 0;
2346 }
2347
2348 // any restrictions on variant types to split?
2349 if ( args->mrows_collapse!=COLLAPSE_BOTH && args->mrows_collapse!=COLLAPSE_ANY )
2350 {
2351 int type = args->mrows_collapse==COLLAPSE_SNPS ? VCF_SNP : VCF_INDEL;
2352 if ( !(bcf_get_variant_types(line) & type) )
2353 {
2354 normalize_line(args, line);
2355 return 0;
2356 }
2357 }
2358
2359 args->nsplit++;
2360 split_multiallelic_to_biallelics(args, line);
2361
2362 int j;
2363 for (j=0; j<args->ntmp_lines; j++)
2364 normalize_line(args, args->tmp_lines[j]);
2365
2366 return 0;
2367 }
2368
2369 static void normalize_vcf(args_t *args)
2370 {
2371 char wmode[8];
2372 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
2373 args->out = hts_open(args->output_fname ? args->output_fname : "-", wmode);
2374 if ( args->out == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
2375 if ( args->n_threads )
2376 hts_set_opt(args->out, HTS_OPT_THREAD_POOL, args->files->p);
2377 if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_norm");
2378 if ( bcf_hdr_write(args->out, args->out_hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
2379 if ( init_index2(args->out,args->out_hdr,args->output_fname,
2380 &args->index_fn, args->write_index)<0 )
2381 error("Error: failed to initialise index for %s\n",args->output_fname);
2382
2383 while (1)
2384 {
2385 // buffer lines until a different position is reached
2386 int done = 0;
2387 while (1)
2388 {
2389 done = split_and_normalize(args);
2390 if ( done ) break; // no more lines available
2391 int i = args->rbuf.f;
2392 int j = rbuf_last(&args->rbuf);
2393 if ( args->lines[i]->rid != args->lines[j]->rid ) break;
2394 if ( args->lines[i]->pos != args->lines[j]->pos ) break;
2395 }
2396 if ( done ) break;
2397
2398 // find out how many sites to flush
2399 int ifst = args->rbuf.f;
2400 int ilast = rbuf_last(&args->rbuf);
2401 int i, j = 0;
2402 for (i=-1; rbuf_next(&args->rbuf,&i); )
2403 {
2404 if ( args->lines[ifst]->rid != args->lines[ilast]->rid )
2405 {
2406 // there are two chromosomes in the buffer, count how many are on the first chromosome
2407 if ( args->lines[ifst]->rid != args->lines[i]->rid ) break;
2408 j++;
2409 continue;
2410 }
2411 // there is just one chromosome, flush only lines that are unlikely to change order on
2412 // realigning (the buf_win constant)
2413 if ( args->lines[ilast]->pos - args->lines[i]->pos < args->buf_win ) break;
2414 j++;
2415 }
2416 if ( j>0 ) flush_buffer(args, args->out, j);
2417 }
2418 flush_buffer(args, args->out, args->rbuf.n);
2419 if ( args->write_index )
2420 {
2421 if ( bcf_idx_save(args->out)<0 )
2422 {
2423 if ( hts_close(args->out)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
2424 error("Error: cannot write to index %s\n", args->index_fn);
2425 }
2426 free(args->index_fn);
2427 }
2428 if ( hts_close(args->out)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
2429
2430 fprintf(bcftools_stderr,"Lines total/split/joined/realigned/removed/skipped:\t%d/%d/%d/%d/%d/%d\n",
2431 args->ntotal,args->nsplit,args->njoined,args->nchanged,args->nskipped,args->nfilter);
2432 if ( args->check_ref & CHECK_REF_FIX )
2433 fprintf(bcftools_stderr,"REF/ALT total/modified/added: \t%d/%d/%d\n", args->nref.tot,args->nref.swap,args->nref.set);
2434 }
2435
2436 static void usage(void)
2437 {
2438 fprintf(bcftools_stderr, "\n");
2439 fprintf(bcftools_stderr, "About: Left-align and normalize indels; check if REF alleles match the reference;\n");
2440 fprintf(bcftools_stderr, " split multiallelic sites into multiple rows; recover multiallelics from\n");
2441 fprintf(bcftools_stderr, " multiple rows.\n");
2442 fprintf(bcftools_stderr, "Usage: bcftools norm [options] <in.vcf.gz>\n");
2443 fprintf(bcftools_stderr, "\n");
2444 fprintf(bcftools_stderr, "Options:\n");
2445 fprintf(bcftools_stderr, " -a, --atomize Decompose complex variants (e.g. MNVs become consecutive SNVs)\n");
2446 fprintf(bcftools_stderr, " --atom-overlaps '*'|. Use the star allele (*) for overlapping alleles or set to missing (.) [*]\n");
2447 fprintf(bcftools_stderr, " -c, --check-ref e|w|x|s Check REF alleles and exit (e), warn (w), exclude (x), or set (s) bad sites [e]\n");
2448 fprintf(bcftools_stderr, " -D, --remove-duplicates Remove duplicate lines of the same type.\n");
2449 fprintf(bcftools_stderr, " -d, --rm-dup TYPE Remove duplicate snps|indels|both|all|exact\n");
2450 fprintf(bcftools_stderr, " -e, --exclude EXPR Do not normalize records for which the expression is true (see man page for details)\n");
2451 fprintf(bcftools_stderr, " -f, --fasta-ref FILE Reference sequence\n");
2452 fprintf(bcftools_stderr, " --force Try to proceed even if malformed tags are encountered. Experimental, use at your own risk\n");
2453 fprintf(bcftools_stderr, " -g, --gff-annot FILE Follow HGVS 3'rule and right-align variants in transcripts on the forward strand\n");
2454 fprintf(bcftools_stderr, " -i, --include EXPR Normalize only records for which the expression is true (see man page for details)\n");
2455 fprintf(bcftools_stderr, " --keep-sum TAG,.. Keep vector sum constant when splitting multiallelics (see github issue #360)\n");
2456 fprintf(bcftools_stderr, " -m, --multiallelics -|+TYPE Split multiallelics (-) or join biallelics (+), type: snps|indels|both|any [both]\n");
2457 fprintf(bcftools_stderr, " --multi-overlaps 0|. Fill in the reference (0) or missing (.) allele when splitting multiallelics [0]\n");
2458 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
2459 fprintf(bcftools_stderr, " -N, --do-not-normalize Do not normalize indels (with -m or -c s)\n");
2460 fprintf(bcftools_stderr, " --old-rec-tag STR Annotate modified records with INFO/STR indicating the original variant\n");
2461 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
2462 fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
2463 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
2464 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
2465 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
2466 fprintf(bcftools_stderr, " -s, --strict-filter When merging (-m+), merged site is PASS only if all sites being merged PASS\n");
2467 fprintf(bcftools_stderr, " -S, --sort METHOD Sort order: chr_pos,lex [chr_pos]\n");
2468 fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
2469 fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
2470 fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
2471 fprintf(bcftools_stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
2472 fprintf(bcftools_stderr, " -v, --verbose INT Verbosity level (0-2) of GFF parsing [1]\n");
2473 fprintf(bcftools_stderr, " -w, --site-win INT Buffer for sorting lines which changed position during realignment [1000]\n");
2474 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
2475 fprintf(bcftools_stderr, "\n");
2476 fprintf(bcftools_stderr, "Examples:\n");
2477 fprintf(bcftools_stderr, " # normalize and left-align indels\n");
2478 fprintf(bcftools_stderr, " bcftools norm -f ref.fa in.vcf\n");
2479 fprintf(bcftools_stderr, "\n");
2480 fprintf(bcftools_stderr, " # split multi-allelic sites\n");
2481 fprintf(bcftools_stderr, " bcftools norm -m- in.vcf\n");
2482 fprintf(bcftools_stderr, "\n");
2483 bcftools_exit(1);
2484 }
2485
2486 int main_vcfnorm(int argc, char *argv[])
2487 {
2488 int c;
2489 args_t *args = (args_t*) calloc(1,sizeof(args_t));
2490 args->argc = argc; args->argv = argv;
2491 args->files = bcf_sr_init();
2492 args->output_fname = "-";
2493 args->output_type = FT_VCF;
2494 args->n_threads = 0;
2495 args->record_cmd_line = 1;
2496 args->aln_win = 100;
2497 args->buf_win = 1000;
2498 args->mrows_collapse = COLLAPSE_BOTH;
2499 args->do_indels = 1;
2500 args->ma_use_ref_allele = 1;
2501 args->clevel = -1;
2502 int region_is_file = 0;
2503 int targets_is_file = 0;
2504 args->use_star_allele = 1;
2505 args->gff_verbosity = 1;
2506 int regions_overlap = 1;
2507 int targets_overlap = 0;
2508 args->cmp_func = cmp_bcf_pos;
2509
2510 static struct option loptions[] =
2511 {
2512 {"help",no_argument,NULL,'h'},
2513 {"force",no_argument,NULL,7},
2514 {"atomize",no_argument,NULL,'a'},
2515 {"atom-overlaps",required_argument,NULL,11},
2516 {"include",required_argument,NULL,'i'},
2517 {"exclude",required_argument,NULL,'e'},
2518 {"old-rec-tag",required_argument,NULL,12},
2519 {"keep-sum",required_argument,NULL,10},
2520 {"fasta-ref",required_argument,NULL,'f'},
2521 {"sort",required_argument,NULL,'S'},
2522 {"gff-annot",required_argument,NULL,'g'},
2523 {"right-align",no_argument,NULL,15}, // undocumented, only for debugging
2524 {"do-not-normalize",no_argument,NULL,'N'},
2525 {"multiallelics",required_argument,NULL,'m'},
2526 {"multi-overlaps",required_argument,NULL,13},
2527 {"regions",required_argument,NULL,'r'},
2528 {"regions-file",required_argument,NULL,'R'},
2529 {"regions-overlap",required_argument,NULL,1},
2530 {"targets",required_argument,NULL,'t'},
2531 {"targets-file",required_argument,NULL,'T'},
2532 {"targets-overlap",required_argument,NULL,2},
2533 {"site-win",required_argument,NULL,'w'},
2534 {"remove-duplicates",no_argument,NULL,'D'},
2535 {"rm-dup",required_argument,NULL,'d'},
2536 {"output",required_argument,NULL,'o'},
2537 {"output-type",required_argument,NULL,'O'},
2538 {"threads",required_argument,NULL,9},
2539 {"check-ref",required_argument,NULL,'c'},
2540 {"strict-filter",no_argument,NULL,'s'},
2541 {"no-version",no_argument,NULL,8},
2542 {"write-index",optional_argument,NULL,'W'},
2543 {"verbose",required_argument,NULL,'v'},
2544 {NULL,0,NULL,0}
2545 };
2546 char *tmp;
2547 while ((c = getopt_long(argc, argv, "hr:R:f:w:Dd:o:O:c:m:t:T:sNag:W::v:S:i:e:",loptions,NULL)) >= 0) {
2548 switch (c) {
2549 case 10:
2550 // possibly generalize this also to INFO/AD and other tags
2551 if ( strcasecmp("ad",optarg) )
2552 error("Error: only --keep-sum AD is currently supported. See https://github.com/samtools/bcftools/issues/360 for more.\n");
2553 args->keep_sum_ad = 1; // this will be set to the header id or -1 in init_data
2554 break;
2555 case 'g': args->gff_fname = optarg; break;
2556 case 'v':
2557 args->gff_verbosity = atoi(optarg);
2558 if ( args->gff_verbosity<0 || args->gff_verbosity>2 ) error("Error: expected integer 0-2 with -v, --verbose\n");
2559 break;
2560 case 'a': args->atomize = SPLIT; break;
2561 case 'e':
2562 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
2563 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
2564 case 'i':
2565 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
2566 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
2567 case 'S':
2568 if ( !strcasecmp(optarg,"pos") ) args->cmp_func = cmp_bcf_pos;
2569 else if ( !strcasecmp(optarg,"lex") ) args->cmp_func = cmp_bcf_pos_ref_alt;
2570 else error("Error: the sort order --sort %s is not recognised\n",optarg);
2571 break;
2572 case 11 :
2573 if ( optarg[0]=='*' ) args->use_star_allele = 1;
2574 else if ( optarg[0]=='.' ) args->use_star_allele = 0;
2575 else error("Invalid argument to --atom-overlaps. Perhaps you wanted: \"--atom-overlaps '*'\"?\n");
2576 break;
2577 case 12 : args->old_rec_tag = optarg; break;
2578 case 13 :
2579 if ( optarg[0]=='0' ) args->ma_use_ref_allele = 1;
2580 else if ( optarg[0]=='.' ) args->ma_use_ref_allele = 0;
2581 else error("Invalid argument to --multi-overlaps\n");
2582 break;
2583 case 'W':
2584 if (!(args->write_index = write_index_parse(optarg)))
2585 error("Unsupported index format '%s'\n", optarg);
2586 break;
2587 case 15 : args->right_align = 1; break;
2588 case 'N': args->do_indels = 0; break;
2589 case 'd':
2590 if ( !strcmp("snps",optarg) ) args->rmdup = BCF_SR_PAIR_SNPS;
2591 else if ( !strcmp("indels",optarg) ) args->rmdup = BCF_SR_PAIR_INDELS;
2592 else if ( !strcmp("both",optarg) ) args->rmdup = BCF_SR_PAIR_BOTH;
2593 else if ( !strcmp("all",optarg) ) args->rmdup = BCF_SR_PAIR_ANY;
2594 else if ( !strcmp("any",optarg) ) args->rmdup = BCF_SR_PAIR_ANY;
2595 else if ( !strcmp("none",optarg) ) args->rmdup = BCF_SR_PAIR_EXACT;
2596 else if ( !strcmp("exact",optarg) ) args->rmdup = BCF_SR_PAIR_EXACT;
2597 else error("The argument to -d not recognised: %s\n", optarg);
2598 break;
2599 case 'm':
2600 if ( optarg[0]=='-' ) args->mrows_op = MROWS_SPLIT;
2601 else if ( optarg[0]=='+' ) args->mrows_op = MROWS_MERGE;
2602 else error("Expected '+' or '-' with -m\n");
2603 if ( optarg[1]!=0 )
2604 {
2605 if ( !strcmp("snps",optarg+1) ) args->mrows_collapse = COLLAPSE_SNPS;
2606 else if ( !strcmp("indels",optarg+1) ) args->mrows_collapse = COLLAPSE_INDELS;
2607 else if ( !strcmp("both",optarg+1) ) args->mrows_collapse = COLLAPSE_BOTH;
2608 else if ( !strcmp("any",optarg+1) ) args->mrows_collapse = COLLAPSE_ANY;
2609 else error("The argument to -m not recognised: %s\n", optarg);
2610 }
2611 break;
2612 case 'c':
2613 if ( strchr(optarg,'w') ) args->check_ref |= CHECK_REF_WARN;
2614 if ( strchr(optarg,'x') ) args->check_ref |= CHECK_REF_SKIP;
2615 if ( strchr(optarg,'s') ) args->check_ref |= CHECK_REF_FIX;
2616 if ( strchr(optarg,'e') ) args->check_ref = CHECK_REF_EXIT; // overrides the above
2617 break;
2618 case 'O':
2619 switch (optarg[0]) {
2620 case 'b': args->output_type = FT_BCF_GZ; break;
2621 case 'u': args->output_type = FT_BCF; break;
2622 case 'z': args->output_type = FT_VCF_GZ; break;
2623 case 'v': args->output_type = FT_VCF; break;
2624 default:
2625 {
2626 args->clevel = strtol(optarg,&tmp,10);
2627 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
2628 }
2629 }
2630 if ( optarg[1] )
2631 {
2632 args->clevel = strtol(optarg+1,&tmp,10);
2633 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
2634 }
2635 break;
2636 case 'o': args->output_fname = optarg; break;
2637 case 'D':
2638 fprintf(bcftools_stderr,"Warning: `-D` is functional but deprecated, replaced by and alias of `-d none`.\n");
2639 args->rmdup = BCF_SR_PAIR_EXACT;
2640 break;
2641 case 's': args->strict_filter = 1; break;
2642 case 'f': args->ref_fname = optarg; break;
2643 case 'r': args->region = optarg; break;
2644 case 'R': args->region = optarg; region_is_file = 1; break;
2645 case 't': args->targets = optarg; break;
2646 case 'T': args->targets = optarg; targets_is_file = 1; break;
2647 case 'w':
2648 args->buf_win = strtol(optarg,&tmp,10);
2649 if ( *tmp ) error("Could not parse argument: --site-win %s\n", optarg);
2650 break;
2651 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
2652 case 8 : args->record_cmd_line = 0; break;
2653 case 7 : args->force = 1; break;
2654 case 1 :
2655 regions_overlap = parse_overlap_option(optarg);
2656 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
2657 break;
2658 case 2 :
2659 targets_overlap = parse_overlap_option(optarg);
2660 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
2661 break;
2662 case 'h':
2663 case '?': usage(); break;
2664 default: error("Unknown argument: %s\n", optarg);
2665 }
2666 }
2667
2668 char *fname = NULL;
2669 if ( optind>=argc )
2670 {
2671 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
2672 else usage();
2673 }
2674 else fname = argv[optind];
2675
2676 if ( !args->ref_fname && !args->mrows_op && !args->rmdup && args->atomize==NONE ) error("Expected -a, -f, -m, -D or -d option\n");
2677 if ( !args->check_ref && args->ref_fname ) args->check_ref = CHECK_REF_EXIT;
2678 if ( args->check_ref && !args->ref_fname ) error("Expected --fasta-ref with --check-ref\n");
2679
2680 if ( args->region )
2681 {
2682 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
2683 if ( bcf_sr_set_regions(args->files, args->region,region_is_file)<0 )
2684 error("Failed to read the regions: %s\n", args->region);
2685 }
2686 if ( args->targets )
2687 {
2688 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
2689 if ( bcf_sr_set_targets(args->files, args->targets,targets_is_file, 0)<0 )
2690 error("Failed to read the targets: %s\n", args->targets);
2691 }
2692
2693 if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
2694 if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
2695 init_data(args);
2696 normalize_vcf(args);
2697 destroy_data(args);
2698 bcf_sr_destroy(args->files);
2699 free(args);
2700 return 0;
2701 }
2702