Debian Codegraph @

bcftools/vcfnorm.c

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