Debian Codegraph @

bcftools/vcfannotate.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfannotate.c -- Annotate and edit VCF/BCF files.
4
5 Copyright (C) 2013-2024 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include <stdio.h>
28 #include <strings.h>
29 #include <unistd.h>
30 #include <getopt.h>
31 #include <assert.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <dirent.h>
38 #include <math.h>
39 #include <inttypes.h>
40 #include <htslib/vcf.h>
41 #include <htslib/synced_bcf_reader.h>
42 #include <htslib/kseq.h>
43 #include <htslib/khash_str2int.h>
44 #include "bcftools.h"
45 #include "vcmp.h"
46 #include "filter.h"
47 #include "convert.h"
48 #include "smpl_ilist.h"
49 #include "regidx.h"
50 #include "dbuf.h"
51
52 struct _args_t;
53
54 typedef struct _rm_tag_t
55 {
56 char *key;
57 int hdr_id;
58 void (*handler)(struct _args_t *, bcf1_t *, struct _rm_tag_t *);
59 }
60 rm_tag_t;
61
62 typedef struct
63 {
64 char **cols;
65 int ncols, mcols;
66 char **als;
67 int nals, mals;
68 kstring_t line;
69 int rid, start, end;
70 }
71 annot_line_t;
72
73 #define REPLACE_MISSING (1<<0) // -c +TAG .. replace only missing values
74 #define REPLACE_ALL (1<<1) // -c TAG .. replace both missing and existing values
75 #define REPLACE_NON_MISSING (1<<2) // -c -TAG .. replace only if tgt is not missing
76 #define SET_OR_APPEND (1<<3) // -c =TAG .. set new value if missing or non-existent, append otherwise
77 #define MATCH_VALUE (1<<4) // -c ~ID .. do not set, just match the value
78 #define CARRY_OVER_MISSING (1<<5) // -c .TAG .. carry over source missing values as well
79 #define MM_FIRST 0 // if multiple annotation lines overlap a VCF record, use the first, discarding the rest
80 #define MM_APPEND 1 // append, possibly multiple times
81 #define MM_UNIQUE 2 // append, only unique values
82 #define MM_SUM 3
83 #define MM_AVG 4
84 #define MM_MIN 5
85 #define MM_MAX 6
86 #define MM_APPEND_MISSING 7 // missing values will be transferred as well
87 typedef struct _annot_col_t
88 {
89 int icol, replace, number; // number: one of BCF_VL_* types
90 char *hdr_key_src, *hdr_key_dst;
91 // The setters return 0 on successful update of the bcf record, negative value (bcf_update_* return status) on errors,
92 // or 1 on (repeated partial updates) concluded with a src=NULL call
93 int (*setter)(struct _args_t *, bcf1_t *dst, struct _annot_col_t *, void *src); // the last is the annotation line, either src bcf1_t or annot_line_t
94 int (*getter)(struct _args_t *, bcf1_t *src, struct _annot_col_t *, void **ptr, int *mptr);
95 int merge_method; // one of the MM_* defines
96 khash_t(str2int) *mm_str_hash; // lookup table to ensure uniqueness of added string values
97 kstring_t mm_kstr;
98 size_t
99 mm_dbl_nalloc, // the allocated size --merge-logic values array
100 mm_dbl_nused, // the number of used elements in the mm_dbl array
101 mm_dbl_ndat; // the number of merged rows (for calculating the average)
102 double
103 *mm_dbl;
104 void *ptr;
105 int mptr, done;
106 }
107 annot_col_t;
108
109 typedef struct
110 {
111 char *name; // column name
112 int ht_type; // type, one of BCF_HT_STR,BCF_HT_INT,BCF_HT_REAL
113 int icol; // index of the annotation column to use
114 union { // memory area with the current annotation value to pass to filter_test_ext
115 int i;
116 float f;
117 char *s;
118 };
119 }
120 ext_t;
121
122 // Logic of the filters: include or exclude sites which match the filters?
123 #define FLT_INCLUDE 1
124 #define FLT_EXCLUDE 2
125
126 #define MARK_LISTED 1
127 #define MARK_UNLISTED 2
128
129 typedef struct _args_t
130 {
131 bcf_srs_t *files;
132 bcf_hdr_t *hdr, *hdr_out, *tgts_hdr;
133 htsFile *out_fh;
134 int output_type, n_threads, clevel;
135 bcf_sr_regions_t *tgts;
136 char *index_fn;
137 int write_index;
138
139 regidx_t *tgt_idx; // keep everything in memory only with .tab annotation file and -c BEG,END columns
140 regitr_t *tgt_itr;
141 int tgt_is_bed;
142
143 filter_t *filter, *filter_ext; // only one is initialized, the latter contains external values to set dynamically on the fly
144 char *filter_str;
145 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
146 int keep_sites;
147
148 rm_tag_t *rm; // tags scheduled for removal
149 int nrm;
150 int flt_keep_pass; // when all filters removed, reset to PASS
151
152 vcmp_t *vcmp; // for matching annotation and VCF lines by allele
153 annot_line_t *alines; // buffered annotation lines
154 annot_line_t *aline_missing;
155 uint32_t *srt_alines; // sorted indexes (iALT<<16 || iAline)
156 int nalines, malines, nsrt_alines, msrt_alines;
157 int ref_idx, alt_idx, chr_idx, beg_idx, end_idx; // -1 if not present
158 annot_col_t *cols; // column indexes and setters
159 int ncols;
160 int match_id; // set iff `-c ~ID` given, -1 otherwise
161 int match_end; // set iff `-c ~INFO/END` is given, -1 otherwise
162
163 char *set_ids_fmt;
164 convert_t *set_ids;
165 int set_ids_replace;
166
167 // external values for dynamic -i/-e expressions
168 int n_ext;
169 ext_t *ext;
170 void **ext_ptr;
171
172 int nsmpl_annot;
173 int *sample_map, nsample_map, sample_is_file; // map[idst] -> isrc
174 uint8_t *src_smpl_pld, *dst_smpl_pld; // for Number=G format fields
175 int mtmpi, mtmpf, mtmps;
176 int mtmpi2, mtmpf2, mtmps2;
177 int mtmpi3, mtmpf3, mtmps3;
178 int32_t *tmpi, *tmpi2, *tmpi3;
179 float *tmpf, *tmpf2, *tmpf3;
180 char *tmps, *tmps2, **tmpp, **tmpp2;
181 kstring_t tmpks;
182
183 char **argv, *output_fname, *targets_fname, *regions_list, *header_fname;
184 char *remove_annots, *columns, *rename_chrs, *rename_annots, *sample_names, *mark_sites;
185 char **rename_annots_map;
186 char *min_overlap_str;
187 float min_overlap_ann, min_overlap_vcf;
188 int rename_annots_nmap;
189 kstring_t merge_method_str;
190 int argc, drop_header, record_cmd_line, tgts_is_vcf, mark_sites_logic, force, single_overlaps;
191 int columns_is_file, has_append_mode, pair_logic;
192 dbuf_t *header_lines;
193 bcf1_t *current_rec; // current record for local setters
194 }
195 args_t;
196
197 char *msprintf(const char *fmt, ...);
198
199 int parse_with_payload(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr)
200 {
201 args_t *args = (args_t*) usr;
202 int ret = args->tgt_is_bed ? regidx_parse_bed(line, chr_beg, chr_end, beg, end, NULL, NULL) : regidx_parse_tab(line, chr_beg, chr_end, beg, end, NULL, NULL);
203 if ( ret<0 ) return ret;
204 *((char **)payload) = strdup(line);
205 return 0;
206 }
207 void free_payload(void *payload)
208 {
209 char *str = *((char**)payload);
210 free(str);
211 }
212
213 void remove_id(args_t *args, bcf1_t *line, rm_tag_t *tag)
214 {
215 bcf_update_id(args->hdr,line,NULL);
216 }
217 void remove_filter(args_t *args, bcf1_t *line, rm_tag_t *tag)
218 {
219 if ( tag->key && tag->hdr_id<0 )
220 {
221 error("Error: Cannot proceed, not even with the --force option, bad things could happen.\n"
222 " Note that \"bcftools annotate -x FILTER\" can be used to remove ALL filters.\n"
223 " Even better, use \"bcftools view -h\" and \"bcftools reheader\" to fix the header!\n"
224 );
225 }
226 if ( !tag->key ) bcf_update_filter(args->hdr, line, NULL, args->flt_keep_pass);
227 else bcf_remove_filter(args->hdr, line, tag->hdr_id, args->flt_keep_pass);
228 }
229 void remove_qual(args_t *args, bcf1_t *line, rm_tag_t *tag)
230 {
231 bcf_float_set_missing(line->qual);
232 }
233 void remove_info(args_t *args, bcf1_t *line, rm_tag_t *tag)
234 {
235 // remove all INFO fields
236 if ( !(line->unpacked & BCF_UN_INFO) ) bcf_unpack(line, BCF_UN_INFO);
237
238 int i;
239 for (i=0; i<line->n_info; i++)
240 {
241 bcf_info_t *inf = &line->d.info[i];
242 if ( !strcmp("END",bcf_hdr_int2id(args->hdr,BCF_DT_ID,inf->key)) )
243 line->rlen = line->n_allele ? strlen(line->d.allele[0]) : 0;
244 if ( inf->vptr_free )
245 {
246 free(inf->vptr - inf->vptr_off);
247 inf->vptr_free = 0;
248 }
249 line->d.shared_dirty |= BCF1_DIRTY_INF;
250 inf->vptr = NULL;
251 inf->vptr_off = inf->vptr_len = 0;
252 }
253 }
254 void remove_info_tag(args_t *args, bcf1_t *line, rm_tag_t *tag)
255 {
256 bcf_update_info(args->hdr, line, tag->key, NULL, 0, BCF_HT_INT); // the type does not matter with n=0
257 }
258 void remove_format_tag(args_t *args, bcf1_t *line, rm_tag_t *tag)
259 {
260 bcf_update_format(args->hdr, line, tag->key, NULL, 0, BCF_HT_INT); // the type does not matter with n=0
261 }
262 void remove_format(args_t *args, bcf1_t *line, rm_tag_t *tag)
263 {
264 // remove all FORMAT fields except GT
265 if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
266
267 int i;
268 for (i=0; i<line->n_fmt; i++)
269 {
270 bcf_fmt_t *fmt = &line->d.fmt[i];
271 const char *key = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
272 if ( key[0]=='G' && key[1]=='T' && !key[2] ) continue;
273
274 if ( fmt->p_free )
275 {
276 free(fmt->p - fmt->p_off);
277 fmt->p_free = 0;
278 }
279 line->d.indiv_dirty = 1;
280 fmt->p = NULL;
281 }
282 }
283
284 #include "htslib/khash.h"
285 KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
286 typedef khash_t(vdict) vdict_t;
287
288 static void remove_hdr_lines(bcf_hdr_t *hdr, int type)
289 {
290 int i = 0, nrm = 0;
291 while ( i<hdr->nhrec )
292 {
293 if ( hdr->hrec[i]->type!=type ) { i++; continue; }
294 bcf_hrec_t *hrec = hdr->hrec[i];
295 if ( type==BCF_HL_FMT || type==BCF_HL_INFO || type==BCF_HL_FMT || type== BCF_HL_CTG )
296 {
297 // everything except FORMAT/GT
298 int id = bcf_hrec_find_key(hrec, "ID");
299 if ( id>=0 )
300 {
301 if ( type==BCF_HL_FMT && !strcmp(hrec->vals[id],"GT") ) { i++; continue; }
302 vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
303 khint_t k = kh_get(vdict, d, hdr->hrec[i]->vals[id]);
304 kh_val(d, k).hrec[type==BCF_HL_CTG?0:type] = NULL;
305 kh_val(d, k).info[type] |= 0xf;
306 }
307 }
308 nrm++;
309 hdr->nhrec--;
310 if ( i < hdr->nhrec )
311 memmove(&hdr->hrec[i],&hdr->hrec[i+1],(hdr->nhrec-i)*sizeof(bcf_hrec_t*));
312 bcf_hrec_destroy(hrec);
313 }
314 if ( nrm ) {
315 if (bcf_hdr_sync(hdr) < 0)
316 error_errno("[%s] Failed to update header", __func__);
317 }
318 }
319
320 static void init_remove_annots(args_t *args)
321 {
322 int keep_info = 0, keep_fmt = 0, keep_flt = 0;
323 void *keep = khash_str2int_init();
324 kstring_t str = {0,0,0};
325 char *ss = args->remove_annots;
326
327 int i, ntags, needs_info = 0;
328 if ( args->set_ids )
329 {
330 const char **tags = convert_list_used_tags(args->set_ids,&ntags);
331 for (i=0; i<ntags; i++)
332 if ( !strncmp("INFO/",tags[i],4) ) needs_info = 1;
333 }
334
335 while ( *ss )
336 {
337 args->nrm++;
338 args->rm = (rm_tag_t*) realloc(args->rm,sizeof(rm_tag_t)*args->nrm);
339 rm_tag_t *tag = &args->rm[args->nrm-1];
340 tag->key = NULL;
341
342 int type = BCF_HL_GEN;
343 if ( !strncasecmp("INFO/",ss,5) ) { type = BCF_HL_INFO; ss += 5; }
344 else if ( !strncasecmp("INF/",ss,4) ) { type = BCF_HL_INFO; ss += 4; }
345 else if ( !strncasecmp("FORMAT/",ss,7) ) { type = BCF_HL_FMT; ss += 7; }
346 else if ( !strncasecmp("FMT/",ss,4) ) { type = BCF_HL_FMT; ss += 4; }
347 else if ( !strncasecmp("FILTER/",ss,7) ) { type = BCF_HL_FLT; ss += 7; }
348 else if ( !strncasecmp("^INFO/",ss,6) ) { type = BCF_HL_INFO; ss += 6; keep_info = 1; }
349 else if ( !strncasecmp("^INF/",ss,5) ) { type = BCF_HL_INFO; ss += 5; keep_info = 1; }
350 else if ( !strncasecmp("^FORMAT/",ss,8) ) { type = BCF_HL_FMT; ss += 8; keep_fmt = 1; }
351 else if ( !strncasecmp("^FMT/",ss,5) ) { type = BCF_HL_FMT; ss += 5; keep_fmt = 1; }
352 else if ( !strncasecmp("^FILTER/",ss,8) ) { type = BCF_HL_FLT; ss += 8; keep_flt = 1; }
353
354 char *se = ss;
355 while ( *se && *se!=',' ) se++;
356 str.l = 0;
357 kputsn(ss, se-ss, &str);
358
359 if ( type==BCF_HL_FLT )
360 {
361 if ( !keep_flt )
362 {
363 args->flt_keep_pass = 1;
364 tag->handler = remove_filter;
365 tag->key = strdup(str.s);
366 tag->hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, tag->key);
367 if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FLT,tag->hdr_id) )
368 {
369 if ( args->keep_sites )
370 error("Error: The filter \"%s\" is not defined in the header, cannot use the -k option\n", str.s);
371 else
372 fprintf(bcftools_stderr,"Warning: The filter \"%s\" is not defined in the header\n", str.s);
373 }
374 else if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,BCF_HL_FLT,tag->key);
375 }
376 else
377 {
378 int value, ret = khash_str2int_get(keep, str.s, &value);
379 if ( ret==-1 ) khash_str2int_set(keep, strdup(str.s),1<<BCF_HL_FLT);
380 else khash_str2int_set(keep, str.s, value | 1<<BCF_HL_FLT);
381 args->nrm--;
382 }
383 }
384 else if ( type!=BCF_HL_GEN )
385 {
386 int id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,str.s);
387 if ( !bcf_hdr_idinfo_exists(args->hdr,type,id) )
388 {
389 if ( args->keep_sites )
390 error("Error: The tag \"%s\" is not defined in the header, cannot use the -k option\n", str.s);
391 else
392 fprintf(bcftools_stderr,"Warning: The tag \"%s\" not defined in the header\n", str.s);
393
394 tag->key = strdup(str.s);
395 if ( type==BCF_HL_INFO )
396 {
397 tag->handler = remove_info_tag;
398 if ( needs_info ) error("Error: `--remove INFO/%s` is executed first, cannot combine with `--set-id %s`\n",tag->key,args->set_ids_fmt);
399 }
400 else if ( type==BCF_HL_FMT ) tag->handler = remove_format_tag;
401 }
402 else if ( (type==BCF_HL_FMT && keep_fmt) || (type==BCF_HL_INFO && keep_info) )
403 {
404 int value, ret = khash_str2int_get(keep, str.s, &value);
405 if ( ret==-1 ) khash_str2int_set(keep, strdup(str.s),1<<type);
406 else khash_str2int_set(keep, str.s, value | 1<<type);
407 args->nrm--;
408 }
409 else
410 {
411 tag->key = strdup(str.s);
412 if ( type==BCF_HL_INFO )
413 {
414 tag->handler = remove_info_tag;
415 if ( needs_info ) error("Error: `--remove INFO/%s` is executed first, cannot combine with `--set-id %s`\n",tag->key,args->set_ids_fmt);
416 }
417 else if ( type==BCF_HL_FMT ) tag->handler = remove_format_tag;
418 if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,type,tag->key);
419 }
420 }
421 else if ( !strcasecmp("ID",str.s) ) tag->handler = remove_id;
422 else if ( !strcasecmp("FILTER",str.s) )
423 {
424 tag->handler = remove_filter;
425 if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_FLT);
426 }
427 else if ( !strcasecmp("QUAL",str.s) ) tag->handler = remove_qual;
428 else if ( !strcasecmp("INFO",str.s) )
429 {
430 if ( needs_info ) error("Error: `--remove INFO` is executed first, cannot combine with `--set-id %s`\n",args->set_ids_fmt);
431 tag->handler = remove_info;
432 if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_INFO);
433 }
434 else if ( !strcasecmp("FMT",str.s) || !strcasecmp("FORMAT",str.s) )
435 {
436 tag->handler = remove_format;
437 if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_FMT);
438 }
439 else if ( str.l )
440 {
441 int id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, str.s);
442 if ( bcf_hdr_idinfo_exists(args->hdr,BCF_HL_INFO,id) ) error("Error: did you mean INFO/%s?\n",str.s);
443 if ( bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FMT,id) ) error("Error: did you mean FORMAT/%s?\n",str.s);
444
445 if ( !args->keep_sites )
446 {
447 if ( str.s[0]=='#' && str.s[1]=='#' )
448 bcf_hdr_remove(args->hdr_out,BCF_HL_GEN,str.s+2);
449 else
450 bcf_hdr_remove(args->hdr_out,BCF_HL_STR,str.s);
451 }
452 args->nrm--;
453 }
454
455 ss = *se ? se+1 : se;
456 }
457 free(str.s);
458 if ( keep_flt || keep_info || keep_fmt )
459 {
460 int j;
461 for (j=0; j<args->hdr->nhrec; j++)
462 {
463 bcf_hrec_t *hrec = args->hdr->hrec[j];
464 if ( hrec->type!=BCF_HL_FLT && hrec->type!=BCF_HL_INFO && hrec->type!=BCF_HL_FMT ) continue;
465 if ( !keep_flt && hrec->type==BCF_HL_FLT ) continue;
466 if ( !keep_info && hrec->type==BCF_HL_INFO ) continue;
467 if ( !keep_fmt && hrec->type==BCF_HL_FMT ) continue;
468 int k = bcf_hrec_find_key(hrec,"ID");
469 assert( k>=0 ); // this should always be true for valid VCFs
470 int value, ret = khash_str2int_get(keep,hrec->vals[k],&value);
471 if ( ret==0 && value>>hrec->type ) // keep
472 {
473 if ( hrec->type==BCF_HL_FLT && !strcmp("PASS",hrec->vals[k]) ) args->flt_keep_pass = 1;
474 continue;
475 }
476 args->nrm++;
477 args->rm = (rm_tag_t*) realloc(args->rm,sizeof(rm_tag_t)*args->nrm);
478 rm_tag_t *tag = &args->rm[args->nrm-1];
479 if ( hrec->type==BCF_HL_INFO ) tag->handler = remove_info_tag;
480 else if ( hrec->type==BCF_HL_FMT ) tag->handler = remove_format_tag;
481 else
482 {
483 tag->handler = remove_filter;
484 tag->hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, hrec->vals[k]);
485 }
486 tag->key = strdup(hrec->vals[k]);
487 if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,hrec->type,tag->key);
488 }
489 }
490 khash_str2int_destroy_free(keep);
491 if ( !args->nrm ) error("No matching tag in -x %s\n", args->remove_annots);
492 if (bcf_hdr_sync(args->hdr_out) < 0)
493 error_errno("[%s] Failed to update header", __func__);
494 }
495 static void init_header_lines(args_t *args)
496 {
497 if ( args->header_fname )
498 {
499 htsFile *file = hts_open(args->header_fname, "rb");
500 if ( !file ) error("Error reading %s\n", args->header_fname);
501 kstring_t str = {0,0,0};
502 while ( hts_getline(file, KS_SEP_LINE, &str) > 0 )
503 {
504 if ( bcf_hdr_append(args->hdr_out,str.s) ) error("Could not parse %s: %s\n", args->header_fname, str.s);
505 bcf_hdr_append(args->hdr,str.s); // the input file may not have the header line if run with -h (and nothing else)
506 }
507 if ( hts_close(file)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->header_fname);
508 free(str.s);
509 }
510 if ( args->header_lines )
511 {
512 int i, n = dbuf_n(args->header_lines);
513 for (i=0; i<n; i++)
514 {
515 char *line = dbuf_ith(args->header_lines,i);
516 if ( bcf_hdr_append(args->hdr_out,line) ) error("Could not parse the header line: %s\n", line);
517 bcf_hdr_append(args->hdr,line); // the input file may not have the header line if run with -H (and nothing else)
518 }
519 dbuf_destroy_free(args->header_lines);
520 args->header_lines = NULL;
521 }
522 if (bcf_hdr_sync(args->hdr_out) < 0)
523 error_errno("[%s] Failed to update output header", __func__);
524 if (bcf_hdr_sync(args->hdr) < 0)
525 error_errno("[%s] Failed to update input header", __func__);
526 }
527 static int vcf_getter_info_str2str(args_t *args, bcf1_t *rec, annot_col_t *col, void **ptr, int *mptr)
528 {
529 return bcf_get_info_string(args->tgts_hdr,rec,col->hdr_key_src,ptr,mptr);
530 }
531 static int vcf_getter_id2str(args_t *args, bcf1_t *rec, annot_col_t *col, void **ptr, int *mptr)
532 {
533 char *str = *((char**)ptr);
534 int i, len = strlen(rec->d.id);
535 if ( len >= *mptr ) str = realloc(str, len+1);
536 for (i=0; i<len; i++)
537 str[i] = rec->d.id[i]==';' ? ',' : rec->d.id[i];
538 str[len] = 0;
539 *((char**)ptr) = str;
540 *mptr = len+1;
541 return len;
542 }
543 inline static int vcf_getter_filter2str_core(bcf_hdr_t *hdr, bcf1_t *rec, char **ptr, int *mptr)
544 {
545 if ( !(rec->unpacked & BCF_UN_FLT) ) bcf_unpack(rec, BCF_UN_FLT);
546
547 kstring_t str;
548 str.s = *ptr;
549 str.m = *mptr;
550 str.l = 0;
551
552 int i;
553 if ( rec->d.n_flt )
554 {
555 for (i=0; i<rec->d.n_flt; i++)
556 {
557 if (i) kputc(',', &str);
558 kputs(bcf_hdr_int2id(hdr,BCF_DT_ID,rec->d.flt[i]), &str);
559 }
560 }
561 else kputc('.', &str);
562
563 *ptr = str.s;
564 *mptr = str.m;
565 return str.l;
566 }
567 static int vcf_getter_filter2str_local(args_t *args, bcf1_t *rec, annot_col_t *col, void **ptr, int *mptr)
568 {
569 return vcf_getter_filter2str_core(args->hdr_out, args->current_rec, (char**)ptr, mptr);
570 }
571 static int vcf_getter_filter2str(args_t *args, bcf1_t *rec, annot_col_t *col, void **ptr, int *mptr)
572 {
573 return vcf_getter_filter2str_core(args->tgts_hdr, rec, (char**)ptr, mptr);
574 }
575 static int setter_filter(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
576 {
577 if ( !data ) error("Error: the --merge-logic option cannot be used with FILTER (yet?)\n");
578
579 // note: so far this works only with one filter, not a list of filters
580 annot_line_t *tab = (annot_line_t*) data;
581 if ( tab->cols[col->icol][0]=='.' && !tab->cols[col->icol][1] ) // don't overwrite with a missing value unless asked
582 {
583 if ( (col->replace & CARRY_OVER_MISSING) && (col->replace & (REPLACE_ALL|REPLACE_NON_MISSING)) ) bcf_update_filter(args->hdr_out,line,NULL,0);
584 return 0;
585 }
586 hts_expand(int,1,args->mtmpi,args->tmpi);
587 args->tmpi[0] = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, tab->cols[col->icol]);
588 if ( args->tmpi[0]<0 ) error("The FILTER \"%s\" is not defined in the header, was the -h option provided?\n", tab->cols[col->icol]);
589 if ( col->replace & SET_OR_APPEND ) return bcf_add_filter(args->hdr_out,line,args->tmpi[0]);
590 if ( !(col->replace & REPLACE_MISSING) )
591 {
592 bcf_update_filter(args->hdr_out,line,NULL,0);
593 return bcf_update_filter(args->hdr_out,line,args->tmpi,1);
594 }
595
596 // only update missing FILTER
597 if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
598 if ( !line->d.n_flt )
599 return bcf_update_filter(args->hdr_out,line,args->tmpi,1);
600
601 return 0;
602 }
603 static int vcf_setter_filter(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
604 {
605 int i, ret = 0;
606 bcf1_t *rec = (bcf1_t*) data;
607 if ( !(rec->unpacked & BCF_UN_FLT) ) bcf_unpack(rec, BCF_UN_FLT);
608 if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
609 if ( !rec->d.n_flt ) // don't overwrite with a missing value unless asked
610 {
611 if ( (col->replace & CARRY_OVER_MISSING) && (col->replace & (REPLACE_ALL|REPLACE_NON_MISSING)) ) bcf_update_filter(args->hdr_out,line,NULL,0);
612 return 0;
613 }
614 if ( col->replace & (SET_OR_APPEND|REPLACE_MISSING) )
615 {
616 if ( (col->replace & REPLACE_MISSING) && line->d.n_flt ) return 0; // only update missing FILTER
617 for (i=0; i<rec->d.n_flt; i++)
618 {
619 const char *flt = bcf_hdr_int2id(args->files->readers[1].header, BCF_DT_ID, rec->d.flt[i]);
620 if ( bcf_add_filter(args->hdr_out,line,bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, flt)) < 0 ) ret = -1;
621 }
622 return ret;
623 }
624 hts_expand(int,rec->d.n_flt,args->mtmpi,args->tmpi);
625 for (i=0; i<rec->d.n_flt; i++)
626 {
627 const char *flt = bcf_hdr_int2id(args->files->readers[1].header, BCF_DT_ID, rec->d.flt[i]);
628 args->tmpi[i] = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, flt);
629 }
630 bcf_update_filter(args->hdr_out,line,NULL,0);
631 return bcf_update_filter(args->hdr_out,line,args->tmpi,rec->d.n_flt);
632 }
633 static int setter_pos(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
634 {
635 annot_line_t *tab = (annot_line_t*) data;
636 if ( tab->cols[col->icol] && tab->cols[col->icol][0]=='.' && !tab->cols[col->icol][1] ) return 0; // don't replace with "."
637 char *tmp;
638 int pos = strtol(tab->cols[col->icol], &tmp, 10);
639 if ( tmp==tab->cols[col->icol] )
640 error("Could not parse -POS at %s:%"PRId64" .. [%s]\n",bcf_seqname(args->hdr,line),(int64_t)line->pos+1,tab->cols[col->icol]);
641 line->pos = pos - 1;
642 return 0;
643 }
644 static int setter_id(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
645 {
646 if ( !data ) error("Error: the --merge-logic option cannot be used with ID (yet?)\n");
647 if ( col->replace & MATCH_VALUE ) return 0;
648
649 // possible cases:
650 // IN ANNOT OUT ACHIEVED_BY
651 // x y x -c +ID
652 // x y y -c ID
653 // x y x,y -c =ID
654 // x . x -c +ID, ID
655 // x . . -x ID
656 // . y y -c +ID, -c ID
657 //
658 annot_line_t *tab = (annot_line_t*) data;
659 if ( tab->cols[col->icol] && tab->cols[col->icol][0]=='.' && !tab->cols[col->icol][1] ) return 0; // don't replace with "."
660 if ( col->replace & SET_OR_APPEND ) return bcf_add_id(args->hdr_out,line,tab->cols[col->icol]);
661 if ( !(col->replace & REPLACE_MISSING) ) return bcf_update_id(args->hdr_out,line,tab->cols[col->icol]);
662
663 // running with +ID, only update missing ids
664 if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) )
665 return bcf_update_id(args->hdr_out,line,tab->cols[col->icol]);
666 return 0;
667 }
668 static int vcf_setter_id(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
669 {
670 if ( col->replace & MATCH_VALUE ) return 0;
671
672 bcf1_t *rec = (bcf1_t*) data;
673
674 char *id;
675 if ( col->getter )
676 {
677 int nret = col->getter(args,rec,col,&col->ptr,&col->mptr);
678 id = (char*) col->ptr;
679 if ( nret<=0 || (nret==1 && *id=='.') ) return 0; // don't replace with "."
680 }
681 else
682 {
683 if ( rec->d.id && rec->d.id[0]=='.' && !rec->d.id[1] ) return 0; // don't replace with "."
684 id = rec->d.id;
685 }
686 if ( col->replace & SET_OR_APPEND ) return bcf_add_id(args->hdr_out,line,id);
687 if ( !(col->replace & REPLACE_MISSING) ) return bcf_update_id(args->hdr_out,line,id);
688
689 // running with +ID, only update missing ids
690 if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) )
691 return bcf_update_id(args->hdr_out,line,id);
692 return 0;
693 }
694 static int vcf_setter_ref(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
695 {
696 bcf1_t *rec = (bcf1_t*) data;
697 if ( !strcmp(rec->d.allele[0],line->d.allele[0]) ) return 0; // no update necessary
698 const char **als = (const char**) malloc(sizeof(char*)*line->n_allele);
699 als[0] = rec->d.allele[0];
700 int i;
701 for (i=1; i<line->n_allele; i++) als[i] = line->d.allele[i];
702 int ret = bcf_update_alleles(args->hdr_out, line, als, line->n_allele);
703 free(als);
704 return ret;
705 }
706 static int vcf_setter_alt(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
707 {
708 bcf1_t *rec = (bcf1_t*) data;
709 int i;
710 if ( line->n_allele>1 && (col->replace & REPLACE_MISSING) ) return 0;
711 if ( rec->n_allele==line->n_allele )
712 {
713 for (i=1; i<rec->n_allele; i++) if ( strcmp(rec->d.allele[i],line->d.allele[i]) ) break;
714 if ( i==rec->n_allele ) return 0; // no update necessary
715 }
716 const char **als = (const char**) malloc(sizeof(char*)*rec->n_allele);
717 als[0] = line->d.allele[0];
718 for (i=1; i<rec->n_allele; i++) als[i] = rec->d.allele[i];
719 int ret = bcf_update_alleles(args->hdr_out, line, als, rec->n_allele);
720 free(als);
721 return ret;
722 }
723 static int setter_qual(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
724 {
725 if ( !data ) error("Error: the --merge-logic option cannot be used with QUAL (yet?)\n");
726
727 annot_line_t *tab = (annot_line_t*) data;
728 char *str = tab->cols[col->icol];
729 if ( str[0]=='.' && str[1]==0 ) // don't overwrite with a missing value unless asked
730 {
731 if ( (col->replace & CARRY_OVER_MISSING) && (col->replace & (REPLACE_ALL|REPLACE_NON_MISSING)) ) bcf_float_set_missing(line->qual);
732 return 0;
733 }
734 if ( (col->replace & REPLACE_MISSING) && !bcf_float_is_missing(line->qual) ) return 0;
735
736 line->qual = strtod(str, &str);
737 if ( str == tab->cols[col->icol] )
738 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
739 return 0;
740 }
741 static int vcf_setter_qual(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
742 {
743 bcf1_t *rec = (bcf1_t*) data;
744 if ( bcf_float_is_missing(rec->qual) ) // don't overwrite with a missing value unless asked
745 {
746 if ( (col->replace & CARRY_OVER_MISSING) && (col->replace & (REPLACE_ALL|REPLACE_NON_MISSING)) ) bcf_float_set_missing(line->qual);
747 return 0;
748 }
749 if ( (col->replace & REPLACE_MISSING) && !bcf_float_is_missing(line->qual) ) return 0;
750 line->qual = rec->qual;
751 return 0;
752 }
753 static int setter_info_flag(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
754 {
755 if ( !data ) error("Error: the --merge-logic option cannot be used with INFO type=Flag (yet?)\n");
756
757 annot_line_t *tab = (annot_line_t*) data;
758 char *str = tab->cols[col->icol];
759 if ( str[0]=='.' && str[1]==0 ) // don't overwrite with a missing value unless asked
760 {
761 if ( (col->replace & CARRY_OVER_MISSING) && (col->replace & (REPLACE_ALL|REPLACE_NON_MISSING)) ) bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,0);
762 return 0;
763 }
764
765 if ( str[0]=='1' && str[1]==0 ) return bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,1);
766 if ( str[0]=='0' && str[1]==0 ) return bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,0);
767 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
768 return -1;
769 }
770 static int vcf_setter_info_flag(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
771 {
772 bcf1_t *rec = (bcf1_t*) data;
773 int flag = bcf_get_info_flag(args->files->readers[1].header,rec,col->hdr_key_src,NULL,NULL);
774 bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,flag);
775 return 0;
776 }
777 static int setter_ARinfo_int32(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als, int ntmpi)
778 {
779 if ( col->number==BCF_VL_A && ntmpi!=nals-1 && (ntmpi!=1 || args->tmpi[0]!=bcf_int32_missing || args->tmpi[1]!=bcf_int32_vector_end) )
780 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpi,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
781 else if ( col->number==BCF_VL_R && ntmpi!=nals && (ntmpi!=1 || args->tmpi[0]!=bcf_int32_missing || args->tmpi[1]!=bcf_int32_vector_end) )
782 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpi,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
783
784 int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
785 int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
786 if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
787
788 // fill in any missing values in the target VCF (or all, if not present)
789 int ntmpi2 = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
790 if ( ntmpi2 < ndst ) hts_expand(int32_t,ndst,args->mtmpi2,args->tmpi2);
791
792 int i;
793 for (i=0; i<ndst; i++)
794 {
795 if ( map[i]<0 )
796 {
797 if ( ntmpi2 < ndst ) args->tmpi2[i] = bcf_int32_missing;
798 continue;
799 }
800 if ( ntmpi2==ndst && (col->replace & REPLACE_MISSING)
801 && args->tmpi2[i]!=bcf_int32_missing
802 && args->tmpi2[i]!=bcf_int32_vector_end ) continue;
803
804 args->tmpi2[i] = args->tmpi[ map[i] ];
805 }
806 return bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,ndst);
807 }
808 static int setter_info_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
809 {
810 annot_line_t *tab = (annot_line_t*) data;
811
812 // This is a bit hacky, only to reuse existing code with minimal changes:
813 // -c =TAG will now behave as -l TAG:APPEND for integers
814 if ( col->replace & SET_OR_APPEND ) col->merge_method=MM_APPEND;
815
816 if ( !tab )
817 {
818 if ( col->merge_method!=MM_SUM && col->merge_method!=MM_AVG &&
819 col->merge_method!=MM_MIN && col->merge_method!=MM_MAX &&
820 col->merge_method!=MM_APPEND &&
821 col->merge_method!=MM_APPEND_MISSING )
822 error("Error: at the moment only the sum,avg,min,max,append,append-missing options are supported with --merge-logic for INFO type=Integer\n");
823 }
824
825 int i,ntmpi = 0;
826 if ( (col->replace & SET_OR_APPEND) && !col->mm_dbl_nused )
827 {
828 ntmpi = bcf_get_info_int32(args->hdr, line, col->hdr_key_dst, &args->tmpi, &args->mtmpi);
829 if ( ntmpi>0 && (args->tmpi[0]!=bcf_int32_missing || (col->replace & CARRY_OVER_MISSING)) )
830 {
831 col->mm_dbl_nused = col->mm_dbl_ndat = ntmpi;
832 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
833 for (i=0; i<ntmpi; i++)
834 col->mm_dbl[i] = args->tmpi[i];
835 col->mm_dbl_ndat = 1;
836 }
837 ntmpi = 0;
838 }
839 if ( tab ) // has data, not flushing yet
840 {
841 char *str = tab->cols[col->icol], *end = str;
842 if ( str[0]=='.' && str[1]==0 && col->merge_method!=MM_APPEND_MISSING && !(col->replace & CARRY_OVER_MISSING) ) return 1;
843
844 while ( *end )
845 {
846 ntmpi++;
847 hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
848 if ( str[0]=='.' && (str[1]==0 || str[1]==',') )
849 {
850 if ( col->merge_method==MM_APPEND_MISSING || (col->replace & CARRY_OVER_MISSING) )
851 args->tmpi[ntmpi-1] = bcf_int32_missing;
852 else
853 ntmpi--;
854 if ( str[1]==0 ) end = str+1;
855 str += 2;
856 }
857 else
858 {
859 args->tmpi[ntmpi-1] = strtol(str, &end, 10);
860 if ( end==str )
861 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
862 str = end+1;
863 }
864 }
865 if ( col->merge_method!=MM_FIRST )
866 {
867 if ( !col->mm_dbl_nused )
868 {
869 col->mm_dbl_nused = ntmpi;
870 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
871 for (i=0; i<ntmpi; i++)
872 col->mm_dbl[i] = args->tmpi[i];
873 }
874 else
875 {
876 if ( col->merge_method==MM_APPEND || col->merge_method==MM_APPEND_MISSING )
877 {
878 int nori = col->mm_dbl_nused;
879 col->mm_dbl_nused += ntmpi;
880 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
881 for (i=0; i<ntmpi; i++)
882 col->mm_dbl[i+nori] = args->tmpi[i];
883 }
884 else
885 {
886 if ( ntmpi!=col->mm_dbl_nused ) error("Error: cannot merge fields of unequal length\n");
887 if ( col->merge_method==MM_SUM || col->merge_method==MM_AVG )
888 for (i=0; i<ntmpi; i++) col->mm_dbl[i] += args->tmpi[i];
889 else if ( col->merge_method==MM_MIN )
890 for (i=0; i<ntmpi; i++) { if ( col->mm_dbl[i] > args->tmpi[i] ) col->mm_dbl[i] = args->tmpi[i]; }
891 else if ( col->merge_method==MM_MAX )
892 for (i=0; i<ntmpi; i++) { if ( col->mm_dbl[i] < args->tmpi[i] ) col->mm_dbl[i] = args->tmpi[i]; }
893 }
894 }
895 col->mm_dbl_ndat++;
896 return 1;
897 }
898 }
899 else if ( col->merge_method==MM_SUM || col->merge_method==MM_MIN || col->merge_method==MM_MAX || col->merge_method==MM_APPEND || col->merge_method==MM_APPEND_MISSING )
900 {
901 ntmpi = col->mm_dbl_nused;
902 hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
903 for (i=0; i<ntmpi; i++) args->tmpi[i] = col->mm_dbl[i];
904 col->mm_dbl_nused = col->mm_dbl_ndat = 0;
905 }
906 else if ( col->merge_method==MM_AVG )
907 {
908 ntmpi = col->mm_dbl_nused;
909 hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
910 for (i=0; i<ntmpi; i++) args->tmpi[i] = col->mm_dbl[i]/col->mm_dbl_ndat;
911 col->mm_dbl_nused = col->mm_dbl_ndat = 0;
912 }
913
914 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
915 return setter_ARinfo_int32(args,line,col,tab->nals,tab->als,ntmpi);
916
917 if ( col->replace & REPLACE_MISSING )
918 {
919 int ret = bcf_get_info_int32(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
920 if ( ret>0 && args->tmpi2[0]!=bcf_int32_missing ) return 0;
921 }
922 return bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi,ntmpi);
923 }
924 static int vcf_setter_info_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
925 {
926 bcf1_t *rec = (bcf1_t*) data;
927 int ntmpi = bcf_get_info_int32(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpi,&args->mtmpi);
928 if ( ntmpi < 0 ) return 0; // nothing to add
929
930 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
931 return setter_ARinfo_int32(args,line,col,rec->n_allele,rec->d.allele,ntmpi);
932
933 if ( col->replace & REPLACE_MISSING )
934 {
935 int ret = bcf_get_info_int32(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
936 if ( ret>0 && args->tmpi2[0]!=bcf_int32_missing ) return 0;
937 }
938
939 return bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi,ntmpi);
940 }
941 static int setter_ARinfo_real(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als, int ntmpf)
942 {
943 if ( col->number==BCF_VL_A && ntmpf!=nals-1 && (ntmpf!=1 || !bcf_float_is_missing(args->tmpf[0]) || !bcf_float_is_vector_end(args->tmpf[0])) )
944 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpf,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
945 else if ( col->number==BCF_VL_R && ntmpf!=nals && (ntmpf!=1 || !bcf_float_is_missing(args->tmpf[0]) || !bcf_float_is_vector_end(args->tmpf[0])) )
946 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpf,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
947
948 int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
949 int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
950 if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
951
952 // fill in any missing values in the target VCF (or all, if not present)
953 int ntmpf2 = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
954 if ( ntmpf2 < ndst ) hts_expand(float,ndst,args->mtmpf2,args->tmpf2);
955
956 int i;
957 for (i=0; i<ndst; i++)
958 {
959 if ( map[i]<0 )
960 {
961 if ( ntmpf2 < ndst ) bcf_float_set_missing(args->tmpf2[i]);
962 continue;
963 }
964 if ( ntmpf2==ndst && (col->replace & REPLACE_MISSING)
965 && !bcf_float_is_missing(args->tmpf2[i])
966 && !bcf_float_is_vector_end(args->tmpf2[i]) ) continue;
967
968 args->tmpf2[i] = args->tmpf[ map[i] ];
969 }
970 return bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,ndst);
971 }
972 static int setter_info_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
973 {
974 annot_line_t *tab = (annot_line_t*) data;
975
976 // This is a bit hacky, only to reuse existing code with minimal changes:
977 // -c =TAG will now behave as -l TAG:APPEND for floats
978 if ( col->replace & SET_OR_APPEND ) col->merge_method=MM_APPEND;
979
980 if ( !tab )
981 {
982 if ( col->merge_method!=MM_SUM && col->merge_method!=MM_AVG &&
983 col->merge_method!=MM_MIN && col->merge_method!=MM_MAX &&
984 col->merge_method!=MM_APPEND &&
985 col->merge_method!=MM_APPEND_MISSING )
986 error("Error: at the moment only the sum,avg,min,max,append,append-missing options are supported with --merge-logic for INFO type=Float\n");
987 }
988
989 int i,ntmpf = 0;
990 if ( (col->replace & SET_OR_APPEND) && !col->mm_dbl_nused )
991 {
992 ntmpf = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf, &args->mtmpf);
993 if ( ntmpf>0 && (!bcf_float_is_missing(args->tmpf[0]) || (col->replace & CARRY_OVER_MISSING)) )
994 {
995 col->mm_dbl_nused = ntmpf;
996 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
997 for (i=0; i<ntmpf; i++)
998 if ( bcf_float_is_missing(args->tmpf[i]) )
999 bcf_double_set_missing(col->mm_dbl[i]);
1000 else
1001 col->mm_dbl[i] = args->tmpf[i];
1002 col->mm_dbl_ndat = 1;
1003 }
1004 ntmpf = 0;
1005 }
1006 if ( tab ) // data row, not just flushing
1007 {
1008 char *str = tab->cols[col->icol], *end = str;
1009 if ( str[0]=='.' && str[1]==0 && col->merge_method!=MM_APPEND_MISSING && !(col->replace & CARRY_OVER_MISSING) ) return 1;
1010
1011 while ( *end )
1012 {
1013 ntmpf++;
1014 hts_expand(float,ntmpf,args->mtmpf,args->tmpf);
1015 if ( str[0]=='.' && (str[1]==0 || str[1]==',') )
1016 {
1017 if ( col->merge_method==MM_APPEND_MISSING || (col->replace & CARRY_OVER_MISSING) )
1018 bcf_float_set_missing(args->tmpf[ntmpf-1]);
1019 else
1020 ntmpf--;
1021 if ( str[1]==0 ) end = str+1;
1022 str += 2;
1023 }
1024 else
1025 {
1026 args->tmpf[ntmpf-1] = strtod(str, &end);
1027 if ( end==str )
1028 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
1029 str = end+1;
1030 }
1031 }
1032 if ( col->merge_method!=MM_FIRST )
1033 {
1034 if ( !col->mm_dbl_nused )
1035 {
1036 col->mm_dbl_nused = ntmpf;
1037 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
1038 for (i=0; i<ntmpf; i++)
1039 {
1040 if ( bcf_float_is_missing(args->tmpf[i]) )
1041 bcf_double_set_missing(col->mm_dbl[i]);
1042 else
1043 col->mm_dbl[i] = args->tmpf[i];
1044 }
1045 }
1046 else
1047 {
1048 if ( col->merge_method==MM_APPEND || col->merge_method==MM_APPEND_MISSING )
1049 {
1050 int nori = col->mm_dbl_nused;
1051 col->mm_dbl_nused += ntmpf;
1052 hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
1053 for (i=0; i<ntmpf; i++)
1054 {
1055 if ( bcf_float_is_missing(args->tmpf[i]) )
1056 bcf_double_set_missing(col->mm_dbl[i+nori]);
1057 else
1058 col->mm_dbl[i+nori] = args->tmpf[i];
1059 }
1060 }
1061 else
1062 {
1063 if ( ntmpf!=col->mm_dbl_nused ) error("Error: cannot merge fields of unequal length\n");
1064 if ( col->merge_method==MM_SUM || col->merge_method==MM_AVG )
1065 for (i=0; i<ntmpf; i++) col->mm_dbl[i] += args->tmpf[i];
1066 else if ( col->merge_method==MM_MIN )
1067 for (i=0; i<ntmpf; i++) { if ( col->mm_dbl[i] > args->tmpf[i] ) col->mm_dbl[i] = args->tmpf[i]; }
1068 else if ( col->merge_method==MM_MAX )
1069 for (i=0; i<ntmpf; i++) { if ( col->mm_dbl[i] < args->tmpf[i] ) col->mm_dbl[i] = args->tmpf[i]; }
1070 }
1071 }
1072 col->mm_dbl_ndat++;
1073 return 1;
1074 }
1075 }
1076 else if ( col->merge_method==MM_SUM || col->merge_method==MM_MIN || col->merge_method==MM_MAX || col->merge_method==MM_APPEND || col->merge_method==MM_APPEND_MISSING )
1077 {
1078 ntmpf = col->mm_dbl_nused;
1079 hts_expand(int32_t,ntmpf,args->mtmpf,args->tmpf);
1080 for (i=0; i<ntmpf; i++)
1081 {
1082 if ( bcf_double_is_missing(col->mm_dbl[i]) )
1083 bcf_float_set_missing(args->tmpf[i]);
1084 else
1085 args->tmpf[i] = col->mm_dbl[i];
1086 }
1087 col->mm_dbl_nused = col->mm_dbl_ndat = 0;
1088 }
1089 else if ( col->merge_method==MM_AVG )
1090 {
1091 ntmpf = col->mm_dbl_nused;
1092 hts_expand(int32_t,ntmpf,args->mtmpf,args->tmpf);
1093 for (i=0; i<ntmpf; i++) args->tmpf[i] = col->mm_dbl[i]/col->mm_dbl_ndat;
1094 col->mm_dbl_nused = col->mm_dbl_ndat = 0;
1095 }
1096
1097 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
1098 return setter_ARinfo_real(args,line,col,tab->nals,tab->als,ntmpf);
1099
1100 if ( col->replace & REPLACE_MISSING )
1101 {
1102 int ret = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
1103 if ( ret>0 && !bcf_float_is_missing(args->tmpf2[0]) ) return 0;
1104 }
1105
1106 return bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf,ntmpf);
1107 }
1108 static int vcf_setter_info_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1109 {
1110 bcf1_t *rec = (bcf1_t*) data;
1111 int ntmpf = bcf_get_info_float(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpf,&args->mtmpf);
1112 if ( ntmpf < 0 ) return 0; // nothing to add
1113
1114 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
1115 return setter_ARinfo_real(args,line,col,rec->n_allele,rec->d.allele,ntmpf);
1116
1117 if ( col->replace & REPLACE_MISSING )
1118 {
1119 int ret = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
1120 if ( ret>0 && !bcf_float_is_missing(args->tmpf2[0]) ) return 0;
1121 }
1122
1123 return bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf,ntmpf);
1124 }
1125 int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst); // see vcfmerge.c
1126 static int setter_ARinfo_string(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als)
1127 {
1128 assert( col->merge_method==MM_FIRST );
1129
1130 int nsrc = 1, lsrc = 0;
1131 while ( args->tmps[lsrc] )
1132 {
1133 if ( args->tmps[lsrc]==',' ) nsrc++;
1134 lsrc++;
1135 }
1136 if ( col->number==BCF_VL_A && nsrc!=nals-1 && (nsrc!=1 || args->tmps[0]!='.' || args->tmps[1]!=0 ) )
1137 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", nsrc,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1138 else if ( col->number==BCF_VL_R && nsrc!=nals && (nsrc!=1 || args->tmps[0]!='.' || args->tmps[1]!=0 ) )
1139 error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", nsrc,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1140
1141 int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
1142 int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
1143 if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1144
1145 // fill in any missing values in the target VCF (or all, if not present)
1146 int i, empty = 0, nstr, mstr = args->tmpks.m;
1147 nstr = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmpks.s, &mstr);
1148 args->tmpks.m = mstr;
1149 if ( nstr<0 || (nstr==1 && args->tmpks.s[0]=='.' && args->tmpks.s[1]==0) )
1150 {
1151 empty = 0;
1152 args->tmpks.l = 0;
1153 kputc('.',&args->tmpks);
1154 for (i=1; i<ndst; i++) kputs(",.",&args->tmpks);
1155 }
1156 else args->tmpks.l = nstr;
1157 for (i=0; i<ndst; i++)
1158 {
1159 if ( map[i]<0 )
1160 {
1161 if ( empty ) copy_string_field(".",0,1,&args->tmpks,i);
1162 continue;
1163 }
1164 if ( col->replace & REPLACE_MISSING )
1165 {
1166 // Do not replace filled values. The field must be looked up again because
1167 // of realloc in copy_string_field
1168 int n = 0;
1169 char *str = args->tmpks.s;
1170 while ( *str && n<i )
1171 {
1172 if ( *str==',' ) n++;
1173 str++;
1174 }
1175 if ( str[0]!='.' || (str[1]!=',' && str[1]!=0) ) continue; // value already set
1176 }
1177 int ret = copy_string_field(args->tmps,map[i],lsrc,&args->tmpks,i);
1178 if ( ret!=0 ) error("[%s:%d %s] Failed to copy a string field\n", __FILE__,__LINE__,__func__);
1179 }
1180 return bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmpks.s);
1181 }
1182 void khash_str2int_clear_free(void *_hash)
1183 {
1184 khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
1185 khint_t k;
1186 if (hash == 0) return;
1187 for (k = 0; k < kh_end(hash); ++k)
1188 if (kh_exist(hash, k)) free((char*)kh_key(hash, k));
1189 kh_clear(str2int, hash);
1190 }
1191 static const char *escape_string(const char *str, char needle[], char **rmme, size_t *len)
1192 {
1193 kstring_t tmp = {0,0,0};
1194 const char *bp = str, *ep = str;
1195 while ( *ep )
1196 {
1197 int i = 0;
1198 while ( needle[i] && needle[i]!=*ep ) i++;
1199 if ( !needle[i] ) { ep++; continue; }
1200 kputsn(bp,ep-bp,&tmp);
1201 ksprintf(&tmp,"%%%X",*ep);
1202 bp = ++ep;
1203 }
1204 if ( !tmp.l )
1205 {
1206 *len = strlen(str);
1207 return str;
1208 }
1209 kputs(bp,&tmp);
1210 *len = tmp.l;
1211 *rmme = tmp.s;
1212 return tmp.s;
1213 }
1214 static int setter_info_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1215 {
1216 if ( (col->replace & REPLACE_MISSING) && col->number!=BCF_VL_A && col->number!=BCF_VL_R )
1217 {
1218 int ret = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmps2, &args->mtmps2);
1219 if ( ret>0 && (args->tmps2[0]!='.' || args->tmps2[1]!=0) ) return 0;
1220 }
1221
1222 // This is a bit hacky, only to reuse existing code with minimal changes:
1223 // -c =TAG will now behave as -l TAG:unique for strings
1224 if ( col->replace & SET_OR_APPEND ) col->merge_method=MM_UNIQUE;
1225
1226 annot_line_t *tab = (annot_line_t*) data;
1227 const char *escaped = NULL;
1228 char *rmme = NULL;
1229
1230 size_t len = 0;
1231 if ( tab )
1232 {
1233 char *str = tab->cols[col->icol];
1234 if ( !str || !*str ) return 0;
1235 if ( !str[1] && str[0]=='.' && col->merge_method!=MM_APPEND_MISSING && !(col->replace & CARRY_OVER_MISSING) ) return 1;
1236 char needle[] = {';','=',0};
1237 escaped = escape_string(tab->cols[col->icol],needle,&rmme,&len);
1238 }
1239
1240 if ( col->merge_method!=MM_FIRST )
1241 {
1242 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
1243 error("Error: the --merge-logic option cannot be used with INFO tags Type=String,Number={A,R,G}\n");
1244
1245 if ( data )
1246 {
1247 assert( col->merge_method==MM_APPEND || col->merge_method==MM_APPEND_MISSING || col->merge_method==MM_UNIQUE );
1248 if ( col->merge_method==MM_UNIQUE )
1249 {
1250 if ( !col->mm_str_hash ) col->mm_str_hash = (khash_t(str2int)*)khash_str2int_init();
1251 if ( khash_str2int_has_key(col->mm_str_hash, escaped) )
1252 {
1253 free(rmme);
1254 return 1;
1255 }
1256 khash_str2int_inc(col->mm_str_hash, strdup(escaped));
1257 }
1258
1259 if ( (col->replace & SET_OR_APPEND) && !col->mm_kstr.l )
1260 {
1261 int m = col->mm_kstr.m;
1262 int n = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &col->mm_kstr.s, &m);
1263 col->mm_kstr.m = m;
1264 if ( n>0 && ((col->replace & CARRY_OVER_MISSING) || col->mm_kstr.s[0]!='.' || col->mm_kstr.s[1]) ) col->mm_kstr.l = n;
1265 }
1266
1267 if ( col->mm_kstr.l ) kputc(',',&col->mm_kstr);
1268 kputs(escaped, &col->mm_kstr);
1269 free(rmme);
1270 return 1;
1271 }
1272 if ( col->mm_kstr.l )
1273 {
1274 hts_expand(char,col->mm_kstr.l+1,args->mtmps,args->tmps);
1275 memcpy(args->tmps,col->mm_kstr.s,col->mm_kstr.l+1);
1276 }
1277 else
1278 {
1279 free(rmme);
1280 return 0;
1281 }
1282
1283 // flush the line
1284 if ( col->merge_method==MM_UNIQUE )
1285 khash_str2int_clear_free(col->mm_str_hash);
1286 col->mm_kstr.l = 0;
1287 }
1288 else
1289 {
1290 assert(tab);
1291 hts_expand(char,len+1,args->mtmps,args->tmps);
1292 memcpy(args->tmps,escaped,len+1);
1293 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
1294 return setter_ARinfo_string(args,line,col,tab->nals,tab->als);
1295 }
1296 int ret = bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmps);
1297 free(rmme);
1298 return ret;
1299 }
1300 static int vcf_setter_info_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1301 {
1302 bcf1_t *rec = (bcf1_t*) data;
1303
1304 if ( col->getter )
1305 col->getter(args,rec,col,(void**)&args->tmps, &args->mtmps);
1306 else
1307 {
1308 int ntmps = bcf_get_info_string(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmps,&args->mtmps);
1309 if ( ntmps < 0 ) return 0; // nothing to add
1310 }
1311
1312 if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
1313 return setter_ARinfo_string(args,line,col,rec->n_allele,rec->d.allele);
1314
1315 if ( col->replace & REPLACE_MISSING )
1316 {
1317 int ret = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmps2, &args->mtmps2);
1318 if ( ret>0 && (args->tmps2[0]!='.' || args->tmps2[1]!=0) ) return 0;
1319 }
1320
1321 return bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmps);
1322 }
1323 static int genotypes_to_string(args_t *args, int nsrc1, int32_t *src, int nsmpl_dst, kstring_t *str)
1324 {
1325 int i, isrc, idst;
1326 int blen = nsrc1 > 1 ? nsrc1 + 1 : 1; // typically the genotypes take three bytes 0/1, no 0-termination is needed
1327
1328 gt_length_too_big:
1329 str->l = 0;
1330 for (idst=0; idst<nsmpl_dst; idst++)
1331 {
1332 isrc = args->sample_map ? args->sample_map[idst] : idst;
1333 if ( isrc==-1 )
1334 {
1335 kputc_('.', str);
1336 for (i=1; i < blen; i++) kputc_(0, str);
1337 continue;
1338 }
1339
1340 size_t plen = str->l;
1341 int32_t *ptr = src + isrc*nsrc1;
1342 for (i=0; i<nsrc1 && ptr[i]!=bcf_int32_vector_end; i++)
1343 {
1344 if ( i ) kputc("/|"[bcf_gt_is_phased(ptr[i])], str);
1345 if ( bcf_gt_is_missing(ptr[i]) ) kputc('.', str);
1346 else kputw(bcf_gt_allele(ptr[i]), str);
1347 }
1348 if ( i==0 ) kputc('.', str);
1349 if ( str->l - plen > blen )
1350 {
1351 // too many alternate alleles or ploidy is too large, the genotype does not fit
1352 // three characters ("0/0" vs "10/10").
1353 blen *= 2;
1354 goto gt_length_too_big;
1355 }
1356 plen = str->l - plen;
1357 while ( plen < blen )
1358 {
1359 kputc_(0, str);
1360 plen++;
1361 }
1362 }
1363 return 0;
1364 }
1365 static int vcf_setter_format_gt(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1366 {
1367 bcf1_t *rec = (bcf1_t*) data;
1368 int nsrc = bcf_get_genotypes(args->files->readers[1].header,rec,&args->tmpi,&args->mtmpi);
1369 if ( nsrc==-3 ) return 0; // the tag is not present
1370 if ( nsrc<=0 ) return 1; // error
1371
1372 // Genotypes are internally represented as integers. This is a complication when
1373 // adding as a different Type=String field, such as FMT/newGT:=GT
1374 if ( strcmp(col->hdr_key_src,col->hdr_key_dst) )
1375 {
1376 int nsmpl_dst = bcf_hdr_nsamples(args->hdr_out);
1377 int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
1378 genotypes_to_string(args,nsrc/nsmpl_src,args->tmpi,nsmpl_dst,&args->tmpks);
1379 return bcf_update_format_char(args->hdr_out,line,col->hdr_key_dst,args->tmpks.s,args->tmpks.l);
1380 }
1381
1382 if ( !args->sample_map )
1383 return bcf_update_genotypes(args->hdr_out,line,args->tmpi,nsrc);
1384
1385 int i, j, ndst = bcf_get_genotypes(args->hdr,line,&args->tmpi2,&args->mtmpi2);
1386 if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
1387 nsrc /= bcf_hdr_nsamples(args->files->readers[1].header);
1388 if ( ndst<=0 ) // field not present in dst file
1389 {
1390 if ( col->replace & REPLACE_NON_MISSING ) return 0;
1391 hts_expand(int32_t, nsrc*bcf_hdr_nsamples(args->hdr_out), args->mtmpi2, args->tmpi2);
1392 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1393 {
1394 int32_t *dst = args->tmpi2 + nsrc*i;
1395 if ( args->sample_map[i]==-1 )
1396 {
1397 dst[0] = bcf_gt_missing;
1398 for (j=1; j<nsrc; j++) dst[j] = bcf_int32_vector_end;
1399 }
1400 else
1401 {
1402 int32_t *src = args->tmpi + nsrc*args->sample_map[i];
1403 for (j=0; j<nsrc; j++) dst[j] = src[j];
1404 }
1405 }
1406 return bcf_update_genotypes(args->hdr_out,line,args->tmpi2,nsrc*bcf_hdr_nsamples(args->hdr_out));
1407 }
1408 else if ( ndst >= nsrc )
1409 {
1410 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1411 {
1412 if ( args->sample_map[i]==-1 ) continue;
1413 int32_t *src = args->tmpi + nsrc*args->sample_map[i];
1414 int32_t *dst = args->tmpi2 + ndst*i;
1415 if ( (col->replace & REPLACE_NON_MISSING) && bcf_gt_is_missing(dst[0]) ) continue;
1416 if ( (col->replace & REPLACE_MISSING) && !bcf_gt_is_missing(dst[0]) ) continue;
1417 for (j=0; j<nsrc; j++) dst[j] = src[j];
1418 for (; j<ndst; j++) dst[j] = bcf_int32_vector_end;
1419 }
1420 return bcf_update_genotypes(args->hdr_out,line,args->tmpi2,ndst*bcf_hdr_nsamples(args->hdr_out));
1421 }
1422 else // ndst < nsrc
1423 {
1424 hts_expand(int32_t, nsrc*bcf_hdr_nsamples(args->hdr_out), args->mtmpi3, args->tmpi3);
1425 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1426 {
1427 int32_t *ori = args->tmpi2 + ndst*i;
1428 int32_t *dst = args->tmpi3 + nsrc*i;
1429 int keep_ori = 0;
1430 if ( args->sample_map[i]==-1 ) keep_ori = 1;
1431 else if ( (col->replace & REPLACE_NON_MISSING) && bcf_gt_is_missing(ori[0]) ) keep_ori = 1;
1432 else if ( (col->replace & REPLACE_MISSING) && !bcf_gt_is_missing(ori[0]) ) keep_ori = 1;
1433 if ( keep_ori )
1434 {
1435 for (j=0; j<ndst; j++) dst[j] = ori[j];
1436 for (; j<nsrc; j++) dst[j] = bcf_int32_vector_end;
1437 }
1438 else
1439 {
1440 int32_t *src = args->tmpi + nsrc*args->sample_map[i];
1441 for (j=0; j<nsrc; j++) dst[j] = src[j];
1442 }
1443 }
1444 return bcf_update_genotypes(args->hdr_out,line,args->tmpi3,nsrc*bcf_hdr_nsamples(args->hdr_out));
1445 }
1446 }
1447 static int count_vals(annot_line_t *tab, int icol_beg, int icol_end)
1448 {
1449 int i, nmax = 1;
1450 for (i=icol_beg; i<icol_end; i++)
1451 {
1452 char *str = tab->cols[i], *end = str;
1453 if ( str[0]=='.' && !str[1] )
1454 {
1455 // missing value
1456 if ( !nmax ) nmax = 1;
1457 continue;
1458 }
1459 int n = 1;
1460 while ( *end )
1461 {
1462 if ( *end==',' ) n++;
1463 end++;
1464 }
1465 if ( nmax<n ) nmax = n;
1466 }
1467 return nmax;
1468 }
1469 static int core_setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, int32_t *vals, int nvals)
1470 {
1471 if ( !args->sample_map )
1472 return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,vals,nvals*args->nsmpl_annot);
1473
1474 int i, j, ndst = bcf_get_format_int32(args->hdr,line,col->hdr_key_dst,&args->tmpi2,&args->mtmpi2);
1475 if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
1476 if ( ndst<=0 )
1477 {
1478 if ( col->replace & REPLACE_NON_MISSING ) return 0; // overwrite only if present
1479 hts_expand(int32_t, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpi2, args->tmpi2);
1480 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1481 {
1482 int32_t *dst = args->tmpi2 + nvals*i;
1483 if ( args->sample_map[i]==-1 )
1484 {
1485 dst[0] = bcf_int32_missing;
1486 for (j=1; j<nvals; j++) dst[j] = bcf_int32_vector_end;
1487 }
1488 else
1489 {
1490 int32_t *src = vals + nvals*args->sample_map[i];
1491 for (j=0; j<nvals; j++) dst[j] = src[j];
1492 }
1493 }
1494 return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,nvals*bcf_hdr_nsamples(args->hdr_out));
1495 }
1496 else if ( ndst >= nvals )
1497 {
1498 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1499 {
1500 if ( args->sample_map[i]==-1 ) continue;
1501 int32_t *src = vals + nvals*args->sample_map[i];
1502 int32_t *dst = args->tmpi2 + ndst*i;
1503 // possible cases:
1504 // in annot out
1505 // x y x TAG,-TAG,=TAG .. REPLACE_ALL, REPLACE_NON_MISSING, SET_OR_APPEND
1506 // x y y +TAG .. REPLACE_MISSING
1507 // . y . =TAG .. SET_OR_APPEND
1508 // . y y TAG,+TAG,-TAG .. REPLACE_ALL, REPLACE_MISSING, REPLACE_NON_MISSING
1509 // x . x TAG,+TAG .. REPLACE_ALL, REPLACE_MISSING
1510 // x . . -TAG .. REPLACE_NON_MISSING
1511 if ( col->replace & REPLACE_NON_MISSING ) { if ( dst[0]==bcf_int32_missing ) continue; }
1512 else if ( col->replace & REPLACE_MISSING ) { if ( dst[0]!=bcf_int32_missing ) continue; }
1513 else if ( col->replace & REPLACE_ALL ) { if ( src[0]==bcf_int32_missing ) continue; }
1514 for (j=0; j<nvals; j++) dst[j] = src[j];
1515 for (; j<ndst; j++) dst[j] = bcf_int32_vector_end;
1516 }
1517 return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,ndst*bcf_hdr_nsamples(args->hdr_out));
1518 }
1519 else // ndst < nvals
1520 {
1521 hts_expand(int32_t, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpi3, args->tmpi3);
1522 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1523 {
1524 int32_t *ann = vals + nvals*args->sample_map[i];
1525 int32_t *ori = args->tmpi2 + ndst*i; // ori vcf line
1526 int32_t *dst = args->tmpi3 + nvals*i; // expanded buffer
1527 int use_new_ann = 1;
1528 if ( args->sample_map[i]==-1 ) use_new_ann = 0;
1529 else if ( col->replace & REPLACE_NON_MISSING ) { if ( ori[0]==bcf_int32_missing ) use_new_ann = 0; }
1530 else if ( col->replace & REPLACE_MISSING ) { if ( ori[0]!=bcf_int32_missing ) use_new_ann = 0; }
1531 else if ( col->replace & REPLACE_ALL ) { if ( ann[0]==bcf_int32_missing ) use_new_ann = 0; }
1532 if ( !use_new_ann )
1533 {
1534 for (j=0; j<ndst; j++) dst[j] = ori[j];
1535 for (; j<nvals; j++) dst[j] = bcf_int32_vector_end;
1536 }
1537 else
1538 for (j=0; j<nvals; j++) dst[j] = ann[j];
1539 }
1540 return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi3,nvals*bcf_hdr_nsamples(args->hdr_out));
1541 }
1542 }
1543 static int core_setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, float *vals, int nvals)
1544 {
1545 if ( !args->sample_map )
1546 return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,vals,nvals*args->nsmpl_annot);
1547
1548 int i, j, ndst = bcf_get_format_float(args->hdr,line,col->hdr_key_dst,&args->tmpf2,&args->mtmpf2);
1549 if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
1550 if ( ndst<=0 )
1551 {
1552 if ( col->replace & REPLACE_NON_MISSING ) return 0; // overwrite only if present
1553 hts_expand(float, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpf2, args->tmpf2);
1554 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1555 {
1556 float *dst = args->tmpf2 + nvals*i;
1557 if ( args->sample_map[i]==-1 )
1558 {
1559 bcf_float_set_missing(dst[0]);
1560 for (j=1; j<nvals; j++) bcf_float_set_vector_end(dst[j]);
1561 }
1562 else
1563 {
1564 float *src = vals + nvals*args->sample_map[i];
1565 for (j=0; j<nvals; j++) dst[j] = src[j];
1566 }
1567 }
1568 return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,nvals*bcf_hdr_nsamples(args->hdr_out));
1569 }
1570 else if ( ndst >= nvals )
1571 {
1572 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1573 {
1574 if ( args->sample_map[i]==-1 ) continue;
1575 float *src = vals + nvals*args->sample_map[i];
1576 float *dst = args->tmpf2 + ndst*i;
1577 if ( col->replace & REPLACE_NON_MISSING ) { if ( bcf_float_is_missing(dst[0]) ) continue; }
1578 else if ( col->replace & REPLACE_MISSING ) { if ( !bcf_float_is_missing(dst[0]) ) continue; }
1579 else if ( col->replace & REPLACE_ALL ) { if ( bcf_float_is_missing(src[0]) ) continue; }
1580 for (j=0; j<nvals; j++) dst[j] = src[j];
1581 for (; j<ndst; j++) bcf_float_set_vector_end(dst[j]);
1582 }
1583 return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,ndst*bcf_hdr_nsamples(args->hdr_out));
1584 }
1585 else // ndst < nvals
1586 {
1587 hts_expand(float, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpf3, args->tmpf3);
1588 for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
1589 {
1590 float *ann = vals + nvals*args->sample_map[i];
1591 float *ori = args->tmpf2 + ndst*i; // ori vcf line
1592 float *dst = args->tmpf3 + nvals*i; // expanded buffer
1593 int use_new_ann = 1;
1594 if ( args->sample_map[i]==-1 ) use_new_ann = 0;
1595 else if ( col->replace & REPLACE_NON_MISSING ) { if ( bcf_float_is_missing(ori[0]) ) use_new_ann = 0; }
1596 else if ( col->replace & REPLACE_MISSING ) { if ( !bcf_float_is_missing(ori[0]) ) use_new_ann = 0; }
1597 else if ( col->replace & REPLACE_ALL ) { if ( bcf_float_is_missing(ann[0]) ) use_new_ann = 0; }
1598 if ( !use_new_ann )
1599 {
1600 for (j=0; j<ndst; j++) dst[j] = ori[j];
1601 for (; j<nvals; j++) bcf_float_set_vector_end(dst[j]);
1602 }
1603 else
1604 for (j=0; j<nvals; j++) dst[j] = ann[j];
1605 }
1606 return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf3,nvals*bcf_hdr_nsamples(args->hdr_out));
1607 }
1608 }
1609 static int core_setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, char **vals)
1610 {
1611 if ( !args->sample_map )
1612 return bcf_update_format_string(args->hdr_out,line,col->hdr_key_dst,(const char**)vals,args->nsmpl_annot);
1613
1614 int i;
1615 args->tmpp2[0] = args->tmps2;
1616 int ret = bcf_get_format_string(args->hdr,line,col->hdr_key_dst,&args->tmpp2,&args->mtmps2);
1617 args->tmps2 = args->tmpp2[0]; // tmps2 might be realloced
1618
1619 int nsmpl = bcf_hdr_nsamples(args->hdr_out);
1620 if ( ret<=0 ) // not present in dst
1621 {
1622 hts_expand(char,bcf_hdr_nsamples(args->hdr_out)*2,args->mtmps2,args->tmps2);
1623 char *tmp = args->tmps2;
1624 for (i=0; i<nsmpl; i++)
1625 {
1626 tmp[0] = '.';
1627 tmp[1] = 0;
1628 args->tmpp2[i] = tmp;
1629 tmp += 2;
1630 }
1631 }
1632 for (i=0; i<nsmpl; i++)
1633 {
1634 if ( args->sample_map[i]==-1 ) continue;
1635 char **src = vals + args->sample_map[i];
1636 char **dst = args->tmpp2 + i;
1637
1638 if ( col->replace & REPLACE_NON_MISSING ) { if ( (*dst)[0]=='.' && (*dst)[1]==0 ) continue; }
1639 else if ( col->replace & REPLACE_MISSING ) { if ( (*dst)[0]!='.' || (*dst)[1]!=0 ) continue; }
1640 else if ( col->replace & REPLACE_ALL ) { if ( (*src)[0]=='.' && (*src)[1]==0 ) continue; }
1641 *dst = *src;
1642 }
1643 return bcf_update_format_string(args->hdr_out,line,col->hdr_key_dst,(const char**)args->tmpp2,nsmpl);
1644 }
1645 static int setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1646 {
1647 if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
1648
1649 annot_line_t *tab = (annot_line_t*) data;
1650 if ( col->icol+args->nsmpl_annot > tab->ncols )
1651 error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1652 int nvals = count_vals(tab,col->icol,col->icol+args->nsmpl_annot);
1653 hts_expand(int32_t,nvals*args->nsmpl_annot,args->mtmpi,args->tmpi);
1654
1655 int icol = col->icol, ismpl;
1656 for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
1657 {
1658 int32_t *ptr = args->tmpi + ismpl*nvals;
1659 int ival = 0;
1660
1661 char *str = tab->cols[icol];
1662 while ( *str )
1663 {
1664 if ( str[0]=='.' && (!str[1] || str[1]==',') ) // missing value
1665 {
1666 ptr[ival++] = bcf_int32_missing;
1667 str += str[1] ? 2 : 1;
1668 continue;
1669 }
1670
1671 char *end = str;
1672 ptr[ival] = strtol(str, &end, 10);
1673 if ( end==str )
1674 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
1675
1676 ival++;
1677 str = *end ? end+1 : end;
1678 }
1679 while ( ival<nvals ) ptr[ival++] = bcf_int32_vector_end;
1680 icol++;
1681 }
1682 return core_setter_format_int(args,line,col,args->tmpi,nvals);
1683 }
1684 static int setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1685 {
1686 if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
1687
1688 annot_line_t *tab = (annot_line_t*) data;
1689 if ( col->icol+args->nsmpl_annot > tab->ncols )
1690 error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1691 int nvals = count_vals(tab,col->icol,col->icol+args->nsmpl_annot);
1692 hts_expand(float,nvals*args->nsmpl_annot,args->mtmpf,args->tmpf);
1693
1694 int icol = col->icol, ismpl;
1695 for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
1696 {
1697 float *ptr = args->tmpf + ismpl*nvals;
1698 int ival = 0;
1699
1700 char *str = tab->cols[icol];
1701 while ( *str )
1702 {
1703 if ( str[0]=='.' && (!str[1] || str[1]==',') ) // missing value
1704 {
1705 bcf_float_set_missing(ptr[ival]);
1706 ival++;
1707 str += str[1] ? 2 : 1;
1708 continue;
1709 }
1710
1711 char *end = str;
1712 ptr[ival] = strtod(str, &end);
1713 if ( end==str )
1714 error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
1715
1716 ival++;
1717 str = *end ? end+1 : end;
1718 }
1719 while ( ival<nvals ) { bcf_float_set_vector_end(ptr[ival]); ival++; }
1720 icol++;
1721 }
1722 return core_setter_format_real(args,line,col,args->tmpf,nvals);
1723 }
1724 static int setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1725 {
1726 if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
1727
1728 annot_line_t *tab = (annot_line_t*) data;
1729 if ( col->icol+args->nsmpl_annot > tab->ncols )
1730 error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1731
1732 char needle[] = {':',0};
1733 int ismpl;
1734 for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
1735 {
1736 size_t len;
1737 char *rmme = NULL;
1738 const char *str = escape_string(tab->cols[col->icol + ismpl],needle,&rmme,&len);
1739 args->tmpp[ismpl] = rmme ? rmme : strdup(str);
1740 }
1741 int ret = core_setter_format_str(args,line,col,args->tmpp);
1742 for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++) free(args->tmpp[ismpl]);
1743 return ret;
1744 }
1745 static int determine_ploidy(int nals, int *vals, int nvals1, uint8_t *smpl, int nsmpl)
1746 {
1747 int i, j, ndip = nals*(nals+1)/2, max_ploidy = 0;
1748 for (i=0; i<nsmpl; i++)
1749 {
1750 int *ptr = vals + i*nvals1;
1751 int has_value = 0;
1752 for (j=0; j<nvals1; j++)
1753 {
1754 if ( ptr[j]==bcf_int32_vector_end ) break;
1755 if ( ptr[j]!=bcf_int32_missing ) has_value = 1;
1756 }
1757 if ( has_value )
1758 {
1759 if ( j==ndip )
1760 {
1761 smpl[i] = 2;
1762 max_ploidy = 2;
1763 }
1764 else if ( j==nals )
1765 {
1766 smpl[i] = 1;
1767 if ( !max_ploidy ) max_ploidy = 1;
1768 }
1769 else return -j;
1770 }
1771 else smpl[i] = 0;
1772 }
1773 return max_ploidy;
1774 }
1775 static int vcf_setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1776 {
1777 bcf1_t *rec = (bcf1_t*) data;
1778 int nsrc = bcf_get_format_int32(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpi,&args->mtmpi);
1779 if ( nsrc==-3 ) return 0; // the tag is not present
1780 if ( nsrc<=0 ) return 1; // error
1781 int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
1782 int nsrc1 = nsrc / nsmpl_src;
1783 if ( col->number!=BCF_VL_G && col->number!=BCF_VL_R && col->number!=BCF_VL_A )
1784 return core_setter_format_int(args,line,col,args->tmpi,nsrc1);
1785
1786 // create mapping from src to dst genotypes, haploid and diploid version
1787 int nmap_hap = col->number==BCF_VL_G || col->number==BCF_VL_R ? rec->n_allele : rec->n_allele - 1;
1788 int *map_hap = vcmp_map_ARvalues(args->vcmp,nmap_hap,line->n_allele,line->d.allele,rec->n_allele,rec->d.allele);
1789 if ( !map_hap ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1790
1791 int i, j;
1792 if ( rec->n_allele==line->n_allele )
1793 {
1794 // alleles unchanged?
1795 for (i=0; i<rec->n_allele; i++) if ( map_hap[i]!=i ) break;
1796 if ( i==rec->n_allele )
1797 return core_setter_format_int(args,line,col,args->tmpi,nsrc1);
1798 }
1799
1800 int nsmpl_dst = rec->n_sample;
1801 int ndst = bcf_get_format_int32(args->hdr,line,col->hdr_key_dst,&args->tmpi2,&args->mtmpi2);
1802 int ndst1 = ndst / nsmpl_dst;
1803 if ( ndst <= 0 )
1804 {
1805 if ( col->replace & REPLACE_NON_MISSING ) return 0; // overwrite only if present
1806 if ( col->number==BCF_VL_G )
1807 ndst1 = line->n_allele*(line->n_allele+1)/2;
1808 else
1809 ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
1810 hts_expand(int, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
1811 for (i=0; i<nsmpl_dst; i++)
1812 {
1813 int32_t *dst = args->tmpi2 + i*ndst1;
1814 for (j=0; j<ndst1; j++) dst[j] = bcf_int32_missing;
1815 }
1816 }
1817
1818 int nmap_dip = 0, *map_dip = NULL;
1819 if ( col->number==BCF_VL_G )
1820 {
1821 map_dip = vcmp_map_dipGvalues(args->vcmp, &nmap_dip);
1822 if ( !args->src_smpl_pld )
1823 {
1824 args->src_smpl_pld = (uint8_t*) malloc(nsmpl_src);
1825 args->dst_smpl_pld = (uint8_t*) malloc(nsmpl_dst);
1826 }
1827 int pld_src = determine_ploidy(rec->n_allele, args->tmpi, nsrc1, args->src_smpl_pld, nsmpl_src);
1828 if ( pld_src<0 )
1829 error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_src, rec->n_allele, bcf_seqname(bcf_sr_get_header(args->files,1),rec),(int64_t) rec->pos+1);
1830 int pld_dst = determine_ploidy(line->n_allele, args->tmpi2, ndst1, args->dst_smpl_pld, nsmpl_dst);
1831 if ( pld_dst<0 )
1832 error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_dst, line->n_allele, bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1833
1834 int ndst1_new = pld_dst==1 ? line->n_allele : line->n_allele*(line->n_allele+1)/2;
1835 if ( ndst1_new != ndst1 )
1836 {
1837 if ( ndst1 ) error("todo: %s ndst1!=ndst .. %d %d at %s:%"PRId64"\n",col->hdr_key_src,ndst1_new,ndst1,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1838 ndst1 = ndst1_new;
1839 hts_expand(int32_t, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
1840 }
1841 }
1842 else if ( !ndst1 )
1843 {
1844 ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
1845 hts_expand(int32_t, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
1846 }
1847
1848 for (i=0; i<nsmpl_dst; i++)
1849 {
1850 int ii = args->sample_map ? args->sample_map[i] : i;
1851 int32_t *ptr_src = args->tmpi + i*nsrc1;
1852 int32_t *ptr_dst = args->tmpi2 + ii*ndst1;
1853
1854 if ( col->number==BCF_VL_G )
1855 {
1856 if ( args->src_smpl_pld[ii] > 0 && args->dst_smpl_pld[i] > 0 && args->src_smpl_pld[ii]!=args->dst_smpl_pld[i] )
1857 error("Sample ploidy differs at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1858 if ( !args->dst_smpl_pld[i] )
1859 for (j=0; j<ndst1; j++) ptr_dst[j] = bcf_int32_missing;
1860 }
1861 if ( col->number!=BCF_VL_G || args->src_smpl_pld[i]==1 )
1862 {
1863 for (j=0; j<nmap_hap; j++)
1864 {
1865 int k = map_hap[j];
1866 if ( k>=0 ) ptr_dst[k] = ptr_src[j];
1867 }
1868 if ( col->number==BCF_VL_G )
1869 for (j=line->n_allele; j<ndst1; j++) ptr_dst[j++] = bcf_int32_vector_end;
1870 }
1871 else
1872 {
1873 for (j=0; j<nmap_dip; j++)
1874 {
1875 int k = map_dip[j];
1876 if ( k>=0 ) ptr_dst[k] = ptr_src[j];
1877 }
1878 }
1879 }
1880 return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,nsmpl_dst*ndst1);
1881 }
1882 static int vcf_setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
1883 {
1884 bcf1_t *rec = (bcf1_t*) data;
1885 int nsrc = bcf_get_format_float(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpf,&args->mtmpf);
1886 if ( nsrc==-3 ) return 0; // the tag is not present
1887 if ( nsrc<=0 ) return 1; // error
1888 int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
1889 int nsrc1 = nsrc / nsmpl_src;
1890 if ( col->number!=BCF_VL_G && col->number!=BCF_VL_R && col->number!=BCF_VL_A )
1891 return core_setter_format_real(args,line,col,args->tmpf,nsrc1);
1892
1893 // create mapping from src to dst genotypes, haploid and diploid version
1894 int nmap_hap = col->number==BCF_VL_G || col->number==BCF_VL_R ? rec->n_allele : rec->n_allele - 1;
1895 int *map_hap = vcmp_map_ARvalues(args->vcmp,nmap_hap,line->n_allele,line->d.allele,rec->n_allele,rec->d.allele);
1896 if ( !map_hap ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1897
1898 int i, j;
1899 if ( rec->n_allele==line->n_allele )
1900 {
1901 // alleles unchanged?
1902 for (i=0; i<rec->n_allele; i++) if ( map_hap[i]!=i ) break;
1903 if ( i==rec->n_allele )
1904 return core_setter_format_real(args,line,col,args->tmpf,nsrc1);
1905 }
1906
1907 int nsmpl_dst = rec->n_sample;
1908 int ndst = bcf_get_format_float(args->hdr,line,col->hdr_key_dst,&args->tmpf2,&args->mtmpf2);
1909 int ndst1 = ndst / nsmpl_dst;
1910 if ( ndst <= 0 )
1911 {
1912 if ( col->replace & REPLACE_NON_MISSING ) return 0; // overwrite only if present
1913 if ( col->number==BCF_VL_G )
1914 ndst1 = line->n_allele*(line->n_allele+1)/2;
1915 else
1916 ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
1917 hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
1918 for (i=0; i<nsmpl_dst; i++)
1919 {
1920 float *dst = args->tmpf2 + i*ndst1;
1921 for (j=0; j<ndst1; j++) bcf_float_set_missing(dst[j]);
1922 }
1923 }
1924
1925 int nmap_dip = 0, *map_dip = NULL;
1926 if ( col->number==BCF_VL_G )
1927 {
1928 map_dip = vcmp_map_dipGvalues(args->vcmp, &nmap_dip);
1929 if ( !args->src_smpl_pld )
1930 {
1931 args->src_smpl_pld = (uint8_t*) malloc(nsmpl_src);
1932 args->dst_smpl_pld = (uint8_t*) malloc(nsmpl_dst);
1933 }
1934 int pld_src = determine_ploidy(rec->n_allele, args->tmpi, nsrc1, args->src_smpl_pld, nsmpl_src);
1935 if ( pld_src<0 )
1936 error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_src, rec->n_allele, bcf_seqname(bcf_sr_get_header(args->files,1),rec),(int64_t) rec->pos+1);
1937 int pld_dst = determine_ploidy(line->n_allele, args->tmpi2, ndst1, args->dst_smpl_pld, nsmpl_dst);
1938 if ( pld_dst<0 )
1939 error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_dst, line->n_allele, bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1940
1941 int ndst1_new = pld_dst==1 ? line->n_allele : line->n_allele*(line->n_allele+1)/2;
1942 if ( ndst1_new != ndst1 )
1943 {
1944 if ( ndst1 ) error("todo: %s ndst1!=ndst .. %d %d at %s:%"PRId64"\n",col->hdr_key_src,ndst1_new,ndst1,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1945 ndst1 = ndst1_new;
1946 hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
1947 }
1948 }
1949 else if ( !ndst1 )
1950 {
1951 ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
1952 hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
1953 }
1954
1955 for (i=0; i<nsmpl_dst; i++)
1956 {
1957 int ii = args->sample_map ? args->sample_map[i] : i;
1958 float *ptr_src = args->tmpf + i*nsrc1;
1959 float *ptr_dst = args->tmpf2 + ii*ndst1;
1960
1961 if ( col->number==BCF_VL_G )
1962 {
1963 if ( args->src_smpl_pld[ii] > 0 && args->dst_smpl_pld[i] > 0 && args->src_smpl_pld[ii]!=args->dst_smpl_pld[i] )
1964 error("Sample ploidy differs at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
1965 if ( !args->dst_smpl_pld[i] )
1966 for (j=0; j<ndst1; j++) bcf_float_set_missing(ptr_dst[j]);
1967 }
1968 if ( col->number!=BCF_VL_G || args->src_smpl_pld[i]==1 )
1969 {
1970 for (j=0; j<nmap_hap; j++)
1971 {
1972 int k = map_hap[j];
1973 if ( k>=0 )
1974 {
1975 if ( bcf_float_is_missing(ptr_src[j]) ) bcf_float_set_missing(ptr_dst[k]);
1976 else if ( bcf_float_is_vector_end(ptr_src[j]) ) bcf_float_set_vector_end(ptr_dst[k]);
1977 else ptr_dst[k] = ptr_src[j];
1978 }
1979 }
1980 if ( col->number==BCF_VL_G )
1981 for (j=line->n_allele; j<ndst1; j++) bcf_float_set_vector_end(ptr_dst[j]);
1982 }
1983 else
1984 {
1985 for (j=0; j<nmap_dip; j++)
1986 {
1987 int k = map_dip[j];
1988 if ( k>=0 )
1989 {
1990 if ( bcf_float_is_missing(ptr_src[j]) ) bcf_float_set_missing(ptr_dst[k]);
1991 else if ( bcf_float_is_vector_end(ptr_src[j]) ) bcf_float_set_vector_end(ptr_dst[k]);
1992 else ptr_dst[k] = ptr_src[j];
1993 }
1994 }
1995 }
1996 }
1997 return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,nsmpl_dst*ndst1);
1998 }
1999
2000 static int vcf_setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
2001 {
2002 bcf1_t *rec = (bcf1_t*) data;
2003 args->tmpp[0] = args->tmps;
2004 int ret = bcf_get_format_string(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpp,&args->mtmps);
2005 args->tmps = args->tmpp[0]; // tmps might be realloced
2006 if ( ret==-3 ) return 0; // the tag is not present
2007 if ( ret<=0 ) return 1; // error
2008 if ( strcmp("GT",col->hdr_key_dst) )
2009 return core_setter_format_str(args,line,col,args->tmpp);
2010
2011 // Genotypes are internally represented as integers. This is a complication for FMT/GT:=oldGT
2012 // First determine the maximum number of alleles per-sample ndst1
2013 int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
2014 int nsmpl_dst = bcf_hdr_nsamples(args->hdr_out);
2015 int isrc,idst, ndst1 = 0, nsrc1 = ret / nsmpl_src;
2016 char *ptr = args->tmps, *ptr_end = ptr + ret;
2017 while ( ptr < ptr_end )
2018 {
2019 char *smpl_end = ptr + nsrc1;
2020 int n = 1;
2021 while ( ptr < smpl_end )
2022 {
2023 if ( *ptr=='/' || *ptr=='|' ) n++;
2024 ptr++;
2025 }
2026 if ( ndst1 < n ) ndst1 = n;
2027 }
2028 assert( ndst1 );
2029
2030 int ndst = ndst1*nsmpl_dst;
2031 hts_expand(int32_t,ndst,args->mtmpi,args->tmpi);
2032 hts_expand(char,ret+1,args->mtmps,args->tmps); args->tmps[ret] = 0; // the FORMAT string may not be 0-terminated
2033 for (idst=0; idst<nsmpl_dst; idst++)
2034 {
2035 int i = 0, is_phased = 0;
2036 int32_t *dst = args->tmpi + idst*ndst1;
2037 isrc = args->sample_map ? args->sample_map[idst] : idst;
2038 if ( isrc==-1 )
2039 {
2040 dst[0] = bcf_gt_missing;
2041 for (i=1; i<ndst1; i++) dst[i] = bcf_int32_vector_end;
2042 continue;
2043 }
2044 char *beg = args->tmps + isrc*nsrc1, *tmp;
2045 char *keep_ptr = beg+nsrc1, keep = *keep_ptr; *keep_ptr = 0;
2046 while ( *beg )
2047 {
2048 char *end = beg;
2049 while ( *end && *end!='/' && *end!='|' ) end++;
2050 if ( *beg=='.' && end-beg==1 ) dst[i] = bcf_gt_missing;
2051 else
2052 {
2053 if ( *end=='|' ) is_phased = 1;
2054 dst[i] = strtol(beg, &tmp, 10);
2055 if ( tmp!=end )
2056 error("Could not parse the %s field at %s:%"PRId64" in %s\n", col->hdr_key_src,bcf_seqname(args->files->readers[1].header,rec),(int64_t) rec->pos+1,args->targets_fname);
2057 if ( dst[i] >= line->n_allele )
2058 error("The source allele index is bigger than the number of destination alleles at %s:%"PRId64"\n", bcf_seqname(args->files->readers[1].header,rec),(int64_t) rec->pos+1);
2059 dst[i] = is_phased ? bcf_gt_phased(dst[i]) : bcf_gt_unphased(dst[i]);
2060 }
2061 beg = *end ? end+1 : end;
2062 i++;
2063 }
2064 *keep_ptr = keep;
2065 for (; i<ndst1; i++) dst[i] = bcf_int32_vector_end;
2066 }
2067 return bcf_update_genotypes(args->hdr_out,line,args->tmpi,ndst);
2068 }
2069 static int init_sample_map(args_t *args, bcf_hdr_t *src, bcf_hdr_t *dst)
2070 {
2071 int i;
2072 if ( !args->sample_names )
2073 {
2074 args->nsmpl_annot = bcf_hdr_nsamples(dst);
2075
2076 // tab annotation file, expecting that all samples are present: sample map not needed
2077 if ( !src ) return 0;
2078
2079 int nmatch = 0;
2080 for (i=0; i<bcf_hdr_nsamples(src); i++)
2081 {
2082 int id = bcf_hdr_id2int(dst, BCF_DT_SAMPLE, src->samples[i]);
2083 if ( id!=-1 ) nmatch++;
2084 }
2085 if ( !nmatch ) return -1; // No matching samples found in the source and the destination file
2086
2087 args->nsample_map = bcf_hdr_nsamples(dst);
2088 args->sample_map = (int*) malloc(sizeof(int)*args->nsample_map);
2089 for (i=0; i<args->nsample_map; i++)
2090 {
2091 int id = bcf_hdr_id2int(src, BCF_DT_SAMPLE, dst->samples[i]);
2092 args->sample_map[i] = id; // idst -> isrc, -1 if not present
2093 }
2094 return 1;
2095 }
2096
2097 args->nsample_map = bcf_hdr_nsamples(dst);
2098 args->sample_map = (int*) malloc(sizeof(int)*args->nsample_map);
2099 for (i=0; i<args->nsample_map; i++) args->sample_map[i] = -1;
2100
2101 int flags = !src ? SMPL_STRICT|SMPL_SINGLE|SMPL_REORDER : SMPL_STRICT|SMPL_SINGLE|SMPL_PAIR2; // is tab vs vcf annotation file
2102 smpl_ilist_t *ilist = smpl_ilist_init(dst, args->sample_names, args->sample_is_file, flags); // gives mapping dst->src
2103 if ( !ilist || !ilist->n ) error("Could not parse the samples: %s\n", args->sample_names);
2104 args->nsmpl_annot = ilist->n;
2105 int need_sample_map = args->nsmpl_annot==bcf_hdr_nsamples(dst) ? 0 : 1;
2106 for (i=0; i<args->nsmpl_annot; i++)
2107 {
2108 int idst = ilist->idx[i];
2109 const char *src_name = ilist->pair && ilist->pair[i] ? ilist->pair[i] : bcf_hdr_int2id(dst, BCF_DT_SAMPLE, idst);
2110 int isrc = i;
2111 if ( src ) // the annotation file is a VCF, not a tab-delimited file
2112 {
2113 isrc = bcf_hdr_id2int(src, BCF_DT_SAMPLE, src_name);
2114 if ( isrc==-1 ) error("Sample \"%s\" not found in the annotation file\n", src_name);
2115 }
2116 if ( isrc!=idst ) need_sample_map = 1;
2117 args->sample_map[idst] = isrc;
2118 }
2119 smpl_ilist_destroy(ilist);
2120 return need_sample_map;
2121 }
2122 static char *columns_complement(char *columns, void **skip_info, void **skip_fmt)
2123 {
2124 kstring_t str = {0,0,0};
2125 char *ss = columns, *se = ss;
2126 while ( *ss )
2127 {
2128 if ( *se && *se!=',' ) { se++; continue; }
2129 if ( *ss!='^' )
2130 {
2131 if ( str.l ) kputc(',',&str);
2132 kputsn(ss, se-ss, &str);
2133 if ( !*se ) break;
2134 ss = ++se;
2135 continue;
2136 }
2137
2138 if ( !strncasecmp("^INFO/",ss,6) )
2139 {
2140 if ( !*skip_info )
2141 {
2142 *skip_info = khash_str2int_init();
2143 if ( str.l ) kputc(',',&str);
2144 kputs("INFO",&str);
2145 }
2146 char tmp = *se; *se = 0;
2147 khash_str2int_inc(*skip_info, strdup(ss+6));
2148 *se = tmp;
2149 }
2150 else if ( !strncasecmp("^FORMAT/",ss,8) || !strncasecmp("^FMT/",ss,5) )
2151 {
2152 int n = !strncasecmp("^FMT/",ss,5) ? 5 : 8;
2153 if ( !*skip_fmt )
2154 {
2155 *skip_fmt = khash_str2int_init();
2156 if ( str.l ) kputc(',',&str);
2157 kputs("FORMAT",&str);
2158 }
2159 char tmp = *se; *se = 0;
2160 khash_str2int_inc(*skip_fmt, strdup(ss+n));
2161 *se = tmp;
2162 }
2163 else
2164 {
2165 if ( !*skip_info )
2166 {
2167 *skip_info = khash_str2int_init();
2168 if ( str.l ) kputc(',',&str);
2169 kputs("INFO",&str);
2170 }
2171 char tmp = *se; *se = 0;
2172 khash_str2int_inc(*skip_info, strdup(ss+1));
2173 *se = tmp;
2174 }
2175
2176 if ( !*se ) break;
2177 ss = ++se;
2178 }
2179 free(columns);
2180 return str.s;
2181 }
2182 static void bcf_hrec_format_rename(bcf_hrec_t *hrec, char *tag, kstring_t *str)
2183 {
2184 int j, nout = 0;
2185 ksprintf(str, "##%s=<", hrec->key);
2186 for (j=0; j<hrec->nkeys; j++)
2187 {
2188 if ( !strcmp("IDX",hrec->keys[j]) ) continue;
2189 if ( nout ) kputc(',',str);
2190 if ( !strcmp("ID", hrec->keys[j]) )
2191 ksprintf(str,"%s=%s", hrec->keys[j], tag);
2192 else
2193 ksprintf(str,"%s=%s", hrec->keys[j], hrec->vals[j]);
2194 nout++;
2195 }
2196 ksprintf(str,">\n");
2197 }
2198 static char *set_replace_mode(char *ss, int *replace)
2199 {
2200 int mode = 0;
2201 while (*ss)
2202 {
2203 if ( *ss=='+' ) mode |= REPLACE_MISSING;
2204 else if ( *ss=='-' ) mode |= REPLACE_NON_MISSING;
2205 else if ( *ss=='=' ) mode |= SET_OR_APPEND;
2206 else if ( *ss=='.' ) mode |= CARRY_OVER_MISSING;
2207 else break;
2208 ss++;
2209 }
2210 if ( !mode ) mode = REPLACE_ALL;
2211 // is exactly one bit set?
2212 // if ( mode && !(mode && ((mode & mode-1) == 0)) )
2213 *replace = mode;
2214 return ss;
2215 }
2216 static void rename_annots_push(args_t *args, char *src, char *dst);
2217 static void init_columns(args_t *args)
2218 {
2219 int need_sample_map = 0;
2220 int sample_map_ok = init_sample_map(args, args->tgts_is_vcf?args->files->readers[1].header:NULL, args->hdr);
2221
2222 kstring_t tmp = {0,0,0};
2223 if ( args->columns_is_file )
2224 {
2225 int i,n;
2226 char **str = hts_readlist(args->columns, args->columns_is_file, &n);
2227 if ( !str ) error("Could not parse %s\n", args->columns);
2228 for (i=0; i<n; i++)
2229 {
2230 char *ptr = str[i];
2231 while ( *ptr && !isspace(*ptr) ) ptr++;
2232 if ( *ptr )
2233 {
2234 *ptr = 0;
2235 ptr++;
2236 while ( *ptr && isspace(*ptr) ) ptr++;
2237 if ( *ptr )
2238 {
2239 if ( args->merge_method_str.l ) kputc(',',&args->merge_method_str);
2240 kputs(str[i],&args->merge_method_str);
2241 kputc(':',&args->merge_method_str);
2242 kputs(ptr,&args->merge_method_str);
2243 }
2244 }
2245 if ( tmp.l ) kputc(',',&tmp);
2246 kputs(str[i],&tmp);
2247 free(str[i]);
2248 }
2249 free(str);
2250 free(args->columns);
2251 args->columns = tmp.s;
2252 tmp.l = tmp.m = 0;
2253 tmp.s = NULL;
2254 }
2255
2256 void *skip_fmt = NULL, *skip_info = NULL;
2257 if ( args->tgts_is_vcf )
2258 args->columns = columns_complement(args->columns, &skip_info, &skip_fmt);
2259
2260 kstring_t str = {0,0,0};
2261 char *ss = args->columns, *se = ss;
2262 args->ncols = 0;
2263 int icol = -1, has_fmt_str = 0;
2264 while ( *ss )
2265 {
2266 char *ptr;
2267 if ( *se && *se!=',' ) { se++; continue; }
2268 int replace;
2269 ss = set_replace_mode(ss, &replace);
2270 icol++;
2271 str.l = 0;
2272 kputsn(ss, se-ss, &str);
2273 if ( !str.s[0] || !strcasecmp("-",str.s) ) ;
2274 else if ( !strcasecmp("CHROM",str.s) ) args->chr_idx = icol;
2275 else if ( !strcasecmp("POS",str.s) )
2276 {
2277 if ( replace==REPLACE_NON_MISSING && !args->tgts_is_vcf )
2278 {
2279 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2280 annot_col_t *col = &args->cols[args->ncols-1];
2281 memset(col,0,sizeof(*col));
2282 col->icol = icol;
2283 col->replace = replace;
2284 col->setter = setter_pos;
2285 col->hdr_key_src = strdup(str.s);
2286 col->hdr_key_dst = strdup(str.s);
2287 args->match_end = icol;
2288 }
2289 else
2290 args->beg_idx = icol;
2291 }
2292 else if ( !strcasecmp("FROM",str.s) || !strcasecmp("BEG",str.s) ) args->beg_idx = icol;
2293 else if ( !strcasecmp("TO",str.s) || !strcasecmp("END",str.s) ) args->end_idx = icol;
2294 else if ( !strcasecmp("REF",str.s) )
2295 {
2296 if ( args->tgts_is_vcf )
2297 {
2298 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2299 annot_col_t *col = &args->cols[args->ncols-1];
2300 memset(col,0,sizeof(*col));
2301 col->setter = vcf_setter_ref;
2302 col->hdr_key_src = strdup(str.s);
2303 col->hdr_key_dst = strdup(str.s);
2304 }
2305 else args->ref_idx = icol;
2306 }
2307 else if ( !strcasecmp("ALT",str.s) )
2308 {
2309 if ( args->tgts_is_vcf )
2310 {
2311 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2312 annot_col_t *col = &args->cols[args->ncols-1];
2313 memset(col,0,sizeof(*col));
2314 col->setter = vcf_setter_alt;
2315 col->hdr_key_src = strdup(str.s);
2316 col->hdr_key_dst = strdup(str.s);
2317 col->replace = replace;
2318 if ( args->pair_logic==-1 ) bcf_sr_set_opt(args->files,BCF_SR_PAIR_LOGIC,BCF_SR_PAIR_BOTH_REF);
2319 }
2320 else args->alt_idx = icol;
2321 }
2322 else if ( !strcasecmp("ID",str.s) || !strcasecmp("~ID",str.s) )
2323 {
2324 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -ID feature has not been implemented yet.\n");
2325 if ( str.s[0]=='~' ) replace = MATCH_VALUE;
2326 if ( args->tgts_is_vcf && (replace & MATCH_VALUE) ) error("todo: -c ~ID with -a VCF?\n");
2327 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2328 annot_col_t *col = &args->cols[args->ncols-1];
2329 memset(col,0,sizeof(*col));
2330 col->icol = icol;
2331 col->replace = replace;
2332 col->setter = args->tgts_is_vcf ? vcf_setter_id : setter_id;
2333 col->hdr_key_src = strdup(str.s);
2334 col->hdr_key_dst = strdup(str.s);
2335 if ( replace & MATCH_VALUE ) args->match_id = icol;
2336 }
2337 else if ( !strcasecmp("~INFO/END",str.s) && !args->tgts_is_vcf )
2338 {
2339 replace = MATCH_VALUE;
2340 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2341 annot_col_t *col = &args->cols[args->ncols-1];
2342 memset(col,0,sizeof(*col));
2343 col->icol = icol;
2344 col->replace = replace;
2345 col->setter = NULL;
2346 col->hdr_key_src = strdup(str.s);
2347 col->hdr_key_dst = strdup(str.s);
2348 args->match_end = icol;
2349 }
2350 else if ( !strcasecmp("~POS",str.s) )
2351 {
2352 error("Error: the use of ~POS has been deprecated, use -POS to transfer the column POS.\n");
2353 }
2354 else if ( str.s[0]=='~' )
2355 {
2356 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2357 annot_col_t *col = &args->cols[args->ncols-1];
2358 memset(col,0,sizeof(*col));
2359 col->icol = icol;
2360 col->replace = MATCH_VALUE;
2361 col->setter = NULL;
2362 col->hdr_key_src = strdup(str.s+1);
2363 }
2364 else if ( !strcasecmp("-POS",str.s) && !args->tgts_is_vcf )
2365 {
2366 if ( args->tgts_is_vcf ) error("Error: cannot use -POS, position can be replaced only from a tab-delimited file\n");
2367 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2368 annot_col_t *col = &args->cols[args->ncols-1];
2369 memset(col,0,sizeof(*col));
2370 col->icol = icol;
2371 col->replace = replace;
2372 col->setter = setter_pos;
2373 col->hdr_key_src = strdup(str.s);
2374 col->hdr_key_dst = strdup(str.s);
2375 args->match_end = icol;
2376 }
2377 else if ( !strncasecmp("ID:=",str.s,4) ) // transfer a tag from INFO to ID column
2378 {
2379 if ( !args->tgts_is_vcf ) error("The annotation source must be a VCF for \"%s\"\n",str.s);
2380 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -ID feature has not been implemented yet.\n");
2381 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2382 annot_col_t *col = &args->cols[args->ncols-1];
2383 memset(col,0,sizeof(*col));
2384 col->icol = icol;
2385 col->replace = replace;
2386 col->setter = vcf_setter_id;
2387 col->getter = vcf_getter_info_str2str;
2388 str.s[2] = 0;
2389 col->hdr_key_dst = strdup(str.s);
2390 col->hdr_key_src = strncasecmp("INFO/",str.s+4,5) ? strdup(str.s+4) : strdup(str.s+4+5);
2391 int hdr_id = bcf_hdr_id2int(args->tgts_hdr, BCF_DT_ID,col->hdr_key_src);
2392 if ( !bcf_hdr_idinfo_exists(args->tgts_hdr,BCF_HL_INFO,hdr_id) )
2393 error("The INFO tag \"%s\" is not defined in %s\n", col->hdr_key_src, args->targets_fname);
2394 if ( bcf_hdr_id2type(args->tgts_hdr,BCF_HL_INFO,hdr_id)!=BCF_HT_STR )
2395 error("Only Type=String tags can be used to annotate the ID column\n");
2396 }
2397 else if ( (ptr=strstr(str.s,":=")) && (!args->targets_fname || !strncasecmp(ptr+2,"./",2)) )
2398 {
2399 *ptr = 0;
2400 if ( !strncasecmp(str.s,"INFO/",5) && (!strcasecmp(ptr+2,"FILTER") || !strcasecmp(ptr+2,"./FILTER")) )
2401 {
2402 // -a not present and transferring filter, needs to be a local transfer
2403 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2404 annot_col_t *col = &args->cols[args->ncols-1];
2405 memset(col,0,sizeof(*col));
2406 col->icol = icol;
2407 col->replace = replace;
2408 col->setter = vcf_setter_info_str;
2409 col->getter = vcf_getter_filter2str_local;
2410 col->hdr_key_src = strdup(ptr+2);
2411 col->hdr_key_dst = strdup(str.s+5);
2412 tmp.l = 0;
2413 ksprintf(&tmp,"##INFO=<ID=%s,Number=1,Type=String,Description=\"Transferred FILTER column\">",col->hdr_key_dst);
2414 bcf_hdr_append(args->hdr_out, tmp.s);
2415 if (bcf_hdr_sync(args->hdr_out) < 0) error_errno("[%s] Failed to update header", __func__);
2416 int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, col->hdr_key_dst);
2417 col->number = bcf_hdr_id2length(args->hdr_out,BCF_HL_INFO,hdr_id);
2418 }
2419 else
2420 rename_annots_push(args,ptr+2,str.s);
2421 *ptr = ':';
2422 }
2423 else if ( !strcasecmp("FILTER",str.s) )
2424 {
2425 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -FILTER feature has not been implemented yet.\n");
2426 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2427 annot_col_t *col = &args->cols[args->ncols-1];
2428 memset(col,0,sizeof(*col));
2429 col->icol = icol;
2430 col->replace = replace;
2431 col->setter = args->tgts_is_vcf ? vcf_setter_filter : setter_filter;
2432 col->hdr_key_src = strdup(str.s);
2433 col->hdr_key_dst = strdup(str.s);
2434 if ( args->tgts_is_vcf )
2435 {
2436 bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
2437 int j;
2438 for (j=0; j<tgts_hdr->nhrec; j++)
2439 {
2440 bcf_hrec_t *hrec = tgts_hdr->hrec[j];
2441 if ( hrec->type!=BCF_HL_FLT ) continue;
2442 int k = bcf_hrec_find_key(hrec,"ID");
2443 if ( k<0 ) error("[%s] Failed to parse the header, the ID attribute not found", __func__);
2444 tmp.l = 0;
2445 bcf_hrec_format(hrec, &tmp);
2446 bcf_hdr_append(args->hdr_out, tmp.s);
2447 }
2448 if (bcf_hdr_sync(args->hdr_out) < 0)
2449 error_errno("[%s] Failed to update header", __func__);
2450 }
2451 }
2452 else if ( !strcasecmp("QUAL",str.s) )
2453 {
2454 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -QUAL feature has not been implemented yet.\n");
2455 if ( replace & SET_OR_APPEND ) error("Apologies, the =QUAL feature has not been implemented yet.\n");
2456 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2457 annot_col_t *col = &args->cols[args->ncols-1];
2458 memset(col,0,sizeof(*col));
2459 col->icol = icol;
2460 col->replace = replace;
2461 col->setter = args->tgts_is_vcf ? vcf_setter_qual : setter_qual;
2462 col->hdr_key_src = strdup(str.s);
2463 col->hdr_key_dst = strdup(str.s);
2464 }
2465 else if ( args->tgts_is_vcf && !strcasecmp("INFO",str.s) ) // All INFO fields
2466 {
2467 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -INFO/TAG feature has not been implemented yet.\n");
2468 if ( replace & SET_OR_APPEND ) error("Apologies, the =INFO feature has not been implemented yet.\n");
2469 bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
2470 int j;
2471 for (j=0; j<tgts_hdr->nhrec; j++)
2472 {
2473 bcf_hrec_t *hrec = tgts_hdr->hrec[j];
2474 if ( hrec->type!=BCF_HL_INFO ) continue;
2475 int k = bcf_hrec_find_key(hrec,"ID");
2476 assert( k>=0 ); // this should always be true for valid VCFs
2477 if ( skip_info && khash_str2int_has_key(skip_info,hrec->vals[k]) ) continue;
2478 tmp.l = 0;
2479 bcf_hrec_format(hrec, &tmp);
2480 bcf_hdr_append(args->hdr_out, tmp.s);
2481 if (bcf_hdr_sync(args->hdr_out) < 0)
2482 error_errno("[%s] Failed to update header", __func__);
2483 int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, hrec->vals[k]);
2484 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2485 annot_col_t *col = &args->cols[args->ncols-1];
2486 memset(col,0,sizeof(*col));
2487 col->icol = -1;
2488 col->replace = replace;
2489 col->hdr_key_src = strdup(hrec->vals[k]);
2490 col->hdr_key_dst = strdup(hrec->vals[k]);
2491 col->number = bcf_hdr_id2length(args->hdr_out,BCF_HL_INFO,hdr_id);
2492 switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id) )
2493 {
2494 case BCF_HT_FLAG: col->setter = vcf_setter_info_flag; break;
2495 case BCF_HT_INT: col->setter = vcf_setter_info_int; break;
2496 case BCF_HT_REAL: col->setter = vcf_setter_info_real; break;
2497 case BCF_HT_STR: col->setter = vcf_setter_info_str; break;
2498 default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id));
2499 }
2500 }
2501 }
2502 else if ( args->tgts_is_vcf && (!strcasecmp("FORMAT",str.s) || !strcasecmp("FMT",str.s)) ) // All FORMAT fields
2503 {
2504 bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
2505 need_sample_map = 1;
2506 int j;
2507 for (j=0; j<tgts_hdr->nhrec; j++)
2508 {
2509 bcf_hrec_t *hrec = tgts_hdr->hrec[j];
2510 if ( hrec->type!=BCF_HL_FMT) continue;
2511 int k = bcf_hrec_find_key(hrec,"ID");
2512 assert( k>=0 ); // this should always be true for valid VCFs
2513 if ( skip_fmt && khash_str2int_has_key(skip_fmt,hrec->vals[k]) ) continue;
2514 tmp.l = 0;
2515 bcf_hrec_format(hrec, &tmp);
2516 bcf_hdr_append(args->hdr_out, tmp.s);
2517 if (bcf_hdr_sync(args->hdr_out) < 0)
2518 error_errno("[%s] Failed to update header", __func__);
2519 int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, hrec->vals[k]);
2520 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2521 annot_col_t *col = &args->cols[args->ncols-1];
2522 memset(col,0,sizeof(*col));
2523 col->icol = -1;
2524 col->replace = replace;
2525 col->hdr_key_src = strdup(hrec->vals[k]);
2526 col->hdr_key_dst = strdup(hrec->vals[k]);
2527 if ( !strcasecmp("GT",col->hdr_key_src) )
2528 {
2529 if ( !args->tgts_is_vcf ) error("The FORMAT/GT field can be currently populated only from a VCF\n");
2530 col->setter = vcf_setter_format_gt;
2531 }
2532 else
2533 switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id) )
2534 {
2535 case BCF_HT_INT: col->setter = vcf_setter_format_int; break;
2536 case BCF_HT_REAL: col->setter = vcf_setter_format_real; break;
2537 case BCF_HT_STR: col->setter = vcf_setter_format_str; has_fmt_str = 1; break;
2538 default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id));
2539 }
2540 hdr_id = bcf_hdr_id2int(tgts_hdr, BCF_DT_ID, hrec->vals[k]);
2541 col->number = bcf_hdr_id2length(tgts_hdr,BCF_HL_FMT,hdr_id);
2542 }
2543 }
2544 else if ( !strncasecmp("FORMAT/",str.s, 7) || !strncasecmp("FMT/",str.s,4) )
2545 {
2546 char *key_dst = str.s + (!strncasecmp("FMT/",str.s,4) ? 4 : 7);
2547 char *key_src = strstr(key_dst,":=");
2548 if ( key_src )
2549 {
2550 *key_src = 0;
2551 key_src += 2;
2552 if ( !strncasecmp("FORMAT/",key_src,7) ) key_src += 7;
2553 else if ( !strncasecmp("FMT/",key_src,4) ) key_src += 4;
2554 }
2555 else
2556 key_src = key_dst;
2557 need_sample_map = 1;
2558 if ( args->tgts_is_vcf )
2559 {
2560 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_FMT, "ID", key_src, NULL);
2561 if ( !hrec ) error("No such annotation \"%s\" in %s\n", key_src,args->targets_fname);
2562 tmp.l = 0;
2563 bcf_hrec_format_rename(hrec, key_dst, &tmp);
2564 bcf_hdr_append(args->hdr_out, tmp.s);
2565 if (bcf_hdr_sync(args->hdr_out) < 0)
2566 error_errno("[%s] Failed to update header", __func__);
2567 }
2568 int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
2569 if ( !bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_FMT,hdr_id) )
2570 error("The FORMAT tag \"%s\" is not defined in %s, was the -h option provided?\n", str.s, args->targets_fname);
2571 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2572 annot_col_t *col = &args->cols[args->ncols-1];
2573 memset(col,0,sizeof(*col));
2574 if ( !args->tgts_is_vcf )
2575 {
2576 col->icol = icol;
2577 icol += args->nsmpl_annot - 1;
2578 }
2579 else
2580 col->icol = -1;
2581 col->replace = replace;
2582 col->hdr_key_src = strdup(key_src);
2583 col->hdr_key_dst = strdup(key_dst);
2584 if ( !strcasecmp("GT",key_src) )
2585 {
2586 if ( !args->tgts_is_vcf ) error("The FORMAT/GT field can be currently populated only from a VCF\n");
2587 col->setter = vcf_setter_format_gt;
2588 }
2589 else
2590 switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id) )
2591 {
2592 case BCF_HT_INT: col->setter = args->tgts_is_vcf ? vcf_setter_format_int : setter_format_int; break;
2593 case BCF_HT_REAL: col->setter = args->tgts_is_vcf ? vcf_setter_format_real : setter_format_real; break;
2594 case BCF_HT_STR: col->setter = args->tgts_is_vcf ? vcf_setter_format_str : setter_format_str; has_fmt_str = 1; break;
2595 default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id));
2596 }
2597 if ( args->tgts_is_vcf )
2598 {
2599 bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
2600 hdr_id = bcf_hdr_id2int(tgts_hdr, BCF_DT_ID, col->hdr_key_src);
2601 col->number = bcf_hdr_id2length(tgts_hdr,BCF_HL_FMT,hdr_id);
2602 }
2603 }
2604 else
2605 {
2606 if ( replace & REPLACE_NON_MISSING ) error("Apologies, the -INFO/TAG feature has not been implemented yet.\n");
2607 if ( replace & SET_OR_APPEND )
2608 {
2609 if ( args->tgts_is_vcf )
2610 error("Error: the =INFO/TAG feature is currently supported only with TAB annotation files and has limitations\n"
2611 " (the annotation type is modified to \"Number=.\" and allele ordering is disregarded)\n");
2612 fprintf(bcftools_stderr,"Warning: the =INFO/TAG feature modifies the annotation to \"Number=.\" and disregards allele ordering\n");
2613 }
2614
2615 args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
2616 annot_col_t *col = &args->cols[args->ncols-1];
2617 memset(col,0,sizeof(*col));
2618 col->icol = icol;
2619 col->replace = replace;
2620
2621 int explicit_src_info = 0;
2622 int explicit_dst_info = 0;
2623 char *key_dst;
2624 if ( !strncasecmp("INFO/",str.s,5) )
2625 {
2626 key_dst = str.s + 5;
2627 explicit_dst_info = 1;
2628 }
2629 else if ( !strcasecmp("~INFO/END",str.s) )
2630 {
2631 key_dst = str.s + 6;
2632 explicit_dst_info = 1;
2633 }
2634 else
2635 key_dst = str.s;
2636 char *key_src = strstr(key_dst,":=");
2637 if ( key_src )
2638 {
2639 *key_src = 0;
2640 key_src += 2;
2641 if ( !strncasecmp("INFO/",key_src,5) )
2642 {
2643 key_src += 5;
2644 explicit_src_info = 1;
2645 }
2646 else if ( !strncasecmp("FMT/",key_src,4) || !strncasecmp("FORMAT/",key_src,5) )
2647 {
2648 key_src[-2] = ':';
2649 error("Did you mean \"FMT/%s\" rather than \"%s\"?\n",str.s,str.s);
2650 }
2651 else if ( !strcasecmp("FILTER",key_src) && args->tgts_is_vcf )
2652 {
2653 col->getter = vcf_getter_filter2str;
2654 }
2655 }
2656 else
2657 key_src = key_dst;
2658
2659 col->hdr_key_src = strdup(key_src);
2660 col->hdr_key_dst = strdup(key_dst);
2661
2662 int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
2663 if ( !bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_INFO,hdr_id) )
2664 {
2665 if ( args->tgts_is_vcf ) // reading annotations from a VCF, add a new header line
2666 {
2667 if ( !strcasecmp("ID",key_src) && !explicit_src_info )
2668 {
2669 // transferring ID column into a new INFO tag
2670 tmp.l = 0;
2671 ksprintf(&tmp,"##INFO=<ID=%s,Number=1,Type=String,Description=\"Transferred ID column\">",key_dst);
2672 }
2673 else if ( !strcasecmp("FILTER",key_src) && !explicit_src_info )
2674 {
2675 // transferring FILTER column into a new INFO tag
2676 tmp.l = 0;
2677 ksprintf(&tmp,"##INFO=<ID=%s,Number=1,Type=String,Description=\"Transferred FILTER column\">",key_dst);
2678 }
2679 else
2680 {
2681 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_INFO, "ID", key_src, NULL);
2682 if ( !hrec )
2683 {
2684 if ( explicit_dst_info+explicit_src_info==0 && bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_FMT, "ID", key_src, NULL) )
2685 error("Did you mean \"FMT/%s\" rather than \"%s\"?\n",str.s,str.s);
2686 char *ptr = strchr(key_src,'=');
2687 if ( ptr )
2688 {
2689 *ptr = 0; tmp.l = 0; ksprintf(&tmp,"%s:=%s",key_src,ptr+1); *ptr = '=';
2690 error("The INFO tag \"%s\" is not defined, is this what you want \"%s\" ?\n",key_src,tmp.s);
2691 }
2692 error("The INFO tag \"%s\" is not defined in %s, was the -h option provided?\n", key_src,args->files->readers[1].fname);
2693 }
2694 tmp.l = 0;
2695 bcf_hrec_format_rename(hrec, key_dst, &tmp);
2696 }
2697 bcf_hdr_append(args->hdr_out, tmp.s);
2698 if (bcf_hdr_sync(args->hdr_out) < 0)
2699 error_errno("[%s] Failed to update header", __func__);
2700 hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
2701 }
2702 else
2703 error("The INFO tag \"%s\" is not defined in %s, was the -h option provided?\n", key_dst, args->targets_fname);
2704 assert( bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_INFO,hdr_id) );
2705 }
2706 if ( args->tgts_is_vcf )
2707 {
2708 if ( !strcasecmp("ID",key_src) && !explicit_src_info ) col->getter = vcf_getter_id2str;
2709 else if ( !strcasecmp("FILTER",key_src) && !explicit_src_info ) col->getter = vcf_getter_filter2str;
2710 }
2711 col->number = bcf_hdr_id2length(args->hdr_out,BCF_HL_INFO,hdr_id);
2712 switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id) )
2713 {
2714 case BCF_HT_FLAG: col->setter = args->tgts_is_vcf ? vcf_setter_info_flag : setter_info_flag; break;
2715 case BCF_HT_INT: col->setter = args->tgts_is_vcf ? vcf_setter_info_int : setter_info_int; break;
2716 case BCF_HT_REAL: col->setter = args->tgts_is_vcf ? vcf_setter_info_real : setter_info_real; break;
2717 case BCF_HT_STR: col->setter = args->tgts_is_vcf ? vcf_setter_info_str : setter_info_str; break;
2718 default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id));
2719 }
2720 if ( replace & SET_OR_APPEND ) // change to Number=.
2721 {
2722 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->hdr_out, BCF_HL_INFO, "ID", key_dst, NULL);
2723 if ( !hrec ) error("Uh, could not find the new tag \"%s\" in the header\n", key_dst);
2724 hrec = bcf_hrec_dup(hrec);
2725 int j = bcf_hrec_find_key(hrec, "Number");
2726 if ( j<0 ) error("Uh, could not find the entry Number in the header record of %s\n",key_dst);
2727 free(hrec->vals[j]);
2728 hrec->vals[j] = strdup(".");
2729 bcf_hdr_remove(args->hdr_out,BCF_HL_INFO, key_dst);
2730 bcf_hdr_add_hrec(args->hdr_out, hrec);
2731 }
2732 }
2733 if ( !*se ) break;
2734 ss = ++se;
2735 }
2736 free(str.s);
2737 free(tmp.s);
2738 free(args->columns);
2739 if ( skip_info ) khash_str2int_destroy_free(skip_info);
2740 if ( skip_fmt ) khash_str2int_destroy_free(skip_fmt);
2741 if ( has_fmt_str )
2742 {
2743 int n = bcf_hdr_nsamples(args->hdr_out);
2744 if ( args->tgts_is_vcf && n<bcf_hdr_nsamples(args->files->readers[1].header) ) n = bcf_hdr_nsamples(args->files->readers[1].header);
2745 args->tmpp = (char**)malloc(sizeof(char*)*n);
2746 args->tmpp2 = (char**)malloc(sizeof(char*)*n);
2747 }
2748 if ( !need_sample_map )
2749 {
2750 free(args->sample_map);
2751 args->sample_map = NULL;
2752 }
2753 else if ( sample_map_ok<0 )
2754 error("No matching samples in source and destination file?\n");
2755 }
2756 static void init_merge_method(args_t *args)
2757 {
2758 int i;
2759 for (i=0; i<args->ncols; i++)
2760 {
2761 args->cols[i].merge_method = MM_FIRST;
2762 args->cols[i].mm_str_hash = NULL;
2763 args->cols[i].mm_dbl = NULL;
2764 args->cols[i].mm_dbl_nalloc = args->cols[i].mm_dbl_nused = args->cols[i].mm_dbl_ndat = 0;
2765 memset(&args->cols[i].mm_kstr, 0, sizeof(args->cols[i].mm_kstr));
2766 }
2767 if ( !args->merge_method_str.l ) return;
2768 if ( args->tgts_is_vcf ) error("Error: the --merge-logic is intended for use with BED or TAB-delimited files only.\n");
2769 if ( !args->tgt_idx && !args->tgts ) error("Error: BEG,END (or FROM,TO) columns or REF,ALT columns are expected with the --merge-logic option.\n");
2770 char *sb = args->merge_method_str.s;
2771 while ( *sb )
2772 {
2773 char *se = sb;
2774 while ( *se && *se!=',' ) se++;
2775 args->tmpks.l = 0;
2776 kputsn(sb, se-sb, &args->tmpks);
2777 kputc(0, &args->tmpks);
2778 char *mm_type_str = args->tmpks.s + args->tmpks.l;
2779 while ( *mm_type_str!=':' && mm_type_str > args->tmpks.s ) mm_type_str--;
2780 if ( *mm_type_str!=':' )
2781 error("Error: could not parse the argument to --merge-logic: %s\n", args->merge_method_str.s);
2782 *mm_type_str = 0;
2783 mm_type_str++;
2784 int mm_type = MM_FIRST;
2785 if ( !strcasecmp("unique",mm_type_str) ) mm_type = MM_UNIQUE;
2786 else if ( !strcasecmp("first",mm_type_str) ) mm_type = MM_FIRST;
2787 else if ( !strcasecmp("append",mm_type_str) ) mm_type = MM_APPEND;
2788 else if ( !strcasecmp("append-missing",mm_type_str) )
2789 {
2790 mm_type = MM_APPEND_MISSING;
2791 if ( args->ref_idx!=-1 ) args->has_append_mode = 1;
2792 }
2793 else if ( !strcasecmp("sum",mm_type_str) ) mm_type = MM_SUM;
2794 else if ( !strcasecmp("avg",mm_type_str) ) mm_type = MM_AVG;
2795 else if ( !strcasecmp("min",mm_type_str) ) mm_type = MM_MIN;
2796 else if ( !strcasecmp("max",mm_type_str) ) mm_type = MM_MAX;
2797 else error("Error: could not parse --merge-logic %s, the logic \"%s\" is not recognised\n", args->merge_method_str.s,mm_type_str);
2798 for (i=0; i<args->ncols; i++)
2799 {
2800 if ( strcmp(args->cols[i].hdr_key_dst,args->tmpks.s) ) continue;
2801 if ( (mm_type==MM_APPEND || mm_type==MM_APPEND_MISSING) && args->cols[i].number!=BCF_VL_VAR )
2802 error("Error: --merge-logic append can be requested only for tags of variable length (Number=.)\n");
2803 args->cols[i].merge_method = mm_type;
2804 break;
2805 }
2806 if ( i==args->ncols ) error("No such tag in the destination file: %s\n", args->tmpks.s);
2807 sb = *se ? se + 1 : se;
2808 }
2809 if ( args->has_append_mode )
2810 {
2811 // create a missing line to insert missing values when VCF ALT finds no match in the annotation file
2812 args->aline_missing = (annot_line_t*)calloc(1,sizeof(*args->aline_missing));
2813 int ncol = 0;
2814 for (i=0; i<args->ncols; i++)
2815 if ( ncol < args->cols[i].icol + 1 ) ncol = args->cols[i].icol + 1;
2816 if ( ncol < args->ref_idx + 1 ) ncol = args->ref_idx + 1;
2817 args->aline_missing->mcols = ncol;
2818 args->aline_missing->ncols = ncol;
2819 args->aline_missing->cols = (char**) malloc(ncol*sizeof(char*));
2820 for (i=0; i<ncol; i++)
2821 args->aline_missing->cols[i] = strdup(".");
2822 }
2823 }
2824
2825 static void rename_chrs(args_t *args, char *fname)
2826 {
2827 int n, i;
2828 char **map = hts_readlist(fname, 1, &n);
2829 if ( !map ) error("Could not read: %s\n", fname);
2830 for (i=0; i<n; i++)
2831 {
2832 char *ss = map[i];
2833 while ( *ss && !isspace(*ss) ) ss++;
2834 if ( !*ss ) error("Could not parse: %s\n", fname);
2835 *ss = 0;
2836 int rid = bcf_hdr_name2id(args->hdr_out, map[i]);
2837 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->hdr_out, BCF_HL_CTG, "ID", map[i], NULL);
2838 if ( !hrec ) continue; // the sequence not present
2839 int j = bcf_hrec_find_key(hrec, "ID");
2840 assert( j>=0 );
2841 free(hrec->vals[j]);
2842 ss++;
2843 while ( *ss && isspace(*ss) ) ss++;
2844 char *se = ss;
2845 while ( *se && !isspace(*se) ) se++;
2846 *se = 0;
2847 hrec->vals[j] = strdup(ss);
2848 args->hdr_out->id[BCF_DT_CTG][rid].key = hrec->vals[j];
2849 }
2850 for (i=0; i<n; i++) free(map[i]);
2851 free(map);
2852 }
2853 // Dirty: this relies on bcf_hdr_sync NOT being called
2854 static int rename_annots_core(args_t *args, char *ori_tag, char *new_tag)
2855 {
2856 int type;
2857 if ( !strncasecmp("info/",ori_tag,5) ) type = BCF_HL_INFO, ori_tag += 5;
2858 else if ( !strncasecmp("format/",ori_tag,7) ) type = BCF_HL_FMT, ori_tag += 7;
2859 else if ( !strncasecmp("fmt/",ori_tag,4) ) type = BCF_HL_FMT, ori_tag += 4;
2860 else if ( !strncasecmp("filter/",ori_tag,7) ) type = BCF_HL_FLT, ori_tag += 7;
2861 else return -1;
2862 if ( !strncasecmp("info/",new_tag,5) )
2863 {
2864 if ( type != BCF_HL_INFO ) error("Cannot transfer %s to INFO\n", ori_tag);
2865 new_tag += 5;
2866 }
2867 else if ( !strncasecmp("format/",new_tag,7) )
2868 {
2869 if ( type != BCF_HL_FMT ) error("Cannot transfer %s to FORMAT\n", ori_tag);
2870 new_tag += 7;
2871 }
2872 else if ( !strncasecmp("fmt/",new_tag,4) )
2873 {
2874 if ( type != BCF_HL_FMT ) error("Cannot transfer %s to FORMAT\n", ori_tag);
2875 new_tag += 4;
2876 }
2877 else if ( !strncasecmp("filter/",new_tag,7) )
2878 {
2879 if ( type != BCF_HL_FLT ) error("Cannot transfer %s to FILTER\n", ori_tag);
2880 new_tag += 7;
2881 }
2882 int id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, ori_tag);
2883 if ( id<0 ) return 1;
2884 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->hdr_out, type, "ID", ori_tag, NULL);
2885 if ( !hrec ) return 1; // the ID attribute not present
2886 int j = bcf_hrec_find_key(hrec, "ID");
2887 assert( j>=0 );
2888 free(hrec->vals[j]);
2889 char *ptr = new_tag;
2890 while ( *ptr && !isspace(*ptr) ) ptr++;
2891 *ptr = 0;
2892 hrec->vals[j] = strdup(new_tag);
2893 args->hdr_out->id[BCF_DT_ID][id].key = hrec->vals[j];
2894 return 0;
2895 }
2896 static void rename_annots(args_t *args)
2897 {
2898 int i;
2899 if ( args->rename_annots )
2900 {
2901 args->rename_annots_map = hts_readlist(args->rename_annots, 1, &args->rename_annots_nmap);
2902 if ( !args->rename_annots_map ) error("Could not read: %s\n", args->rename_annots);
2903 }
2904 for (i=0; i<args->rename_annots_nmap; i++)
2905 {
2906 char *ptr = args->rename_annots_map[i];
2907 while ( *ptr && !isspace(*ptr) ) ptr++;
2908 if ( !*ptr ) error("Could not parse: %s\n", args->rename_annots_map[i]);
2909 char *rmme = ptr;
2910 *ptr = 0;
2911 ptr++;
2912 while ( *ptr && isspace(*ptr) ) ptr++;
2913 if ( !*ptr ) { *rmme = ' '; error("Could not parse: %s\n", args->rename_annots_map[i]); }
2914 if ( rename_annots_core(args, args->rename_annots_map[i], ptr) < 0 )
2915 error("Cannot rename \"%s\" to \"%s\"\n",args->rename_annots_map[i],ptr);
2916 }
2917 }
2918 static void rename_annots_push(args_t *args, char *src, char *dst)
2919 {
2920 args->rename_annots_nmap++;
2921 args->rename_annots_map = (char**)realloc(args->rename_annots_map,sizeof(*args->rename_annots_map)*args->rename_annots_nmap);
2922 kstring_t str = {0,0,0};
2923 ksprintf(&str,"%s %s",src,dst);
2924 args->rename_annots_map[ args->rename_annots_nmap - 1 ] = str.s;
2925 }
2926 static void init_filters(args_t *args)
2927 {
2928 // Check if the -i/-e expressions contain external values that should be determined
2929 // on the fly from the annotation file. The expressions can be given as
2930 // TAG={NAME}
2931 // TAG={str:NAME}
2932 // TAG={int:NAME}
2933 // TAG={float:NAME}
2934 kstring_t str = {0,0,0};
2935 char *src = strdup(args->filter_str);
2936 int len = 0;
2937 while (1)
2938 {
2939 char *beg = strchr(src+len,'{');
2940 if ( !beg ) break;
2941
2942 // check if "{" appears inside quotes, in such case do not modify
2943 char skip = 0;
2944 char *tmp = src;
2945 while ( tmp<beg )
2946 {
2947 if ( tmp[0]!='"' && tmp[0]!='\'' ) { tmp++; continue; }
2948
2949 // quote character found
2950 int quote = tmp[0];
2951 tmp++;
2952 while ( *tmp && tmp[0]!=quote ) tmp++;
2953 if ( !*tmp ) error("Could not parse the expression: %s\n",args->filter_str); // unbalanced quotation; todo: check for escape char
2954 len = tmp - src + 1;
2955 skip = 1;
2956 }
2957 if ( skip ) continue;
2958
2959 char *end = ++beg;
2960 while ( *end && *end!='}' ) end++;
2961 if ( !*end ) error("Could not parse the expression: %s\n",args->filter_str);
2962 *end = 0;
2963
2964 // explicit typing?
2965 int type = -1;
2966 tmp = beg;
2967 while ( *tmp && *tmp!=':' ) tmp++;
2968 if ( *tmp )
2969 {
2970 *tmp = 0;
2971 if ( !strcasecmp(beg,"str") ) type = BCF_HT_STR;
2972 else if ( !strcasecmp(beg,"int") ) type = BCF_HT_INT;
2973 else if ( !strcasecmp(beg,"float") ) type = BCF_HT_REAL;
2974 }
2975 args->n_ext++;
2976 args->ext = (ext_t*)realloc(args->ext,sizeof(*args->ext)*args->n_ext);
2977 ext_t *ext = &args->ext[args->n_ext-1];
2978 ext->ht_type = type;
2979 ext->name = strdup(beg);
2980 if ( beg-1 > src ) kputsn(src,beg-1-src,&str);
2981 if ( type==-1 ) kputs("{}",&str);
2982 else if ( type==BCF_HT_STR ) kputs("{str}",&str);
2983 else if ( type==BCF_HT_INT ) kputs("{int}",&str);
2984 else if ( type==BCF_HT_REAL ) kputs("{float}",&str);
2985 len = str.l;
2986 kputs(end+1,&str);
2987 free(src);
2988 src = strdup(str.s);
2989 str.l = 0;
2990 }
2991 args->filter = filter_init(args->hdr, src);
2992 free(src);
2993 free(str.s);
2994
2995 int i,j,n_ext;
2996 const int *ext_type = filter_ext_types(args->filter, &n_ext);
2997 if ( n_ext != args->n_ext )
2998 error("Failed to parse the expression, unexpected number of dynamic variables (%d vs %d): %s\n",n_ext,args->n_ext,args->filter_str);
2999
3000 if ( !args->n_ext ) return;
3001
3002 if ( !args->tgts )
3003 error("Error: dynamic variables in -i/-e expressions can be currently used only with tab-delimited file, not with VCF (todo)\n");
3004
3005 // contains external values
3006 args->ext_ptr = malloc(sizeof(*args->ext_ptr)*args->n_ext);
3007 for (i=0; i<args->n_ext; i++) args->ext[i].ht_type = ext_type[i];
3008 args->filter_ext = args->filter;
3009 args->filter = NULL;
3010
3011 // set the column idx
3012 if ( args->ncols )
3013 {
3014 for (i=0; i<args->n_ext; i++)
3015 {
3016 for (j=0; j<args->ncols; j++)
3017 {
3018 if ( strcmp(args->ext[i].name,args->cols[j].hdr_key_src) ) continue;
3019 args->ext[i].icol = args->cols[j].icol;
3020 break;
3021 }
3022 if ( j==args->ncols ) error("No such column: %s\n",args->ext[i].name);
3023 }
3024 }
3025 }
3026
3027 static void init_data(args_t *args)
3028 {
3029 args->hdr = args->files->readers[0].header;
3030 args->hdr_out = bcf_hdr_dup(args->hdr);
3031
3032 if ( args->set_ids_fmt )
3033 {
3034 if ( args->set_ids_fmt[0]=='+' ) { args->set_ids_replace = 0; args->set_ids_fmt++; }
3035 args->set_ids = convert_init(args->hdr_out, NULL, 0, args->set_ids_fmt);
3036 }
3037 if ( args->remove_annots ) init_remove_annots(args);
3038 if ( args->header_fname || args->header_lines ) init_header_lines(args);
3039 if ( args->targets_fname && args->tgts_is_vcf )
3040 {
3041 // reading annots from a VCF
3042 if ( !bcf_sr_add_reader(args->files, args->targets_fname) )
3043 error("Failed to open %s: %s\n", args->targets_fname,bcf_sr_strerror(args->files->errnum));
3044 args->tgts_hdr = args->files->readers[1].header;
3045 }
3046 if ( args->columns ) init_columns(args);
3047 if ( args->targets_fname && !args->tgts_is_vcf )
3048 {
3049 if ( !args->columns ) error("The -c option not given\n");
3050 if ( args->chr_idx==-1 ) error("The -c CHROM option not given\n");
3051 if ( args->beg_idx==-1 ) error("The -c POS option not given\n");
3052 if ( args->single_overlaps && args->merge_method_str.l ) error("The options --merge-logic and --single-overlaps cannot be combined\n");
3053 if ( args->end_idx==-1 || (args->single_overlaps && !args->merge_method_str.l) )
3054 {
3055 args->end_idx = -args->beg_idx - 1;
3056 args->tgts = bcf_sr_regions_init(args->targets_fname,1,args->chr_idx,args->beg_idx,args->end_idx);
3057 if ( !args->tgts ) error("Could not initialize the annotation file: %s\n", args->targets_fname);
3058 if ( !args->tgts->tbx ) error("Expected tabix-indexed annotation file: %s\n", args->targets_fname);
3059 }
3060 else
3061 {
3062 if ( args->ref_idx!=-1 ) error("Error: the REF columns will be ignored when BEG,END (or FROM,TO) is present. Replace END (or TO) with \"-\".\n");
3063 int len = strlen(args->targets_fname);
3064 if ( len>=7 && !strcasecmp(".bed.gz",args->targets_fname+len-7) ) args->tgt_is_bed = 1;
3065 else if ( len>=8 && !strcasecmp(".bed.bgz",args->targets_fname+len-8) ) args->tgt_is_bed = 1;
3066 else if ( len>=4 && !strcasecmp(".bed",args->targets_fname+len-4) ) args->tgt_is_bed = 1;
3067 args->tgt_idx = regidx_init(args->targets_fname,parse_with_payload,free_payload,sizeof(char*),args);
3068 if ( !args->tgt_idx ) error("Failed to parse: %s\n", args->targets_fname);
3069 args->tgt_itr = regitr_init(args->tgt_idx);
3070 args->nalines++;
3071 hts_expand0(annot_line_t,args->nalines,args->malines,args->alines);
3072 }
3073 if ( args->min_overlap_str )
3074 {
3075 char *tmp = args->min_overlap_str;
3076 if ( args->min_overlap_str[0] != ':' )
3077 {
3078 args->min_overlap_ann = strtod(args->min_overlap_str,&tmp);
3079 if ( args->min_overlap_ann < 0 || args->min_overlap_ann > 1 || (*tmp && *tmp!=':') )
3080 error("Could not parse \"--min-overlap %s\", expected value(s) between 0-1\n", args->min_overlap_str);
3081 }
3082 if ( *tmp && *tmp==':' )
3083 {
3084 args->min_overlap_vcf = strtod(tmp+1,&tmp);
3085 if ( args->min_overlap_vcf < 0 || args->min_overlap_vcf > 1 || *tmp )
3086 error("Could not parse \"--min-overlap %s\", expected value(s) between 0-1\n", args->min_overlap_str);
3087 }
3088 }
3089 }
3090 init_merge_method(args);
3091 args->vcmp = vcmp_init();
3092
3093 if ( args->filter_str )
3094 init_filters(args);
3095
3096 if ( args->mark_sites )
3097 {
3098 if ( !args->targets_fname )
3099 {
3100 if ( args->mark_sites_logic!=MARK_LISTED ) error("The -a option not given but -%s logic was requested\n",args->mark_sites);
3101 fprintf(bcftools_stderr,"Note: The -a option not given, all sites will be annotated with INFO/%s\n",args->mark_sites);
3102 bcf_hdr_printf(args->hdr_out,"##INFO=<ID=%s,Number=0,Type=Flag,Description=\"Sites marked with `bcftools annotate -m %s`\">",
3103 args->mark_sites,args->mark_sites);
3104 }
3105 else
3106 bcf_hdr_printf(args->hdr_out,"##INFO=<ID=%s,Number=0,Type=Flag,Description=\"Sites %slisted in %s\">",
3107 args->mark_sites,args->mark_sites_logic==MARK_LISTED?"":"not ",args->mark_sites);
3108 }
3109
3110 if (args->record_cmd_line) bcf_hdr_append_version(args->hdr_out, args->argc, args->argv, "bcftools_annotate");
3111 if ( !args->drop_header )
3112 {
3113 if ( args->rename_chrs ) rename_chrs(args, args->rename_chrs);
3114 if ( args->rename_annots || args->rename_annots_map ) rename_annots(args);
3115
3116 char wmode[8];
3117 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
3118 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
3119 if ( args->out_fh == NULL ) error("[%s] Error: cannot write to \"%s\": %s\n", __func__,args->output_fname, strerror(errno));
3120 if ( args->n_threads )
3121 hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->files->p);
3122 if ( bcf_hdr_write(args->out_fh, args->hdr_out)!=0 ) error("[%s] Error: failed to write the header to %s\n", __func__,args->output_fname);
3123 if ( init_index2(args->out_fh,args->hdr,args->output_fname,
3124 &args->index_fn, args->write_index) < 0 )
3125 error("Error: failed to initialise index for %s\n",args->output_fname);
3126 }
3127 }
3128
3129 static void destroy_data(args_t *args)
3130 {
3131 int i;
3132 for (i=0; i<args->n_ext; i++)
3133 {
3134 free(args->ext[i].name);
3135 if ( args->ext[i].ht_type!=BCF_HT_STR ) continue;
3136 }
3137 free(args->ext_ptr);
3138 free(args->ext);
3139 for (i=0; i<args->nrm; i++) free(args->rm[i].key);
3140 free(args->rm);
3141 if ( args->hdr_out ) bcf_hdr_destroy(args->hdr_out);
3142 if (args->vcmp) vcmp_destroy(args->vcmp);
3143 for (i=0; i<args->ncols; i++)
3144 {
3145 free(args->cols[i].hdr_key_src);
3146 free(args->cols[i].hdr_key_dst);
3147 free(args->cols[i].mm_kstr.s);
3148 if ( args->cols[i].mm_str_hash ) khash_str2int_destroy_free(args->cols[i].mm_str_hash);
3149 free(args->cols[i].mm_dbl);
3150 free(args->cols[i].ptr);
3151 }
3152 free(args->cols);
3153 if ( args->aline_missing )
3154 {
3155 for (i=0; i<args->aline_missing->ncols; i++) free(args->aline_missing->cols[i]);
3156 free(args->aline_missing->cols);
3157 free(args->aline_missing);
3158 }
3159 for (i=0; i<args->malines; i++)
3160 {
3161 free(args->alines[i].cols);
3162 free(args->alines[i].als);
3163 free(args->alines[i].line.s);
3164 }
3165 free(args->alines);
3166 free(args->srt_alines);
3167 if ( args->tgt_idx )
3168 {
3169 regidx_destroy(args->tgt_idx);
3170 regitr_destroy(args->tgt_itr);
3171 }
3172 if ( args->rename_annots_map )
3173 {
3174 for (i=0; i<args->rename_annots_nmap; i++) free(args->rename_annots_map[i]);
3175 free(args->rename_annots_map);
3176 }
3177 if ( args->tgts ) bcf_sr_regions_destroy(args->tgts);
3178 free(args->tmpks.s);
3179 free(args->tmpi);
3180 free(args->tmpf);
3181 free(args->tmps);
3182 free(args->tmpp);
3183 free(args->tmpi2);
3184 free(args->tmpf2);
3185 free(args->tmps2);
3186 free(args->tmpp2);
3187 free(args->tmpi3);
3188 free(args->tmpf3);
3189 free(args->src_smpl_pld);
3190 free(args->dst_smpl_pld);
3191 if ( args->set_ids )
3192 convert_destroy(args->set_ids);
3193 if ( args->filter ) filter_destroy(args->filter);
3194 if ( args->filter_ext ) filter_destroy(args->filter_ext);
3195 if (args->out_fh)
3196 {
3197 if ( args->write_index )
3198 {
3199 if ( bcf_idx_save(args->out_fh)<0 )
3200 {
3201 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
3202 error("Error: cannot write to index %s\n", args->index_fn);
3203 }
3204 free(args->index_fn);
3205 }
3206 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
3207 }
3208 free(args->sample_map);
3209 free(args->merge_method_str.s);
3210 }
3211
3212 static void parse_annot_line(args_t *args, char *str, annot_line_t *tmp)
3213 {
3214 tmp->line.l = 0;
3215 kputs(str, &tmp->line);
3216 char *s = tmp->line.s;
3217 tmp->ncols = 1;
3218 hts_expand(char*,tmp->ncols,tmp->mcols,tmp->cols);
3219 tmp->cols[0] = s;
3220 while ( *s )
3221 {
3222 if ( *s=='\t' )
3223 {
3224 tmp->ncols++;
3225 hts_expand(char*,tmp->ncols,tmp->mcols,tmp->cols);
3226 tmp->cols[tmp->ncols-1] = s+1;
3227 *s = 0;
3228 }
3229 s++;
3230 }
3231 if ( args->ref_idx != -1 )
3232 {
3233 if ( args->ref_idx >= tmp->ncols )
3234 error("Could not parse the line, expected %d+ columns, found %d:\n\t%s\n",args->ref_idx+1,tmp->ncols,str);
3235 if ( args->alt_idx >= tmp->ncols )
3236 error("Could not parse the line, expected %d+ columns, found %d:\n\t%s\n",args->alt_idx+1,tmp->ncols,str);
3237 tmp->nals = 2;
3238 hts_expand(char*,tmp->nals,tmp->mals,tmp->als);
3239 tmp->als[0] = tmp->cols[args->ref_idx];
3240 tmp->als[1] = s = tmp->cols[args->alt_idx];
3241 while ( *s )
3242 {
3243 if ( *s==',' )
3244 {
3245 tmp->nals++;
3246 hts_expand(char*,tmp->nals,tmp->mals,tmp->als);
3247 tmp->als[tmp->nals-1] = s+1;
3248 *s = 0;
3249 }
3250 s++;
3251 }
3252 }
3253 }
3254 static void buffer_annot_lines(args_t *args, bcf1_t *line, int start_pos, int end_pos)
3255 {
3256 if ( args->nalines && args->alines[0].rid != line->rid ) args->nalines = 0;
3257
3258 int i = 0;
3259 while ( i<args->nalines )
3260 {
3261 if ( line->pos > args->alines[i].end )
3262 {
3263 args->nalines--;
3264 if ( args->nalines && i<args->nalines )
3265 {
3266 annot_line_t tmp = args->alines[i];
3267 memmove(&args->alines[i],&args->alines[i+1],(args->nalines-i)*sizeof(annot_line_t));
3268 args->alines[args->nalines] = tmp;
3269 }
3270 }
3271 else i++;
3272 }
3273 if ( !args->filter_ext && args->ref_idx==-1 && args->nalines ) return;
3274
3275 while ( !bcf_sr_regions_overlap(args->tgts, bcf_seqname(args->hdr,line), start_pos,end_pos) )
3276 {
3277 if ( args->nalines + 1 == 0xffff ) break; // likely a symbolic allele, don't let the buffer overflow
3278 args->nalines++;
3279 hts_expand0(annot_line_t,args->nalines,args->malines,args->alines);
3280 annot_line_t *tmp = &args->alines[args->nalines-1];
3281 tmp->rid = line->rid;
3282 tmp->start = args->tgts->start;
3283 tmp->end = args->tgts->end;
3284 parse_annot_line(args, args->tgts->line.s, tmp);
3285 if ( args->filter_ext || args->ref_idx != -1 )
3286 {
3287 int iseq = args->tgts->iseq;
3288 if ( bcf_sr_regions_next(args->tgts)<0 || args->tgts->iseq!=iseq ) break;
3289 }
3290 else break;
3291 }
3292 }
3293
3294 // search string in semicolon separated strings (xx vs aa;bb)
3295 static int str_match(char *needle, char *haystack)
3296 {
3297 int len = strlen(needle);
3298 char *ptr = haystack;
3299 while ( *ptr && (ptr=strstr(ptr,needle)) )
3300 {
3301 if ( ptr[len]!=0 && ptr[len]!=';' ) ptr++; // a prefix, not a match
3302 else if ( ptr==haystack || ptr[-1]==';' ) return 1; // a match
3303 ptr++; // a suffix, not a match
3304 }
3305 return 0;
3306 }
3307 // search common string in semicolon separated strings (xx;yy;zz vs aa;bb)
3308 static int strstr_match(char *a, char *b)
3309 {
3310 char *beg = a;
3311 while ( *beg )
3312 {
3313 char *end = beg;
3314 while ( *end && *end!=';' ) end++;
3315 char tmp = *end;
3316 if ( *end==';' ) *end = 0;
3317 int ret = str_match(beg,b);
3318 *end = tmp;
3319 if ( ret || !*end ) return ret;
3320 beg = end + 1;
3321 }
3322 return 0;
3323 }
3324 static int annotate_from_regidx(args_t *args, bcf1_t *line)
3325 {
3326 int j;
3327 int has_overlap = 0;
3328
3329 for (j=0; j<args->ncols; j++) args->cols[j].done = 0;
3330 if ( regidx_overlap(args->tgt_idx, bcf_seqname(args->hdr,line),line->pos,line->pos+line->rlen-1, args->tgt_itr) )
3331 {
3332 hts_pos_t vcf_end = line->pos + line->rlen - 1;
3333 while ( regitr_overlap(args->tgt_itr) )
3334 {
3335 annot_line_t *tmp = &args->alines[0];
3336 tmp->rid = line->rid;
3337 tmp->start = args->tgt_itr->beg;
3338 tmp->end = args->tgt_itr->end;
3339
3340 // Check min overlap
3341 int len_ann = tmp->end - tmp->start + 1;
3342 int len_vcf = line->rlen;
3343 int isec = (tmp->end < vcf_end ? tmp->end : vcf_end) - (tmp->start > line->pos ? tmp->start : line->pos) + 1;
3344 assert( isec > 0 );
3345 if ( args->min_overlap_ann && args->min_overlap_ann > (float)isec/len_ann ) continue;
3346 if ( args->min_overlap_vcf && args->min_overlap_vcf > (float)isec/len_vcf ) continue;
3347
3348 parse_annot_line(args, regitr_payload(args->tgt_itr,char*), tmp);
3349
3350 // If a plain BED file is provided and we are asked to just mark overlapping sites, there are
3351 // no additional columns. Not sure if there can be any side effects for ill-formatted BED files
3352 // with variable number of columns
3353 if ( !args->ncols && args->mark_sites ) has_overlap = 1;
3354
3355 for (j=0; j<args->ncols; j++)
3356 {
3357 if ( args->cols[j].done==1 ) continue;
3358 int ret = args->cols[j].setter(args,line,&args->cols[j],tmp);
3359 if ( ret < 0 )
3360 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3361 if ( ret==0 )
3362 args->cols[j].done = 1;
3363 has_overlap = 1;
3364 }
3365 }
3366 }
3367 for (j=0; j<args->ncols; j++)
3368 {
3369 if ( args->cols[j].done==1 || args->cols[j].merge_method == MM_FIRST ) continue;
3370 if ( !args->cols[j].setter ) continue;
3371 if ( args->cols[j].setter(args,line,&args->cols[j],NULL) < 0 )
3372 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3373 }
3374 return has_overlap;
3375 }
3376 static int pass_filter_test_ext(args_t *args, bcf1_t *line, annot_line_t *ann)
3377 {
3378 char *tmp;
3379 int i;
3380 for (i=0; i<args->n_ext; i++)
3381 {
3382 int j = args->ext[i].icol;
3383 if ( args->ext[i].ht_type==BCF_HT_STR ) args->ext_ptr[i] = args->ext[i].s = ann->cols[j];
3384 else if ( args->ext[i].ht_type==BCF_HT_INT )
3385 {
3386 args->ext[i].i = strtol(ann->cols[j],&tmp,10);
3387 if ( *tmp )
3388 {
3389 if ( strcmp(".",ann->cols[j]) ) error("Error: could not parse the annotation file, expected an integer, found \"%s\"\n",ann->cols[j]);
3390 args->ext_ptr[i] = NULL;
3391 }
3392 else
3393 args->ext_ptr[i] = &args->ext[i].i;
3394 }
3395 else if ( args->ext[i].ht_type==BCF_HT_REAL )
3396 {
3397 args->ext[i].f = strtod(ann->cols[j],&tmp);
3398 if ( *tmp )
3399 {
3400 if ( strcmp(".",ann->cols[j]) ) error("Error: could not parse the annotation file, expected a float, found \"%s\"\n",ann->cols[j]);
3401 args->ext_ptr[i] = NULL;
3402 }
3403 else
3404 args->ext_ptr[i] = &args->ext[i].f;
3405 }
3406 }
3407 int pass = filter_test_ext(args->filter_ext,line,NULL,(const void**)args->ext_ptr);
3408 if ( args->filter_logic==FLT_EXCLUDE ) pass = pass ? 0 : 1;
3409 return pass;
3410 }
3411 static int annotate_from_tab(args_t *args, bcf1_t *line)
3412 {
3413 int i,j;
3414 int has_overlap = 0;
3415
3416 // Buffer annotation lines. When multiple ALT alleles are present in the annotation file, at least one
3417 // must match some of the VCF alleles. If the append-missing mode is set (and REF+ALT is requested), the
3418 // buffered lines will annotate the VCF respecting the order in ALT and when no matching line is found
3419 // for an ALT, missing value is appended instead.
3420 int end_pos = line->pos + line->rlen - 1;
3421 buffer_annot_lines(args, line, line->pos, end_pos);
3422
3423 args->nsrt_alines = 0;
3424 hts_expand(uint32_t,args->nalines,args->msrt_alines,args->srt_alines);
3425 if ( args->nalines >= 0xffff || line->n_allele >= 0xffff )
3426 error("Error: too many alleles or annotation lines in the buffer at %s:%"PRId64" (todo:skip?)\n",bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3427
3428 kstring_t match_end = {0,0,0};
3429 if ( args->match_end>=0 && bcf_get_info_int32(args->hdr,line,"END",&args->tmpi,&args->mtmpi)==1 )
3430 kputw(args->tmpi[0],&match_end);
3431
3432 // Find matching lines
3433 for (i=0; i<args->nalines; i++)
3434 {
3435 if ( line->pos > args->alines[i].end || end_pos < args->alines[i].start ) continue;
3436 if ( args->ref_idx != -1 ) // REF+ALT matching requested
3437 {
3438 if ( line->pos!=args->alines[i].start || vcmp_set_ref(args->vcmp, line->d.allele[0], args->alines[i].als[0]) < 0 ) continue; // refs are not compatible
3439 for (j=1; j<args->alines[i].nals; j++)
3440 {
3441 int ialt;
3442 if ( line->n_allele==1 && args->alines[i].als[j][0]=='.' && args->alines[i].als[j][1]==0 ) // match: no ALT allele in VCF and annot file has "."
3443 ialt = 0;
3444 else
3445 {
3446 ialt = vcmp_find_allele(args->vcmp, line->d.allele+1, line->n_allele - 1, args->alines[i].als[j]);
3447 if ( ialt < 0 ) continue;
3448 ialt++;
3449 }
3450 if ( args->match_id>=0 && !strstr_match(line->d.id,args->alines[i].cols[args->match_id]) ) continue;
3451 if ( args->match_end>=0 && match_end.l && strcmp(match_end.s,args->alines[i].cols[args->match_end]) ) continue;
3452 if ( args->filter_ext && !pass_filter_test_ext(args,line,&args->alines[i]) ) continue;
3453 args->srt_alines[args->nsrt_alines++] = (ialt<<16) | i;
3454 has_overlap = 1;
3455 break;
3456 }
3457 }
3458 else if ( args->filter_ext )
3459 {
3460 if ( pass_filter_test_ext(args,line,&args->alines[i]) )
3461 {
3462 args->srt_alines[args->nsrt_alines++] = (0xffff<<16) | i;
3463 has_overlap = 1;
3464 }
3465 }
3466 else // overlap, REF+ALT matching not requested
3467 {
3468 args->srt_alines[args->nsrt_alines++] = (0xffff<<16) | i;
3469 has_overlap = 1;
3470 }
3471 }
3472
3473 free(match_end.s);
3474 if ( !has_overlap && args->filter_ext && !args->keep_sites ) return has_overlap;
3475
3476 // Sort lines if needed
3477 if ( args->has_append_mode )
3478 {
3479 // insertion sort by VCF ALT index (top bits) and alines index (low bits)
3480 uint32_t tmp;
3481 for (i=1; i<args->nsrt_alines; i++)
3482 for (j=i; j>0 && args->srt_alines[j] < args->srt_alines[j-1]; j--)
3483 tmp = args->srt_alines[j], args->srt_alines[j] = args->srt_alines[j-1], args->srt_alines[j-1] = tmp;
3484 }
3485 // Annotate
3486 for (j=0; j<args->ncols; j++) args->cols[j].done = 0;
3487 int ialt_exp = 1;
3488 for (i=0; i<args->nsrt_alines; i++)
3489 {
3490 int ialt = args->srt_alines[i] >> 16;
3491 int ilin = args->srt_alines[i] & 0xffff;
3492 if ( args->has_append_mode )
3493 {
3494 if ( ialt_exp > ialt ) continue; // multiple annotation lines for the same position
3495 if ( ialt_exp < ialt )
3496 {
3497 // REF+ALT matching requested, append-missing mode: insert "." if no annotation line was found for the ALT
3498 while ( ialt_exp++ < ialt )
3499 {
3500 for (j=0; j<args->ncols; j++)
3501 {
3502 if ( args->cols[j].merge_method != MM_APPEND_MISSING ) continue;
3503 if ( args->cols[j].done==1 ) continue;
3504 if ( !args->cols[j].setter ) continue;
3505 int ret = args->cols[j].setter(args,line,&args->cols[j],args->aline_missing);
3506 if ( ret < 0 )
3507 error("fixme: Could not set missing %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3508 if ( ret==0 )
3509 args->cols[j].done = 1;
3510 }
3511 }
3512 }
3513 }
3514 for (j=0; j<args->ncols; j++)
3515 {
3516 if ( args->cols[j].done==1 ) continue;
3517 if ( !args->cols[j].setter ) continue;
3518 int ret = args->cols[j].setter(args,line,&args->cols[j],&args->alines[ilin]);
3519 if ( ret < 0 )
3520 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3521 if ( ret==0 )
3522 args->cols[j].done = 1;
3523 }
3524 ialt_exp = ialt + 1;
3525 }
3526 if ( args->nsrt_alines )
3527 {
3528 // In the append-missing mode fill missing values to all trailing ALTs, but only if at least one
3529 // record was found. Otherwise leave the row will be left without annotation.
3530 if ( args->has_append_mode && ialt_exp < line->n_allele )
3531 {
3532 while ( ialt_exp++ < line->n_allele )
3533 {
3534 for (j=0; j<args->ncols; j++)
3535 {
3536 if ( args->cols[j].merge_method != MM_APPEND_MISSING ) continue;
3537 if ( args->cols[j].done==1 ) continue;
3538 if ( !args->cols[j].setter ) continue;
3539 int ret = args->cols[j].setter(args,line,&args->cols[j],args->aline_missing);
3540 if ( ret < 0 )
3541 error("fixme: Could not set missing %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3542 if ( ret==0 )
3543 args->cols[j].done = 1;
3544 }
3545 }
3546 }
3547 // Flush
3548 for (j=0; j<args->ncols; j++)
3549 {
3550 if ( args->cols[j].done==1 || args->cols[j].merge_method == MM_FIRST ) continue;
3551 if ( !args->cols[j].setter ) continue;
3552 int ret = args->cols[j].setter(args,line,&args->cols[j],NULL);
3553 if ( ret < 0 )
3554 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3555 }
3556 }
3557 return has_overlap;
3558 }
3559 static int annotate_from_vcf(args_t *args, bcf1_t *line)
3560 {
3561 if ( !bcf_sr_has_line(args->files,1) ) return 0;
3562 int j;
3563 bcf1_t *aline = bcf_sr_get_line(args->files,1);
3564 for (j=0; j<args->ncols; j++)
3565 {
3566 if ( !args->cols[j].setter ) continue;
3567 if ( args->cols[j].setter(args,line,&args->cols[j],aline) )
3568 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3569 }
3570 return 1;
3571 }
3572 static int annotate_from_self(args_t *args, bcf1_t *line)
3573 {
3574 int j;
3575 for (j=0; j<args->ncols; j++)
3576 {
3577 if ( !args->cols[j].setter ) continue;
3578 if ( args->cols[j].setter(args,line,&args->cols[j],NULL) )
3579 error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
3580 }
3581 return 0;
3582 }
3583 static int annotate_line(args_t *args, bcf1_t *line)
3584 {
3585 args->current_rec = line;
3586
3587 int i;
3588 for (i=0; i<args->nrm; i++)
3589 args->rm[i].handler(args, line, &args->rm[i]);
3590
3591 int has_overlap = 0;
3592 if ( args->tgt_idx )
3593 has_overlap = annotate_from_regidx(args,line);
3594
3595 else if ( args->tgts )
3596 has_overlap = annotate_from_tab(args,line);
3597
3598 else if ( args->files->nreaders == 2 )
3599 has_overlap = annotate_from_vcf(args,line);
3600
3601 else if ( args->ncols )
3602 has_overlap = annotate_from_self(args,line);
3603
3604 if ( args->set_ids )
3605 {
3606 args->tmpks.l = 0;
3607 convert_line(args->set_ids, line, &args->tmpks);
3608 if ( args->tmpks.l )
3609 {
3610 int replace = 0;
3611 if ( args->set_ids_replace ) replace = 1;
3612 else if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) ) replace = 1;
3613 if ( replace )
3614 bcf_update_id(args->hdr_out,line,args->tmpks.s);
3615 }
3616 }
3617
3618 if ( args->mark_sites )
3619 {
3620 if ( !args->targets_fname ) has_overlap = 1;
3621
3622 // ideally, we'd like to be far more general than this in future, see https://github.com/samtools/bcftools/issues/87
3623 if ( args->mark_sites_logic==MARK_LISTED )
3624 bcf_update_info_flag(args->hdr_out,line,args->mark_sites,NULL,has_overlap?1:0);
3625 else
3626 bcf_update_info_flag(args->hdr_out,line,args->mark_sites,NULL,has_overlap?0:1);
3627 }
3628
3629 return has_overlap;
3630 }
3631
3632 static void usage(args_t *args)
3633 {
3634 fprintf(bcftools_stderr, "\n");
3635 fprintf(bcftools_stderr, "About: Annotate and edit VCF/BCF files.\n");
3636 fprintf(bcftools_stderr, "Usage: bcftools annotate [options] VCF\n");
3637 fprintf(bcftools_stderr, "\n");
3638 fprintf(bcftools_stderr, "Options:\n");
3639 fprintf(bcftools_stderr, " -a, --annotations FILE VCF file or tabix-indexed FILE with annotations: CHR\\tPOS[\\tVALUE]+\n");
3640 fprintf(bcftools_stderr, " -c, --columns LIST List of columns in the annotation file, e.g. CHROM,POS,REF,ALT,-,INFO/TAG. See man page for details\n");
3641 fprintf(bcftools_stderr, " -C, --columns-file FILE Read -c columns from FILE, one name per row, with optional --merge-logic TYPE: NAME[ TYPE]\n");
3642 fprintf(bcftools_stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n");
3643 fprintf(bcftools_stderr, " --force Continue despite parsing error (at your own risk!)\n");
3644 fprintf(bcftools_stderr, " -H, --header-line STR Header line which should be appended to the VCF header, can be given multiple times\n");
3645 fprintf(bcftools_stderr, " -h, --header-lines FILE Lines which should be appended to the VCF header\n");
3646 fprintf(bcftools_stderr, " -I, --set-id [+]FORMAT Set ID column using a `bcftools query`-like expression, see man page for details\n");
3647 fprintf(bcftools_stderr, " -i, --include EXPR Select sites for which the expression is true (see man page for details)\n");
3648 fprintf(bcftools_stderr, " -k, --keep-sites Leave -i/-e sites unchanged instead of discarding them\n");
3649 fprintf(bcftools_stderr, " -l, --merge-logic TAG:TYPE Merge logic for multiple overlapping regions (see man page for details), EXPERIMENTAL\n");
3650 fprintf(bcftools_stderr, " -m, --mark-sites [+-]TAG Add INFO/TAG flag to sites which are (\"+\") or are not (\"-\") listed in the -a file\n");
3651 fprintf(bcftools_stderr, " --min-overlap ANN:VCF Required overlap as a fraction of variant in the -a file (ANN), the VCF (:VCF), or reciprocal (ANN:VCF)\n");
3652 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
3653 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
3654 fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
3655 fprintf(bcftools_stderr, " --pair-logic STR Matching records by <snps|indels|both|all|some|exact>, see man page for details [some]\n");
3656 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
3657 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in FILE\n");
3658 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
3659 fprintf(bcftools_stderr, " --rename-annots FILE Rename annotations: TYPE/old\\tnew, where TYPE is one of FILTER,INFO,FORMAT\n");
3660 fprintf(bcftools_stderr, " --rename-chrs FILE Rename sequences according to the mapping: old\\tnew\n");
3661 fprintf(bcftools_stderr, " -s, --samples [^]LIST Comma separated list of samples to annotate (or exclude with \"^\" prefix)\n");
3662 fprintf(bcftools_stderr, " -S, --samples-file [^]FILE File of samples to annotate (or exclude with \"^\" prefix)\n");
3663 fprintf(bcftools_stderr, " --single-overlaps Keep memory low by avoiding complexities arising from handling multiple overlapping intervals\n");
3664 fprintf(bcftools_stderr, " -x, --remove LIST List of annotations (e.g. ID,INFO/DP,FORMAT/DP,FILTER) to remove (or keep with \"^\" prefix). See man page for details\n");
3665 fprintf(bcftools_stderr, " --threads INT Number of extra output compression threads [0]\n");
3666 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
3667 fprintf(bcftools_stderr, "\n");
3668 fprintf(bcftools_stderr, "Examples:\n");
3669 fprintf(bcftools_stderr, " http://samtools.github.io/bcftools/howtos/annotate.html\n");
3670 fprintf(bcftools_stderr, "\n");
3671 bcftools_exit(1);
3672 }
3673
3674 int main_vcfannotate(int argc, char *argv[])
3675 {
3676 int c;
3677 args_t *args = (args_t*) calloc(1,sizeof(args_t));
3678 args->argc = argc; args->argv = argv;
3679 args->files = bcf_sr_init();
3680 args->output_fname = "-";
3681 args->output_type = FT_VCF;
3682 args->n_threads = 0;
3683 args->record_cmd_line = 1;
3684 args->ref_idx = args->alt_idx = args->chr_idx = args->beg_idx = args->end_idx = -1;
3685 args->set_ids_replace = 1;
3686 args->match_id = -1;
3687 args->match_end = -1;
3688 args->clevel = -1;
3689 args->pair_logic = -1;
3690 int regions_is_file = 0;
3691 int regions_overlap = 1;
3692
3693 static struct option loptions[] =
3694 {
3695 {"keep-sites",no_argument,NULL,'k'},
3696 {"mark-sites",required_argument,NULL,'m'},
3697 {"set-id",required_argument,NULL,'I'},
3698 {"output",required_argument,NULL,'o'},
3699 {"output-type",required_argument,NULL,'O'},
3700 {"threads",required_argument,NULL,9},
3701 {"annotations",required_argument,NULL,'a'},
3702 {"merge-logic",required_argument,NULL,'l'},
3703 {"collapse",required_argument,NULL,2},
3704 {"pair-logic",required_argument,NULL,2},
3705 {"include",required_argument,NULL,'i'},
3706 {"exclude",required_argument,NULL,'e'},
3707 {"regions",required_argument,NULL,'r'},
3708 {"regions-file",required_argument,NULL,'R'},
3709 {"regions-overlap",required_argument,NULL,3},
3710 {"remove",required_argument,NULL,'x'},
3711 {"columns-file",required_argument,NULL,'C'},
3712 {"columns",required_argument,NULL,'c'},
3713 {"rename-annots",required_argument,NULL,11},
3714 {"rename-chrs",required_argument,NULL,1},
3715 {"header-lines",required_argument,NULL,'h'},
3716 {"header-line",required_argument,NULL,'H'},
3717 {"samples",required_argument,NULL,'s'},
3718 {"samples-file",required_argument,NULL,'S'},
3719 {"single-overlaps",no_argument,NULL,10},
3720 {"min-overlap",required_argument,NULL,12},
3721 {"no-version",no_argument,NULL,8},
3722 {"force",no_argument,NULL,'f'},
3723 {"write-index",optional_argument,NULL,'W'},
3724 {NULL,0,NULL,0}
3725 };
3726 char *tmp;
3727 while ((c = getopt_long(argc, argv, "h:H:?o:O:r:R:a:x:c:C:i:e:S:s:I:m:kl:fW::",loptions,NULL)) >= 0)
3728 {
3729 switch (c) {
3730 case 'f': args->force = 1; break;
3731 case 'k': args->keep_sites = 1; break;
3732 case 'm':
3733 args->mark_sites_logic = MARK_LISTED;
3734 if ( optarg[0]=='+' ) args->mark_sites = optarg+1;
3735 else if ( optarg[0]=='-' ) { args->mark_sites = optarg+1; args->mark_sites_logic = MARK_UNLISTED; }
3736 else args->mark_sites = optarg;
3737 break;
3738 case 'l':
3739 if ( args->merge_method_str.l ) kputc(',',&args->merge_method_str);
3740 kputs(optarg,&args->merge_method_str);
3741 break;
3742 case 'I': args->set_ids_fmt = optarg; break;
3743 case 's': args->sample_names = optarg; break;
3744 case 'S': args->sample_names = optarg; args->sample_is_file = 1; break;
3745 case 'c': args->columns = strdup(optarg); break;
3746 case 'C': args->columns = strdup(optarg); args->columns_is_file = 1; break;
3747 case 'o': args->output_fname = optarg; break;
3748 case 'O':
3749 switch (optarg[0]) {
3750 case 'b': args->output_type = FT_BCF_GZ; break;
3751 case 'u': args->output_type = FT_BCF; break;
3752 case 'z': args->output_type = FT_VCF_GZ; break;
3753 case 'v': args->output_type = FT_VCF; break;
3754 default:
3755 {
3756 args->clevel = strtol(optarg,&tmp,10);
3757 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
3758 }
3759 };
3760 if ( optarg[1] )
3761 {
3762 args->clevel = strtol(optarg+1,&tmp,10);
3763 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
3764 }
3765 break;
3766 case 'e':
3767 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
3768 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
3769 case 'i':
3770 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
3771 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
3772 case 'x': args->remove_annots = optarg; break;
3773 case 'a': args->targets_fname = optarg; break;
3774 case 'r': args->regions_list = optarg; break;
3775 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
3776 case 'h': args->header_fname = optarg; break;
3777 case 'H': args->header_lines = dbuf_push(args->header_lines,strdup(optarg)); break;
3778 case 1 : args->rename_chrs = optarg; break;
3779 case 2 :
3780 if ( args->pair_logic==-1 ) args->pair_logic = 0;
3781 if ( !strcmp(optarg,"snps") ) args->pair_logic |= BCF_SR_PAIR_SNP_REF;
3782 else if ( !strcmp(optarg,"indels") ) args->pair_logic |= BCF_SR_PAIR_INDEL_REF;
3783 else if ( !strcmp(optarg,"both") ) args->pair_logic |= BCF_SR_PAIR_BOTH_REF;
3784 else if ( !strcmp(optarg,"any") ) args->pair_logic |= BCF_SR_PAIR_ANY;
3785 else if ( !strcmp(optarg,"all") ) args->pair_logic |= BCF_SR_PAIR_ANY;
3786 else if ( !strcmp(optarg,"some") ) args->pair_logic |= BCF_SR_PAIR_SOME;
3787 else if ( !strcmp(optarg,"none") ) args->pair_logic = BCF_SR_PAIR_EXACT;
3788 else if ( !strcmp(optarg,"exact") ) args->pair_logic = BCF_SR_PAIR_EXACT;
3789 else error("The --pair-logic string \"%s\" not recognised.\n", optarg);
3790 break;
3791 case 3 :
3792 regions_overlap = parse_overlap_option(optarg);
3793 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
3794 break;
3795 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
3796 case 8 : args->record_cmd_line = 0; break;
3797 case 10 : args->single_overlaps = 1; break;
3798 case 11 : args->rename_annots = optarg; break;
3799 case 12 : args->min_overlap_str = optarg; break;
3800 case 'W':
3801 if (!(args->write_index = write_index_parse(optarg)))
3802 error("Unsupported index format '%s'\n", optarg);
3803 break;
3804 case '?': usage(args); break;
3805 default: error("Unknown argument: %s\n", optarg);
3806 }
3807 }
3808
3809 char *fname = NULL;
3810 if ( optind>=argc )
3811 {
3812 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
3813 else usage(args);
3814 }
3815 else fname = argv[optind];
3816
3817 if ( args->regions_list )
3818 {
3819 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
3820 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
3821 error("Failed to read the regions: %s\n", args->regions_list);
3822 }
3823 if ( args->targets_fname )
3824 {
3825 htsFile *fp = hts_open(args->targets_fname,"r");
3826 if ( !fp ) error("Failed to open %s\n", args->targets_fname);
3827 htsFormat type = *hts_get_format(fp);
3828 hts_close(fp);
3829
3830 if ( type.format==vcf || type.format==bcf )
3831 {
3832 args->tgts_is_vcf = 1;
3833 args->files->require_index = 1;
3834 bcf_sr_set_opt(args->files,BCF_SR_PAIR_LOGIC,args->pair_logic>=0 ? args->pair_logic : BCF_SR_PAIR_SOME);
3835 if ( args->min_overlap_str ) error("The --min-overlap option cannot be used when annotating from a VCF\n");
3836 }
3837 }
3838 if ( args->min_overlap_str && args->single_overlaps ) error("The options --single-overlaps and --min-overlap cannot be combined\n");
3839 if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
3840 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));
3841
3842 static int line_errcode_warned = 0;
3843 init_data(args);
3844 while ( bcf_sr_next_line(args->files) )
3845 {
3846 if ( !bcf_sr_has_line(args->files,0) ) continue;
3847 bcf1_t *line = bcf_sr_get_line(args->files,0);
3848 if ( line->errcode )
3849 {
3850 if ( !args->force )
3851 error("Encountered an error, cannot proceed. Please check the error output above.\n"
3852 "If feeling adventurous, use the --force option. (At your own risk!)\n");
3853 else if ( !line_errcode_warned )
3854 {
3855 fprintf(bcftools_stderr,
3856 "Warning: Encountered an error, proceeding only because --force was given.\n"
3857 " Note that this can result in a segfault or a silent corruption of the output file!\n");
3858 line_errcode_warned = 1;
3859 line->errcode = 0;
3860 }
3861 }
3862 if ( args->filter )
3863 {
3864 int pass = filter_test(args->filter, line, NULL);
3865 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
3866 if ( !pass )
3867 {
3868 if ( args->keep_sites && bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname);
3869 continue;
3870 }
3871 }
3872 int keep = annotate_line(args, line);
3873 if ( args->filter_ext && !args->keep_sites && !keep ) continue;
3874 if ( bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname);
3875 }
3876 destroy_data(args);
3877 bcf_sr_destroy(args->files);
3878 free(args);
3879 return 0;
3880 }