forked from samtools/bcftools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
vcfmerge.c
3304 lines (3072 loc) · 129 KB
/
vcfmerge.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vcfmerge.c -- Merge multiple VCF/BCF files to create one multi-sample file.
Copyright (C) 2012-2021 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <getopt.h>
#include <inttypes.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/vcfutils.h>
#include <htslib/faidx.h>
#include <math.h>
#include <ctype.h>
#include <time.h>
#include "bcftools.h"
#include "regidx.h"
#include "vcmp.h"
#define DBG 0
#include <htslib/khash.h>
KHASH_MAP_INIT_STR(strdict, int)
typedef khash_t(strdict) strdict_t;
#define FLT_LOGIC_ADD 0
#define FLT_LOGIC_REMOVE 1
#define SKIP_DONE 1 // the record was processed
#define SKIP_DIFF 2 // not compatible, merge later
#define IS_VL_G(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_G)
#define IS_VL_A(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_A)
#define IS_VL_R(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_R)
#define SWAP(type_t,a,b) { type_t tmp = (a); (a) = (b); (b) = tmp; }
#define PL2PROB_MAX 1024
// For merging INFO Number=A,G,R tags
typedef struct
{
const char *hdr_tag;
int type, nvals;
int nbuf, mbuf;
uint8_t *buf;
}
AGR_info_t;
// Rules for merging arbitrary INFO tags
typedef struct _info_rule_t
{
char *hdr_tag;
void (*merger)(bcf_hdr_t *hdr, bcf1_t *line, struct _info_rule_t *rule);
int type; // one of BCF_HT_*
int block_size; // number of values in a block
int type_size; // size of the corresponding BCF_HT_* type
int nblocks; // number of blocks in nvals (the number of merged files)
int nvals, mvals; // used and total size of vals array
void *vals; // the info tag values
}
info_rule_t;
typedef struct
{
bcf1_t *line;
int end, active; // end: 0-based INFO/END
}
gvcf_aux_t;
// Auxiliary merge data for selecting the right combination
// of buffered records across multiple readers. maux1_t
// corresponds to one buffered line.
typedef struct
{
int skip;
int *map; // mapping from input alleles to the array of output alleles (set by merge_alleles)
int mmap; // size of map array (only buffer[i].n_allele is actually used)
int als_differ;
}
maux1_t;
typedef struct
{
int rid; // current rid
int beg,end; // valid ranges in reader's buffer [beg,end). Maintained by maux_reset and gvcf_flush.
int cur; // current line or -1 if none
int mrec; // allocated size of buf
maux1_t *rec; // buffer to keep reader's lines
bcf1_t **lines; // source buffer: either gvcf or readers' buffer
}
buffer_t;
typedef struct
{
int n, pos, var_types; // number of readers, current position, currently available variant types
char *chr; // current chromosome
char **als, **out_als; // merged alleles (temp, may contain empty records) and merged alleles ready for output
int nals, mals, nout_als, mout_als; // size of the output array
int *cnt, ncnt; // number of records that refer to the alleles
int *smpl_ploidy, *smpl_nGsize; // ploidy and derived number of values in Number=G tags, updated for each line (todo: cache for missing cases)
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
int nfmt_map; // number of rows in the fmt_map array
int *agr_map, nagr_map, magr_map; // mapping between Number=AGR element indexes
void *tmp_arr;
size_t ntmp_arr;
buffer_t *buf;
AGR_info_t *AGR_info;
int nAGR_info, mAGR_info;
bcf_srs_t *files;
int gvcf_min, // min buffered gvcf END position (NB: gvcf_min is 1-based) or 0 if no active lines are present
gvcf_break; // 0-based position of a next record which breaks a gVCF block
gvcf_aux_t *gvcf; // buffer of gVCF lines, for each reader one line
int nout_smpl;
kstring_t *str;
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
int nlaa, laa_dirty; // number of LAA alleles actually used at this site, and was any L* added?
int32_t *tmpi, *k2k;
double *tmpd, *pl2prob; // mapping from phred-score likelihoods (PL) to probability
int ntmpi, ntmpd, nk2k;
}
maux_t;
typedef struct
{
vcmp_t *vcmp;
maux_t *maux;
regidx_t *regs; // apply regions only after the blocks are expanded
regitr_t *regs_itr;
int header_only, collapse, output_type, force_samples, merge_by_id, do_gvcf, filter_logic, missing_to_ref, no_index;
char *header_fname, *output_fname, *regions_list, *info_rules, *file_list;
faidx_t *gvcf_fai;
info_rule_t *rules;
int nrules;
strdict_t *tmph;
kstring_t tmps;
bcf_srs_t *files;
bcf1_t *out_line;
htsFile *out_fh;
bcf_hdr_t *out_hdr;
char **argv;
int argc, n_threads, record_cmd_line, clevel;
int local_alleles; // the value of -L option
int keep_AC_AN;
}
args_t;
static bcf1_t *maux_get_line(args_t *args, int i)
{
maux_t *ma = args->maux;
int ibuf = ma->buf[i].cur;
if ( ibuf >= 0 ) return ma->buf[i].lines[ibuf];
return NULL;
}
static void info_rules_merge_sum(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
{
if ( !rule->nvals ) return;
int i, j, ndim = rule->block_size;
#define BRANCH(type_t,is_missing) { \
type_t *ptr = (type_t*) rule->vals; \
for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = 0; \
for (i=1; i<rule->nblocks; i++) \
{ \
for (j=0; j<ndim; j++) ptr[j] += ptr[j+i*ndim]; \
} \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break;
case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
}
static void info_rules_merge_avg(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
{
if ( !rule->nvals ) return;
int i, j, ndim = rule->block_size;
#define BRANCH(type_t,is_missing) { \
type_t *ptr = (type_t*) rule->vals; \
for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = 0; \
for (j=0; j<ndim; j++) \
{ \
double sum = 0; \
for (i=0; i<rule->nblocks; i++) sum += ptr[j+i*ndim]; \
ptr[j] = sum / rule->nblocks; \
} \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break;
case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
}
static void info_rules_merge_min(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
{
if ( !rule->nvals ) return;
int i, j, ndim = rule->block_size;
#define BRANCH(type_t,is_missing,set_missing,huge_val) { \
type_t *ptr = (type_t*) rule->vals; \
for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = huge_val; \
for (i=1; i<rule->nblocks; i++) \
{ \
for (j=0; j<ndim; j++) if ( ptr[j] > ptr[j+i*ndim] ) ptr[j] = ptr[j+i*ndim]; \
} \
for (i=0; i<rule->nvals; i++) if ( ptr[i]==huge_val ) set_missing; \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MAX); break;
case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), HUGE_VAL); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
}
static void info_rules_merge_max(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
{
if ( !rule->nvals ) return;
int i, j, ndim = rule->block_size;
#define BRANCH(type_t,is_missing,set_missing,huge_val) { \
type_t *ptr = (type_t*) rule->vals; \
for (i=0; i<rule->nvals; i++) if ( is_missing ) ptr[i] = huge_val; \
for (i=1; i<rule->nblocks; i++) \
{ \
for (j=0; j<ndim; j++) if ( ptr[j] < ptr[j+i*ndim] ) ptr[j] = ptr[j+i*ndim]; \
} \
for (i=0; i<rule->nvals; i++) if ( ptr[i]==huge_val ) set_missing; \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MIN); break;
case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), -HUGE_VAL); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type);
}
static void info_rules_merge_join(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule)
{
if ( !rule->nvals ) return;
if ( rule->type==BCF_HT_STR )
{
((char*)rule->vals)[rule->nvals] = 0;
bcf_update_info_string(hdr,line,rule->hdr_tag,rule->vals);
}
else
{
int isrc, idst = 0;
#define BRANCH(type_t,is_missing,is_vector_end) { \
type_t *ptr = (type_t*) rule->vals; \
for (isrc=0; isrc<rule->nvals; isrc++) \
{ \
if ( is_vector_end ) break; \
if ( is_missing ) continue; \
if ( idst!=isrc ) ptr[idst] = ptr[isrc]; \
idst++; \
} \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int32_t, ptr[isrc]==bcf_int32_missing, ptr[isrc]==bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[isrc]), bcf_float_is_vector_end(ptr[isrc])); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
rule->nvals = idst;
bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,rule->nvals,rule->type);
}
}
static int info_rules_comp_key2(const void *a, const void *b)
{
info_rule_t *rule1 = (info_rule_t*) a;
info_rule_t *rule2 = (info_rule_t*) b;
return strcmp(rule1->hdr_tag, rule2->hdr_tag);
}
static int info_rules_comp_key(const void *a, const void *b)
{
char *key = (char*) a;
info_rule_t *rule = (info_rule_t*) b;
return strcmp(key, rule->hdr_tag);
}
static void info_rules_init(args_t *args)
{
if ( args->info_rules && !strcmp("-",args->info_rules) ) return;
kstring_t str = {0,0,0};
if ( !args->info_rules )
{
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);
if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "DP4")) )
{
if ( str.l ) kputc(',',&str);
kputs("DP4:sum",&str);
}
if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "QS")) )
{
if ( str.l ) kputc(',',&str);
kputs("QS:sum",&str);
}
if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "MinDP")) )
{
if ( str.l ) kputc(',',&str);
kputs("MinDP:min",&str);
}
if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "I16")) )
{
if ( str.l ) kputc(',',&str);
kputs("I16:sum",&str);
}
if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IDV")) )
{
if ( str.l ) kputc(',',&str);
kputs("IDV:max",&str);
}
if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IMF")) )
{
if ( str.l ) kputc(',',&str);
kputs("IMF:max",&str);
}
if ( !bcf_hdr_nsamples(args->out_hdr) )
{
if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AN")) )
{
if ( str.l ) kputc(',',&str);
kputs("AN:sum",&str);
}
if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AC")) )
{
if ( str.l ) kputc(',',&str);
kputs("AC:sum",&str);
}
}
if ( !str.l ) return;
args->info_rules = str.s;
}
args->nrules = 1;
char *ss = strdup(args->info_rules), *tmp = ss;
int n = 0;
while ( *ss )
{
if ( *ss==':' ) { *ss = 0; n++; if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); }
else if ( *ss==',' ) { *ss = 0; args->nrules++; n++; if ( n%2==1 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); }
ss++;
}
if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules);
args->rules = (info_rule_t*) calloc(args->nrules,sizeof(info_rule_t));
n = 0;
ss = tmp;
while ( n < args->nrules )
{
info_rule_t *rule = &args->rules[n];
rule->hdr_tag = strdup(ss);
int id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, rule->hdr_tag);
if ( !bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,id) ) error("The tag is not defined in the header: \"%s\"\n", rule->hdr_tag);
rule->type = bcf_hdr_id2type(args->out_hdr,BCF_HL_INFO,id);
if ( rule->type==BCF_HT_INT ) rule->type_size = sizeof(int32_t);
else if ( rule->type==BCF_HT_REAL ) rule->type_size = sizeof(float);
else if ( rule->type==BCF_HT_STR ) rule->type_size = sizeof(char);
else error("The INFO rule \"%s\" is not supported; the tag \"%s\" type is %d\n", ss,rule->hdr_tag,rule->type);
if ( !strcmp(rule->hdr_tag,"AC") || !strcmp(rule->hdr_tag,"AN") ) args->keep_AC_AN = 1;
ss = strchr(ss, '\0'); ss++;
if ( !*ss ) error("Could not parse INFO rules, missing logic of \"%s\"\n", rule->hdr_tag);
int is_join = 0;
if ( !strcasecmp(ss,"sum") ) rule->merger = info_rules_merge_sum;
else if ( !strcasecmp(ss,"avg") ) rule->merger = info_rules_merge_avg;
else if ( !strcasecmp(ss,"min") ) rule->merger = info_rules_merge_min;
else if ( !strcasecmp(ss,"max") ) rule->merger = info_rules_merge_max;
else if ( !strcasecmp(ss,"join") ) { rule->merger = info_rules_merge_join; is_join = 1; }
else error("The rule logic \"%s\" not recognised\n", ss);
if ( !is_join && rule->type==BCF_HT_STR )
error("Numeric operation \"%s\" requested on non-numeric field: %s\n", ss, rule->hdr_tag);
if ( bcf_hdr_id2number(args->out_hdr,BCF_HL_INFO,id)==0xfffff )
{
int is_agr = (
bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_A ||
bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_G ||
bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_R
) ? 1 : 0;
if ( is_join && bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)!=BCF_VL_VAR )
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->out_hdr, BCF_HL_INFO, "ID", rule->hdr_tag, NULL);
hrec = bcf_hrec_dup(hrec);
int i = bcf_hrec_find_key(hrec, "Number");
if ( i<0 ) error("Uh, could not find the entry Number in the header record of %s\n",rule->hdr_tag);
free(hrec->vals[i]);
hrec->vals[i] = strdup(".");
bcf_hdr_remove(args->out_hdr,BCF_HL_INFO, rule->hdr_tag);
bcf_hdr_add_hrec(args->out_hdr, hrec);
}
if ( !is_join && !is_agr )
error("Only fixed-length vectors are supported with -i %s:%s\n", ss, rule->hdr_tag);
}
ss = strchr(ss, '\0'); ss++;
n++;
}
free(str.s);
free(tmp);
qsort(args->rules, args->nrules, sizeof(*args->rules), info_rules_comp_key2);
}
static void info_rules_destroy(args_t *args)
{
int i;
for (i=0; i<args->nrules; i++)
{
info_rule_t *rule = &args->rules[i];
free(rule->hdr_tag);
free(rule->vals);
}
free(args->rules);
}
static void info_rules_reset(args_t *args)
{
int i;
for (i=0; i<args->nrules; i++)
args->rules[i].nblocks = args->rules[i].nvals = args->rules[i].block_size = 0;
}
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)
{
int msize = args->maux->ntmp_arr / rule->type_size;
int ret = bcf_get_info_values(hdr, line, rule->hdr_tag, &args->maux->tmp_arr, &msize, rule->type);
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);
args->maux->ntmp_arr = msize * rule->type_size;
rule->nblocks++;
if ( rule->type==BCF_HT_STR )
{
int need_comma = rule->nblocks==1 ? 0 : 1;
hts_expand(char,rule->nvals+ret+need_comma+1,rule->mvals,rule->vals); // 1 for null-termination
char *tmp = (char*) rule->vals + rule->nvals;
if ( rule->nvals>0 ) { *tmp = ','; tmp++; }
strncpy(tmp,(char*)args->maux->tmp_arr,ret);
rule->nvals += ret + need_comma;
return 1;
}
int i, j;
if ( var_len==BCF_VL_A )
{
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);
args->maux->nagr_map = ret;
hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
// create mapping from source file ALT indexes to dst file indexes
for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i+1] - 1;
rule->block_size = args->maux->nout_als - 1;
}
else if ( var_len==BCF_VL_R )
{
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);
args->maux->nagr_map = ret;
hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i];
rule->block_size = args->maux->nout_als;
}
else if ( var_len==BCF_VL_G )
{
args->maux->nagr_map = bcf_alleles2gt(line->n_allele-1,line->n_allele-1)+1;
assert( ret==line->n_allele || ret==args->maux->nagr_map );
if ( ret==line->n_allele ) // haploid
{
args->maux->nagr_map = line->n_allele;
hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
for (i=0; i<ret; i++) args->maux->agr_map[i] = als->map[i];
rule->block_size = args->maux->nout_als;
}
else
{
hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map);
int k_src = 0;
for (i=0; i<line->n_allele; i++)
{
for (j=0; j<=i; j++)
{
args->maux->agr_map[k_src] = bcf_alleles2gt(als->map[i],als->map[j]);
k_src++;
}
}
rule->block_size = bcf_alleles2gt(args->maux->nout_als-1,args->maux->nout_als-1)+1;
}
}
else
{
if ( rule->nblocks>1 && ret!=rule->block_size )
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);
rule->block_size = ret;
args->maux->nagr_map = 0;
}
#define BRANCH(src_type_t,dst_type_t,set_missing) { \
src_type_t *src = (src_type_t *) args->maux->tmp_arr; \
hts_expand0(dst_type_t,(rule->nvals+rule->block_size),rule->mvals,rule->vals); \
dst_type_t *dst = (dst_type_t *) rule->vals + rule->nvals; \
rule->nvals += rule->block_size; \
if ( !args->maux->nagr_map ) \
{ \
for (i=0; i<ret; i++) dst[i] = src[i]; \
} \
else \
{ \
for (i=0; i<rule->block_size; i++) set_missing; \
for (i=0; i<ret; i++) dst[args->maux->agr_map[i]] = src[i]; \
} \
}
switch (rule->type) {
case BCF_HT_INT: BRANCH(int, int32_t, dst[i] = bcf_int32_missing); break;
case BCF_HT_REAL: BRANCH(float, float, bcf_float_set_missing(dst[i])); break;
default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type);
}
#undef BRANCH
return 1;
}
int bcf_hdr_sync(bcf_hdr_t *h);
void merge_headers(bcf_hdr_t *hw, const bcf_hdr_t *hr, const char *clash_prefix, int force_samples)
{
// header lines
hw = bcf_hdr_merge(hw, hr);
// samples
int i;
for (i=0; i<bcf_hdr_nsamples(hr); i++)
{
char *rmme = NULL, *name = hr->samples[i];
while ( bcf_hdr_id2int(hw, BCF_DT_SAMPLE, name)!=-1 )
{
// there is a sample with the same name
if ( !force_samples ) error("Error: Duplicate sample names (%s), use --force-samples to proceed anyway.\n", name);
// Resolve conflicting samples names. For example, replace:
// A + A with A,2:A
// A,2:A + A with A,2:A,2:2:A
int len = strlen(name) + strlen(clash_prefix) + 1;
char *tmp = (char*) malloc(sizeof(char)*(len+1));
sprintf(tmp,"%s:%s",clash_prefix,name);
free(rmme);
rmme = name = tmp;
}
bcf_hdr_add_sample(hw,name);
free(rmme);
}
}
void debug_als(char **als, int nals)
{
int k; for (k=0; k<nals; k++) fprintf(stderr,"%s ", als[k]);
fprintf(stderr,"\n");
}
/**
* normalize_alleles() - create smallest possible representation of the alleles
* @als: alleles to be merged, first is REF (rw)
* @nals: number of $a alleles
*
* Best explained on an example:
* In: REF=GTTT ALT=GTT
* Out: REF=GT ALT=G
*
* Note: the als array will be modified
*/
void normalize_alleles(char **als, int nals)
{
if ( !als[0][1] ) return; // ref is 1base long, we're done
int j, i = 1, done = 0;
int *lens = (int*) malloc(sizeof(int)*nals);
for (j=0; j<nals; j++) lens[j] = strlen(als[j]);
while ( i<lens[0] )
{
for (j=1; j<nals; j++)
{
if ( i>=lens[j] ) done = 1;
if ( als[j][lens[j]-i] != als[0][lens[0]-i] ) { done = 1; break; }
}
if ( done ) break;
i++;
}
if ( i>1 )
{
i--;
als[0][lens[0]-i] = 0;
for (j=1; j<nals; j++) als[j][lens[j]-i] = 0;
}
free(lens);
}
/**
* merge_alleles() - merge two REF,ALT records, $a and $b into $b.
* @a: alleles to be merged, first is REF
* @na: number of $a alleles
* @map: map from the original $a indexes to new $b indexes (0-based)
* @b: alleles to be merged, the array will be expanded as required
* @nb: number of $b alleles
* @mb: size of $b
*
* Returns NULL on error or $b expanded to incorporate $a alleles and sets
* $map. Best explained on an example:
* In: REF ALT
* a: ACG, AC,A (1bp and 2bp deletion)
* b: ACGT, A (3bp deletion)
* Out:
* b: ACGT, A,ACT,AT (3bp, 1bp and 2bp deletion)
* map: 0,2,3
* Here the mapping from the original $a alleles to the new $b alleles is 0->0,
* 1->2, and 2->3.
*/
char **merge_alleles(char **a, int na, int *map, char **b, int *nb, int *mb)
{
// reference allele never changes
map[0] = 0;
int i,j;
int rla = !a[0][1] ? 1 : strlen(a[0]);
int rlb = !b[0][1] ? 1 : strlen(b[0]);
// the most common case: same SNPs
if ( na==2 && *nb==2 && rla==1 && rlb==1 && a[1][0]==b[1][0] && !a[1][1] && !b[1][1] )
{
map[1] = 1;
return b;
}
// Sanity check: reference prefixes must be identical
if ( strncmp(a[0],b[0],rla<rlb?rla:rlb) )
{
if ( strncasecmp(a[0],b[0],rla<rlb?rla:rlb) )
{
fprintf(stderr, "The REF prefixes differ: %s vs %s (%d,%d)\n", a[0],b[0],rla,rlb);
return NULL;
}
// Different case, change to uppercase
for (i=0; i<na; i++)
{
int len = strlen(a[i]);
for (j=0; j<len; j++) a[i][j] = toupper(a[i][j]);
}
for (i=0; i<*nb; i++)
{
int len = strlen(b[i]);
for (j=0; j<len; j++) b[i][j] = toupper(b[i][j]);
}
}
int n = *nb + na;
hts_expand0(char*,n,*mb,b);
// $b alleles need expanding
if ( rla>rlb )
{
for (i=0; i<*nb; i++)
{
if ( b[i][0]=='<' ) continue; // symbolic allele, do not modify
if ( b[i][0]=='*' ) continue; // overlapping deletion (*), do not modify
int l = strlen(b[i]);
b[i] = (char*) realloc(b[i],l+rla-rlb+1);
memcpy(b[i]+l,a[0]+rlb,rla-rlb+1);
}
}
// now check if the $a alleles are present and if not add them
for (i=1; i<na; i++)
{
int const_ai = 1;
char *ai;
if ( rlb>rla && a[i][0]!='<' && a[i][0]!='*' ) // $a alleles need expanding and not a symbolic allele or *
{
int l = strlen(a[i]);
ai = (char*) malloc(l+rlb-rla+1);
memcpy(ai,a[i],l);
memcpy(ai+l,b[0]+rla,rlb-rla+1);
const_ai = 0;
}
else
ai = a[i];
for (j=1; j<*nb; j++)
if ( !strcasecmp(ai,b[j]) ) break;
if ( j<*nb ) // $b already has the same allele
{
map[i] = j;
if ( !const_ai ) free(ai);
continue;
}
// new allele
map[i] = *nb;
b[*nb] = const_ai ? strdup(ai) : ai;
(*nb)++;
}
return b;
}
maux_t *maux_init(args_t *args)
{
bcf_srs_t *files = args->files;
maux_t *ma = (maux_t*) calloc(1,sizeof(maux_t));
ma->n = files->nreaders;
ma->files = files;
int i, n_smpl = 0;
for (i=0; i<ma->n; i++)
n_smpl += bcf_hdr_nsamples(files->readers[i].header);
ma->nout_smpl = n_smpl;
assert( n_smpl==bcf_hdr_nsamples(args->out_hdr) );
if ( args->do_gvcf )
{
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
for (i=0; i<ma->n; i++)
ma->gvcf[i].line = bcf_init1();
}
ma->smpl_ploidy = (int*) calloc(n_smpl,sizeof(int));
ma->smpl_nGsize = (int*) malloc(n_smpl*sizeof(int));
ma->buf = (buffer_t*) calloc(ma->n,sizeof(buffer_t));
for (i=0; i<ma->n; i++)
ma->buf[i].rid = -1;
ma->str = (kstring_t*) calloc(n_smpl,sizeof(kstring_t));
if ( args->local_alleles )
{
ma->laa = (int32_t*)malloc(sizeof(*ma->laa)*ma->nout_smpl*(1+args->local_alleles));
ma->pl2prob = (double*)malloc(PL2PROB_MAX*sizeof(*ma->pl2prob));
for (i=0; i<PL2PROB_MAX; i++)
ma->pl2prob[i] = pow(10,-0.1*i);
}
return ma;
}
void maux_destroy(maux_t *ma)
{
int i,j;
for (i=0; i<ma->nout_smpl; i++) free(ma->str[i].s);
free(ma->str);
for (i=0; i<ma->mals; i++)
{
free(ma->als[i]);
ma->als[i] = NULL;
}
for (i=0; i<ma->n; i++) // for each reader
{
for (j=0; j<ma->buf[i].mrec; j++) // for each buffered line
free(ma->buf[i].rec[j].map);
free(ma->buf[i].rec);
}
free(ma->buf);
if ( ma->gvcf )
{
for (i=0; i<ma->n; i++) bcf_destroy(ma->gvcf[i].line);
free(ma->gvcf);
}
for (i=0; i<ma->mAGR_info; i++)
free(ma->AGR_info[i].buf);
free(ma->agr_map);
free(ma->AGR_info);
if (ma->ntmp_arr) free(ma->tmp_arr);
if (ma->nfmt_map) free(ma->fmt_map);
// ma->inf freed in bcf_destroy1
for (i=0; i<ma->mals; i++) free(ma->als[i]);
if (ma->mout_als) free(ma->out_als);
free(ma->als);
free(ma->cnt);
free(ma->smpl_ploidy);
free(ma->smpl_nGsize);
free(ma->chr);
free(ma->laa);
free(ma->tmpi);
free(ma->k2k);
free(ma->tmpd);
free(ma->pl2prob);
free(ma);
}
void maux_expand1(buffer_t *buf, int size)
{
if ( buf->mrec < size )
{
hts_expand0(maux1_t,size,buf->mrec,buf->rec);
buf->mrec = size;
}
}
void maux_reset(maux_t *ma, int *rid_tab)
{
int i,j;
for (i=0; i<ma->n; i++) maux_expand1(&ma->buf[i],ma->files->readers[i].nbuffer+1);
for (i=0; i<ma->ncnt; i++) ma->cnt[i] = 0;
for (i=0; i<ma->mals; i++)
{
free(ma->als[i]);
ma->als[i] = NULL;
}
const char *chr = NULL;
ma->nals = 0;
ma->pos = -1;
for (i=0; i<ma->n; i++)
{
if ( !bcf_sr_has_line(ma->files,i) ) continue;
bcf1_t *line = bcf_sr_get_line(ma->files,i);
bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i);
chr = bcf_seqname(hdr,line);
ma->pos = line->pos;
break;
}
int new_chr = 0;
if ( chr && (!ma->chr || strcmp(ma->chr,chr)) )
{
free(ma->chr);
ma->chr = strdup(chr);
new_chr = 1;
}
for (i=0; i<ma->n; i++)
{
bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i);
if (new_chr)
rid_tab[i] = bcf_hdr_name2id(hdr,chr);
ma->buf[i].rid = rid_tab[i];
ma->buf[i].beg = bcf_sr_has_line(ma->files,i) ? 0 : 1;
for (j=ma->buf[i].beg; j<=ma->files->readers[i].nbuffer; j++)
{
ma->buf[i].rec[j].skip = 0;
bcf1_t *line = ma->files->readers[i].buffer[j];
if ( line->rid!=ma->buf[i].rid || line->pos!=ma->pos ) break;
}
ma->buf[i].end = j;
ma->buf[i].cur = -1;
if ( ma->buf[i].beg < ma->buf[i].end )
{
ma->buf[i].lines = ma->files->readers[i].buffer;
if ( ma->gvcf ) ma->gvcf[i].active = 0; // gvcf block cannot overlap with the next record
}
if ( new_chr && ma->gvcf ) ma->gvcf[i].active = 0; // make sure to close active gvcf block on new chr
}
}
void maux_debug(maux_t *ma, int ir, int ib)
{
printf("[%d,%d]\t", ir,ib);
int i;
for (i=0; i<ma->nals; i++)
{
printf(" %s [%d]", ma->als[i], ma->cnt[i]);
}
printf("\n");
}
void merge_chrom2qual(args_t *args, bcf1_t *out)
{
bcf_srs_t *files = args->files;
bcf_hdr_t *out_hdr = args->out_hdr;
int i, ret;
khiter_t kitr;
strdict_t *tmph = args->tmph;
kh_clear(strdict, tmph);
kstring_t *tmps = &args->tmps;
tmps->l = 0;
maux_t *ma = args->maux;
int *al_idxs = (int*) calloc(ma->nals,sizeof(int));
bcf_float_set_missing(out->qual);
// CHROM, POS, ID, QUAL
out->pos = -1;
for (i=0; i<files->nreaders; i++)
{
bcf1_t *line = maux_get_line(args, i);
if ( !line ) continue;
bcf_unpack(line, BCF_UN_ALL);
bcf_sr_t *reader = &files->readers[i];
bcf_hdr_t *hdr = reader->header;
// not all maux alleles are always used, mark the ones we'll need
int j;
for (j=1; j<line->n_allele; j++)
{
int irec = ma->buf[i].cur;
al_idxs[ ma->buf[i].rec[irec].map[j] ] = 1;
}
// position
if ( out->pos==-1 )
{
const char *chr = hdr->id[BCF_DT_CTG][line->rid].key;
out->rid = bcf_hdr_name2id(out_hdr, chr);
if ( strcmp(chr,out_hdr->id[BCF_DT_CTG][out->rid].key) ) error("Uh\n");
out->pos = line->pos;
}
// ID
if ( line->d.id[0]!='.' || line->d.id[1] )
{
kitr = kh_get(strdict, tmph, line->d.id);
if ( kitr == kh_end(tmph) )
{
if ( tmps->l ) kputc(';', tmps);
kputs(line->d.id, tmps);
kh_put(strdict, tmph, line->d.id, &ret);
}
}
// set QUAL to the max qual value. Not exactly correct, but good enough for now
if ( !bcf_float_is_missing(line->qual) )
{
if ( bcf_float_is_missing(out->qual) || out->qual < line->qual ) out->qual = line->qual;
}
}
// set ID
if ( !tmps->l ) kputs(".", tmps);
bcf_update_id(out_hdr, out, tmps->s);
// set alleles
ma->nout_als = 0;
for (i=1; i<ma->nals; i++)
{
if ( !al_idxs[i] ) continue;
ma->nout_als++;
// Adjust the indexes, the allele map could be created for multiple collapsed records,
// some of which might be unused for this output line
int ir, j;
for (ir=0; ir<files->nreaders; ir++)
{
bcf1_t *line = maux_get_line(args,ir);
if ( !line ) continue;
for (j=1; j<line->n_allele; j++)
{
int irec = ma->buf[ir].cur;
if ( ma->buf[ir].rec[irec].map[j]==i ) ma->buf[ir].rec[irec].map[j] = ma->nout_als;
}
}
}
// Expand the arrays and realloc the alleles string. Note that all alleles are in a single allocated block.
ma->nout_als++;
hts_expand0(char*, ma->nout_als, ma->mout_als, ma->out_als);
int k = 0;
for (i=0; i<ma->nals; i++)
if ( i==0 || al_idxs[i] ) ma->out_als[k++] = strdup(ma->als[i]);
assert( k==ma->nout_als );
normalize_alleles(ma->out_als, ma->nout_als);
bcf_update_alleles(out_hdr, out, (const char**) ma->out_als, ma->nout_als);
free(al_idxs);
for (i=0; i<ma->nout_als; i++) free(ma->out_als[i]);
}
void merge_filter(args_t *args, bcf1_t *out)
{
bcf_srs_t *files = args->files;
bcf_hdr_t *out_hdr = args->out_hdr;
int i, ret;
if ( args->filter_logic == FLT_LOGIC_REMOVE )
{
for (i=0; i<files->nreaders; i++)
{
bcf1_t *line = maux_get_line(args, i);
if ( !line ) continue;
bcf_sr_t *reader = &files->readers[i];
bcf_hdr_t *hdr = reader->header;
if ( bcf_has_filter(hdr, line, "PASS") ) break;
}
if ( i<files->nreaders )
{
int flt_id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, "PASS");