Imported Upstream version 0.6
[pysam.git] / samtools / bam_md.c.pysam.c
1 #include "pysam.h"
2
3 #include <unistd.h>
4 #include <assert.h>
5 #include <string.h>
6 #include <ctype.h>
7 #include <math.h>
8 #include "faidx.h"
9 #include "sam.h"
10 #include "kstring.h"
11 #include "kaln.h"
12 #include "kprobaln.h"
13
14 #define USE_EQUAL 1
15 #define DROP_TAG  2
16 #define BIN_QUAL  4
17 #define UPDATE_NM 8
18 #define UPDATE_MD 16
19 #define HASH_QNM  32
20
21 char bam_nt16_nt4_table[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 };
22
23 int bam_aux_drop_other(bam1_t *b, uint8_t *s);
24
25 void bam_fillmd1_core(bam1_t *b, char *ref, int flag, int max_nm)
26 {
27         uint8_t *seq = bam1_seq(b);
28         uint32_t *cigar = bam1_cigar(b);
29         bam1_core_t *c = &b->core;
30         int i, x, y, u = 0;
31         kstring_t *str;
32         int32_t old_nm_i = -1, nm = 0;
33
34         str = (kstring_t*)calloc(1, sizeof(kstring_t));
35         for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
36                 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
37                 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
38                         for (j = 0; j < l; ++j) {
39                                 int z = y + j;
40                                 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
41                                 if (ref[x+j] == 0) break; // out of boundary
42                                 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
43                                         if (flag&USE_EQUAL) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
44                                         ++u;
45                                 } else {
46                                         kputw(u, str); kputc(ref[x+j], str);
47                                         u = 0; ++nm;
48                                 }
49                         }
50                         if (j < l) break;
51                         x += l; y += l;
52                 } else if (op == BAM_CDEL) {
53                         kputw(u, str); kputc('^', str);
54                         for (j = 0; j < l; ++j) {
55                                 if (ref[x+j] == 0) break;
56                                 kputc(ref[x+j], str);
57                         }
58                         u = 0;
59                         if (j < l) break;
60                         x += l; nm += l;
61                 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
62                         y += l;
63                         if (op == BAM_CINS) nm += l;
64                 } else if (op == BAM_CREF_SKIP) {
65                         x += l;
66                 }
67         }
68         kputw(u, str);
69         // apply max_nm
70         if (max_nm > 0 && nm >= max_nm) {
71                 for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
72                         int j, l = cigar[i]>>4, op = cigar[i]&0xf;
73                         if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
74                                 for (j = 0; j < l; ++j) {
75                                         int z = y + j;
76                                         int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
77                                         if (ref[x+j] == 0) break; // out of boundary
78                                         if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
79                                                 seq[z/2] |= (z&1)? 0x0f : 0xf0;
80                                                 bam1_qual(b)[z] = 0;
81                                         }
82                                 }
83                                 if (j < l) break;
84                                 x += l; y += l;
85                         } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) x += l;
86                         else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l;
87                 }
88         }
89         // update NM
90         if (flag & UPDATE_NM) {
91                 uint8_t *old_nm = bam_aux_get(b, "NM");
92                 if (c->flag & BAM_FUNMAP) return;
93                 if (old_nm) old_nm_i = bam_aux2i(old_nm);
94                 if (!old_nm) bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
95                 else if (nm != old_nm_i) {
96                         fprintf(pysamerr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam1_qname(b), old_nm_i, nm);
97                         bam_aux_del(b, old_nm);
98                         bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
99                 }
100         }
101         // update MD
102         if (flag & UPDATE_MD) {
103                 uint8_t *old_md = bam_aux_get(b, "MD");
104                 if (c->flag & BAM_FUNMAP) return;
105                 if (!old_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
106                 else {
107                         int is_diff = 0;
108                         if (strlen((char*)old_md+1) == str->l) {
109                                 for (i = 0; i < str->l; ++i)
110                                         if (toupper(old_md[i+1]) != toupper(str->s[i]))
111                                                 break;
112                                 if (i < str->l) is_diff = 1;
113                         } else is_diff = 1;
114                         if (is_diff) {
115                                 fprintf(pysamerr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam1_qname(b), old_md+1, str->s);
116                                 bam_aux_del(b, old_md);
117                                 bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
118                         }
119                 }
120         }
121         // drop all tags but RG
122         if (flag&DROP_TAG) {
123                 uint8_t *q = bam_aux_get(b, "RG");
124                 bam_aux_drop_other(b, q);
125         }
126         // reduce the resolution of base quality
127         if (flag&BIN_QUAL) {
128                 uint8_t *qual = bam1_qual(b);
129                 for (i = 0; i < b->core.l_qseq; ++i)
130                         if (qual[i] >= 3) qual[i] = qual[i]/10*10 + 7;
131         }
132         free(str->s); free(str);
133 }
134
135 void bam_fillmd1(bam1_t *b, char *ref, int flag)
136 {
137         bam_fillmd1_core(b, ref, flag, 0);
138 }
139
140 int bam_cap_mapQ(bam1_t *b, char *ref, int thres)
141 {
142         uint8_t *seq = bam1_seq(b), *qual = bam1_qual(b);
143         uint32_t *cigar = bam1_cigar(b);
144         bam1_core_t *c = &b->core;
145         int i, x, y, mm, q, len, clip_l, clip_q;
146         double t;
147         if (thres < 0) thres = 40; // set the default
148         mm = q = len = clip_l = clip_q = 0;
149         for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
150                 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
151                 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
152                         for (j = 0; j < l; ++j) {
153                                 int z = y + j;
154                                 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
155                                 if (ref[x+j] == 0) break; // out of boundary
156                                 if (c2 != 15 && c1 != 15 && qual[z] >= 13) { // not ambiguous
157                                         ++len;
158                                         if (c1 && c1 != c2 && qual[z] >= 13) { // mismatch
159                                                 ++mm;
160                                                 q += qual[z] > 33? 33 : qual[z];
161                                         }
162                                 }
163                         }
164                         if (j < l) break;
165                         x += l; y += l; len += l;
166                 } else if (op == BAM_CDEL) {
167                         for (j = 0; j < l; ++j)
168                                 if (ref[x+j] == 0) break;
169                         if (j < l) break;
170                         x += l;
171                 } else if (op == BAM_CSOFT_CLIP) {
172                         for (j = 0; j < l; ++j) clip_q += qual[y+j];
173                         clip_l += l;
174                         y += l;
175                 } else if (op == BAM_CHARD_CLIP) {
176                         clip_q += 13 * l;
177                         clip_l += l;
178                 } else if (op == BAM_CINS) y += l;
179                 else if (op == BAM_CREF_SKIP) x += l;
180         }
181         for (i = 0, t = 1; i < mm; ++i)
182                 t *= (double)len / (i+1);
183         t = q - 4.343 * log(t) + clip_q / 5.;
184         if (t > thres) return -1;
185         if (t < 0) t = 0;
186         t = sqrt((thres - t) / thres) * thres;
187 //      fprintf(pysamerr, "%s %lf %d\n", bam1_qname(b), t, q);
188         return (int)(t + .499);
189 }
190
191 int bam_prob_realn_core(bam1_t *b, const char *ref, int flag)
192 {
193         int k, i, bw, x, y, yb, ye, xb, xe, apply_baq = flag&1, extend_baq = flag>>1&1;
194         uint32_t *cigar = bam1_cigar(b);
195         bam1_core_t *c = &b->core;
196         kpa_par_t conf = kpa_par_def;
197         uint8_t *bq = 0, *zq = 0, *qual = bam1_qual(b);
198         if ((c->flag & BAM_FUNMAP) || b->core.l_qseq == 0) return -1; // do nothing
199         // test if BQ or ZQ is present
200         if ((bq = bam_aux_get(b, "BQ")) != 0) ++bq;
201         if ((zq = bam_aux_get(b, "ZQ")) != 0 && *zq == 'Z') ++zq;
202         if (bq && zq) { // remove the ZQ tag
203                 bam_aux_del(b, zq-1);
204                 zq = 0;
205         }
206         if (bq || zq) {
207                 if ((apply_baq && zq) || (!apply_baq && bq)) return -3; // in both cases, do nothing
208                 if (bq && apply_baq) { // then convert BQ to ZQ
209                         for (i = 0; i < c->l_qseq; ++i)
210                                 qual[i] = qual[i] + 64 < bq[i]? 0 : qual[i] - ((int)bq[i] - 64);
211                         *(bq - 3) = 'Z';
212                 } else if (zq && !apply_baq) { // then convert ZQ to BQ
213                         for (i = 0; i < c->l_qseq; ++i)
214                                 qual[i] += (int)zq[i] - 64;
215                         *(zq - 3) = 'B';
216                 }
217                 return 0;
218         }
219         // find the start and end of the alignment      
220         x = c->pos, y = 0, yb = ye = xb = xe = -1;
221         for (k = 0; k < c->n_cigar; ++k) {
222                 int op, l;
223                 op = cigar[k]&0xf; l = cigar[k]>>4;
224                 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
225                         if (yb < 0) yb = y;
226                         if (xb < 0) xb = x;
227                         ye = y + l; xe = x + l;
228                         x += l; y += l;
229                 } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
230                 else if (op == BAM_CDEL) x += l;
231                 else if (op == BAM_CREF_SKIP) return -1; // do nothing if there is a reference skip
232         }
233         // set bandwidth and the start and the end
234         bw = 7;
235         if (abs((xe - xb) - (ye - yb)) > bw)
236                 bw = abs((xe - xb) - (ye - yb)) + 3;
237         conf.bw = bw;
238         xb -= yb + bw/2; if (xb < 0) xb = 0;
239         xe += c->l_qseq - ye + bw/2;
240         if (xe - xb - c->l_qseq > bw)
241                 xb += (xe - xb - c->l_qseq - bw) / 2, xe -= (xe - xb - c->l_qseq - bw) / 2;
242         { // glocal
243                 uint8_t *s, *r, *q, *seq = bam1_seq(b), *bq;
244                 int *state;
245                 bq = calloc(c->l_qseq + 1, 1);
246                 memcpy(bq, qual, c->l_qseq);
247                 s = calloc(c->l_qseq, 1);
248                 for (i = 0; i < c->l_qseq; ++i) s[i] = bam_nt16_nt4_table[bam1_seqi(seq, i)];
249                 r = calloc(xe - xb, 1);
250                 for (i = xb; i < xe; ++i) {
251                         if (ref[i] == 0) { xe = i; break; }
252                         r[i-xb] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[i]]];
253                 }
254                 state = calloc(c->l_qseq, sizeof(int));
255                 q = calloc(c->l_qseq, 1);
256                 kpa_glocal(r, xe-xb, s, c->l_qseq, qual, &conf, state, q);
257                 if (!extend_baq) { // in this block, bq[] is capped by base quality qual[]
258                         for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
259                                 int op = cigar[k]&0xf, l = cigar[k]>>4;
260                                 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
261                                         for (i = y; i < y + l; ++i) {
262                                                 if ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y)) bq[i] = 0;
263                                                 else bq[i] = bq[i] < q[i]? bq[i] : q[i];
264                                         }
265                                         x += l; y += l;
266                                 } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
267                                 else if (op == BAM_CDEL) x += l;
268                         }
269                         for (i = 0; i < c->l_qseq; ++i) bq[i] = qual[i] - bq[i] + 64; // finalize BQ
270                 } else { // in this block, bq[] is BAQ that can be larger than qual[] (different from the above!)
271                         uint8_t *left, *rght;
272                         left = calloc(c->l_qseq, 1); rght = calloc(c->l_qseq, 1);
273                         for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
274                                 int op = cigar[k]&0xf, l = cigar[k]>>4;
275                                 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
276                                         for (i = y; i < y + l; ++i)
277                                                 bq[i] = ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y))? 0 : q[i];
278                                         for (left[y] = bq[y], i = y + 1; i < y + l; ++i)
279                                                 left[i] = bq[i] > left[i-1]? bq[i] : left[i-1];
280                                         for (rght[y+l-1] = bq[y+l-1], i = y + l - 2; i >= y; --i)
281                                                 rght[i] = bq[i] > rght[i+1]? bq[i] : rght[i+1];
282                                         for (i = y; i < y + l; ++i)
283                                                 bq[i] = left[i] < rght[i]? left[i] : rght[i];
284                                         x += l; y += l;
285                                 } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
286                                 else if (op == BAM_CDEL) x += l;
287                         }
288                         for (i = 0; i < c->l_qseq; ++i) bq[i] = 64 + (qual[i] <= bq[i]? 0 : qual[i] - bq[i]); // finalize BQ
289                         free(left); free(rght);
290                 }
291                 if (apply_baq) {
292                         for (i = 0; i < c->l_qseq; ++i) qual[i] -= bq[i] - 64; // modify qual
293                         bam_aux_append(b, "ZQ", 'Z', c->l_qseq + 1, bq);
294                 } else bam_aux_append(b, "BQ", 'Z', c->l_qseq + 1, bq);
295                 free(bq); free(s); free(r); free(q); free(state);
296         }
297         return 0;
298 }
299
300 int bam_prob_realn(bam1_t *b, const char *ref)
301 {
302         return bam_prob_realn_core(b, ref, 1);
303 }
304
305 int bam_fillmd(int argc, char *argv[])
306 {
307         int c, flt_flag, tid = -2, ret, len, is_bam_out, is_sam_in, is_uncompressed, max_nm, is_realn, capQ, baq_flag;
308         samfile_t *fp, *fpout = 0;
309         faidx_t *fai;
310         char *ref = 0, mode_w[8], mode_r[8];
311         bam1_t *b;
312
313         flt_flag = UPDATE_NM | UPDATE_MD;
314         is_bam_out = is_sam_in = is_uncompressed = is_realn = max_nm = capQ = baq_flag = 0;
315         mode_w[0] = mode_r[0] = 0;
316         strcpy(mode_r, "r"); strcpy(mode_w, "w");
317         while ((c = getopt(argc, argv, "EqreuNhbSC:n:Ad")) >= 0) {
318                 switch (c) {
319                 case 'r': is_realn = 1; break;
320                 case 'e': flt_flag |= USE_EQUAL; break;
321                 case 'd': flt_flag |= DROP_TAG; break;
322                 case 'q': flt_flag |= BIN_QUAL; break;
323                 case 'h': flt_flag |= HASH_QNM; break;
324                 case 'N': flt_flag &= ~(UPDATE_MD|UPDATE_NM); break;
325                 case 'b': is_bam_out = 1; break;
326                 case 'u': is_uncompressed = is_bam_out = 1; break;
327                 case 'S': is_sam_in = 1; break;
328                 case 'n': max_nm = atoi(optarg); break;
329                 case 'C': capQ = atoi(optarg); break;
330                 case 'A': baq_flag |= 1; break;
331                 case 'E': baq_flag |= 2; break;
332                 default: fprintf(pysamerr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
333                 }
334         }
335         if (!is_sam_in) strcat(mode_r, "b");
336         if (is_bam_out) strcat(mode_w, "b");
337         else strcat(mode_w, "h");
338         if (is_uncompressed) strcat(mode_w, "u");
339         if (optind + 1 >= argc) {
340                 fprintf(pysamerr, "\n");
341                 fprintf(pysamerr, "Usage:   samtools fillmd [-eubrS] <aln.bam> <ref.fasta>\n\n");
342                 fprintf(pysamerr, "Options: -e       change identical bases to '='\n");
343                 fprintf(pysamerr, "         -u       uncompressed BAM output (for piping)\n");
344                 fprintf(pysamerr, "         -b       compressed BAM output\n");
345                 fprintf(pysamerr, "         -S       the input is SAM with header\n");
346                 fprintf(pysamerr, "         -A       modify the quality string\n");
347                 fprintf(pysamerr, "         -r       compute the BQ tag (without -A) or cap baseQ by BAQ (with -A)\n");
348                 fprintf(pysamerr, "         -E       extended BAQ for better sensitivity but lower specificity\n\n");
349                 return 1;
350         }
351         fp = samopen(argv[optind], mode_r, 0);
352         if (fp == 0) return 1;
353         if (is_sam_in && (fp->header == 0 || fp->header->n_targets == 0)) {
354                 fprintf(pysamerr, "[bam_fillmd] input SAM does not have header. Abort!\n");
355                 return 1;
356         }
357         fpout = samopen("-", mode_w, fp->header);
358         fai = fai_load(argv[optind+1]);
359
360         b = bam_init1();
361         while ((ret = samread(fp, b)) >= 0) {
362                 if (b->core.tid >= 0) {
363                         if (tid != b->core.tid) {
364                                 free(ref);
365                                 ref = fai_fetch(fai, fp->header->target_name[b->core.tid], &len);
366                                 tid = b->core.tid;
367                                 if (ref == 0)
368                                         fprintf(pysamerr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
369                                                         fp->header->target_name[tid]);
370                         }
371                         if (is_realn) bam_prob_realn_core(b, ref, baq_flag);
372                         if (capQ > 10) {
373                                 int q = bam_cap_mapQ(b, ref, capQ);
374                                 if (b->core.qual > q) b->core.qual = q;
375                         }
376                         if (ref) bam_fillmd1_core(b, ref, flt_flag, max_nm);
377                 }
378                 samwrite(fpout, b);
379         }
380         bam_destroy1(b);
381
382         free(ref);
383         fai_destroy(fai);
384         samclose(fp); samclose(fpout);
385         return 0;
386 }