Imported Upstream version 0.1.9
[samtools.git] / bam_md.c
1 #include <unistd.h>
2 #include <assert.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include <math.h>
6 #include "faidx.h"
7 #include "sam.h"
8 #include "kstring.h"
9 #include "kaln.h"
10
11 void bam_fillmd1_core(bam1_t *b, char *ref, int is_equal, int max_nm)
12 {
13         uint8_t *seq = bam1_seq(b);
14         uint32_t *cigar = bam1_cigar(b);
15         bam1_core_t *c = &b->core;
16         int i, x, y, u = 0;
17         kstring_t *str;
18         uint8_t *old_md, *old_nm;
19         int32_t old_nm_i = -1, nm = 0;
20
21         str = (kstring_t*)calloc(1, sizeof(kstring_t));
22         for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
23                 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
24                 if (op == BAM_CMATCH) {
25                         for (j = 0; j < l; ++j) {
26                                 int z = y + j;
27                                 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
28                                 if (ref[x+j] == 0) break; // out of boundary
29                                 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
30                                         if (is_equal) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
31                                         ++u;
32                                 } else {
33                                         ksprintf(str, "%d", u);
34                                         kputc(ref[x+j], str);
35                                         u = 0; ++nm;
36                                 }
37                         }
38                         if (j < l) break;
39                         x += l; y += l;
40                 } else if (op == BAM_CDEL) {
41                         ksprintf(str, "%d", u);
42                         kputc('^', str);
43                         for (j = 0; j < l; ++j) {
44                                 if (ref[x+j] == 0) break;
45                                 kputc(ref[x+j], str);
46                         }
47                         u = 0;
48                         if (j < l) break;
49                         x += l; nm += l;
50                 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
51                         y += l;
52                         if (op == BAM_CINS) nm += l;
53                 } else if (op == BAM_CREF_SKIP) {
54                         x += l;
55                 }
56         }
57         ksprintf(str, "%d", u);
58         // apply max_nm
59         if (max_nm > 0 && nm >= max_nm) {
60                 for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
61                         int j, l = cigar[i]>>4, op = cigar[i]&0xf;
62                         if (op == BAM_CMATCH) {
63                                 for (j = 0; j < l; ++j) {
64                                         int z = y + j;
65                                         int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
66                                         if (ref[x+j] == 0) break; // out of boundary
67                                         if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
68                                                 seq[z/2] |= (z&1)? 0x0f : 0xf0;
69                                                 bam1_qual(b)[z] = 0;
70                                         }
71                                 }
72                                 if (j < l) break;
73                                 x += l; y += l;
74                         } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) x += l;
75                         else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l;
76                 }
77         }
78         // update NM
79         old_nm = bam_aux_get(b, "NM");
80         if (c->flag & BAM_FUNMAP) return;
81         if (old_nm) old_nm_i = bam_aux2i(old_nm);
82         if (!old_nm) bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
83         else if (nm != old_nm_i) {
84                 fprintf(stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam1_qname(b), old_nm_i, nm);
85                 bam_aux_del(b, old_nm);
86                 bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
87         }
88         // update MD
89         old_md = bam_aux_get(b, "MD");
90         if (!old_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
91         else {
92                 int is_diff = 0;
93                 if (strlen((char*)old_md+1) == str->l) {
94                         for (i = 0; i < str->l; ++i)
95                                 if (toupper(old_md[i+1]) != toupper(str->s[i]))
96                                         break;
97                         if (i < str->l) is_diff = 1;
98                 } else is_diff = 1;
99                 if (is_diff) {
100                         fprintf(stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam1_qname(b), old_md+1, str->s);
101                         bam_aux_del(b, old_md);
102                         bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
103                 }
104         }
105         free(str->s); free(str);
106 }
107
108 void bam_fillmd1(bam1_t *b, char *ref, int is_equal)
109 {
110         bam_fillmd1_core(b, ref, is_equal, 0);
111 }
112
113 int bam_cap_mapQ(bam1_t *b, char *ref, int thres)
114 {
115         uint8_t *seq = bam1_seq(b), *qual = bam1_qual(b);
116         uint32_t *cigar = bam1_cigar(b);
117         bam1_core_t *c = &b->core;
118         int i, x, y, mm, q, len, clip_l, clip_q;
119         double t;
120         if (thres < 0) thres = 40; // set the default
121         mm = q = len = clip_l = clip_q = 0;
122         for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
123                 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
124                 if (op == BAM_CMATCH) {
125                         for (j = 0; j < l; ++j) {
126                                 int z = y + j;
127                                 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
128                                 if (ref[x+j] == 0) break; // out of boundary
129                                 if (c2 != 15 && c1 != 15 && qual[z] >= 13) { // not ambiguous
130                                         ++len;
131                                         if (c1 && c1 != c2 && qual[z] >= 13) { // mismatch
132                                                 ++mm;
133                                                 q += qual[z] > 33? 33 : qual[z];
134                                         }
135                                 }
136                         }
137                         if (j < l) break;
138                         x += l; y += l; len += l;
139                 } else if (op == BAM_CDEL) {
140                         for (j = 0; j < l; ++j)
141                                 if (ref[x+j] == 0) break;
142                         if (j < l) break;
143                         x += l;
144                 } else if (op == BAM_CSOFT_CLIP) {
145                         for (j = 0; j < l; ++j) clip_q += qual[y+j];
146                         clip_l += l;
147                         y += l;
148                 } else if (op == BAM_CHARD_CLIP) {
149                         clip_q += 13 * l;
150                         clip_l += l;
151                 } else if (op == BAM_CINS) y += l;
152                 else if (op == BAM_CREF_SKIP) x += l;
153         }
154         for (i = 0, t = 1; i < mm; ++i)
155                 t *= (double)len / (i+1);
156         t = q - 4.343 * log(t) + clip_q / 5.;
157         if (t > thres) return -1;
158         if (t < 0) t = 0;
159         t = sqrt((thres - t) / thres) * thres;
160 //      fprintf(stderr, "%s %lf %d\n", bam1_qname(b), t, q);
161         return (int)(t + .499);
162 }
163
164 int bam_prob_realn(bam1_t *b, const char *ref)
165 {
166         int k, i, bw, x, y, yb, ye, xb, xe;
167         uint32_t *cigar = bam1_cigar(b);
168         bam1_core_t *c = &b->core;
169         ka_probpar_t conf = ka_probpar_def;
170         // find the start and end of the alignment
171         if (c->flag & BAM_FUNMAP) return -1;
172         x = c->pos, y = 0, yb = ye = xb = xe = -1;
173         for (k = 0; k < c->n_cigar; ++k) {
174                 int op, l;
175                 op = cigar[k]&0xf; l = cigar[k]>>4;
176                 if (op == BAM_CMATCH) {
177                         if (yb < 0) yb = y;
178                         if (xb < 0) xb = x;
179                         ye = y + l; xe = x + l;
180                         x += l; y += l;
181                 } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
182                 else if (op == BAM_CDEL) x += l;
183                 else if (op == BAM_CREF_SKIP) return -1;
184         }
185         // set bandwidth and the start and the end
186         bw = 7;
187         if (abs((xe - xb) - (ye - yb)) > bw)
188                 bw = abs((xe - xb) - (ye - yb)) + 3;
189         conf.bw = bw;
190         xb -= yb + bw/2; if (xb < 0) xb = 0;
191         xe += c->l_qseq - ye + bw/2;
192         if (xe - xb - c->l_qseq > bw)
193                 xb += (xe - xb - c->l_qseq - bw) / 2, xe -= (xe - xb - c->l_qseq - bw) / 2;
194         { // glocal
195                 uint8_t *s, *r, *q, *seq = bam1_seq(b), *qual = bam1_qual(b);
196                 int *state;
197                 s = calloc(c->l_qseq, 1);
198                 for (i = 0; i < c->l_qseq; ++i) s[i] = bam_nt16_nt4_table[bam1_seqi(seq, i)];
199                 r = calloc(xe - xb, 1);
200                 for (i = xb; i < xe; ++i)
201                         r[i-xb] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[i]]];
202                 state = calloc(c->l_qseq, sizeof(int));
203                 q = calloc(c->l_qseq, 1);
204                 ka_prob_glocal(r, xe-xb, s, c->l_qseq, qual, &conf, state, q);
205                 for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
206                         int op = cigar[k]&0xf, l = cigar[k]>>4;
207                         if (op == BAM_CMATCH) {
208                                 for (i = y; i < y + l; ++i) {
209                                         if ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y)) qual[i] = 0;
210                                         else qual[i] = qual[i] < q[i]? qual[i] : q[i];
211                                 }
212                                 x += l; y += l;
213                         } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
214                         else if (op == BAM_CDEL) x += l;
215                 }
216                 free(s); free(r); free(q); free(state);
217         }
218         return 0;
219 }
220
221 int bam_fillmd(int argc, char *argv[])
222 {
223         int c, is_equal = 0, tid = -2, ret, len, is_bam_out, is_sam_in, is_uncompressed, max_nm = 0, is_realn, capQ = 0;
224         samfile_t *fp, *fpout = 0;
225         faidx_t *fai;
226         char *ref = 0, mode_w[8], mode_r[8];
227         bam1_t *b;
228
229         is_bam_out = is_sam_in = is_uncompressed = is_realn = 0;
230         mode_w[0] = mode_r[0] = 0;
231         strcpy(mode_r, "r"); strcpy(mode_w, "w");
232         while ((c = getopt(argc, argv, "reubSC:n:")) >= 0) {
233                 switch (c) {
234                 case 'r': is_realn = 1; break;
235                 case 'e': is_equal = 1; break;
236                 case 'b': is_bam_out = 1; break;
237                 case 'u': is_uncompressed = is_bam_out = 1; break;
238                 case 'S': is_sam_in = 1; break;
239                 case 'n': max_nm = atoi(optarg); break;
240                 case 'C': capQ = atoi(optarg); break;
241                 default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
242                 }
243         }
244         if (!is_sam_in) strcat(mode_r, "b");
245         if (is_bam_out) strcat(mode_w, "b");
246         else strcat(mode_w, "h");
247         if (is_uncompressed) strcat(mode_w, "u");
248         if (optind + 1 >= argc) {
249                 fprintf(stderr, "\n");
250                 fprintf(stderr, "Usage:   samtools fillmd [-eubrS] <aln.bam> <ref.fasta>\n\n");
251                 fprintf(stderr, "Options: -e       change identical bases to '='\n");
252                 fprintf(stderr, "         -u       uncompressed BAM output (for piping)\n");
253                 fprintf(stderr, "         -b       compressed BAM output\n");
254                 fprintf(stderr, "         -S       the input is SAM with header\n");
255                 fprintf(stderr, "         -r       read-independent local realignment\n\n");
256                 return 1;
257         }
258         fp = samopen(argv[optind], mode_r, 0);
259         if (fp == 0) return 1;
260         if (is_sam_in && (fp->header == 0 || fp->header->n_targets == 0)) {
261                 fprintf(stderr, "[bam_fillmd] input SAM does not have header. Abort!\n");
262                 return 1;
263         }
264         fpout = samopen("-", mode_w, fp->header);
265         fai = fai_load(argv[optind+1]);
266
267         b = bam_init1();
268         while ((ret = samread(fp, b)) >= 0) {
269                 if (b->core.tid >= 0) {
270                         if (tid != b->core.tid) {
271                                 free(ref);
272                                 ref = fai_fetch(fai, fp->header->target_name[b->core.tid], &len);
273                                 tid = b->core.tid;
274                                 if (ref == 0)
275                                         fprintf(stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
276                                                         fp->header->target_name[tid]);
277                         }
278 //                      if (is_realn) bam_realn(b, ref);
279                         if (is_realn) bam_prob_realn(b, ref);
280                         if (capQ > 10) {
281                                 int q = bam_cap_mapQ(b, ref, capQ);
282                                 if (b->core.qual > q) b->core.qual = q;
283                         }
284                         if (ref) bam_fillmd1_core(b, ref, is_equal, max_nm);
285                 }
286                 samwrite(fpout, b);
287         }
288         bam_destroy1(b);
289
290         free(ref);
291         fai_destroy(fai);
292         samclose(fp); samclose(fpout);
293         return 0;
294 }