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