13 #include "sam_header.h"
17 KSTREAM_INIT(gzFile, gzread, 8192)
18 KHASH_MAP_INIT_STR(ref, uint64_t)
20 void bam_init_header_hash(bam_header_t *header);
21 void bam_destroy_header_hash(bam_header_t *header);
22 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
24 unsigned char bam_nt16_table[256] = {
25 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
26 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
27 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
28 1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15,
29 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
30 15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15,
31 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
32 15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15,
33 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
34 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
35 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
36 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
37 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
38 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
39 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
40 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15
43 unsigned short bam_char2flag_table[256] = {
44 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
45 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
46 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
47 0,BAM_FREAD1,BAM_FREAD2,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
48 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
49 BAM_FPROPER_PAIR,0,BAM_FMREVERSE,0, 0,BAM_FMUNMAP,0,0, 0,0,0,0, 0,0,0,0,
50 0,0,0,0, BAM_FDUP,0,BAM_FQCFAIL,0, 0,0,0,0, 0,0,0,0,
51 BAM_FPAIRED,0,BAM_FREVERSE,BAM_FSECONDARY, 0,BAM_FUNMAP,0,0, 0,0,0,0, 0,0,0,0,
52 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
53 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
54 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
55 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
56 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
57 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
58 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
59 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
62 char *bam_nt16_rev_table = "=ACMGRSVTWYHKDBN";
72 char **__bam_get_lines(const char *fn, int *_n) // for bam_plcmd.c only
75 int n = 0, dret, m = 0;
76 gzFile fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
79 str = (kstring_t*)calloc(1, sizeof(kstring_t));
81 while (ks_getuntil(ks, '\n', str, &dret) > 0) {
84 list = (char**)realloc(list, m * sizeof(char*));
86 if (str->s[str->l-1] == '\r')
87 str->s[--str->l] = '\0';
88 s = list[n++] = (char*)calloc(str->l + 1, 1);
93 free(str->s); free(str);
98 static bam_header_t *hash2header(const kh_ref_t *hash)
100 bam_header_t *header;
102 header = bam_header_init();
103 header->n_targets = kh_size(hash);
104 header->target_name = (char**)calloc(kh_size(hash), sizeof(char*));
105 header->target_len = (uint32_t*)calloc(kh_size(hash), 4);
106 for (k = kh_begin(hash); k != kh_end(hash); ++k) {
107 if (kh_exist(hash, k)) {
108 int i = (int)kh_value(hash, k);
109 header->target_name[i] = (char*)kh_key(hash, k);
110 header->target_len[i] = kh_value(hash, k)>>32;
113 bam_init_header_hash(header);
116 bam_header_t *sam_header_read2(const char *fn)
118 bam_header_t *header;
125 if (fn == 0) return 0;
126 fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
127 if (fp == 0) return 0;
130 str = (kstring_t*)calloc(1, sizeof(kstring_t));
131 while (ks_getuntil(ks, 0, str, &dret) > 0) {
132 char *s = strdup(str->s);
135 ks_getuntil(ks, 0, str, &dret);
137 k = kh_put(ref, hash, s, &ret);
138 kh_value(hash, k) = (uint64_t)len<<32 | i;
140 while ((c = ks_getc(ks)) != '\n' && c != -1);
144 free(str->s); free(str);
145 fprintf(stderr, "[sam_header_read2] %d sequences loaded.\n", kh_size(hash));
146 header = hash2header(hash);
147 kh_destroy(ref, hash);
150 static inline uint8_t *alloc_data(bam1_t *b, int size)
152 if (b->m_data < size) {
154 kroundup32(b->m_data);
155 b->data = (uint8_t*)realloc(b->data, b->m_data);
159 static inline void parse_error(int64_t n_lines, const char * __restrict msg)
161 fprintf(stderr, "Parse error at line %lld: %s\n", (long long)n_lines, msg);
164 static inline void append_text(bam_header_t *header, kstring_t *str)
166 int x = header->l_text, y = header->l_text + str->l + 2; // 2 = 1 byte dret + 1 byte null
167 kroundup32(x); kroundup32(y);
168 if (x < y) header->text = (char*)realloc(header->text, y);
169 strncpy(header->text + header->l_text, str->s, str->l+1); // we cannot use strcpy() here.
170 header->l_text += str->l + 1;
171 header->text[header->l_text] = 0;
174 int sam_header_parse_rg(bam_header_t *h)
176 if (h->dict == 0) h->dict = sam_header_parse2(h->text);
177 if (h->rg2lib) h->rg2lib = sam_header2tbl(h->dict, "RG", "ID", "LB");
178 return sam_tbl_size(h->rg2lib);
181 int sam_header_parse(bam_header_t *h)
186 free(h->target_len); free(h->target_name);
187 h->n_targets = 0; h->target_len = 0; h->target_name = 0;
188 if (h->l_text < 3) return 0;
189 if (h->dict == 0) h->dict = sam_header_parse2(h->text);
190 tbl = sam_header2tbl(h->dict, "SQ", "SN", "LN");
191 h->n_targets = sam_tbl_size(tbl);
192 if (h->n_targets == 0) {
193 sam_tbl_destroy(tbl);
196 h->target_len = (uint32_t*)calloc(h->n_targets, 4);
197 h->target_name = (char**)calloc(h->n_targets, sizeof(void*));
198 tmp = (char**)calloc(h->n_targets, sizeof(void*));
199 sam_tbl_pair(tbl, h->target_name, tmp);
200 for (i = 0; i < h->n_targets; ++i)
201 h->target_len[i] = atoi(tmp[i]);
203 sam_tbl_destroy(tbl);
207 bam_header_t *sam_header_read(tamFile fp)
210 bam_header_t *header = bam_header_init();
211 kstring_t *str = fp->str;
212 while ((ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret)) >= 0 && str->s[0] == '@') { // skip header
213 str->s[str->l] = dret; // note that str->s is NOT null terminated!!
214 append_text(header, str);
216 ret = ks_getuntil(fp->ks, '\n', str, &dret);
217 str->s[str->l] = '\n'; // NOT null terminated!!
218 append_text(header, str);
222 sam_header_parse(header);
223 bam_init_header_hash(header);
228 int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b)
230 int ret, doff, doff0, dret, z = 0;
231 bam1_core_t *c = &b->core;
232 kstring_t *str = fp->str;
233 kstream_t *ks = fp->ks;
239 do { // special consideration for empty lines
240 ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret);
241 if (ret >= 0) z += str->l + 1;
244 if (ret < 0) return -1;
249 c->l_qname = strlen(str->s) + 1;
250 memcpy(alloc_data(b, doff + c->l_qname) + doff, str->s, c->l_qname);
256 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
257 flag = strtol((char*)str->s, &s, 0);
258 if (*s) { // not the end of the string
260 for (s = str->s; *s; ++s)
261 flag |= bam_char2flag_table[(int)*s];
266 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->tid = bam_get_tid(header, str->s);
267 if (c->tid < 0 && strcmp(str->s, "*")) {
268 if (header->n_targets == 0) {
269 fprintf(stderr, "[sam_read1] missing header? Abort!\n");
271 } else fprintf(stderr, "[sam_read1] reference '%s' is recognized as '*'.\n", str->s);
273 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->pos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
274 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->qual = isdigit(str->s[0])? atoi(str->s) : 0;
275 if (ret < 0) return -2;
282 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -3;
284 if (str->s[0] != '*') {
285 for (s = str->s; *s; ++s) {
286 if (isalpha(*s)) ++c->n_cigar;
287 else if (!isdigit(*s)) parse_error(fp->n_lines, "invalid CIGAR character");
289 b->data = alloc_data(b, doff + c->n_cigar * 4);
290 for (i = 0, s = str->s; i != c->n_cigar; ++i) {
291 x = strtol(s, &t, 10);
293 if (op == 'M' || op == '=' || op == 'X') op = BAM_CMATCH;
294 else if (op == 'I') op = BAM_CINS;
295 else if (op == 'D') op = BAM_CDEL;
296 else if (op == 'N') op = BAM_CREF_SKIP;
297 else if (op == 'S') op = BAM_CSOFT_CLIP;
298 else if (op == 'H') op = BAM_CHARD_CLIP;
299 else if (op == 'P') op = BAM_CPAD;
300 else parse_error(fp->n_lines, "invalid CIGAR operation");
302 bam1_cigar(b)[i] = x << BAM_CIGAR_SHIFT | op;
304 if (*s) parse_error(fp->n_lines, "unmatched CIGAR operation");
305 c->bin = bam_reg2bin(c->pos, bam_calend(c, bam1_cigar(b)));
306 doff += c->n_cigar * 4;
308 if (!(c->flag&BAM_FUNMAP)) {
309 fprintf(stderr, "Parse warning at line %lld: mapped sequence without CIGAR\n", (long long)fp->n_lines);
310 c->flag |= BAM_FUNMAP;
312 c->bin = bam_reg2bin(c->pos, c->pos + 1);
315 { // mtid, mpos, isize
316 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
317 c->mtid = strcmp(str->s, "=")? bam_get_tid(header, str->s) : c->tid;
318 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
319 c->mpos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
320 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
321 c->isize = (str->s[0] == '-' || isdigit(str->s[0]))? atoi(str->s) : 0;
322 if (ret < 0) return -4;
327 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -5; // seq
329 if (strcmp(str->s, "*")) {
330 c->l_qseq = strlen(str->s);
331 if (c->n_cigar && c->l_qseq != (int32_t)bam_cigar2qlen(c, bam1_cigar(b)))
332 parse_error(fp->n_lines, "CIGAR and sequence length are inconsistent");
333 p = (uint8_t*)alloc_data(b, doff + c->l_qseq + (c->l_qseq+1)/2) + doff;
334 memset(p, 0, (c->l_qseq+1)/2);
335 for (i = 0; i < c->l_qseq; ++i)
336 p[i/2] |= bam_nt16_table[(int)str->s[i]] << 4*(1-i%2);
337 } else c->l_qseq = 0;
338 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -6; // qual
340 if (strcmp(str->s, "*") && c->l_qseq != strlen(str->s))
341 parse_error(fp->n_lines, "sequence and quality are inconsistent");
342 p += (c->l_qseq+1)/2;
343 if (strcmp(str->s, "*") == 0) for (i = 0; i < c->l_qseq; ++i) p[i] = 0xff;
344 else for (i = 0; i < c->l_qseq; ++i) p[i] = str->s[i] - 33;
345 doff += c->l_qseq + (c->l_qseq+1)/2;
348 if (dret != '\n' && dret != '\r') { // aux
349 while (ks_getuntil(ks, KS_SEP_TAB, str, &dret) >= 0) {
350 uint8_t *s, type, key[2];
352 if (str->l < 6 || str->s[2] != ':' || str->s[4] != ':')
353 parse_error(fp->n_lines, "missing colon in auxiliary data");
354 key[0] = str->s[0]; key[1] = str->s[1];
356 s = alloc_data(b, doff + 3) + doff;
357 s[0] = key[0]; s[1] = key[1]; s += 2; doff += 2;
358 if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { // c and C for backward compatibility
359 s = alloc_data(b, doff + 2) + doff;
360 *s++ = 'A'; *s = str->s[5];
362 } else if (type == 'I' || type == 'i') {
364 s = alloc_data(b, doff + 5) + doff;
365 x = (long long)atoll(str->s + 5);
368 *s++ = 'c'; *(int8_t*)s = (int8_t)x;
370 } else if (x >= -32767) {
371 *s++ = 's'; *(int16_t*)s = (int16_t)x;
374 *s++ = 'i'; *(int32_t*)s = (int32_t)x;
376 if (x < -2147483648ll)
377 fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
378 (long long)fp->n_lines, x);
382 *s++ = 'C'; *s++ = (uint8_t)x;
384 } else if (x <= 65535) {
385 *s++ = 'S'; *(uint16_t*)s = (uint16_t)x;
388 *s++ = 'I'; *(uint32_t*)s = (uint32_t)x;
390 if (x > 4294967295ll)
391 fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
392 (long long)fp->n_lines, x);
395 } else if (type == 'f') {
396 s = alloc_data(b, doff + 5) + doff;
398 *(float*)s = (float)atof(str->s + 5);
400 } else if (type == 'd') {
401 s = alloc_data(b, doff + 9) + doff;
403 *(float*)s = (float)atof(str->s + 9);
405 } else if (type == 'Z' || type == 'H') {
406 int size = 1 + (str->l - 5) + 1;
407 if (type == 'H') { // check whether the hex string is valid
409 if ((str->l - 5) % 2 == 1) parse_error(fp->n_lines, "length of the hex string not even");
410 for (i = 0; i < str->l - 5; ++i) {
411 int c = toupper(str->s[5 + i]);
412 if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')))
413 parse_error(fp->n_lines, "invalid hex character");
416 s = alloc_data(b, doff + size) + doff;
418 memcpy(s, str->s + 5, str->l - 5);
421 } else parse_error(fp->n_lines, "unrecognized type");
422 if (dret == '\n' || dret == '\r') break;
425 b->l_aux = doff - doff0;
430 tamFile sam_open(const char *fn)
433 gzFile gzfp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "rb") : gzopen(fn, "rb");
434 if (gzfp == 0) return 0;
435 fp = (tamFile)calloc(1, sizeof(struct __tamFile_t));
436 fp->str = (kstring_t*)calloc(1, sizeof(kstring_t));
438 fp->ks = ks_init(fp->fp);
442 void sam_close(tamFile fp)
447 free(fp->str->s); free(fp->str);