15 #include "sam_header.h"
19 KSTREAM_INIT(gzFile, gzread, 16384)
20 KHASH_MAP_INIT_STR(ref, uint64_t)
22 void bam_init_header_hash(bam_header_t *header);
23 void bam_destroy_header_hash(bam_header_t *header);
24 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
26 unsigned char bam_nt16_table[256] = {
27 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
28 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
29 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
30 1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,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, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
34 15,15, 5, 6, 8,15, 7, 9, 15,10,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,
41 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
42 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15
45 unsigned short bam_char2flag_table[256] = {
46 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
47 0,0,0,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 0,BAM_FREAD1,BAM_FREAD2,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
50 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
51 BAM_FPROPER_PAIR,0,BAM_FMREVERSE,0, 0,BAM_FMUNMAP,0,0, 0,0,0,0, 0,0,0,0,
52 0,0,0,0, BAM_FDUP,0,BAM_FQCFAIL,0, 0,0,0,0, 0,0,0,0,
53 BAM_FPAIRED,0,BAM_FREVERSE,BAM_FSECONDARY, 0,BAM_FUNMAP,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,
60 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
61 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
64 char *bam_nt16_rev_table = "=ACMGRSVTWYHKDBN";
74 char **__bam_get_lines(const char *fn, int *_n) // for bam_plcmd.c only
77 int n = 0, dret, m = 0;
78 gzFile fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
81 str = (kstring_t*)calloc(1, sizeof(kstring_t));
83 while (ks_getuntil(ks, '\n', str, &dret) > 0) {
86 list = (char**)realloc(list, m * sizeof(char*));
88 if (str->s[str->l-1] == '\r')
89 str->s[--str->l] = '\0';
90 s = list[n++] = (char*)calloc(str->l + 1, 1);
95 free(str->s); free(str);
100 static bam_header_t *hash2header(const kh_ref_t *hash)
102 bam_header_t *header;
104 header = bam_header_init();
105 header->n_targets = kh_size(hash);
106 header->target_name = (char**)calloc(kh_size(hash), sizeof(char*));
107 header->target_len = (uint32_t*)calloc(kh_size(hash), 4);
108 for (k = kh_begin(hash); k != kh_end(hash); ++k) {
109 if (kh_exist(hash, k)) {
110 int i = (int)kh_value(hash, k);
111 header->target_name[i] = (char*)kh_key(hash, k);
112 header->target_len[i] = kh_value(hash, k)>>32;
115 bam_init_header_hash(header);
118 bam_header_t *sam_header_read2(const char *fn)
120 bam_header_t *header;
121 int c, dret, ret, error = 0;
127 if (fn == 0) return 0;
128 fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
129 if (fp == 0) return 0;
132 str = (kstring_t*)calloc(1, sizeof(kstring_t));
133 while (ks_getuntil(ks, 0, str, &dret) > 0) {
134 char *s = strdup(str->s);
137 ks_getuntil(ks, 0, str, &dret);
139 k = kh_put(ref, hash, s, &ret);
141 fprintf(pysamerr, "[sam_header_read2] duplicated sequence name: %s\n", s);
144 kh_value(hash, k) = (uint64_t)len<<32 | i;
146 while ((c = ks_getc(ks)) != '\n' && c != -1);
150 free(str->s); free(str);
151 fprintf(pysamerr, "[sam_header_read2] %d sequences loaded.\n", kh_size(hash));
153 header = hash2header(hash);
154 kh_destroy(ref, hash);
157 static inline uint8_t *alloc_data(bam1_t *b, int size)
159 if (b->m_data < size) {
161 kroundup32(b->m_data);
162 b->data = (uint8_t*)realloc(b->data, b->m_data);
166 static inline void parse_error(int64_t n_lines, const char * __restrict msg)
168 fprintf(pysamerr, "Parse error at line %lld: %s\n", (long long)n_lines, msg);
171 static inline void append_text(bam_header_t *header, kstring_t *str)
173 size_t x = header->l_text, y = header->l_text + str->l + 2; // 2 = 1 byte dret + 1 byte null
174 kroundup32(x); kroundup32(y);
178 header->text = (char*)realloc(header->text, y);
181 fprintf(pysamerr,"realloc failed to alloc %ld bytes\n", y);
186 if ( header->l_text+str->l+1 >= header->n_text )
188 fprintf(pysamerr,"append_text FIXME: %ld>=%ld, x=%ld,y=%ld\n", header->l_text+str->l+1,header->n_text,x,y);
191 strncpy(header->text + header->l_text, str->s, str->l+1); // we cannot use strcpy() here.
192 header->l_text += str->l + 1;
193 header->text[header->l_text] = 0;
196 int sam_header_parse(bam_header_t *h)
200 free(h->target_len); free(h->target_name);
201 h->n_targets = 0; h->target_len = 0; h->target_name = 0;
202 if (h->l_text < 3) return 0;
203 if (h->dict == 0) h->dict = sam_header_parse2(h->text);
204 tmp = sam_header2list(h->dict, "SQ", "SN", &h->n_targets);
205 if (h->n_targets == 0) return 0;
206 h->target_name = calloc(h->n_targets, sizeof(void*));
207 for (i = 0; i < h->n_targets; ++i)
208 h->target_name[i] = strdup(tmp[i]);
210 tmp = sam_header2list(h->dict, "SQ", "LN", &h->n_targets);
211 h->target_len = calloc(h->n_targets, 4);
212 for (i = 0; i < h->n_targets; ++i)
213 h->target_len[i] = atoi(tmp[i]);
218 bam_header_t *sam_header_read(tamFile fp)
221 bam_header_t *header = bam_header_init();
222 kstring_t *str = fp->str;
223 while ((ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret)) >= 0 && str->s[0] == '@') { // skip header
224 str->s[str->l] = dret; // note that str->s is NOT null terminated!!
225 append_text(header, str);
227 ret = ks_getuntil(fp->ks, '\n', str, &dret);
228 str->s[str->l] = '\n'; // NOT null terminated!!
229 append_text(header, str);
233 sam_header_parse(header);
234 bam_init_header_hash(header);
239 int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b)
241 int ret, doff, doff0, dret, z = 0;
242 bam1_core_t *c = &b->core;
243 kstring_t *str = fp->str;
244 kstream_t *ks = fp->ks;
250 do { // special consideration for empty lines
251 ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret);
252 if (ret >= 0) z += str->l + 1;
255 if (ret < 0) return -1;
260 c->l_qname = strlen(str->s) + 1;
261 memcpy(alloc_data(b, doff + c->l_qname) + doff, str->s, c->l_qname);
267 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
268 flag = strtol((char*)str->s, &s, 0);
269 if (*s) { // not the end of the string
271 for (s = str->s; *s; ++s)
272 flag |= bam_char2flag_table[(int)*s];
277 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->tid = bam_get_tid(header, str->s);
278 if (c->tid < 0 && strcmp(str->s, "*")) {
279 if (header->n_targets == 0) {
280 fprintf(pysamerr, "[sam_read1] missing header? Abort!\n");
282 } else fprintf(pysamerr, "[sam_read1] reference '%s' is recognized as '*'.\n", str->s);
284 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->pos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
285 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->qual = isdigit(str->s[0])? atoi(str->s) : 0;
286 if (ret < 0) return -2;
293 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -3;
295 if (str->s[0] != '*') {
296 for (s = str->s; *s; ++s) {
297 if ((isalpha(*s)) || (*s=='=')) ++c->n_cigar;
298 else if (!isdigit(*s)) parse_error(fp->n_lines, "invalid CIGAR character");
300 b->data = alloc_data(b, doff + c->n_cigar * 4);
301 for (i = 0, s = str->s; i != c->n_cigar; ++i) {
302 x = strtol(s, &t, 10);
304 if (op == 'M') op = BAM_CMATCH;
305 else if (op == 'I') op = BAM_CINS;
306 else if (op == 'D') op = BAM_CDEL;
307 else if (op == 'N') op = BAM_CREF_SKIP;
308 else if (op == 'S') op = BAM_CSOFT_CLIP;
309 else if (op == 'H') op = BAM_CHARD_CLIP;
310 else if (op == 'P') op = BAM_CPAD;
311 else if (op == '=') op = BAM_CEQUAL;
312 else if (op == 'X') op = BAM_CDIFF;
313 else parse_error(fp->n_lines, "invalid CIGAR operation");
315 bam1_cigar(b)[i] = x << BAM_CIGAR_SHIFT | op;
317 if (*s) parse_error(fp->n_lines, "unmatched CIGAR operation");
318 c->bin = bam_reg2bin(c->pos, bam_calend(c, bam1_cigar(b)));
319 doff += c->n_cigar * 4;
321 if (!(c->flag&BAM_FUNMAP)) {
322 fprintf(pysamerr, "Parse warning at line %lld: mapped sequence without CIGAR\n", (long long)fp->n_lines);
323 c->flag |= BAM_FUNMAP;
325 c->bin = bam_reg2bin(c->pos, c->pos + 1);
328 { // mtid, mpos, isize
329 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
330 c->mtid = strcmp(str->s, "=")? bam_get_tid(header, str->s) : c->tid;
331 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
332 c->mpos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
333 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
334 c->isize = (str->s[0] == '-' || isdigit(str->s[0]))? atoi(str->s) : 0;
335 if (ret < 0) return -4;
340 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -5; // seq
342 if (strcmp(str->s, "*")) {
343 c->l_qseq = strlen(str->s);
344 if (c->n_cigar && c->l_qseq != (int32_t)bam_cigar2qlen(c, bam1_cigar(b))) {
345 fprintf(pysamerr, "Line %ld, sequence length %i vs %i from CIGAR\n",
346 (long)fp->n_lines, c->l_qseq, (int32_t)bam_cigar2qlen(c, bam1_cigar(b)));
347 parse_error(fp->n_lines, "CIGAR and sequence length are inconsistent");
349 p = (uint8_t*)alloc_data(b, doff + c->l_qseq + (c->l_qseq+1)/2) + doff;
350 memset(p, 0, (c->l_qseq+1)/2);
351 for (i = 0; i < c->l_qseq; ++i)
352 p[i/2] |= bam_nt16_table[(int)str->s[i]] << 4*(1-i%2);
353 } else c->l_qseq = 0;
354 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -6; // qual
356 if (strcmp(str->s, "*") && c->l_qseq != strlen(str->s))
357 parse_error(fp->n_lines, "sequence and quality are inconsistent");
358 p += (c->l_qseq+1)/2;
359 if (strcmp(str->s, "*") == 0) for (i = 0; i < c->l_qseq; ++i) p[i] = 0xff;
360 else for (i = 0; i < c->l_qseq; ++i) p[i] = str->s[i] - 33;
361 doff += c->l_qseq + (c->l_qseq+1)/2;
364 if (dret != '\n' && dret != '\r') { // aux
365 while (ks_getuntil(ks, KS_SEP_TAB, str, &dret) >= 0) {
366 uint8_t *s, type, key[2];
368 if (str->l < 6 || str->s[2] != ':' || str->s[4] != ':')
369 parse_error(fp->n_lines, "missing colon in auxiliary data");
370 key[0] = str->s[0]; key[1] = str->s[1];
372 s = alloc_data(b, doff + 3) + doff;
373 s[0] = key[0]; s[1] = key[1]; s += 2; doff += 2;
374 if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { // c and C for backward compatibility
375 s = alloc_data(b, doff + 2) + doff;
376 *s++ = 'A'; *s = str->s[5];
378 } else if (type == 'I' || type == 'i') {
380 s = alloc_data(b, doff + 5) + doff;
381 x = (long long)atoll(str->s + 5);
384 *s++ = 'c'; *(int8_t*)s = (int8_t)x;
386 } else if (x >= -32767) {
387 *s++ = 's'; *(int16_t*)s = (int16_t)x;
390 *s++ = 'i'; *(int32_t*)s = (int32_t)x;
392 if (x < -2147483648ll)
393 fprintf(pysamerr, "Parse warning at line %lld: integer %lld is out of range.",
394 (long long)fp->n_lines, x);
398 *s++ = 'C'; *s++ = (uint8_t)x;
400 } else if (x <= 65535) {
401 *s++ = 'S'; *(uint16_t*)s = (uint16_t)x;
404 *s++ = 'I'; *(uint32_t*)s = (uint32_t)x;
406 if (x > 4294967295ll)
407 fprintf(pysamerr, "Parse warning at line %lld: integer %lld is out of range.",
408 (long long)fp->n_lines, x);
411 } else if (type == 'f') {
412 s = alloc_data(b, doff + 5) + doff;
414 *(float*)s = (float)atof(str->s + 5);
416 } else if (type == 'd') {
417 s = alloc_data(b, doff + 9) + doff;
419 *(float*)s = (float)atof(str->s + 9);
421 } else if (type == 'Z' || type == 'H') {
422 int size = 1 + (str->l - 5) + 1;
423 if (type == 'H') { // check whether the hex string is valid
425 if ((str->l - 5) % 2 == 1) parse_error(fp->n_lines, "length of the hex string not even");
426 for (i = 0; i < str->l - 5; ++i) {
427 int c = toupper(str->s[5 + i]);
428 if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')))
429 parse_error(fp->n_lines, "invalid hex character");
432 s = alloc_data(b, doff + size) + doff;
434 memcpy(s, str->s + 5, str->l - 5);
437 } else if (type == 'B') {
438 int32_t n = 0, Bsize, k = 0, size;
440 if (str->l < 8) parse_error(fp->n_lines, "too few values in aux type B");
441 Bsize = bam_aux_type2size(str->s[5]); // the size of each element
442 for (p = (char*)str->s + 6; *p; ++p) // count the number of elements in the array
444 p = str->s + 7; // now p points to the first number in the array
445 size = 6 + Bsize * n; // total number of bytes allocated to this tag
446 s = alloc_data(b, doff + 6 * Bsize * n) + doff; // allocate memory
447 *s++ = 'B'; *s++ = str->s[5];
448 memcpy(s, &n, 4); s += 4; // write the number of elements
449 if (str->s[5] == 'c') while (p < str->s + str->l) ((int8_t*)s)[k++] = (int8_t)strtol(p, &p, 0), ++p;
450 else if (str->s[5] == 'C') while (p < str->s + str->l) ((uint8_t*)s)[k++] = (uint8_t)strtol(p, &p, 0), ++p;
451 else if (str->s[5] == 's') while (p < str->s + str->l) ((int16_t*)s)[k++] = (int16_t)strtol(p, &p, 0), ++p; // FIXME: avoid unaligned memory
452 else if (str->s[5] == 'S') while (p < str->s + str->l) ((uint16_t*)s)[k++] = (uint16_t)strtol(p, &p, 0), ++p;
453 else if (str->s[5] == 'i') while (p < str->s + str->l) ((int32_t*)s)[k++] = (int32_t)strtol(p, &p, 0), ++p;
454 else if (str->s[5] == 'I') while (p < str->s + str->l) ((uint32_t*)s)[k++] = (uint32_t)strtol(p, &p, 0), ++p;
455 else if (str->s[5] == 'f') while (p < str->s + str->l) ((float*)s)[k++] = (float)strtod(p, &p), ++p;
456 else parse_error(fp->n_lines, "unrecognized array type");
457 s += Bsize * n; doff += size;
458 } else parse_error(fp->n_lines, "unrecognized type");
459 if (dret == '\n' || dret == '\r') break;
462 b->l_aux = doff - doff0;
467 tamFile sam_open(const char *fn)
470 gzFile gzfp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "rb") : gzopen(fn, "rb");
471 if (gzfp == 0) return 0;
472 fp = (tamFile)calloc(1, sizeof(struct __tamFile_t));
473 fp->str = (kstring_t*)calloc(1, sizeof(kstring_t));
475 fp->ks = ks_init(fp->fp);
479 void sam_close(tamFile fp)
484 free(fp->str->s); free(fp->str);