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