]> git.donarmstrong.com Git - samtools.git/blob - bam_import.c
* samtools-0.1.2-24
[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 #include "bam.h"
9 #include "kseq.h"
10 #include "khash.h"
11
12 KSTREAM_INIT(gzFile, gzread, 8192)
13 KHASH_MAP_INIT_STR(ref, uint64_t)
14
15 void bam_init_header_hash(bam_header_t *header);
16 void bam_destroy_header_hash(bam_header_t *header);
17 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
18
19 unsigned char bam_nt16_table[256] = {
20         15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
21         15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
22         15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
23          1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15,
24         15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
25         15,15, 5, 6,  8,15, 7, 9, 15,10,15,15, 15,15,15,15,
26         15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
27         15,15, 5, 6,  8,15, 7, 9, 15,10,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         15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
31         15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
32         15,15,15,15, 15,15,15,15, 15,15,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 };
37
38 char *bam_nt16_rev_table = "=ACMGRSVTWYHKDBN";
39
40 struct __tamFile_t {
41         gzFile fp;
42         kstream_t *ks;
43         kstring_t *str;
44         uint64_t n_lines;
45 };
46
47 char **__bam_get_lines(const char *fn, int *_n) // for bam_plcmd.c only
48 {
49         char **list = 0, *s;
50         int n = 0, dret, m = 0;
51         gzFile fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
52         kstream_t *ks;
53         kstring_t *str;
54         str = (kstring_t*)calloc(1, sizeof(kstring_t));
55         ks = ks_init(fp);
56         while (ks_getuntil(ks, '\n', str, &dret) > 0) {
57                 if (n == m) {
58                         m = m? m << 1 : 16;
59                         list = (char**)realloc(list, m * sizeof(char*));
60                 }
61                 if (str->s[str->l-1] == '\r')
62                         str->s[--str->l] = '\0';
63                 s = list[n++] = (char*)calloc(str->l + 1, 1);
64                 strcpy(s, str->s);
65         }
66         ks_destroy(ks);
67         gzclose(fp);
68         free(str->s); free(str);
69         *_n = n;
70         return list;
71 }
72
73 static bam_header_t *hash2header(const kh_ref_t *hash)
74 {
75         bam_header_t *header;
76         khiter_t k;
77         header = bam_header_init();
78         header->n_targets = kh_size(hash);
79         header->target_name = (char**)calloc(kh_size(hash), sizeof(char*));
80         header->target_len = (uint32_t*)calloc(kh_size(hash), 4);
81         for (k = kh_begin(hash); k != kh_end(hash); ++k) {
82                 if (kh_exist(hash, k)) {
83                         int i = (int)kh_value(hash, k);
84                         header->target_name[i] = (char*)kh_key(hash, k);
85                         header->target_len[i] = kh_value(hash, k)>>32;
86                 }
87         }
88         bam_init_header_hash(header);
89         return header;
90 }
91 bam_header_t *sam_header_read2(const char *fn)
92 {
93         bam_header_t *header;
94         int c, dret, ret;
95         gzFile fp;
96         kstream_t *ks;
97         kstring_t *str;
98         kh_ref_t *hash;
99         khiter_t k;
100         hash = kh_init(ref);
101         fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
102         assert(fp);
103         ks = ks_init(fp);
104         str = (kstring_t*)calloc(1, sizeof(kstring_t));
105         while (ks_getuntil(ks, 0, str, &dret) > 0) {
106                 char *s = strdup(str->s);
107                 int len, i;
108                 i = kh_size(hash);
109                 ks_getuntil(ks, 0, str, &dret);
110                 len = atoi(str->s);
111                 k = kh_put(ref, hash, s, &ret);
112                 kh_value(hash, k) = (uint64_t)len<<32 | i;
113                 if (dret != '\n')
114                         while ((c = ks_getc(ks)) != '\n' && c != -1);
115         }
116         ks_destroy(ks);
117         gzclose(fp);
118         free(str->s); free(str);
119         fprintf(stderr, "[sam_header_read2] %d sequences loaded.\n", kh_size(hash));
120         header = hash2header(hash);
121         kh_destroy(ref, hash);
122         return header;
123 }
124 static inline uint8_t *alloc_data(bam1_t *b, int size)
125 {
126         if (b->m_data < size) {
127                 b->m_data = size;
128                 kroundup32(b->m_data);
129                 b->data = (uint8_t*)realloc(b->data, b->m_data);
130         }
131         return b->data;
132 }
133 static inline void parse_error(int64_t n_lines, const char * __restrict msg)
134 {
135         fprintf(stderr, "Parse error at line %lld: %s\n", (long long)n_lines, msg);
136         abort();
137 }
138 static inline void append_text(bam_header_t *header, kstring_t *str)
139 {
140         int x = header->l_text, y = header->l_text + str->l + 2; // 2 = 1 byte dret + 1 byte null
141         kroundup32(x); kroundup32(y);
142         if (x < y) header->text = (char*)realloc(header->text, y);
143         strncpy(header->text + header->l_text, str->s, str->l+1); // we cannot use strcpy() here.
144         header->l_text += str->l + 1;
145         header->text[header->l_text] = 0;
146 }
147 int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b)
148 {
149         int ret, doff, doff0, dret;
150         bam1_core_t *c = &b->core;
151         kstring_t *str = fp->str;
152         kstream_t *ks = fp->ks;
153
154         while ((ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret)) >= 0 && str->s[0] == '@') { // skip header
155                 str->s[str->l] = dret; // note that str->s is NOT null terminated!!
156                 append_text(header, str);
157                 if (dret != '\n') {
158                         ret = ks_getuntil(fp->ks, '\n', str, &dret);
159                         str->s[str->l] = '\n'; // NOT null terminated!!
160                         append_text(header, str);
161                 }
162                 ++fp->n_lines;
163         }
164         while (ret == 0) ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret); // special consideration for "\r\n"
165         if (ret < 0) return -1;
166         ++fp->n_lines;
167         doff = 0;
168
169         { // name
170                 c->l_qname = strlen(str->s) + 1;
171                 memcpy(alloc_data(b, doff + c->l_qname) + doff, str->s, c->l_qname);
172                 doff += c->l_qname;
173         }
174         { // flag, tid, pos, qual
175                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->flag = atoi(str->s);
176                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->tid = bam_get_tid(header, str->s);
177                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->pos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
178                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->qual = isdigit(str->s[0])? atoi(str->s) : 0;
179                 if (ret < 0) return -2;
180         }
181         { // cigar
182                 char *s, *t;
183                 int i, op;
184                 long x;
185                 c->n_cigar = 0;
186                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -3;
187                 if (str->s[0] != '*') {
188                         for (s = str->s; *s; ++s) {
189                                 if (isalpha(*s)) ++c->n_cigar;
190                                 else if (!isdigit(*s)) parse_error(fp->n_lines, "invalid CIGAR character");
191                         }
192                         b->data = alloc_data(b, doff + c->n_cigar * 4);
193                         for (i = 0, s = str->s; i != c->n_cigar; ++i) {
194                                 x = strtol(s, &t, 10);
195                                 op = toupper(*t);
196                                 if (op == 'M') op = BAM_CMATCH;
197                                 else if (op == 'I') op = BAM_CINS;
198                                 else if (op == 'D') op = BAM_CDEL;
199                                 else if (op == 'N') op = BAM_CREF_SKIP;
200                                 else if (op == 'S') op = BAM_CSOFT_CLIP;
201                                 else if (op == 'H') op = BAM_CHARD_CLIP;
202                                 else if (op == 'P') op = BAM_CPAD;
203                                 else parse_error(fp->n_lines, "invalid CIGAR operation");
204                                 s = t + 1;
205                                 bam1_cigar(b)[i] = x << BAM_CIGAR_SHIFT | op;
206                         }
207                         if (*s) parse_error(fp->n_lines, "unmatched CIGAR operation");
208                         c->bin = bam_reg2bin(c->pos, bam_calend(c, bam1_cigar(b)));
209                         doff += c->n_cigar * 4;
210                 } else c->bin = bam_reg2bin(c->pos, c->pos + 1);
211         }
212         { // mtid, mpos, isize
213                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->mtid = strcmp(str->s, "=")? bam_get_tid(header, str->s) : c->tid;
214                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->mpos = isdigit(str->s[0])? atoi(str->s) - 1 : -1;
215                 ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); c->isize = (str->s[0] == '-' || isdigit(str->s[0]))? atoi(str->s) : 0;
216                 if (ret < 0) return -4;
217         }
218         { // seq and qual
219                 int i;
220                 uint8_t *p;
221                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -5; // seq
222                 c->l_qseq = strlen(str->s);
223                 if (c->n_cigar && c->l_qseq != (int32_t)bam_cigar2qlen(c, bam1_cigar(b)))
224                         parse_error(fp->n_lines, "CIGAR and sequence length are inconsistent");
225                 p = (uint8_t*)alloc_data(b, doff + c->l_qseq + (c->l_qseq+1)/2) + doff;
226                 bzero(p, (c->l_qseq+1)/2);
227                 for (i = 0; i < c->l_qseq; ++i)
228                         p[i/2] |= bam_nt16_table[(int)str->s[i]] << 4*(1-i%2);
229                 if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -6; // qual
230                 if (strcmp(str->s, "*") && c->l_qseq != strlen(str->s))
231                         parse_error(fp->n_lines, "sequence and quality are inconsistent");
232                 p += (c->l_qseq+1)/2;
233                 if (strcmp(str->s, "*") == 0) for (i = 0; i < c->l_qseq; ++i) p[i] = 0xff;
234                 else for (i = 0; i < c->l_qseq; ++i) p[i] = str->s[i] - 33;
235                 doff += c->l_qseq + (c->l_qseq+1)/2;
236         }
237         doff0 = doff;
238         if (dret != '\n' && dret != '\r') { // aux
239                 while (ks_getuntil(ks, KS_SEP_TAB, str, &dret) >= 0) {
240                         uint8_t *s, type, key[2];
241                         if (str->l < 6 || str->s[2] != ':' || str->s[4] != ':')
242                                 parse_error(fp->n_lines, "missing colon in auxiliary data");
243                         key[0] = str->s[0]; key[1] = str->s[1];
244                         type = str->s[3];
245                         s = alloc_data(b, doff + 3) + doff;
246                         s[0] = key[0]; s[1] = key[1]; s += 2; doff += 2;
247                         if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { // c and C for backward compatibility
248                                 s = alloc_data(b, doff + 2) + doff;
249                                 *s++ = 'A'; *s = str->s[5];
250                                 doff += 2;
251                         } else if (type == 'I' || type == 'i') {
252                                 long long x;
253                                 s = alloc_data(b, doff + 5) + doff;
254                                 x = (long long)atoll(str->s + 5);
255                                 if (x < 0) {
256                                         if (x >= -127) {
257                                                 *s++ = 'c'; *(int8_t*)s = (int8_t)x;
258                                                 s += 1; doff += 2;
259                                         } else if (x >= -32767) {
260                                                 *s++ = 's'; *(int16_t*)s = (int16_t)x;
261                                                 s += 2; doff += 3;
262                                         } else {
263                                                 *s++ = 'i'; *(int32_t*)s = (int32_t)x;
264                                                 s += 4; doff += 5;
265                                                 if (x < -2147483648ll)
266                                                         fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
267                                                                         (long long)fp->n_lines, x);
268                                         }
269                                 } else {
270                                         if (x <= 255) {
271                                                 *s++ = 'C'; *s++ = (uint8_t)x;
272                                                 doff += 2;
273                                         } else if (x <= 65535) {
274                                                 *s++ = 'S'; *(uint16_t*)s = (uint16_t)x;
275                                                 s += 2; doff += 3;
276                                         } else {
277                                                 *s++ = 'I'; *(uint32_t*)s = (uint32_t)x;
278                                                 s += 4; doff += 5;
279                                                 if (x > 4294967295ll)
280                                                         fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.",
281                                                                         (long long)fp->n_lines, x);
282                                         }
283                                 }
284                         } else if (type == 'f') {
285                                 s = alloc_data(b, doff + 5) + doff;
286                                 *s++ = 'f';
287                                 *(float*)s = (float)atof(str->s + 5);
288                                 s += 4; doff += 5;
289                         } else if (type == 'd') {
290                                 s = alloc_data(b, doff + 9) + doff;
291                                 *s++ = 'd';
292                                 *(float*)s = (float)atof(str->s + 9);
293                                 s += 8; doff += 9;
294                         } else if (type == 'Z' || type == 'H') {
295                                 int size = 1 + (str->l - 5) + 1;
296                                 if (type == 'H') { // check whether the hex string is valid
297                                         int i;
298                                         if ((str->l - 5) % 2 == 1) parse_error(fp->n_lines, "length of the hex string not even");
299                                         for (i = 0; i < str->l - 5; ++i) {
300                                                 int c = toupper(str->s[5 + i]);
301                                                 if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')))
302                                                         parse_error(fp->n_lines, "invalid hex character");
303                                         }
304                                 }
305                                 s = alloc_data(b, doff + size) + doff;
306                                 *s++ = type;
307                                 memcpy(s, str->s + 5, str->l - 5);
308                                 s[str->l - 5] = 0;
309                                 doff += size;
310                         } else parse_error(fp->n_lines, "unrecognized type");
311                         if (dret == '\n' || dret == '\r') break;
312                 }
313         }
314         b->l_aux = doff - doff0;
315         b->data_len = doff;
316         return 0;
317 }
318
319 tamFile sam_open(const char *fn)
320 {
321         tamFile fp;
322         fp = (tamFile)calloc(1, sizeof(struct __tamFile_t));
323         fp->str = (kstring_t*)calloc(1, sizeof(kstring_t));
324         fp->fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r");
325         fp->ks = ks_init(fp->fp);
326         fp->n_lines = 0;
327         return fp;
328 }
329
330 void sam_close(tamFile fp)
331 {
332         if (fp) {
333                 ks_destroy(fp->ks);
334                 gzclose(fp->fp);
335                 free(fp->str->s); free(fp->str);
336                 free(fp);
337         }
338 }
339
340 static void taf2baf_core(const char *fntaf, const char *fnbaf, bam_header_t *header)
341 {
342         bamFile fpbaf;
343         bam1_t *b;
344         tamFile fp;
345         int ret;
346
347         b = (bam1_t*)calloc(1, sizeof(bam1_t));
348         fpbaf = (strcmp(fnbaf, "-") == 0)? bam_dopen(fileno(stdout), "w") : bam_open(fnbaf, "w");
349         fp = sam_open(fntaf);
350         ret = sam_read1(fp, header, b);
351         bam_header_write(fpbaf, header);
352         if (ret >= 0) {
353                 bam_write1(fpbaf, b);
354                 while (sam_read1(fp, header, b) >= 0) bam_write1(fpbaf, b);
355         }
356         bam_close(fpbaf);
357         free(b->data); free(b);
358         sam_close(fp);
359 }
360
361 int bam_taf2baf(int argc, char *argv[])
362 {
363         int c;
364         bam_header_t *header;
365
366         while ((c = getopt(argc, argv, "")) >= 0) {
367         }
368         if (optind + 3 > argc) {
369                 fprintf(stderr, "Usage: bamtk import <in.ref_list> <in.sam> <out.bam>\n");
370                 return 1;
371         }
372         header = sam_header_read2(argv[optind]);
373         taf2baf_core(argv[optind+1], argv[optind+2], header);
374         bam_header_destroy(header);
375         return 0;
376 }