Debian Codegraph @

bcftools/vcfmerge.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfmerge.c -- Merge multiple VCF/BCF files to create one multi-sample file.
4
5 Copyright (C) 2012-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 <string.h>
29 #include <strings.h>
30 #include <assert.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <getopt.h>
34 #include <inttypes.h>
35 #include <htslib/vcf.h>
36 #include <htslib/synced_bcf_reader.h>
37 #include <htslib/vcfutils.h>
38 #include <htslib/faidx.h>
39 #include <htslib/kbitset.h>
40 #include <htslib/hts_endian.h>
41 #include <math.h>
42 #include <ctype.h>
43 #include <time.h>
44 #include "bcftools.h"
45 #include "regidx.h"
46 #include "vcmp.h"
47
48 #define DBG 0
49
50 #define COLLAPSE_SNP_INS_DEL (1<<10)
51
52 #include <htslib/khash.h>
53 KHASH_MAP_INIT_STR(strdict, int)
54 typedef khash_t(strdict) strdict_t;
55
56 #define FLT_LOGIC_ADD 0
57 #define FLT_LOGIC_REMOVE 1
58
59 #define SKIP_DONE 1 // the record was processed
60 #define SKIP_DIFF 2 // not compatible, merge later
61
62 #define IS_VL_G(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_G)
63 #define IS_VL_A(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_A)
64 #define IS_VL_R(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_R)
65
66 #define SWAP(type_t,a,b) { type_t tmp = (a); (a) = (b); (b) = tmp; }
67
68 #define PL2PROB_MAX 1024
69
70 // Rules for merging FORMAT Number=A,G,R vectors with missing values
71 #define MERGE_MISSING_DOT 0 // leave as is, i.e. use a missing value "."
72 #define MERGE_MISSING_CONST 1 // use a constant value
73 #define MERGE_MISSING_MAX 2 // use the existing maximum value
74
75 typedef struct _missing_rule_t
76 {
77 char *hdr_tag;
78 int type;
79 float value;
80 }
81 missing_rule_t;
82
83 // For merging INFO Number=A,G,R tags
84 typedef struct
85 {
86 const char *hdr_tag;
87 int type, nvals;
88 int nbuf, mbuf;
89 uint8_t *buf;
90 }
91 AGR_info_t;
92
93 // Rules for merging arbitrary INFO tags
94 typedef struct _info_rule_t
95 {
96 char *hdr_tag;
97 void (*merger)(bcf_hdr_t *hdr, bcf1_t *line, struct _info_rule_t *rule);
98 int type; // one of BCF_HT_*
99 int block_size; // number of values in a block
100 int type_size; // size of the corresponding BCF_HT_* type
101 int nblocks; // number of blocks in nvals (the number of merged files)
102 int nvals, mvals; // used and total size of vals array
103 void *vals; // the info tag values
104 }
105 info_rule_t;
106
107 typedef struct
108 {
109 bcf1_t *line;
110 int end, active; // end: 0-based INFO/END
111 }
112 gvcf_aux_t;
113
114 // Auxiliary merge data for selecting the right combination
115 // of buffered records across multiple readers. maux1_t
116 // corresponds to one buffered line.
117 typedef struct
118 {
119 int skip;
120 int *map; // mapping from input alleles to the array of output alleles (set by merge_alleles)
121 int mmap; // size of map array (only buffer[i].n_allele is actually used)
122 int als_differ;
123 int var_types; // variant types in this record, shifted by <<1 to account for VCF_REF
124 }
125 maux1_t;
126
127 // Buffered lines for a single reader
128 typedef struct
129 {
130 int rid; // current rid
131 int beg,end; // valid ranges in reader's buffer [beg,end). Maintained by maux_reset and gvcf_flush.
132 int unkn_allele;// the index of the unknown allele (<*>, <NON_REF>)
133 int cur; // current line or -1 if none
134 int mrec; // allocated size of buf
135 maux1_t *rec; // buffer to keep reader's lines
136 bcf1_t **lines; // source buffer: either gvcf or readers' buffer
137 int var_types; // reader's variant types in the active [beg,end] window
138 }
139 buffer_t;
140 typedef struct
141 {
142 int n, pos, var_types; // number of readers; current position; variant types at this position across all available records
143 int *als_types, // allele type of each output allele
144 mals_types;
145 char *chr; // current chromosome
146 char **als, **out_als; // merged alleles (temp, may contain empty records) and merged alleles ready for output
147 int nals, mals, nout_als, mout_als; // size of the output array
148 int *cnt, ncnt; // number of records that refer to the alleles
149 int *smpl_ploidy, *smpl_nGsize; // ploidy and derived number of values in Number=G tags, updated for each line (todo: cache for missing cases)
150 const char **fmt_key;// temporary short-lived array to store output tag names
151 bcf_fmt_t **fmt_map; // i-th output FORMAT field corresponds in j-th reader to i*nreader+j, first row is reserved for GT
152 int nfmt_map; // number of rows in the fmt_map array
153 int *agr_map, nagr_map, magr_map; // mapping between Number=AGR element indexes, from src idxs to dst file idxs
154 void *tmp_arr;
155 size_t ntmp_arr;
156 buffer_t *buf;
157 AGR_info_t *AGR_info;
158 int nAGR_info, mAGR_info;
159 bcf_srs_t *files;
160 int gvcf_min, // min buffered gvcf END position (NB: gvcf_min is 1-based) or 0 if no active lines are present
161 gvcf_break; // 0-based position of a next record which breaks a gVCF block
162 gvcf_aux_t *gvcf; // buffer of gVCF lines, for each reader one line
163 int nout_smpl;
164 kstring_t *str;
165 int32_t *laa; // localized alternate alleles given as input-based indexes in per-sample blocks of (args->local_alleles+1) values, 0 is always first
166 int nlaa, laa_dirty; // number of LAA alleles actually used at this site, and was any L* added?
167 int32_t *tmpi, *k2k;
168 double *tmpd, *pl2prob; // mapping from phred-score likelihoods (PL) to probability
169 int ntmpi, ntmpd, nk2k;
170 }
171 maux_t;
172
173 typedef struct
174 {
175 vcmp_t *vcmp;
176 maux_t *maux;
177 regidx_t *regs; // apply regions only after the blocks are expanded
178 regitr_t *regs_itr;
179 int header_only, collapse, output_type, force_samples, force_single, merge_by_id, do_gvcf, filter_logic, missing_to_ref, no_index;
180 char *header_fname, *output_fname, *regions_list, *info_rules, *file_list;
181 faidx_t *gvcf_fai;
182 info_rule_t *rules;
183 int nrules;
184 char *missing_rules_str;
185 missing_rule_t *missing_rules; // lookup for -M, --missing-rules
186 int nmissing_rules;
187 strdict_t *tmph;
188 kstring_t tmps;
189 bcf_srs_t *files;
190 bcf1_t *out_line;
191 htsFile *out_fh;
192 bcf_hdr_t *out_hdr;
193 char **argv;
194 int argc, n_threads, record_cmd_line, clevel;
195 int local_alleles; // the value of -L option
196 int keep_AC_AN;
197 char *index_fn;
198 int write_index;
199 int trim_star_allele; // 0=don't trim; 1=trim at variant sites; 2=trim at all sites
200 }
201 args_t;
202
203 static bcf1_t *maux_get_line(args_t *args, int i)
204 {
205 maux_t *ma = args->maux;
206 int ibuf = ma->buf[i].cur;
207 if ( ibuf >= 0 ) return ma->buf[i].lines[ibuf];
208 return NULL;
209 }
210
211 static void info_rules_merge_sum(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
212 {
213 if ( !rule->nvals ) return;
214 int i, j, ndim = rule->block_size;
215 #define BRANCH(type_t,is_missing) { \
216 type_t *ptr = (type_t*) rule->vals; \
217 for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = 0; \
218 for (i=1; i<rule->nblocks; i++) \
219 { \
220 for (j=0; j<ndim; j++) ptr[j] += ptr[j+i*ndim]; \
221 } \
222 }
223 switch (rule->type) {
224 case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break;
225 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break;
226 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
227 }
228 #undef BRANCH
229
230 bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
231 }
232 static void info_rules_merge_avg(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
233 {
234 if ( !rule->nvals ) return;
235 int i, j, ndim = rule->block_size;
236 #define BRANCH(type_t,is_missing) { \
237 type_t *ptr = (type_t*) rule->vals; \
238 for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = 0; \
239 for (j=0; j<ndim; j++) \
240 { \
241 double sum = 0; \
242 for (i=0; i<rule->nblocks; i++) sum += ptr[j+i*ndim]; \
243 ptr[j] = sum / rule->nblocks; \
244 } \
245 }
246 switch (rule->type) {
247 case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break;
248 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break;
249 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
250 }
251 #undef BRANCH
252
253 bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
254 }
255 static void info_rules_merge_min(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
256 {
257 if ( !rule->nvals ) return;
258 int i, j, ndim = rule->block_size;
259 #define BRANCH(type_t,is_missing,set_missing,huge_val) { \
260 type_t *ptr = (type_t*) rule->vals; \
261 for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = huge_val; \
262 for (i=1; i<rule->nblocks; i++) \
263 { \
264 for (j=0; j<ndim; j++) if ( ptr[j] > ptr[j+i*ndim] ) ptr[j] = ptr[j+i*ndim]; \
265 } \
266 for (i=0; i<rule->nvals; i++) if ( ptr[i]==huge_val ) set_missing; \
267 }
268 switch (rule->type) {
269 case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MAX); break;
270 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), HUGE_VAL); break;
271 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
272 }
273 #undef BRANCH
274
275 bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
276 }
277 static void info_rules_merge_max(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
278 {
279 if ( !rule->nvals ) return;
280 int i, j, ndim = rule->block_size;
281 #define BRANCH(type_t,is_missing,set_missing,huge_val) { \
282 type_t *ptr = (type_t*) rule->vals; \
283 for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = huge_val; \
284 for (i=1; i<rule->nblocks; i++) \
285 { \
286 for (j=0; j<ndim; j++) if ( ptr[j] < ptr[j+i*ndim] ) ptr[j] = ptr[j+i*ndim]; \
287 } \
288 for (i=0; i<rule->nvals; i++) if ( ptr[i]==huge_val ) set_missing; \
289 }
290 switch (rule->type) {
291 case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MIN); break;
292 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), -HUGE_VAL); break;
293 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
294 }
295 #undef BRANCH
296
297 bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
298 }
299 static void info_rules_merge_join(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
300 {
301 if ( !rule->nvals ) return;
302 if ( rule->type==BCF_HT_STR )
303 {
304 ((char*)rule->vals)[rule->nvals] = 0;
305 bcf_update_info_string(hdr,line,rule->hdr_tag,rule->vals);
306 }
307 else
308 {
309 int isrc, idst = 0;
310 #define BRANCH(type_t,is_missing,is_vector_end) { \
311 type_t *ptr = (type_t*) rule->vals; \
312 for (isrc=0; isrc<rule->nvals; isrc++) \
313 { \
314 if ( is_vector_end ) break; \
315 if ( is_missing ) continue; \
316 if ( idst!=isrc ) ptr[idst] = ptr[isrc]; \
317 idst++; \
318 } \
319 }
320 switch (rule->type) {
321 case BCF_HT_INT: BRANCH(int32_t, ptr[isrc]==bcf_int32_missing, ptr[isrc]==bcf_int32_vector_end); break;
322 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[isrc]), bcf_float_is_vector_end(ptr[isrc])); break;
323 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
324 }
325 #undef BRANCH
326
327 rule->nvals = idst;
328 bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,rule->nvals,rule->type);
329 }
330 }
331
332 static int missing_rules_comp_key2(const void *a, const void *b)
333 {
334 missing_rule_t *rule1 = (missing_rule_t*) a;
335 missing_rule_t *rule2 = (missing_rule_t*) b;
336 return strcmp(rule1->hdr_tag, rule2->hdr_tag);
337 }
338 static int missing_rules_comp_key(const void *a, const void *b)
339 {
340 char *key = (char*) a;
341 missing_rule_t *rule = (missing_rule_t*) b;
342 return strcmp(key, rule->hdr_tag);
343 }
344 static void missing_rules_init(args_t *args)
345 {
346 kstring_t str = {0,0,0};
347 if ( args->missing_rules_str )
348 {
349 if ( !strcmp("-",args->missing_rules_str) ) kputs("PL:.,AD:.",&str);
350 else kputs(args->missing_rules_str,&str);
351 }
352 else if ( args->do_gvcf ) kputs("PL:max,AD:0",&str);
353 else return;
354
355 args->nmissing_rules = 1;
356 char *ss = str.s, *tmp = ss;
357 int n = 0;
358 while ( *ss )
359 {
360 if ( *ss==':' ) { *ss = 0; n++; if ( n%2==0 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); }
361 else if ( *ss==',' ) { *ss = 0; args->nmissing_rules++; n++; if ( n%2==1 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); }
362 ss++;
363 }
364 if ( n%2==0 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str);
365 args->missing_rules = (missing_rule_t*) calloc(args->nmissing_rules,sizeof(missing_rule_t));
366
367 n = args->nmissing_rules;
368 args->nmissing_rules = 0;
369 ss = tmp;
370 while ( args->nmissing_rules < n )
371 {
372 missing_rule_t *rule = &args->missing_rules[args->nmissing_rules];
373 rule->hdr_tag = strdup(ss);
374 int id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, rule->hdr_tag);
375 if ( !bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_FMT,id) )
376 {
377 if ( args->missing_rules_str ) error("The FORMAT tag is not defined in the header: \"%s\"\n", rule->hdr_tag);
378 free(rule->hdr_tag);
379 n--;
380 ss = strchr(ss, '\0'); ss++;
381 if ( !*ss ) error("Could not parse --missing-rules, missing logic of \"%s\"\n", rule->hdr_tag);
382 ss = strchr(ss, '\0'); ss++;
383 continue;
384 }
385
386 ss = strchr(ss, '\0'); ss++;
387 if ( !*ss ) error("Could not parse --missing-rules, missing logic of \"%s\"\n", rule->hdr_tag);
388
389 if ( !strcasecmp(ss,".") ) rule->type = MERGE_MISSING_DOT;
390 else if ( !strcasecmp(ss,"max") ) rule->type = MERGE_MISSING_MAX;
391 else
392 {
393 char *tmp = ss;
394 rule->value = strtod(ss, &tmp);
395 if ( *tmp ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str);
396 rule->type = MERGE_MISSING_CONST;
397 }
398 ss = strchr(ss, '\0'); ss++;
399 args->nmissing_rules++;
400 }
401 qsort(args->missing_rules, args->nmissing_rules, sizeof(*args->missing_rules), missing_rules_comp_key2);
402 free(str.s);
403 }
404 static void missing_rules_destroy(args_t *args)
405 {
406 int i;
407 for (i=0; i<args->nmissing_rules; i++)
408 {
409 missing_rule_t *rule = &args->missing_rules[i];
410 free(rule->hdr_tag);
411 }
412 free(args->missing_rules);
413 }
414
415 static int info_rules_comp_key2(const void *a, const void *b)
416 {
417 info_rule_t *rule1 = (info_rule_t*) a;
418 info_rule_t *rule2 = (info_rule_t*) b;
419 return strcmp(rule1->hdr_tag, rule2->hdr_tag);
420 }
421 static int info_rules_comp_key(const void *a, const void *b)
422 {
423 char *key = (char*) a;
424 info_rule_t *rule = (info_rule_t*) b;
425 return strcmp(key, rule->hdr_tag);
426 }
427 static void info_rules_init(args_t *args)
428 {
429 if ( args->info_rules && !strcmp("-",args->info_rules) ) return;
430
431 kstring_t str = {0,0,0};
432 if ( !args->info_rules )
433 {
434 if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "DP")) ) kputs("DP:sum",&str);
435 if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "DP4")) )
436 {
437 if ( str.l ) kputc(',',&str);
438 kputs("DP4:sum",&str);
439 }
440 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "QS")) )
441 {
442 if ( str.l ) kputc(',',&str);
443 kputs("QS:sum",&str);
444 }
445 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "MIN_DP")) )
446 {
447 if ( str.l ) kputc(',',&str);
448 kputs("MIN_DP:min",&str);
449 }
450 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "MinDP")) )
451 {
452 if ( str.l ) kputc(',',&str);
453 kputs("MinDP:min",&str);
454 }
455 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "I16")) )
456 {
457 if ( str.l ) kputc(',',&str);
458 kputs("I16:sum",&str);
459 }
460 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IDV")) )
461 {
462 if ( str.l ) kputc(',',&str);
463 kputs("IDV:max",&str);
464 }
465 if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IMF")) )
466 {
467 if ( str.l ) kputc(',',&str);
468 kputs("IMF:max",&str);
469 }
470 if ( !bcf_hdr_nsamples(args->out_hdr) )
471 {
472 if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AN")) )
473 {
474 if ( str.l ) kputc(',',&str);
475 kputs("AN:sum",&str);
476 }
477 if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AC")) )
478 {
479 if ( str.l ) kputc(',',&str);
480 kputs("AC:sum",&str);
481 }
482 }
483
484 if ( !str.l ) return;
485 args->info_rules = str.s;
486 }
487
488 args->nrules = 1;
489 char *ss = strdup(args->info_rules), *tmp = ss;
490 int n = 0;
491 while ( *ss )
492 {
493 if ( *ss==':' ) { *ss = 0; n++; if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); }
494 else if ( *ss==',' ) { *ss = 0; args->nrules++; n++; if ( n%2==1 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); }
495 ss++;
496 }
497 if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules);
498 args->rules = (info_rule_t*) calloc(args->nrules,sizeof(info_rule_t));
499
500 n = 0;
501 ss = tmp;
502 while ( n < args->nrules )
503 {
504 info_rule_t *rule = &args->rules[n];
505 rule->hdr_tag = strdup(ss);
506 int id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, rule->hdr_tag);
507 if ( !bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,id) ) error("The INFO tag is not defined in the header: \"%s\"\n", rule->hdr_tag);
508 rule->type = bcf_hdr_id2type(args->out_hdr,BCF_HL_INFO,id);
509 if ( rule->type==BCF_HT_INT ) rule->type_size = sizeof(int32_t);
510 else if ( rule->type==BCF_HT_REAL ) rule->type_size = sizeof(float);
511 else if ( rule->type==BCF_HT_STR ) rule->type_size = sizeof(char);
512 else error("The INFO rule \"%s\" is not supported; the tag \"%s\" type is %d\n", ss,rule->hdr_tag,rule->type);
513
514 if ( !strcmp(rule->hdr_tag,"AC") || !strcmp(rule->hdr_tag,"AN") ) args->keep_AC_AN = 1;
515
516 ss = strchr(ss, '\0'); ss++;
517 if ( !*ss ) error("Could not parse INFO rules, missing logic of \"%s\"\n", rule->hdr_tag);
518
519 int is_join = 0;
520 if ( !strcasecmp(ss,"sum") ) rule->merger = info_rules_merge_sum;
521 else if ( !strcasecmp(ss,"avg") ) rule->merger = info_rules_merge_avg;
522 else if ( !strcasecmp(ss,"min") ) rule->merger = info_rules_merge_min;
523 else if ( !strcasecmp(ss,"max") ) rule->merger = info_rules_merge_max;
524 else if ( !strcasecmp(ss,"join") ) { rule->merger = info_rules_merge_join; is_join = 1; }
525 else error("The rule logic \"%s\" not recognised\n", ss);
526
527 if ( !is_join && rule->type==BCF_HT_STR )
528 error("Numeric operation \"%s\" requested on non-numeric field: %s\n", ss, rule->hdr_tag);
529 if ( bcf_hdr_id2number(args->out_hdr,BCF_HL_INFO,id)==0xfffff )
530 {
531 int is_agr = (
532 bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_A ||
533 bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_G ||
534 bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_R
535 ) ? 1 : 0;
536 if ( is_join && bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)!=BCF_VL_VAR )
537 {
538 bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->out_hdr, BCF_HL_INFO, "ID", rule->hdr_tag, NULL);
539 hrec = bcf_hrec_dup(hrec);
540 int i = bcf_hrec_find_key(hrec, "Number");
541 if ( i<0 ) error("Uh, could not find the entry Number in the header record of %s\n",rule->hdr_tag);
542 free(hrec->vals[i]);
543 hrec->vals[i] = strdup(".");
544 bcf_hdr_remove(args->out_hdr,BCF_HL_INFO, rule->hdr_tag);
545 bcf_hdr_add_hrec(args->out_hdr, hrec);
546 }
547 if ( !is_join && !is_agr )
548 error("Only fixed-length vectors are supported with -i %s:%s\n", ss, rule->hdr_tag);
549 }
550
551 ss = strchr(ss, '\0'); ss++;
552 n++;
553 }
554 free(str.s);
555 free(tmp);
556
557 qsort(args->rules, args->nrules, sizeof(*args->rules), info_rules_comp_key2);
558 }
559 static void info_rules_destroy(args_t *args)
560 {
561 int i;
562 for (i=0; i<args->nrules; i++)
563 {
564 info_rule_t *rule = &args->rules[i];
565 free(rule->hdr_tag);
566 free(rule->vals);
567 }
568 free(args->rules);
569 }
570 static void info_rules_reset(args_t *args)
571 {
572 int i;
573 for (i=0; i<args->nrules; i++)
574 args->rules[i].nblocks = args->rules[i].nvals = args->rules[i].block_size = 0;
575 }
576 static int info_rules_add_values(args_t *args, bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule, maux1_t *als, int var_len)
577 {
578 int msize = args->maux->ntmp_arr / rule->type_size;
579 int ret = bcf_get_info_values(hdr, line, rule->hdr_tag, &args->maux->tmp_arr, &msize, rule->type);
580 if ( ret<=0 ) error("FIXME: error parsing %s at %s:%"PRId64" .. %d\n", rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1,ret);
581 args->maux->ntmp_arr = msize * rule->type_size;
582
583 rule->nblocks++;
584
585 if ( rule->type==BCF_HT_STR )
586 {
587 int need_comma = rule->nblocks==1 ? 0 : 1;
588 hts_expand(char,rule->nvals+ret+need_comma+1,rule->mvals,rule->vals); // 1 for null-termination
589 char *tmp = (char*) rule->vals + rule->nvals;
590 if ( rule->nvals>0 ) { *tmp = ','; tmp++; }
591 strncpy(tmp,(char*)args->maux->tmp_arr,ret);
592 rule->nvals += ret + need_comma;
593 return 1;
594 }
595
596 int i, j;
597 if ( var_len==BCF_VL_A )
598 {
599 if ( ret!=line->n_allele-1 ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1);
600 args->maux->nagr_map = ret;
601 hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
602 // create mapping from source file ALT indexes to dst file indexes
603 for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i+1] - 1;
604 rule->block_size = args->maux->nout_als - 1;
605 }
606 else if ( var_len==BCF_VL_R )
607 {
608 if ( ret!=line->n_allele ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1);
609 args->maux->nagr_map = ret;
610 hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
611 for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i];
612 rule->block_size = args->maux->nout_als;
613 }
614 else if ( var_len==BCF_VL_G )
615 {
616 args->maux->nagr_map = bcf_alleles2gt(line->n_allele-1,line->n_allele-1)+1;
617 if ( ret!=line->n_allele && ret!=args->maux->nagr_map ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1);
618 if ( ret==line->n_allele ) // haploid
619 {
620 args->maux->nagr_map = line->n_allele;
621 hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
622 for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i];
623 rule->block_size = args->maux->nout_als;
624 }
625 else
626 {
627 hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
628 int k_src = 0;
629 for (i=0; i<line->n_allele; i++)
630 {
631 for (j=0; j<=i; j++)
632 {
633 args->maux->agr_map[k_src] = bcf_alleles2gt(als->map[i],als->map[j]);
634 k_src++;
635 }
636 }
637 rule->block_size = bcf_alleles2gt(args->maux->nout_als-1,args->maux->nout_als-1)+1;
638 }
639 }
640 else
641 {
642 if ( rule->nblocks>1 && ret!=rule->block_size )
643 error("Mismatch in number of values for INFO/%s at %s:%"PRId64"\n", rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1);
644 rule->block_size = ret;
645 args->maux->nagr_map = 0;
646 }
647
648 #define BRANCH(src_type_t,dst_type_t,set_missing) { \
649 src_type_t *src = (src_type_t *) args->maux->tmp_arr; \
650 hts_expand0(dst_type_t,(rule->nvals+rule->block_size),rule->mvals,rule->vals); \
651 dst_type_t *dst = (dst_type_t *) rule->vals + rule->nvals; \
652 rule->nvals += rule->block_size; \
653 if ( !args->maux->nagr_map ) \
654 { \
655 for (i=0; i<ret; i++) dst[i] = src[i]; \
656 } \
657 else \
658 { \
659 for (i=0; i<rule->block_size; i++) set_missing; \
660 for (i=0; i<ret; i++) dst[args->maux->agr_map[i]] = src[i]; \
661 } \
662 }
663 switch (rule->type) {
664 case BCF_HT_INT: BRANCH(int, int32_t, dst[i] = bcf_int32_missing); break;
665 case BCF_HT_REAL: BRANCH(float, float, bcf_float_set_missing(dst[i])); break;
666 default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
667 }
668 #undef BRANCH
669
670 return 1;
671 }
672
673 int bcf_hdr_sync(bcf_hdr_t *h);
674
675 void merge_headers(bcf_hdr_t *hw, const bcf_hdr_t *hr, const char *clash_prefix, int force_samples)
676 {
677 // header lines
678 hw = bcf_hdr_merge(hw, hr);
679
680 // samples
681 int i;
682 for (i=0; i<bcf_hdr_nsamples(hr); i++)
683 {
684 char *rmme = NULL, *name = hr->samples[i];
685 while ( bcf_hdr_id2int(hw, BCF_DT_SAMPLE, name)!=-1 )
686 {
687 // there is a sample with the same name
688 if ( !force_samples ) error("Error: Duplicate sample names (%s), use --force-samples to proceed anyway.\n", name);
689
690 // Resolve conflicting samples names. For example, replace:
691 // A + A with A,2:A
692 // A,2:A + A with A,2:A,2:2:A
693
694 int len = strlen(name) + strlen(clash_prefix) + 1;
695 char *tmp = (char*) malloc(sizeof(char)*(len+1));
696 sprintf(tmp,"%s:%s",clash_prefix,name);
697 free(rmme);
698 rmme = name = tmp;
699 }
700 bcf_hdr_add_sample(hw,name);
701 free(rmme);
702 }
703 }
704
705 void debug_als(char **als, int nals)
706 {
707 int k; for (k=0; k<nals; k++) fprintf(bcftools_stderr,"%s ", als[k]);
708 fprintf(bcftools_stderr,"\n");
709 }
710
711 /**
712 * normalize_alleles() - create smallest possible representation of the alleles
713 * @als: alleles to be merged, first is REF (rw)
714 * @nals: number of $a alleles
715 *
716 * Best explained on an example:
717 * In: REF=GTTT ALT=GTT
718 * Out: REF=GT ALT=G
719 *
720 * Note: the als array will be modified
721 */
722 void normalize_alleles(char **als, int nals)
723 {
724 if ( !als[0][1] ) return; // ref is 1base long, we're done
725
726 int j, i = 1, done = 0;
727 int *lens = (int*) malloc(sizeof(int)*nals);
728 for (j=0; j<nals; j++) lens[j] = strlen(als[j]);
729
730 while ( i<lens[0] )
731 {
732 for (j=1; j<nals; j++)
733 {
734 if ( i>=lens[j] ) done = 1;
735 if ( als[j][lens[j]-i] != als[0][lens[0]-i] ) { done = 1; break; }
736 }
737 if ( done ) break;
738 i++;
739 }
740 if ( i>1 )
741 {
742 i--;
743 als[0][lens[0]-i] = 0;
744 for (j=1; j<nals; j++) als[j][lens[j]-i] = 0;
745 }
746 free(lens);
747 }
748
749 /**
750 * merge_alleles() - merge two REF,ALT records, $a and $b into $b.
751 * @a: alleles to be merged, first is REF
752 * @na: number of $a alleles
753 * @map: map from the original $a indexes to new $b indexes (0-based)
754 * @b: alleles to be merged, the array will be expanded as required
755 * @nb: number of $b alleles
756 * @mb: size of $b
757 *
758 * Returns NULL on error or $b expanded to incorporate $a alleles and sets
759 * $map. Best explained on an example:
760 * In: REF ALT
761 * a: ACG, AC,A (1bp and 2bp deletion)
762 * b: ACGT, A (3bp deletion)
763 * Out:
764 * b: ACGT, A,ACT,AT (3bp, 1bp and 2bp deletion)
765 * map: 0,2,3
766 * Here the mapping from the original $a alleles to the new $b alleles is 0->0,
767 * 1->2, and 2->3.
768 */
769 char **merge_alleles(char **a, int na, int *map, char **b, int *nb, int *mb)
770 {
771 // reference allele never changes
772 map[0] = 0;
773
774 int i,j;
775 int rla = !a[0][1] ? 1 : strlen(a[0]);
776 int rlb = !b[0][1] ? 1 : strlen(b[0]);
777
778 // the most common case: same SNPs
779 if ( na==2 && *nb==2 && rla==1 && rlb==1 && a[1][0]==b[1][0] && !a[1][1] && !b[1][1] )
780 {
781 map[1] = 1;
782 return b;
783 }
784
785 // Sanity check: reference prefixes must be identical
786 if ( strncmp(a[0],b[0],rla<rlb?rla:rlb) )
787 {
788 if ( strncasecmp(a[0],b[0],rla<rlb?rla:rlb) )
789 {
790 fprintf(bcftools_stderr, "The REF prefixes differ: %s vs %s (%d,%d)\n", a[0],b[0],rla,rlb);
791 return NULL;
792 }
793 // Different case, change to uppercase
794 for (i=0; i<na; i++)
795 {
796 int len = strlen(a[i]);
797 for (j=0; j<len; j++) a[i][j] = toupper(a[i][j]);
798 }
799 for (i=0; i<*nb; i++)
800 {
801 int len = strlen(b[i]);
802 for (j=0; j<len; j++) b[i][j] = toupper(b[i][j]);
803 }
804 }
805
806 int n = *nb + na;
807 hts_expand0(char*,n,*mb,b);
808
809 // $b alleles need expanding
810 if ( rla>rlb )
811 {
812 for (i=0; i<*nb; i++)
813 {
814 if ( b[i][0]=='<' ) continue; // symbolic allele, do not modify
815 if ( b[i][0]=='*' ) continue; // overlapping deletion (*), do not modify
816 int l = strlen(b[i]);
817 b[i] = (char*) realloc(b[i],l+rla-rlb+1);
818 memcpy(b[i]+l,a[0]+rlb,rla-rlb+1);
819 }
820 }
821
822 // now check if the $a alleles are present and if not add them
823 for (i=1; i<na; i++)
824 {
825 int const_ai = 1;
826 char *ai;
827 if ( rlb>rla && a[i][0]!='<' && a[i][0]!='*' ) // $a alleles need expanding and not a symbolic allele or *
828 {
829 int l = strlen(a[i]);
830 ai = (char*) malloc(l+rlb-rla+1);
831 memcpy(ai,a[i],l);
832 memcpy(ai+l,b[0]+rla,rlb-rla+1);
833 const_ai = 0;
834 }
835 else
836 ai = a[i];
837
838 for (j=1; j<*nb; j++)
839 if ( !strcasecmp(ai,b[j]) ) break;
840
841 if ( j<*nb ) // $b already has the same allele
842 {
843 map[i] = j;
844 if ( !const_ai ) free(ai);
845 continue;
846 }
847 // new allele
848 map[i] = *nb;
849 b[*nb] = const_ai ? strdup(ai) : ai;
850 (*nb)++;
851 }
852 return b;
853 }
854
855 maux_t *maux_init(args_t *args)
856 {
857 bcf_srs_t *files = args->files;
858 maux_t *ma = (maux_t*) calloc(1,sizeof(maux_t));
859 ma->n = files->nreaders;
860 ma->files = files;
861 int i, n_smpl = 0;
862 for (i=0; i<ma->n; i++)
863 n_smpl += bcf_hdr_nsamples(files->readers[i].header);
864 ma->nout_smpl = n_smpl;
865 assert( n_smpl==bcf_hdr_nsamples(args->out_hdr) );
866 if ( args->do_gvcf )
867 {
868 ma->gvcf = (gvcf_aux_t*) calloc(ma->n,sizeof(gvcf_aux_t)); // -Walloc-size-larger-than gives a harmless warning caused by signed integer ma->n
869 for (i=0; i<ma->n; i++)
870 ma->gvcf[i].line = bcf_init1();
871 }
872 ma->smpl_ploidy = (int*) calloc(n_smpl,sizeof(int));
873 ma->smpl_nGsize = (int*) malloc(n_smpl*sizeof(int));
874 ma->buf = (buffer_t*) calloc(ma->n,sizeof(buffer_t));
875 for (i=0; i<ma->n; i++)
876 ma->buf[i].rid = -1;
877 ma->str = (kstring_t*) calloc(n_smpl,sizeof(kstring_t));
878 if ( args->local_alleles )
879 {
880 ma->laa = (int32_t*)malloc(sizeof(*ma->laa)*ma->nout_smpl*(1+args->local_alleles));
881 ma->pl2prob = (double*)malloc(PL2PROB_MAX*sizeof(*ma->pl2prob));
882 for (i=0; i<PL2PROB_MAX; i++)
883 ma->pl2prob[i] = pow(10,-0.1*i);
884 }
885 return ma;
886 }
887 void maux_destroy(maux_t *ma)
888 {
889 int i,j;
890 for (i=0; i<ma->nout_smpl; i++) free(ma->str[i].s);
891 free(ma->str);
892 free(ma->als_types);
893 for (i=0; i<ma->mals; i++)
894 {
895 free(ma->als[i]);
896 ma->als[i] = NULL;
897 }
898 for (i=0; i<ma->n; i++) // for each reader
899 {
900 for (j=0; j<ma->buf[i].mrec; j++) // for each buffered line
901 free(ma->buf[i].rec[j].map);
902 free(ma->buf[i].rec);
903 }
904 free(ma->buf);
905 if ( ma->gvcf )
906 {
907 for (i=0; i<ma->n; i++) bcf_destroy(ma->gvcf[i].line);
908 free(ma->gvcf);
909 }
910 for (i=0; i<ma->mAGR_info; i++)
911 free(ma->AGR_info[i].buf);
912 free(ma->agr_map);
913 free(ma->AGR_info);
914 if (ma->ntmp_arr) free(ma->tmp_arr);
915 if (ma->nfmt_map) free(ma->fmt_map);
916 free(ma->fmt_key);
917 // ma->inf freed in bcf_destroy1
918 for (i=0; i<ma->mals; i++) free(ma->als[i]);
919 if (ma->mout_als) free(ma->out_als);
920 free(ma->als);
921 free(ma->cnt);
922 free(ma->smpl_ploidy);
923 free(ma->smpl_nGsize);
924 free(ma->chr);
925 free(ma->laa);
926 free(ma->tmpi);
927 free(ma->k2k);
928 free(ma->tmpd);
929 free(ma->pl2prob);
930 free(ma);
931 }
932 void maux_expand1(buffer_t *buf, int size)
933 {
934 if ( buf->mrec < size )
935 {
936 hts_expand0(maux1_t,size,buf->mrec,buf->rec);
937 buf->mrec = size;
938 }
939 }
940 void maux_reset(maux_t *ma, int *rid_tab)
941 {
942 int i,j;
943 for (i=0; i<ma->n; i++) maux_expand1(&ma->buf[i],ma->files->readers[i].nbuffer+1);
944 for (i=0; i<ma->mals; i++)
945 {
946 free(ma->als[i]);
947 ma->als[i] = NULL;
948 }
949 const char *chr = NULL;
950 ma->nals = 0;
951 ma->pos = -1;
952 for (i=0; i<ma->n; i++)
953 {
954 if ( !bcf_sr_has_line(ma->files,i) ) continue;
955 bcf1_t *line = bcf_sr_get_line(ma->files,i);
956 bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i);
957 chr = bcf_seqname(hdr,line);
958 ma->pos = line->pos;
959 break;
960 }
961 int new_chr = 0;
962 if ( chr && (!ma->chr || strcmp(ma->chr,chr)) )
963 {
964 free(ma->chr);
965 ma->chr = strdup(chr);
966 new_chr = 1;
967 }
968 for (i=0; i<ma->n; i++)
969 {
970 bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i);
971 if (new_chr)
972 rid_tab[i] = bcf_hdr_name2id(hdr,chr);
973
974 ma->buf[i].rid = rid_tab[i];
975 ma->buf[i].beg = bcf_sr_has_line(ma->files,i) ? 0 : 1;
976 for (j=ma->buf[i].beg; j<=ma->files->readers[i].nbuffer; j++)
977 {
978 ma->buf[i].rec[j].skip = 0;
979 ma->buf[i].rec[j].var_types = 0;
980 bcf1_t *line = ma->files->readers[i].buffer[j];
981 if ( line->rid!=ma->buf[i].rid || line->pos!=ma->pos ) break;
982 }
983 ma->buf[i].end = j;
984 ma->buf[i].cur = -1;
985 if ( ma->buf[i].beg < ma->buf[i].end )
986 {
987 ma->buf[i].lines = ma->files->readers[i].buffer;
988 if ( ma->gvcf ) ma->gvcf[i].active = 0; // gvcf block cannot overlap with the next record
989 }
990 if ( new_chr && ma->gvcf ) ma->gvcf[i].active = 0; // make sure to close active gvcf block on new chr
991 }
992 }
993 void maux_debug(maux_t *ma, int ir, int ib)
994 {
995 fprintf(bcftools_stdout, "[%d,%d]\t", ir,ib);
996 int i;
997 for (i=0; i<ma->nals; i++)
998 {
999 fprintf(bcftools_stdout, " %s [%d]", ma->als[i], ma->cnt[i]);
1000 }
1001 fprintf(bcftools_stdout, "\n");
1002 }
1003
1004 void merge_chrom2qual(args_t *args, bcf1_t *out)
1005 {
1006 bcf_srs_t *files = args->files;
1007 bcf_hdr_t *out_hdr = args->out_hdr;
1008
1009 int i, ret;
1010 khiter_t kitr;
1011 strdict_t *tmph = args->tmph;
1012 kh_clear(strdict, tmph);
1013 kstring_t *tmps = &args->tmps;
1014 tmps->l = 0;
1015
1016 maux_t *ma = args->maux;
1017 int *al_idxs = (int*) calloc(ma->nals,sizeof(int));
1018 bcf_float_set_missing(out->qual);
1019
1020 // CHROM, POS, ID, QUAL
1021 out->pos = -1;
1022 for (i=0; i<files->nreaders; i++)
1023 {
1024 bcf1_t *line = maux_get_line(args, i);
1025 if ( !line ) continue;
1026 bcf_unpack(line, BCF_UN_ALL);
1027
1028 bcf_sr_t *reader = &files->readers[i];
1029 bcf_hdr_t *hdr = reader->header;
1030
1031 // not all maux alleles are always used, mark the ones we'll need
1032 int j;
1033 for (j=1; j<line->n_allele; j++)
1034 {
1035 int irec = ma->buf[i].cur;
1036 al_idxs[ ma->buf[i].rec[irec].map[j] ] = 1;
1037 }
1038
1039 // position
1040 if ( out->pos==-1 )
1041 {
1042 const char *chr = hdr->id[BCF_DT_CTG][line->rid].key;
1043 out->rid = bcf_hdr_name2id(out_hdr, chr);
1044 if ( strcmp(chr,out_hdr->id[BCF_DT_CTG][out->rid].key) ) error("Uh\n");
1045 out->pos = line->pos;
1046 }
1047
1048 // ID
1049 if ( line->d.id[0]!='.' || line->d.id[1] )
1050 {
1051 kitr = kh_get(strdict, tmph, line->d.id);
1052 if ( kitr == kh_end(tmph) )
1053 {
1054 if ( tmps->l ) kputc(';', tmps);
1055 kputs(line->d.id, tmps);
1056 kh_put(strdict, tmph, line->d.id, &ret);
1057 }
1058 }
1059
1060 // set QUAL to the max qual value. Not exactly correct, but good enough for now
1061 if ( !bcf_float_is_missing(line->qual) )
1062 {
1063 if ( bcf_float_is_missing(out->qual) || out->qual < line->qual ) out->qual = line->qual;
1064 }
1065 }
1066
1067 // set ID
1068 if ( !tmps->l ) kputs(".", tmps);
1069 bcf_update_id(out_hdr, out, tmps->s);
1070
1071 // set alleles
1072 ma->nout_als = 0;
1073 for (i=1; i<ma->nals; i++)
1074 {
1075 if ( !al_idxs[i] ) continue;
1076 ma->nout_als++;
1077
1078 // Adjust the indexes, the allele map could be created for multiple collapsed records,
1079 // some of which might be unused for this output line
1080 int ir, j;
1081 for (ir=0; ir<files->nreaders; ir++)
1082 {
1083 ma->buf[ir].unkn_allele = 0;
1084 bcf1_t *line = maux_get_line(args,ir);
1085 if ( !line ) continue;
1086 for (j=1; j<line->n_allele; j++)
1087 {
1088 int irec = ma->buf[ir].cur;
1089 if ( ma->buf[ir].rec[irec].map[j]==i ) ma->buf[ir].rec[irec].map[j] = ma->nout_als;
1090 if ( bcf_has_variant_type(line,j,VCF_REF) && line->d.allele[j][0]=='<' ) ma->buf[ir].unkn_allele = j;
1091 }
1092 }
1093 }
1094 // Expand the arrays and realloc the alleles string. Note that all alleles are in a single allocated block.
1095 ma->nout_als++;
1096 hts_expand0(char*, ma->nout_als, ma->mout_als, ma->out_als);
1097 int k = 0;
1098 for (i=0; i<ma->nals; i++)
1099 if ( i==0 || al_idxs[i] ) ma->out_als[k++] = strdup(ma->als[i]);
1100 if ( k!=ma->nout_als ) error("Error: could not merge alleles at %s:%"PRId64", sanity check failed: %d!=%d\n",bcf_seqname(out_hdr,out),out->pos+1,k,ma->nout_als);
1101 normalize_alleles(ma->out_als, ma->nout_als);
1102 bcf_update_alleles(out_hdr, out, (const char**) ma->out_als, ma->nout_als);
1103 free(al_idxs);
1104 for (i=0; i<ma->nout_als; i++) free(ma->out_als[i]);
1105 }
1106
1107 void merge_filter(args_t *args, bcf1_t *out)
1108 {
1109 bcf_srs_t *files = args->files;
1110 bcf_hdr_t *out_hdr = args->out_hdr;
1111
1112 int i, ret;
1113 if ( args->filter_logic == FLT_LOGIC_REMOVE )
1114 {
1115 for (i=0; i<files->nreaders; i++)
1116 {
1117 bcf1_t *line = maux_get_line(args, i);
1118 if ( !line ) continue;
1119 bcf_sr_t *reader = &files->readers[i];
1120 bcf_hdr_t *hdr = reader->header;
1121 if ( bcf_has_filter(hdr, line, "PASS") ) break;
1122 }
1123 if ( i<files->nreaders )
1124 {
1125 int flt_id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, "PASS");
1126 bcf_add_filter(out_hdr, out, flt_id);
1127 return;
1128 }
1129 }
1130
1131 khiter_t kitr;
1132 strdict_t *tmph = args->tmph;
1133 kh_clear(strdict, tmph);
1134
1135 out->d.n_flt = 0;
1136 for (i=0; i<files->nreaders; i++)
1137 {
1138 bcf1_t *line = maux_get_line(args, i);
1139 if ( !line ) continue;
1140
1141 bcf_sr_t *reader = &files->readers[i];
1142 bcf_hdr_t *hdr = reader->header;
1143
1144 int k;
1145 for (k=0; k<line->d.n_flt; k++)
1146 {
1147 const char *flt = hdr->id[BCF_DT_ID][line->d.flt[k]].key;
1148 kitr = kh_get(strdict, tmph, flt);
1149 if ( kitr == kh_end(tmph) )
1150 {
1151 int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, flt);
1152 if ( id==-1 ) error("Error: The filter is not defined in the header: %s\n", flt);
1153 hts_expand(int,out->d.n_flt+1,out->d.m_flt,out->d.flt);
1154 out->d.flt[out->d.n_flt] = id;
1155 out->d.n_flt++;
1156 kh_put(strdict, tmph, flt, &ret);
1157 }
1158 }
1159 }
1160 // Check if PASS is not mixed with other filters
1161 if ( out->d.n_flt>1 )
1162 {
1163 int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, "PASS");
1164 for (i=0; i<out->d.n_flt; i++)
1165 if ( out->d.flt[i]==id ) break;
1166 if ( i<out->d.n_flt )
1167 {
1168 out->d.n_flt--;
1169 for (; i<out->d.n_flt; i++) out->d.flt[i] = out->d.flt[i+1];
1170 }
1171 }
1172 }
1173
1174 static void bcf_info_set_id(bcf1_t *line, bcf_info_t *info, int id, kstring_t *tmp_str)
1175 {
1176 uint8_t *ptr = info->vptr - info->vptr_off;
1177 bcf_dec_typed_int1(ptr, &ptr);
1178
1179 tmp_str->l = 0;
1180 bcf_enc_int1(tmp_str, id);
1181
1182 if ( tmp_str->l == ptr - info->vptr + info->vptr_off )
1183 {
1184 // the new id is represented with the same number of bytes
1185 memcpy(info->vptr - info->vptr_off, tmp_str->s, tmp_str->l);
1186 return;
1187 }
1188
1189 kputsn_(ptr, info->vptr - ptr, tmp_str);
1190 info->vptr_off = tmp_str->l;
1191 kputsn_(info->vptr, info->len << bcf_type_shift[info->type], tmp_str);
1192
1193 info->vptr = (uint8_t*) tmp_str->s + info->vptr_off;
1194 tmp_str->s = NULL;
1195 tmp_str->m = 0;
1196 tmp_str->l = 0;
1197 }
1198
1199 /*
1200 * copy_string_field() - copy a comma-separated field
1201 * @param src: source string
1202 * @param isrc: index of the field to copy
1203 * @param src_len: length of source string (excluding the terminating \0)
1204 * @param dst: destination kstring (must be initialized with missing values, e.g. as ".")
1205 * @param idst: index of the destination field
1206 */
1207 int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst)
1208 {
1209 int ith_src = 0, start_src = 0; // i-th field in src string
1210 while ( ith_src<isrc && start_src<src_len )
1211 {
1212 if ( src[start_src]==',' ) { ith_src++; }
1213 start_src++;
1214 }
1215 if ( ith_src!=isrc ) return -1; // requested field not found
1216 int end_src = start_src;
1217 while ( end_src<src_len && src[end_src] && src[end_src]!=',' ) end_src++;
1218
1219 int nsrc_cpy = end_src - start_src; // number of chars to copy (excluding \0)
1220 if ( nsrc_cpy==1 && src[start_src]=='.' ) return 0; // don't write missing values, dst is already initialized
1221
1222 int ith_dst = 0, start_dst = 0;
1223 while ( ith_dst<idst && start_dst<dst->l )
1224 {
1225 if ( dst->s[start_dst]==',' ) { ith_dst++; }
1226 start_dst++;
1227 }
1228 if ( ith_dst!=idst ) return -2;
1229 int end_dst = start_dst;
1230 while ( end_dst<dst->l && dst->s[end_dst]!=',' ) end_dst++;
1231
1232 if ( end_dst - start_dst>1 || dst->s[start_dst]!='.' ) return 0; // do not overwrite non-empty values
1233
1234 // Now start_dst and end_dst are indexes to the destination memory area
1235 // which needs to be replaced with nsrc_cpy
1236 // source bytes, end_dst points just after.
1237 int ndst_shift = nsrc_cpy - (end_dst - start_dst);
1238 int ndst_move = dst->l - end_dst + 1; // how many bytes must be moved (including \0)
1239 if ( ndst_shift )
1240 {
1241 ks_resize(dst, dst->l + ndst_shift + 1); // plus \0
1242 memmove(dst->s+end_dst+ndst_shift, dst->s+end_dst, ndst_move);
1243 }
1244 memcpy(dst->s+start_dst, src+start_src, nsrc_cpy);
1245 dst->l += ndst_shift;
1246 return 0;
1247 }
1248
1249 static void merge_AGR_info_tag(bcf_hdr_t *hdr, bcf1_t *line, bcf_info_t *info, int len, maux1_t *als, AGR_info_t *agr)
1250 {
1251 int i;
1252 if ( !agr->nbuf )
1253 {
1254 if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 || info->type==BCF_BT_FLOAT )
1255 {
1256 agr->nbuf = 4 * agr->nvals;
1257 hts_expand(uint8_t,agr->nbuf,agr->mbuf,agr->buf);
1258 if ( info->type!=BCF_BT_FLOAT )
1259 {
1260 int32_t *tmp = (int32_t*) agr->buf;
1261 for (i=0; i<agr->nvals; i++) tmp[i] = bcf_int32_missing;
1262 }
1263 else
1264 {
1265 float *tmp = (float*) agr->buf;
1266 for (i=0; i<agr->nvals; i++) bcf_float_set_missing(tmp[i]);
1267 }
1268 }
1269 else if ( info->type==BCF_BT_CHAR )
1270 {
1271 kstring_t tmp; tmp.l = 0; tmp.m = agr->mbuf; tmp.s = (char*)agr->buf;
1272 kputc('.',&tmp);
1273 for (i=1; i<agr->nvals; i++) kputs(",.",&tmp);
1274 agr->mbuf = tmp.m; agr->nbuf = tmp.l; agr->buf = (uint8_t*)tmp.s;
1275 }
1276 else
1277 error("Not ready for type [%d]: %s at %"PRId64"\n", info->type,agr->hdr_tag,(int64_t) line->pos+1);
1278 }
1279
1280 if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 || info->type==BCF_BT_FLOAT )
1281 {
1282 if ( len==BCF_VL_A || len==BCF_VL_R )
1283 {
1284 int ifrom = len==BCF_VL_A ? 1 : 0;
1285 #define BRANCH(type_t, convert, is_missing, is_vector_end, out_type_t) { \
1286 uint8_t *src = info->vptr; \
1287 out_type_t *tgt = (out_type_t *) agr->buf; \
1288 int iori, inew; \
1289 for (iori=ifrom; iori<line->n_allele; iori++, src += sizeof(type_t)) \
1290 { \
1291 type_t val = convert(src); \
1292 if ( is_vector_end ) break; \
1293 if ( is_missing ) continue; \
1294 inew = als->map[iori] - ifrom; \
1295 tgt[inew] = val; \
1296 } \
1297 }
1298 switch (info->type) {
1299 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, int); break;
1300 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, int); break;
1301 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, int); break;
1302 case BCF_BT_FLOAT: BRANCH(float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), float); break;
1303 default: fprintf(bcftools_stderr,"TODO: %s:%d .. info->type=%d\n", __FILE__,__LINE__, info->type); bcftools_exit(1);
1304 }
1305 #undef BRANCH
1306 }
1307 else
1308 {
1309 #define BRANCH(type_t, convert, is_missing, is_vector_end, out_type_t) { \
1310 uint8_t *src = info->vptr; \
1311 out_type_t *tgt = (out_type_t *) agr->buf; \
1312 int iori,jori, inew,jnew; \
1313 for (iori=0; iori<line->n_allele; iori++) \
1314 { \
1315 inew = als->map[iori]; \
1316 for (jori=0; jori<=iori; jori++) \
1317 { \
1318 jnew = als->map[jori]; \
1319 int kori = iori*(iori+1)/2 + jori; \
1320 type_t val = convert(&src[kori * sizeof(type_t)]); \
1321 if ( is_vector_end ) break; \
1322 if ( is_missing ) continue; \
1323 int knew = inew>jnew ? inew*(inew+1)/2 + jnew : jnew*(jnew+1)/2 + inew; \
1324 tgt[knew] = val; \
1325 } \
1326 if ( jori<=iori ) break; \
1327 } \
1328 }
1329 switch (info->type) {
1330 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, int); break;
1331 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, int); break;
1332 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, int); break;
1333 case BCF_BT_FLOAT: BRANCH(float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), float); break;
1334 default: fprintf(bcftools_stderr,"TODO: %s:%d .. info->type=%d\n", __FILE__,__LINE__, info->type); bcftools_exit(1);
1335 }
1336 #undef BRANCH
1337 }
1338 }
1339 else
1340 {
1341 kstring_t tmp; tmp.l = agr->nbuf; tmp.m = agr->mbuf; tmp.s = (char*)agr->buf;
1342 if ( len==BCF_VL_A || len==BCF_VL_R )
1343 {
1344 int iori, ifrom = len==BCF_VL_A ? 1 : 0;
1345 for (iori=ifrom; iori<line->n_allele; iori++)
1346 {
1347 int ret = copy_string_field((char*)info->vptr, iori-ifrom, info->len, &tmp, als->map[iori]-ifrom);
1348 if ( ret )
1349 error("Error at %s:%"PRId64": wrong number of fields in %s?\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,agr->hdr_tag);
1350 }
1351 }
1352 else
1353 {
1354 int iori,jori, inew,jnew;
1355 for (iori=0; iori<line->n_allele; iori++)
1356 {
1357 inew = als->map[iori];
1358 for (jori=0; jori<=iori; jori++)
1359 {
1360 jnew = als->map[jori];
1361 int kori = iori*(iori+1)/2 + jori;
1362 int knew = bcf_alleles2gt(inew,jnew);
1363 int ret = copy_string_field((char*)info->vptr, kori, info->len, &tmp, knew);
1364 if ( ret )
1365 error("Error at %s:%"PRId64": wrong number of fields in %s?\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,agr->hdr_tag);
1366 }
1367 }
1368 }
1369 agr->mbuf = tmp.m; agr->nbuf = tmp.l; agr->buf = (uint8_t*)tmp.s;
1370 }
1371 }
1372
1373 void merge_info(args_t *args, bcf1_t *out)
1374 {
1375 bcf_srs_t *files = args->files;
1376 bcf_hdr_t *out_hdr = args->out_hdr;
1377
1378 int i, j, ret;
1379 khiter_t kitr;
1380 strdict_t *tmph = args->tmph;
1381 kh_clear(strdict, tmph);
1382
1383 maux_t *ma = args->maux;
1384 ma->nAGR_info = 0;
1385 out->n_info = 0;
1386 info_rules_reset(args);
1387 for (i=0; i<files->nreaders; i++)
1388 {
1389 bcf1_t *line = maux_get_line(args,i);
1390 if ( !line ) continue;
1391 int irec = ma->buf[i].cur;
1392 bcf_sr_t *reader = &files->readers[i];
1393 bcf_hdr_t *hdr = reader->header;
1394 for (j=0; j<line->n_info; j++)
1395 {
1396 bcf_info_t *inf = &line->d.info[j];
1397
1398 const char *key = hdr->id[BCF_DT_ID][inf->key].key;
1399 // AC and AN are done in merge_format() after genotypes are done
1400 if (!args->keep_AC_AN &&
1401 (key[0] == 'A'
1402 && (key[1] == 'C' || key[1] == 'N')
1403 && key[2] == 0))
1404 continue;
1405
1406 int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, key);
1407 if ( id==-1 ) error("Error: The INFO field is not defined in the header: %s\n", key);
1408
1409 kitr = kh_get(strdict, tmph, key); // have we seen the tag in one of the readers?
1410 int len = bcf_hdr_id2length(hdr,BCF_HL_INFO,inf->key);
1411 if ( args->nrules )
1412 {
1413 info_rule_t *rule = (info_rule_t*) bsearch(key, args->rules, args->nrules, sizeof(*args->rules), info_rules_comp_key);
1414 if ( rule )
1415 {
1416 maux1_t *als = ( len==BCF_VL_A || len==BCF_VL_G || len==BCF_VL_R ) ? &ma->buf[i].rec[irec] : NULL;
1417 if ( info_rules_add_values(args, hdr, line, rule, als, len) ) continue;
1418 }
1419 }
1420
1421 // Todo: Number=AGR tags should use the newer info_rules_* functions (info_rules_merge_first to be added)
1422 // and merge_AGR_info_tag to be made obsolete.
1423 if ( len==BCF_VL_A || len==BCF_VL_G || len==BCF_VL_R ) // Number=R,G,A requires special treatment
1424 {
1425 if ( kitr == kh_end(tmph) )
1426 {
1427 // seeing this key for the first time
1428 ma->nAGR_info++;
1429 hts_expand0(AGR_info_t,ma->nAGR_info,ma->mAGR_info,ma->AGR_info);
1430 kitr = kh_put(strdict, tmph, key, &ret);
1431 kh_val(tmph,kitr) = ma->nAGR_info - 1;
1432 ma->AGR_info[ma->nAGR_info-1].hdr_tag = key;
1433 ma->AGR_info[ma->nAGR_info-1].type = bcf_hdr_id2type(hdr,BCF_HL_INFO,inf->key);
1434 ma->AGR_info[ma->nAGR_info-1].nbuf = 0; // size of the buffer
1435 switch (len)
1436 {
1437 case BCF_VL_A: ma->AGR_info[ma->nAGR_info-1].nvals = ma->nout_als - 1; break;
1438 case BCF_VL_G: ma->AGR_info[ma->nAGR_info-1].nvals = bcf_alleles2gt(ma->nout_als-1,ma->nout_als-1)+1; break;
1439 case BCF_VL_R: ma->AGR_info[ma->nAGR_info-1].nvals = ma->nout_als; break;
1440 }
1441 }
1442 kitr = kh_get(strdict, tmph, key);
1443 int idx = kh_val(tmph, kitr);
1444 if ( idx<0 ) error("Error occurred while processing INFO tag \"%s\" at %s:%"PRId64"\n", key,bcf_seqname(hdr,line),(int64_t) line->pos+1);
1445 merge_AGR_info_tag(hdr, line,inf,len,&ma->buf[i].rec[irec],&ma->AGR_info[idx]);
1446 continue;
1447 }
1448
1449 if ( kitr == kh_end(tmph) )
1450 {
1451 // Seeing this key for the first time. Although quite hacky,
1452 // this is faster than anything else given the data structures..
1453
1454 hts_expand0(bcf_info_t,out->n_info+1,out->d.m_info,out->d.info);
1455 out->d.info[out->n_info].key = id;
1456 out->d.info[out->n_info].type = inf->type;
1457 out->d.info[out->n_info].len = inf->len;
1458 out->d.info[out->n_info].v1.i = inf->v1.i;
1459 out->d.info[out->n_info].v1.f = inf->v1.f;
1460 out->d.info[out->n_info].vptr_off = inf->vptr_off;
1461 out->d.info[out->n_info].vptr_len = inf->vptr_len;
1462 out->d.info[out->n_info].vptr_free = 1;
1463 out->d.info[out->n_info].vptr = (uint8_t*) malloc(inf->vptr_len+inf->vptr_off);
1464 memcpy(out->d.info[out->n_info].vptr,inf->vptr-inf->vptr_off, inf->vptr_len+inf->vptr_off);
1465 out->d.info[out->n_info].vptr += inf->vptr_off;
1466 if ( (args->output_type & FT_BCF) && id!=bcf_hdr_id2int(hdr, BCF_DT_ID, key) )
1467 bcf_info_set_id(out, &out->d.info[out->n_info], id, &args->tmps);
1468 out->d.shared_dirty |= BCF1_DIRTY_INF;
1469 out->n_info++;
1470 kitr = kh_put(strdict, tmph, key, &ret);
1471 kh_val(tmph,kitr) = -(out->n_info-1); // arbitrary negative value
1472 }
1473 }
1474 }
1475 for (i=0; i<args->nrules; i++)
1476 args->rules[i].merger(args->out_hdr, out, &args->rules[i]);
1477 for (i=0; i<ma->nAGR_info; i++)
1478 {
1479 AGR_info_t *agr = &ma->AGR_info[i];
1480 bcf_update_info(out_hdr,out,agr->hdr_tag,agr->buf,agr->nvals,agr->type);
1481 }
1482 }
1483
1484 void update_AN_AC(bcf_hdr_t *hdr, bcf1_t *line)
1485 {
1486 int32_t an = 0, *tmp = (int32_t*) malloc(sizeof(int)*line->n_allele);
1487 int ret = bcf_calc_ac(hdr, line, tmp, BCF_UN_FMT);
1488 if ( ret>0 )
1489 {
1490 int i;
1491 for (i=0; i<line->n_allele; i++) an += tmp[i];
1492 bcf_update_info_int32(hdr, line, "AN", &an, 1);
1493 bcf_update_info_int32(hdr, line, "AC", tmp+1, line->n_allele-1);
1494 }
1495 free(tmp);
1496 }
1497
1498 static inline int max_used_gt_ploidy(bcf_fmt_t *fmt, int nsmpl)
1499 {
1500 int i,j, max_ploidy = 0;
1501
1502 #define BRANCH(type_t, convert, vector_end) { \
1503 uint8_t *ptr = fmt->p; \
1504 for (i=0; i<nsmpl; i++) \
1505 { \
1506 for (j=0; j<fmt->n; j++) \
1507 if ( convert(&ptr[j * sizeof(type_t)])==vector_end ) break; \
1508 if ( j==fmt->n ) \
1509 { \
1510 /* all fields were used */ \
1511 if ( max_ploidy < j ) max_ploidy = j; \
1512 break; \
1513 } \
1514 if ( max_ploidy < j ) max_ploidy = j; \
1515 ptr += fmt->n * sizeof(type_t); \
1516 } \
1517 }
1518 switch (fmt->type)
1519 {
1520 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, bcf_int8_vector_end); break;
1521 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, bcf_int16_vector_end); break;
1522 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, bcf_int32_vector_end); break;
1523 default: error("Unexpected case: %d\n", fmt->type);
1524 }
1525 #undef BRANCH
1526 return max_ploidy;
1527 }
1528
1529 // Sets ma->laa to local indexes relevant for each sample or missing/vector_end.
1530 // The indexes are with respect to the source indexes and must be translated as
1531 // the very last step.
1532 void init_local_alleles(args_t *args, bcf1_t *out, int ifmt_PL)
1533 {
1534 bcf_srs_t *files = args->files;
1535 maux_t *ma = args->maux;
1536 int i,j,k,l, ismpl = 0, nlaa = 0;
1537 static int warned = 0;
1538
1539 hts_expand(double,out->n_allele,ma->ntmpd,ma->tmpd); // allele probabilities
1540 hts_expand(int,out->n_allele,ma->ntmpi,ma->tmpi); // indexes of the sorted probabilities
1541
1542 // Let map[] be the mapping from src to output idx. Then k2k[] is mapping from src allele idxs to src allele idxs
1543 // reordered so that if i<j then map[k2k[i]] < map[k2k[j]]
1544 hts_expand(int,out->n_allele,ma->nk2k,ma->k2k);
1545
1546 // Determine local alleles: either take all that are present in the reader or use PL to determine the best
1547 // subset for each sample. The alleles must be listed in the order of the alleles in the output file.
1548 for (i=0; i<files->nreaders; i++)
1549 {
1550 bcf_sr_t *reader = &files->readers[i];
1551 bcf_hdr_t *hdr = reader->header;
1552 bcf_fmt_t *fmt_ori = ma->fmt_map[files->nreaders*ifmt_PL+i];
1553 bcf1_t *line = maux_get_line(args, i);
1554 int nsmpl = bcf_hdr_nsamples(hdr);
1555 if ( line )
1556 {
1557 if ( nlaa < line->n_allele - 1 )
1558 nlaa = line->n_allele - 1 <= args->local_alleles ? line->n_allele - 1 : args->local_alleles;
1559
1560 for (j=0; j<line->n_allele; j++) ma->k2k[j] = j;
1561
1562 if ( line->n_allele <= args->local_alleles + 1 )
1563 {
1564 // sort to the output order, insertion sort, ascending
1565 int *map = ma->buf[i].rec[ma->buf[i].cur].map;
1566 int *k2k = ma->k2k;
1567 int tmp;
1568 for (k=1; k<line->n_allele; k++)
1569 for (l=k; l>0 && map[k2k[l]] < map[k2k[l-1]]; l--)
1570 tmp = k2k[l], k2k[l] = k2k[l-1], k2k[l-1] = tmp;
1571
1572 // fewer than the allowed number of alleles, use all alleles from this file
1573 for (j=0; j<nsmpl; j++)
1574 {
1575 int32_t *ptr = ma->laa + (1+args->local_alleles)*ismpl;
1576 for (k=0; k<line->n_allele; k++) ptr[k] = k2k[k];
1577 for (; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end;
1578 ismpl++;
1579 }
1580 continue;
1581 }
1582 }
1583 if ( !line || !fmt_ori )
1584 {
1585 // no values, fill in missing values
1586 for (j=0; j<nsmpl; j++)
1587 {
1588 int32_t *ptr = ma->laa + (1+args->local_alleles)*ismpl;
1589 ptr[0] = bcf_int32_missing;
1590 for (k=1; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end;
1591 ismpl++;
1592 }
1593 continue;
1594 }
1595
1596 // there are more alternate alleles in the input files than is allowed on output, need to subset
1597 if ( ifmt_PL==-1 )
1598 {
1599 if ( !warned )
1600 fprintf(bcftools_stderr,"Warning: local alleles are determined from FORMAT/PL but the tag is missing, cannot apply --local-alleles\n");
1601 warned = 1;
1602 ma->nlaa = 0;
1603 return;
1604 }
1605
1606 if ( !IS_VL_G(hdr, fmt_ori->id) ) error("FORMAT/PL must be defined as Number=G\n");
1607 if ( 2*fmt_ori->n != line->n_allele*(line->n_allele+1) ) error("Todo: haploid PL to LPL\n");
1608
1609 int *map = ma->buf[i].rec[ma->buf[i].cur].map;
1610 double *allele_prob = ma->tmpd;
1611 int *idx = ma->tmpi;
1612 #define BRANCH(src_type_t, convert, src_is_missing, src_is_vector_end, pl2prob_idx) { \
1613 uint8_t *src = fmt_ori->p; \
1614 for (j=0; j<nsmpl; j++) \
1615 { \
1616 for (k=0; k<line->n_allele; k++) allele_prob[k] = 0; \
1617 for (k=0; k<line->n_allele; k++) \
1618 for (l=0; l<=k; l++) \
1619 { \
1620 src_type_t val = convert(src); \
1621 if ( !(src_is_missing) && !(src_is_vector_end) ) \
1622 { \
1623 double prob = ma->pl2prob[pl2prob_idx]; \
1624 allele_prob[k] += prob; \
1625 allele_prob[l] += prob; \
1626 } \
1627 src += sizeof(src_type_t); \
1628 } \
1629 /* insertion sort by allele probability, descending order, with the twist that REF (idx=0) always comes first */ \
1630 allele_prob++; idx[0] = -1; idx++; /* keep REF first */ \
1631 int si,sj,tmp; \
1632 for (si=0; si<line->n_allele-1; si++) idx[si] = si; \
1633 for (si=1; si<line->n_allele-1; si++) \
1634 for (sj=si; sj>0 && allele_prob[idx[sj]] > allele_prob[idx[sj-1]]; sj--) \
1635 tmp = idx[sj], idx[sj] = idx[sj-1], idx[sj-1] = tmp; \
1636 /*for debugging only: test order*/ \
1637 for (si=1; si<line->n_allele-1; si++) \
1638 assert( allele_prob[idx[si-1]] >= allele_prob[idx[si]] ); \
1639 allele_prob--; idx--; /* this was to keep REF first */ \
1640 int32_t *ptr = ma->laa + (1+args->local_alleles)*ismpl; \
1641 ptr[0] = 0; \
1642 for (k=1; k<=args->local_alleles && k<line->n_allele; k++) ptr[k] = idx[k]+1; \
1643 int kmax = k; \
1644 for (; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end; \
1645 /* insertion sort by indexes to the output order, ascending */ \
1646 for (k=1; k<kmax; k++) \
1647 for (l=k; l>0 && map[ptr[l]] < map[ptr[l-1]]; l--) \
1648 tmp = ptr[l], ptr[l] = ptr[l-1], ptr[l-1] = tmp; \
1649 ismpl++; \
1650 } \
1651 }
1652 switch (fmt_ori->type)
1653 {
1654 case BCF_BT_INT8: BRANCH( int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, val); break;
1655 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, val>=0 && val<PL2PROB_MAX ? val : PL2PROB_MAX-1); break;
1656 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, val>=0 && val<PL2PROB_MAX ? val : PL2PROB_MAX-1); break;
1657 default: error("Unexpected case: %d, PL\n", fmt_ori->type);
1658 }
1659 #undef BRANCH
1660 }
1661 ma->nlaa = nlaa;
1662 }
1663
1664 void update_local_alleles(args_t *args, bcf1_t *out)
1665 {
1666 bcf_srs_t *files = args->files;
1667 maux_t *ma = args->maux;
1668 int i,j,k,ismpl=0,nsamples = bcf_hdr_nsamples(args->out_hdr);
1669 for (i=0; i<files->nreaders; i++)
1670 {
1671 int irec = ma->buf[i].cur;
1672 bcf_sr_t *reader = &files->readers[i];
1673 int nsmpl = bcf_hdr_nsamples(reader->header);
1674 for (k=0; k<nsmpl; k++)
1675 {
1676 int32_t *src = ma->laa + ismpl*(1+args->local_alleles);
1677 int32_t *dst = ma->laa + ismpl*ma->nlaa;
1678 j = 0;
1679 if ( irec>=0 )
1680 {
1681 for (; j<ma->nlaa; j++)
1682 {
1683 if ( src[j+1]==bcf_int32_missing ) dst[j] = bcf_int32_missing;
1684 else if ( src[j+1]==bcf_int32_vector_end ) break;
1685 else
1686 dst[j] = ma->buf[i].rec[irec].map[src[j+1]];
1687 }
1688 }
1689 if ( j==0 ) dst[j++] = bcf_int32_missing;
1690 for (; j<ma->nlaa; j++) src[j] = bcf_int32_vector_end;
1691 ismpl++;
1692 }
1693 }
1694 bcf_update_format_int32(args->out_hdr, out, "LAA", ma->laa, nsamples*ma->nlaa);
1695 }
1696
1697 void merge_GT(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out)
1698 {
1699 bcf_srs_t *files = args->files;
1700 bcf_hdr_t *out_hdr = args->out_hdr;
1701 maux_t *ma = args->maux;
1702 int i, ismpl = 0, nsamples = bcf_hdr_nsamples(out_hdr);
1703 static int warned = 0;
1704
1705 int nsize = 0;
1706 for (i=0; i<files->nreaders; i++)
1707 {
1708 bcf_fmt_t *fmt = fmt_map[i];
1709 if ( !fmt ) continue;
1710 int pld = max_used_gt_ploidy(fmt_map[i], bcf_hdr_nsamples(bcf_sr_get_header(args->files,i)));
1711 if ( nsize < pld ) nsize = pld;
1712 }
1713 if ( nsize==0 ) nsize = 1;
1714
1715 size_t msize = sizeof(int32_t)*nsize*nsamples;
1716 if ( msize > 2147483647 )
1717 {
1718 if ( !warned ) fprintf(bcftools_stderr,"Warning: Too many genotypes at %s:%"PRId64", requires %zu bytes, skipping.\n", bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize);
1719 warned = 1;
1720 return;
1721 }
1722 if ( ma->ntmp_arr < msize )
1723 {
1724 ma->tmp_arr = realloc(ma->tmp_arr, msize);
1725 if ( !ma->tmp_arr ) error("Could not allocate %zu bytes\n",msize);
1726 ma->ntmp_arr = msize;
1727 }
1728 memset(ma->smpl_ploidy,0,nsamples*sizeof(int));
1729
1730 int default_gt = args->missing_to_ref ? bcf_gt_unphased(0) : bcf_gt_missing;
1731 for (i=0; i<files->nreaders; i++)
1732 {
1733 bcf_sr_t *reader = &files->readers[i];
1734 bcf_hdr_t *hdr = reader->header;
1735 bcf_fmt_t *fmt_ori = fmt_map[i];
1736 int32_t *tmp = (int32_t *) ma->tmp_arr + ismpl*nsize;
1737 int irec = ma->buf[i].cur;
1738
1739 int j,k;
1740 if ( !fmt_ori )
1741 {
1742 // missing values: assume maximum ploidy
1743 for (j=0; j<bcf_hdr_nsamples(hdr); j++)
1744 {
1745 for (k=0; k<nsize; k++) { tmp[k] = default_gt; ma->smpl_ploidy[ismpl+j]++; }
1746 tmp += nsize;
1747 }
1748 ismpl += bcf_hdr_nsamples(hdr);
1749 continue;
1750 }
1751
1752 #define BRANCH(type_t, convert, vector_end) { \
1753 uint8_t *p_ori = fmt_ori->p; \
1754 if ( !ma->buf[i].rec[irec].als_differ ) \
1755 { \
1756 /* the allele numbering is unchanged */ \
1757 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
1758 { \
1759 for (k=0; k<fmt_ori->n; k++) \
1760 { \
1761 type_t val = convert(&p_ori[k * sizeof(type_t)]); \
1762 if ( val==vector_end ) break; /* smaller ploidy */ \
1763 ma->smpl_ploidy[ismpl+j]++; \
1764 if ( bcf_gt_is_missing(val) ) tmp[k] = 0; /* missing allele */ \
1765 else tmp[k] = val; \
1766 } \
1767 for (; k<nsize; k++) tmp[k] = bcf_int32_vector_end; \
1768 tmp += nsize; \
1769 p_ori += fmt_ori->n * sizeof(type_t); \
1770 } \
1771 ismpl += bcf_hdr_nsamples(hdr); \
1772 continue; \
1773 } \
1774 /* allele numbering needs to be changed */ \
1775 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
1776 { \
1777 for (k=0; k<fmt_ori->n; k++) \
1778 { \
1779 type_t val = convert(&p_ori[k * sizeof(type_t)]); \
1780 if ( val==vector_end ) break; /* smaller ploidy */ \
1781 ma->smpl_ploidy[ismpl+j]++; \
1782 if ( bcf_gt_is_missing(val) ) tmp[k] = 0; /* missing allele */ \
1783 else \
1784 { \
1785 int al = (val>>1) - 1; \
1786 al = al<=0 ? al + 1 : ma->buf[i].rec[irec].map[al] + 1; \
1787 tmp[k] = (al << 1) | ((val)&1); \
1788 } \
1789 } \
1790 for (; k<nsize; k++) tmp[k] = bcf_int32_vector_end; \
1791 tmp += nsize; \
1792 p_ori += fmt_ori->n * sizeof(type_t); \
1793 } \
1794 ismpl += bcf_hdr_nsamples(hdr); \
1795 }
1796 switch (fmt_ori->type)
1797 {
1798 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, bcf_int8_vector_end); break;
1799 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, bcf_int16_vector_end); break;
1800 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, bcf_int32_vector_end); break;
1801 default: error("Unexpected case: %d\n", fmt_ori->type);
1802 }
1803 #undef BRANCH
1804 }
1805 bcf_update_format_int32(out_hdr, out, "GT", (int32_t*)ma->tmp_arr, nsamples*nsize);
1806 }
1807
1808 void merge_format_string(args_t *args, const char *key, bcf_fmt_t **fmt_map, bcf1_t *out, int length, int nsize)
1809 {
1810 bcf_srs_t *files = args->files;
1811 bcf_hdr_t *out_hdr = args->out_hdr;
1812 maux_t *ma = args->maux;
1813 int i,j, nsamples = bcf_hdr_nsamples(out_hdr);
1814 static int warned = 0;
1815
1816 // initialize empty strings, a dot for each value, e.g. ".,.,."
1817 int nmax = 0;
1818 for (i=0; i<nsamples; i++)
1819 {
1820 kstring_t *str = &ma->str[i];
1821 if ( length==BCF_VL_FIXED || length==BCF_VL_VAR )
1822 {
1823 str->l = 1;
1824 ks_resize(str, str->l+1);
1825 str->s[0] = '.';
1826 }
1827 else
1828 {
1829 str->l = nsize*2 - 1;
1830 ks_resize(str, str->l+1);
1831 str->s[0] = '.';
1832 for (j=1; j<nsize; j++) str->s[j*2-1] = ',', str->s[j*2] = '.';
1833 }
1834 str->s[str->l] = 0;
1835 if ( nmax < str->l ) nmax = str->l;
1836 }
1837
1838 // fill in values for each sample
1839 int ismpl = 0;
1840 for (i=0; i<files->nreaders; i++)
1841 {
1842 bcf_sr_t *reader = &files->readers[i];
1843 bcf_hdr_t *hdr = reader->header;
1844 bcf_fmt_t *fmt_ori = fmt_map[i];
1845 if ( !fmt_ori )
1846 {
1847 // the field is not present in this file
1848 ismpl += bcf_hdr_nsamples(hdr);
1849 continue;
1850 }
1851
1852 bcf1_t *line = maux_get_line(args, i);
1853 int irec = ma->buf[i].cur;
1854 char *src = (char*) fmt_ori->p;
1855
1856 if ( length==BCF_VL_FIXED || length==BCF_VL_VAR || (line->n_allele==out->n_allele && !ma->buf[i].rec[irec].als_differ) )
1857 {
1858 // alleles unchanged, copy over
1859 for (j=0; j<bcf_hdr_nsamples(hdr); j++)
1860 {
1861 kstring_t *str = &ma->str[ismpl++];
1862 str->l = 0;
1863 kputsn(src, fmt_ori->n, str);
1864 if ( nmax < str->l ) nmax = str->l;
1865 src += fmt_ori->n;
1866 }
1867 continue;
1868 }
1869 // NB, what is below is not the fastest way, copy_string_field() keeps
1870 // finding the indexes repeatedly at multiallelic sites
1871 if ( length==BCF_VL_A || length==BCF_VL_R )
1872 {
1873 int ifrom = length==BCF_VL_A ? 1 : 0;
1874 for (j=0; j<bcf_hdr_nsamples(hdr); j++)
1875 {
1876 kstring_t *str = &ma->str[ismpl++];
1877 int iori,inew;
1878 for (iori=ifrom; iori<line->n_allele; iori++)
1879 {
1880 inew = ma->buf[i].rec[irec].map[iori] - ifrom;
1881 int ret = copy_string_field(src, iori - ifrom, fmt_ori->size, str, inew);
1882 if ( ret<-1 ) error("[E::%s] fixme: internal error at %s:%"PRId64" .. %d\n",__func__,bcf_seqname(hdr,line),(int64_t) line->pos+1,ret);
1883 }
1884 if ( nmax < str->l ) nmax = str->l;
1885 src += fmt_ori->size;
1886 }
1887 continue;
1888 }
1889 assert( length==BCF_VL_G );
1890 error("[E::%s] Merging of Number=G FORMAT strings (in your case FORMAT/%s) is not supported yet, sorry!\n"
1891 "Please open an issue on github if this feature is essential for you. However, note that using FORMAT strings is not\n"
1892 "a good idea in general - it is slow to parse and does not compress well, it is better to use integer codes instead.\n"
1893 "If you don't really need it, use `bcftools annotate -x` to remove the annotation before merging.\n", __func__,key);
1894 }
1895 // update the record
1896 size_t msize = nsamples*nmax;
1897 if ( msize > 2147483647 )
1898 {
1899 if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize);
1900 warned = 1;
1901 return;
1902 }
1903 if ( ma->ntmp_arr < msize )
1904 {
1905 ma->tmp_arr = realloc(ma->tmp_arr, msize);
1906 if ( !ma->tmp_arr ) error("Could not allocate %zu bytes\n",msize);
1907 ma->ntmp_arr = msize;
1908 }
1909 char *tgt = (char*) ma->tmp_arr;
1910 for (i=0; i<nsamples; i++)
1911 {
1912 memcpy(tgt, ma->str[i].s, ma->str[i].l);
1913 if ( ma->str[i].l < nmax ) memset(tgt + ma->str[i].l, 0, nmax - ma->str[i].l);
1914 tgt += nmax;
1915 }
1916 bcf_update_format_char(out_hdr, out, key, (float*)ma->tmp_arr, nsamples*nmax);
1917 }
1918
1919 // Note: only diploid Number=G tags only for now
1920 void merge_localized_numberG_format_field(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out, int irdr)
1921 {
1922 int i,j,k, nsamples = bcf_hdr_nsamples(args->out_hdr);
1923 bcf_srs_t *files = args->files;
1924 maux_t *ma = args->maux;
1925 bcf_fmt_t *fmt = fmt_map[irdr];
1926 const char *key = files->readers[irdr].header->id[BCF_DT_ID][fmt_map[irdr]->id].key;
1927 size_t nsize = (ma->nlaa+1)*(ma->nlaa+2)/2; // max number of Number=G localized fields
1928 size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t);
1929 msize *= nsamples*nsize;
1930 if ( msize > 2147483647 )
1931 {
1932 static int warned = 0;
1933 if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,msize);
1934 warned = 1;
1935 return;
1936 }
1937 if ( ma->ntmp_arr < msize )
1938 {
1939 ma->tmp_arr = realloc(ma->tmp_arr, msize);
1940 if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key);
1941 ma->ntmp_arr = msize;
1942 }
1943 int ismpl = 0;
1944 for (i=0; i<files->nreaders; i++)
1945 {
1946 bcf_sr_t *reader = &files->readers[i];
1947 bcf_hdr_t *hdr = reader->header;
1948 bcf_fmt_t *fmt_ori = fmt_map[i];
1949 bcf1_t *line = maux_get_line(args, i);
1950 int nsmpl = bcf_hdr_nsamples(hdr);
1951
1952 if ( !fmt_ori )
1953 {
1954 // fill missing values
1955 #define BRANCH(tgt_type_t, tgt_set_missing, tgt_set_vector_end) { \
1956 for (j=0; j<nsmpl; j++) \
1957 { \
1958 tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \
1959 tgt_set_missing; \
1960 for (k=1; k<nsize; k++) { tgt++; tgt_set_vector_end; } \
1961 ismpl++; \
1962 } \
1963 }
1964 switch (fmt->type)
1965 {
1966 case BCF_BT_INT8: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
1967 case BCF_BT_INT16: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
1968 case BCF_BT_INT32: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
1969 case BCF_BT_FLOAT: BRANCH(float, bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break;
1970 default: error("Unexpected case: %d, %s\n", fmt->type, key);
1971 }
1972 #undef BRANCH
1973 continue;
1974 }
1975 if ( 2*fmt_ori->n!=line->n_allele*(line->n_allele+1) ) error("Todo: localization of missing or haploid Number=G tags\n");
1976
1977 // localize
1978 #define BRANCH(tgt_type_t, src_type_t, convert, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \
1979 for (j=0; j<nsmpl; j++) \
1980 { \
1981 uint8_t *src = fmt_ori->p + sizeof(src_type_t)*j*fmt_ori->n; \
1982 tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \
1983 int *laa = ma->laa + (1+args->local_alleles)*ismpl; \
1984 int ii,ij,tgt_idx = 0; \
1985 for (ii=0; ii<=ma->nlaa; ii++) \
1986 { \
1987 if ( laa[ii]==bcf_int32_missing || laa[ii]==bcf_int32_vector_end ) break; \
1988 for (ij=0; ij<=ii; ij++) \
1989 { \
1990 int src_idx = bcf_alleles2gt(laa[ii],laa[ij]); \
1991 src_type_t val = convert(&src[src_idx * sizeof(src_type_t)]); \
1992 if ( src_is_missing ) tgt_set_missing; \
1993 else if ( src_is_vector_end ) break; \
1994 else tgt[tgt_idx] = val; \
1995 tgt_idx++; \
1996 } \
1997 } \
1998 if ( !tgt_idx ) { tgt_set_missing; tgt_idx++; } \
1999 for (; tgt_idx<nsize; tgt_idx++) tgt_set_vector_end; \
2000 ismpl++; \
2001 } \
2002 }
2003 switch (fmt_ori->type)
2004 {
2005 case BCF_BT_INT8: BRANCH(int32_t, int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2006 case BCF_BT_INT16: BRANCH(int32_t, int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2007 case BCF_BT_INT32: BRANCH(int32_t, int32_t, le_to_i16, val==bcf_int32_missing, val==bcf_int32_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2008 case BCF_BT_FLOAT: BRANCH(float, float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), bcf_float_set_missing(tgt[tgt_idx]), bcf_float_set_vector_end(tgt[tgt_idx])); break;
2009 default: error("Unexpected case: %d, %s\n", fmt_ori->type, key);
2010 }
2011 #undef BRANCH
2012 }
2013 args->tmps.l = 0;
2014 kputc('L',&args->tmps);
2015 kputs(key,&args->tmps);
2016 if ( fmt_map[irdr]->type==BCF_BT_FLOAT )
2017 bcf_update_format_float(args->out_hdr, out, args->tmps.s, (float*)ma->tmp_arr, nsamples*nsize);
2018 else
2019 bcf_update_format_int32(args->out_hdr, out, args->tmps.s, (int32_t*)ma->tmp_arr, nsamples*nsize);
2020 ma->laa_dirty = 1;
2021 }
2022 void merge_localized_numberAR_format_field(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out, int irdr)
2023 {
2024 int i,j,k, nsamples = bcf_hdr_nsamples(args->out_hdr);
2025 bcf_srs_t *files = args->files;
2026 maux_t *ma = args->maux;
2027 bcf_fmt_t *fmt = fmt_map[irdr];
2028 const char *key = files->readers[irdr].header->id[BCF_DT_ID][fmt->id].key;
2029 size_t nsize = IS_VL_R(files->readers[irdr].header, fmt->id) ? ma->nlaa + 1 : ma->nlaa;
2030 size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t);
2031 msize *= nsamples*nsize;
2032 if ( msize > 2147483647 )
2033 {
2034 static int warned = 0;
2035 if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,msize);
2036 warned = 1;
2037 return;
2038 }
2039 if ( ma->ntmp_arr < msize )
2040 {
2041 ma->tmp_arr = realloc(ma->tmp_arr, msize);
2042 if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key);
2043 ma->ntmp_arr = msize;
2044 }
2045 int ismpl = 0, ibeg = IS_VL_R(files->readers[irdr].header, fmt->id) ? 0 : 1;;
2046 for (i=0; i<files->nreaders; i++)
2047 {
2048 bcf_sr_t *reader = &files->readers[i];
2049 bcf_hdr_t *hdr = reader->header;
2050 bcf_fmt_t *fmt_ori = fmt_map[i];
2051 int nsmpl = bcf_hdr_nsamples(hdr);
2052
2053 if ( !fmt_ori )
2054 {
2055 // fill missing values
2056 #define BRANCH(tgt_type_t, tgt_set_missing, tgt_set_vector_end) { \
2057 for (j=0; j<nsmpl; j++) \
2058 { \
2059 tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \
2060 tgt_set_missing; \
2061 for (k=1; k<nsize; k++) { tgt++; tgt_set_vector_end; } \
2062 ismpl++; \
2063 } \
2064 }
2065 switch (fmt->type)
2066 {
2067 case BCF_BT_INT8: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2068 case BCF_BT_INT16: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2069 case BCF_BT_INT32: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2070 case BCF_BT_FLOAT: BRANCH(float, bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break;
2071 default: error("Unexpected case: %d, %s\n", fmt->type, key);
2072 }
2073 #undef BRANCH
2074 continue;
2075 }
2076
2077 // localize
2078 #define BRANCH(tgt_type_t, src_type_t, convert, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \
2079 for (j=0; j<nsmpl; j++) \
2080 { \
2081 uint8_t *src = fmt_ori->p + sizeof(src_type_t)*j*fmt_ori->n; \
2082 tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \
2083 int *laa = ma->laa + (1+args->local_alleles)*ismpl; \
2084 int ii,tgt_idx = 0; \
2085 for (ii=ibeg; ii<=ma->nlaa; ii++) \
2086 { \
2087 if ( laa[ii]==bcf_int32_missing || laa[ii]==bcf_int32_vector_end ) break; \
2088 int src_idx = laa[ii] - ibeg; \
2089 src_type_t val = convert(&src[src_idx * sizeof(src_type_t)]); \
2090 if ( src_is_missing ) tgt_set_missing; \
2091 else if ( src_is_vector_end ) break; \
2092 else tgt[tgt_idx] = val; \
2093 tgt_idx++; \
2094 } \
2095 if ( !tgt_idx ) { tgt_set_missing; tgt_idx++; } \
2096 for (; tgt_idx<nsize; tgt_idx++) tgt_set_vector_end; \
2097 ismpl++; \
2098 } \
2099 }
2100 switch (fmt_ori->type)
2101 {
2102 case BCF_BT_INT8: BRANCH(int32_t, int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2103 case BCF_BT_INT16: BRANCH(int32_t, int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2104 case BCF_BT_INT32: BRANCH(int32_t, int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break;
2105 case BCF_BT_FLOAT: BRANCH(float, float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), bcf_float_set_missing(tgt[tgt_idx]), bcf_float_set_vector_end(tgt[tgt_idx])); break;
2106 default: error("Unexpected case: %d, %s\n", fmt_ori->type, key);
2107 }
2108 #undef BRANCH
2109 }
2110 args->tmps.l = 0;
2111 kputc('L',&args->tmps);
2112 kputs(key,&args->tmps);
2113 if ( fmt_map[irdr]->type==BCF_BT_FLOAT )
2114 bcf_update_format_float(args->out_hdr, out, args->tmps.s, (float*)ma->tmp_arr, nsamples*nsize);
2115 else
2116 bcf_update_format_int32(args->out_hdr, out, args->tmps.s, (int32_t*)ma->tmp_arr, nsamples*nsize);
2117 ma->laa_dirty = 1;
2118 }
2119 void merge_format_field(args_t *args, bcf_fmt_t **fmt_map, missing_rule_t *mrule, bcf1_t *out)
2120 {
2121 bcf_srs_t *files = args->files;
2122 bcf_hdr_t *out_hdr = args->out_hdr;
2123 maux_t *ma = args->maux;
2124 int i, ismpl = 0, nsamples = bcf_hdr_nsamples(out_hdr);
2125 static int warned = 0;
2126
2127 const char *key = NULL;
2128 size_t nsize = 0, length = BCF_VL_FIXED;
2129 int type = -1;
2130 for (i=0; i<files->nreaders; i++)
2131 {
2132 if ( !maux_get_line(args,i) ) continue;
2133 if ( !fmt_map[i] ) continue;
2134 if ( !key ) key = files->readers[i].header->id[BCF_DT_ID][fmt_map[i]->id].key;
2135 type = fmt_map[i]->type;
2136 if ( IS_VL_G(files->readers[i].header, fmt_map[i]->id) )
2137 {
2138 length = BCF_VL_G;
2139 nsize = out->n_allele*(out->n_allele + 1)/2;
2140 break;
2141 }
2142 if ( IS_VL_A(files->readers[i].header, fmt_map[i]->id) )
2143 {
2144 length = BCF_VL_A;
2145 nsize = out->n_allele - 1;
2146 break;
2147 }
2148 if ( IS_VL_R(files->readers[i].header, fmt_map[i]->id) )
2149 {
2150 length = BCF_VL_R;
2151 nsize = out->n_allele;
2152 break;
2153 }
2154 if ( fmt_map[i]->n > nsize ) nsize = fmt_map[i]->n;
2155 }
2156 if ( ma->nlaa && length!=BCF_VL_FIXED )
2157 {
2158 if ( length==BCF_VL_G ) merge_localized_numberG_format_field(args,fmt_map,out,i);
2159 else if ( length==BCF_VL_A || length==BCF_VL_R ) merge_localized_numberAR_format_field(args,fmt_map,out,i);
2160 return;
2161 }
2162
2163 if ( type==BCF_BT_CHAR )
2164 {
2165 merge_format_string(args, key, fmt_map, out, length, nsize);
2166 return;
2167 }
2168
2169 size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t);
2170 msize *= nsamples*nsize;
2171 if ( msize > 2147483647 )
2172 {
2173 if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize);
2174 warned = 1;
2175 return;
2176 }
2177 if ( ma->ntmp_arr < msize )
2178 {
2179 ma->tmp_arr = realloc(ma->tmp_arr, msize);
2180 if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key);
2181 ma->ntmp_arr = msize;
2182 }
2183
2184 // Fill the temp array for all samples by collecting values from all files
2185 for (i=0; i<files->nreaders; i++)
2186 {
2187 bcf_sr_t *reader = &files->readers[i];
2188 bcf_hdr_t *hdr = reader->header;
2189 bcf_fmt_t *fmt_ori = fmt_map[i];
2190 bcf1_t *line = maux_get_line(args, i);
2191 int irec = ma->buf[i].cur;
2192
2193 if ( fmt_ori )
2194 {
2195 type = fmt_ori->type;
2196 int nals_ori = line->n_allele;
2197 if ( length==BCF_VL_G )
2198 {
2199 // if all fields are missing then n==1 is valid
2200 if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori*(nals_ori+1)/2 && fmt_map[i]->n != nals_ori )
2201 error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=G, but found\n"
2202 "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n",
2203 key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori);
2204 }
2205 else if ( length==BCF_VL_A )
2206 {
2207 if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori-1 )
2208 error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=A, but found\n"
2209 "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n",
2210 key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori);
2211 }
2212 else if ( length==BCF_VL_R )
2213 {
2214 if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori )
2215 error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=R, but found\n"
2216 "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n",
2217 key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori);
2218 }
2219 }
2220
2221 // set the values
2222 #define BRANCH(tgt_type_t, src_type_t, convert, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \
2223 int j, l, k; \
2224 tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \
2225 if ( !fmt_ori ) \
2226 { \
2227 /* the field is not present in this file, set missing values */ \
2228 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
2229 { \
2230 tgt_set_missing; tgt++; for (l=1; l<nsize; l++) { tgt_set_vector_end; tgt++; } \
2231 } \
2232 ismpl += bcf_hdr_nsamples(hdr); \
2233 continue; \
2234 } \
2235 uint8_t *src = fmt_ori->p; \
2236 if ( (length!=BCF_VL_G && length!=BCF_VL_A && length!=BCF_VL_R) || (line->n_allele==out->n_allele && !ma->buf[i].rec[irec].als_differ) ) \
2237 { \
2238 /* alleles unchanged, copy over */ \
2239 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
2240 { \
2241 for (l=0; l<fmt_ori->n; l++) \
2242 { \
2243 if ( src_is_vector_end ) break; \
2244 else if ( src_is_missing ) tgt_set_missing; \
2245 else *tgt = convert(src); \
2246 tgt++; src += sizeof(src_type_t); \
2247 } \
2248 for (k=l; k<nsize; k++) { tgt_set_vector_end; tgt++; } \
2249 src += sizeof(src_type_t) * (fmt_ori->n - l); \
2250 } \
2251 ismpl += bcf_hdr_nsamples(hdr); \
2252 continue; \
2253 } \
2254 /* allele numbering needs to be changed */ \
2255 if ( length==BCF_VL_G ) \
2256 { \
2257 /* Number=G tags */ \
2258 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
2259 { \
2260 tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize; \
2261 src = fmt_ori->p + sizeof(src_type_t) * j * fmt_ori->n; \
2262 int tag_missing = src_is_missing && fmt_ori->n==1; \
2263 if ( src_is_missing && fmt_ori->n>1 ) { \
2264 src += sizeof(src_type_t); \
2265 tag_missing = src_is_vector_end ; \
2266 } \
2267 if ( tag_missing ) \
2268 { \
2269 /* tag with missing value "." */ \
2270 tgt_set_missing; \
2271 for (l=1; l<nsize; l++) { tgt++; tgt_set_vector_end; } \
2272 continue; \
2273 } \
2274 int haploid = ma->smpl_ploidy[ismpl+j]==1 ? 1 : 0; \
2275 int ngsize = haploid ? out->n_allele : out->n_allele*(out->n_allele + 1)/2; \
2276 if ( ma->buf[i].unkn_allele ) /* Use value from the unknown allele when available */ \
2277 { \
2278 src = fmt_ori->p + sizeof(src_type_t)*j*fmt_ori->n; \
2279 int iunkn = haploid ? ma->buf[i].unkn_allele : (ma->buf[i].unkn_allele+1)*(ma->buf[i].unkn_allele + 2)/2 - 1; \
2280 src_type_t val = convert(&src[iunkn * sizeof(src_type_t)]); \
2281 for (l=0; l<ngsize; l++) { *tgt = val; tgt++; } \
2282 } \
2283 else if ( mrule && mrule->type==MERGE_MISSING_CONST ) \
2284 { \
2285 for (l=0; l<ngsize; l++) { *tgt = mrule->value; tgt++; } \
2286 } \
2287 else if ( mrule && mrule->type==MERGE_MISSING_MAX ) \
2288 { \
2289 src = fmt_ori->p + sizeof(src_type_t)*j*fmt_ori->n; \
2290 src_type_t max = convert(src); \
2291 for (l=1; l<fmt_ori->n; l++) \
2292 { \
2293 src_type_t val = convert(&src[l * sizeof(src_type_t)]); \
2294 if ( max < val ) max = val; \
2295 } \
2296 for (l=0; l<ngsize; l++) { *tgt = max; tgt++; } \
2297 } \
2298 else \
2299 { \
2300 for (l=0; l<ngsize; l++) { tgt_set_missing; tgt++; } \
2301 } \
2302 for (; l<nsize; l++) { tgt_set_vector_end; tgt++; } \
2303 if ( haploid ) \
2304 { \
2305 int iori, inew; \
2306 for (iori=0; iori<line->n_allele; iori++) \
2307 { \
2308 inew = ma->buf[i].rec[irec].map[iori]; \
2309 src = fmt_ori->p + (j*fmt_ori->n + iori) * sizeof(src_type_t); \
2310 tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + inew; \
2311 if ( src_is_vector_end ) break; \
2312 if ( src_is_missing ) tgt_set_missing; \
2313 else *tgt = convert(src); \
2314 } \
2315 } \
2316 else \
2317 { \
2318 /* Diploid */ \
2319 int iori,jori, inew,jnew; \
2320 for (iori=0; iori<line->n_allele; iori++) \
2321 { \
2322 inew = ma->buf[i].rec[irec].map[iori]; \
2323 for (jori=0; jori<=iori; jori++) \
2324 { \
2325 jnew = ma->buf[i].rec[irec].map[jori]; \
2326 int kori = iori*(iori+1)/2 + jori; \
2327 int knew = inew>jnew ? inew*(inew+1)/2 + jnew : jnew*(jnew+1)/2 + inew; \
2328 src = fmt_ori->p + (j*fmt_ori->n + kori) * sizeof(src_type_t); \
2329 tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + knew; \
2330 if ( src_is_vector_end ) \
2331 { \
2332 iori = line->n_allele; \
2333 break; \
2334 } \
2335 if ( src_is_missing ) tgt_set_missing; \
2336 else *tgt = convert(src); \
2337 } \
2338 } \
2339 } \
2340 } \
2341 } \
2342 else \
2343 { \
2344 /* Number=A or Number=R tags */ \
2345 int ifrom = length==BCF_VL_A ? 1 : 0; \
2346 for (j=0; j<bcf_hdr_nsamples(hdr); j++) \
2347 { \
2348 tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize; \
2349 src = fmt_ori->p + j*fmt_ori->size; \
2350 int tag_missing = src_is_missing && fmt_ori->n==1; \
2351 if ( src_is_missing && fmt_ori->n>1 ) { \
2352 src += sizeof(src_type_t); \
2353 tag_missing = src_is_vector_end ; \
2354 } \
2355 if ( tag_missing ) \
2356 { \
2357 /* tag with missing value "." */ \
2358 tgt_set_missing; \
2359 for (l=1; l<nsize; l++) { tgt++; tgt_set_vector_end; } \
2360 continue; \
2361 } \
2362 src = fmt_ori->p + j*fmt_ori->size; \
2363 if ( ma->buf[i].unkn_allele ) /* Use value from the unknown allele when available */ \
2364 { \
2365 int iunkn = ma->buf[i].unkn_allele; \
2366 src_type_t val = convert(&src[iunkn * sizeof(src_type_t)]); \
2367 for (l=0; l<nsize; l++) { *tgt = val; tgt++; } \
2368 } \
2369 else if ( mrule && mrule->type==MERGE_MISSING_CONST ) \
2370 { \
2371 for (l=0; l<nsize; l++) { *tgt = mrule->value; tgt++; } \
2372 } \
2373 else if ( mrule && mrule->type==MERGE_MISSING_MAX ) \
2374 { \
2375 src = fmt_ori->p + sizeof(src_type_t)*j*fmt_ori->n; \
2376 src_type_t max = convert(src); \
2377 for (l=1; l<fmt_ori->n; l++) \
2378 { \
2379 src_type_t val = convert(&src[l * sizeof(src_type_t)]); \
2380 if ( max < val ) max = val; \
2381 } \
2382 for (l=0; l<nsize; l++) { *tgt = max; tgt++; } \
2383 } \
2384 else \
2385 { \
2386 for (l=0; l<nsize; l++) { tgt_set_missing; tgt++; } \
2387 } \
2388 int iori,inew; \
2389 for (iori=ifrom; iori<line->n_allele; iori++) \
2390 { \
2391 inew = ma->buf[i].rec[irec].map[iori] - ifrom; \
2392 tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + inew; \
2393 if ( src_is_vector_end ) break; \
2394 if ( src_is_missing ) tgt_set_missing; \
2395 else *tgt = convert(src); \
2396 src += sizeof(src_type_t); \
2397 } \
2398 } \
2399 } \
2400 ismpl += bcf_hdr_nsamples(hdr); \
2401 }
2402 switch (type)
2403 {
2404 case BCF_BT_INT8: BRANCH(int32_t, int8_t, le_to_i8, le_to_i8(src)==bcf_int8_missing, le_to_i8(src)==bcf_int8_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2405 case BCF_BT_INT16: BRANCH(int32_t, int16_t, le_to_i16, le_to_i16(src)==bcf_int16_missing, le_to_i16(src)==bcf_int16_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2406 case BCF_BT_INT32: BRANCH(int32_t, int32_t, le_to_i32, le_to_i32(src)==bcf_int32_missing, le_to_i32(src)==bcf_int32_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break;
2407 case BCF_BT_FLOAT: BRANCH(float, float, le_to_float, bcf_float_is_missing(le_to_float(src)), bcf_float_is_vector_end(le_to_float(src)), bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break;
2408 default: error("Unexpected case: %d, %s\n", type, key);
2409 }
2410 #undef BRANCH
2411 }
2412 if ( type==BCF_BT_FLOAT )
2413 bcf_update_format_float(out_hdr, out, key, (float*)ma->tmp_arr, nsamples*nsize);
2414 else
2415 bcf_update_format_int32(out_hdr, out, key, (int32_t*)ma->tmp_arr, nsamples*nsize);
2416 }
2417
2418 void merge_format(args_t *args, bcf1_t *out)
2419 {
2420 bcf_srs_t *files = args->files;
2421 bcf_hdr_t *out_hdr = args->out_hdr;
2422 maux_t *ma = args->maux;
2423 if ( !ma->nfmt_map )
2424 {
2425 ma->nfmt_map = 2;
2426 ma->fmt_map = (bcf_fmt_t**) calloc(ma->nfmt_map*files->nreaders, sizeof(bcf_fmt_t*));
2427 ma->fmt_key = (const char**) malloc(ma->nfmt_map*sizeof(*ma->fmt_key));
2428 }
2429 else
2430 memset(ma->fmt_map, 0, ma->nfmt_map*files->nreaders*sizeof(bcf_fmt_t**));
2431
2432 khiter_t kitr;
2433 strdict_t *tmph = args->tmph;
2434 kh_clear(strdict, tmph);
2435 int i, j, ret, has_GT = 0, has_PL = -1, max_ifmt = 0; // max fmt index
2436 for (i=0; i<files->nreaders; i++)
2437 {
2438 bcf1_t *line = maux_get_line(args,i);
2439 if ( !line ) continue;
2440 bcf_sr_t *reader = &files->readers[i];
2441 bcf_hdr_t *hdr = reader->header;
2442 for (j=0; j<line->n_fmt; j++)
2443 {
2444 // Was this tag already seen?
2445 bcf_fmt_t *fmt = &line->d.fmt[j];
2446 const char *key = hdr->id[BCF_DT_ID][fmt->id].key;
2447 kitr = kh_get(strdict, tmph, key);
2448
2449 int ifmt;
2450 if ( kitr != kh_end(tmph) )
2451 ifmt = kh_value(tmph, kitr); // seen
2452 else
2453 {
2454 // new FORMAT tag
2455 if ( key[0]=='G' && key[1]=='T' && key[2]==0 ) { has_GT = 1; ifmt = 0; }
2456 else
2457 {
2458 ifmt = ++max_ifmt;
2459 if ( max_ifmt >= ma->nfmt_map )
2460 {
2461 ma->fmt_map = (bcf_fmt_t**) realloc(ma->fmt_map, sizeof(bcf_fmt_t*)*(max_ifmt+1)*files->nreaders);
2462 memset(ma->fmt_map+ma->nfmt_map*files->nreaders, 0, (max_ifmt-ma->nfmt_map+1)*files->nreaders*sizeof(bcf_fmt_t*));
2463 ma->fmt_key = (const char**) realloc(ma->fmt_key, sizeof(*ma->fmt_key)*(max_ifmt+1));
2464 ma->nfmt_map = max_ifmt+1;
2465 }
2466 if ( key[0]=='P' && key[1]=='L' && key[2]==0 ) { has_PL = ifmt; }
2467 ma->fmt_key[max_ifmt] = key;
2468 }
2469 kitr = kh_put(strdict, tmph, key, &ret);
2470 kh_value(tmph, kitr) = ifmt;
2471 }
2472 ma->fmt_map[ifmt*files->nreaders+i] = fmt;
2473 }
2474 // Check if the allele numbering must be changed
2475 int irec = ma->buf[i].cur;
2476 for (j=1; j<line->n_allele; j++)
2477 if ( ma->buf[i].rec[irec].map[j]!=j ) break;
2478 ma->buf[i].rec[irec].als_differ = j==line->n_allele ? 0 : 1;
2479 }
2480
2481 if ( args->local_alleles )
2482 {
2483 ma->laa_dirty = ma->nlaa = 0;
2484 if ( out->n_allele > args->local_alleles + 1 ) init_local_alleles(args, out, has_PL);
2485 }
2486
2487 out->n_sample = bcf_hdr_nsamples(out_hdr);
2488 if ( has_GT )
2489 merge_GT(args, ma->fmt_map, out);
2490 if ( !args->keep_AC_AN )
2491 update_AN_AC(out_hdr, out);
2492
2493 for (i=1; i<=max_ifmt; i++)
2494 {
2495 missing_rule_t *rule = (missing_rule_t*) bsearch(ma->fmt_key[i], args->missing_rules, args->nmissing_rules, sizeof(*args->missing_rules), missing_rules_comp_key);
2496 merge_format_field(args, &ma->fmt_map[i*files->nreaders], rule, out);
2497 }
2498
2499 if ( ma->laa_dirty )
2500 update_local_alleles(args, out);
2501
2502 out->d.indiv_dirty = 1;
2503 }
2504
2505 void gvcf_set_alleles(args_t *args)
2506 {
2507 int i,k;
2508 bcf_srs_t *files = args->files;
2509 maux_t *maux = args->maux;
2510 gvcf_aux_t *gaux = maux->gvcf;
2511 for (i=0; i<maux->nals; i++)
2512 {
2513 free(maux->als[i]);
2514 maux->als[i] = NULL;
2515 }
2516 maux->nals = 0;
2517
2518 for (i=0; i<files->nreaders; i++)
2519 {
2520 if ( !gaux[i].active ) continue;
2521 bcf1_t *line = maux_get_line(args, i);
2522 if ( !line ) continue;
2523 int irec = maux->buf[i].cur;
2524
2525 hts_expand(int, line->n_allele, maux->buf[i].rec[irec].mmap, maux->buf[i].rec[irec].map);
2526 if ( !maux->nals ) // first record, copy the alleles to the output
2527 {
2528 maux->nals = line->n_allele;
2529 hts_expand0(char*, maux->nals, maux->mals, maux->als);
2530 hts_expand0(int, maux->nals, maux->ncnt, maux->cnt);
2531 for (k=0; k<maux->nals; k++)
2532 {
2533 if ( maux->als[k] ) free(maux->als[k]);
2534 maux->als[k] = strdup(line->d.allele[k]);
2535 maux->buf[i].rec[irec].map[k] = k;
2536 }
2537 }
2538 else
2539 {
2540 maux->als = merge_alleles(line->d.allele, line->n_allele, maux->buf[i].rec[irec].map, maux->als, &maux->nals, &maux->mals);
2541 if ( !maux->als )
2542 {
2543 bcf_hdr_t *hdr = bcf_sr_get_header(args->files,i);
2544 error("Failed to merge alleles at %s:%"PRId64"\n",bcf_seqname(hdr,line),(int64_t) line->pos+1);
2545 }
2546 }
2547 }
2548 }
2549
2550 /*
2551 Output staged gVCF blocks, end is the last position of the block. Assuming
2552 gaux[i].active flags are set and maux_get_line returns correct lines.
2553 Both start,end coordinates are 0-based.
2554 */
2555 void gvcf_write_block(args_t *args, int start, int end)
2556 {
2557 int i;
2558 maux_t *maux = args->maux;
2559 gvcf_aux_t *gaux = maux->gvcf;
2560 assert(gaux);
2561
2562 // Update POS
2563 int min = INT_MAX; // the minimum active gVCF INFO/END (0-based)
2564 char ref = 'N';
2565 for (i=0; i<args->files->nreaders; i++)
2566 {
2567 if ( !gaux[i].active ) continue;
2568 if ( ref=='N' && gaux[i].line->pos==start ) ref = gaux[i].line->d.allele[0][0];
2569 gaux[i].line->pos = start;
2570 }
2571 for (i=0; i<args->files->nreaders; i++)
2572 {
2573 if ( !gaux[i].active ) continue;
2574 if ( gaux[i].end < start )
2575 {
2576 gaux[i].active = 0;
2577 maux->buf[i].cur = -1;
2578 continue;
2579 }
2580 gaux[i].line->d.allele[0][0] = ref;
2581 if ( min > gaux[i].end ) min = gaux[i].end;
2582 }
2583 // Check for valid gVCF blocks in this region
2584 if ( min==INT_MAX ) // this probably should not happen
2585 {
2586 assert(0);
2587 maux->gvcf_min = 0;
2588 return;
2589 }
2590
2591 bcf1_t *out = args->out_line;
2592
2593 gvcf_set_alleles(args);
2594
2595 // Merge the staged lines
2596 merge_chrom2qual(args, out);
2597 merge_filter(args, out);
2598 merge_info(args, out);
2599 merge_format(args, out);
2600
2601 if ( args->gvcf_fai && out->d.allele[0][0]=='N' )
2602 {
2603 int slen = 0;
2604 char *seq = faidx_fetch_seq(args->gvcf_fai,maux->chr,out->pos,out->pos,&slen);
2605 if (!seq)
2606 bcftools_exit(1); // faidx_fetch_seq has already reported the error.
2607
2608 if (slen)
2609 {
2610 out->d.allele[0][0] = seq[0];
2611 free(seq);
2612 }
2613 }
2614
2615 // Update END boundary
2616 if ( end > start )
2617 {
2618 end++;
2619 bcf_update_info_int32(args->out_hdr, out, "END", &end, 1);
2620 }
2621 else
2622 bcf_update_info_int32(args->out_hdr, out, "END", NULL, 0);
2623
2624 int iunseen;
2625 if ( args->trim_star_allele && (out->n_allele > 2 || args->trim_star_allele > 1) && (iunseen=get_unseen_allele(out)) && iunseen>0 )
2626 {
2627 // the unobserved star allele should be trimmed, either it is variant site or trimming of all sites was requested
2628 kbitset_t *rm_set = kbs_init(out->n_allele);
2629 kbs_insert(rm_set, iunseen);
2630 if ( bcf_remove_allele_set(args->out_hdr,out,rm_set) )
2631 error("[%s] Error: failed to trim the unobserved allele at %s:%"PRIhts_pos"\n",__func__,bcf_seqname(args->out_hdr,out),out->pos+1);
2632 kbs_destroy(rm_set);
2633 }
2634 if ( bcf_write1(args->out_fh, args->out_hdr, out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
2635 bcf_clear1(out);
2636
2637 // Inactivate blocks which do not extend beyond END and find new gvcf_min
2638 min = INT_MAX;
2639 for (i=0; i<args->files->nreaders; i++)
2640 {
2641 if ( !gaux[i].active ) continue;
2642 if ( gaux[i].end < end )
2643 {
2644 gaux[i].active = 0;
2645 maux->buf[i].cur = -1;
2646 continue;
2647 }
2648 // next min END position bigger than the current one
2649 if ( maux->gvcf_min < gaux[i].end+1 && min > gaux[i].end+1 ) min = gaux[i].end + 1;
2650 }
2651 maux->gvcf_min = min==INT_MAX ? 0 : min;
2652 }
2653
2654 /*
2655 Flush staged gVCF blocks. Flush everything if there are no more lines
2656 (done=1) or if there is a new chromosome. If still on the same chromosome,
2657 all hanging blocks must be ended by creating new records:
2658 A
2659 1 END=10
2660 B
2661 3 END=7
2662 C
2663 3 END=5
2664 out
2665 1 END=2 A . .
2666 3 END=5 A B C
2667 6 END=7 A B .
2668 8 END=10 A . .
2669
2670 */
2671 void gvcf_flush(args_t *args, int done)
2672 {
2673 int i;
2674 maux_t *maux = args->maux;
2675
2676 if ( !maux->chr ) return; // first time here, nothing to flush
2677
2678 int flush_until = INT_MAX;
2679 if ( !done )
2680 {
2681 // Get current position and chromosome
2682 for (i=0; i<maux->n; i++)
2683 if ( bcf_sr_has_line(maux->files,i) ) break;
2684 bcf1_t *line = bcf_sr_get_line(maux->files,i);
2685 bcf_hdr_t *hdr = bcf_sr_get_header(maux->files,i);
2686
2687 if ( !strcmp(maux->chr,bcf_seqname(hdr,line)) ) flush_until = line->pos; // still on the same chr
2688 }
2689
2690 // When called on a region, trim the blocks accordingly
2691 int start = maux->gvcf_break>=0 ? maux->gvcf_break + 1 : maux->pos; // the start of a new gvcf block to output
2692 if ( args->regs )
2693 {
2694 int rstart = -1, rend = -1;
2695 if ( regidx_overlap(args->regs,maux->chr,start,flush_until,args->regs_itr) )
2696 {
2697 // In case there are multiple regions, we treat them as one
2698 rstart = args->regs_itr->beg;
2699 while ( regitr_overlap(args->regs_itr) ) rend = args->regs_itr->end;
2700 }
2701 if ( rstart > start ) start = rstart;
2702 if ( rend < flush_until ) flush_until = rend+1;
2703 }
2704
2705 // output all finished blocks
2706 while ( maux->gvcf_min && start < flush_until )
2707 {
2708 // does the block end before the new line or is it interrupted?
2709 int tmp = maux->gvcf_min < flush_until ? maux->gvcf_min : flush_until;
2710 if ( start > tmp-1 ) break;
2711 gvcf_write_block(args,start,tmp-1); // gvcf_min is 1-based, passing 0-based coordinates
2712 start = tmp;
2713 }
2714 }
2715
2716 static inline int is_gvcf_block(bcf1_t *line)
2717 {
2718 if ( line->rlen<=1 ) return 0;
2719 if ( strlen(line->d.allele[0])==line->rlen ) return 0;
2720 if ( line->n_allele==1 ) return 1;
2721
2722 int i;
2723 for (i=1; i<line->n_allele; i++)
2724 {
2725 if ( !strcmp(line->d.allele[i],"<*>") ) return 1;
2726 if ( !strcmp(line->d.allele[i],"<NON_REF>") ) return 1;
2727 if ( !strcmp(line->d.allele[i],"<X>") ) return 1;
2728 }
2729 return 0;
2730 }
2731
2732 /*
2733 Check incoming lines for new gVCF blocks, set pointer to the current source
2734 buffer (gvcf or readers). In contrast to gvcf_flush, this function can be
2735 called only after maux_reset as it relies on updated maux buffers.
2736 The coordinate is 0-based
2737 */
2738 void gvcf_stage(args_t *args, int pos)
2739 {
2740 maux_t *maux = args->maux;
2741 gvcf_aux_t *gaux = maux->gvcf;
2742 bcf_srs_t *files = args->files;
2743 int32_t *end = (int32_t*) maux->tmp_arr;
2744 int i, nend = maux->ntmp_arr / sizeof(int32_t);
2745
2746 maux->gvcf_break = -1;
2747 maux->gvcf_min = INT_MAX;
2748 for (i=0; i<files->nreaders; i++)
2749 {
2750 if ( gaux[i].active && gaux[i].end < pos ) gaux[i].active = 0;
2751 if ( gaux[i].active )
2752 {
2753 // gvcf block should not overlap with another record
2754 if ( maux->gvcf_min > gaux[i].end+1 ) maux->gvcf_min = gaux[i].end + 1;
2755 maux->buf[i].beg = 0;
2756 maux->buf[i].end = 1;
2757 maux->buf[i].cur = 0;
2758 continue;
2759 }
2760
2761 // Does any of the lines have END set? It is enough to check only the
2762 // first line, there should be no duplicate records with END in gVCF
2763
2764 if ( maux->buf[i].beg==maux->buf[i].end ) continue; // no new record
2765
2766 int irec = maux->buf[i].beg;
2767 bcf_hdr_t *hdr = bcf_sr_get_header(files, i);
2768 bcf1_t *line = args->files->readers[i].buffer[irec];
2769 int ret = is_gvcf_block(line) ? bcf_get_info_int32(hdr,line,"END",&end,&nend) : 0;
2770 if ( ret==1 )
2771 {
2772 if ( end[0] == line->pos + 1 ) // POS and INFO/END are identical, treat as if a normal w/o INFO/END
2773 {
2774 maux->gvcf_break = line->pos;
2775 continue;
2776 }
2777 if ( end[0] <= line->pos ) error("Error: Incorrect END at %s:%"PRId64" .. END=%d\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,end[0]);
2778
2779 // END is set, this is a new gVCF block. Cache this line in gaux[i] and swap with
2780 // an empty record: the gaux line must be kept until we reach its END.
2781
2782 gaux[i].active = 1;
2783 gaux[i].end = end[0] - 1;
2784 SWAP(bcf1_t*,args->files->readers[i].buffer[irec],gaux[i].line);
2785 gaux[i].line->pos = pos;
2786
2787 maux->buf[i].lines = &gaux[i].line;
2788 maux->buf[i].beg = 0;
2789 maux->buf[i].end = 1;
2790 maux->buf[i].cur = 0;
2791
2792 // Set the rid,pos of the swapped line in the buffer or else the
2793 // synced reader will have a problem with the next line
2794 //
2795 args->files->readers[i].buffer[irec]->rid = maux->buf[i].rid;
2796 args->files->readers[i].buffer[irec]->pos = maux->pos;
2797
2798 // Update block offsets
2799 if ( maux->gvcf_min > gaux[i].end+1 ) maux->gvcf_min = gaux[i].end + 1;
2800 }
2801 else
2802 maux->gvcf_break = line->pos; // must break the gvcf block
2803 }
2804 maux->ntmp_arr = nend * sizeof(int32_t);
2805 maux->tmp_arr = end;
2806 if ( maux->gvcf_min==INT_MAX ) maux->gvcf_min = 0;
2807 }
2808
2809
2810 void debug_buffers(FILE *fp, bcf_srs_t *files);
2811 void debug_buffer(FILE *fp, bcf_srs_t *files, int reader);
2812
2813 /*
2814 Flush all buffered and processed records with the same coordinate.
2815 Note that synced reader discards buffer[0], so that needs to stay
2816 untouched.
2817 */
2818 void clean_buffer(args_t *args)
2819 {
2820 maux_t *ma = args->maux;
2821
2822 int ir;
2823 for (ir=0; ir<ma->n; ir++)
2824 {
2825 // Invalidate pointer to reader's buffer or else gvcf_flush will attempt
2826 // to use the old lines via maux_get_line()
2827 if ( ma->gvcf )
2828 {
2829 if ( ma->gvcf[ir].active )
2830 {
2831 if ( ma->pos > ma->gvcf[ir].end ) ma->gvcf[ir].active = 0;
2832 else if ( ma->buf[ir].cur==-1 ) ma->buf[ir].cur = ma->buf[ir].beg; // re-activate interrupted gVCF block
2833 }
2834 if ( !ma->gvcf[ir].active ) ma->buf[ir].cur = -1;
2835 }
2836
2837 bcf_sr_t *reader = bcf_sr_get_reader(args->files,ir);
2838 if ( !reader->nbuffer ) continue; // nothing to clean
2839
2840 bcf1_t **buf = reader->buffer;
2841 if ( buf[1]->rid!=ma->buf[ir].rid || buf[1]->pos!=ma->pos ) continue; // nothing to flush
2842
2843 int a = 1, b = 2;
2844 while ( b<=reader->nbuffer && buf[b]->rid==ma->buf[ir].rid && buf[b]->pos==ma->pos ) b++;
2845 // b now points to the first line we want to preserve
2846 while ( b<=reader->nbuffer )
2847 {
2848 SWAP(bcf1_t*, buf[a], buf[b]);
2849 a++; b++;
2850 }
2851 reader->nbuffer -= b-a;
2852 }
2853 }
2854
2855 void debug_maux(args_t *args)
2856 {
2857 bcf_srs_t *files = args->files;
2858 maux_t *maux = args->maux;
2859 int j,k,l;
2860
2861 fprintf(bcftools_stderr,"Alleles to merge at %d, nals=%d\n", maux->pos+1,maux->nals);
2862 for (j=0; j<files->nreaders; j++)
2863 {
2864 bcf_sr_t *reader = &files->readers[j];
2865 buffer_t *buf = &maux->buf[j];
2866 fprintf(bcftools_stderr," reader %d (k=%d-%d): ", j,buf->beg,buf->end);
2867 for (k=buf->beg; k<buf->end; k++)
2868 {
2869 if ( buf->rec[k].skip & SKIP_DONE ) { fprintf(bcftools_stderr," DONE"); continue; }
2870 bcf1_t *line = reader->buffer[k]; // selected for merging by can_merge
2871 fprintf(bcftools_stderr,"\t");
2872 if ( buf->cur==k ) fprintf(bcftools_stderr,"!"); // selected for merging by stage_line
2873 if ( buf->rec[k].skip ) fprintf(bcftools_stderr,"["); // this record cannot be merged in this round
2874 if ( !line->n_allele && maux->gvcf[j].active )
2875 fprintf(bcftools_stderr,"<*>");
2876 for (l=0; l<line->n_allele; l++)
2877 fprintf(bcftools_stderr,"%s%s", l==0?"":",", line->d.allele[l]);
2878 if ( buf->rec[k].skip ) fprintf(bcftools_stderr,"]");
2879 }
2880 fprintf(bcftools_stderr,"\n");
2881 }
2882 fprintf(bcftools_stderr," counts: ");
2883 for (j=0; j<maux->nals; j++) fprintf(bcftools_stderr,"%s %dx %s", j==0?"":",",maux->cnt[j], maux->als[j]);
2884 fprintf(bcftools_stderr,"\n\n");
2885 }
2886
2887 void debug_state(args_t *args)
2888 {
2889 maux_t *maux = args->maux;
2890 int i,j;
2891 fprintf(bcftools_stderr,"State after position=%d done:\n",maux->pos+1);
2892 for (i=0; i<args->files->nreaders; i++)
2893 {
2894 fprintf(bcftools_stderr,"\treader %d:\tcur,beg,end=% d,%d,%d", i,maux->buf[i].cur,maux->buf[i].beg,maux->buf[i].end);
2895 if ( maux->buf[i].cur >=0 )
2896 {
2897 bcf_hdr_t *hdr = bcf_sr_get_header(args->files,i);
2898 const char *chr = bcf_hdr_id2name(hdr, maux->buf[i].rid);
2899 fprintf(bcftools_stderr,"\t");
2900 for (j=maux->buf[i].beg; j<maux->buf[i].end; j++) fprintf(bcftools_stderr," %s:%"PRId64,chr,(int64_t) maux->buf[i].lines[j]->pos+1);
2901 }
2902 fprintf(bcftools_stderr,"\n");
2903 }
2904 fprintf(bcftools_stderr,"\tgvcf_min=%d\n", args->maux->gvcf_min);
2905 for (i=0; i<args->files->nreaders; i++)
2906 {
2907 fprintf(bcftools_stderr,"\t\treader %d:\tgvcf_active=%d", i,maux->gvcf[i].active);
2908 if ( maux->gvcf[i].active ) fprintf(bcftools_stderr,"\tpos,end=%"PRId64",%"PRId64, (int64_t) maux->gvcf[i].line->pos+1,(int64_t) maux->gvcf[i].end+1);
2909 fprintf(bcftools_stderr,"\n");
2910 }
2911 fprintf(bcftools_stderr,"\n");
2912 }
2913
2914
2915 // Lines can come with any combination of variant types. We use a subset of types defined in vcf.h
2916 // but shift by two bits to account for VCF_REF defined as 0 (design flaw in vcf.h, my fault)
2917 static const int
2918 snp_mask = (VCF_SNP<<1)|(VCF_MNP<<1),
2919 indel_mask = (VCF_INDEL<<1),
2920 ins_mask = VCF_INS<<1,
2921 del_mask = VCF_DEL<<1,
2922 ref_mask = 1;
2923
2924 // Can these types be merged given the -m settings? Despite the function's name, its focus is on
2925 // excluding incompatible records, there will be a finer matching later in stage_line()
2926 static inline int types_compatible(args_t *args, int selected_types, buffer_t *buf, int irec)
2927 {
2928 int k;
2929 maux_t *maux = args->maux;
2930 bcf1_t *rec = buf->lines[irec];
2931 int rec_types = buf->rec[irec].var_types;
2932
2933 assert( selected_types ); // this is trivially true, set in can_merge()
2934
2935 if ( args->collapse & COLLAPSE_ANY ) return 1; // can merge anything with anything
2936
2937 // REF and gVCF_REF with no other alleles present can be merged with anything
2938 if ( (selected_types&ref_mask) && !(selected_types&(~ref_mask)) ) return 1;
2939 if ( (rec_types&ref_mask) && !(rec_types&(~ref_mask)) ) return 1;
2940
2941 if ( args->collapse!=COLLAPSE_NONE )
2942 {
2943 // If we are here, one the following modes must have been set: both,snps,indels,snp-ins-del
2944 // Include the new record if
2945 // - rec has SNV, we already have SNV, and -m is both,snps,snp-ins-del
2946 // - rec has indel, we already have an indel, and -m both,indels,snp-ins-del
2947 if ( args->collapse&(COLLAPSE_SNPS|COLLAPSE_SNP_INS_DEL) )
2948 {
2949 if ( (rec_types&snp_mask) && (selected_types&snp_mask) ) return 1;
2950 }
2951 if ( args->collapse&COLLAPSE_INDELS )
2952 {
2953 if ( (rec_types&indel_mask) && (selected_types&indel_mask) ) return 1;
2954 }
2955 if ( args->collapse&COLLAPSE_SNP_INS_DEL )
2956 {
2957 if ( (rec_types&ins_mask) && (selected_types&ins_mask) ) return 1;
2958 if ( (rec_types&del_mask) && (selected_types&del_mask) ) return 1;
2959 }
2960 // Whatever is left, allow to match if the alleles match exactly
2961 }
2962
2963 // The -m none mode or exact matching requested
2964 // Simple test first: are the variants of the same type?
2965 int x = selected_types >> 1; // remove REF
2966 int y = rec_types >> 1; // remove REF
2967 while ( x && y ) { x>>=1; y>>=1; }
2968 if ( x || y ) return 0; // the types differ
2969
2970 if ( vcmp_set_ref(args->vcmp,maux->als[0],rec->d.allele[0]) < 0 ) return 0; // refs are not compatible
2971 for (k=1; k<rec->n_allele; k++)
2972 {
2973 if ( bcf_has_variant_type(rec,k,VCF_REF) ) continue; // this must be gVCF_REF (<*> or <NON_REF>)
2974 if ( vcmp_find_allele(args->vcmp,maux->als+1,maux->nals-1,rec->d.allele[k])>=0 ) break;
2975 }
2976 if ( k==rec->n_allele ) return 0; // this record has a new allele rec->d.allele[k]
2977 return 1; // all alleles in rec are also in the records selected thus far, perhaps save for gVCF_REF
2978 }
2979
2980 static void maux_update_alleles(args_t *args, int ireader, int irec)
2981 {
2982 int k;
2983 bcf_sr_t *reader = &args->files->readers[ireader];
2984 maux_t *maux = args->maux;
2985 buffer_t *buf = &maux->buf[ireader];
2986 maux1_t *ma1 = &buf->rec[irec];
2987 bcf1_t *line = buf->lines[irec];
2988 hts_expand(int, line->n_allele, ma1->mmap, ma1->map);
2989 if ( !maux->nals ) // first record to be merged, copy the alleles to the output
2990 {
2991 maux->nals = line->n_allele;
2992 hts_expand0(char*, maux->nals, maux->mals, maux->als);
2993 hts_expand0(int, maux->nals, maux->ncnt, maux->cnt);
2994 hts_expand0(int, maux->nals, maux->mals_types, maux->als_types);
2995 for (k=0; k<maux->nals; k++)
2996 {
2997 free(maux->als[k]);
2998 maux->als[k] = strdup(line->d.allele[k]);
2999 ma1->map[k] = k;
3000 maux->cnt[k] = 1;
3001 int var_type = bcf_has_variant_type(line, k, VCF_ANY);
3002 if ( args->collapse==COLLAPSE_SNP_INS_DEL ) var_type &= ~VCF_INDEL;
3003 maux->als_types[k] = var_type ? var_type<<1 : ref_mask;
3004 }
3005 return;
3006 }
3007 // normalize alleles
3008 maux->als = merge_alleles(line->d.allele, line->n_allele, ma1->map, maux->als, &maux->nals, &maux->mals);
3009 if ( !maux->als ) error("Failed to merge alleles at %s:%"PRId64" in %s\n",maux->chr,(int64_t) line->pos+1,reader->fname);
3010 hts_expand0(int, maux->nals, maux->ncnt, maux->cnt);
3011 hts_expand0(int, maux->nals, maux->mals_types, maux->als_types);
3012 for (k=1; k<line->n_allele; k++)
3013 {
3014 int ik = ma1->map[k];
3015 int var_type = bcf_has_variant_type(line, k, VCF_ANY);
3016 if ( args->collapse==COLLAPSE_SNP_INS_DEL ) var_type &= ~VCF_INDEL;
3017 maux->als_types[ik] = var_type ? var_type<<1 : ref_mask;
3018 maux->cnt[ik]++; // how many times an allele appears in the files
3019 }
3020 maux->cnt[0]++;
3021 }
3022
3023 /*
3024 Determine which lines remain to be merged across readers at the current position and
3025 are compatible given the -m criteria. This is indicated by maux1_t.skip: 0=compatible,
3026 SKIP_DONE=the record is done, SKIP_DIFF=not compatible and will be included next time.
3027
3028 At the same time count how many times is each allele present across the readers and records
3029 so that we can prioritize the records with the same alleles to come first. In the end maximum
3030 one record at a time can be selected from each reader and that witll be done in stage_line().
3031
3032 The function maux_reset already initialized structures for this position, so here each
3033 reader comes with the beg,end indexes that point to records with the same maux_t.pos position.
3034 */
3035 int can_merge(args_t *args)
3036 {
3037 bcf_srs_t *files = args->files;
3038 maux_t *maux = args->maux;
3039 gvcf_aux_t *gaux = maux->gvcf;
3040 char *id = NULL, ref = 'N';
3041 int i,j, ntodo = 0;
3042
3043 for (i=0; i<maux->nals; i++)
3044 {
3045 free(maux->als[i]);
3046 maux->als[i] = NULL;
3047 maux->cnt[i] = 0;
3048 }
3049 maux->var_types = maux->nals = 0;
3050
3051 // In this loop we do the following:
3052 // - remember the first encountered ID if matching by ID
3053 // - count the number of unprocessed records at this position
3054 // - collect all variant types at this position. This is to be able to perform -m matching and
3055 // print SNVs first, then indels, then gVCF blocks
3056 // - init the 'skip' variable to SKIP_DIFF for each record that has not been used yet
3057 for (i=0; i<files->nreaders; i++)
3058 {
3059 buffer_t *buf = &maux->buf[i];
3060 buf->var_types = 0;
3061
3062 if ( gaux && gaux[i].active ) // active gvcf block
3063 {
3064 buf->rec[buf->beg].skip = SKIP_DIFF;
3065 maux->var_types |= ref_mask;
3066 buf->var_types |= ref_mask;
3067 buf->rec[buf->beg].var_types = ref_mask;
3068 continue;
3069 }
3070
3071 // for gvcf: find out REF at this position
3072 if ( buf->beg < buf->end && ref=='N' ) ref = buf->lines[buf->beg]->d.allele[0][0];
3073
3074 for (j=buf->beg; j<buf->end; j++)
3075 {
3076 if ( buf->rec[j].skip & SKIP_DONE ) continue;
3077
3078 buf->rec[j].skip = SKIP_DIFF;
3079 ntodo++;
3080
3081 bcf1_t *line = buf->lines[j];
3082 if ( args->merge_by_id && !id ) { id = line->d.id; continue; } // set ID when merging by id
3083
3084 if ( !buf->rec[j].var_types )
3085 {
3086 int var_type = bcf_has_variant_types(line, VCF_ANY, bcf_match_overlap);
3087 if ( var_type < 0 ) error("bcf_has_variant_types() failed.");
3088 if ( args->collapse==COLLAPSE_SNP_INS_DEL )
3089 {
3090 // need to distinguish between ins and del so strip the VCF_INDEL flag
3091 var_type &= ~VCF_INDEL;
3092 }
3093 var_type = var_type ? var_type<<1 : ref_mask;
3094 if ( args->do_gvcf && is_gvcf_block(line) ) var_type |= ref_mask;
3095 buf->rec[j].var_types = var_type;
3096 }
3097 maux->var_types |= buf->rec[j].var_types;
3098 buf->var_types |= buf->rec[j].var_types;
3099 }
3100 }
3101 if ( !ntodo ) return 0;
3102
3103 int selected_types = 0;
3104
3105 // In this loop we select from each reader compatible candidate lines.
3106 // (i.e. SNPs or indels). Go through all files and all lines at this
3107 // position and normalize relevant alleles.
3108 // REF-only sites may be associated with both SNPs and indels.
3109 for (i=0; i<files->nreaders; i++)
3110 {
3111 buffer_t *buf = &maux->buf[i];
3112 if ( gaux && gaux[i].active )
3113 {
3114 // gVCF records inherited from an upstream gVCF block have incorrect or missing allele and position
3115 gaux[i].line->d.allele[0][0] = ref;
3116 gaux[i].line->pos = maux->pos;
3117 maux_update_alleles(args, i, buf->beg);
3118 selected_types |= ref_mask;
3119 continue;
3120 }
3121 for (j=buf->beg; j<buf->end; j++)
3122 {
3123 if ( buf->rec[j].skip & SKIP_DONE ) continue;
3124
3125 bcf1_t *line = buf->lines[j]; // ptr to reader's buffer or gvcf buffer
3126 int line_types = buf->rec[j].var_types;
3127
3128 // select relevant lines
3129 if ( args->merge_by_id )
3130 {
3131 if ( strcmp(id,line->d.id) ) continue; // matching by ID and it does not match the selected record
3132 }
3133 else if ( selected_types && !types_compatible(args,selected_types,buf,j) ) continue;
3134 else
3135 {
3136 // First time here, choosing the first line: prioritize SNPs when available in the -m snps,both modes
3137 if ( (args->collapse&COLLAPSE_SNPS || args->collapse==COLLAPSE_NONE) // asked to merge SNVs into multiallelics
3138 && (maux->var_types&snp_mask) // there are SNVs at the current position
3139 && !(buf->rec[j].var_types&(snp_mask|ref_mask)) // and this record is not a SNV nor ref
3140 ) continue;
3141 }
3142 selected_types |= line_types;
3143
3144 buf->rec[j].skip = 0; // the j-th record from i-th reader can be included. Final decision will be made in stage_line
3145 maux_update_alleles(args, i, j);
3146 }
3147 }
3148 return 1;
3149 }
3150
3151 /*
3152 Select records that have the same alleles; the input ordering of indels
3153 must not matter. Multiple VCF lines can be emitted from this loop.
3154 We expect only very few alleles and not many records with the same
3155 position in the buffers, therefore the nested loops should not slow us
3156 much.
3157 */
3158 void stage_line(args_t *args)
3159 {
3160 bcf_srs_t *files = args->files;
3161 maux_t *maux = args->maux;
3162
3163 // Take the most frequent allele present in multiple files, REF and gVCF_REF is skipped.
3164 int i,j,k,icnt = -1;
3165 for (i=1; i<maux->nals; i++)
3166 {
3167 if ( maux->als_types[i] & ref_mask ) continue;
3168 if ( icnt==-1 || maux->cnt[icnt] < maux->cnt[i] ) icnt = i;
3169 }
3170 int selected_type = icnt>0 ? maux->als_types[icnt] : ref_mask;
3171
3172 int nout = 0;
3173 for (i=0; i<files->nreaders; i++)
3174 {
3175 buffer_t *buf = &maux->buf[i];
3176 buf->cur = -1;
3177 if ( buf->beg >= buf->end ) continue; // No lines in the buffer at this site
3178
3179 // find lines with the same allele
3180 for (j=buf->beg; j<buf->end; j++)
3181 {
3182 if ( buf->rec[j].skip )
3183 {
3184 int is_gvcf = maux->gvcf && maux->gvcf[i].active ? 1 : 0;
3185 if ( !is_gvcf && is_gvcf_block(buf->lines[j]) ) is_gvcf = 1;
3186 if ( !is_gvcf ) continue; // done or not compatible
3187 }
3188 if ( args->merge_by_id ) break; // if merging by ID and the line is compatible, the this is THE line
3189
3190 // skip if the reader has a record that matches the most frequent allele and this record is not it
3191 if ( (selected_type & buf->var_types) && !(selected_type & buf->rec[j].var_types) ) continue;
3192
3193 // if the reader does not have the most frequent allele type but is a ref, accept
3194 if ( !(selected_type & buf->var_types) && (buf->rec[j].var_types & ref_mask) ) break;
3195 if ( selected_type==ref_mask ) break;
3196
3197 // accept if the record has the most frequent allele
3198 for (k=0; k<buf->lines[j]->n_allele; k++)
3199 if ( icnt==buf->rec[j].map[k] ) break;
3200 if ( k<buf->lines[j]->n_allele ) break;
3201 }
3202 if ( j>=buf->end )
3203 {
3204 // no matching allele found in this file
3205 if ( args->collapse==COLLAPSE_NONE ) continue; // exact matching requested, skip
3206
3207 // choose something compatible to create a multiallelic site given the -m criteria
3208 for (j=buf->beg; j<buf->end; j++)
3209 {
3210 if ( buf->rec[j].skip ) continue; // done or not compatible
3211 if ( args->collapse&COLLAPSE_ANY ) break; // anything can be merged
3212 int line_type = buf->rec[j].var_types;
3213 if ( maux->var_types&snp_mask && line_type&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break;
3214 if ( maux->var_types&indel_mask && line_type&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break;
3215 if ( maux->var_types&ins_mask && line_type&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3216 if ( maux->var_types&del_mask && line_type&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3217 if ( line_type&ref_mask )
3218 {
3219 if ( maux->var_types&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break;
3220 if ( maux->var_types&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break;
3221 if ( maux->var_types&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3222 if ( maux->var_types&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3223 if ( maux->var_types&ref_mask ) break;
3224 }
3225 else if ( maux->var_types&ref_mask )
3226 {
3227 if ( line_type&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break;
3228 if ( line_type&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break;
3229 if ( line_type&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3230 if ( line_type&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break;
3231 }
3232 }
3233 }
3234 if ( j<buf->end )
3235 {
3236 // found a suitable line for merging
3237 buf->cur = j;
3238 }
3239 }
3240
3241 // debug_maux(args);
3242
3243 // Mark lines staged for merging as finished so that they are ignored next time
3244 for (i=0; i<files->nreaders; i++)
3245 {
3246 buffer_t *buf = &maux->buf[i];
3247 if ( buf->cur == -1 ) continue;
3248
3249 buf->rec[buf->cur].skip = SKIP_DONE;
3250 nout++;
3251 }
3252
3253 assert( nout );
3254 }
3255
3256 void merge_line(args_t *args)
3257 {
3258 bcf1_t *out = args->out_line;
3259 merge_chrom2qual(args, out);
3260 if ( args->regs && !regidx_overlap(args->regs,args->maux->chr,out->pos,out->pos+out->rlen-1,NULL) ) return;
3261 merge_filter(args, out);
3262 merge_info(args, out);
3263 if ( args->do_gvcf )
3264 bcf_update_info_int32(args->out_hdr, out, "END", NULL, 0);
3265 merge_format(args, out);
3266 int iunseen;
3267 if ( args->trim_star_allele && (out->n_allele > 2 || args->trim_star_allele > 1) && (iunseen=get_unseen_allele(out)) && iunseen>0 )
3268 {
3269 // the unobserved star allele should be trimmed, either it is variant site or trimming of all sites was requested
3270 kbitset_t *rm_set = kbs_init(out->n_allele);
3271 kbs_insert(rm_set, iunseen);
3272 if ( bcf_remove_allele_set(args->out_hdr,out,rm_set) )
3273 error("[%s] Error: failed to trim the unobserved allele at %s:%"PRIhts_pos"\n",__func__,bcf_seqname(args->out_hdr,out),out->pos+1);
3274 kbs_destroy(rm_set);
3275 }
3276 if ( bcf_write1(args->out_fh, args->out_hdr, out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
3277 bcf_clear1(out);
3278 }
3279
3280 void bcf_hdr_append_version(bcf_hdr_t *hdr, int argc, char **argv, const char *cmd)
3281 {
3282 kstring_t str = {0,0,0};
3283 int e = 0;
3284 if (ksprintf(&str,"##%sVersion=%s+htslib-%s\n", cmd, bcftools_version(), hts_version()) < 0)
3285 goto fail;
3286 if (bcf_hdr_append(hdr,str.s) < 0)
3287 goto fail;
3288
3289 str.l = 0;
3290 e |= ksprintf(&str,"##%sCommand=%s", cmd, argv[0]) < 0;
3291 int i;
3292 for (i=1; i<argc; i++)
3293 {
3294 if ( strchr(argv[i],' ') )
3295 e |= ksprintf(&str, " '%s'", argv[i]) < 0;
3296 else
3297 e |= ksprintf(&str, " %s", argv[i]) < 0;
3298 }
3299 e |= kputs("; Date=", &str) < 0;
3300 time_t tm; time(&tm);
3301 e |= kputs(ctime(&tm), &str) < 0;
3302 e |= kputc('\n', &str) < 0;
3303 if (e)
3304 goto fail;
3305 if (bcf_hdr_append(hdr,str.s) < 0)
3306 goto fail;
3307 free(ks_release(&str));
3308
3309 if (bcf_hdr_sync(hdr) < 0)
3310 goto fail;
3311 return;
3312
3313 fail:
3314 free(str.s);
3315 error_errno("[%s] Failed to add program information to header", __func__);
3316 }
3317
3318 void hdr_add_localized_tags(args_t *args, bcf_hdr_t *hdr)
3319 {
3320 char **str = NULL;
3321 int i,j, nstr = 0, mstr = 0;
3322 for (i=0; i<hdr->nhrec; i++)
3323 {
3324 if ( hdr->hrec[i]->type!=BCF_HL_FMT ) continue;
3325 j = bcf_hrec_find_key(hdr->hrec[i],"ID");
3326 if ( j<0 ) continue;
3327 char *key = hdr->hrec[i]->vals[j];
3328 int id = bcf_hdr_id2int(hdr, BCF_DT_ID, key);
3329 assert( id>=0 );
3330 int localize = 0;
3331 if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_G ) localize = 1;
3332 if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_A ) localize = 1;
3333 if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_R ) localize = 1;
3334 if ( !localize ) continue;
3335 args->tmps.l = 0;
3336
3337 uint32_t e = 0, nout = 0;
3338 e |= ksprintf(&args->tmps, "##%s=<", hdr->hrec[i]->key) < 0;
3339 for (j=0; j<hdr->hrec[i]->nkeys; j++)
3340 {
3341 if ( !strcmp("IDX",hdr->hrec[i]->keys[j]) ) continue;
3342 if ( nout ) e |= kputc(',',&args->tmps) < 0;
3343 if ( !strcmp("ID",hdr->hrec[i]->keys[j]) )
3344 e |= ksprintf(&args->tmps,"%s=L%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]) < 0;
3345 else if ( !strcmp("Number",hdr->hrec[i]->keys[j]) )
3346 e |= ksprintf(&args->tmps,"Number=.") < 0;
3347 else if ( !strcmp("Description",hdr->hrec[i]->keys[j]) && hdr->hrec[i]->vals[j][0]=='"' )
3348 e |= ksprintf(&args->tmps,"Description=\"Localized field: %s", hdr->hrec[i]->vals[j]+1) < 0;
3349 else
3350 e |= ksprintf(&args->tmps,"%s=%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]) < 0;
3351 nout++;
3352 }
3353 e |= ksprintf(&args->tmps,">\n") < 0;
3354 if ( e ) error("Failed to format the header line for %s\n", key);
3355 nstr++;
3356 hts_expand(char*,nstr,mstr,str);
3357 str[nstr-1] = strdup(args->tmps.s);
3358 }
3359 if ( !nstr ) return;
3360 bcf_hdr_append(hdr,"##FORMAT=<ID=LAA,Number=.,Type=Integer,Description=\"Localized alleles: subset of alternate alleles relevant for each sample\">");
3361 for (i=0; i<nstr; i++)
3362 {
3363 bcf_hdr_append(hdr, str[i]);
3364 free(str[i]);
3365 }
3366 free(str);
3367 }
3368 void merge_vcf(args_t *args)
3369 {
3370 char wmode[8];
3371 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
3372 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
3373 if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
3374 if ( args->n_threads ) hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->files->p); //hts_set_threads(args->out_fh, args->n_threads);
3375 args->out_hdr = bcf_hdr_init("w");
3376
3377 if ( args->header_fname )
3378 {
3379 if ( bcf_hdr_set(args->out_hdr,args->header_fname) ) error("Could not read/parse the header: %s\n", args->header_fname);
3380 }
3381 else
3382 {
3383 int i;
3384 for (i=0; i<args->files->nreaders; i++)
3385 {
3386 char buf[24]; snprintf(buf,sizeof buf,"%d",i+1);
3387 merge_headers(args->out_hdr, args->files->readers[i].header,buf,args->force_samples);
3388 }
3389 if ( args->local_alleles ) hdr_add_localized_tags(args, args->out_hdr);
3390 if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_merge");
3391 if (bcf_hdr_sync(args->out_hdr) < 0)
3392 error_errno("[%s] Failed to update header", __func__);
3393 }
3394 info_rules_init(args);
3395 missing_rules_init(args);
3396
3397 bcf_hdr_set_version(args->out_hdr, bcf_hdr_get_version(args->files->readers[0].header));
3398 if ( bcf_hdr_write(args->out_fh, args->out_hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
3399 if ( args->header_only )
3400 {
3401 bcf_hdr_destroy(args->out_hdr);
3402 if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
3403 return;
3404 }
3405 else if ( init_index2(args->out_fh,args->out_hdr,args->output_fname,
3406 &args->index_fn, args->write_index)<0 )
3407 error("Error: failed to initialise index for %s\n",args->output_fname);
3408
3409 args->vcmp = vcmp_init();
3410 args->maux = maux_init(args);
3411 args->out_line = bcf_init1();
3412 args->tmph = kh_init(strdict);
3413
3414 int *rid_tab = calloc(args->maux->n, sizeof(*rid_tab));
3415 if (!rid_tab)
3416 error("[%s:%d] Could not allocate %zu bytes\n", __FILE__, __LINE__, args->maux->n*sizeof(*rid_tab));
3417
3418 while ( bcf_sr_next_line(args->files) )
3419 {
3420 // output cached gVCF blocks which end before the new record
3421 if ( args->do_gvcf )
3422 gvcf_flush(args,0);
3423
3424 maux_reset(args->maux, rid_tab);
3425
3426 // determine which of the new records are gvcf blocks
3427 if ( args->do_gvcf )
3428 gvcf_stage(args, args->maux->pos);
3429
3430 while ( can_merge(args) )
3431 {
3432 stage_line(args);
3433 merge_line(args);
3434 }
3435 clean_buffer(args);
3436 // debug_state(args);
3437 }
3438 free(rid_tab);
3439 if ( args->do_gvcf )
3440 gvcf_flush(args,1);
3441
3442 info_rules_destroy(args);
3443 missing_rules_destroy(args);
3444 maux_destroy(args->maux);
3445 bcf_hdr_destroy(args->out_hdr);
3446 if ( args->write_index )
3447 {
3448 if ( bcf_idx_save(args->out_fh)<0 )
3449 {
3450 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
3451 error("Error: cannot write to index %s\n", args->index_fn);
3452 }
3453 free(args->index_fn);
3454 }
3455 if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname?args->output_fname:"bcftools_stdout");
3456 bcf_destroy1(args->out_line);
3457 kh_destroy(strdict, args->tmph);
3458 if ( args->tmps.m ) free(args->tmps.s);
3459 if ( args->vcmp ) vcmp_destroy(args->vcmp);
3460 }
3461
3462 static void usage(void)
3463 {
3464 fprintf(bcftools_stderr, "\n");
3465 fprintf(bcftools_stderr, "About: Merge multiple VCF/BCF files from non-overlapping sample sets to create one multi-sample file.\n");
3466 fprintf(bcftools_stderr, " Note that only records from different files can be merged, never from the same file. For\n");
3467 fprintf(bcftools_stderr, " \"vertical\" merge take a look at \"bcftools norm\" instead.\n");
3468 fprintf(bcftools_stderr, "Usage: bcftools merge [options] <A.vcf.gz> <B.vcf.gz> [...]\n");
3469 fprintf(bcftools_stderr, "\n");
3470 fprintf(bcftools_stderr, "Options:\n");
3471 fprintf(bcftools_stderr, " --force-no-index Merge unindexed files, synonymous to --no-index\n");
3472 fprintf(bcftools_stderr, " --force-samples Resolve duplicate sample names\n");
3473 fprintf(bcftools_stderr, " --force-single Run even if there is only one file on input\n");
3474 fprintf(bcftools_stderr, " --print-header Print only the merged header and exit\n");
3475 fprintf(bcftools_stderr, " --use-header FILE Use the provided header\n");
3476 fprintf(bcftools_stderr, " -0 --missing-to-ref Assume genotypes at missing sites are 0/0\n");
3477 fprintf(bcftools_stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n");
3478 fprintf(bcftools_stderr, " -F, --filter-logic x|+ Remove filters if some input is PASS (\"x\"), or apply all filters (\"+\") [+]\n");
3479 fprintf(bcftools_stderr, " -g, --gvcf -|REF.FA Merge gVCF blocks, INFO/END tag is expected. Implies -i QS:sum,MinDP:min,MIN_DP:min,I16:sum,IDV:max,IMF:max -M PL:max,AD:0\n");
3480 fprintf(bcftools_stderr, " -i, --info-rules TAG:METHOD,.. Rules for merging INFO fields (method is one of sum,avg,min,max,join) or \"-\" to turn off the default [DP:sum,DP4:sum]\n");
3481 fprintf(bcftools_stderr, " -l, --file-list FILE Read file names from the file\n");
3482 fprintf(bcftools_stderr, " -L, --local-alleles INT If more than INT alt alleles are encountered, drop FMT/PL and output LAA+LPL instead; 0=unlimited [0]\n");
3483 fprintf(bcftools_stderr, " -m, --merge STRING[*|**] Allow multiallelic records for snps,indels,both,snp-ins-del,all,none,id,*,**; see man page for details [both]\n");
3484 fprintf(bcftools_stderr, " -M, --missing-rules TAG:METHOD Rules for replacing missing values in numeric vectors (.,0,max) when unknown allele <*> is not present [.]\n");
3485 fprintf(bcftools_stderr, " --no-index Merge unindexed files, the same chromosomal order is required and -r/-R are not allowed\n");
3486 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
3487 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
3488 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");
3489 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
3490 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
3491 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
3492 fprintf(bcftools_stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
3493 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
3494 fprintf(bcftools_stderr, "\n");
3495 bcftools_exit(1);
3496 }
3497
3498 int main_vcfmerge(int argc, char *argv[])
3499 {
3500 int c;
3501 args_t *args = (args_t*) calloc(1,sizeof(args_t));
3502 args->files = bcf_sr_init();
3503 args->argc = argc; args->argv = argv;
3504 args->output_fname = "-";
3505 args->output_type = FT_VCF;
3506 args->n_threads = 0;
3507 args->record_cmd_line = 1;
3508 args->collapse = COLLAPSE_BOTH;
3509 args->clevel = -1;
3510 int regions_is_file = 0;
3511 int regions_overlap = 1;
3512
3513 static struct option loptions[] =
3514 {
3515 {"help",no_argument,NULL,'h'},
3516 {"merge",required_argument,NULL,'m'},
3517 {"local-alleles",required_argument,NULL,'L'},
3518 {"gvcf",required_argument,NULL,'g'},
3519 {"file-list",required_argument,NULL,'l'},
3520 {"missing-to-ref",no_argument,NULL,'0'},
3521 {"apply-filters",required_argument,NULL,'f'},
3522 {"use-header",required_argument,NULL,1},
3523 {"print-header",no_argument,NULL,2},
3524 {"force-samples",no_argument,NULL,3},
3525 {"output",required_argument,NULL,'o'},
3526 {"output-type",required_argument,NULL,'O'},
3527 {"threads",required_argument,NULL,9},
3528 {"regions",required_argument,NULL,'r'},
3529 {"regions-file",required_argument,NULL,'R'},
3530 {"regions-overlap",required_argument,NULL,4},
3531 {"info-rules",required_argument,NULL,'i'},
3532 {"missing-rules",required_argument,NULL,'M'},
3533 {"no-version",no_argument,NULL,8},
3534 {"no-index",no_argument,NULL,10},
3535 {"force-no-index",no_argument,NULL,10},
3536 {"force-single",no_argument,NULL,12},
3537 {"filter-logic",required_argument,NULL,'F'},
3538 {"write-index",optional_argument,NULL,'W'},
3539 {NULL,0,NULL,0}
3540 };
3541 char *tmp;
3542 while ((c = getopt_long(argc, argv, "hm:f:r:R:o:O:i:M:l:g:F:0L:W::",loptions,NULL)) >= 0) {
3543 switch (c) {
3544 case 'L':
3545 args->local_alleles = strtol(optarg,&tmp,10);
3546 if ( *tmp ) error("Could not parse argument: --local-alleles %s\n", optarg);
3547 if ( args->local_alleles < 1 )
3548 error("Error: \"--local-alleles %s\" makes no sense, expected value bigger or equal than 1\n", optarg);
3549 break;
3550 case 'F':
3551 if ( !strcmp(optarg,"+") ) args->filter_logic = FLT_LOGIC_ADD;
3552 else if ( !strcmp(optarg,"x") ) args->filter_logic = FLT_LOGIC_REMOVE;
3553 else error("Filter logic not recognised: %s\n", optarg);
3554 break;
3555 case '0': args->missing_to_ref = 1; break;
3556 case 'g':
3557 args->do_gvcf = 1;
3558 if ( strcmp("-",optarg) )
3559 {
3560 args->gvcf_fai = fai_load(optarg);
3561 if ( !args->gvcf_fai ) error("Failed to load the fai index: %s\n", optarg);
3562 }
3563 break;
3564 case 'l': args->file_list = optarg; break;
3565 case 'i': args->info_rules = optarg; break;
3566 case 'M': args->missing_rules_str = optarg; break;
3567 case 'o': args->output_fname = optarg; break;
3568 case 'O':
3569 switch (optarg[0]) {
3570 case 'b': args->output_type = FT_BCF_GZ; break;
3571 case 'u': args->output_type = FT_BCF; break;
3572 case 'z': args->output_type = FT_VCF_GZ; break;
3573 case 'v': args->output_type = FT_VCF; break;
3574 default:
3575 {
3576 args->clevel = strtol(optarg,&tmp,10);
3577 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
3578 }
3579 }
3580 if ( optarg[1] )
3581 {
3582 args->clevel = strtol(optarg+1,&tmp,10);
3583 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
3584 }
3585 break;
3586 case 'm':
3587 {
3588 int len = strlen(optarg);
3589 if ( optarg[len-1]=='*' ) { args->trim_star_allele++; len--; }
3590 if ( optarg[len-1]=='*' ) { args->trim_star_allele++; len--; }
3591 if ( optarg[len-1]==',' ) len--;
3592 args->collapse = COLLAPSE_NONE;
3593 if ( !strncmp(optarg,"snp-ins-del",len) ) args->collapse = COLLAPSE_SNP_INS_DEL|COLLAPSE_SNPS;
3594 else if ( !strncmp(optarg,"snps",len) ) args->collapse |= COLLAPSE_SNPS;
3595 else if ( !strncmp(optarg,"indels",len) ) args->collapse |= COLLAPSE_INDELS;
3596 else if ( !strncmp(optarg,"id",len) ) { args->collapse = COLLAPSE_NONE; args->merge_by_id = 1; }
3597 else if ( !strncmp(optarg,"any",len) ) args->collapse |= COLLAPSE_ANY;
3598 else if ( !strncmp(optarg,"all",len) ) args->collapse |= COLLAPSE_ANY;
3599 else if ( !strncmp(optarg,"both",len) ) args->collapse |= COLLAPSE_BOTH;
3600 else if ( !strncmp(optarg,"none",len) ) args->collapse = COLLAPSE_NONE;
3601 else error("The -m type \"%s\" is not recognised.\n", optarg);
3602 break;
3603 }
3604 case 'f': args->files->apply_filters = optarg; break;
3605 case 'r': args->regions_list = optarg; break;
3606 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
3607 case 1 : args->header_fname = optarg; break;
3608 case 2 : args->header_only = 1; break;
3609 case 3 : args->force_samples = 1; break;
3610 case 4 :
3611 regions_overlap = parse_overlap_option(optarg);
3612 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
3613 break;
3614 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
3615 case 8 : args->record_cmd_line = 0; break;
3616 case 10 : args->no_index = 1; break;
3617 case 'W':
3618 if (!(args->write_index = write_index_parse(optarg)))
3619 error("Unsupported index format '%s'\n", optarg);
3620 break;
3621 case 12 : args->force_single = 1; break;
3622 case 'h':
3623 case '?': usage(); break;
3624 default: error("Unknown argument: %s\n", optarg);
3625 }
3626 }
3627 if ( argc==optind && !args->file_list ) usage();
3628 if ( args->no_index )
3629 {
3630 if ( args->regions_list ) error("Error: cannot combine --no-index with -r/-R\n");
3631 bcf_sr_set_opt(args->files,BCF_SR_ALLOW_NO_IDX);
3632 }
3633 else
3634 bcf_sr_set_opt(args->files,BCF_SR_REQUIRE_IDX);
3635 if ( args->regions_list )
3636 {
3637 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
3638 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
3639 error("Failed to read the regions: %s\n", args->regions_list);
3640 if ( regions_is_file )
3641 args->regs = regidx_init(args->regions_list,NULL,NULL,sizeof(char*),NULL);
3642 else
3643 {
3644 args->regs = regidx_init(NULL,regidx_parse_reg,NULL,sizeof(char*),NULL);
3645 if ( regidx_insert_list(args->regs,args->regions_list,',') !=0 ) error("Could not parse the regions: %s\n", args->regions_list);
3646 regidx_insert(args->regs,NULL);
3647 }
3648 if ( !args->regs ) error("Could not parse the regions: %s\n", args->regions_list);
3649 args->regs_itr = regitr_init(args->regs);
3650 }
3651
3652 if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
3653 while (optind<argc)
3654 {
3655 if ( !bcf_sr_add_reader(args->files, argv[optind]) ) error("Failed to open %s: %s\n", argv[optind],bcf_sr_strerror(args->files->errnum));
3656 optind++;
3657 }
3658 if ( args->file_list )
3659 {
3660 int nfiles, i;
3661 char **files = hts_readlines(args->file_list, &nfiles);
3662 if ( !files ) error("Failed to read from %s\n", args->file_list);
3663 for (i=0;i<nfiles; i++)
3664 if ( !bcf_sr_add_reader(args->files, files[i]) ) error("Failed to open %s: %s\n", files[i],bcf_sr_strerror(args->files->errnum));
3665 for (i=0; i<nfiles; i++) free(files[i]);
3666 free(files);
3667 }
3668 if ( !args->files->nreaders ) usage();
3669 if ( args->files->nreaders==1 && !args->force_single ) error("Expected two or more files to merge, got only one. Use --force-single to proceed anyway\n");
3670
3671 merge_vcf(args);
3672 bcf_sr_destroy(args->files);
3673 if ( args->regs ) regidx_destroy(args->regs);
3674 if ( args->regs_itr ) regitr_destroy(args->regs_itr);
3675 if ( args->gvcf_fai ) fai_destroy(args->gvcf_fai);
3676 free(args);
3677 return 0;
3678 }
3679