]> git.donarmstrong.com Git - samtools.git/blob - bam2bcf_indel.c
* samtools-0.1.9-9 (r810)
[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 ap = { 1e-4, 1e-2, 10 };
240                 ap.bw = abs(types[t]) + 3;
241                 // compute indelreg
242                 if (types[t] == 0) ir = 0;
243                 else if (types[t] > 0) ir = est_indelreg(pos, ref, types[t], &inscns[t*max_ins]);
244                 else ir = est_indelreg(pos, ref, -types[t], 0);
245                 if (ir > bca->indelreg) bca->indelreg = ir;
246 //              fprintf(stderr, "%d, %d, %d\n", pos, types[t], ir);
247                 // write ref2
248                 for (k = 0, j = left; j <= pos; ++j)
249                         ref2[k++] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[j]]];
250                 if (types[t] <= 0) j += -types[t];
251                 else for (l = 0; l < types[t]; ++l)
252                                  ref2[k++] = inscns[t*max_ins + l];
253                 if (types[0] < 0) { // mask deleted sequences to avoid a particular error in the model.
254                         int jj, tmp = types[t] >= 0? -types[0] : -types[0] + types[t];
255                         for (jj = 0; jj < tmp && j < right && ref[j]; ++jj, ++j)
256                                 ref2[k++] = 4;
257                 }
258                 for (; j < right && ref[j]; ++j)
259                         ref2[k++] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[j]]];
260                 if (j < right) right = j;
261                 // align each read to ref2
262                 for (s = K = 0; s < n; ++s) {
263                         for (i = 0; i < n_plp[s]; ++i, ++K) {
264                                 bam_pileup1_t *p = plp[s] + i;
265                                 int qbeg, qend, tbeg, tend, sc;
266                                 uint8_t *seq = bam1_seq(p->b);
267                                 // FIXME: the following skips soft clips, but using them may be more sensitive.
268                                 // determine the start and end of sequences for alignment
269                                 qbeg = tpos2qpos(&p->b->core, bam1_cigar(p->b), left,  0, &tbeg);
270                                 qend = tpos2qpos(&p->b->core, bam1_cigar(p->b), right, 1, &tend);
271                                 if (types[t] < 0) {
272                                         int l = -types[t];
273                                         tbeg = tbeg - l > left?  tbeg - l : left;
274                                 }
275                                 // write the query sequence
276                                 for (l = qbeg; l < qend; ++l)
277                                         query[l - qbeg] = bam_nt16_nt4_table[bam1_seqi(seq, l)];
278                                 { // do alignment; this is the bottleneck
279                                         const uint8_t *qual = bam1_qual(p->b), *bq;
280                                         uint8_t *qq = 0;
281                                         qq = calloc(qend - qbeg, 1);
282                                         bq = (uint8_t*)bam_aux_get(p->b, "BQ");
283                                         if (bq) ++bq;
284                                         for (l = qbeg; l < qend; ++l)
285                                                 qq[l - qbeg] = bq? qual[l] + (bq[l] - 33) : qual[l];
286                                         sc = kpa_glocal((uint8_t*)ref2 + tbeg - left, tend - tbeg + abs(types[t]),
287                                                                         (uint8_t*)query, qend - qbeg, qq, &ap, 0, 0);
288                                         score[K*n_types + t] = sc;
289                                         free(qq);
290                                 }
291 /*
292                                 for (l = 0; l < tend - tbeg + abs(types[t]); ++l)
293                                         fputc("ACGTN"[(int)ref2[tbeg-left+l]], stderr);
294                                 fputc('\n', stderr);
295                                 for (l = 0; l < qend - qbeg; ++l) fputc("ACGTN"[(int)query[l]], stderr);
296                                 fputc('\n', stderr);
297                                 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);
298 */
299                         }
300                 }
301         }
302         free(ref2); free(query);
303         { // compute indelQ
304                 int *sc, tmp, *sumq;
305                 sc   = alloca(n_types * sizeof(int));
306                 sumq = alloca(n_types * sizeof(int));
307                 memset(sumq, 0, sizeof(int) * n_types);
308                 for (s = K = 0; s < n; ++s) {
309                         for (i = 0; i < n_plp[s]; ++i, ++K) {
310                                 bam_pileup1_t *p = plp[s] + i;
311                                 int *sct = &score[K*n_types], indelQ, seqQ;
312                                 for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t;
313                                 for (t = 1; t < n_types; ++t) // insertion sort
314                                         for (j = t; j > 0 && sc[j] < sc[j-1]; --j)
315                                                 tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp;
316                                 /* errmod_cal() assumes that if the call is wrong, the
317                                  * likelihoods of other events are equal. This is about
318                                  * right for substitutions, but is not desired for
319                                  * indels. To reuse errmod_cal(), I have to make
320                                  * compromise for multi-allelic indels.
321                                  */
322                                 if ((sc[0]&0x3f) == ref_type) {
323                                         indelQ = (sc[1]>>6) - (sc[0]>>6);
324                                         seqQ = est_seqQ(bca, types[sc[1]&0x3f], l_run);
325                                 } else {
326                                         for (t = 0; t < n_types; ++t) // look for the reference type
327                                                 if ((sc[t]&0x3f) == ref_type) break;
328                                         indelQ = (sc[t]>>6) - (sc[0]>>6);
329                                         seqQ = est_seqQ(bca, types[sc[0]&0x3f], l_run);
330                                 }
331                                 if (sc[0]>>6 > MAX_SCORE) indelQ = 0; // too many mismatches; something bad possibly happened
332                                 p->aux = (sc[0]&0x3f)<<16 | seqQ<<8 | indelQ;
333                                 sumq[sc[0]&0x3f] += indelQ < seqQ? indelQ : seqQ;
334 //                              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);
335                         }
336                 }
337                 // determine bca->indel_types[] and bca->inscns
338                 bca->maxins = max_ins;
339                 bca->inscns = realloc(bca->inscns, bca->maxins * 4);
340                 for (t = 0; t < n_types; ++t)
341                         sumq[t] = sumq[t]<<6 | t;
342                 for (t = 1; t < n_types; ++t) // insertion sort
343                         for (j = t; j > 0 && sumq[j] > sumq[j-1]; --j)
344                                 tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp;
345                 for (t = 0; t < n_types; ++t) // look for the reference type
346                         if ((sumq[t]&0x3f) == ref_type) break;
347                 if (t) { // then move the reference type to the first
348                         tmp = sumq[t];
349                         for (; t > 0; --t) sumq[t] = sumq[t-1];
350                         sumq[0] = tmp;
351                 }
352                 for (t = 0; t < 4; ++t) bca->indel_types[t] = B2B_INDEL_NULL;
353                 for (t = 0; t < 4 && t < n_types; ++t) {
354                         bca->indel_types[t] = types[sumq[t]&0x3f];
355                         memcpy(&bca->inscns[t * bca->maxins], &inscns[(sumq[t]&0x3f) * max_ins], bca->maxins);
356                 }
357                 // update p->aux
358                 for (s = n_alt = 0; s < n; ++s) {
359                         for (i = 0; i < n_plp[s]; ++i) {
360                                 bam_pileup1_t *p = plp[s] + i;
361                                 int x = types[p->aux>>16&0x3f];
362                                 for (j = 0; j < 4; ++j)
363                                         if (x == bca->indel_types[j]) break;
364                                 p->aux = j<<16 | (j == 4? 0 : (p->aux&0xffff));
365                                 if ((p->aux>>16&0x3f) > 0) ++n_alt;
366 //                              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);
367                         }
368                 }               
369         }
370         free(score);
371         // free
372         free(types); free(inscns);
373         return n_alt > 0? 0 : -1;
374 }