forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hts.c
1665 lines (1521 loc) · 52.1 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
/* hts.c -- format-neutral I/O, indexing, and iterator API functions.
Copyright (C) 2008, 2009, 2012-2015 Genome Research Ltd.
Copyright (C) 2012, 2013 Broad Institute.
Author: Heng Li <[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 <zlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.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, the gzFile branch can be removed
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";
const int seq_nt16_int[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 };
/**********************
*** Basic file I/O ***
**********************/
static enum htsFormatCategory format_category(enum htsExactFormat fmt)
{
switch (fmt) {
case bam:
case sam:
case cram:
return sequence_data;
case vcf:
case bcf:
return variant_data;
case bai:
case crai:
case csi:
case gzi:
case tbi:
return index_file;
case bed:
return region_list;
case unknown_format:
case binary_format:
case text_format:
case format_maximum:
break;
}
return unknown_category;
}
// 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;
}
// Parse "x.y" text, taking care because the string is not NUL-terminated
// and filling in major/minor only when the digits are followed by a delimiter,
// so we don't misread "1.10" as "1.1" due to reaching the end of the buffer.
static void
parse_version(htsFormat *fmt, const unsigned char *u, const unsigned char *ulim)
{
const char *str = (const char *) u;
const char *slim = (const char *) ulim;
const char *s;
fmt->version.major = fmt->version.minor = -1;
for (s = str; s < slim; s++) if (!isdigit(*s)) break;
if (s < slim) {
fmt->version.major = atoi(str);
if (*s == '.') {
str = &s[1];
for (s = str; s < slim; s++) if (!isdigit(*s)) break;
if (s < slim)
fmt->version.minor = atoi(str);
}
else
fmt->version.minor = 0;
}
}
int hts_detect_format(hFILE *hfile, htsFormat *fmt)
{
unsigned char s[21];
ssize_t len = hpeek(hfile, s, 18);
if (len < 0) return -1;
if (len >= 2 && s[0] == 0x1f && s[1] == 0x8b) {
// The stream is either gzip-compressed or BGZF-compressed.
// Determine which, and decompress the first few bytes.
fmt->compression = (len >= 18 && (s[3] & 4) &&
memcmp(&s[12], "BC\2\0", 4) == 0)? bgzf : gzip;
len = decompress_peek(hfile, s, sizeof s);
}
else {
fmt->compression = no_compression;
len = hpeek(hfile, s, sizeof s);
}
if (len < 0) return -1;
fmt->compression_level = -1;
fmt->specific = NULL;
if (len >= 6 && memcmp(s,"CRAM",4) == 0 && s[4]>=1 && s[4]<=3 && s[5]<=1) {
fmt->category = sequence_data;
fmt->format = cram;
fmt->version.major = s[4], fmt->version.minor = s[5];
fmt->compression = custom;
return 0;
}
else if (len >= 4 && s[3] <= '\4') {
if (memcmp(s, "BAM\1", 4) == 0) {
fmt->category = sequence_data;
fmt->format = bam;
// TODO Decompress enough to pick version from @HD-VN header
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BAI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = bai;
fmt->version.major = -1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BCF\4", 4) == 0) {
fmt->category = variant_data;
fmt->format = bcf;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BCF\2", 4) == 0) {
fmt->category = variant_data;
fmt->format = bcf;
fmt->version.major = s[3];
fmt->version.minor = (len >= 5 && s[4] <= 2)? s[4] : 0;
return 0;
}
else if (memcmp(s, "CSI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = csi;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "TBI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = tbi;
fmt->version.major = -1, fmt->version.minor = -1;
return 0;
}
}
else if (len >= 16 && memcmp(s, "##fileformat=VCF", 16) == 0) {
fmt->category = variant_data;
fmt->format = vcf;
if (len >= 21 && s[16] == 'v')
parse_version(fmt, &s[17], &s[len]);
else
fmt->version.major = fmt->version.minor = -1;
return 0;
}
else if (len >= 4 && s[0] == '@' &&
(memcmp(s, "@HD\t", 4) == 0 || memcmp(s, "@SQ\t", 4) == 0 ||
memcmp(s, "@RG\t", 4) == 0 || memcmp(s, "@PG\t", 4) == 0)) {
fmt->category = sequence_data;
fmt->format = sam;
// @HD-VN is not guaranteed to be the first tag, but then @HD is
// not guaranteed to be present at all...
if (len >= 9 && memcmp(s, "@HD\tVN:", 7) == 0)
parse_version(fmt, &s[7], &s[len]);
else
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else {
// Various possibilities for tab-delimited text:
// .crai (gzipped tab-delimited six columns: seqid 5*number)
// .bed ([3..12] tab-delimited columns)
// .bedpe (>= 10 tab-delimited columns)
// .sam (tab-delimited >= 11 columns: seqid number seqid...)
// FIXME For now, assume it's SAM
fmt->category = sequence_data;
fmt->format = sam;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
fmt->category = unknown_category;
fmt->format = unknown_format;
fmt->version.major = fmt->version.minor = -1;
fmt->compression = no_compression;
return 0;
}
char *hts_format_description(const htsFormat *format)
{
kstring_t str = { 0, 0, NULL };
switch (format->format) {
case sam: kputs("SAM", &str); break;
case bam: kputs("BAM", &str); break;
case cram: kputs("CRAM", &str); break;
case vcf: kputs("VCF", &str); break;
case bcf:
if (format->version.major == 1) kputs("Legacy BCF", &str);
else kputs("BCF", &str);
break;
case bai: kputs("BAI", &str); break;
case crai: kputs("CRAI", &str); break;
case csi: kputs("CSI", &str); break;
case tbi: kputs("Tabix", &str); break;
default: kputs("unknown", &str); break;
}
if (format->version.major >= 0) {
kputs(" version ", &str);
kputw(format->version.major, &str);
if (format->version.minor >= 0) {
kputc('.', &str);
kputw(format->version.minor, &str);
}
}
switch (format->compression) {
case custom: kputs(" compressed", &str); break;
case gzip: kputs(" gzip-compressed", &str); break;
case bgzf:
switch (format->format) {
case bam:
case bcf:
case csi:
case tbi:
// These are by definition BGZF, so just use the generic term
kputs(" compressed", &str);
break;
default:
kputs(" BGZF-compressed", &str);
break;
}
break;
default: break;
}
switch (format->category) {
case sequence_data: kputs(" sequence", &str); break;
case variant_data: kputs(" variant calling", &str); break;
case index_file: kputs(" index", &str); break;
case region_list: kputs(" genomic region", &str); break;
default: break;
}
if (format->compression == no_compression)
switch (format->format) {
case sam:
case crai:
case vcf:
case bed:
kputs(" text", &str);
break;
default:
kputs(" data", &str);
break;
}
else
kputs(" data", &str);
return ks_release(&str);
}
htsFile *hts_open(const char *fn, const char *mode)
{
htsFile *fp = NULL;
hFILE *hfile = hopen(fn, mode);
if (hfile == NULL) goto error;
fp = hts_hopen(hfile, fn, mode);
if (fp == NULL) goto error;
return fp;
error:
if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] fail to open file '%s'\n", __func__, fn);
if (hfile)
hclose_abruptly(hfile);
return NULL;
}
htsFile *hts_hopen(struct hFILE *hfile, const char *fn, const char *mode)
{
htsFile *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')) {
if (hts_detect_format(hfile, &fp->format) < 0) goto error;
}
else if (strchr(mode, 'w') || strchr(mode, 'a')) {
htsFormat *fmt = &fp->format;
fp->is_write = 1;
if (strchr(mode, 'b')) fmt->format = binary_format;
else if (strchr(mode, 'c')) fmt->format = cram;
else fmt->format = text_format;
if (strchr(mode, 'z')) fmt->compression = bgzf;
else if (strchr(mode, 'g')) fmt->compression = gzip;
else if (strchr(mode, 'u')) fmt->compression = no_compression;
else {
// No compression mode specified, set to the default for the format
switch (fmt->format) {
case binary_format: fmt->compression = bgzf; break;
case cram: fmt->compression = custom; break;
case text_format: fmt->compression = no_compression; break;
default: abort();
}
}
// Fill in category (if determinable; e.g. 'b' could be BAM or BCF)
fmt->category = format_category(fmt->format);
fmt->version.major = fmt->version.minor = -1;
fmt->compression_level = -1;
fmt->specific = NULL;
}
else goto error;
switch (fp->format.format) {
case binary_format:
case bam:
case bcf:
fp->fp.bgzf = bgzf_hopen(hfile, mode);
if (fp->fp.bgzf == NULL) goto error;
fp->is_bin = 1;
break;
case 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);
fp->is_cram = 1;
break;
case text_format:
case sam:
case vcf:
if (!fp->is_write) {
#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 if (fp->format.compression != no_compression) {
fp->fp.bgzf = bgzf_hopen(hfile, mode);
if (fp->fp.bgzf == NULL) goto error;
}
else
fp->fp.hfile = hfile;
break;
default:
goto error;
}
return fp;
error:
if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] fail to open file '%s'\n", __func__, fn);
if (fp) {
free(fp->fn);
free(fp->fn_aux);
free(fp);
}
return NULL;
}
int hts_close(htsFile *fp)
{
int ret, save;
switch (fp->format.format) {
case binary_format:
case bam:
case bcf:
ret = bgzf_close(fp->fp.bgzf);
break;
case 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);
break;
case text_format:
case sam:
case vcf:
if (!fp->is_write) {
#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 if (fp->format.compression != no_compression)
ret = bgzf_close(fp->fp.bgzf);
else
ret = hclose(fp->fp.hfile);
break;
default:
ret = -1;
break;
}
save = errno;
free(fp->fn);
free(fp->fn_aux);
free(fp->line.s);
free(fp);
errno = save;
return ret;
}
const htsFormat *hts_get_format(htsFile *fp)
{
return fp? &fp->format : NULL;
}
int hts_set_opt(htsFile *fp, enum cram_option opt, ...) {
int r;
va_list args;
if (fp->format.format != cram)
return 0;
va_start(args, opt);
r = cram_set_voption(fp->fp.cram, opt, args);
va_end(args);
return r;
}
int hts_set_threads(htsFile *fp, int n)
{
if (fp->format.compression == bgzf) {
return bgzf_mt(fp->fp.bgzf, n, 256);
} else if (fp->format.format == cram) {
return hts_set_opt(fp, CRAM_OPT_NTHREADS, n);
}
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;
if (fp->format.format == cram)
cram_set_option(fp->fp.cram, CRAM_OPT_REFERENCE, fp->fn_aux);
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;
}
// DEPRECATED: To be removed in a future HTSlib release
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;
hFILE *f = hopen(fname, "r");
if (f == NULL) return 0;
htsFormat fmt;
if (hts_detect_format(f, &fmt) < 0) { hclose_abruptly(f); return 0; }
if (hclose(f) < 0) return 0;
switch (fmt.format) {
case vcf: return (fmt.compression == no_compression)? FT_VCF : FT_VCF_GZ;
case bcf: return (fmt.compression == no_compression)? FT_BCF : FT_BCF_GZ;
default: 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, sizeof(hts_pair64_t));
}
if (l->n == l->m) {
l->m <<= 1;
l->list = (hts_pair64_t*)realloc(l->list, l->m * sizeof(hts_pair64_t));
}
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 * sizeof(uint64_t));
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 * sizeof(hts_pair64_t));
}
memcpy(q->list + q->n, p->list, p->n * sizeof(hts_pair64_t));
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<0) beg = -1, end = 0;
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;