Debian Codegraph @

samtools/consensus_pileup.c.pysam.c

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