-
Notifications
You must be signed in to change notification settings - Fork 1
/
hts_utils.cpp
1316 lines (1163 loc) · 33.8 KB
/
hts_utils.cpp
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) 2013 Adrian Tan <atks@umich.edu>
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 "hts_utils.h"
extern "C" {
#include "htslib/hfile.h"
}
#include "Error.h"
#include <cassert>
/********
*General
********/
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;
//#ifdef __cplusplus
//extern "C" {
//#endif
// int ks_resize2(kstring_t*, unsigned long);
//#ifdef __cplusplus
//}
//#endif
//struct faidx_t {
// BGZF *bgzf;
// int n, m;
// char **name;
// khash_t(s) *hash;
// enum fai_format_options format;
//};
/**********
*FAI UTILS
**********/
/**
* An alternate sequence fetcher for upper case sequence.
*/
char *faidx_fetch_uc_seq(const faidx_t *fai, const char *c_name, int p_beg_i, int p_end_i, int *len)
{
char* seq = faidx_fetch_seq(fai, c_name, p_beg_i, p_end_i, len);
if ( *len > 0 ) {
for(int i=0; i < *len; ++i)
if ( isgraph(seq[i]) ) seq[i] = toupper(seq[i]);
}
return seq;
// int l;
// char c;
// khiter_t iter;
// faidx1_t val;
// char *seq=NULL;
// // Adjust position
// iter = kh_get(s, fai->hash, c_name);
// if(iter == kh_end(fai->hash)) return 0;
// val = kh_value(fai->hash, iter);
// if(p_end_i < p_beg_i) p_beg_i = p_end_i;
// if(p_beg_i < 0) p_beg_i = 0;
// else if(val.len <= p_beg_i) p_beg_i = val.len - 1;
// if(p_end_i < 0) p_end_i = 0;
// else if(val.len <= p_end_i) p_end_i = val.len - 1;
// // Now retrieve the sequence
// int ret = bgzf_useek(fai->bgzf, val.offset + p_beg_i / val.line_blen * val.line_len + p_beg_i % val.line_blen, SEEK_SET);
// if ( ret<0 )
// {
// *len = -1;
// fprintf(stderr,"[fai_fetch_seq] Error: fai_fetch failed. (Seeking in a compressed, .gzi unindexed, file?)\n");
// return NULL;
// }
// l = 0;
// seq = (char*)malloc(p_end_i - p_beg_i + 2);
// while ( (c=bgzf_getc(fai->bgzf))>=0 && l < p_end_i - p_beg_i + 1)
// if (isgraph(c)) seq[l++] = toupper(c);
// seq[l] = '\0';
// *len = l;
// return seq;
}
/**********
*HTS UTILS
**********/
/**
* Checks file extension for use in writing files.
*/
bool str_ends_with(std::string& file_name, const char* ext)
{
size_t len = file_name.size();
const char* suffix = file_name.c_str();
size_t ext_len = strlen(ext);
suffix = (len>ext_len) ? suffix + len - ext_len : suffix;
if (!strcmp(ext, suffix))
{
return true;
}
return false;
}
/**************
*BAM HDR UTILS
**************/
/**
* Copies contigs found in bam header to bcf header.
*/
void bam_hdr_transfer_contigs_to_bcf_hdr(const bam_hdr_t *sh, bcf_hdr_t *vh)
{
kstring_t s = {0,0,0};
for (size_t i=0; i<(size_t)bam_hdr_get_n_targets(sh); ++i)
{
s.l = 0;
ksprintf(&s, "##contig=<ID=%s,length=%d>", bam_hdr_get_target_name(sh)[i], bam_hdr_get_target_len(sh)[i]);
bcf_hdr_append(vh, s.s);
}
if (s.m) free(s.s);
}
/**********
*BAM UTILS
**********/
/**
* Gets the end position of the last mapped base in the read.
*/
int32_t bam_get_end_pos1(bam1_t *s)
{
int32_t end_pos1 = bam_get_pos1(s);
int32_t n_cigar_op = bam_get_n_cigar_op(s);
if (n_cigar_op)
{
uint32_t *cigar = bam_get_cigar(s);
for (int32_t i = 0; i < (int32_t)n_cigar_op; ++i)
{
int32_t opchr = bam_cigar_opchr(cigar[i]);
if (opchr=='M' || opchr=='D' || opchr=='N' || opchr=='=' || opchr=='X')
{
end_pos1 += bam_cigar_oplen(cigar[i]);
}
}
}
return end_pos1-1;
}
/**
* Gets the read sequence from a bam record
*/
void bam_get_seq_string(bam1_t *s, kstring_t *seq)
{
seq->l=0;
uint8_t* sq = bam_get_seq(s);
for (uint16_t i = 0; i < bam_get_l_qseq(s); ++i)
{
kputc("=ACMGRSVTWYHKDBN"[bam_seqi(sq, i)], seq);
}
};
/**
* Gets the base qualities from a bam record, when N is observed, a placeholder value of 0(!, 33 adjusted) is entered
*/
void bam_get_qual_string(bam1_t *s, kstring_t *qual)
{
qual->l=0;
uint32_t offset = 0;
uint8_t* q = bam_get_qual(s);
for (int32_t i = 0; i < bam_get_l_qseq(s); ++i)
{
kputc(q[i-offset] + 33, qual);
}
};
/**
* Gets the cigar from a BAM record
*/
void bam_get_cigar_string(bam1_t *s, kstring_t *cigar_string)
{
cigar_string->l=0;
int32_t n_cigar_op = bam_get_n_cigar_op(s);
if (n_cigar_op)
{
uint32_t *cigar = bam_get_cigar(s);
for (int32_t i = 0; i < (int32_t)n_cigar_op; ++i)
{
kputw(bam_cigar_oplen(cigar[i]), cigar_string);
kputc(bam_cigar_opchr(cigar[i]), cigar_string);
}
}
}
/**
* Gets the cigar string from a bam record
*/
void bam_get_cigar_expanded_string(bam1_t *s, kstring_t *cigar_expanded_string)
{
kstring_t cigar_string = {0,0,0};
bam_get_cigar_string(s, &cigar_string);
cigar_expanded_string->l = 0;
int32_t lastIndex = cigar_string.l;
int32_t i = 0;
kstring_t token = {0,0,0};
if (lastIndex<0)
{
return;
}
char c;
bool seenM = false;
while (i<=lastIndex)
{
c = cigar_string.s[i];
//captures the numeric count
if (c<'A')
{
kputc(c, &token);
}
if (c>'A' || i==lastIndex)
{
//it is possible for I's to be observed before the first M's in the cigar string
//in this case, we treat them as 'S'
if (!seenM)
{
if (c=='I')
{
c = 'S';
}
else if (c=='M')
{
seenM = true;
}
}
int32_t count = atoi(token.s);
for (int32_t j=0; j<count; ++j)
kputc(c, cigar_expanded_string);
token.l = 0;;
}
++i;
}
if (cigar_string.m) free(cigar_string.s);
if (token.m) free(token.s);
}
/**
* Gets the base in the read that is mapped to a genomic position.
* Extracts the read sequence and qualities too.
*/
void bam_get_base_and_qual_and_read_and_qual(bam1_t *srec, uint32_t pos, char& base, char& qual, int32_t& rpos, kstring_t* readseq, kstring_t* readqual)
{
bam1_core_t *c = &srec->core;
int32_t rlen = c->l_qseq;
uint32_t cpos = c->pos; //reference coordinates of the first mapped base
rpos = 0; //read coordinates
kstring_t str = {0,0,0};
base = 'N';
qual = 0;
if (c->n_cigar)
{
uint32_t *cigar = bam_get_cigar(srec);
for (uint32_t i = 0; i < c->n_cigar; ++i)
{
char op = bam_cigar_opchr(cigar[i]);
str.l = 0;
kputw(bam_cigar_oplen(cigar[i]), &str);
char* stop;
uint32_t len = strtol(str.s, &stop, 10);
assert(stop);
//fprintf(stderr,"%d%c",bam_cigar_oplen(cigar[i]),op);
if (op=='M')
{
if (pos>=cpos && pos<=cpos+len-1)
{
rpos += pos-cpos;
break;
}
cpos += len;
rpos += len;
}
else if ( ( op=='D' ) || ( op=='N' ) )
{
if (pos>=cpos && pos<=cpos+len-1)
{
rpos = -1;
break;
}
cpos += len;
}
else if (op=='S' || op=='I')
{
rpos += len;
}
}
//std::cout << "bpos " << bpos << "\n";
if (rpos>=0 && rpos<=rlen)
{
//sequence
bam_get_seq_string(srec, readseq);
base = readseq->s[rpos];
//qual
bam_get_qual_string(srec, readqual);
qual = readqual->s[rpos];
}
else
{
rpos = BAM_READ_INDEX_NA;
}
}
if ( str.s ) free(str.s);
if ( rpos >= rlen ) {
rpos = BAM_READ_INDEX_NA;
base = '.';
}
//if ( rand() % 1000 == 0 )
//fprintf(stderr,", pos = %d, cpos = %d, b = %c, q = %c, rpos=%d, seq=%s, qual = %s\n", pos, cpos, base, qual, rpos, readseq->s, readqual->s);
// std::cout << "q: " << s[bpos-1] << " " << q << "\n";
// for (uint32_t i = 0; i < c->l_qseq; ++i) std::cerr << ((char)(s[i] + 33));
};
/**
* Prints a bam.
*/
void bam_print(bam_hdr_t *h, bam1_t *s)
{
const char* chrom = bam_get_chrom(h, s);
uint32_t pos1 = bam_get_pos1(s);
kstring_t seq = {0,0,0};
bam_get_seq_string(s, &seq);
uint32_t len = bam_get_l_qseq(s);
kstring_t qual = {0,0,0};
bam_get_qual_string(s, &qual);
kstring_t cigar_string = {0,0,0};
bam_get_cigar_string(s, &cigar_string);
kstring_t cigar_expanded_string = {0,0,0};
bam_get_cigar_expanded_string(s, &cigar_expanded_string);
//uint16_t flag = bam_get_flag(s);
uint32_t mapq = bam_get_mapq(s);
std::cerr << "##################" << "\n";
std::cerr << "chrom-pos: " << chrom << "-" << pos1 << "\n";
std::cerr << "read : " << seq.s << "\n";
std::cerr << "qual : " << qual.s << "\n";
std::cerr << "cigar_str: " << cigar_string.s << "\n";
std::cerr << "cigar : " << cigar_expanded_string.s << "\n";
std::cerr << "len : " << len << "\n";
std::cerr << "mapq : " << mapq << "\n";
std::cerr << "mpos1 : " << bam_get_mpos1(s) << "\n";
std::cerr << "mtid : " << bam_get_mtid(s) << "\n";
if (seq.m) free(seq.s);
if (qual.m) free(qual.s);
if (cigar_string.m) free(cigar_string.s);
if (cigar_expanded_string.m) free(cigar_expanded_string.s);
}
/**************
*BCF HDR UTILS
**************/
/**
* Copies contigs found in bcf header to another bcf header.
*/
void bcf_hdr_transfer_contigs(const bcf_hdr_t *hsrc, bcf_hdr_t *hdest)
{
vdict_t *d = (vdict_t*)hsrc->dict[BCF_DT_CTG];
int tid, m = kh_size(d);
const char **names = (const char**) calloc(m,sizeof(const char*));
int len[m];
khint_t k;
for (k=kh_begin(d); k<kh_end(d); k++)
{
if ( !kh_exist(d,k) ) continue;
tid = kh_val(d,k).id;
len[tid] = bcf_hrec_find_key(kh_val(d, k).hrec[0],"length");
int j;
if ( sscanf(kh_val(d, k).hrec[0]->vals[len[tid]],"%d",&j) )
len[tid] = j;
names[tid] = kh_key(d,k);
}
kstring_t s = {0,0,0};
for (tid=0; tid<m; tid++)
{
s.l = 0;
ksprintf(&s, "##contig=<ID=%s,length=%d>", names[tid], len[tid]);
bcf_hdr_append(hdest, s.s);
}
if (s.m) free(s.s);
}
/**
* Extracts sequence length by rid.
*/
int32_t* bcf_hdr_seqlen(const bcf_hdr_t *hdr, int32_t *nseq)
{
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_CTG];
int tid, m = kh_size(d);
int32_t *len = (int32_t*) malloc(m*sizeof(int32_t));
khint_t k;
for (k=kh_begin(d); k<kh_end(d); k++)
{
if ( !kh_exist(d,k) ) continue;
tid = kh_val(d,k).id;
len[tid] = bcf_hrec_find_key(kh_val(d, k).hrec[0],"length");
int j;
if ( sscanf(kh_val(d, k).hrec[0]->vals[len[tid]],"%d",&j) )
len[tid] = j;
}
return len;
}
/**
* Prints a VCF record to STDERR.
*/
void bcf_print(bcf_hdr_t *h, bcf1_t *v)
{
kstring_t s = {0,0,0,};
vcf_format(h, v, &s);
std::cerr << s.s;
if (s.m) free(s.s);
};
/**
* Prints a VCF record in compact string representation to STDERR.
*/
void bcf_print_liten(bcf_hdr_t *h, bcf1_t *v)
{
kstring_t s = {0,0,0,};
bcf_variant2string(h, v, &s);
std::cerr << s.s << "\n";
if (s.m) free(s.s);
};
/**
* Prints a VCF record in compact string representation to STDERR.
*/
void bcf_print_lite(bcf_hdr_t *h, bcf1_t *v)
{
kstring_t s = {0,0,0,};
bcf_variant2string(h, v, &s);
std::cerr << s.s;
if (s.m) free(s.s);
};
/**
* Prints a VCF record in compact string representation to STDERR with alleles sorted.
*/
void bcf_print_lite_sorted(bcf_hdr_t *h, bcf1_t *v)
{
kstring_t s = {0,0,0,};
bcf_variant2string_sorted(h, v, &s);
std::cerr << s.s;
if (s.m) free(s.s);
};
/**
* Reads header of a VCF file and returns the bcf header object.
* This wraps around vcf_hdr_read from the original htslib to
* allow for an alternative header file to be read in.
*
* this searches for the alternative header saved as <filename>.hdr
* If the VCF files is BCF, any alternative header is ignored.
*/
bcf_hdr_t *bcf_alt_hdr_read(htsFile *fp)
{
bcf_hdr_t *h = NULL;
//check for existence of alternative header
kstring_t alt_hdr_fn = {0, 0, 0};
kputs(fp->fn, &alt_hdr_fn);
kputs(".hdr", &alt_hdr_fn);
FILE *file = NULL;
struct stat st;
if (stat(alt_hdr_fn.s, &st)==0 && st.st_size)
{
file = fopen(alt_hdr_fn.s, "r");
}
if (fp->format.format ==bcf || !file)
{
h = bcf_hdr_read(fp);
}
else
{
fprintf(stderr,"[I:%s:%d %s] read alternative header for %s\n", __FILE__, __LINE__, __FUNCTION__, fp->fn);
fclose(file);
htsFile *alt_hdr = hts_open(alt_hdr_fn.s, "r");
h = bcf_hdr_read(alt_hdr);
hts_close(alt_hdr);
//helps move the pointer to the right place
bcf_hdr_t *temp_h = bcf_hdr_read(fp);
bcf_hdr_destroy(temp_h);
}
if (alt_hdr_fn.m) free(alt_hdr_fn.s);
return h;
}
int32_t bcf_hdr_sample_index(bcf_hdr_t* h, const char* id) {
return bcf_hdr_id2int(h, BCF_DT_SAMPLE, id);
}
const char* bcf_hdr_sample_id(bcf_hdr_t* h, int32_t idx) {
//return (const char*)(h->id[BCF_DT_SAMPLE][idx]);
return bcf_hdr_int2id(h, BCF_DT_SAMPLE, idx);
}
/**
* Get number of samples in bcf header
*/
int32_t bcf_hdr_get_n_sample(bcf_hdr_t *h)
{
vdict_t *d = (vdict_t*)h->dict[BCF_DT_SAMPLE];
return kh_size(d);
}
/**
* Help function for adding a header with a backup tag name.
* If the <tag> is already present, a new tag is attempted
* in the format <tag>_1 to <tag>_9. If <tag>_9 failed,
* the function will not add any new tag and will return
* an empty string.
*
* Returns the tag that was inserted or updated.
*/
std::string bcf_hdr_append_info_with_backup_naming(bcf_hdr_t *h, std::string tag, std::string number, std::string type, std::string description, bool rename)
{
if (bcf_hdr_id2int(h, BCF_DT_ID, tag.c_str())==-1)
{
std::string meta_hdr = "##INFO=<ID=" + tag +
",Number=" + number +
",Type=" + type +
",Description=\"" + description + "\">";
bcf_hdr_append(h, meta_hdr.c_str());
}
else
{
if (rename)
{
std::string new_tag = "";
for (uint32_t i=0; i<=9; ++i)
{
char c = 49+i;
new_tag = tag + "_" + c;
if (bcf_hdr_id2int(h, BCF_DT_ID, new_tag.c_str())==-1)
{
std::string meta_hdr = "##INFO=<ID=" + new_tag +
",Number=" + number +
",Type=" + type +
",Description=\"" + description + "\">";
bcf_hdr_append(h, meta_hdr.c_str());
break;
}
new_tag = "";
}
return new_tag;
}
else
{
return tag;
}
}
return tag;
}
/**
* bcf_get_format_*() - same as bcf_get_info*() above
*
* The function bcf_get_format_string() is a higher-level (slower) variant of bcf_get_format_char().
* see the description of bcf_update_format_string() and bcf_update_format_char() above.
* Unlike other bcf_get_format__*() functions, bcf_get_format_string() allocates two arrays:
* a single block of \0-terminated strings collapsed into a single array and an array of pointers
* to these strings. Both arrays must be cleaned by the user.
*
* Returns negative value on error or the number of written values on success.
*
* Example:
* int ndst = 0; char **dst = NULL;
* if ( bcf_get_format_string(hdr, line, "XX", &dst, &ndst) > 0 )
* for (i=0; i<bcf_hdr_nsamples(hdr); i++) printf("%s\n", dst[i]);
* free(dst[0]); free(dst);
*
* Example:
* int ngt, *gt_arr = NULL, ngt_arr = 0;
* ngt = bcf_get_genotypes(hdr, line, >_arr, &ngt_arr);
*
* todo: modify to allow direct reading, instead of copying to char*
*/
int32_t bcf_get_format_string_ro(const bcf_hdr_t *hdr, bcf1_t *line, const char *tag, char ***dst, int *ndst)
{
int i,tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, tag);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,tag_id) ) return -1; // no such FORMAT field in the header
if ( bcf_hdr_id2type(hdr,BCF_HL_FMT,tag_id)!=BCF_HT_STR ) return -2; // expected different type
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
for (i=0; i<line->n_fmt; i++)
if ( line->d.fmt[i].id==tag_id ) break;
if ( i==line->n_fmt ) return -3; // the tag is not present in this record
bcf_fmt_t *fmt = &line->d.fmt[i];
int nsmpl = bcf_hdr_nsamples(hdr);
if ( !*dst )
{
*dst = (char**) malloc(sizeof(char*)*nsmpl);
if ( !*dst ) return -4; // could not alloc
(*dst)[0] = NULL;
}
int n = (fmt->n+1)*nsmpl;
if ( *ndst < n )
{
(*dst)[0] = (char*) realloc((*dst)[0], n);
if ( !(*dst)[0] ) return -4; // could not alloc
*ndst = n;
}
for (i=0; i<nsmpl; i++)
{
uint8_t *src = fmt->p + i*fmt->n;
uint8_t *tmp = (uint8_t*)(*dst)[0] + i*(fmt->n+1);
memcpy(tmp,src,fmt->n);
tmp[fmt->n] = 0;
(*dst)[i] = (char*) tmp;
}
return n;
}
/**********
*BCF UTILS
**********/
/**
* n choose r.
*/
uint32_t choose(uint32_t n, uint32_t r)
{
if (r>n)
{
return 0;
}
else if (r==n)
{
return 1;
}
else if (r==0)
{
return 1;
}
else
{
if (r>(n>>1))
{
r = n-r;
}
uint32_t num = n;
uint32_t denum = 1;
for (uint32_t i=1; i<r; ++i)
{
num *= n-i;
denum *= i+1;
}
return num/denum;
}
}
/**
* Gets number of genotypes from number of alleles and ploidy.
*/
uint32_t bcf_ap2g(uint32_t no_allele, uint32_t no_ploidy)
{
if (no_ploidy==1)
{
return no_allele;
}
else if (no_ploidy==2)
{
return (((no_allele+1)*(no_allele))>>1); ;
}
else
{
return choose(no_ploidy+no_allele-1, no_allele-1);
}
}
/**
* Gets number of genotypes from number of alleles and genotypes.
*/
uint32_t bcf_ag2p(uint32_t no_alleles, uint32_t no_genotypes)
{
if (no_alleles==2 && no_genotypes==3)
{
return 2;
}
else if (no_alleles==3 && no_genotypes==6)
{
return 2;
}
else if (no_alleles==4 && no_genotypes==10)
{
return 2;
}
else if (no_alleles == no_genotypes)
{
return 1;
}
uint32_t no_ploidy = 1;
while (true)
{
uint32_t k = choose(no_ploidy+no_alleles-1, no_alleles-1);
if (k==no_genotypes)
{
return no_ploidy;
}
else if (k>no_genotypes)
{
return 0;
}
++no_ploidy;
}
}
/**
* Gets number of genotypes from number of alleles and ploidy.
*/
uint32_t bcf_g2i(int32_t* g, uint32_t n)
{
if (n==1)
{
return g[0];
}
if (n==2)
{
return g[0] + (((g[1]+1)*(g[1]))>>1);
}
else
{
uint32_t index = 0;
for (uint32_t i=0; i<n; ++i)
{
index += bcf_ap2g(g[i], i+1);
}
return index;
}
}
/**
* Gets number of genotypes from number of alleles and ploidy.
*/
uint32_t bcf_g2i(int32_t g0, int32_t g1)
{
return g0 + (((g1+1)*(g1))>>1);
}
/**
* Gets number of genotypes from number of alleles and ploidy.
*/
uint32_t bcf_g2i(std::string genotype)
{
uint32_t index = 0;
for (uint32_t i=0; i<genotype.size(); ++i)
{
uint32_t allele = genotype.at(i)-65;
index += bcf_ap2g(allele, i+1);
}
return index;
}
/**
* Gets a string representation of a variant.
*/
void bcf_variant2string(bcf_hdr_t *h, bcf1_t *v, kstring_t *var)
{
bcf_unpack(v, BCF_UN_STR);
var->l = 0;
kputs(bcf_get_chrom(h, v), var);
kputc(':', var);
kputw(bcf_get_pos1(v), var);
kputc(':', var);
for (size_t i=0; i<bcf_get_n_allele(v); ++i)
{
if (i) kputc('/', var);
kputs(bcf_get_alt(v, i), var);
}
}
/**
* strcmp wrapper for qsort.
*/
int32_t cmpstr(void const *a, void const *b)
{
char const *aa = *(char const **)a;
char const *bb = *(char const **)b;
return strcmp(aa, bb);
}
/**
* Returns true if a is before b, false otherwise.
*/
bool bcf_is_in_order(bcf1_t *a, bcf1_t *b)
{
if (bcf_get_rid(a)==bcf_get_rid(b))
{
return bcf_get_pos0(a)<=bcf_get_pos0(b);
}
return bcf_get_rid(a)<bcf_get_rid(b);
}
/**
* Gets a sorted string representation of a variant.
*/
void bcf_variant2string_sorted(bcf_hdr_t *h, bcf1_t *v, kstring_t *var)
{
bcf_unpack(v, BCF_UN_STR);
var->l = 0;
kputs(bcf_get_chrom(h, v), var);
kputc(':', var);
kputw(bcf_get_pos1(v), var);
kputc(':', var);
if (v->n_allele==2)
{
kputs(bcf_get_alt(v, 0), var);
kputc(',', var);
kputs(bcf_get_alt(v, 1), var);
}
else
{
char** allele = bcf_get_allele(v);
char** temp = (char**) malloc((bcf_get_n_allele(v)-1)*sizeof(char*));
for (size_t i=1; i<v->n_allele; ++i)
{
temp[i] = allele[i];
}
std::qsort(temp, bcf_get_n_allele(v), sizeof(char*), cmpstr);
kputs(bcf_get_alt(v, 0), var);
for (int32_t i=0; i<v->n_allele-1; ++i)
{
kputc(',', var);
kputs(temp[i], var);
}
free(temp);
}
}
/**
* Gets a string representation of the alleles of a variant.
*/
void bcf_alleles2string(bcf_hdr_t *h, bcf1_t *v, kstring_t *var)
{
bcf_unpack(v, BCF_UN_STR);
var->l = 0;
if (v->n_allele==2)
{
kputs(bcf_get_alt(v, 0), var);
kputc(',', var);
kputs(bcf_get_alt(v, 1), var);
}
else
{
char** allele = bcf_get_allele(v);
for (int32_t i=0; i<v->n_allele; ++i)
{
if (i) kputc(',', var);
kputs(allele[i], var);
}
}
}
/**
* Gets a sorted string representation of the alleles of a variant.
*/
void bcf_alleles2string_sorted(bcf_hdr_t *h, bcf1_t *v, kstring_t *var)
{
bcf_unpack(v, BCF_UN_STR);
var->l = 0;
if (v->n_allele==2)
{
kputs(bcf_get_alt(v, 0), var);
kputc(',', var);
kputs(bcf_get_alt(v, 1), var);
}
else
{
char** allele = bcf_get_allele(v);
char** temp = (char**) malloc((bcf_get_n_allele(v)-1)*sizeof(char*));
for (int32_t i=1; i<v->n_allele; ++i)
{
temp[i-1] = allele[i];
}
std::qsort(temp, bcf_get_n_allele(v)-1, sizeof(char*), cmpstr);
kputs(bcf_get_alt(v, 0), var);
for (int32_t i=0; i<v->n_allele-1; ++i)
{
kputc(',', var);
kputs(temp[i], var);
}
free(temp);
}
}
/**
* Get chromosome name
*/
const char* bcf_get_chrom(bcf_hdr_t *h, bcf1_t *v)
{
if (v->rid >= h->n[BCF_DT_CTG])
{
error("[E:%s:%d %s] [E:%s:%d %s] rid '%d' does not have an associated contig defined in the header. Try tabix workaround or just add the header.\n",__FILE__,__LINE__,__FUNCTION__, __FILE__, __LINE__, __FUNCTION__, v->rid);
//exit(1);
//return NULL;
}
else if ( v->rid < 0 ) return NULL;
return h->id[BCF_DT_CTG][v->rid].key;
}
/**
*Set chromosome name.
*/
void bcf_set_chrom(bcf_hdr_t *h, bcf1_t *v, const char* chrom)
{
vdict_t *d = (vdict_t*)h->dict[BCF_DT_CTG];
khint_t k = kh_get(vdict, d, chrom);
if (k == kh_end(d))
{
error("[E:%s:%d %s] [E:%s:%d %s] contig '%s' is not defined in the header\n",__FILE__,__LINE__,__FUNCTION__, __FILE__, __LINE__, __FUNCTION__, chrom);
kstring_t contig = {0,0,0};
ksprintf(&contig, "##contig=<ID=%s,length=2147483647>", chrom);
bcf_hdr_append(h, contig.s);
if (contig.m) free(contig.s);
k = kh_get(vdict, d, chrom);
}
v->rid = kh_val(d, k).id;
};
/**