-
Notifications
You must be signed in to change notification settings - Fork 8
/
liftover.c
2626 lines (2453 loc) · 119 KB
/
liftover.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
/* The MIT License
Copyright (C) 2022-2024 Giulio Genovese
Author: Giulio Genovese <[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 <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <htslib/kseq.h>
#include <htslib/vcf.h>
#include <htslib/faidx.h>
#include <htslib/khash.h> // required to reset the contigs dictionary and table
#include "bcftools.h"
#include "regidx.h" // cannot use htslib/regdix.h see http://github.com/samtools/htslib/pull/761
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
#define LIFTOVER_VERSION "2024-09-27"
#define FLIP_TAG "FLIP"
#define SWAP_TAG "SWAP"
#define DROP_TAGS "."
#define AC_TAGS "INFO/AC,FMT/AC"
#define AF_TAGS "INFO/AF,FMT/AF,FMT/AP1,FMT/AP2"
#define DS_TAGS "FMT/DS"
#define GT_TAGS "INFO/ALLELE_A,INFO/ALLELE_B"
#define ES_TAGS "FMT/EZ,FMT/ES,FMT/ED"
#define NO_RULE 0
#define RULE_DROP 1
#define RULE_AC 2
#define RULE_AF 3
#define RULE_DS 4
#define RULE_GT 5
#define RULE_ES 6
#define RULE_AGR 7
const char *rules_str[] = {"DROP", "AC", "AF", "DS", "GT", "FLIP", "AGR"};
static inline char rev_nt(char iupac) {
static const char iupac_complement[128] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, '-', 0x2E, '/',
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x40, 'T', 'V', 'G', 'H', 0x45, 0x46, 'C', 'D', 0x49, 0x4A, 'M', 0x4C, 'K', 'N', 0x4F,
0x50, 0x51, 'Y', 'S', 'A', 0x55, 'B', 'W', 0x58, 'R', 0x5A, ']', 0x5C, '[', 0x5E, 0x5F,
0x60, 't', 'v', 'g', 'h', 0x65, 0x66, 'c', 'd', 0x69, 0x6A, 'm', 0x6C, 'k', 'n', 0x6F,
0x70, 0x71, 'y', 's', 'a', 0x75, 'b', 'w', 0x78, 'r', 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
};
return iupac_complement[(int)(iupac & 0x7F)];
}
static inline void reverse_complement(char *str) {
int i, len = strlen(str);
for (i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = rev_nt(str[len - i - 1]);
str[len - i - 1] = rev_nt(tmp);
}
if (len % 2 == 1) str[len / 2] = rev_nt(str[len / 2]);
}
typedef struct {
int tStart;
int qStart;
int size;
int chain_ind; // index of chain the block belongs to
int tStart_gap; // size of gap to reach previous contiguous block in target space
int tEnd_gap; // size of gap to reach next contiguous block in target space
int qStart_gap; // size of gap to reach previous contiguous block in query space
int qEnd_gap; // size of gap to reach next contiguous block in query space
} block_t;
typedef struct {
uint64_t score;
int t_rid;
int tSize;
int tStart;
int tEnd;
int q_rid;
int qSize;
int qStrand;
int qStart;
int qEnd;
int id;
int block_ind; // index of first block of the chain
int n_blocks; // number of blocks in the chain
} chain_t;
// return previous block from the same chain (NULL if it is the first block)
static inline const block_t *prev_block(const block_t *block, const block_t *blocks, const chain_t *chains) {
int ind = (block - blocks) - chains[block->chain_ind].block_ind;
return ind == 0 ? NULL : block - 1;
}
// return next block from the same chain (NULL if it is the last block)
static inline const block_t *next_block(const block_t *block, const block_t *blocks, const chain_t *chains) {
int ind = (block - blocks) - chains[block->chain_ind].block_ind;
return ind == chains[block->chain_ind].n_blocks - 1 ? NULL : block + 1;
}
typedef struct {
int int_id; // VCF header int_id
int coltype; // whether BCF_HL_INFO or BCF_HL_FMT
int rule; // which rule should apply (DROP, AC, AF, DS, GT, FLIP, or AGR)
} tag_t;
typedef struct {
bcf_hdr_t *in_hdr;
bcf_hdr_t *out_hdr;
faidx_t *src_fai;
faidx_t *dst_fai;
int n_ctgs;
int n_chains;
chain_t *chains;
block_t *blocks;
regidx_t *idx;
regitr_t *itr;
htsFile *reject_fh;
int max_indel_inc;
int aln_win;
int in_mt_rid;
int out_mt_rid;
int lift_mt;
int no_left_align;
int write_src;
int write_fail;
int write_nw;
int reject_filter;
int info_end_id;
int info_an_id;
int fmt_gt_id;
int fmt_an_id;
int *af_arr;
int *ploidy_arr;
const char *flip_tag;
const char *swap_tag;
int n_tags;
tag_t *tags;
int warning_symbolic;
int warning_indel;
int ntotal;
int nswapped;
int nref_added;
int nrejected;
kstring_t tmp_kstr;
kstring_t tmp_pad;
kstring_t *tmp_als;
int m_tmp_als;
int8_t *tmp_arr;
int m_tmp_arr;
int32_t *int32_arr;
int m_int32_arr;
} args_t;
args_t *args;
/****************************************
* CHAIN FUNCTIONS *
****************************************/
static inline int bcf_hdr_name2id_flexible(const bcf_hdr_t *hdr, char *chr) {
if (!chr) return -1;
char buf[] = {'c', 'h', 'r', '\0', '\0', '\0'};
int rid = bcf_hdr_name2id(hdr, chr);
if (rid >= 0) return rid;
if (strncmp(chr, "chr", 3) == 0) rid = bcf_hdr_name2id(hdr, chr + 3);
if (rid >= 0) return rid;
strncpy(buf + 3, chr, 2);
rid = bcf_hdr_name2id(hdr, buf);
if (rid >= 0) return rid;
if (strcmp(chr, "23") == 0 || strcmp(chr, "25") == 0 || strcmp(chr, "XY") == 0 || strcmp(chr, "XX") == 0
|| strcmp(chr, "PAR1") == 0 || strcmp(chr, "PAR2") == 0) {
rid = bcf_hdr_name2id(hdr, "X");
if (rid >= 0) return rid;
rid = bcf_hdr_name2id(hdr, "chrX");
} else if (strcmp(chr, "24") == 0) {
rid = bcf_hdr_name2id(hdr, "Y");
if (rid >= 0) return rid;
rid = bcf_hdr_name2id(hdr, "chrY");
} else if (strcmp(chr, "26") == 0 || strcmp(chr, "MT") == 0 || strcmp(chr, "chrM") == 0) {
rid = bcf_hdr_name2id(hdr, "MT");
if (rid >= 0) return rid;
rid = bcf_hdr_name2id(hdr, "chrM");
}
return rid;
}
// load the chain file (see http://genome.ucsc.edu/goldenPath/help/chain.html)
static int read_chains(htsFile *fp, const bcf_hdr_t *in_hdr, const bcf_hdr_t *out_hdr, int max_snp_gap,
chain_t **chains, block_t **blocks) {
int n_chains = 0;
int n_blocks = 0;
int m_chains = 0;
int m_blocks = 0;
char *tmp = NULL;
kstring_t str = {0, 0, NULL};
int moff = 0, *off = NULL;
while (hts_getline(fp, KS_SEP_LINE, &str) >= 0) {
hts_expand(chain_t, n_chains + 1, m_chains, *chains);
chain_t *chain = &(*chains)[n_chains++];
int ncols = ksplit_core(str.s, 0, &moff, &off);
if (ncols != 13) error("Wrong number of columns in the chain file: %s\n", fp->fn);
// read Header Lines
if (strcmp(&str.s[off[0]], "chain") != 0)
error("Chain line should start with word \"chain\" but \"%s\" found in the chain file: %s\n",
&str.s[off[0]], fp->fn);
chain->score = (uint64_t)strtoll(&str.s[off[1]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[1]], fp->fn);
chain->t_rid = bcf_hdr_name2id_flexible(in_hdr, &str.s[off[2]]);
chain->tSize = strtol(&str.s[off[3]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[3]], fp->fn);
if (chain->t_rid >= 0) {
uint64_t len = in_hdr->id[BCF_DT_CTG][chain->t_rid].val->info[0];
if (len != 0 && chain->tSize != len)
fprintf(stderr,
"Warning: source contig %s has length %" PRId64 " in the VCF and length %s in the chain file\n",
&str.s[off[2]], len, &str.s[off[3]]);
}
if (str.s[off[4]] != '+')
error("Chain line fifth column should be \"+\" but \"%s\" found in the chain file: %s\n", &str.s[off[4]],
fp->fn);
chain->tStart = strtol(&str.s[off[5]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[5]], fp->fn);
chain->tEnd = strtol(&str.s[off[6]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[6]], fp->fn);
chain->q_rid = bcf_hdr_name2id_flexible(out_hdr, &str.s[off[7]]);
chain->qSize = strtol(&str.s[off[8]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[8]], fp->fn);
if (chain->q_rid >= 0) {
uint64_t len = out_hdr->id[BCF_DT_CTG][chain->q_rid].val->info[0];
if (len != 0 && chain->qSize != len)
fprintf(stderr,
"Warning: query contig %s has length %" PRId64 " in the VCF and length %s in the chain file\n",
&str.s[off[7]], len, &str.s[off[8]]);
}
if (str.s[off[9]] != '+' && str.s[off[9]] != '-')
error("Chain line tenth column should be \"+\" or \"-\" but \"%s\" found in the chain file: %s\n",
&str.s[off[9]], fp->fn);
chain->qStrand = str.s[off[9]] == '-';
chain->qStart = strtol(&str.s[off[10]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[10]], fp->fn);
chain->qEnd = strtol(&str.s[off[11]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[11]], fp->fn);
chain->id = strtol(&str.s[off[12]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[12]], fp->fn);
// read Data Lines
int tStart = 0;
int qStart = 0;
int dt = -1;
int dq = -1;
chain->block_ind = n_blocks;
chain->n_blocks = 0;
block_t *block;
int merge_in_progress = 0;
while (hts_getline(fp, KS_SEP_LINE, &str) > 0) {
int ncols = ksplit_core(str.s, 0, &moff, &off);
if (ncols != 1 && ncols != 3) error("Wrong number of columns in the chain file: %s\n", fp->fn);
int size = strtol(&str.s[off[0]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[0]], fp->fn);
if (merge_in_progress) {
block->size += size;
} else {
hts_expand(block_t, n_blocks + 1, m_blocks, *blocks);
block = &(*blocks)[n_blocks++];
block->tStart = tStart;
block->qStart = qStart;
block->size = size;
block->chain_ind = n_chains - 1;
block->tStart_gap = dt;
block->tEnd_gap = -1;
block->qStart_gap = dq;
block->qEnd_gap = -1;
chain->n_blocks++;
}
if (ncols == 1) {
tStart += size;
if (chain->tStart + tStart != chain->tEnd)
error("Chain malformed as target interval %s:%d-%d not fully covered in the chain file: %s\n",
bcf_hdr_id2name(in_hdr, chain->t_rid), chain->tStart, chain->tEnd, fp->fn);
qStart += size;
if (chain->qStart + qStart != chain->qEnd)
error("Chain malformed as query interval %s:%d-%d not fully covered in the chain file: %s\n",
bcf_hdr_id2name(in_hdr, chain->q_rid), chain->qStart, chain->qEnd, fp->fn);
} else {
dt = strtol(&str.s[off[1]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[1]], fp->fn);
dq = strtol(&str.s[off[2]], &tmp, 0);
if (*tmp) error("Could not parse integer %s in the chain file: %s\n", &str.s[off[2]], fp->fn);
tStart += size + dt;
qStart += size + dq;
merge_in_progress = dt == dq && dt <= max_snp_gap;
if (merge_in_progress) {
block->size += dt;
} else {
block->tEnd_gap = dt;
block->qEnd_gap = dq;
}
}
}
}
free(off);
free(str.s);
return n_chains;
}
static void write_chains(FILE *stream, const bcf_hdr_t *in_hdr, const bcf_hdr_t *out_hdr, const chain_t *chains,
int n_chains, block_t *blocks) {
int i, j;
for (i = 0; i < n_chains; i++) {
const chain_t *chain = &chains[i];
const char *tName = bcf_hdr_id2name(in_hdr, chain->t_rid);
const char *qName = bcf_hdr_id2name(out_hdr, chain->q_rid);
fprintf(stream, "chain %" PRIhts_pos " %s %d + %d %d %s %d %c %d %d %d\n", chain->score, tName, chain->tSize,
chain->tStart, chain->tEnd, qName, chain->qSize, chain->qStrand ? '-' : '+', chain->qStart, chain->qEnd,
chain->id);
for (j = 0; j < chain->n_blocks; j++) {
const block_t *block = &blocks[chain->block_ind + j];
fprintf(stream, "%s\t%d\t%d\t%d\t%" PRIhts_pos "\t%c\t%s\t%d\t%d\n", tName, chain->tStart + block->tStart,
chain->tStart + block->tStart + block->size, chain->id, chain->score, chain->qStrand ? '-' : '+',
qName,
chain->qStrand ? chain->qSize - chain->qStart - block->qStart - block->size
: chain->qStart + block->qStart,
chain->qStrand ? chain->qSize - chain->qStart - block->qStart
: chain->qStart + block->qStart + block->size);
}
}
}
KHASH_MAP_INIT_INT(32, char)
static regidx_t *regidx_init_chains(const bcf_hdr_t *in_hdr, const chain_t *chains, int n_chains, block_t *blocks) {
khash_t(32) *h = kh_init(32);
regidx_t *idx = regidx_init(NULL, NULL, NULL, sizeof(uint64_t), NULL);
int i, j;
for (i = 0; i < n_chains; i++) {
const chain_t *chain = &chains[i];
if (chain->t_rid < 0 || chain->q_rid < 0) continue;
// check whether the chain has already been added as Ensembl duplicates chains in the chain file
if (chain->id) {
khiter_t k = kh_get(32, h, chain->id);
int ret, is_missing = (k == kh_end(h));
if (!is_missing) continue;
kh_put(32, h, chain->id, &ret);
}
const char *name = bcf_hdr_id2name(in_hdr, chain->t_rid);
int len = strlen(name);
for (j = 0; j < chain->n_blocks; j++) {
int block_ind = chain->block_ind + j;
const block_t *block = &blocks[block_ind];
regidx_push(idx, (char *)name, (char *)name + len, chain->tStart + block->tStart + 1,
chain->tStart + block->tStart + block->size, (void *)&block_ind);
}
}
kh_destroy(32, h);
return idx;
}
/****************************************
* TAGS FUNCTIONS *
****************************************/
// assign AGR tags rules
static void find_AGR_tags(const bcf_hdr_t *hdr, int *info_rules, int *fmt_rules) {
const int coltypes[2] = {BCF_HL_INFO, BCF_HL_FMT};
int i, j;
for (i = 0; i < 2; i++) {
int *rules = i == 0 ? info_rules : fmt_rules;
for (j = 0; j < hdr->n[BCF_DT_ID]; j++) {
// http://github.com/samtools/htslib/issues/1538
if (!hdr->id[BCF_DT_ID][j].val || bcf_hdr_id2coltype(hdr, coltypes[i], j) == 0xf) continue;
int length = bcf_hdr_id2length(hdr, coltypes[i], j);
if (length == BCF_VL_A || length == BCF_VL_G || length == BCF_VL_R) rules[j] = RULE_AGR;
}
}
}
// assign special tags rules
static void assign_tags(const bcf_hdr_t *hdr, const char *tags, int length_flag, int field_type_flag, int rule,
int *info_rules, int *fmt_rules) {
if (strcmp(tags, ".") == 0) return;
char *s = strdup(tags);
int i, moff = 0, *off = NULL;
int n = ksplit_core(s, ',', &moff, &off);
for (i = 0; i < n; i++) {
char *ss = &s[off[i]];
int coltype = -1;
if (!strncasecmp("INFO/", ss, 5)) {
coltype = BCF_HL_INFO;
ss += 5;
} else if (!strncasecmp("INF/", ss, 4)) {
coltype = BCF_HL_INFO;
ss += 4;
} else if (!strncasecmp("FORMAT/", ss, 7)) {
coltype = BCF_HL_FMT;
ss += 7;
} else if (!strncasecmp("FMT/", ss, 4)) {
coltype = BCF_HL_FMT;
ss += 4;
}
int int_id = bcf_hdr_id2int(hdr, BCF_DT_ID, ss);
if (coltype == -1) {
if (bcf_hdr_idinfo_exists(hdr, BCF_HL_INFO, int_id)) error("Error: did you mean INFO/%s?\n", ss);
if (bcf_hdr_idinfo_exists(hdr, BCF_HL_FMT, int_id)) error("Error: did you mean FORMAT/%s?\n", ss);
error("No matching tag %s\n", ss);
}
if (!bcf_hdr_idinfo_exists(hdr, coltype, int_id)) continue;
unsigned int length = bcf_hdr_id2length(hdr, coltype, int_id);
if (!(1 << length & length_flag)) {
if (length) {
char bcf_vl = length == BCF_VL_A ? 'A' : length == BCF_VL_G ? 'G' : length == BCF_VL_R ? 'R' : '.';
error("The %s tag \"%s\" is a Number=%c tag which is not the expected length for this tag\n",
coltype == BCF_HL_INFO ? "INFO" : "FORMAT", ss, bcf_vl);
} else {
int number = bcf_hdr_id2number(hdr, coltype, int_id);
error("The %s tag \"%s\" is a Number=%d tag which is not the expected length for this tag\n",
coltype == BCF_HL_INFO ? "INFO" : "FORMAT", ss, number);
}
}
int field_type = bcf_hdr_id2type(hdr, coltype, int_id);
if (!(1 << field_type & field_type_flag)) {
const char *bcf_ht = field_type == BCF_HT_FLAG ? "Flag"
: field_type == BCF_HT_INT ? "Integer"
: field_type == BCF_HT_REAL ? "Float"
: field_type == BCF_HT_STR ? "String"
: ".";
error("The %s tag \"%s\" is a Type=%s tag which is not the expected type for this tag\n",
coltype == BCF_HL_INFO ? "INFO" : "FORMAT", ss, bcf_ht);
}
int *rules = coltype == BCF_HL_INFO ? info_rules : fmt_rules;
rules[int_id] = rule;
}
free(off);
free(s);
}
// make list of tags rules
static int compress_tags(int *info_rules, int *fmt_rules, int n, tag_t **tags) {
const int coltypes[2] = {BCF_HL_INFO, BCF_HL_FMT};
int i, j, n_tags = 0, m_tags = 0;
*tags = NULL;
for (i = 0; i < 2; i++) {
int *rules = i == 0 ? info_rules : fmt_rules;
for (j = 0; j < n; j++) {
if (!rules[j]) continue;
hts_expand(tag_t, n_tags + 1, m_tags, *tags);
tag_t *tag = &(*tags)[n_tags++];
tag->int_id = j;
tag->coltype = coltypes[i];
tag->rule = rules[j];
}
}
return n_tags;
}
/****************************************
* PLUGIN *
****************************************/
const char *about(void) { return "Lift over a VCF from one genome build to another.\n"; }
const char *usage(void) {
return "\n"
"About: Lift over a VCF from one genome build to another. "
"(version " LIFTOVER_VERSION
" http://github.com/freeseek/score)\n"
"[ Genovese, G., et al. BCFtools/liftover: an accurate and comprehensive tool to convert genetic variants\n"
"across genome assemblies. Bioinformatics 40, Issue 2 (2024) http://doi.org/10.1093/bioinformatics/btae038 "
"]\n"
"\n"
"Usage: bcftools +liftover [General Options] -- [Plugin Options]\n"
"Options:\n"
" run \"bcftools plugin\" for a list of common options\n"
"\n"
"Plugin options:\n"
" -s, --src-fasta-ref <file> source reference sequence in fasta format\n"
" -f, --fasta-ref <file> destination reference sequence in fasta format\n"
" --set-cache-size <int> select fasta cache size in bytes\n"
" -c, --chain <file> UCSC liftOver chain file\n"
" --max-snp-gap <int> maximum distance to merge contiguous blocks separated by same distance "
"[1]\n"
" --max-indel-inc <int> maximum distance used to increase the size an indel during liftover "
"[250]\n"
" --lift-mt force liftover of MT/chrMT [automatically determined from contig "
"lengths]\n"
" --print-blocks <file> output contiguous blocks used for the liftOver\n"
" --no-left-align do not attempt to left align indels after liftover\n"
" --reject <file> output variants that cannot be lifted over\n"
" -O, --reject-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level "
"[v]\n"
" --write-src write the source contig/position/alleles for lifted variants\n"
" --write-fail write whether the 5' and 3' anchors have failed to lift\n"
" --write-nw write the Needleman-Wunsch alignments when required\n"
" --write-reject write the reason variants cannot be lifted over\n"
"\n"
"Options for how to update INFO/FORMAT records:\n"
" --fix-tags fix Number type for INFO/AC, INFO/AF, FORMAT/GP, and FORMAT/DS tags\n"
" --flip-tag <string> INFO annotation flag to record whether alleles are flipped [FLIP]\n"
" --swap-tag <string> INFO annotation to record when alleles are swapped [SWAP]\n"
" --drop-tags <list> tags to drop when alleles are swapped [" DROP_TAGS
"]\n"
" --ac-tags <list> AC-like tags (must be Number=A,Type=Integer/Float) [" AC_TAGS
"]\n"
" --af-tags <list> AF-like tags (must be Number=A,Type=Float) [" AF_TAGS
"]\n"
" --ds-tags <list> DS-like tags (must be Number=A,Type=Float) [" DS_TAGS
"]\n"
" --gt-tags <list> tags with integers like FORMAT/GT (must be Type=Integer) [" GT_TAGS
"]\n"
" --es-tags <list> GWAS-VCF tags (must be Number=A) [" ES_TAGS
"]\n"
"\n"
"Examples:\n"
" bcftools +liftover -Ou input.hg19.bcf -- -s hg19.fa -f hg38.fa \\\n"
" -c hg19ToHg38.over.chain.gz | bcftools sort -Ob -o output.hg38.bcf -W\n"
" bcftools +liftover -Ou GRCh38_dbSNPv156.vcf.gz -- -s hg38.fa -f chm13v2.0.fa \\\n"
" -c hg38ToHs1.over.chain.gz | bcftools sort -Oz -o chm13v2.0_dbSNPv156.vcf.gz -W=tbi\n"
"\n"
"To obtain liftover chain files:\n"
" wget http://hgdownload.cse.ucsc.edu/goldenpath/hg19/liftOver/hg19ToHg38.over.chain.gz\n"
" wget http://ftp.ensembl.org/pub/assembly_mapping/homo_sapiens/GRCh37_to_GRCh38.chain.gz\n"
" wget http://hgdownload.soe.ucsc.edu/goldenPath/hg38/liftOver/hg38ToHs1.over.chain.gz\n"
"\n";
}
static inline FILE *get_file_handle(const char *str) {
FILE *ret;
if (strcmp(str, "-") == 0)
ret = stdout;
else {
ret = fopen(str, "w");
if (!ret) error("Failed to open %s: %s\n", str, strerror(errno));
}
return ret;
}
int init(int argc, char **argv, bcf_hdr_t *in, bcf_hdr_t *out) {
args = (args_t *)calloc(1, sizeof(args_t));
args->in_hdr = in;
args->out_hdr = out;
args->max_indel_inc = 250;
args->aln_win = 100;
args->flip_tag = FLIP_TAG;
args->swap_tag = SWAP_TAG;
int i, j, k;
int cache_size = 0;
int output_type = FT_VCF;
int clevel = -1;
int max_snp_gap = 1; // maximum distance between two contiguous blocks to allow merging
int fix_tags = 0;
char *tmp = NULL;
const char *src_ref_fname = NULL;
const char *dst_ref_fname = NULL;
const char *chain_fname = NULL;
const char *blocks_fname = NULL;
const char *reject_fname = NULL;
char *drop_tags = DROP_TAGS;
char *ac_tags = AC_TAGS;
char *af_tags = AF_TAGS;
char *ds_tags = DS_TAGS;
char *gt_tags = GT_TAGS;
char *es_tags = ES_TAGS;
static struct option loptions[] = {{"src-fasta-ref", required_argument, NULL, 's'},
{"fasta-ref", required_argument, NULL, 'f'},
{"set-cache-size", required_argument, NULL, 1},
{"chain", required_argument, NULL, 'c'},
{"max-snp-gap", required_argument, NULL, 2},
{"max-indel-inc", required_argument, NULL, 3},
{"lift-mt", no_argument, NULL, 4},
{"print-blocks", required_argument, NULL, 5},
{"no-left-align", no_argument, NULL, 6},
{"reject", required_argument, NULL, 7},
{"reject-type", required_argument, NULL, 'O'},
{"write-src", no_argument, NULL, 8},
{"write-fail", no_argument, NULL, 9},
{"write-nw", no_argument, NULL, 10},
{"write-reject", no_argument, NULL, 11},
{"fix-tags", no_argument, NULL, 12},
{"flip-tag", required_argument, NULL, 13},
{"swap-tag", required_argument, NULL, 14},
{"drop-tags", required_argument, NULL, 15},
{"ac-tags", required_argument, NULL, 16},
{"af-tags", required_argument, NULL, 17},
{"ds-tags", required_argument, NULL, 18},
{"gt-tags", required_argument, NULL, 19},
{"es-tags", required_argument, NULL, 20},
{NULL, 0, NULL, 0}};
int c;
while ((c = getopt_long(argc, argv, "h?s:f:c:O:", loptions, NULL)) >= 0) {
switch (c) {
case 's':
src_ref_fname = optarg;
break;
case 'f':
dst_ref_fname = optarg;
break;
case 1:
cache_size = strtol(optarg, &tmp, 0);
if (*tmp) error("Could not parse: --set-cache-size %s\n", optarg);
break;
case 'c':
chain_fname = optarg;
break;
case 2:
max_snp_gap = strtol(optarg, &tmp, 0);
if (*tmp) error("Could not parse: --max-snp-gap %s\n", optarg);
break;
case 3:
args->max_indel_inc = strtol(optarg, &tmp, 0);
if (*tmp) error("Could not parse: --max-indel-inc %s\n", optarg);
break;
case 4:
args->lift_mt = 1;
break;
case 5:
blocks_fname = optarg;
break;
case 6:
args->no_left_align = 1;
break;
case 7:
reject_fname = optarg;
break;
case 'O':
switch (optarg[0]) {
case 'b':
output_type = FT_BCF_GZ;
break;
case 'u':
output_type = FT_BCF;
break;
case 'z':
output_type = FT_VCF_GZ;
break;
case 'v':
output_type = FT_VCF;
break;
default: {
clevel = strtol(optarg, &tmp, 10);
if (*tmp || clevel < 0 || clevel > 9) error("The output type \"%s\" not recognised\n", optarg);
}
}
if (optarg[1]) {
clevel = strtol(optarg + 1, &tmp, 10);
if (*tmp || clevel < 0 || clevel > 9)
error("Could not parse argument: --compression-level %s\n", optarg + 1);
}
break;
case 8:
args->write_src = 1;
break;
case 9:
args->write_fail = 1;
break;
case 10:
args->write_nw = 1;
break;
case 11:
args->reject_filter = 1;
break;
case 12:
fix_tags = 1;
break;
case 13:
args->flip_tag = optarg;
break;
case 14:
args->swap_tag = optarg;
break;
case 15:
drop_tags = optarg;
break;
case 16:
ac_tags = optarg;
break;
case 17:
af_tags = optarg;
break;
case 18:
ds_tags = optarg;
break;
case 19:
gt_tags = optarg;
break;
case 20:
es_tags = optarg;
break;
case 'h':
case '?':
default:
error("%s", usage());
break;
}
}
if (!in || !out) error("Expected input VCF\n%s", usage());
args->n_ctgs = in->n[BCF_DT_CTG];
// load target reference file
if (src_ref_fname) {
args->src_fai = fai_load(src_ref_fname);
if (!args->src_fai) error("Could not load the reference %s\n", src_ref_fname);
if (cache_size) fai_set_cache_size(args->src_fai, cache_size);
} else {
if (!dst_ref_fname || !chain_fname)
error("At least one of --src-fasta-ref or --fasta-ref and --chain options required\n");
}
// does not perform liftover ... only performs the indel extension
if (!dst_ref_fname || !chain_fname) return 0;
// load query reference file
args->dst_fai = fai_load(dst_ref_fname);
if (!args->dst_fai) error("Could not load the reference %s\n", dst_ref_fname);
if (cache_size) fai_set_cache_size(args->dst_fai, cache_size);
// reset contig table for the output header
bcf_hdr_remove(out, BCF_HL_CTG, NULL);
// required to reset the contigs dictionary and table
kh_clear(vdict, out->dict[BCF_DT_CTG]);
for (i = 0; i < out->n[BCF_DT_CTG]; i++) free((void *)out->id[BCF_DT_CTG][i].key);
out->n[BCF_DT_CTG] = 0;
int n = faidx_nseq(args->dst_fai);
for (i = 0; i < n; i++) {
const char *seq = faidx_iseq(args->dst_fai, i);
int len = faidx_seq_len(args->dst_fai, seq);
bcf_hdr_printf(out, "##contig=<ID=%s,length=%d>", seq, len);
}
// fix INFO/AC, INFO/AF, FORMAT/GP, and FORMAT/DS tags from the Michigan imputation server
if (fix_tags) {
bcf_hdr_t *hdrs[] = {in, out};
const char *tags[] = {"AC", "AF", "GP", "DS"};
int coltypes[] = {BCF_HL_INFO, BCF_HL_INFO, BCF_HL_FMT, BCF_HL_FMT};
int numbers[] = {1, 1, 3, 1};
int lengths[] = {BCF_VL_A, BCF_VL_A, BCF_VL_G, BCF_VL_A};
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
int int_id = bcf_hdr_id2int(hdrs[i], BCF_DT_ID, tags[j]);
if (int_id < 0) continue;
bcf_idinfo_t *val = (bcf_idinfo_t *)hdrs[i]->id[BCF_DT_ID][int_id].val;
if ((val->info[coltypes[j]] & 0xf) == 0xf) continue;
if ((val->info[coltypes[j]] >> 8 & 0xf) == 0 && val->info[coltypes[j]] >> 12 == numbers[j]) {
val->info[coltypes[j]] &= 0xff;
val->info[coltypes[j]] += lengths[j] << 8;
bcf_hrec_t *hrec = val->hrec[coltypes[j]];
for (k = 0; k < hrec->nkeys; k++) {
if (!strcmp(hrec->keys[k], "Number")) {
if (!strcmp(hrec->vals[k], "1"))
hrec->vals[k][0] = 'A';
else if (!strcmp(hrec->vals[k], "3"))
hrec->vals[k][0] = 'G';
}
}
}
}
}
}
if (bcf_hdr_printf(
out, "##INFO=<ID=%s,Number=0,Type=Flag,Description=\"Whether alleles flipped strand during liftover\">",
args->flip_tag)
< 0)
error_errno("Failed to add \"%s\" INFO header", args->flip_tag);
if (bcf_hdr_printf(out,
"##INFO=<ID=%s,Number=1,Type=Integer,Description=\"Which alternate allele became the reference "
"during liftover (-1 for new reference)\">",
args->swap_tag)
< 0)
error_errno("Failed to add \"%s\" INFO header", args->swap_tag);
if (args->write_src) {
if (bcf_hdr_printf(out,
"##INFO=<ID=SRC_CHROM,Number=1,Type=String,Description=\"The name of the source contig of "
"the variant prior to liftover\">")
< 0)
error_errno("Failed to add \"SRC_CHROM\" INFO header");
if (bcf_hdr_printf(out,
"##INFO=<ID=SRC_POS,Number=1,Type=Integer,Description=\"The position of the variant on the "
"source contig prior to liftover\">")
< 0)
error_errno("Failed to add \"SRC_POS\" INFO header");
if (bcf_hdr_printf(out,
"##INFO=<ID=SRC_REF_ALT,Number=.,Type=String,Description=\"A list of the original alleles "
"of the variant prior to liftover\">")
< 0)
error_errno("Failed to add \"SRC_REF_ALT\" INFO header");
}
if (args->write_fail) {
if (bcf_hdr_printf(
out,
"##INFO=<ID=FAIL5,Number=0,Type=Flag,Description=\"Whether the original 5' anchor failed to lift\">")
< 0)
error_errno("Failed to add \"FAIL5\" INFO header");
if (bcf_hdr_printf(
out,
"##INFO=<ID=FAIL3,Number=0,Type=Flag,Description=\"Whether the original 3' anchor failed to lift\">")
< 0)
error_errno("Failed to add \"FAIL3\" INFO header");
}
if (args->write_nw) {
if (bcf_hdr_printf(out, "##INFO=<ID=NW,Number=.,Type=String,Description=\"Needleman-Wunsch alignments\">") < 0)
error_errno("Failed to add \"NW\" INFO header");
}
if (src_ref_fname)
bcf_hdr_printf(out, "##liftover_target_reference=%s",
strrchr(src_ref_fname, '/') ? strrchr(src_ref_fname, '/') + 1 : src_ref_fname);
if (dst_ref_fname)
bcf_hdr_printf(out, "##liftover_query_reference=%s",
strrchr(dst_ref_fname, '/') ? strrchr(dst_ref_fname, '/') + 1 : dst_ref_fname);
if (chain_fname)
bcf_hdr_printf(out, "##liftover_chain_file=%s",
strrchr(chain_fname, '/') ? strrchr(chain_fname, '/') + 1 : chain_fname);
if (bcf_hdr_sync(out) < 0) error_errno("Failed to update header");
// load chain file
if (max_snp_gap > 20)
fprintf(
stderr,
"Warning: merging contiguous blocks farther than 20 bp apart (--max-snp-gap %d used) is not recommended\n",
max_snp_gap);
if (args->max_indel_inc > 250)
fprintf(stderr,
"Warning: dealing with indels with edges farther apart than 250 bp apart (--max-indel-inc %d used) is "
"not recommended\nThe complexity of the Needleman-Wunsch algorithm used to realign indel sequences "
"near chain gaps grows quadratically in this number",
args->max_indel_inc);
htsFile *fp = hts_open(chain_fname, "r");
if (fp == NULL) error("Could not open %s: %s\n", fp->fn, strerror(errno));
args->n_chains = read_chains(fp, in, out, max_snp_gap, &args->chains, &args->blocks);
if (hts_close(fp) < 0) error("Close failed: %s\n", fp->fn);
if (blocks_fname) {
FILE *blocks_file = get_file_handle(blocks_fname);
write_chains(blocks_file, in, out, args->chains, args->n_chains, args->blocks);
if (blocks_file != stdout && blocks_file != stderr) fclose(blocks_file);
}
args->idx = regidx_init_chains(in, args->chains, args->n_chains, args->blocks);
args->itr = regitr_init(args->idx);
args->info_end_id = bcf_hdr_id2int(in, BCF_DT_ID, "END");
if (!bcf_hdr_idinfo_exists(in, BCF_HL_INFO, args->info_end_id)) args->info_end_id = -1;
args->info_an_id = bcf_hdr_id2int(in, BCF_DT_ID, "AN");
if (!bcf_hdr_idinfo_exists(in, BCF_HL_INFO, args->info_an_id)) args->info_an_id = -1;
args->fmt_gt_id = bcf_hdr_id2int(in, BCF_DT_ID, "GT");
if (!bcf_hdr_idinfo_exists(in, BCF_HL_FMT, args->fmt_gt_id)) args->fmt_gt_id = -1;
args->fmt_an_id = bcf_hdr_id2int(in, BCF_DT_ID, "AN");
if (!bcf_hdr_idinfo_exists(in, BCF_HL_FMT, args->fmt_an_id)) args->fmt_an_id = -1;
args->af_arr = (int *)malloc(sizeof(int) * bcf_hdr_nsamples(in));
for (i = 0; i < bcf_hdr_nsamples(in); i++) args->af_arr[i] = 1;
args->ploidy_arr = (int *)malloc(sizeof(int) * bcf_hdr_nsamples(in));
int *info_rules = (int *)calloc(sizeof(int), in->n[BCF_DT_ID]);
int *fmt_rules = (int *)calloc(sizeof(int), in->n[BCF_DT_ID]);
find_AGR_tags(in, info_rules, fmt_rules);
assign_tags(in, ac_tags, 1 << BCF_VL_A, 1 << BCF_HT_INT | 1 << BCF_HT_REAL, RULE_AC, info_rules, fmt_rules);
assign_tags(in, af_tags, 1 << BCF_VL_A, 1 << BCF_HT_REAL, RULE_AF, info_rules, fmt_rules);
assign_tags(in, ds_tags, 1 << BCF_VL_A, 1 << BCF_HT_REAL, RULE_DS, info_rules, fmt_rules);
assign_tags(in, gt_tags, 1 << BCF_VL_FIXED | 1 << BCF_VL_VAR | 1 << BCF_VL_A | 1 << BCF_VL_G | 1 << BCF_VL_R,
1 << BCF_HT_INT, RULE_GT, info_rules, fmt_rules);
assign_tags(in, es_tags, 1 << BCF_VL_A, 1 << BCF_HT_INT | 1 << BCF_HT_REAL | 1 << BCF_HT_STR, RULE_ES, info_rules,
fmt_rules);
assign_tags(in, drop_tags, 1 << BCF_VL_FIXED | 1 << BCF_VL_VAR | 1 << BCF_VL_A | 1 << BCF_VL_G | 1 << BCF_VL_R,
1 << BCF_HT_FLAG | 1 << BCF_HT_INT | 1 << BCF_HT_REAL | 1 << BCF_HT_STR, RULE_DROP, info_rules,
fmt_rules);
args->n_tags = compress_tags(info_rules, fmt_rules, in->n[BCF_DT_ID], &args->tags);
free(info_rules);
free(fmt_rules);
for (i = 0; i < args->n_tags; i++) {
tag_t *tag = &args->tags[i];
const char *key = bcf_hdr_int2id(in, BCF_DT_ID, tag->int_id);
fprintf(stderr, "%s/%s is handled by %s rule\n", tag->coltype == BCF_HL_INFO ? "INFO" : "FORMAT", key,
rules_str[tag->rule - 1]);
}
// mitochrondria is handled in a special way as GRCh37 has a different mitochondria than hg19
args->in_mt_rid = bcf_hdr_name2id_flexible(in, "MT");
args->out_mt_rid = bcf_hdr_name2id_flexible(out, "chrM");
if (!args->lift_mt && args->in_mt_rid >= 0 && args->out_mt_rid >= 0) {
int in_mt_length = in->id[BCF_DT_CTG][args->in_mt_rid].val->info[0];
int out_mt_length = out->id[BCF_DT_CTG][args->out_mt_rid].val->info[0];
if (in_mt_length == 0 || in_mt_length != out_mt_length) args->lift_mt = 1;
}
if (reject_fname) {
char wmode[8];
set_wmode(wmode, output_type, (char *)reject_fname, clevel);
args->reject_fh = hts_open(reject_fname, hts_bcf_wmode(output_type));
if (args->reject_filter) {
if (bcf_hdr_printf(args->in_hdr,
"##FILTER=<ID=MissingContig,Description=\"Contig not defined in the header\">")
< 0)
error_errno("Failed to add \"MissingContig\" FILTER header");
if (bcf_hdr_printf(args->in_hdr, "##FILTER=<ID=UnmappedAnchors,Description=\"Anchors unmapped\">") < 0)
error_errno("Failed to add \"UnmappedAnchors\" FILTER header");
if (bcf_hdr_printf(args->in_hdr, "##FILTER=<ID=UnmappedAnchor5,Description=\"5' anchor unmapped\">") < 0)
error_errno("Failed to add \"UnmappedAnchor5\" FILTER header");
if (bcf_hdr_printf(args->in_hdr, "##FILTER=<ID=UnmappedAnchor3,Description=\"3' anchor unmapped\">") < 0)
error_errno("Failed to add \"UnmappedAnchor3\" FILTER header");
if (bcf_hdr_printf(args->in_hdr,
"##FILTER=<ID=MismatchAnchors,Description=\"Anchors mappings inconsistent\">")
< 0)
error_errno("Failed to add \"MismatchAnchors\" FILTER header");
if (bcf_hdr_printf(args->in_hdr, "##FILTER=<ID=ApartAnchors,Description=\"Anchors mapping too far apart\">")
< 0)
error_errno("Failed to add \"ApartAnchors\" FILTER header");
if (!args->src_fai
&& bcf_hdr_printf(
args->in_hdr,
"##FILTER=<ID=MissingFasta,Description=\"Reference allele sequence could not be extended\">")
< 0)
error_errno("Failed to add \"MissingFasta\" FILTER header");
}
if (args->reject_fh == NULL || bcf_hdr_write(args->reject_fh, args->in_hdr) < 0)
error("Error: cannot write to \"%s\": %s\n", reject_fname, strerror(errno));
}
return 0;
}
/****************************************
* FETCH REFERENCE GENOME SEQUENCE *
****************************************/
// Petr Danecek's code from bcftools/vcfnorm.c
static inline void seq_to_upper(char *seq, int len) {
int i;
for (i = 0; i < len; i++) seq[i] = nt_to_upper(seq[i]);
}
// Petr Danecek's code from bcftools/vcfnorm.c
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' && c != 'N') {
seq[i] = 'N';
n++;
}
}
return n;
}
// fetches sequence in the same way samtools faidx would do using 1-based coordinate system
static inline char *fetch_sequence(const faidx_t *fai, const char *c_name, hts_pos_t p_beg_i, hts_pos_t p_end_i) {
hts_pos_t len;
char *ref = faidx_fetch_seq64(fai, c_name, p_beg_i - 1, p_end_i - 1, &len);
if (!ref || len != p_end_i - p_beg_i + 1) {
free(ref);
return NULL;
}
seq_to_upper(ref, len);
replace_iupac_codes(ref, len);
return ref;
}
/****************************************
* ALLELE EXTENSION FRAMEWORK *
****************************************/
// class to realign alleles using the reference
typedef struct {
const bcf_hdr_t *hdr;
bcf1_t *rec;
kstring_t *als;