forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhts.c
1335 lines (1238 loc) · 37.8 KB
/
hts.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
#include <zlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include "htslib/bgzf.h"
#include "htslib/hts.h"
#include "cram/cram.h"
#include "htslib/hfile.h"
#include "version.h"
#include "htslib/kseq.h"
#define KS_BGZF 1
#if KS_BGZF
// bgzf now supports gzip-compressed files
KSTREAM_INIT2(, BGZF*, bgzf_read, 65536)
#else
KSTREAM_INIT2(, gzFile, gzread, 16384)
#endif
#include "htslib/khash.h"
KHASH_INIT2(s2i,, kh_cstr_t, int64_t, 1, kh_str_hash_func, kh_str_hash_equal)
int hts_verbose = 3;
const char *hts_version()
{
return HTS_VERSION;
}
const unsigned char seq_nt16_table[256] = {
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15,
15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15,
15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15
};
const char seq_nt16_str[] = "=ACMGRSVTWYHKDBN";
/**********************
*** Basic file I/O ***
**********************/
// Decompress up to ten or so bytes by peeking at the file, which must be
// positioned at the start of a GZIP block.
static size_t decompress_peek(hFILE *fp, unsigned char *dest, size_t destsize)
{
// Typically at most a couple of hundred bytes of input are required
// to get a few bytes of output from inflate(), so hopefully this buffer
// size suffices in general.
unsigned char buffer[512];
z_stream zs;
ssize_t npeek = hpeek(fp, buffer, sizeof buffer);
if (npeek < 0) return 0;
zs.zalloc = NULL;
zs.zfree = NULL;
zs.next_in = buffer;
zs.avail_in = npeek;
zs.next_out = dest;
zs.avail_out = destsize;
if (inflateInit2(&zs, 31) != Z_OK) return 0;
while (zs.total_out < destsize)
if (inflate(&zs, Z_SYNC_FLUSH) != Z_OK) break;
destsize = zs.total_out;
inflateEnd(&zs);
return destsize;
}
// Returns whether the block contains any control characters, i.e.,
// characters less than SPACE other than whitespace etc (ASCII BEL..CR).
static int is_binary(unsigned char *s, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
if (s[i] < 0x07 || (s[i] >= 0x0e && s[i] < 0x20)) return 1;
return 0;
}
htsFile *hts_open(const char *fn, const char *mode)
{
htsFile *fp = NULL;
hFILE *hfile = hopen(fn, mode);
if (hfile == NULL) goto error;
fp = (htsFile*)calloc(1, sizeof(htsFile));
if (fp == NULL) goto error;
fp->fn = strdup(fn);
fp->is_be = ed_is_big();
if (strchr(mode, 'r')) {
unsigned char s[18];
if (hpeek(hfile, s, 6) == 6 && memcmp(s, "CRAM", 4) == 0 &&
s[4] >= 1 && s[4] <= 2 && s[5] <= 1) {
fp->is_cram = 1;
}
else if (hpeek(hfile, s, 18) == 18 && s[0] == 0x1f && s[1] == 0x8b &&
(s[3] & 4) && memcmp(&s[12], "BC\2\0", 4) == 0) {
// The stream is BGZF-compressed. Decompress a few bytes to see
// whether it's in a binary format (e.g., BAM or BCF, starting
// with four bytes of magic including a control character) or is
// a bgzipped SAM or VCF text file.
fp->is_compressed = 1;
if (is_binary(s, decompress_peek(hfile, s, 4))) fp->is_bin = 1;
else fp->is_kstream = 1;
}
else if (hpeek(hfile, s, 2) == 2 && s[0] == 0x1f && s[1] == 0x8b) {
// Plain GZIP header... so a gzipped text file.
fp->is_compressed = 1;
fp->is_kstream = 1;
}
else if (hpeek(hfile, s, 4) == 4 && is_binary(s, 4)) {
// Binary format, but in a raw non-compressed form.
fp->is_bin = 1;
}
else {
fp->is_kstream = 1;
}
}
else if (strchr(mode, 'w') || strchr(mode, 'a')) {
fp->is_write = 1;
if (strchr(mode, 'b')) fp->is_bin = 1;
if (strchr(mode, 'c')) fp->is_cram = 1;
if (strchr(mode, 'z')) fp->is_compressed = 1;
else if (strchr(mode, 'u')) fp->is_compressed = 0;
else fp->is_compressed = 2; // not set, default behaviour
}
else goto error;
if (fp->is_bin || (fp->is_write && fp->is_compressed==1)) {
fp->fp.bgzf = bgzf_hopen(hfile, mode);
if (fp->fp.bgzf == NULL) goto error;
}
else if (fp->is_cram) {
fp->fp.cram = cram_dopen(hfile, fn, mode);
if (fp->fp.cram == NULL) goto error;
if (!fp->is_write)
cram_set_option(fp->fp.cram, CRAM_OPT_DECODE_MD, 1);
}
else if (fp->is_kstream) {
#if KS_BGZF
BGZF *gzfp = bgzf_hopen(hfile, mode);
#else
// TODO Implement gzip hFILE adaptor
hclose(hfile); // This won't work, especially for stdin
gzFile gzfp = strcmp(fn, "-")? gzopen(fn, "rb") : gzdopen(fileno(stdin), "rb");
#endif
if (gzfp) fp->fp.voidp = ks_init(gzfp);
else goto error;
}
else {
fp->fp.hfile = hfile;
}
return fp;
error:
if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] fail to open file '%s'\n", __func__, fn);
if (hfile)
hclose_abruptly(hfile);
if (fp) {
free(fp->fn);
free(fp->fn_aux);
free(fp);
}
return NULL;
}
int hts_close(htsFile *fp)
{
int ret, save;
if (fp->is_bin || (fp->is_write && fp->is_compressed==1)) {
ret = bgzf_close(fp->fp.bgzf);
} else if (fp->is_cram) {
if (!fp->is_write) {
switch (cram_eof(fp->fp.cram)) {
case 0:
fprintf(stderr, "[E::%s] Failed to decode sequence.\n", __func__);
return -1;
case 2:
fprintf(stderr, "[W::%s] EOF marker is absent. The input is probably truncated.\n", __func__);
break;
default: /* case 1, expected EOF */
break;
}
}
ret = cram_close(fp->fp.cram);
} else if (fp->is_kstream) {
#if KS_BGZF
BGZF *gzfp = ((kstream_t*)fp->fp.voidp)->f;
ret = bgzf_close(gzfp);
#else
gzFile gzfp = ((kstream_t*)fp->fp.voidp)->f;
ret = gzclose(gzfp);
#endif
ks_destroy((kstream_t*)fp->fp.voidp);
} else {
ret = hclose(fp->fp.hfile);
}
save = errno;
free(fp->fn);
free(fp->fn_aux);
free(fp->line.s);
free(fp);
errno = save;
return ret;
}
int hts_set_threads(htsFile *fp, int n)
{
// TODO Plug in CRAM and other threading
if (fp->is_bin) {
return bgzf_mt(fp->fp.bgzf, n, 256);
}
else return 0;
}
int hts_set_fai_filename(htsFile *fp, const char *fn_aux)
{
free(fp->fn_aux);
if (fn_aux) {
fp->fn_aux = strdup(fn_aux);
if (fp->fn_aux == NULL) return -1;
}
else fp->fn_aux = NULL;
return 0;
}
// For VCF/BCF backward sweeper. Not exposing these functions because their
// future is uncertain. Things will probably have to change with hFILE...
BGZF *hts_get_bgzfp(htsFile *fp)
{
if ( fp->is_bin )
return fp->fp.bgzf;
else
return ((kstream_t*)fp->fp.voidp)->f;
}
int hts_useek(htsFile *fp, long uoffset, int where)
{
if ( fp->is_bin )
return bgzf_useek(fp->fp.bgzf, uoffset, where);
else
{
ks_rewind((kstream_t*)fp->fp.voidp);
((kstream_t*)fp->fp.voidp)->seek_pos = uoffset;
return bgzf_useek(((kstream_t*)fp->fp.voidp)->f, uoffset, where);
}
}
long hts_utell(htsFile *fp)
{
if ( fp->is_bin )
return bgzf_utell(fp->fp.bgzf);
else
return ((kstream_t*)fp->fp.voidp)->seek_pos;
}
int hts_getline(htsFile *fp, int delimiter, kstring_t *str)
{
int ret, dret;
ret = ks_getuntil((kstream_t*)fp->fp.voidp, delimiter, str, &dret);
++fp->lineno;
return ret;
}
char **hts_readlist(const char *string, int is_file, int *_n)
{
int m = 0, n = 0, dret;
char **s = 0;
if ( is_file )
{
#if KS_BGZF
BGZF *fp = bgzf_open(string, "r");
#else
gzFile fp = gzopen(string, "r");
#endif
if ( !fp ) return NULL;
kstream_t *ks;
kstring_t str;
str.s = 0; str.l = str.m = 0;
ks = ks_init(fp);
while (ks_getuntil(ks, KS_SEP_LINE, &str, &dret) >= 0)
{
if (str.l == 0) continue;
n++;
hts_expand(char*,n,m,s);
s[n-1] = strdup(str.s);
}
ks_destroy(ks);
#if KS_BGZF
bgzf_close(fp);
#else
gzclose(fp);
#endif
free(str.s);
}
else
{
const char *q = string, *p = string;
while ( 1 )
{
if (*p == ',' || *p == 0)
{
n++;
hts_expand(char*,n,m,s);
s[n-1] = (char*)calloc(p - q + 1, 1);
strncpy(s[n-1], q, p - q);
q = p + 1;
}
if ( !*p ) break;
p++;
}
}
s = (char**)realloc(s, n * sizeof(char*));
*_n = n;
return s;
}
char **hts_readlines(const char *fn, int *_n)
{
int m = 0, n = 0, dret;
char **s = 0;
#if KS_BGZF
BGZF *fp = bgzf_open(fn, "r");
#else
gzFile fp = gzopen(fn, "r");
#endif
if ( fp ) { // read from file
kstream_t *ks;
kstring_t str;
str.s = 0; str.l = str.m = 0;
ks = ks_init(fp);
while (ks_getuntil(ks, KS_SEP_LINE, &str, &dret) >= 0) {
if (str.l == 0) continue;
if (m == n) {
m = m? m<<1 : 16;
s = (char**)realloc(s, m * sizeof(char*));
}
s[n++] = strdup(str.s);
}
ks_destroy(ks);
#if KS_BGZF
bgzf_close(fp);
#else
gzclose(fp);
#endif
s = (char**)realloc(s, n * sizeof(char*));
free(str.s);
} else if (*fn == ':') { // read from string
const char *q, *p;
for (q = p = fn + 1;; ++p)
if (*p == ',' || *p == 0) {
if (m == n) {
m = m? m<<1 : 16;
s = (char**)realloc(s, m * sizeof(char*));
}
s[n] = (char*)calloc(p - q + 1, 1);
strncpy(s[n++], q, p - q);
q = p + 1;
if (*p == 0) break;
}
} else return 0;
s = (char**)realloc(s, n * sizeof(char*));
*_n = n;
return s;
}
int hts_file_type(const char *fname)
{
int len = strlen(fname);
if ( !strcasecmp(".vcf.gz",fname+len-7) ) return FT_VCF_GZ;
if ( !strcasecmp(".vcf",fname+len-4) ) return FT_VCF;
if ( !strcasecmp(".bcf",fname+len-4) ) return FT_BCF_GZ;
if ( !strcmp("-",fname) ) return FT_STDIN;
// ... etc
int fd = open(fname, O_RDONLY);
if ( !fd ) return 0;
uint8_t magic[5];
if ( read(fd,magic,2)!=2 ) { close(fd); return 0; }
if ( !strncmp((char*)magic,"##",2) ) { close(fd); return FT_VCF; }
if ( !strncmp((char*)magic,"BCF",3) ) { close(fd); return FT_BCF; }
close(fd);
if ( magic[0]==0x1f && magic[1]==0x8b ) // compressed
{
BGZF *fp = bgzf_open(fname, "r");
if ( !fp ) return 0;
if ( bgzf_read(fp, magic, 3)!=3 ) { bgzf_close(fp); return 0; }
bgzf_close(fp);
if ( !strncmp((char*)magic,"##",2) ) return FT_VCF;
if ( !strncmp((char*)magic,"BCF",3) ) return FT_BCF_GZ;
}
return 0;
}
/****************
*** Indexing ***
****************/
#define HTS_MIN_MARKER_DIST 0x10000
// Finds the special meta bin
// ((1<<(3 * n_lvls + 3)) - 1) / 7 + 1
#define META_BIN(idx) ((idx)->n_bins + 1)
#define pair64_lt(a,b) ((a).u < (b).u)
#include "htslib/ksort.h"
KSORT_INIT(_off, hts_pair64_t, pair64_lt)
typedef struct {
int32_t m, n;
uint64_t loff;
hts_pair64_t *list;
} bins_t;
#include "htslib/khash.h"
KHASH_MAP_INIT_INT(bin, bins_t)
typedef khash_t(bin) bidx_t;
typedef struct {
int32_t n, m;
uint64_t *offset;
} lidx_t;
struct __hts_idx_t {
int fmt, min_shift, n_lvls, n_bins;
uint32_t l_meta;
int32_t n, m;
uint64_t n_no_coor;
bidx_t **bidx;
lidx_t *lidx;
uint8_t *meta;
struct {
uint32_t last_bin, save_bin;
int last_coor, last_tid, save_tid, finished;
uint64_t last_off, save_off;
uint64_t off_beg, off_end;
uint64_t n_mapped, n_unmapped;
} z; // keep internal states
};
static inline void insert_to_b(bidx_t *b, int bin, uint64_t beg, uint64_t end)
{
khint_t k;
bins_t *l;
int absent;
k = kh_put(bin, b, bin, &absent);
l = &kh_value(b, k);
if (absent) {
l->m = 1; l->n = 0;
l->list = (hts_pair64_t*)calloc(l->m, 16);
}
if (l->n == l->m) {
l->m <<= 1;
l->list = (hts_pair64_t*)realloc(l->list, l->m * 16);
}
l->list[l->n].u = beg;
l->list[l->n++].v = end;
}
static inline void insert_to_l(lidx_t *l, int64_t _beg, int64_t _end, uint64_t offset, int min_shift)
{
int i, beg, end;
beg = _beg >> min_shift;
end = (_end - 1) >> min_shift;
if (l->m < end + 1) {
int old_m = l->m;
l->m = end + 1;
kroundup32(l->m);
l->offset = (uint64_t*)realloc(l->offset, l->m * 8);
memset(l->offset + old_m, 0xff, 8 * (l->m - old_m)); // fill l->offset with (uint64_t)-1
}
if (beg == end) { // to save a loop in this case
if (l->offset[beg] == (uint64_t)-1) l->offset[beg] = offset;
} else {
for (i = beg; i <= end; ++i)
if (l->offset[i] == (uint64_t)-1) l->offset[i] = offset;
}
if (l->n < end + 1) l->n = end + 1;
}
hts_idx_t *hts_idx_init(int n, int fmt, uint64_t offset0, int min_shift, int n_lvls)
{
hts_idx_t *idx;
idx = (hts_idx_t*)calloc(1, sizeof(hts_idx_t));
if (idx == NULL) return NULL;
idx->fmt = fmt;
idx->min_shift = min_shift;
idx->n_lvls = n_lvls;
idx->n_bins = ((1<<(3 * n_lvls + 3)) - 1) / 7;
idx->z.save_bin = idx->z.save_tid = idx->z.last_tid = idx->z.last_bin = 0xffffffffu;
idx->z.save_off = idx->z.last_off = idx->z.off_beg = idx->z.off_end = offset0;
idx->z.last_coor = 0xffffffffu;
if (n) {
idx->n = idx->m = n;
idx->bidx = (bidx_t**)calloc(n, sizeof(bidx_t*));
if (idx->bidx == NULL) { free(idx); return NULL; }
idx->lidx = (lidx_t*) calloc(n, sizeof(lidx_t));
if (idx->lidx == NULL) { free(idx->bidx); free(idx); return NULL; }
}
return idx;
}
static void update_loff(hts_idx_t *idx, int i, int free_lidx)
{
bidx_t *bidx = idx->bidx[i];
lidx_t *lidx = &idx->lidx[i];
khint_t k;
int l;
uint64_t offset0 = 0;
if (bidx) {
k = kh_get(bin, bidx, META_BIN(idx));
if (k != kh_end(bidx))
offset0 = kh_val(bidx, k).list[0].u;
for (l = 0; l < lidx->n && lidx->offset[l] == (uint64_t)-1; ++l)
lidx->offset[l] = offset0;
} else l = 1;
for (; l < lidx->n; ++l) // fill missing values
if (lidx->offset[l] == (uint64_t)-1)
lidx->offset[l] = lidx->offset[l-1];
if (bidx == 0) return;
for (k = kh_begin(bidx); k != kh_end(bidx); ++k) // set loff
if (kh_exist(bidx, k))
{
if ( kh_key(bidx, k) < idx->n_bins )
{
int bot_bin = hts_bin_bot(kh_key(bidx, k), idx->n_lvls);
// disable linear index if bot_bin out of bounds
kh_val(bidx, k).loff = bot_bin < lidx->n ? lidx->offset[bot_bin] : 0;
}
else
kh_val(bidx, k).loff = 0;
}
if (free_lidx) {
free(lidx->offset);
lidx->m = lidx->n = 0;
lidx->offset = 0;
}
}
static void compress_binning(hts_idx_t *idx, int i)
{
bidx_t *bidx = idx->bidx[i];
khint_t k;
int l, m;
if (bidx == 0) return;
// merge a bin to its parent if the bin is too small
for (l = idx->n_lvls; l > 0; --l) {
unsigned start = hts_bin_first(l);
for (k = kh_begin(bidx); k != kh_end(bidx); ++k) {
bins_t *p, *q;
if (!kh_exist(bidx, k) || kh_key(bidx, k) >= idx->n_bins || kh_key(bidx, k) < start) continue;
p = &kh_value(bidx, k);
if (l < idx->n_lvls && p->n > 1) ks_introsort(_off, p->n, p->list);
if ((p->list[p->n - 1].v>>16) - (p->list[0].u>>16) < HTS_MIN_MARKER_DIST) {
khint_t kp;
kp = kh_get(bin, bidx, hts_bin_parent(kh_key(bidx, k)));
if (kp == kh_end(bidx)) continue;
q = &kh_val(bidx, kp);
if (q->n + p->n > q->m) {
q->m = q->n + p->n;
kroundup32(q->m);
q->list = (hts_pair64_t*)realloc(q->list, q->m * 16);
}
memcpy(q->list + q->n, p->list, p->n * 16);
q->n += p->n;
free(p->list);
kh_del(bin, bidx, k);
}
}
}
k = kh_get(bin, bidx, 0);
if (k != kh_end(bidx)) ks_introsort(_off, kh_val(bidx, k).n, kh_val(bidx, k).list);
// merge adjacent chunks that start from the same BGZF block
for (k = kh_begin(bidx); k != kh_end(bidx); ++k) {
bins_t *p;
if (!kh_exist(bidx, k) || kh_key(bidx, k) >= idx->n_bins) continue;
p = &kh_value(bidx, k);
for (l = 1, m = 0; l < p->n; ++l) {
if (p->list[m].v>>16 >= p->list[l].u>>16) {
if (p->list[m].v < p->list[l].v) p->list[m].v = p->list[l].v;
} else p->list[++m] = p->list[l];
}
p->n = m + 1;
}
}
void hts_idx_finish(hts_idx_t *idx, uint64_t final_offset)
{
int i;
if (idx == NULL || idx->z.finished) return; // do not run this function on an empty index or multiple times
if (idx->z.save_tid >= 0) {
insert_to_b(idx->bidx[idx->z.save_tid], idx->z.save_bin, idx->z.save_off, final_offset);
insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.off_beg, final_offset);
insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.n_mapped, idx->z.n_unmapped);
}
for (i = 0; i < idx->n; ++i) {
update_loff(idx, i, (idx->fmt == HTS_FMT_CSI));
compress_binning(idx, i);
}
idx->z.finished = 1;
}
int hts_idx_push(hts_idx_t *idx, int tid, int beg, int end, uint64_t offset, int is_mapped)
{
int bin;
if (tid >= idx->m) { // enlarge the index
int32_t oldm = idx->m;
idx->m = idx->m? idx->m<<1 : 2;
idx->bidx = (bidx_t**)realloc(idx->bidx, idx->m * sizeof(bidx_t*));
idx->lidx = (lidx_t*) realloc(idx->lidx, idx->m * sizeof(lidx_t));
memset(&idx->bidx[oldm], 0, (idx->m - oldm) * sizeof(bidx_t*));
memset(&idx->lidx[oldm], 0, (idx->m - oldm) * sizeof(lidx_t));
}
if (idx->n < tid + 1) idx->n = tid + 1;
if (idx->z.finished) return 0;
if (idx->z.last_tid != tid || (idx->z.last_tid >= 0 && tid < 0)) { // change of chromosome
if ( tid>=0 && idx->n_no_coor )
{
if (hts_verbose >= 1) fprintf(stderr,"[E::%s] NO_COOR reads not in a single block at the end %d %d\n", __func__, tid,idx->z.last_tid);
return -1;
}
if (tid>=0 && idx->bidx[tid] != 0)
{
if (hts_verbose >= 1) fprintf(stderr, "[E::%s] chromosome blocks not continuous\n", __func__);
return -1;
}
idx->z.last_tid = tid;
idx->z.last_bin = 0xffffffffu;
} else if (tid >= 0 && idx->z.last_coor > beg) { // test if positions are out of order
if (hts_verbose >= 1) fprintf(stderr, "[E::%s] unsorted positions\n", __func__);
return -1;
}
if ( tid>=0 )
{
if (idx->bidx[tid] == 0) idx->bidx[tid] = kh_init(bin);
if ( is_mapped)
insert_to_l(&idx->lidx[tid], beg, end, idx->z.last_off, idx->min_shift); // last_off points to the start of the current record
}
else idx->n_no_coor++;
bin = hts_reg2bin(beg, end, idx->min_shift, idx->n_lvls);
if ((int)idx->z.last_bin != bin) { // then possibly write the binning index
if (idx->z.save_bin != 0xffffffffu) // save_bin==0xffffffffu only happens to the first record
insert_to_b(idx->bidx[idx->z.save_tid], idx->z.save_bin, idx->z.save_off, idx->z.last_off);
if (idx->z.last_bin == 0xffffffffu && idx->z.save_bin != 0xffffffffu) { // change of chr; keep meta information
idx->z.off_end = idx->z.last_off;
insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.off_beg, idx->z.off_end);
insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.n_mapped, idx->z.n_unmapped);
idx->z.n_mapped = idx->z.n_unmapped = 0;
idx->z.off_beg = idx->z.off_end;
}
idx->z.save_off = idx->z.last_off;
idx->z.save_bin = idx->z.last_bin = bin;
idx->z.save_tid = tid;
if (tid < 0) { // come to the end of the records having coordinates
hts_idx_finish(idx, offset);
return 0;
}
}
if (is_mapped) ++idx->z.n_mapped;
else ++idx->z.n_unmapped;
idx->z.last_off = offset;
idx->z.last_coor = beg;
return 0;
}
void hts_idx_destroy(hts_idx_t *idx)
{
khint_t k;
int i;
if (idx == 0) return;
// For HTS_FMT_CRAI, idx actually points to a different type -- see sam.c
if (idx->fmt == HTS_FMT_CRAI) { free(idx); return; }
for (i = 0; i < idx->m; ++i) {
bidx_t *bidx = idx->bidx[i];
free(idx->lidx[i].offset);
if (bidx == 0) continue;
for (k = kh_begin(bidx); k != kh_end(bidx); ++k)
if (kh_exist(bidx, k))
free(kh_value(bidx, k).list);
kh_destroy(bin, bidx);
}
free(idx->bidx); free(idx->lidx); free(idx->meta);
free(idx);
}
static inline long idx_read(int is_bgzf, void *fp, void *buf, long l)
{
if (is_bgzf) return bgzf_read((BGZF*)fp, buf, l);
else return (long)fread(buf, 1, l, (FILE*)fp);
}
static inline long idx_write(int is_bgzf, void *fp, const void *buf, long l)
{
if (is_bgzf) return bgzf_write((BGZF*)fp, buf, l);
else return (long)fwrite(buf, 1, l, (FILE*)fp);
}
static inline void swap_bins(bins_t *p)
{
int i;
for (i = 0; i < p->n; ++i) {
ed_swap_8p(&p->list[i].u);
ed_swap_8p(&p->list[i].v);
}
}
static void hts_idx_save_core(const hts_idx_t *idx, void *fp, int fmt)
{
int32_t i, size, is_be;
int is_bgzf = (fmt != HTS_FMT_BAI);
is_be = ed_is_big();
if (is_be) {
uint32_t x = idx->n;
idx_write(is_bgzf, fp, ed_swap_4p(&x), 4);
} else idx_write(is_bgzf, fp, &idx->n, 4);
if (fmt == HTS_FMT_TBI && idx->l_meta) idx_write(is_bgzf, fp, idx->meta, idx->l_meta);
for (i = 0; i < idx->n; ++i) {
khint_t k;
bidx_t *bidx = idx->bidx[i];
lidx_t *lidx = &idx->lidx[i];
// write binning index
size = bidx? kh_size(bidx) : 0;
if (is_be) { // big endian
uint32_t x = size;
idx_write(is_bgzf, fp, ed_swap_4p(&x), 4);
} else idx_write(is_bgzf, fp, &size, 4);
if (bidx == 0) goto write_lidx;
for (k = kh_begin(bidx); k != kh_end(bidx); ++k) {
bins_t *p;
if (!kh_exist(bidx, k)) continue;
p = &kh_value(bidx, k);
if (is_be) { // big endian
uint32_t x;
x = kh_key(bidx, k); idx_write(is_bgzf, fp, ed_swap_4p(&x), 4);
if (fmt == HTS_FMT_CSI) {
uint64_t y = kh_val(bidx, k).loff;
idx_write(is_bgzf, fp, ed_swap_4p(&y), 8);
}
x = p->n; idx_write(is_bgzf, fp, ed_swap_4p(&x), 4);
swap_bins(p);
idx_write(is_bgzf, fp, p->list, 16 * p->n);
swap_bins(p);
} else {
idx_write(is_bgzf, fp, &kh_key(bidx, k), 4);
if (fmt == HTS_FMT_CSI) idx_write(is_bgzf, fp, &kh_val(bidx, k).loff, 8);
//int j;for(j=0;j<p->n;++j)fprintf(stderr,"%d,%llx,%d,%llx:%llx\n",kh_key(bidx,k),kh_val(bidx, k).loff,j,p->list[j].u,p->list[j].v);
idx_write(is_bgzf, fp, &p->n, 4);
idx_write(is_bgzf, fp, p->list, p->n << 4);
}
}
write_lidx:
if (fmt != HTS_FMT_CSI) {
if (is_be) {
int32_t x = lidx->n;
idx_write(is_bgzf, fp, ed_swap_4p(&x), 4);
for (x = 0; x < lidx->n; ++x) ed_swap_8p(&lidx->offset[x]);
idx_write(is_bgzf, fp, lidx->offset, lidx->n << 3);
for (x = 0; x < lidx->n; ++x) ed_swap_8p(&lidx->offset[x]);
} else {
idx_write(is_bgzf, fp, &lidx->n, 4);
idx_write(is_bgzf, fp, lidx->offset, lidx->n << 3);
}
}
}
if (is_be) { // write the number of reads without coordinates
uint64_t x = idx->n_no_coor;
idx_write(is_bgzf, fp, &x, 8);
} else idx_write(is_bgzf, fp, &idx->n_no_coor, 8);
}
void hts_idx_save(const hts_idx_t *idx, const char *fn, int fmt)
{
char *fnidx;
fnidx = (char*)calloc(1, strlen(fn) + 5);
strcpy(fnidx, fn);
if (fmt == HTS_FMT_CSI) {
BGZF *fp;
uint32_t x[3];
int is_be, i;
is_be = ed_is_big();
fp = bgzf_open(strcat(fnidx, ".csi"), "w");
bgzf_write(fp, "CSI\1", 4);
x[0] = idx->min_shift; x[1] = idx->n_lvls; x[2] = idx->l_meta;
if (is_be) {
for (i = 0; i < 3; ++i)
bgzf_write(fp, ed_swap_4p(&x[i]), 4);
} else bgzf_write(fp, &x, 12);
if (idx->l_meta) bgzf_write(fp, idx->meta, idx->l_meta);
hts_idx_save_core(idx, fp, HTS_FMT_CSI);
bgzf_close(fp);
} else if (fmt == HTS_FMT_TBI) {
BGZF *fp;
fp = bgzf_open(strcat(fnidx, ".tbi"), "w");
bgzf_write(fp, "TBI\1", 4);
hts_idx_save_core(idx, fp, HTS_FMT_TBI);
bgzf_close(fp);
} else if (fmt == HTS_FMT_BAI) {
FILE *fp;
fp = fopen(strcat(fnidx, ".bai"), "w");
fwrite("BAI\1", 1, 4, fp);
hts_idx_save_core(idx, fp, HTS_FMT_BAI);
fclose(fp);
} else abort();
free(fnidx);
}
static int hts_idx_load_core(hts_idx_t *idx, void *fp, int fmt)
{
int32_t i, n, is_be;
int is_bgzf = (fmt != HTS_FMT_BAI);
is_be = ed_is_big();
if (idx == NULL) return -4;
for (i = 0; i < idx->n; ++i) {
bidx_t *h;
lidx_t *l = &idx->lidx[i];
uint32_t key;
int j, absent;
bins_t *p;
h = idx->bidx[i] = kh_init(bin);
if (idx_read(is_bgzf, fp, &n, 4) != 4) return -1;
if (is_be) ed_swap_4p(&n);
for (j = 0; j < n; ++j) {
khint_t k;
if (idx_read(is_bgzf, fp, &key, 4) != 4) return -1;
if (is_be) ed_swap_4p(&key);
k = kh_put(bin, h, key, &absent);
if (absent <= 0) return -3; // Duplicate bin number
p = &kh_val(h, k);
if (fmt == HTS_FMT_CSI) {
if (idx_read(is_bgzf, fp, &p->loff, 8) != 8) return -1;
if (is_be) ed_swap_8p(&p->loff);
} else p->loff = 0;
if (idx_read(is_bgzf, fp, &p->n, 4) != 4) return -1;
if (is_be) ed_swap_4p(&p->n);
p->m = p->n;
p->list = (hts_pair64_t*)malloc(p->m * 16);
if (p->list == NULL) return -2;
if (idx_read(is_bgzf, fp, p->list, p->n<<4) != p->n<<4) return -1;
if (is_be) swap_bins(p);
}
if (fmt != HTS_FMT_CSI) { // load linear index
int j;
if (idx_read(is_bgzf, fp, &l->n, 4) != 4) return -1;
if (is_be) ed_swap_4p(&l->n);
l->m = l->n;
l->offset = (uint64_t*)malloc(l->n << 3);
if (l->offset == NULL) return -2;
if (idx_read(is_bgzf, fp, l->offset, l->n << 3) != l->n << 3) return -1;
if (is_be) for (j = 0; j < l->n; ++j) ed_swap_8p(&l->offset[j]);
for (j = 1; j < l->n; ++j) // fill missing values; may happen given older samtools and tabix
if (l->offset[j] == 0) l->offset[j] = l->offset[j-1];
update_loff(idx, i, 1);
}
}
if (idx_read(is_bgzf, fp, &idx->n_no_coor, 8) != 8) idx->n_no_coor = 0;
if (is_be) ed_swap_8p(&idx->n_no_coor);
return 0;
}
hts_idx_t *hts_idx_load_local(const char *fn, int fmt)
{
uint8_t magic[4];
int i, is_be;
hts_idx_t *idx = NULL;
is_be = ed_is_big();
if (fmt == HTS_FMT_CSI) {
BGZF *fp;
uint32_t x[3], n;
uint8_t *meta = 0;
if ((fp = bgzf_open(fn, "r")) == 0) return NULL;
if (bgzf_read(fp, magic, 4) != 4) goto csi_fail;
if (memcmp(magic, "CSI\1", 4) != 0) goto csi_fail;
if (bgzf_read(fp, x, 12) != 12) goto csi_fail;
if (is_be) for (i = 0; i < 3; ++i) ed_swap_4p(&x[i]);
if (x[2]) {
if ((meta = (uint8_t*)malloc(x[2])) == NULL) goto csi_fail;
if (bgzf_read(fp, meta, x[2]) != x[2]) goto csi_fail;
}
if (bgzf_read(fp, &n, 4) != 4) goto csi_fail;
if (is_be) ed_swap_4p(&n);
if ((idx = hts_idx_init(n, fmt, 0, x[0], x[1])) == NULL) goto csi_fail;
idx->l_meta = x[2];
idx->meta = meta;
meta = NULL;
if (hts_idx_load_core(idx, fp, HTS_FMT_CSI) < 0) goto csi_fail;
bgzf_close(fp);
return idx;
csi_fail:
bgzf_close(fp);
hts_idx_destroy(idx);
free(meta);
return NULL;
} else if (fmt == HTS_FMT_TBI) {
BGZF *fp;
uint32_t x[8];
if ((fp = bgzf_open(fn, "r")) == 0) return NULL;
if (bgzf_read(fp, magic, 4) != 4) goto tbi_fail;
if (memcmp(magic, "TBI\1", 4) != 0) goto tbi_fail;
if (bgzf_read(fp, x, 32) != 32) goto tbi_fail;
if (is_be) for (i = 0; i < 8; ++i) ed_swap_4p(&x[i]);
if ((idx = hts_idx_init(x[0], fmt, 0, 14, 5)) == NULL) goto tbi_fail;
idx->l_meta = 28 + x[7];
if ((idx->meta = (uint8_t*)malloc(idx->l_meta)) == NULL) goto tbi_fail;
memcpy(idx->meta, &x[1], 28);
if (bgzf_read(fp, idx->meta + 28, x[7]) != x[7]) goto tbi_fail;
if (hts_idx_load_core(idx, fp, HTS_FMT_TBI) < 0) goto tbi_fail;
bgzf_close(fp);
return idx;
tbi_fail:
bgzf_close(fp);
hts_idx_destroy(idx);
return NULL;
} else if (fmt == HTS_FMT_BAI) {
uint32_t n;
FILE *fp;
if ((fp = fopen(fn, "rb")) == 0) return NULL;
if (fread(magic, 1, 4, fp) != 4) goto bai_fail;
if (memcmp(magic, "BAI\1", 4) != 0) goto bai_fail;
if (fread(&n, 4, 1, fp) != 1) goto bai_fail;
if (is_be) ed_swap_4p(&n);
idx = hts_idx_init(n, fmt, 0, 14, 5);
if (hts_idx_load_core(idx, fp, HTS_FMT_BAI) < 0) goto bai_fail;
fclose(fp);
return idx;
bai_fail:
fclose(fp);
hts_idx_destroy(idx);
return NULL;
} else abort();
}
void hts_idx_set_meta(hts_idx_t *idx, int l_meta, uint8_t *meta, int is_copy)
{
if (idx->meta) free(idx->meta);
idx->l_meta = l_meta;
if (is_copy) {
idx->meta = (uint8_t*)malloc(l_meta);
memcpy(idx->meta, meta, l_meta);
} else idx->meta = meta;
}
uint8_t *hts_idx_get_meta(hts_idx_t *idx, int *l_meta)
{
*l_meta = idx->l_meta;
return idx->meta;
}
const char **hts_idx_seqnames(const hts_idx_t *idx, int *n, hts_id2name_f getid, void *hdr)
{
if ( !idx->n )
{
*n = 0;
return NULL;
}
int tid = 0, i;
const char **names = (const char**) calloc(idx->n,sizeof(const char*));
for (i=0; i<idx->n; i++)
{
bidx_t *bidx = idx->bidx[i];
if ( !bidx ) continue;