forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sam.c
2059 lines (1886 loc) · 67.5 KB
/
sam.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
/* sam.c -- SAM and BAM file I/O and manipulation.
Copyright (C) 2008-2010, 2012-2014 Genome Research Ltd.
Copyright (C) 2010, 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 <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <zlib.h>
#include "htslib/sam.h"
#include "htslib/bgzf.h"
#include "cram/cram.h"
#include "hts_internal.h"
#include "htslib/hfile.h"
#include "htslib/khash.h"
KHASH_DECLARE(s2i, kh_cstr_t, int64_t)
typedef khash_t(s2i) sdict_t;
/**********************
*** BAM header I/O ***
**********************/
bam_hdr_t *bam_hdr_init()
{
return (bam_hdr_t*)calloc(1, sizeof(bam_hdr_t));
}
void bam_hdr_destroy(bam_hdr_t *h)
{
int32_t i;
if (h == NULL) return;
if (h->target_name) {
for (i = 0; i < h->n_targets; ++i)
free(h->target_name[i]);
free(h->target_name);
free(h->target_len);
}
free(h->text); free(h->cigar_tab);
if (h->sdict) kh_destroy(s2i, (sdict_t*)h->sdict);
free(h);
}
bam_hdr_t *bam_hdr_dup(const bam_hdr_t *h0)
{
if (h0 == NULL) return NULL;
bam_hdr_t *h;
if ((h = bam_hdr_init()) == NULL) return NULL;
// copy the simple data
h->n_targets = h0->n_targets;
h->ignore_sam_err = h0->ignore_sam_err;
h->l_text = h0->l_text;
// Then the pointery stuff
h->cigar_tab = NULL;
h->sdict = NULL;
// TODO Check for memory allocation failures
h->text = (char*)calloc(h->l_text + 1, 1);
memcpy(h->text, h0->text, h->l_text);
h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t));
h->target_name = (char**)calloc(h->n_targets, sizeof(char*));
int i;
for (i = 0; i < h->n_targets; ++i) {
h->target_len[i] = h0->target_len[i];
h->target_name[i] = strdup(h0->target_name[i]);
}
return h;
}
static bam_hdr_t *hdr_from_dict(sdict_t *d)
{
bam_hdr_t *h;
khint_t k;
h = bam_hdr_init();
h->sdict = d;
h->n_targets = kh_size(d);
// TODO Check for memory allocation failures
h->target_len = (uint32_t*)malloc(sizeof(uint32_t) * h->n_targets);
h->target_name = (char**)malloc(sizeof(char*) * h->n_targets);
for (k = kh_begin(d); k != kh_end(d); ++k) {
if (!kh_exist(d, k)) continue;
h->target_name[kh_val(d, k)>>32] = (char*)kh_key(d, k);
h->target_len[kh_val(d, k)>>32] = kh_val(d, k)<<32>>32;
kh_val(d, k) >>= 32;
}
return h;
}
bam_hdr_t *bam_hdr_read(BGZF *fp)
{
bam_hdr_t *h;
char buf[4];
int magic_len, has_EOF;
int32_t i, name_len, num_names = 0;
size_t bufsize;
ssize_t bytes;
// check EOF
has_EOF = bgzf_check_EOF(fp);
if (has_EOF < 0) {
perror("[W::bam_hdr_read] bgzf_check_EOF");
} else if (has_EOF == 0 && hts_verbose >= 2)
fprintf(stderr, "[W::%s] EOF marker is absent. The input is probably truncated.\n", __func__);
// read "BAM1"
magic_len = bgzf_read(fp, buf, 4);
if (magic_len != 4 || strncmp(buf, "BAM\1", 4)) {
if (hts_verbose >= 1) fprintf(stderr, "[E::%s] invalid BAM binary header\n", __func__);
return 0;
}
h = bam_hdr_init();
if (!h) goto nomem;
// read plain text and the number of reference sequences
bytes = bgzf_read(fp, &h->l_text, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->l_text);
bufsize = ((size_t) h->l_text) + 1;
if (bufsize < h->l_text) goto nomem; // so large that adding 1 overflowed
h->text = (char*)malloc(bufsize);
if (!h->text) goto nomem;
h->text[h->l_text] = 0; // make sure it is NULL terminated
bytes = bgzf_read(fp, h->text, h->l_text);
if (bytes != h->l_text) goto read_err;
bytes = bgzf_read(fp, &h->n_targets, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->n_targets);
if (h->n_targets < 0) goto invalid;
// read reference sequence names and lengths
if (h->n_targets > 0) {
h->target_name = (char**)calloc(h->n_targets, sizeof(char*));
if (!h->target_name) goto nomem;
h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t));
if (!h->target_len) goto nomem;
}
else {
h->target_name = NULL;
h->target_len = NULL;
}
for (i = 0; i != h->n_targets; ++i) {
bytes = bgzf_read(fp, &name_len, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&name_len);
if (name_len <= 0) goto invalid;
h->target_name[i] = (char*)malloc(name_len);
if (!h->target_name[i]) goto nomem;
num_names++;
bytes = bgzf_read(fp, h->target_name[i], name_len);
if (bytes != name_len) goto read_err;
if (h->target_name[i][name_len - 1] != '\0') {
/* Fix missing NUL-termination. Is this being too nice?
We could alternatively bail out with an error. */
char *new_name;
if (name_len == INT32_MAX) goto invalid;
new_name = realloc(h->target_name[i], name_len + 1);
if (new_name == NULL) goto nomem;
h->target_name[i] = new_name;
h->target_name[i][name_len] = '\0';
}
bytes = bgzf_read(fp, &h->target_len[i], 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->target_len[i]);
}
return h;
nomem:
if (hts_verbose >= 1) fprintf(stderr, "[E::%s] out of memory\n", __func__);
goto clean;
read_err:
if (hts_verbose >= 1) {
if (bytes < 0) {
fprintf(stderr, "[E::%s] error reading BGZF stream\n", __func__);
} else {
fprintf(stderr, "[E::%s] truncated bam header\n", __func__);
}
}
goto clean;
invalid:
if (hts_verbose >= 1) {
fprintf(stderr, "[E::%s] invalid BAM binary header\n", __func__);
}
clean:
if (h != NULL) {
h->n_targets = num_names; // ensure we free only allocated target_names
bam_hdr_destroy(h);
}
return NULL;
}
int bam_hdr_write(BGZF *fp, const bam_hdr_t *h)
{
char buf[4];
int32_t i, name_len, x;
// write "BAM1"
strncpy(buf, "BAM\1", 4);
bgzf_write(fp, buf, 4);
// write plain text and the number of reference sequences
if (fp->is_be) {
x = ed_swap_4(h->l_text);
bgzf_write(fp, &x, 4);
if (h->l_text) bgzf_write(fp, h->text, h->l_text);
x = ed_swap_4(h->n_targets);
bgzf_write(fp, &x, 4);
} else {
bgzf_write(fp, &h->l_text, 4);
if (h->l_text) bgzf_write(fp, h->text, h->l_text);
bgzf_write(fp, &h->n_targets, 4);
}
// write sequence names and lengths
for (i = 0; i != h->n_targets; ++i) {
char *p = h->target_name[i];
name_len = strlen(p) + 1;
if (fp->is_be) {
x = ed_swap_4(name_len);
bgzf_write(fp, &x, 4);
} else bgzf_write(fp, &name_len, 4);
bgzf_write(fp, p, name_len);
if (fp->is_be) {
x = ed_swap_4(h->target_len[i]);
bgzf_write(fp, &x, 4);
} else bgzf_write(fp, &h->target_len[i], 4);
}
bgzf_flush(fp);
return 0;
}
int bam_name2id(bam_hdr_t *h, const char *ref)
{
sdict_t *d = (sdict_t*)h->sdict;
khint_t k;
if (h->sdict == 0) {
int i, absent;
d = kh_init(s2i);
for (i = 0; i < h->n_targets; ++i) {
k = kh_put(s2i, d, h->target_name[i], &absent);
kh_val(d, k) = i;
}
h->sdict = d;
}
k = kh_get(s2i, d, ref);
return k == kh_end(d)? -1 : kh_val(d, k);
}
/*************************
*** BAM alignment I/O ***
*************************/
bam1_t *bam_init1()
{
return (bam1_t*)calloc(1, sizeof(bam1_t));
}
void bam_destroy1(bam1_t *b)
{
if (b == 0) return;
free(b->data); free(b);
}
bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc)
{
uint8_t *data = bdst->data;
int m_data = bdst->m_data; // backup data and m_data
if (m_data < bsrc->l_data) { // double the capacity
m_data = bsrc->l_data; kroundup32(m_data);
data = (uint8_t*)realloc(data, m_data);
}
memcpy(data, bsrc->data, bsrc->l_data); // copy var-len data
*bdst = *bsrc; // copy the rest
// restore the backup
bdst->m_data = m_data;
bdst->data = data;
return bdst;
}
bam1_t *bam_dup1(const bam1_t *bsrc)
{
if (bsrc == NULL) return NULL;
bam1_t *bdst = bam_init1();
if (bdst == NULL) return NULL;
return bam_copy1(bdst, bsrc);
}
int bam_cigar2qlen(int n_cigar, const uint32_t *cigar)
{
int k, l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&1)
l += bam_cigar_oplen(cigar[k]);
return l;
}
int bam_cigar2rlen(int n_cigar, const uint32_t *cigar)
{
int k, l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&2)
l += bam_cigar_oplen(cigar[k]);
return l;
}
int32_t bam_endpos(const bam1_t *b)
{
if (!(b->core.flag & BAM_FUNMAP) && b->core.n_cigar > 0)
return b->core.pos + bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b));
else
return b->core.pos + 1;
}
static inline int aux_type2size(uint8_t type)
{
switch (type) {
case 'A': case 'c': case 'C':
return 1;
case 's': case 'S':
return 2;
case 'i': case 'I': case 'f':
return 4;
case 'd':
return 8;
case 'Z': case 'H': case 'B':
return type;
default:
return 0;
}
}
static void swap_data(const bam1_core_t *c, int l_data, uint8_t *data, int is_host)
{
uint8_t *s;
uint32_t *cigar = (uint32_t*)(data + c->l_qname);
uint32_t i, n;
s = data + c->n_cigar*4 + c->l_qname + c->l_qseq + (c->l_qseq + 1)/2;
for (i = 0; i < c->n_cigar; ++i) ed_swap_4p(&cigar[i]);
while (s < data + l_data) {
int size;
s += 2; // skip key
size = aux_type2size(*s); ++s; // skip type
switch (size) {
case 1: ++s; break;
case 2: ed_swap_2p(s); s += 2; break;
case 4: ed_swap_4p(s); s += 4; break;
case 8: ed_swap_8p(s); s += 8; break;
case 'Z':
case 'H':
while (*s) ++s;
++s;
break;
case 'B':
size = aux_type2size(*s); ++s;
if (is_host) memcpy(&n, s, 4), ed_swap_4p(s);
else ed_swap_4p(s), memcpy(&n, s, 4);
s += 4;
switch (size) {
case 1: s += n; break;
case 2: for (i = 0; i < n; ++i, s += 2) ed_swap_2p(s); break;
case 4: for (i = 0; i < n; ++i, s += 4) ed_swap_4p(s); break;
case 8: for (i = 0; i < n; ++i, s += 8) ed_swap_8p(s); break;
}
break;
}
}
}
int bam_read1(BGZF *fp, bam1_t *b)
{
bam1_core_t *c = &b->core;
int32_t block_len, ret, i;
uint32_t x[8];
if ((ret = bgzf_read(fp, &block_len, 4)) != 4) {
if (ret == 0) return -1; // normal end-of-file
else return -2; // truncated
}
if (bgzf_read(fp, x, 32) != 32) return -3;
if (fp->is_be) {
ed_swap_4p(&block_len);
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
}
c->tid = x[0]; c->pos = x[1];
c->bin = x[2]>>16; c->qual = x[2]>>8&0xff; c->l_qname = x[2]&0xff;
c->flag = x[3]>>16; c->n_cigar = x[3]&0xffff;
c->l_qseq = x[4];
c->mtid = x[5]; c->mpos = x[6]; c->isize = x[7];
b->l_data = block_len - 32;
if (b->l_data < 0 || c->l_qseq < 0 || c->l_qname < 1) return -4;
if ((char *)bam_get_aux(b) - (char *)b->data > b->l_data)
return -4;
if (b->m_data < b->l_data) {
b->m_data = b->l_data;
kroundup32(b->m_data);
b->data = (uint8_t*)realloc(b->data, b->m_data);
if (!b->data)
return -4;
}
if (bgzf_read(fp, b->data, b->l_data) != b->l_data) return -4;
//b->l_aux = b->l_data - c->n_cigar * 4 - c->l_qname - c->l_qseq - (c->l_qseq+1)/2;
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
return 4 + block_len;
}
int bam_write1(BGZF *fp, const bam1_t *b)
{
const bam1_core_t *c = &b->core;
uint32_t x[8], block_len = b->l_data + 32, y;
int i, ok;
x[0] = c->tid;
x[1] = c->pos;
x[2] = (uint32_t)c->bin<<16 | c->qual<<8 | c->l_qname;
x[3] = (uint32_t)c->flag<<16 | c->n_cigar;
x[4] = c->l_qseq;
x[5] = c->mtid;
x[6] = c->mpos;
x[7] = c->isize;
ok = (bgzf_flush_try(fp, 4 + block_len) >= 0);
if (fp->is_be) {
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
y = block_len;
if (ok) ok = (bgzf_write(fp, ed_swap_4p(&y), 4) >= 0);
swap_data(c, b->l_data, b->data, 1);
} else {
if (ok) ok = (bgzf_write(fp, &block_len, 4) >= 0);
}
if (ok) ok = (bgzf_write(fp, x, 32) >= 0);
if (ok) ok = (bgzf_write(fp, b->data, b->l_data) >= 0);
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
return ok? 4 + block_len : -1;
}
/********************
*** BAM indexing ***
********************/
static hts_idx_t *bam_index(BGZF *fp, int min_shift)
{
int n_lvls, i, fmt, ret;
bam1_t *b;
hts_idx_t *idx;
bam_hdr_t *h;
h = bam_hdr_read(fp);
if (h == NULL) return NULL;
if (min_shift > 0) {
int64_t max_len = 0, s;
for (i = 0; i < h->n_targets; ++i)
if (max_len < h->target_len[i]) max_len = h->target_len[i];
max_len += 256;
for (n_lvls = 0, s = 1<<min_shift; max_len > s; ++n_lvls, s <<= 3);
fmt = HTS_FMT_CSI;
} else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_BAI;
idx = hts_idx_init(h->n_targets, fmt, bgzf_tell(fp), min_shift, n_lvls);
bam_hdr_destroy(h);
b = bam_init1();
while ((ret = bam_read1(fp, b)) >= 0) {
ret = hts_idx_push(idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(fp), !(b->core.flag&BAM_FUNMAP));
if (ret < 0) goto err; // unsorted
}
if (ret < -1) goto err; // corrupted BAM file
hts_idx_finish(idx, bgzf_tell(fp));
bam_destroy1(b);
return idx;
err:
bam_destroy1(b);
hts_idx_destroy(idx);
return NULL;
}
int sam_index_build2(const char *fn, const char *fnidx, int min_shift)
{
hts_idx_t *idx;
htsFile *fp;
int ret = 0;
if ((fp = hts_open(fn, "r")) == 0) return -2;
switch (fp->format.format) {
case cram:
ret = cram_index_build(fp->fp.cram, fn, fnidx);
break;
case bam:
idx = bam_index(fp->fp.bgzf, min_shift);
if (idx) {
ret = hts_idx_save_as(idx, fn, fnidx, (min_shift > 0)? HTS_FMT_CSI : HTS_FMT_BAI);
hts_idx_destroy(idx);
}
else ret = -1;
break;
default:
ret = -3;
break;
}
hts_close(fp);
return ret;
}
int sam_index_build(const char *fn, int min_shift)
{
return sam_index_build2(fn, NULL, min_shift);
}
// Provide bam_index_build() symbol for binary compability with earlier HTSlib
#undef bam_index_build
int bam_index_build(const char *fn, int min_shift)
{
return sam_index_build2(fn, NULL, min_shift);
}
static int bam_readrec(BGZF *fp, void *ignored, void *bv, int *tid, int *beg, int *end)
{
bam1_t *b = bv;
int ret;
if ((ret = bam_read1(fp, b)) >= 0) {
*tid = b->core.tid;
*beg = b->core.pos;
*end = bam_endpos(b);
}
return ret;
}
// This is used only with read_rest=1 iterators, so need not set tid/beg/end.
static int cram_readrec(BGZF *ignored, void *fpv, void *bv, int *tid, int *beg, int *end)
{
htsFile *fp = fpv;
bam1_t *b = bv;
return cram_get_bam_seq(fp->fp.cram, &b);
}
// This is used only with read_rest=1 iterators, so need not set tid/beg/end.
static int sam_bam_cram_readrec(BGZF *bgzfp, void *fpv, void *bv, int *tid, int *beg, int *end)
{
htsFile *fp = fpv;
bam1_t *b = bv;
switch (fp->format.format) {
case bam: return bam_read1(bgzfp, b);
case cram: return cram_get_bam_seq(fp->fp.cram, &b);
default:
// TODO Need headers available to implement this for SAM files
fprintf(stderr, "[sam_bam_cram_readrec] Not implemented for SAM files -- Exiting\n");
abort();
}
}
hts_idx_t *sam_index_load2(htsFile *fp, const char *fn, const char *fnidx)
{
switch (fp->format.format) {
case bam:
return fnidx? hts_idx_load2(fn, fnidx) : hts_idx_load(fn, HTS_FMT_BAI);
case cram: {
if (cram_index_load(fp->fp.cram, fn, fnidx) < 0) return NULL;
// Cons up a fake "index" just pointing at the associated cram_fd:
hts_cram_idx_t *idx = malloc(sizeof (hts_cram_idx_t));
if (idx == NULL) return NULL;
idx->fmt = HTS_FMT_CRAI;
idx->cram = fp->fp.cram;
return (hts_idx_t *) idx;
}
default:
return NULL; // TODO Would use tbx_index_load if it returned hts_idx_t
}
}
hts_idx_t *sam_index_load(htsFile *fp, const char *fn)
{
return sam_index_load2(fp, fn, NULL);
}
static hts_itr_t *cram_itr_query(const hts_idx_t *idx, int tid, int beg, int end, hts_readrec_func *readrec)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
hts_itr_t *iter = (hts_itr_t *) calloc(1, sizeof(hts_itr_t));
if (iter == NULL) return NULL;
// Cons up a dummy iterator for which hts_itr_next() will simply invoke
// the readrec function:
iter->read_rest = 1;
iter->off = NULL;
iter->bins.a = NULL;
iter->readrec = readrec;
if (tid >= 0 || tid == HTS_IDX_NOCOOR) {
cram_range r = { tid == HTS_IDX_NOCOOR ? -1 : tid, beg+1, end };
int ret = cram_set_option(cidx->cram, CRAM_OPT_RANGE, &r);
iter->curr_off = 0;
// The following fields are not required by hts_itr_next(), but are
// filled in in case user code wants to look at them.
iter->tid = tid;
iter->beg = beg;
iter->end = end;
switch (ret) {
case 0:
break;
case -2:
// No data vs this ref, so mark iterator as completed.
// Same as HTS_IDX_NONE.
iter->finished = 1;
break;
default:
free(iter);
return NULL;
}
}
else switch (tid) {
case HTS_IDX_REST:
iter->curr_off = 0;
break;
case HTS_IDX_NONE:
iter->curr_off = 0;
iter->finished = 1;
break;
default:
fprintf(stderr, "[cram_itr_query] tid=%d not implemented for CRAM files -- Exiting\n", tid);
abort();
break;
}
return iter;
}
hts_itr_t *sam_itr_queryi(const hts_idx_t *idx, int tid, int beg, int end)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
if (idx == NULL)
return hts_itr_query(NULL, tid, beg, end, sam_bam_cram_readrec);
else if (cidx->fmt == HTS_FMT_CRAI)
return cram_itr_query(idx, tid, beg, end, cram_readrec);
else
return hts_itr_query(idx, tid, beg, end, bam_readrec);
}
static int cram_name2id(void *fdv, const char *ref)
{
cram_fd *fd = (cram_fd *) fdv;
return sam_hdr_name2ref(fd->header, ref);
}
hts_itr_t *sam_itr_querys(const hts_idx_t *idx, bam_hdr_t *hdr, const char *region)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
if (cidx->fmt == HTS_FMT_CRAI)
return hts_itr_querys(idx, region, cram_name2id, cidx->cram, cram_itr_query, cram_readrec);
else
return hts_itr_querys(idx, region, (hts_name2id_f)(bam_name2id), hdr, hts_itr_query, bam_readrec);
}
/**********************
*** SAM header I/O ***
**********************/
#include "htslib/kseq.h"
#include "htslib/kstring.h"
bam_hdr_t *sam_hdr_parse(int l_text, const char *text)
{
const char *q, *r, *p;
khash_t(s2i) *d;
d = kh_init(s2i);
for (p = text; *p; ++p) {
if (strncmp(p, "@SQ\t", 4) == 0) {
char *sn = 0;
int ln = -1;
for (q = p + 4;; ++q) {
if (strncmp(q, "SN:", 3) == 0) {
q += 3;
for (r = q; *r != '\t' && *r != '\n' && *r != '\0'; ++r);
sn = (char*)calloc(r - q + 1, 1);
strncpy(sn, q, r - q);
q = r;
} else if (strncmp(q, "LN:", 3) == 0)
ln = strtol(q + 3, (char**)&q, 10);
while (*q != '\t' && *q != '\n' && *q != '\0') ++q;
if (*q == '\0' || *q == '\n') break;
}
p = q;
if (sn && ln >= 0) {
khint_t k;
int absent;
k = kh_put(s2i, d, sn, &absent);
if (!absent) {
if (hts_verbose >= 2)
fprintf(stderr, "[W::%s] duplicated sequence '%s'\n", __func__, sn);
free(sn);
} else kh_val(d, k) = (int64_t)(kh_size(d) - 1)<<32 | ln;
}
}
while (*p != '\0' && *p != '\n') ++p;
}
return hdr_from_dict(d);
}
bam_hdr_t *sam_hdr_read(htsFile *fp)
{
switch (fp->format.format) {
case bam:
return bam_hdr_read(fp->fp.bgzf);
case cram:
return cram_header_to_bam(fp->fp.cram->header);
case sam: {
kstring_t str;
bam_hdr_t *h;
int has_SQ = 0;
str.l = str.m = 0; str.s = 0;
while (hts_getline(fp, KS_SEP_LINE, &fp->line) >= 0) {
if (fp->line.s[0] != '@') break;
if (fp->line.l > 3 && strncmp(fp->line.s,"@SQ",3) == 0) has_SQ = 1;
kputsn(fp->line.s, fp->line.l, &str);
kputc('\n', &str);
}
if (! has_SQ && fp->fn_aux) {
char line[2048];
FILE *f = fopen(fp->fn_aux, "r");
if (f == NULL) return NULL;
while (fgets(line, sizeof line, f)) {
const char *name = strtok(line, "\t");
const char *length = strtok(NULL, "\t");
ksprintf(&str, "@SQ\tSN:%s\tLN:%s\n", name, length);
}
fclose(f);
}
if (str.l == 0) kputsn("", 0, &str);
h = sam_hdr_parse(str.l, str.s);
h->l_text = str.l; h->text = str.s;
return h;
}
default:
abort();
}
}
int sam_hdr_write(htsFile *fp, const bam_hdr_t *h)
{
switch (fp->format.format) {
case binary_format:
fp->format.category = sequence_data;
fp->format.format = bam;
/* fall-through */
case bam:
bam_hdr_write(fp->fp.bgzf, h);
break;
case cram: {
cram_fd *fd = fp->fp.cram;
SAM_hdr *hdr = bam_header_to_cram((bam_hdr_t *)h);
if (! hdr) return -1;
if (cram_set_header(fd, hdr) < 0) return -1;
if (fp->fn_aux)
cram_load_reference(fd, fp->fn_aux);
if (cram_write_SAM_hdr(fd, fd->header) < 0) return -1;
}
break;
case text_format:
fp->format.category = sequence_data;
fp->format.format = sam;
/* fall-through */
case sam: {
char *p;
hputs(h->text, fp->fp.hfile);
p = strstr(h->text, "@SQ\t"); // FIXME: we need a loop to make sure "@SQ\t" does not match something unwanted!!!
if (p == 0) {
int i;
for (i = 0; i < h->n_targets; ++i) {
fp->line.l = 0;
kputsn("@SQ\tSN:", 7, &fp->line); kputs(h->target_name[i], &fp->line);
kputsn("\tLN:", 4, &fp->line); kputw(h->target_len[i], &fp->line); kputc('\n', &fp->line);
if ( hwrite(fp->fp.hfile, fp->line.s, fp->line.l) != fp->line.l ) return -1;
}
}
if ( hflush(fp->fp.hfile) != 0 ) return -1;
}
break;
default:
abort();
}
return 0;
}
/**********************
*** SAM record I/O ***
**********************/
int sam_parse1(kstring_t *s, bam_hdr_t *h, bam1_t *b)
{
#define _read_token(_p) (_p); for (; *(_p) && *(_p) != '\t'; ++(_p)); if (*(_p) != '\t') goto err_ret; *(_p)++ = 0
#define _read_token_aux(_p) (_p); for (; *(_p) && *(_p) != '\t'; ++(_p)); *(_p)++ = 0 // this is different in that it does not test *(_p)=='\t'
#define _get_mem(type_t, _x, _s, _l) ks_resize((_s), (_s)->l + (_l)); *(_x) = (type_t*)((_s)->s + (_s)->l); (_s)->l += (_l)
#define _parse_err(cond, msg) do { if ((cond) && hts_verbose >= 1) { fprintf(stderr, "[E::%s] " msg "\n", __func__); goto err_ret; } } while (0)
#define _parse_warn(cond, msg) if ((cond) && hts_verbose >= 2) fprintf(stderr, "[W::%s] " msg "\n", __func__)
uint8_t *t;
char *p = s->s, *q;
int i;
kstring_t str;
bam1_core_t *c = &b->core;
str.l = b->l_data = 0;
str.s = (char*)b->data; str.m = b->m_data;
memset(c, 0, 32);
if (h->cigar_tab == 0) {
h->cigar_tab = (int8_t*) malloc(128);
for (i = 0; i < 128; ++i)
h->cigar_tab[i] = -1;
for (i = 0; BAM_CIGAR_STR[i]; ++i)
h->cigar_tab[(int)BAM_CIGAR_STR[i]] = i;
}
// qname
q = _read_token(p);
_parse_warn(p - q <= 1, "empty query name");
_parse_err(p - q > 255, "query name too long");
kputsn_(q, p - q, &str);
c->l_qname = p - q;
// flag
c->flag = strtol(p, &p, 0);
if (*p++ != '\t') goto err_ret; // malformated flag
// chr
q = _read_token(p);
if (strcmp(q, "*")) {
_parse_err(h->n_targets == 0, "missing SAM header");
c->tid = bam_name2id(h, q);
_parse_warn(c->tid < 0, "urecognized reference name; treated as unmapped");
} else c->tid = -1;
// pos
c->pos = strtol(p, &p, 10) - 1;
if (*p++ != '\t') goto err_ret;
if (c->pos < 0 && c->tid >= 0) {
_parse_warn(1, "mapped query cannot have zero coordinate; treated as unmapped");
c->tid = -1;
}
if (c->tid < 0) c->flag |= BAM_FUNMAP;
// mapq
c->qual = strtol(p, &p, 10);
if (*p++ != '\t') goto err_ret;
// cigar
if (*p != '*') {
uint32_t *cigar;
size_t n_cigar = 0;
for (q = p; *p && *p != '\t'; ++p)
if (!isdigit(*p)) ++n_cigar;
if (*p++ != '\t') goto err_ret;
_parse_err(n_cigar == 0, "no CIGAR operations");
_parse_err(n_cigar >= 65536, "too many CIGAR operations");
c->n_cigar = n_cigar;
_get_mem(uint32_t, &cigar, &str, c->n_cigar * sizeof(uint32_t));
for (i = 0; i < c->n_cigar; ++i, ++q) {
int op;
cigar[i] = strtol(q, &q, 10)<<BAM_CIGAR_SHIFT;
op = (uint8_t)*q >= 128? -1 : h->cigar_tab[(int)*q];
_parse_err(op < 0, "unrecognized CIGAR operator");
cigar[i] |= op;
}
// can't use bam_endpos() directly as some fields not yet set up
i = (!(c->flag&BAM_FUNMAP))? bam_cigar2rlen(c->n_cigar, cigar) : 1;
} else {
_parse_warn(!(c->flag&BAM_FUNMAP), "mapped query must have a CIGAR; treated as unmapped");
c->flag |= BAM_FUNMAP;
q = _read_token(p);
i = 1;
}
c->bin = hts_reg2bin(c->pos, c->pos + i, 14, 5);
// mate chr
q = _read_token(p);
if (strcmp(q, "=") == 0) c->mtid = c->tid;
else if (strcmp(q, "*") == 0) c->mtid = -1;
else c->mtid = bam_name2id(h, q);
// mpos
c->mpos = strtol(p, &p, 10) - 1;
if (*p++ != '\t') goto err_ret;
if (c->mpos < 0 && c->mtid >= 0) {
_parse_warn(1, "mapped mate cannot have zero coordinate; treated as unmapped");
c->mtid = -1;
}
// tlen
c->isize = strtol(p, &p, 10);
if (*p++ != '\t') goto err_ret;
// seq
q = _read_token(p);
if (strcmp(q, "*")) {
c->l_qseq = p - q - 1;
i = bam_cigar2qlen(c->n_cigar, (uint32_t*)(str.s + c->l_qname));
_parse_err(c->n_cigar && i != c->l_qseq, "CIGAR and query sequence are of different length");
i = (c->l_qseq + 1) >> 1;
_get_mem(uint8_t, &t, &str, i);
memset(t, 0, i);
for (i = 0; i < c->l_qseq; ++i)
t[i>>1] |= seq_nt16_table[(int)q[i]] << ((~i&1)<<2);
} else c->l_qseq = 0;
// qual
q = _read_token_aux(p);
_get_mem(uint8_t, &t, &str, c->l_qseq);
if (strcmp(q, "*")) {
_parse_err(p - q - 1 != c->l_qseq, "SEQ and QUAL are of different length");
for (i = 0; i < c->l_qseq; ++i) t[i] = q[i] - 33;
} else memset(t, 0xff, c->l_qseq);
// aux
// Note that (like the bam1_core_t fields) this aux data in b->data is
// stored in host endianness; so there is no byte swapping needed here.
while (p < s->s + s->l) {
uint8_t type;
q = _read_token_aux(p); // FIXME: can be accelerated for long 'B' arrays
_parse_err(p - q - 1 < 6, "incomplete aux field");
kputsn_(q, 2, &str);
q += 3; type = *q++; ++q; // q points to value
if (type == 'A' || type == 'a' || type == 'c' || type == 'C') {
kputc_('A', &str);
kputc_(*q, &str);
} else if (type == 'i' || type == 'I') {
if (*q == '-') {
long x = strtol(q, &q, 10);
if (x >= INT8_MIN) {
kputc_('c', &str); kputc_(x, &str);
} else if (x >= INT16_MIN) {
int16_t y = x;
kputc_('s', &str); kputsn_((char*)&y, 2, &str);
} else {
int32_t y = x;
kputc_('i', &str); kputsn_(&y, 4, &str);
}
} else {
unsigned long x = strtoul(q, &q, 10);
if (x <= UINT8_MAX) {
kputc_('C', &str); kputc_(x, &str);
} else if (x <= UINT16_MAX) {
uint16_t y = x;
kputc_('S', &str); kputsn_(&y, 2, &str);
} else {
uint32_t y = x;
kputc_('I', &str); kputsn_(&y, 4, &str);
}
}
} else if (type == 'f') {
float x;
x = strtod(q, &q);
kputc_('f', &str); kputsn_(&x, 4, &str);
} else if (type == 'd') {
double x;
x = strtod(q, &q);
kputc_('d', &str); kputsn_(&x, 8, &str);
} else if (type == 'Z' || type == 'H') {
kputc_(type, &str);kputsn_(q, p - q, &str); // note that this include the trailing NULL
} else if (type == 'B') {
int32_t n;
char *r;
_parse_err(p - q - 1 < 3, "incomplete B-typed aux field");
type = *q++; // q points to the first ',' following the typing byte
for (r = q, n = 0; *r; ++r)
if (*r == ',') ++n;
kputc_('B', &str); kputc_(type, &str); kputsn_(&n, 4, &str);
// FIXME: to evaluate which is faster: a) aligned array and then memmove(); b) unaligned array; c) kputsn_()
if (type == 'c') while (q + 1 < p) { int8_t x = strtol(q + 1, &q, 0); kputc_(x, &str); }
else if (type == 'C') while (q + 1 < p) { uint8_t x = strtoul(q + 1, &q, 0); kputc_(x, &str); }
else if (type == 's') while (q + 1 < p) { int16_t x = strtol(q + 1, &q, 0); kputsn_(&x, 2, &str); }
else if (type == 'S') while (q + 1 < p) { uint16_t x = strtoul(q + 1, &q, 0); kputsn_(&x, 2, &str); }
else if (type == 'i') while (q + 1 < p) { int32_t x = strtol(q + 1, &q, 0); kputsn_(&x, 4, &str); }
else if (type == 'I') while (q + 1 < p) { uint32_t x = strtoul(q + 1, &q, 0); kputsn_(&x, 4, &str); }
else if (type == 'f') while (q + 1 < p) { float x = strtod(q + 1, &q); kputsn_(&x, 4, &str); }