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