Debian Codegraph @

bcftools/vcfmerge.c

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