forked from samtools/bcftools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcfnorm.c
1816 lines (1718 loc) · 71 KB
/
vcfnorm.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
/* vcfnorm.c -- Left-align and normalize indels.
Copyright (C) 2013-2016 Genome Research Ltd.
Author: Petr Danecek <[email protected]>
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 <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/faidx.h>
#include "bcftools.h"
#include "rbuf.h"
#define CHECK_REF_EXIT 0
#define CHECK_REF_WARN 1
#define CHECK_REF_SKIP 2
#define CHECK_REF_FIX 4
#define MROWS_SPLIT 1
#define MROWS_MERGE 2
// for -m+, mapping from allele indexes of a single input record
// to allele indexes of output record
typedef struct
{
int nals, mals, *map;
}
map_t;
typedef struct
{
char *tseq, *seq;
int mseq;
bcf1_t **lines, **tmp_lines, **alines, **blines, *mrow_out;
int ntmp_lines, mtmp_lines, nalines, malines, nblines, mblines;
map_t *maps; // mrow map for each buffered record
char **als;
int mmaps, nals, mals;
uint8_t *tmp_arr1, *tmp_arr2, *diploid;
int ntmp_arr1, ntmp_arr2;
kstring_t *tmp_str;
kstring_t *tmp_als, tmp_als_str;
int ntmp_als;
rbuf_t rbuf;
int buf_win; // maximum distance between two records to consider
int aln_win; // the realignment window size (maximum repeat size)
bcf_srs_t *files; // using the synced reader only for -r option
bcf_hdr_t *hdr;
faidx_t *fai;
struct { int tot, set, swap; } nref;
char **argv, *output_fname, *ref_fname, *vcf_fname, *region, *targets;
int argc, rmdup, output_type, n_threads, check_ref, strict_filter, do_indels;
int nchanged, nskipped, nsplit, ntotal, mrows_op, mrows_collapse, parsimonious;
int record_cmd_line;
}
args_t;
static inline int replace_iupac_codes(char *seq, int nseq)
{
// Replace ambiguity codes with N for now, it awaits to be seen what the VCF spec codifies in the end
int i, n = 0;
for (i=0; i<nseq; i++)
{
char c = toupper(seq[i]);
if ( c!='A' && c!='C' && c!='G' && c!='T' ) { seq[i] = 'N'; n++; }
}
return n;
}
static void fix_ref(args_t *args, bcf1_t *line)
{
int reflen = strlen(line->d.allele[0]);
int i, maxlen = reflen, len;
for (i=1; i<line->n_allele; i++)
{
int len = strlen(line->d.allele[i]);
if ( maxlen < len ) maxlen = len;
}
char *ref = faidx_fetch_seq(args->fai, (char*)bcf_seqname(args->hdr,line), line->pos, line->pos+maxlen-1, &len);
if ( !ref ) error("faidx_fetch_seq failed at %s:%d\n", bcf_seqname(args->hdr,line),line->pos+1);
replace_iupac_codes(ref,len);
args->nref.tot++;
// is the REF different?
if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
// is the REF allele missing or N?
if ( reflen==1 && (line->d.allele[0][0]=='.' || line->d.allele[0][0]=='N' || line->d.allele[0][0]=='n') )
{
line->d.allele[0][0] = ref[0];
args->nref.set++;
free(ref);
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
return;
}
// does REF contain non-standard bases?
if ( replace_iupac_codes(line->d.allele[0],strlen(line->d.allele[0])) )
{
args->nref.set++;
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
}
// is it swapped?
for (i=1; i<line->n_allele; i++)
{
int len = strlen(line->d.allele[i]);
if ( !strncasecmp(line->d.allele[i],ref,len) ) break;
}
kstring_t str = {0,0,0};
if ( i==line->n_allele )
{
// none of the alternate alleles matches the reference
if ( line->n_allele>1 )
args->nref.set++;
else
args->nref.swap++;
kputs(line->d.allele[0],&str);
kputc(',',&str);
for (i=1; i<line->n_allele; i++)
{
kputs(line->d.allele[i],&str);
kputc(',',&str);
}
kputc(ref[0],&str);
bcf_update_alleles_str(args->hdr,line,str.s);
str.l = 0;
}
else
args->nref.swap++;
free(ref);
// swap the alleles
int j;
kputs(line->d.allele[i],&str);
for (j=1; j<i; j++)
{
kputc(',',&str);
kputs(line->d.allele[j],&str);
}
kputc(',',&str);
kputs(line->d.allele[0],&str);
for (j=i+1; j<line->n_allele; j++)
{
kputc(',',&str);
kputs(line->d.allele[j],&str);
}
bcf_update_alleles_str(args->hdr,line,str.s);
// swap genotypes
int ntmp = args->ntmp_arr1 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr1, &ntmp);
args->ntmp_arr1 = ntmp * sizeof(int32_t);
int32_t *gts = (int32_t*) args->tmp_arr1;
int ni = 0;
for (j=0; j<ngts; j++)
{
if ( gts[j]==bcf_gt_unphased(0) ) { gts[j] = bcf_gt_unphased(i); ni++; }
else if ( gts[j]==bcf_gt_phased(0) ) { gts[j] = bcf_gt_phased(i); ni++; }
else if ( gts[j]==bcf_gt_unphased(i) ) gts[j] = bcf_gt_unphased(0);
else if ( gts[j]==bcf_gt_phased(i) ) gts[j] = bcf_gt_phased(0);
}
bcf_update_genotypes(args->hdr,line,gts,ngts);
// update AC
int nac = bcf_get_info_int32(args->hdr, line, "AC", &args->tmp_arr1, &ntmp);
args->ntmp_arr1 = ntmp * sizeof(int32_t);
if ( i <= nac )
{
int32_t *ac = (int32_t*)args->tmp_arr1;
ac[i-1] = ni;
bcf_update_info_int32(args->hdr, line, "AC", ac, nac);
}
free(str.s);
}
static void fix_dup_alt(args_t *args, bcf1_t *line)
{
// update alleles, create a mapping between old and new indexes
hts_expand(uint8_t,line->n_allele,args->ntmp_arr1,args->tmp_arr1);
args->tmp_arr1[0] = 0; // ref always unchanged
int i, j, nals = line->n_allele, nals_ori = line->n_allele;
for (i=1, j=1; i<line->n_allele; i++)
{
if ( strcmp(line->d.allele[0],line->d.allele[i]) )
{
args->tmp_arr1[i] = j++;
continue;
}
args->tmp_arr1[i] = 0;
nals--;
}
for (i=1, j=1; i<line->n_allele; i++)
{
if ( !args->tmp_arr1[i] ) continue;
line->d.allele[j++] = line->d.allele[i];
}
bcf_update_alleles(args->hdr, line, (const char**)line->d.allele, nals);
// update genotypes
int ntmp = args->ntmp_arr2 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr2, &ntmp);
args->ntmp_arr2 = ntmp * sizeof(int32_t);
int32_t *gts = (int32_t*) args->tmp_arr2;
int changed = 0;
for (i=0; i<ngts; i++)
{
if ( bcf_gt_is_missing(gts[i]) || gts[i]==bcf_int32_vector_end ) continue;
int ial = bcf_gt_allele(gts[i]);
if ( ial<nals_ori && ial==args->tmp_arr1[ial] ) continue;
int ial_new = ial<nals_ori ? args->tmp_arr1[ial] : 0;
gts[i] = bcf_gt_is_phased(gts[i]) ? bcf_gt_phased(ial_new) : bcf_gt_unphased(ial_new);
changed = 1;
}
if ( changed ) bcf_update_genotypes(args->hdr,line,gts,ngts);
}
#define ERR_DUP_ALLELE -2
#define ERR_REF_MISMATCH -1
#define ERR_OK 0
#define ERR_SYMBOLIC 1
static int realign(args_t *args, bcf1_t *line)
{
bcf_unpack(line, BCF_UN_STR);
// Sanity check REF
int i, nref, reflen = strlen(line->d.allele[0]);
char *ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos, line->pos+reflen-1, &nref);
if ( !ref ) error("faidx_fetch_seq failed at %s:%d\n", args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos+1);
replace_iupac_codes(ref,nref);
// does REF contain non-standard bases?
if ( replace_iupac_codes(line->d.allele[0],reflen) )
{
args->nchanged++;
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
}
if ( strcasecmp(ref,line->d.allele[0]) )
{
if ( args->check_ref==CHECK_REF_EXIT )
error("Reference allele mismatch at %s:%d .. REF_SEQ:'%s' vs VCF:'%s'\n", bcf_seqname(args->hdr,line),line->pos+1,ref,line->d.allele[0]);
if ( args->check_ref & CHECK_REF_WARN )
fprintf(stderr,"REF_MISMATCH\t%s\t%d\t%s\n", bcf_seqname(args->hdr,line),line->pos+1,line->d.allele[0]);
free(ref);
return ERR_REF_MISMATCH;
}
free(ref);
ref = NULL;
if ( line->n_allele == 1 ) return ERR_OK; // a REF
// make a copy of each allele for trimming
hts_expand0(kstring_t,line->n_allele,args->ntmp_als,args->tmp_als);
kstring_t *als = args->tmp_als;
for (i=0; i<line->n_allele; i++)
{
if ( line->d.allele[i][0]=='<' ) return ERR_SYMBOLIC; // symbolic allele
als[i].l = 0;
kputs(line->d.allele[i], &als[i]);
if ( i>0 && als[i].l==als[0].l && !strcasecmp(als[0].s,als[i].s) ) return ERR_DUP_ALLELE;
}
// trim from right
int ori_pos = line->pos;
while (1)
{
// is the rightmost base identical in all alleles?
int min_len = als[0].l;
for (i=1; i<line->n_allele; i++)
{
if ( als[0].s[ als[0].l-1 ]!=als[i].s[ als[i].l-1 ] ) break;
if ( als[i].l < min_len ) min_len = als[i].l;
}
if ( i!=line->n_allele ) break; // there are differences, cannot be trimmed
if ( min_len<=1 && line->pos==0 ) break;
int pad_from_left = 0;
for (i=0; i<line->n_allele; i++) // trim all alleles
{
als[i].l--;
if ( !als[i].l ) pad_from_left = 1;
}
if ( pad_from_left )
{
int npad = line->pos >= args->aln_win ? args->aln_win : line->pos;
free(ref);
ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos-npad, line->pos-1, &nref);
if ( !ref ) error("faidx_fetch_seq failed at %s:%d\n", args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos-npad+1);
replace_iupac_codes(ref,nref);
for (i=0; i<line->n_allele; i++)
{
ks_resize(&als[i], als[i].l + npad);
if ( als[i].l ) memmove(als[i].s+npad,als[i].s,als[i].l);
memcpy(als[i].s,ref,npad);
als[i].l += npad;
}
line->pos -= npad;
}
}
free(ref);
// trim from left
int ntrim_left = 0;
while (1)
{
// is the first base identical in all alleles?
int min_len = als[0].l - ntrim_left;
for (i=1; i<line->n_allele; i++)
{
if ( als[0].s[ntrim_left]!=als[i].s[ntrim_left] ) break;
if ( min_len > als[i].l - ntrim_left ) min_len = als[i].l - ntrim_left;
}
if ( i!=line->n_allele || min_len<=1 ) break; // there are differences, cannot be trimmed
ntrim_left++;
}
if ( ntrim_left )
{
for (i=0; i<line->n_allele; i++)
{
memmove(als[i].s,als[i].s+ntrim_left,als[i].l-ntrim_left);
als[i].l -= ntrim_left;
}
line->pos += ntrim_left;
}
// Have the alleles changed?
als[0].s[ als[0].l ] = 0; // in order for strcmp to work
if ( ori_pos==line->pos && !strcasecmp(line->d.allele[0],als[0].s) ) return ERR_OK;
// Create new block of alleles and update
args->tmp_als_str.l = 0;
for (i=0; i<line->n_allele; i++)
{
if (i>0) kputc(',',&args->tmp_als_str);
kputsn(als[i].s,als[i].l,&args->tmp_als_str);
}
args->tmp_als_str.s[ args->tmp_als_str.l ] = 0;
bcf_update_alleles_str(args->hdr,line,args->tmp_als_str.s);
args->nchanged++;
return ERR_OK;
}
static void split_info_numeric(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int ret = bcf_get_info_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( ret>0 ); \
type_t *vals = (type_t*) args->tmp_arr1; \
int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
if ( len==BCF_VL_A ) \
{ \
assert( ret==src->n_allele-1); \
bcf_update_info_##type(args->hdr,dst,tag,vals+ialt,1); \
} \
else if ( len==BCF_VL_R ) \
{ \
assert( ret==src->n_allele); \
if ( ialt!=0 ) vals[1] = vals[ialt+1]; \
bcf_update_info_##type(args->hdr,dst,tag,vals,2); \
} \
else if ( len==BCF_VL_G ) \
{ \
assert( ret==src->n_allele*(src->n_allele+1)/2 ); \
if ( ialt!=0 ) \
{ \
vals[1] = vals[bcf_alleles2gt(0,ialt+1)]; \
vals[2] = vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
} \
bcf_update_info_##type(args->hdr,dst,tag,vals,3); \
} \
else \
bcf_update_info_##type(args->hdr,dst,tag,vals,ret); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float); break;
}
#undef BRANCH_NUMERIC
}
// Find n-th field in a comma-separated list and move it to dst.
// The memory areas may overlap.
#define STR_MOVE_NTH(dst,src,end,nth,len) \
{ \
char *ss = src, *se = src; \
int j = 0; \
while ( *se && se<(end) ) \
{ \
if ( *se==',' ) \
{ \
if ( j==nth ) break; \
j++; \
ss = se+1; \
} \
se++; \
} \
if ( j==nth ) \
{ \
int n = se - ss; \
memmove((dst),ss,n); \
src = se; \
len += n; \
} \
else len = -1; \
}
static void split_info_string(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_string(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
assert( ret>0 );
kstring_t str;
str.m = args->ntmp_arr1;
str.l = ret;
str.s = (char*) args->tmp_arr1;
int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
if ( len==BCF_VL_A )
{
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_R )
{
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,0,len);
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_G )
{
int i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,0,len);
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,iaa-i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
static void split_info_flag(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_flag(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_flag(args->hdr,dst,tag,NULL,ret);
}
static void split_format_genotype(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
int ntmp = args->ntmp_arr1 / 4;
int ngts = bcf_get_genotypes(args->hdr,src,&args->tmp_arr1,&ntmp);
args->ntmp_arr1 = ntmp * 4;
assert( ngts >0 );
int32_t *gt = (int32_t*) args->tmp_arr1;
int i, j, nsmpl = bcf_hdr_nsamples(args->hdr);
ngts /= nsmpl;
for (i=0; i<nsmpl; i++)
{
for (j=0; j<ngts; j++)
{
if ( gt[j]==bcf_int32_vector_end ) break;
if ( bcf_gt_is_missing(gt[j]) || bcf_gt_allele(gt[j])==0 ) continue; // missing allele or ref: leave as is
if ( bcf_gt_allele(gt[j])==ialt+1 )
gt[j] = bcf_gt_unphased(1) | bcf_gt_is_phased(gt[j]); // set to first ALT
else
gt[j] = bcf_gt_unphased(0) | bcf_gt_is_phased(gt[j]); // set to REF
}
gt += ngts;
}
bcf_update_genotypes(args->hdr,dst,args->tmp_arr1,ngts*nsmpl);
}
static void split_format_numeric(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t,is_vector_end,set_vector_end) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int nvals = bcf_get_format_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( nvals>0 ); \
type_t *vals = (type_t *) args->tmp_arr1; \
int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id); \
int i, nsmpl = bcf_hdr_nsamples(args->hdr); \
if ( nvals==nsmpl ) /* all values are missing */ \
{ \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl); \
return; \
} \
if ( len==BCF_VL_A ) \
{ \
assert( nvals==(src->n_allele-1)*nsmpl); \
nvals /= nsmpl; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
dst_vals[0] = src_vals[ialt]; \
dst_vals += 1; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl); \
} \
else if ( len==BCF_VL_R ) \
{ \
assert( nvals==src->n_allele*nsmpl); \
nvals /= nsmpl; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
dst_vals[0] = src_vals[0]; \
dst_vals[1] = src_vals[ialt+1]; \
dst_vals += 2; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl*2); \
} \
else if ( len==BCF_VL_G ) \
{ \
if ( nvals!=src->n_allele*(src->n_allele+1)/2*nsmpl && nvals!=src->n_allele*nsmpl ) \
error("Error at %s:%d, the tag %s has wrong number of fields\n", bcf_seqname(args->hdr,src),src->pos+1,bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id)); \
nvals /= nsmpl; \
int all_haploid = nvals==src->n_allele ? 1 : 0; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
int haploid = all_haploid; \
if ( !haploid ) \
{ \
int j; \
for (j=0; j<nvals; j++) if ( is_vector_end ) break; \
if ( j!=nvals ) haploid = 1; \
} \
dst_vals[0] = src_vals[0]; \
if ( haploid ) \
{ \
dst_vals[1] = src_vals[ialt+1]; \
if ( !all_haploid ) set_vector_end; \
} \
else \
{ \
dst_vals[1] = src_vals[bcf_alleles2gt(0,ialt+1)]; \
dst_vals[2] = src_vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
} \
dst_vals += all_haploid ? 2 : 3; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,all_haploid ? nsmpl*2 : nsmpl*3); \
} \
else \
bcf_update_format_##type(args->hdr,dst,tag,vals,nvals); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, src_vals[j]==bcf_int32_vector_end, dst_vals[2]=bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_is_vector_end(src_vals[j]), bcf_float_set_vector_end(dst_vals[2])); break;
}
#undef BRANCH_NUMERIC
}
static void squeeze_format_char(char *str, int src_blen, int dst_blen, int n)
{
int i, isrc = 0, idst = 0;
for (i=0; i<n; i++)
{
memmove(str+idst,str+isrc,dst_blen);
idst += dst_blen;
isrc += src_blen;
}
}
static void split_format_string(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
int ret = bcf_get_format_char(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
assert( ret>0 );
kstring_t str;
str.m = args->ntmp_arr1;
str.l = ret;
str.s = (char*) args->tmp_arr1;
int nsmpl = bcf_hdr_nsamples(args->hdr);
int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id);
if ( len==BCF_VL_A )
{
int i, blen = ret/nsmpl, maxlen = 0;
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *tmp = ptr;
int len = 0;
STR_MOVE_NTH(tmp,tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else if ( len==BCF_VL_R )
{
int i, blen = ret/nsmpl, maxlen = 0;
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *tmp = ptr;
int len = 0;
STR_MOVE_NTH(ptr,tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else if ( len==BCF_VL_G )
{
int i, blen = ret/nsmpl, maxlen = 0, i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *se = ptr, *sx = ptr+blen;
int nfields = 1;
while ( *se && se<sx )
{
if ( *se==',' ) nfields++;
se++;
}
assert( nfields==src->n_allele*(src->n_allele+1)/2 || nfields==src->n_allele );
int len = 0;
if ( nfields==src->n_allele ) // haploid
{
char *tmp = ptr;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
}
else // diploid
{
char *tmp = ptr;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,iaa-i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
}
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else
bcf_update_format_char(args->hdr,dst,tag,str.s,str.l);
}
static void split_multiallelic_to_biallelics(args_t *args, bcf1_t *line)
{
int i;
bcf_unpack(line, BCF_UN_ALL);
// Init the target biallelic lines
args->ntmp_lines = line->n_allele-1;
if ( args->mtmp_lines < args->ntmp_lines )
{
args->tmp_lines = (bcf1_t **)realloc(args->tmp_lines,sizeof(bcf1_t*)*args->ntmp_lines);
for (i=args->mtmp_lines; i<args->ntmp_lines; i++)
args->tmp_lines[i] = NULL;
args->mtmp_lines = args->ntmp_lines;
}
kstring_t tmp = {0,0,0};
kputs(line->d.allele[0], &tmp);
kputc(',', &tmp);
int rlen = tmp.l;
int gt_id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"GT");
for (i=0; i<args->ntmp_lines; i++) // for each ALT allele
{
if ( !args->tmp_lines[i] ) args->tmp_lines[i] = bcf_init1();
bcf1_t *dst = args->tmp_lines[i];
bcf_clear(dst);
dst->rid = line->rid;
dst->pos = line->pos;
dst->qual = line->qual;
// Not quite sure how to handle IDs, they can be assigned to a specific
// ALT. For now we leave the ID unchanged for all.
bcf_update_id(args->hdr, dst, line->d.id ? line->d.id : ".");
tmp.l = rlen;
kputs(line->d.allele[i+1],&tmp);
bcf_update_alleles_str(args->hdr,dst,tmp.s);
if ( line->d.n_flt ) bcf_update_filter(args->hdr, dst, line->d.flt, line->d.n_flt);
int j;
for (j=0; j<line->n_info; j++)
{
bcf_info_t *info = &line->d.info[j];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key);
if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_info_numeric(args, line, info, i, dst);
else if ( type==BCF_HT_FLAG ) split_info_flag(args, line, info, i, dst);
else split_info_string(args, line, info, i, dst);
}
dst->n_sample = line->n_sample;
for (j=0; j<line->n_fmt; j++)
{
bcf_fmt_t *fmt = &line->d.fmt[j];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id);
if ( fmt->id==gt_id ) split_format_genotype(args, line, fmt, i, dst);
else if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_format_numeric(args, line, fmt, i, dst);
else split_format_string(args, line, fmt, i, dst);
}
}
free(tmp.s);
}
// Enlarge FORMAT array containing nsmpl samples each with nals_ori values
// to accommodate nvals values for each sample, filling the gaps with missing
// values. Works also for INFO arrays, with nsmpl set to 1.
#define ENLARGE_ARRAY(type_t,set_missing,arr,narr_bytes,nsmpl,nvals_ori,nvals) \
{ \
int nbytes_new = (nsmpl)*(nvals)*sizeof(type_t); \
hts_expand(uint8_t,nbytes_new,narr_bytes,arr); \
int ismpl, k; \
for (ismpl=nsmpl-1; ismpl>=0; ismpl--) \
{ \
type_t *dst_ptr = ((type_t*)arr) + ismpl*(nvals); \
type_t *src_ptr = ((type_t*)arr) + ismpl*nvals_ori; \
memmove(dst_ptr,src_ptr,sizeof(type_t)*nvals_ori); \
for (k=nvals_ori; k<nvals; k++) set_missing; \
} \
}
static void merge_info_numeric(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t,set_missing,is_vector_end) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int nvals_ori = bcf_get_info_##type(args->hdr,lines[0],tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( nvals_ori>0 ); \
type_t *vals = (type_t*) args->tmp_arr1, *vals2; \
int i,k,len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
if ( len==BCF_VL_A ) \
{ \
if (nvals_ori!=lines[0]->n_allele - 1) \
error("vcfnorm: number of fields in first record at position %s:%d for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele-1); \
int nvals = dst->n_allele - 1; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele-1) \
error("vcfnorm: could not merge INFO tag %s at position %s:%d\n", tag, bcf_seqname(args->hdr,lines[i]),lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k+1] - 1 ] = vals2[k]; \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else if ( len==BCF_VL_R ) \
{ \
if (nvals_ori!=lines[0]->n_allele) \
error("vcfnorm: number of fields in first record at position %s:%d for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele); \
int nvals = dst->n_allele; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele) \
error("vcfnorm: could not merge INFO tag %s at position %s:%d\n", tag, bcf_seqname(args->hdr,lines[i]),lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k] ] = vals2[k]; \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else if ( len==BCF_VL_G ) \
{ \
/* expecting diploid gt in INFO */ \
if (nvals_ori!=lines[0]->n_allele*(lines[0]->n_allele+1)/2) { \
fprintf(stderr, "todo: merge Number=G INFO fields for haploid sites\n"); \
error("vcfnorm: number of fields in first record at position %s:%d for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele*(lines[0]->n_allele+1)/2); \
} \
int nvals = dst->n_allele*(dst->n_allele+1)/2; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele*(lines[i]->n_allele+1)/2) \
error("vcfnorm: could not merge INFO tag %s at position %s:%d\n", tag, bcf_seqname(args->hdr,lines[i]),lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
int ia,ib; \
k = 0; \
for (ia=0; ia<lines[i]->n_allele; ia++) \
{ \
for (ib=0; ib<=ia; ib++) \
{ \
if ( is_vector_end ) break; \
int l = bcf_alleles2gt(args->maps[i].map[ia],args->maps[i].map[ib]); \
vals[l] = vals2[k]; \
k++; \
} \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else \
bcf_update_info_##type(args->hdr,dst,tag,vals,nvals_ori); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, dst_ptr[k]=bcf_int32_missing, vals2[k]==bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_set_missing(dst_ptr[k]), bcf_float_is_vector_end(vals2[k])); break;
}
#undef BRANCH_NUMERIC
}
static void merge_info_flag(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_flag(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_flag(args->hdr,dst,tag,NULL,ret);
}
int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst); // see vcfmerge.c
static void merge_info_string(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
kstring_t str;
str.m = args->ntmp_arr1;
str.l = 0;
str.s = (char*) args->tmp_arr1;
int i, j, len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
if ( len==BCF_VL_A || len==BCF_VL_R )
{
int jfrom = len==BCF_VL_A ? 1 : 0;
kputc('.',&str);
for (i=jfrom+1; i<dst->n_allele; i++) kputs(",.",&str);
for (i=0; i<nlines; i++)
{
bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
if (!src) continue;
for (j=jfrom; j<lines[i]->n_allele; j++)
copy_string_field((char*)src->vptr, j-jfrom, src->len, &str, args->maps[i].map[j]-jfrom);
}
str.s[str.l] = 0;
args->tmp_arr1 = (uint8_t*) str.s;
args->ntmp_arr1 = str.m;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_G )
{
int ngts = dst->n_allele*(dst->n_allele+1)/2;
kputc('.',&str);
for (i=1; i<ngts; i++) kputs(",.",&str);
for (i=0; i<nlines; i++)
{
bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
if (!src) continue;
int iori, jori, kori = 0;
for (iori=0; iori<lines[i]->n_allele; iori++)
{
int inew = args->maps[i].map[iori];
for (jori=0; jori<=iori; jori++)
{
int jnew = args->maps[i].map[jori];
int knew = bcf_alleles2gt(inew,jnew);
copy_string_field((char*)src->vptr,kori,src->len,&str,knew);
kori++;
}
}
}
str.s[str.l] = 0;
args->tmp_arr1 = (uint8_t*) str.s;
args->ntmp_arr1 = str.m;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else
{
bcf_get_info_string(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_string(args->hdr,dst,tag,args->tmp_arr1);
}
}
static void merge_format_genotype(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
{
int ntmp = args->ntmp_arr1 / 4;
int ngts = bcf_get_genotypes(args->hdr,lines[0],&args->tmp_arr1,&ntmp);
args->ntmp_arr1 = ntmp * 4;
assert( ngts >0 );
int nsmpl = bcf_hdr_nsamples(args->hdr);
ngts /= nsmpl;
int i, j, k;
for (i=1; i<nlines; i++)
{
int ntmp2 = args->ntmp_arr2 / 4;
int ngts2 = bcf_get_genotypes(args->hdr,lines[i],&args->tmp_arr2,&ntmp2);
args->ntmp_arr2 = ntmp2 * 4;
ngts2 /= nsmpl;
if ( ngts!=ngts2 ) error("Error at %s:%d: cannot combine diploid with haploid genotype\n", bcf_seqname(args->hdr,lines[i]),lines[i]->pos+1);
int32_t *gt = (int32_t*) args->tmp_arr1;
int32_t *gt2 = (int32_t*) args->tmp_arr2;
for (j=0; j<nsmpl; j++)
{
for (k=0; k<ngts; k++)
{
if ( gt2[k]==bcf_int32_vector_end ) break;
if ( bcf_gt_is_missing(gt2[k]) || bcf_gt_allele(gt2[k])==0 ) continue;
if ( gt2[k]==0 ) gt[k] = 0; // missing genotype
else
{
int ial = bcf_gt_allele(gt2[k]);
assert( ial<args->maps[i].nals );
gt[k] = bcf_gt_unphased( args->maps[i].map[ial] ) | bcf_gt_is_phased(gt[k]);
}
}