Imported Upstream version 0.1.7~dfsg
[samtools.git] / bam_import.c
1 #include <zlib.h>
2 #include <stdio.h>
3 #include <ctype.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <assert.h>
8 #ifdef _WIN32
9 #include <fcntl.h>
10 #endif
11 #include "kstring.h"
12 #include "bam.h"
13 #include "sam_header.h"
14 #include "kseq.h"
15 #include "khash.h"
16
17 KSTREAM_INIT(gzFile, gzread, 8192)
18 KHASH_MAP_INIT_STR(ref, uint64_t)
19
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);
23
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
41 };
42
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
60 };
61
62 char *bam_nt16_rev_table = "=ACMGRSVTWYHKDBN";
63
64 struct __tamFile_t {
65         gzFile fp;
66         kstream_t *ks;
67         kstring_t *str;
68         uint64_t n_lines;
69         int is_first;
70 };
71
72 char **__bam_get_lines(const char *fn, int *_n) // for bam_plcmd.c only
73 {
74         char **list = 0, *s;
75         int n = 0, dret, m = 0;
76         gzFile fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
77         kstream_t *ks;
78         kstring_t *str;
79         str = (kstring_t*)calloc(1, sizeof(kstring_t));
80         ks = ks_init(fp);
81         while (ks_getuntil(ks, '\n', str, &dret) > 0) {
82                 if (n == m) {
83                         m = m? m << 1 : 16;
84                         list = (char**)realloc(list, m * sizeof(char*));
85                 }
86                 if (str->s[str->l-1] == '\r')
87                         str->s[--str->l] = '\0';
88                 s = list[n++] = (char*)calloc(str->l + 1, 1);
89                 strcpy(s, str->s);
90         }
91         ks_destroy(ks);
92         gzclose(fp);
93         free(str->s); free(str);
94         *_n = n;
95         return list;
96 }
97
98 static bam_header_t *hash2header(const kh_ref_t *hash)
99 {
100         bam_header_t *header;
101         khiter_t k;
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;
111                 }
112         }
113         bam_init_header_hash(header);
114         return header;
115 }
116 bam_header_t *sam_header_read2(const char *fn)
117 {
118         bam_header_t *header;
119         int c, dret, ret;
120         gzFile fp;
121         kstream_t *ks;
122         kstring_t *str;
123         kh_ref_t *hash;
124         khiter_t k;
125         if (fn == 0) return 0;
126         fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
127         if (fp == 0) return 0;
128         hash = kh_init(ref);
129         ks = ks_init(fp);
130         str = (kstring_t*)calloc(1, sizeof(kstring_t));
131         while (ks_getuntil(ks, 0, str, &dret) > 0) {
132                 char *s = strdup(str->s);
133                 int len, i;
134                 i = kh_size(hash);
135                 ks_getuntil(ks, 0, str, &dret);
136                 len = atoi(str->s);
137                 k = kh_put(ref, hash, s, &ret);
138                 kh_value(hash, k) = (uint64_t)len<<32 | i;
139                 if (dret != '\n')
140                         while ((c = ks_getc(ks)) != '\n' && c != -1);
141         }
142         ks_destroy(ks);
143         gzclose(fp);
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);
148         return header;
149 }
150 static inline uint8_t *alloc_data(bam1_t *b, int size)
151 {
152         if (b->m_data < size) {
153                 b->m_data = size;
154                 kroundup32(b->m_data);
155                 b->data = (uint8_t*)realloc(b->data, b->m_data);
156         }
157         return b->data;
158 }
159 static inline void parse_error(int64_t n_lines, const char * __restrict msg)
160 {
161         fprintf(stderr, "Parse error at line %lld: %s\n", (long long)n_lines, msg);
162         abort();
163 }
164 static inline void append_text(bam_header_t *header, kstring_t *str)
165 {
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;
172 }
173
174 int sam_header_parse(bam_header_t *h)
175 {
176         char **tmp;
177         int i;
178         free(h->target_len); free(h->target_name);
179         h->n_targets = 0; h->target_len = 0; h->target_name = 0;
180         if (h->l_text < 3) return 0;
181         if (h->dict == 0) h->dict = sam_header_parse2(h->text);
182         tmp = sam_header2list(h->dict, "SQ", "SN", &h->n_targets);
183         if (h->n_targets == 0) return 0;
184         h->target_name = calloc(h->n_targets, sizeof(void*));
185         for (i = 0; i < h->n_targets; ++i)
186                 h->target_name[i] = strdup(tmp[i]);
187         free(tmp);
188         tmp = sam_header2list(h->dict, "SQ", "LN", &h->n_targets);
189         h->target_len = calloc(h->n_targets, 4);
190         for (i = 0; i < h->n_targets; ++i)
191                 h->target_len[i] = atoi(tmp[i]);
192         free(tmp);
193         return h->n_targets;
194 }
195
196 bam_header_t *sam_header_read(tamFile fp)
197 {
198         int ret, dret;
199         bam_header_t *header = bam_header_init();
200         kstring_t *str = fp->str;
201         while ((ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret)) >= 0 && str->s[0] == '@') { // skip header
202                 str->s[str->l] = dret; // note that str->s is NOT null terminated!!
203                 append_text(header, str);
204                 if (dret != '\n') {
205                         ret = ks_getuntil(fp->ks, '\n', str, &dret);
206                         str->s[str->l] = '\n'; // NOT null terminated!!
207                         append_text(header, str);
208                 }
209                 ++fp->n_lines;
210         }
211         sam_header_parse(header);
212         bam_init_header_hash(header);
213         fp->is_first = 1;
214         return header;
215 }
216
217 int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b)
218 {
219         int ret, doff, doff0, dret, z = 0;
220         bam1_core_t *c = &b->core;
221         kstring_t *str = fp->str;
222         kstream_t *ks = fp->ks;
223
224         if (fp->is_first) {
225                 fp->is_first = 0;
226                 ret = str->l;
227         } else {
228                 do { // special consideration for empty lines
229                         ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret);
230                         if (ret >= 0) z += str->l + 1;
231                 } while (ret == 0);
232         }
233         if (ret < 0) return -1;
234         ++fp->n_lines;
235         doff = 0;
236
237         { // name
238                 c->l_qname = strlen(str->s) + 1;
239                 memcpy(alloc_data(b, doff + c->l_qname) + doff, str->s, c->l_qname);
240                 doff += c->l_qname;
241         }
242         { // flag
243                 long flag;
244                 char *s;
245                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
246                 flag = strtol((char*)str->s, &s, 0);
247                 if (*s) { // not the end of the string
248                         flag = 0;
249                         for (s = str->s; *s; ++s)
250                                 flag |= bam_char2flag_table[(int)*s];
251                 }
252                 c->flag = flag;
253         }
254         { // tid, pos, qual
255                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->tid = bam_get_tid(header, str->s);
256                 if (c->tid < 0 && strcmp(str->s, "*")) {
257                         if (header->n_targets == 0) {
258                                 fprintf(stderr, "[sam_read1] missing header? Abort!\n");
259                                 exit(1);
260                         } else fprintf(stderr, "[sam_read1] reference '%s' is recognized as '*'.\n", str->s);
261                 }
262                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->pos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
263                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->qual = isdigit(str->s[0])? atoi(str->s) : 0;
264                 if (ret < 0) return -2;
265         }
266         { // cigar
267                 char *s, *t;
268                 int i, op;
269                 long x;
270                 c->n_cigar = 0;
271                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -3;
272                 z += str->l + 1;
273                 if (str->s[0] != '*') {
274                         for (s = str->s; *s; ++s) {
275                                 if (isalpha(*s)) ++c->n_cigar;
276                                 else if (!isdigit(*s)) parse_error(fp->n_lines, "invalid CIGAR character");
277                         }
278                         b->data = alloc_data(b, doff + c->n_cigar * 4);
279                         for (i = 0, s = str->s; i != c->n_cigar; ++i) {
280                                 x = strtol(s, &t, 10);
281                                 op = toupper(*t);
282                                 if (op == 'M' || op == '=' || op == 'X') op = BAM_CMATCH;
283                                 else if (op == 'I') op = BAM_CINS;
284                                 else if (op == 'D') op = BAM_CDEL;
285                                 else if (op == 'N') op = BAM_CREF_SKIP;
286                                 else if (op == 'S') op = BAM_CSOFT_CLIP;
287                                 else if (op == 'H') op = BAM_CHARD_CLIP;
288                                 else if (op == 'P') op = BAM_CPAD;
289                                 else parse_error(fp->n_lines, "invalid CIGAR operation");
290                                 s = t + 1;
291                                 bam1_cigar(b)[i] = x << BAM_CIGAR_SHIFT | op;
292                         }
293                         if (*s) parse_error(fp->n_lines, "unmatched CIGAR operation");
294                         c->bin = bam_reg2bin(c->pos, bam_calend(c, bam1_cigar(b)));
295                         doff += c->n_cigar * 4;
296                 } else {
297                         if (!(c->flag&BAM_FUNMAP)) {
298                                 fprintf(stderr, "Parse warning at line %lld: mapped sequence without CIGAR\n", (long long)fp->n_lines);
299                                 c->flag |= BAM_FUNMAP;
300                         }
301                         c->bin = bam_reg2bin(c->pos, c->pos + 1);
302                 }
303         }
304         { // mtid, mpos, isize
305                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
306                 c->mtid = strcmp(str->s, "=")? bam_get_tid(header, str->s) : c->tid;
307                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
308                 c->mpos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
309                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1;
310                 c->isize = (str->s[0] == '-' || isdigit(str->s[0]))? atoi(str->s) : 0;
311                 if (ret < 0) return -4;
312         }
313         { // seq and qual
314                 int i;
315                 uint8_t *p = 0;
316                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -5; // seq
317                 z += str->l + 1;
318                 if (strcmp(str->s, "*")) {
319                         c->l_qseq = strlen(str->s);
320                         if (c->n_cigar && c->l_qseq != (int32_t)bam_cigar2qlen(c, bam1_cigar(b)))
321                                 parse_error(fp->n_lines, "CIGAR and sequence length are inconsistent");
322                         p = (uint8_t*)alloc_data(b, doff + c->l_qseq + (c->l_qseq+1)/2) + doff;
323                         memset(p, 0, (c->l_qseq+1)/2);
324                         for (i = 0; i < c->l_qseq; ++i)
325                                 p[i/2] |= bam_nt16_table[(int)str->s[i]] << 4*(1-i%2);
326                 } else c->l_qseq = 0;
327                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -6; // qual
328                 z += str->l + 1;
329                 if (strcmp(str->s, "*") && c->l_qseq != strlen(str->s))
330                         parse_error(fp->n_lines, "sequence and quality are inconsistent");
331                 p += (c->l_qseq+1)/2;
332                 if (strcmp(str->s, "*") == 0) for (i = 0; i < c->l_qseq; ++i) p[i] = 0xff;
333                 else for (i = 0; i < c->l_qseq; ++i) p[i] = str->s[i] - 33;
334                 doff += c->l_qseq + (c->l_qseq+1)/2;
335         }
336         doff0 = doff;
337         if (dret != '\n' && dret != '\r') { // aux
338                 while (ks_getuntil(ks, KS_SEP_TAB, str, &dret) >= 0) {
339                         uint8_t *s, type, key[2];
340                         z += str->l + 1;
341                         if (str->l < 6 || str->s[2] != ':' || str->s[4] != ':')
342                                 parse_error(fp->n_lines, "missing colon in auxiliary data");
343                         key[0] = str->s[0]; key[1] = str->s[1];
344                         type = str->s[3];
345                         s = alloc_data(b, doff + 3) + doff;
346                         s[0] = key[0]; s[1] = key[1]; s += 2; doff += 2;
347                         if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { // c and C for backward compatibility
348                                 s = alloc_data(b, doff + 2) + doff;
349                                 *s++ = 'A'; *s = str->s[5];
350                                 doff += 2;
351                         } else if (type == 'I' || type == 'i') {
352                                 long long x;
353                                 s = alloc_data(b, doff + 5) + doff;
354                                 x = (long long)atoll(str->s + 5);
355                                 if (x < 0) {
356                                         if (x >= -127) {
357                                                 *s++ = 'c'; *(int8_t*)s = (int8_t)x;
358                                                 s += 1; doff += 2;
359                                         } else if (x >= -32767) {
360                                                 *s++ = 's'; *(int16_t*)s = (int16_t)x;
361                                                 s += 2; doff += 3;
362                                         } else {
363                                                 *s++ = 'i'; *(int32_t*)s = (int32_t)x;
364                                                 s += 4; doff += 5;
365                                                 if (x < -2147483648ll)
366                                                         fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
367                                                                         (long long)fp->n_lines, x);
368                                         }
369                                 } else {
370                                         if (x <= 255) {
371                                                 *s++ = 'C'; *s++ = (uint8_t)x;
372                                                 doff += 2;
373                                         } else if (x <= 65535) {
374                                                 *s++ = 'S'; *(uint16_t*)s = (uint16_t)x;
375                                                 s += 2; doff += 3;
376                                         } else {
377                                                 *s++ = 'I'; *(uint32_t*)s = (uint32_t)x;
378                                                 s += 4; doff += 5;
379                                                 if (x > 4294967295ll)
380                                                         fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
381                                                                         (long long)fp->n_lines, x);
382                                         }
383                                 }
384                         } else if (type == 'f') {
385                                 s = alloc_data(b, doff + 5) + doff;
386                                 *s++ = 'f';
387                                 *(float*)s = (float)atof(str->s + 5);
388                                 s += 4; doff += 5;
389                         } else if (type == 'd') {
390                                 s = alloc_data(b, doff + 9) + doff;
391                                 *s++ = 'd';
392                                 *(float*)s = (float)atof(str->s + 9);
393                                 s += 8; doff += 9;
394                         } else if (type == 'Z' || type == 'H') {
395                                 int size = 1 + (str->l - 5) + 1;
396                                 if (type == 'H') { // check whether the hex string is valid
397                                         int i;
398                                         if ((str->l - 5) % 2 == 1) parse_error(fp->n_lines, "length of the hex string not even");
399                                         for (i = 0; i < str->l - 5; ++i) {
400                                                 int c = toupper(str->s[5 + i]);
401                                                 if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')))
402                                                         parse_error(fp->n_lines, "invalid hex character");
403                                         }
404                                 }
405                                 s = alloc_data(b, doff + size) + doff;
406                                 *s++ = type;
407                                 memcpy(s, str->s + 5, str->l - 5);
408                                 s[str->l - 5] = 0;
409                                 doff += size;
410                         } else parse_error(fp->n_lines, "unrecognized type");
411                         if (dret == '\n' || dret == '\r') break;
412                 }
413         }
414         b->l_aux = doff - doff0;
415         b->data_len = doff;
416         return z;
417 }
418
419 tamFile sam_open(const char *fn)
420 {
421         tamFile fp;
422         gzFile gzfp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "rb") : gzopen(fn, "rb");
423         if (gzfp == 0) return 0;
424         fp = (tamFile)calloc(1, sizeof(struct __tamFile_t));
425         fp->str = (kstring_t*)calloc(1, sizeof(kstring_t));
426         fp->fp = gzfp;
427         fp->ks = ks_init(fp->fp);
428         return fp;
429 }
430
431 void sam_close(tamFile fp)
432 {
433         if (fp) {
434                 ks_destroy(fp->ks);
435                 gzclose(fp->fp);
436                 free(fp->str->s); free(fp->str);
437                 free(fp);
438         }
439 }