]> git.donarmstrong.com Git - samtools.git/blob - bam_md.c
fixed a bug in realignment
[samtools.git] / bam_md.c
1 #include <unistd.h>
2 #include <assert.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include "faidx.h"
6 #include "sam.h"
7 #include "kstring.h"
8 #include "kaln.h"
9
10 void bam_fillmd1_core(bam1_t *b, char *ref, int is_equal, int max_nm)
11 {
12         uint8_t *seq = bam1_seq(b);
13         uint32_t *cigar = bam1_cigar(b);
14         bam1_core_t *c = &b->core;
15         int i, x, y, u = 0;
16         kstring_t *str;
17         uint8_t *old_md, *old_nm;
18         int32_t old_nm_i = -1, nm = 0;
19
20         str = (kstring_t*)calloc(1, sizeof(kstring_t));
21         for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
22                 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
23                 if (op == BAM_CMATCH) {
24                         for (j = 0; j < l; ++j) {
25                                 int z = y + j;
26                                 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
27                                 if (ref[x+j] == 0) break; // out of boundary
28                                 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
29                                         if (is_equal) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
30                                         ++u;
31                                 } else {
32                                         ksprintf(str, "%d", u);
33                                         kputc(ref[x+j], str);
34                                         u = 0; ++nm;
35                                 }
36                         }
37                         if (j < l) break;
38                         x += l; y += l;
39                 } else if (op == BAM_CDEL) {
40                         ksprintf(str, "%d", u);
41                         kputc('^', str);
42                         for (j = 0; j < l; ++j) {
43                                 if (ref[x+j] == 0) break;
44                                 kputc(ref[x+j], str);
45                         }
46                         u = 0;
47                         if (j < l) break;
48                         x += l; nm += l;
49                 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
50                         y += l;
51                         if (op == BAM_CINS) nm += l;
52                 } else if (op == BAM_CREF_SKIP) {
53                         x += l;
54                 }
55         }
56         ksprintf(str, "%d", u);
57         // apply max_nm
58         if (max_nm > 0 && nm >= max_nm) {
59                 for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
60                         int j, l = cigar[i]>>4, op = cigar[i]&0xf;
61                         if (op == BAM_CMATCH) {
62                                 for (j = 0; j < l; ++j) {
63                                         int z = y + j;
64                                         int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
65                                         if (ref[x+j] == 0) break; // out of boundary
66                                         if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
67                                                 seq[z/2] |= (z&1)? 0x0f : 0xf0;
68                                                 bam1_qual(b)[z] = 0;
69                                         }
70                                 }
71                                 if (j < l) break;
72                                 x += l; y += l;
73                         } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) x += l;
74                         else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l;
75                 }
76         }
77         // update NM
78         old_nm = bam_aux_get(b, "NM");
79         if (c->flag & BAM_FUNMAP) return;
80         if (old_nm) old_nm_i = bam_aux2i(old_nm);
81         if (!old_nm) bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
82         else if (nm != old_nm_i) {
83                 fprintf(stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam1_qname(b), old_nm_i, nm);
84                 bam_aux_del(b, old_nm);
85                 bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm);
86         }
87         // update MD
88         old_md = bam_aux_get(b, "MD");
89         if (!old_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
90         else {
91                 int is_diff = 0;
92                 if (strlen((char*)old_md+1) == str->l) {
93                         for (i = 0; i < str->l; ++i)
94                                 if (toupper(old_md[i+1]) != toupper(str->s[i]))
95                                         break;
96                         if (i < str->l) is_diff = 1;
97                 } else is_diff = 1;
98                 if (is_diff) {
99                         fprintf(stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam1_qname(b), old_md+1, str->s);
100                         bam_aux_del(b, old_md);
101                         bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
102                 }
103         }
104         free(str->s); free(str);
105 }
106
107 void bam_fillmd1(bam1_t *b, char *ref, int is_equal)
108 {
109         bam_fillmd1_core(b, ref, is_equal, 0);
110 }
111
112 // local realignment
113
114 #define MIN_REF_LEN 10
115
116 int bam_realn(bam1_t *b, const char *ref)
117 {
118         int k, l_ref, score, n_cigar;
119         uint32_t *cigar = bam1_cigar(b);
120         uint8_t *s_ref = 0, *s_read = 0, *seq;
121         ka_param_t par;
122         bam1_core_t *c = &b->core;
123         // set S/W parameters
124         par = ka_param_blast; par.gap_open = 4; par.gap_ext = 1; par.gap_end_open = par.gap_end_ext = 0;
125         // calculate the length of the reference in the alignment
126         for (k = l_ref = 0; k < c->n_cigar; ++k) {
127                 if ((cigar[k]&0xf) == BAM_CREF_SKIP) break; // do not do realignment if there is an `N' operation
128                 if ((cigar[k]&0xf) == BAM_CMATCH || (cigar[k]&0xf) == BAM_CDEL)
129                         l_ref += cigar[k]>>4;
130         }
131         if (k != c->n_cigar || l_ref < MIN_REF_LEN) return -1;
132         for (k = 0; k < l_ref; ++k)
133                 if (ref[c->pos + k] == 0) return -1; // the read stands out of the reference
134         // allocate
135         s_ref = calloc(l_ref, 1);
136         s_read = calloc(c->l_qseq, 1);
137         for (k = 0, seq = bam1_seq(b); k < c->l_qseq; ++k)
138                 s_read[k] = bam_nt16_nt4_table[bam1_seqi(seq, k)];
139         for (k = 0; k < l_ref; ++k)
140                 s_ref[k] = bam_nt16_nt4_table[(int)bam_nt16_table[(int)ref[c->pos + k]]];
141         // do alignment
142         cigar = ka_global_core(s_ref, l_ref, s_read, c->l_qseq, &par, &score, &n_cigar);
143         if (score <= 0) { // realignment failed
144                 free(cigar); free(s_ref); free(s_read);
145                 return -1;
146         }
147         // copy over the alignment
148         if (4 * (n_cigar - (int)c->n_cigar) + b->data_len > b->m_data) { // enlarge b->data
149                 b->m_data = 4 * (n_cigar - (int)c->n_cigar) + b->data_len;
150                 kroundup32(b->m_data);
151                 b->data = realloc(b->data, b->m_data);
152         }
153         if (n_cigar != (int)c->n_cigar) { // move data
154                 memmove(b->data + c->l_qname + 4 * n_cigar, bam1_seq(b), b->data_len - c->l_qname - 4 * c->n_cigar);
155                 b->data_len += 4 * (n_cigar - (int)c->n_cigar);
156         }
157         memcpy(bam1_cigar(b), cigar, n_cigar * 4);
158         c->n_cigar = n_cigar;
159         free(s_ref); free(s_read); free(cigar);
160         return 0;
161 }
162
163 int bam_fillmd(int argc, char *argv[])
164 {
165         int c, is_equal = 0, tid = -2, ret, len, is_bam_out, is_sam_in, is_uncompressed, max_nm = 0, is_realn;
166         samfile_t *fp, *fpout = 0;
167         faidx_t *fai;
168         char *ref = 0, mode_w[8], mode_r[8];
169         bam1_t *b;
170
171         is_bam_out = is_sam_in = is_uncompressed = is_realn = 0;
172         mode_w[0] = mode_r[0] = 0;
173         strcpy(mode_r, "r"); strcpy(mode_w, "w");
174         while ((c = getopt(argc, argv, "reubSn:")) >= 0) {
175                 switch (c) {
176                 case 'r': is_realn = 1; break;
177                 case 'e': is_equal = 1; break;
178                 case 'b': is_bam_out = 1; break;
179                 case 'u': is_uncompressed = is_bam_out = 1; break;
180                 case 'S': is_sam_in = 1; break;
181                 case 'n': max_nm = atoi(optarg); break;
182                 default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
183                 }
184         }
185         if (!is_sam_in) strcat(mode_r, "b");
186         if (is_bam_out) strcat(mode_w, "b");
187         else strcat(mode_w, "h");
188         if (is_uncompressed) strcat(mode_w, "u");
189         if (optind + 1 >= argc) {
190                 fprintf(stderr, "\n");
191                 fprintf(stderr, "Usage:   samtools fillmd [-eubrS] <aln.bam> <ref.fasta>\n\n");
192                 fprintf(stderr, "Options: -e       change identical bases to '='\n");
193                 fprintf(stderr, "         -u       uncompressed BAM output (for piping)\n");
194                 fprintf(stderr, "         -b       compressed BAM output\n");
195                 fprintf(stderr, "         -S       the input is SAM with header\n");
196                 fprintf(stderr, "         -r       read-independent local realignment\n\n");
197                 return 1;
198         }
199         fp = samopen(argv[optind], mode_r, 0);
200         if (fp == 0) return 1;
201         if (is_sam_in && (fp->header == 0 || fp->header->n_targets == 0)) {
202                 fprintf(stderr, "[bam_fillmd] input SAM does not have header. Abort!\n");
203                 return 1;
204         }
205         fpout = samopen("-", mode_w, fp->header);
206         fai = fai_load(argv[optind+1]);
207
208         b = bam_init1();
209         while ((ret = samread(fp, b)) >= 0) {
210                 if (b->core.tid >= 0) {
211                         if (tid != b->core.tid) {
212                                 free(ref);
213                                 ref = fai_fetch(fai, fp->header->target_name[b->core.tid], &len);
214                                 tid = b->core.tid;
215                                 if (ref == 0)
216                                         fprintf(stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
217                                                         fp->header->target_name[tid]);
218                         }
219                         if (is_realn) bam_realn(b, ref);
220                         if (ref) bam_fillmd1_core(b, ref, is_equal, max_nm);
221                 }
222                 samwrite(fpout, b);
223         }
224         bam_destroy1(b);
225
226         free(ref);
227         fai_destroy(fai);
228         samclose(fp); samclose(fpout);
229         return 0;
230 }