Debian Codegraph @

samtools/consensus_pileup.c

raw symbols SCIP
1 /* consensus__pileup.h -- Pileup orientated data per consensus column
2
3 Copyright (C) 2013-2016, 2020-2022 Genome Research Ltd.
4
5 Author: James Bonfied <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notices and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 DEALINGS IN THE SOFTWARE. */
24
25 #include <config.h>
26 #include <htslib/sam.h>
27
28 #ifdef __SSE__
29 # include <xmmintrin.h>
30 #else
31 # define _mm_prefetch(a,b)
32 #endif
33
34 #include "consensus_pileup.h"
35
36 #define MIN(a,b) ((a)<(b)?(a):(b))
37 #define bam_strand(b) (((b)->core.flag & BAM_FREVERSE) != 0)
38
39 /*
40 * START_WITH_DEL is the mode that Gap5 uses when building this. It prepends
41 * all cigar strings with 1D and decrements the position by one. (And then
42 * has code to reverse this operation in the pileup handler.)
43 *
44 * The reason for this is that it means reads starting with an insertion work.
45 * Otherwise the inserted bases are silently lost. (Try it with "samtools
46 * mpileup" and you can see it has the same issue.)
47 *
48 * However it's probably not want most people expect.
49 */
50 //#define START_WITH_DEL
51
52 /* --------------------------------------------------------------------------
53 * The pileup code itself.
54 *
55 * This consists of the external pileup_loop() function, which takes a
56 * sam/bam samfile_t pointer and a callback function. The callback function
57 * is called once per column of aligned data (so once per base in an
58 * insertion).
59 *
60 * Current known issues.
61 * 1) zero length matches, ie 2S2S cause failures.
62 * 2) Insertions at starts of sequences get included in the soft clip, so
63 * 2S2I2M is treated as if it's 4S2M
64 * 3) From 1 and 2 above, 1S1I2S becomes 2S2S which fails.
65 */
66
67
68 /*
69 * Fetches the next base => the nth base at unpadded position pos. (Nth can
70 * be greater than 0 if we have an insertion in this column). Do not call this
71 * with pos/nth lower than the previous query, although higher is better.
72 * (This allows it to be initialised at base 0.)
73 *
74 * Stores the result in base and also updates is_insert to indicate that
75 * this sequence still has more bases in this position beyond the current
76 * nth parameter.
77 *
78 * Returns 1 if a base was fetched
79 * 0 if not (eg ran off the end of sequence)
80 */
81 static int get_next_base(pileup_t *p, hts_pos_t pos, int nth, int *is_insert) {
82 bam1_t *b = &p->b;
83 int op = p->cigar_op;
84
85 p->start -= p->start>0;
86 if (p->first_del && op != BAM_CPAD)
87 p->first_del = 0;
88
89 *is_insert = 0;
90
91 /* Find pos first */
92 while (p->pos < pos) {
93 p->nth = 0;
94
95 if (p->cigar_len == 0) {
96 if (p->cigar_ind >= b->core.n_cigar) {
97 p->eof = 1;
98 return 0;
99 }
100
101 op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK;
102 p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT;
103 p->cigar_ind++;
104 }
105
106 if ((op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF)
107 && p->cigar_len <= pos - p->pos) {
108 p->seq_offset += p->cigar_len;
109 p->pos += p->cigar_len;
110 p->cigar_len = 0;
111 } else {
112 switch (op) {
113 case BAM_CMATCH:
114 case BAM_CEQUAL:
115 case BAM_CDIFF:
116 p->seq_offset++;
117 /* Fall through */
118 case BAM_CDEL:
119 case BAM_CREF_SKIP:
120 p->pos++;
121 p->cigar_len--;
122 break;
123
124 case BAM_CINS:
125 case BAM_CSOFT_CLIP:
126 p->seq_offset += p->cigar_len;
127 /* Fall through */
128 case BAM_CPAD:
129 case BAM_CHARD_CLIP:
130 p->cigar_len = 0;
131 break;
132
133 default:
134 fprintf(stderr, "Unhandled cigar_op %d\n", op);
135 return -1;
136 }
137 }
138 }
139
140 /* Now at pos, find nth base */
141 while (p->nth < nth) {
142 if (p->cigar_len == 0) {
143 if (p->cigar_ind >= b->core.n_cigar) {
144 p->eof = 1;
145 return 0; /* off end of seq */
146 }
147
148 op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK;
149 p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT;
150 p->cigar_ind++;
151 }
152
153 switch (op) {
154 case BAM_CMATCH:
155 case BAM_CEQUAL:
156 case BAM_CDIFF:
157 case BAM_CSOFT_CLIP:
158 case BAM_CDEL:
159 case BAM_CREF_SKIP:
160 goto at_nth; /* sorry, but it's fast! */
161
162 case BAM_CINS:
163 p->seq_offset++;
164 /* Fall through */
165 case BAM_CPAD:
166 p->cigar_len--;
167 p->nth++;
168 break;
169
170 case BAM_CHARD_CLIP:
171 p->cigar_len = 0;
172 break;
173
174 default:
175 fprintf(stderr, "Unhandled cigar_op %d\n", op);
176 return -1;
177 }
178 }
179 at_nth:
180
181 /* Fill out base & qual fields */
182 p->ref_skip = 0;
183 if (p->nth < nth && op != BAM_CINS) {
184 //p->base = '-';
185 p->base = '*';
186 p->base4 = 16;
187 p->padding = 1;
188 if (p->seq_offset < b->core.l_qseq)
189 p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]);
190 else
191 p->qual = 0;
192 } else {
193 p->padding = 0;
194 switch(op) {
195 case BAM_CDEL:
196 p->base = '*';
197 p->base4 = 16;
198 if (p->seq_offset+1 < b->core.l_qseq)
199 p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]);
200 else
201 p->qual = MIN(p->qual, p->b_qual[p->seq_offset]);
202 break;
203
204 case BAM_CPAD:
205 //p->base = '+';
206 p->base = '*';
207 p->base4 = 16;
208 if (p->seq_offset+1 < b->core.l_qseq)
209 p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]);
210 else
211 p->qual = MIN(p->qual, p->b_qual[p->seq_offset]);
212 break;
213
214 case BAM_CREF_SKIP:
215 p->base = '.';
216 p->base4 = 0;
217 p->qual = 0;
218 /* end of fragment, but not sequence */
219 p->eof = p->eof ? 2 : 3;
220 p->ref_skip = 1;
221 break;
222
223 default:
224 if (p->seq_offset < b->core.l_qseq) {
225 p->qual = p->b_qual[p->seq_offset];
226 p->base4 = p->b_seq[p->seq_offset/2] >>
227 ((~p->seq_offset&1)<<2) & 0xf;
228 p->base = "NACMGRSVTWYHKDBN"[p->base4];
229 } else {
230 p->base = 'N';
231 p->base4 = 15;
232 p->qual = 0xff;
233 }
234
235 break;
236 }
237 }
238
239 /* Handle moving out of N (skip) into sequence again */
240 if (p->eof && p->base != '.') {
241 p->start = 1;
242 p->ref_skip = 1;
243 p->eof = 0;
244 }
245
246 /* Starting with an indel needs a minor fudge */
247 if (p->start && p->cigar_op == BAM_CDEL) {
248 p->first_del = 1;
249 }
250
251 /* Check if next op is an insertion of some sort */
252 if (p->cigar_len == 0) {
253 if (p->cigar_ind < b->core.n_cigar) {
254 op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK;
255 p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT;
256 p->cigar_ind++;
257 if (op == BAM_CREF_SKIP) {
258 p->eof = 3;
259 p->ref_skip = 1;
260 }
261 } else {
262 p->eof = 1;
263 }
264 }
265
266 switch (op) {
267 case BAM_CPAD:
268 case BAM_CINS:
269 *is_insert = p->cigar_len;
270 break;
271
272 case BAM_CSOFT_CLIP:
273 /* Last op 'S' => eof */
274 p->eof = (p->cigar_ind == b->core.n_cigar ||
275 (p->cigar_ind+1 == b->core.n_cigar &&
276 (p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK)
277 == BAM_CHARD_CLIP))
278 ? 1
279 : 0;
280 break;
281
282 case BAM_CHARD_CLIP:
283 p->eof = 1;
284 break;
285
286 default:
287 break;
288 }
289
290 return 1;
291 }
292
293 /*
294 * Loops through a set of supplied ranges producing columns of data.
295 * When found, it calls func with clientdata as a callback. Func should
296 * return 0 for success and non-zero for failure. seq_init() is called
297 * on each new entry before we start processing it. It should return 0 or 1
298 * to indicate reject or accept status (eg to filter unmapped data).
299 * If seq_init() returns -1 we abort the pileup_loop with an error.
300 * seq_init may be NULL.
301 *
302 * Returns 0 on success
303 * -1 on failure
304 */
305 int pileup_loop(samFile *fp,
306 sam_hdr_t *h,
307 int (*seq_fetch)(void *client_data,
308 samFile *fp,
309 sam_hdr_t *h,
310 bam1_t *b),
311 int (*seq_init)(void *client_data,
312 samFile *fp,
313 sam_hdr_t *h,
314 pileup_t *p),
315 int (*seq_column)(void *client_data,
316 samFile *fp,
317 sam_hdr_t *h,
318 pileup_t *p,
319 int depth,
320 hts_pos_t pos,
321 int nth,
322 int is_insert),
323 void (*seq_free)(void *client_data,
324 samFile *fp,
325 sam_hdr_t *h,
326 pileup_t *p),
327 void *client_data) {
328 int ret = -1;
329 pileup_t *phead = NULL, *p, *pfree = NULL, *last, *next, *ptail = NULL;
330 pileup_t *pnew = NULL;
331 int is_insert, nth = 0, r;
332 hts_pos_t col = 0;
333 int last_ref = -1;
334
335 /* FIXME: allow for start/stop boundaries rather than consuming all data */
336
337 if (NULL == (pnew = calloc(1, sizeof(*p))))
338 return -1;
339
340 do {
341 bam1_t *b;
342 hts_pos_t pos;
343
344 r = seq_fetch(client_data, fp, h, &pnew->b);
345 if (r < -1) {
346 fprintf(stderr, "bam_next_seq() failure.\n");
347 goto error;
348 }
349
350 b = &pnew->b;
351
352 /* Force realloc */
353 //fp->bs = NULL;
354 //fp->bs_size = 0;
355
356 //r = samread(fp, pnew->b);
357 if (r >= 0) {
358 if (b->core.flag & BAM_FUNMAP)
359 continue;
360
361 if (b->core.tid == -1) {
362 /* Another indicator for unmapped */
363 continue;
364 } else if (b->core.tid == last_ref) {
365 pos = b->core.pos+1;
366 //printf("New seq at pos %d @ %d %s\n", pos, b->core.tid,
367 // bam_name(b));
368 } else {
369 //printf("New ctg at pos %ld @ %d\n",b->core.pos+1,b->core.tid);
370 pos = HTS_POS_MAX;
371 }
372 } else {
373 pos = HTS_POS_MAX;
374 }
375
376 if (col > pos) {
377 fprintf(stderr, "BAM/SAM file is not sorted by position. "
378 "Aborting\n");
379 goto error;
380 }
381
382 /* Process data between the last column and our latest addition */
383 while (col < pos && phead) {
384 struct pileup *eof_head = NULL, *eofp = NULL;
385 int v, ins, depth = 0;
386 //printf("Col=%ld pos=%ld nth=%d\n", col, pos, nth);
387
388 /* Pileup */
389 is_insert = 0;
390 pileup_t *pnext = phead ? phead->next : NULL;
391 for (p = phead, last = NULL; p; p = pnext) {
392 #if 0
393 // Simple prefetching
394 pnext = p->next;
395 if (pnext)
396 _mm_prefetch(pnext, _MM_HINT_T0);
397 #else
398 // More complex prefetching => more instructions, but
399 // usually faster.
400 pnext = p->next;
401 if (pnext) {
402 // start memory fetches; a big help on very deep data
403 if (pnext->next)
404 // struct 2 ahead
405 _mm_prefetch(pnext->next, _MM_HINT_T0);
406 // seq/qual 1 ahead
407 _mm_prefetch(pnext->b_qual + pnext->seq_offset,
408 _MM_HINT_T0);
409 _mm_prefetch(pnext->b_seq + pnext->seq_offset/2,
410 _MM_HINT_T0);
411 }
412 #endif
413
414 if (!get_next_base(p, col, nth, &ins))
415 p->eof = 1;
416 if (p->eof == 1) {
417 if (eofp)
418 eofp->eofn = p;
419 eofp = p;
420 eofp->eofl = last;
421 if (!eof_head)
422 eof_head = eofp;
423 } else {
424 last = p;
425 }
426
427 if (is_insert < ins)
428 is_insert = ins;
429
430 depth++;
431 }
432 if ((ptail = last) == NULL)
433 ptail = phead;
434
435 /* Call our function on phead linked list */
436 v = seq_column(client_data, fp, h, phead, depth,
437 #ifdef START_WITH_DEL
438 col-1,
439 #else
440 col,
441 #endif
442 nth, is_insert);
443
444 /* Remove dead seqs */
445 for (p = eof_head ; p; p = p->eofn) {
446 if (p->eofl)
447 p->eofl->next = p->next;
448 else
449 phead = p->next;
450
451 p->next = pfree;
452 pfree = p;
453
454 if (seq_free)
455 seq_free(client_data, fp, h, p);
456 }
457
458 if (v == 1)
459 break; /* early abort */
460
461 if (v != 0)
462 goto error;
463
464 /* Next column */
465 if (is_insert) {
466 nth++;
467 } else {
468 nth = 0;
469 col++;
470 }
471 }
472
473 /* May happen if we have a hole in the contig */
474 col = pos;
475
476 /* New contig */
477 if (b && b->core.tid != last_ref) {
478 last_ref = b->core.tid;
479 pos = b->core.pos+1;
480 nth = 0;
481 col = pos;
482 }
483
484 /*
485 * Add this seq.
486 * Note: cigars starting with I or P ops (eg 2P3I10M) mean we have
487 * alignment instructions that take place before the designated
488 * starting location listed in the SAM file. They won't get included
489 * in the callback function until they officially start, which is
490 * already too late.
491 *
492 * So to workaround this, we prefix all CIGAR with 1D, move the
493 * position by 1bp, and then force the callback code to remove
494 * leaving pads (either P or D generated).
495 *
496 * Ie it's a level 10 hack!
497 */
498 if (r >= 0) {
499 p = pnew;
500 p->next = NULL;
501 p->cd = NULL;
502 p->eofn = NULL;
503 p->eofl = NULL;
504 p->start = 2;
505 p->eof = 0;
506 #ifdef START_WITH_DEL
507 p->pos = pos-1;
508 p->cigar_ind = 0;
509 p->b_cigar = bam_get_cigar(&p->b);
510 if ((p->b_cigar[0] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) {
511 p->cigar_len = p->b_cigar[0] >> BAM_CIGAR_SHIFT;
512 p->cigar_op = BAM_CHARD_CLIP;
513 if ((p->b_cigar[1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
514 /* xHxS... => xHxS1D... */
515 p->b_cigar[0] = p->b_cigar[1];
516 p->b_cigar[1] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL;
517 } else {
518 /* xH... => xH1D... */
519 p->b_cigar[0] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL;
520 }
521 } else {
522 if ((p->b_cigar[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
523 /* xS... => xS1D... */
524 p->cigar_len = p->b_cigar[0] >> BAM_CIGAR_SHIFT;
525 p->cigar_op = BAM_CSOFT_CLIP;
526 p->b_cigar[0] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL;
527 } else {
528 /* ... => 1D... */
529 p->cigar_len = 1; /* was 0 */
530 p->cigar_op = BAM_CDEL; /* was 'X' */
531 }
532 }
533 p->seq_offset = -1;
534 p->first_del = 1;
535 #else
536 p->pos = pos-1;
537 p->cigar_ind = 0;
538 p->b_cigar = bam_get_cigar(&p->b);
539 p->cigar_len = 0;
540 p->cigar_op = -1;
541 p->seq_offset = -1;
542 p->first_del = 0;
543 #endif
544 p->b_is_rev = bam_is_rev(&p->b);
545 p->b_qual = (uint8_t *)bam_get_qual(&p->b);
546 p->b_seq = (uint8_t *)bam_get_seq(&p->b);
547
548 if (seq_init) {
549 int v;
550 v = seq_init(client_data, fp, h, p);
551 if (v == -1)
552 goto error;
553
554 if (v == 1) {
555 /* Keep this seq */
556 if (phead) {
557 ptail->next = p;
558 } else {
559 phead = p;
560 }
561 ptail = p;
562 } else {
563 /* Push back on free list */
564 p->next = pfree;
565 pfree = p;
566 }
567 } else {
568 if (phead)
569 ptail->next = p;
570 else
571 phead = p;
572 ptail = p;
573 }
574
575 /* Allocate the next pileup rec */
576 if (pfree) {
577 pnew = pfree;
578 pfree = pfree->next;
579 } else {
580 if (NULL == (pnew = calloc(1, sizeof(*pnew))))
581 goto error;
582 }
583 }
584 } while (r >= 0);
585
586 ret = 0;
587 error:
588
589 if (pnew) {
590 free(pnew->b.data);
591 free(pnew);
592 }
593
594 /* Tidy up */
595 for (p = pfree; p; p = next) {
596 next = p->next;
597 if (seq_free)
598 seq_free(client_data, fp, h, p);
599 free(p->b.data);
600 free(p);
601 }
602
603 return ret;
604 }