]> git.donarmstrong.com Git - samtools.git/blob - bam2bcf_indel.c
* samtools-0.1.9-10 (r816)
[samtools.git] / bam2bcf_indel.c
1 #include <assert.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include "bam.h"
5 #include "bam2bcf.h"
6 #include "ksort.h"
7 #include "kaln.h"
8 #include "kprobaln.h"
9 #include "khash.h"
10 KHASH_SET_INIT_STR(rg)
11
12 #define MINUS_CONST 0x10000000
13 #define INDEL_WINDOW_SIZE 50
14 #define MAX_SCORE 90
15
16 void *bcf_call_add_rg(void *_hash, const char *hdtext, const char *list)
17 {
18         const char *s, *p, *q, *r, *t;
19         khash_t(rg) *hash;
20         if (list == 0 || hdtext == 0) return _hash;
21         if (_hash == 0) _hash = kh_init(rg);
22         hash = (khash_t(rg)*)_hash;
23         if ((s = strstr(hdtext, "@RG\t")) == 0) return hash;
24         do {
25                 t = strstr(s + 4, "@RG\t"); // the next @RG
26                 if ((p = strstr(s, "\tID:")) != 0) p += 4;
27                 if ((q = strstr(s, "\tPL:")) != 0) q += 4;
28                 if (p && q && (t == 0 || (p < t && q < t))) { // ID and PL are both present
29                         int lp, lq;
30                         char *x;
31                         for (r = p; *r && *r != '\t' && *r != '\n'; ++r); lp = r - p;
32                         for (r = q; *r && *r != '\t' && *r != '\n'; ++r); lq = r - q;
33                         x = calloc((lp > lq? lp : lq) + 1, 1);
34                         for (r = q; *r && *r != '\t' && *r != '\n'; ++r) x[r-q] = *r;
35                         if (strstr(list, x)) { // insert ID to the hash table
36                                 khint_t k;
37                                 int ret;
38                                 for (r = p; *r && *r != '\t' && *r != '\n'; ++r) x[r-p] = *r;
39                                 x[r-p] = 0;
40                                 k = kh_get(rg, hash, x);
41                                 if (k == kh_end(hash)) k = kh_put(rg, hash, x, &ret);
42                                 else free(x);
43                         } else free(x);
44                 }
45                 s = t;
46         } while (s);
47         return hash;
48 }
49
50 void bcf_call_del_rghash(void *_hash)
51 {
52         khint_t k;
53         khash_t(rg) *hash = (khash_t(rg)*)_hash;
54         if (hash == 0) return;
55         for (k = kh_begin(hash); k < kh_end(hash); ++k)
56                 if (kh_exist(hash, k))
57                         free((char*)kh_key(hash, k));
58         kh_destroy(rg, hash);
59 }
60
61 static int tpos2qpos(const bam1_core_t *c, const uint32_t *cigar, int32_t tpos, int is_left, int32_t *_tpos)
62 {
63         int k, x = c->pos, y = 0, last_y = 0;
64         *_tpos = c->pos;
65         for (k = 0; k < c->n_cigar; ++k) {
66                 int op = cigar[k] & BAM_CIGAR_MASK;
67                 int l = cigar[k] >> BAM_CIGAR_SHIFT;
68                 if (op == BAM_CMATCH) {
69                         if (c->pos > tpos) return y;
70                         if (x + l > tpos) {
71                                 *_tpos = tpos;
72                                 return y + (tpos - x);
73                         }
74                         x += l; y += l;
75                         last_y = y;
76                 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l;
77                 else if (op == BAM_CDEL || op == BAM_CREF_SKIP) {
78                         if (x + l > tpos) {
79                                 *_tpos = is_left? x : x + l;
80                                 return y;
81                         }
82                         x += l;
83                 }
84         }
85         *_tpos = x;
86         return last_y;
87 }
88 // FIXME: check if the inserted sequence is consistent with the homopolymer run
89 // l is the relative gap length and l_run is the length of the homopolymer on the reference
90 static inline int est_seqQ(const bcf_callaux_t *bca, int l, int l_run)
91 {
92         int q, qh;
93         q = bca->openQ + bca->extQ * (abs(l) - 1);
94         qh = l_run >= 3? (int)(bca->tandemQ * (double)abs(l) / l_run + .499) : 1000;
95         return q < qh? q : qh;
96 }
97
98 static inline int est_indelreg(int pos, const char *ref, int l, char *ins4)
99 {
100         int i, j, max = 0, max_i = pos, score = 0;
101         l = abs(l);
102         for (i = pos + 1, j = 0; ref[i]; ++i, ++j) {
103                 if (ins4) score += (toupper(ref[i]) != "ACGTN"[(int)ins4[j%l]])? -10 : 1;
104                 else score += (toupper(ref[i]) != toupper(ref[pos+1+j%l]))? -10 : 1;
105                 if (score < 0) break;
106                 if (max < score) max = score, max_i = i;
107         }
108         return max_i - pos;
109 }
110
111 int bcf_call_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref,
112                                           const void *rghash)
113 {
114         extern void ks_introsort_uint32_t(int, uint32_t*);
115         int i, s, j, k, t, n_types, *types, max_rd_len, left, right, max_ins, *score, N, K, l_run, ref_type, n_alt;
116         char *inscns = 0, *ref2, *query;
117         khash_t(rg) *hash = (khash_t(rg)*)rghash;
118         if (ref == 0 || bca == 0) return -1;
119         // mark filtered reads
120         if (rghash) {
121                 N = 0;
122                 for (s = N = 0; s < n; ++s) {
123                         for (i = 0; i < n_plp[s]; ++i) {
124                                 bam_pileup1_t *p = plp[s] + i;
125                                 const uint8_t *rg = bam_aux_get(p->b, "RG");
126                                 p->aux = 1; // filtered by default
127                                 if (rg) {
128                                         khint_t k = kh_get(rg, hash, (const char*)(rg + 1));
129                                         if (k != kh_end(hash)) p->aux = 0, ++N; // not filtered
130                                 }
131                         }
132                 }
133                 if (N == 0) return -1; // no reads left
134         }
135         // determine if there is a gap
136         for (s = N = 0; s < n; ++s) {
137                 for (i = 0; i < n_plp[s]; ++i)
138                         if (plp[s][i].indel != 0) break;
139                 if (i < n_plp[s]) break;
140         }
141         if (s == n) return -1; // there is no indel at this position.
142         for (s = N = 0; s < n; ++s) N += n_plp[s]; // N is the total number of reads
143         { // find out how many types of indels are present
144                 int m;
145                 uint32_t *aux;
146                 aux = calloc(N + 1, 4);
147                 m = max_rd_len = 0;
148                 aux[m++] = MINUS_CONST; // zero indel is always a type
149                 for (s = 0; s < n; ++s) {
150                         for (i = 0; i < n_plp[s]; ++i) {
151                                 const bam_pileup1_t *p = plp[s] + i;
152                                 if (p->indel != 0 && (rghash == 0 || p->aux == 0))
153                                         aux[m++] = MINUS_CONST + p->indel;
154                                 j = bam_cigar2qlen(&p->b->core, bam1_cigar(p->b));
155                                 if (j > max_rd_len) max_rd_len = j;
156                         }
157                 }
158                 ks_introsort(uint32_t, m, aux);
159                 // squeeze out identical types
160                 for (i = 1, n_types = 1; i < m; ++i)
161                         if (aux[i] != aux[i-1]) ++n_types;
162                 if (n_types == 1) { // no indels
163                         free(aux); return -1;
164                 }
165                 types = (int*)calloc(n_types, sizeof(int));
166                 t = 0;
167                 types[t++] = aux[0] - MINUS_CONST; 
168                 for (i = 1; i < m; ++i)
169                         if (aux[i] != aux[i-1])
170                                 types[t++] = aux[i] - MINUS_CONST;
171                 free(aux);
172                 for (t = 0; t < n_types; ++t)
173                         if (types[t] == 0) break;
174                 ref_type = t; // the index of the reference type (0)
175                 assert(n_types < 64);
176         }
177         { // calculate left and right boundary
178                 left = pos > INDEL_WINDOW_SIZE? pos - INDEL_WINDOW_SIZE : 0;
179                 right = pos + INDEL_WINDOW_SIZE;
180                 if (types[0] < 0) right -= types[0];
181                 // in case the alignments stand out the reference
182                 for (i = pos; i < right; ++i)
183                         if (ref[i] == 0) break;
184                 right = i;
185         }
186         { // the length of the homopolymer run around the current position
187                 int c = bam_nt16_table[(int)ref[pos + 1]];
188                 if (c == 15) l_run = 1;
189                 else {
190                         for (i = pos + 2; ref[i]; ++i)
191                                 if (bam_nt16_table[(int)ref[i]] != c) break;
192                         l_run = i;
193                         for (i = pos; i >= 0; --i)
194                                 if (bam_nt16_table[(int)ref[i]] != c) break;
195                         l_run -= i + 1;
196                 }
197         }
198         // construct the consensus sequence
199         max_ins = types[n_types - 1]; // max_ins is at least 0
200         if (max_ins > 0) {
201                 int *inscns_aux = calloc(4 * n_types * max_ins, sizeof(int));
202                 // count the number of occurrences of each base at each position for each type of insertion
203                 for (t = 0; t < n_types; ++t) {
204                         if (types[t] > 0) {
205                                 for (s = 0; s < n; ++s) {
206                                         for (i = 0; i < n_plp[s]; ++i) {
207                                                 bam_pileup1_t *p = plp[s] + i;
208                                                 if (p->indel == types[t]) {
209                                                         uint8_t *seq = bam1_seq(p->b);
210                                                         for (k = 1; k <= p->indel; ++k) {
211                                                                 int c = bam_nt16_nt4_table[bam1_seqi(seq, p->qpos + k)];
212                                                                 if (c < 4) ++inscns_aux[(t*max_ins+(k-1))*4 + c];
213                                                         }
214                                                 }
215                                         }
216                                 }
217                         }
218                 }
219                 // use the majority rule to construct the consensus
220                 inscns = calloc(n_types * max_ins, 1);
221                 for (t = 0; t < n_types; ++t) {
222                         for (j = 0; j < types[t]; ++j) {
223                                 int max = 0, max_k = -1, *ia = &inscns_aux[(t*max_ins+j)*4];
224                                 for (k = 0; k < 4; ++k)
225                                         if (ia[k] > max)
226                                                 max = ia[k], max_k = k;
227                                 inscns[t*max_ins + j] = max? max_k : 4;
228                         }
229                 }
230                 free(inscns_aux);
231         }
232         // compute the likelihood given each type of indel for each read
233         ref2  = calloc(right - left + max_ins + 2, 1);
234         query = calloc(right - left + max_rd_len + max_ins + 2, 1);
235         score = calloc(N * n_types, sizeof(int));
236         bca->indelreg = 0;
237         for (t = 0; t < n_types; ++t) {
238                 int l, ir;
239                 kpa_par_t apf = { 1e-4, 1e-2, 10 };
240                 ka_param2_t apv = ka_param2_qual;
241                 apf.bw = apv.band_width = abs(types[t]) + 3;
242                 // compute indelreg
243                 if (types[t] == 0) ir = 0;
244                 else if (types[t] > 0) ir = est_indelreg(pos, ref, types[t], &inscns[t*max_ins]);
245                 else ir = est_indelreg(pos, ref, -types[t], 0);
246                 if (ir > bca->indelreg) bca->indelreg = ir;
247 //              fprintf(stderr, "%d, %d, %d\n", pos, types[t], ir);
248                 // write ref2
249                 for (k = 0, j = left; j <= pos; ++j)
250                         ref2[k++] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[j]]];
251                 if (types[t] <= 0) j += -types[t];
252                 else for (l = 0; l < types[t]; ++l)
253                                  ref2[k++] = inscns[t*max_ins + l];
254                 if (types[0] < 0) { // mask deleted sequences to avoid a particular error in the model.
255                         int jj, tmp = types[t] >= 0? -types[0] : -types[0] + types[t];
256                         for (jj = 0; jj < tmp && j < right && ref[j]; ++jj, ++j)
257                                 ref2[k++] = 4;
258                 }
259                 for (; j < right && ref[j]; ++j)
260                         ref2[k++] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[j]]];
261                 if (j < right) right = j;
262                 // align each read to ref2
263                 for (s = K = 0; s < n; ++s) {
264                         for (i = 0; i < n_plp[s]; ++i, ++K) {
265                                 bam_pileup1_t *p = plp[s] + i;
266                                 int qbeg, qend, tbeg, tend, sc;
267                                 uint8_t *seq = bam1_seq(p->b);
268                                 // FIXME: the following skips soft clips, but using them may be more sensitive.
269                                 // determine the start and end of sequences for alignment
270                                 qbeg = tpos2qpos(&p->b->core, bam1_cigar(p->b), left,  0, &tbeg);
271                                 qend = tpos2qpos(&p->b->core, bam1_cigar(p->b), right, 1, &tend);
272                                 if (types[t] < 0) {
273                                         int l = -types[t];
274                                         tbeg = tbeg - l > left?  tbeg - l : left;
275                                 }
276                                 // write the query sequence
277                                 for (l = qbeg; l < qend; ++l)
278                                         query[l - qbeg] = bam_nt16_nt4_table[bam1_seqi(seq, l)];
279                                 // do alignment; this is the bottleneck
280                                 if (1) {
281                                         const uint8_t *qual = bam1_qual(p->b), *bq;
282                                         uint8_t *qq = 0;
283                                         qq = calloc(qend - qbeg, 1);
284                                         bq = (uint8_t*)bam_aux_get(p->b, "BQ");
285                                         if (bq) ++bq;
286                                         for (l = qbeg; l < qend; ++l) {
287                                                 qq[l - qbeg] = bq? qual[l] + (bq[l] - 33) : qual[l];
288                                                 if (qq[l - qbeg] > 30) qq[l - qbeg] = 30;
289                                                 if (qq[l - qbeg] < 7) qq[l - qbeg] = 7;
290                                         }
291                                         sc = kpa_glocal((uint8_t*)ref2 + tbeg - left, tend - tbeg + abs(types[t]),
292                                                                         (uint8_t*)query, qend - qbeg, qq, &apf, 0, 0);
293                                         score[K*n_types + t] = sc;
294                                         free(qq);
295                                 } else { // the following block is for testing only
296                                         sc = ka_global_score((uint8_t*)ref2 + tbeg - left, tend - tbeg + abs(types[t]),
297                                                                                  (uint8_t*)query, qend - qbeg, &apv);
298                                         score[K*n_types + t] = -sc;
299                                 }
300 /*
301                                 for (l = 0; l < tend - tbeg + abs(types[t]); ++l)
302                                         fputc("ACGTN"[(int)ref2[tbeg-left+l]], stderr);
303                                 fputc('\n', stderr);
304                                 for (l = 0; l < qend - qbeg; ++l) fputc("ACGTN"[(int)query[l]], stderr);
305                                 fputc('\n', stderr);
306                                 fprintf(stderr, "pos=%d type=%d read=%d:%d name=%s qbeg=%d tbeg=%d score=%d\n", pos, types[t], s, i, bam1_qname(p->b), qbeg, tbeg, sc);
307 */
308                         }
309                 }
310         }
311         free(ref2); free(query);
312         { // compute indelQ
313                 int *sc, tmp, *sumq;
314                 sc   = alloca(n_types * sizeof(int));
315                 sumq = alloca(n_types * sizeof(int));
316                 memset(sumq, 0, sizeof(int) * n_types);
317                 for (s = K = 0; s < n; ++s) {
318                         for (i = 0; i < n_plp[s]; ++i, ++K) {
319                                 bam_pileup1_t *p = plp[s] + i;
320                                 int *sct = &score[K*n_types], indelQ, seqQ;
321                                 for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t;
322                                 for (t = 1; t < n_types; ++t) // insertion sort
323                                         for (j = t; j > 0 && sc[j] < sc[j-1]; --j)
324                                                 tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp;
325                                 /* errmod_cal() assumes that if the call is wrong, the
326                                  * likelihoods of other events are equal. This is about
327                                  * right for substitutions, but is not desired for
328                                  * indels. To reuse errmod_cal(), I have to make
329                                  * compromise for multi-allelic indels.
330                                  */
331                                 if ((sc[0]&0x3f) == ref_type) {
332                                         indelQ = (sc[1]>>6) - (sc[0]>>6);
333                                         seqQ = est_seqQ(bca, types[sc[1]&0x3f], l_run);
334                                 } else {
335                                         for (t = 0; t < n_types; ++t) // look for the reference type
336                                                 if ((sc[t]&0x3f) == ref_type) break;
337                                         indelQ = (sc[t]>>6) - (sc[0]>>6);
338                                         seqQ = est_seqQ(bca, types[sc[0]&0x3f], l_run);
339                                 }
340                                 if (sc[0]>>6 > MAX_SCORE) indelQ = 0; // too many mismatches; something bad possibly happened
341                                 p->aux = (sc[0]&0x3f)<<16 | seqQ<<8 | indelQ;
342                                 sumq[sc[0]&0x3f] += indelQ < seqQ? indelQ : seqQ;
343 //                              fprintf(stderr, "pos=%d read=%d:%d name=%s call=%d q=%d\n", pos, s, i, bam1_qname(p->b), types[sc[0]&0x3f], indelQ);
344                         }
345                 }
346                 // determine bca->indel_types[] and bca->inscns
347                 bca->maxins = max_ins;
348                 bca->inscns = realloc(bca->inscns, bca->maxins * 4);
349                 for (t = 0; t < n_types; ++t)
350                         sumq[t] = sumq[t]<<6 | t;
351                 for (t = 1; t < n_types; ++t) // insertion sort
352                         for (j = t; j > 0 && sumq[j] > sumq[j-1]; --j)
353                                 tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp;
354                 for (t = 0; t < n_types; ++t) // look for the reference type
355                         if ((sumq[t]&0x3f) == ref_type) break;
356                 if (t) { // then move the reference type to the first
357                         tmp = sumq[t];
358                         for (; t > 0; --t) sumq[t] = sumq[t-1];
359                         sumq[0] = tmp;
360                 }
361                 for (t = 0; t < 4; ++t) bca->indel_types[t] = B2B_INDEL_NULL;
362                 for (t = 0; t < 4 && t < n_types; ++t) {
363                         bca->indel_types[t] = types[sumq[t]&0x3f];
364                         memcpy(&bca->inscns[t * bca->maxins], &inscns[(sumq[t]&0x3f) * max_ins], bca->maxins);
365                 }
366                 // update p->aux
367                 for (s = n_alt = 0; s < n; ++s) {
368                         for (i = 0; i < n_plp[s]; ++i) {
369                                 bam_pileup1_t *p = plp[s] + i;
370                                 int x = types[p->aux>>16&0x3f];
371                                 for (j = 0; j < 4; ++j)
372                                         if (x == bca->indel_types[j]) break;
373                                 p->aux = j<<16 | (j == 4? 0 : (p->aux&0xffff));
374                                 if ((p->aux>>16&0x3f) > 0) ++n_alt;
375 //                              fprintf(stderr, "X pos=%d read=%d:%d name=%s call=%d type=%d q=%d seqQ=%d\n", pos, s, i, bam1_qname(p->b), p->aux>>16&63, bca->indel_types[p->aux>>16&63], p->aux&0xff, p->aux>>8&0xff);
376                         }
377                 }               
378         }
379         free(score);
380         // free
381         free(types); free(inscns);
382         return n_alt > 0? 0 : -1;
383 }