]> git.donarmstrong.com Git - samtools.git/blob - bam_md.c
prob_realn() seems working!
[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 // local realignment
165
166 #define MIN_REF_LEN 10
167 #define MIN_BAND_WIDTH 11
168
169 int bam_realn(bam1_t *b, const char *ref)
170 {
171         int k, score, q[2], r[2], kk[2], kl[2], x, y, max, j, n_cigar, endx = -1;
172         uint32_t *cigar = bam1_cigar(b);
173         uint8_t *seq = bam1_seq(b);
174         bam1_core_t *c = &b->core;
175         q[0] = q[1] = r[0] = r[1] = kk[0] = kk[1] = kl[0] = kl[1] = -1;
176         // find the right boundary
177         for (k = 0, score = max = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
178                 int op = cigar[k]&0xf;
179                 int ol = cigar[k]>>4;
180                 if (op == BAM_CMATCH) {
181                         for (j = 0; j < ol; ++j) {
182                                 int c1, c2, z = y + j;
183                                 c1 = bam_nt16_nt4_table[bam1_seqi(seq, z)];
184                                 if (ref[x+j] == 0) return -1;
185                                 c2 = bam_nt16_nt4_table[(int)bam_nt16_table[(int)ref[x+j]]];
186                                 if (c1 < 3 && c2 < 3)
187                                         score += c1 == c2? 5 : -4;
188                                 if (score < 0) score = 0;
189                                 if (score > max) max = score, q[1] = z, r[1] = x+j, kk[1] = k, kl[1] = j + 1;
190                         }
191                         x += ol; y += ol;
192                 } else if (op == BAM_CINS) {
193                         score -= 4 - ol * 3;
194                         y += ol;
195                         if (score < 0) score = 0;
196                 } else if (op == BAM_CDEL) {
197                         score -= 4 - ol * 3;
198                         x += ol;
199                         if (score < 0) score = 0;
200                 } else if (op == BAM_CSOFT_CLIP) y += ol;
201                 else if (op == BAM_CREF_SKIP) x += ol;
202         }
203         if (q[1] < 0) return -1; // no high scoring segments
204         endx = x - 1;
205         // find the left boundary
206         for (k = c->n_cigar - 1, score = max = 0, x = x-1, y = y-1; k >= 0; --k) {
207                 int op = cigar[k]&0xf;
208                 int ol = cigar[k]>>4;
209                 if (op == BAM_CMATCH) {
210                         for (j = 0; j < ol; ++j) {
211                                 int c1, c2, z = y - j;
212                                 c1 = bam_nt16_nt4_table[bam1_seqi(seq, z)];
213                                 if (ref[x+j] == 0) return -1;
214                                 c2 = bam_nt16_nt4_table[(int)bam_nt16_table[(int)ref[x-j]]];
215                                 if (c1 < 3 && c2 < 3)
216                                         score += c1 == c2? 5 : -4;
217                                 if (score < 0) score = 0;
218                                 if (score > max) max = score, q[0] = z, r[0] = x-j, kk[0] = k, kl[0] = j + 1;
219                         }
220                         x -= ol; y -= ol;
221                 } else if (op == BAM_CINS) {
222                         score -= 4 - ol * 3;
223                         y -= ol;
224                         if (score < 0) score = 0;
225                 } else if (op == BAM_CDEL) {
226                         score -= 4 - ol * 3;
227                         x -= ol;
228                         if (score < 0) score = 0;
229                 } else if (op == BAM_CSOFT_CLIP) y -= ol;
230                 else if (op == BAM_CREF_SKIP) x -= ol;
231         }
232         if (q[0] < 0 || q[1] - q[0] < 15) return -1; // the high-scoring segment is too short
233         // modify CIGAR
234         n_cigar = 0;
235         cigar = calloc(c->n_cigar + 4, 4);
236         if (q[0] != 0) cigar[n_cigar++] = (uint32_t)q[0]<<4 | BAM_CSOFT_CLIP;
237         if (r[0] != c->pos) cigar[n_cigar++] = (uint32_t)(r[0] - c->pos)<<4 | BAM_CREF_SKIP;
238         if (kk[0] == kk[1]) {
239                 cigar[n_cigar++] = (uint32_t)(kl[0] + kl[1] - (bam1_cigar(b)[kk[0]]>>4))<<4 | BAM_CMATCH;
240         } else {
241                 cigar[n_cigar++] = (uint32_t)kl[0]<<4 | BAM_CMATCH;
242                 for (k = kk[0] + 1; k < kk[1]; ++k)
243                         cigar[n_cigar++] = bam1_cigar(b)[k];
244                 cigar[n_cigar++] = (uint32_t)kl[1]<<4 | BAM_CMATCH; // FIXME: add ref_skip after this line
245         }
246         if (q[1] + 1 != c->l_qseq)
247                 cigar[n_cigar++] = (uint32_t)(c->l_qseq - q[1] - 1)<<4 | BAM_CSOFT_CLIP;
248         // copy over the alignment
249         if (4 * (n_cigar - (int)c->n_cigar) + b->data_len > b->m_data) { // enlarge b->data
250                 b->m_data = 4 * (n_cigar - (int)c->n_cigar) + b->data_len;
251                 kroundup32(b->m_data);
252                 b->data = realloc(b->data, b->m_data);
253         }
254         if (n_cigar != (int)c->n_cigar) { // move data
255                 memmove(b->data + c->l_qname + 4 * n_cigar, bam1_seq(b), b->data_len - c->l_qname - 4 * c->n_cigar);
256                 b->data_len += 4 * (n_cigar - (int)c->n_cigar);
257         }
258         memcpy(bam1_cigar(b), cigar, n_cigar * 4);
259         c->n_cigar = n_cigar;
260         free(cigar);
261         return 0;
262 }
263
264 int bam_prob_realn(bam1_t *b, const char *ref)
265 {
266         int k, i, bw, x, y, yb, ye, xb, xe;
267         uint32_t *cigar = bam1_cigar(b);
268         bam1_core_t *c = &b->core;
269         ka_probpar_t conf = ka_probpar_def;
270         // find the start and end of the alignment
271         if (c->flag & BAM_FUNMAP) return -1;
272         x = c->pos, y = 0, yb = ye = xb = xe = -1;
273         for (k = 0; k < c->n_cigar; ++k) {
274                 int op, l;
275                 op = cigar[k]&0xf; l = cigar[k]>>4;
276                 if (op == BAM_CMATCH) {
277                         if (yb < 0) yb = y;
278                         if (xb < 0) xb = x;
279                         ye = y + l; xe = x + l;
280                         x += l; y += l;
281                 } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
282                 else if (op == BAM_CDEL) x += l;
283                 else if (op == BAM_CREF_SKIP) return -1;
284         }
285         // set bandwidth and the start and the end
286         bw = 7;
287         if (abs((xe - xb) - (ye - yb)) > bw)
288                 bw = abs((xe - xb) - (ye - yb)) + 3;
289         conf.bw = bw;
290         xb -= yb + bw/2; if (xb < 0) xb = 0;
291         xe += c->l_qseq - ye + bw/2;
292         if (xe - xb - c->l_qseq > bw)
293                 xb += (xe - xb - c->l_qseq - bw) / 2, xe -= (xe - xb - c->l_qseq - bw) / 2;
294         { // glocal
295                 uint8_t *s, *r, *q, *seq = bam1_seq(b), *qual = bam1_qual(b);
296                 int *state;
297                 s = calloc(c->l_qseq, 1);
298                 for (i = 0; i < c->l_qseq; ++i) s[i] = bam_nt16_nt4_table[bam1_seqi(seq, i)];
299                 r = calloc(xe - xb, 1);
300                 for (i = xb; i < xe; ++i)
301                         r[i-xb] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[i]]];
302                 state = calloc(c->l_qseq, sizeof(int));
303                 q = calloc(c->l_qseq, 1);
304                 ka_prob_glocal(r, xe-xb, s, c->l_qseq, qual, &conf, state, q);
305                 for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) {
306                         int op = cigar[k]&0xf, l = cigar[k]>>4;
307                         if (op == BAM_CMATCH) {
308                                 for (i = y; i < y + l; ++i) {
309                                         if ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y)) qual[i] = 0;
310                                         else qual[i] = qual[i] < q[i]? qual[i] : q[i];
311                                 }
312                                 x += l; y += l;
313                         } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l;
314                         else if (op == BAM_CDEL) x += l;
315                 }
316                 free(s); free(r); free(q); free(state);
317         }
318         return 0;
319 }
320
321 int bam_fillmd(int argc, char *argv[])
322 {
323         int c, is_equal = 0, tid = -2, ret, len, is_bam_out, is_sam_in, is_uncompressed, max_nm = 0, is_realn, capQ = 0;
324         samfile_t *fp, *fpout = 0;
325         faidx_t *fai;
326         char *ref = 0, mode_w[8], mode_r[8];
327         bam1_t *b;
328
329         is_bam_out = is_sam_in = is_uncompressed = is_realn = 0;
330         mode_w[0] = mode_r[0] = 0;
331         strcpy(mode_r, "r"); strcpy(mode_w, "w");
332         while ((c = getopt(argc, argv, "reubSC:n:")) >= 0) {
333                 switch (c) {
334                 case 'r': is_realn = 1; break;
335                 case 'e': is_equal = 1; break;
336                 case 'b': is_bam_out = 1; break;
337                 case 'u': is_uncompressed = is_bam_out = 1; break;
338                 case 'S': is_sam_in = 1; break;
339                 case 'n': max_nm = atoi(optarg); break;
340                 case 'C': capQ = atoi(optarg); break;
341                 default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
342                 }
343         }
344         if (!is_sam_in) strcat(mode_r, "b");
345         if (is_bam_out) strcat(mode_w, "b");
346         else strcat(mode_w, "h");
347         if (is_uncompressed) strcat(mode_w, "u");
348         if (optind + 1 >= argc) {
349                 fprintf(stderr, "\n");
350                 fprintf(stderr, "Usage:   samtools fillmd [-eubrS] <aln.bam> <ref.fasta>\n\n");
351                 fprintf(stderr, "Options: -e       change identical bases to '='\n");
352                 fprintf(stderr, "         -u       uncompressed BAM output (for piping)\n");
353                 fprintf(stderr, "         -b       compressed BAM output\n");
354                 fprintf(stderr, "         -S       the input is SAM with header\n");
355                 fprintf(stderr, "         -r       read-independent local realignment\n\n");
356                 return 1;
357         }
358         fp = samopen(argv[optind], mode_r, 0);
359         if (fp == 0) return 1;
360         if (is_sam_in && (fp->header == 0 || fp->header->n_targets == 0)) {
361                 fprintf(stderr, "[bam_fillmd] input SAM does not have header. Abort!\n");
362                 return 1;
363         }
364         fpout = samopen("-", mode_w, fp->header);
365         fai = fai_load(argv[optind+1]);
366
367         b = bam_init1();
368         while ((ret = samread(fp, b)) >= 0) {
369                 if (b->core.tid >= 0) {
370                         if (tid != b->core.tid) {
371                                 free(ref);
372                                 ref = fai_fetch(fai, fp->header->target_name[b->core.tid], &len);
373                                 tid = b->core.tid;
374                                 if (ref == 0)
375                                         fprintf(stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
376                                                         fp->header->target_name[tid]);
377                         }
378 //                      if (is_realn) bam_realn(b, ref);
379                         if (is_realn) bam_prob_realn(b, ref);
380                         if (capQ > 10) {
381                                 int q = bam_cap_mapQ(b, ref, capQ);
382                                 if (b->core.qual > q) b->core.qual = q;
383                         }
384                         if (ref) bam_fillmd1_core(b, ref, is_equal, max_nm);
385                 }
386                 samwrite(fpout, b);
387         }
388         bam_destroy1(b);
389
390         free(ref);
391         fai_destroy(fai);
392         samclose(fp); samclose(fpout);
393         return 0;
394 }