Debian Codegraph @

samtools/reference.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_reference.c -- extracts an embedded reference from a CRAM file,
4 or creates it from alignments plus MD:Z tags.
5
6 Copyright (C) 2022 Genome Research Ltd.
7
8 Author: James Bonfield <[email protected]>
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in
18 all copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 DEALINGS IN THE SOFTWARE. */
27
28 #include <config.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <ctype.h>
35
36 #include "htslib/sam.h"
37 #include "htslib/cram.h"
38 #include "samtools.h"
39 #include "sam_opts.h"
40
41
42 /*
43 * There are two main modes of operation.
44 *
45 * 1. Extracting the reference from the CRAM file embed_ref blocks.
46 * 2. Generation of reference by analysing consensus plus patches applied
47 * via MD tags.
48 *
49 * The first is very rapid, but only applies to a CRAM files generated with
50 * the specific options (not commonly used and not the default). The second
51 * is a slow operation, but applies to any data type.
52 *
53 * This is also a testing ground for a future CRAM auto-embed-ref option that
54 * permits the use of an embedded reference without having to first extract
55 * the reference. (Note this may require the creation of MD tags during
56 * decode by use of an existing embedded reference, if the records don't
57 * have an MD tag themselves, but that's an issue for htslib when we get
58 * there.)
59 */
60
61 /*
62 * ---------------------------------------------------------------------------
63 * Shared utility functions by both methods.
64 */
65
66 #define haszero(x) (((x)-0x0101010101010101UL)&~(x)&0x8080808080808080UL)
67 #define MIN(a,b) ((a)<(b)?(a):(b))
68 static int dump_ref(sam_hdr_t *h, hts_itr_t *iter, int ref_id,
69 char *ref, uint64_t ref_len, FILE *fp, int verbose) {
70 int N = 0;
71 if (iter && iter->end >= HTS_POS_MAX)
72 iter->end = ref_len;
73 if (iter && (iter->beg > 0 || iter->end < ref_len)) {
74 fprintf(fp, ">%s:%"PRIhts_pos"-%"PRIhts_pos"\n",
75 sam_hdr_tid2name(h, ref_id), iter->beg+1, iter->end);
76 ref += iter->beg;
77 ref_len = MIN(ref_len, iter->end) - iter->beg;
78 } else {
79 fprintf(fp, ">%s\n", sam_hdr_tid2name(h, ref_id));
80 }
81
82 int i, j;
83 uint64_t rem = ref_len;
84
85 // Count coverage, purely for information purposes.
86 // About 90% of dump_ref CPU is here, so maybe this isn't useful,
87 // but this is still 3-4x faster than the obvious naive loop.
88 //
89 // Overall though it's only about 5% overhead of the entire process
90 // (was ~20%).
91 if (verbose) {
92 int n4[8] = {0};
93 for (j = 0; j < ref_len && (((uintptr_t) &ref[j] & 7) != 0); j++)
94 N += ref[j] == 'N';
95 uint64_t fast_end = ((ref_len - j) & ~7) + j;
96 for (; j < fast_end; j+=8) {
97 uint64_t i64 = *(uint64_t *)&ref[j];
98 if (!haszero(i64 ^ 0x4e4e4e4e4e4e4e4eUL)) // 'N' <-> 0
99 continue;
100
101 n4[0] += ref[j+0] == 'N';
102 n4[1] += ref[j+1] == 'N';
103 n4[2] += ref[j+2] == 'N';
104 n4[3] += ref[j+3] == 'N';
105 n4[4] += ref[j+4] == 'N';
106 n4[5] += ref[j+5] == 'N';
107 n4[6] += ref[j+6] == 'N';
108 n4[7] += ref[j+7] == 'N';
109 }
110 for (; j < ref_len; j++)
111 N += ref[j] == 'N';
112 N += n4[0]+n4[1]+n4[2]+n4[3]+
113 n4[4]+n4[5]+n4[6]+n4[7];
114 }
115
116 // Format reference
117 for (i = 0; i < ref_len; i += 60, rem -= 60) {
118 int len = (int)(rem < 60 ? rem : 60);
119 if (fwrite(ref, 1, len, fp) != len)
120 return -1;
121 putc('\n', fp);
122 ref += 60;
123 }
124
125 if (verbose)
126 fprintf(samtools_stderr, "Dump ref %d len %"PRId64", coverage %.2f%%\n",
127 ref_id, ref_len, 100 - N*100.0 / ref_len);
128
129 return 0;
130 }
131
132 /*
133 * ---------------------------------------------------------------------------
134 * CRAM embedded reference method of reference construction
135 */
136
137 /*
138 * Extracts an embedded reference from a sorted CRAM file.
139 * Modelled on the CRAM container copy loop from bam_cat.c.
140 */
141 static int cram2ref(samFile *in, sam_hdr_t *h, hts_idx_t *idx, char *reg,
142 FILE *outfp, int verbose) {
143 cram_fd *in_c;
144 cram_container *c = NULL;
145 cram_block *blk = NULL;
146 cram_block_slice_hdr *shdr = NULL;
147
148 int curr_ref_id = -99;
149 char *ref = NULL;
150 uint64_t ref_len = 0;
151
152 // We have no direct public API for seeking in CRAM to a specific
153 // location by genome coordinates. The sam_itr_query API is
154 // designed for fetching records, rather than seeks to specific
155 // file locations.
156 //
157 // TODO: consider exposing cram_range and cram_seek_to_refpos API.
158 // After a sam_index_load which will add the index to infp, these
159 // functions should seek direct to the start of a container.
160 // Or use cram_index *e =cram_index_query(cram, tid, beg, NULL);
161 //
162 // However, fortuitously(?) sam_itr_querys calls cram_seek_to_refpos
163 // so we can do a region query and let that do the initial seek.
164 // We still need to do our own end-range detection though.
165
166 hts_itr_t *iter = NULL;
167 if (reg) {
168 iter = sam_itr_querys(idx, h, reg);
169 if (!iter) {
170 print_error("reference", "failed to parse region '%s'", reg);
171 goto err;
172 }
173 }
174
175 in_c = in->fp.cram; // low level htslib abuse?
176 int eor = 0;
177 while (!eor && (c = cram_read_container(in_c))) {
178 if (cram_container_is_empty(in_c)) {
179 cram_block *blk;
180 // Container compression header
181 if (!(blk = cram_read_block(in_c)))
182 goto err;
183 cram_free_block(blk);
184 cram_free_container(c);
185 c = NULL; blk = NULL;
186 continue;
187 }
188
189 // Container compression header; read and discard
190 int32_t num_slices;
191 if (!(blk = cram_read_block(in_c)))
192 goto err;
193 cram_free_block(blk);
194 blk = NULL;
195
196 // Container num_blocks can be invalid, due to a bug.
197 // Instead we iterate in slice context instead.
198 (void)cram_container_get_landmarks(c, &num_slices);
199 int i, j;
200 for (i = 0; i < num_slices; i++) {
201 // Slice header
202 if (!(blk = cram_read_block(in_c)))
203 goto err;
204 if (!(shdr = cram_decode_slice_header(in_c, blk)))
205 goto err;
206 cram_free_block(blk);
207 blk = NULL;
208
209 int num_blocks = cram_slice_hdr_get_num_blocks(shdr);
210 int embed_id = cram_slice_hdr_get_embed_ref_id(shdr);
211 int ref_id;
212 hts_pos_t ref_start, ref_span;
213 cram_slice_hdr_get_coords(shdr, &ref_id, &ref_start, &ref_span);
214
215 if (iter) {
216 if (iter->tid != ref_id || ref_start > iter->end) {
217 // Beyond end of specified region.
218 cram_free_slice_header(shdr);
219 eor = 1;
220 break;
221 }
222 }
223
224 if (embed_id < 0 && ref_id != -1) {
225 fprintf(samtools_stderr, "CRAM file has slice without embedded "
226 "reference\n");
227 goto err;
228 }
229
230 if (ref_id != curr_ref_id) {
231 if (curr_ref_id >= 0) {
232 if (dump_ref(h, iter, curr_ref_id, ref, ref_len,
233 outfp, verbose) < 0)
234 goto err;
235 }
236
237 ref_len = sam_hdr_tid2len(h, ref_id);
238 if (ref_len) {
239 char *ref2 = realloc(ref, ref_len);
240 if (!ref2)
241 goto err;
242 else
243 ref = ref2;
244 memset(ref, 'N', ref_len);
245 }
246 curr_ref_id = ref_id;
247 }
248
249 // Slice data blocks
250 for (j = 0; j < num_blocks; j++) {
251 // read and discard, unless it's the ref-ID block
252 if (!(blk = cram_read_block(in_c)))
253 goto err;
254 if (cram_block_get_content_id(blk) == embed_id) {
255 cram_uncompress_block(blk);
256 //printf("%.*s\n", blk->uncomp_size, blk->data);
257
258 int32_t usize = cram_block_get_uncomp_size(blk);
259 int ref_end = ref_start + usize;
260 if (ref_end > ref_len+1)
261 ref_end = ref_len+1;
262 if (ref_end > ref_start)
263 memcpy(ref + ref_start-1, cram_block_get_data(blk),
264 ref_end - ref_start);
265 }
266 cram_free_block(blk);
267 blk = NULL;
268 }
269 cram_free_slice_header(shdr);
270 shdr = NULL;
271 }
272
273 cram_free_container(c);
274 c = NULL;
275 }
276
277 int ret = 0;
278 if (curr_ref_id >= 0) {
279 ret = dump_ref(h, iter, curr_ref_id, ref, ref_len, outfp, verbose);
280 } else if (reg) {
281 // no data present
282 // no data present, but we explicitly asked for the reference so
283 // report it still as Ns.
284 ref_len = MIN(iter->end, sam_hdr_tid2len(h, iter->tid));
285 ref = malloc(ref_len);
286 memset(ref, 'N', ref_len);
287 if (!ref)
288 goto err;
289 ret = dump_ref(h, iter, iter->tid, ref, ref_len, outfp, verbose);
290 }
291
292 free(ref);
293 if (iter)
294 hts_itr_destroy(iter);
295
296 return ret;
297
298 err:
299 free(ref);
300 if (blk)
301 cram_free_block(blk);
302 if (shdr)
303 cram_free_slice_header(shdr);
304 if (c)
305 cram_free_container(c);
306 if (iter)
307 hts_itr_destroy(iter);
308
309 return -1;
310 }
311
312 /*
313 * ---------------------------------------------------------------------------
314 * MD method of reference construction
315 */
316
317 // Returns the next cigar op code: one of the BAM_C* codes,
318 // or -1 if no more are present.
319 static inline
320 int next_cigar_op(uint32_t *cigar, int *ncigar, int *skip, int *spos,
321 uint32_t *cig_ind, uint32_t *cig_op, uint32_t *cig_len) {
322 for(;;) {
323 while (*cig_len == 0) {
324 if (*cig_ind < *ncigar) {
325 *cig_op = cigar[*cig_ind] & BAM_CIGAR_MASK;
326 *cig_len = cigar[*cig_ind] >> BAM_CIGAR_SHIFT;
327 (*cig_ind)++;
328 } else {
329 return -1;
330 }
331 }
332
333 if (skip[*cig_op]) {
334 *spos += (bam_cigar_type(*cig_op)&1) * *cig_len;
335 *cig_len = 0;
336 continue;
337 }
338
339 (*cig_len)--;
340 break;
341 }
342
343 return *cig_op;
344 }
345
346 // Converts a bam object with SEQ, POS/CIGAR and MD:Z to a reference.
347 // Updates ref[] array.
348 //
349 // Returns >0 on success,
350 // 0 on no-MD found,
351 // -1 on failure (eg inconsistent data)
352 static int build_ref(bam1_t *b, char *ref, size_t ref_len) {
353 uint8_t *seq = bam_get_seq(b);
354 uint32_t *cigar = bam_get_cigar(b);
355 int ncigar = b->core.n_cigar;
356 uint32_t cig_op = 0, cig_len = 0, cig_ind = 0;
357
358 const uint8_t *MD = bam_aux_get(b, "MD");
359 if (!MD || *MD != 'Z')
360 return 0;
361 MD++;
362
363 // Walk through MD + seq to generate ref
364 int iseq = 0, iref = b->core.pos, next_op;
365 int cig_skip[16] = {0,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1};
366 while (iseq < b->core.l_qseq && *MD) {
367 if (isdigit(*MD)) {
368 // match
369 int len = strtol((char *)MD, (char **)&MD, 10);
370 while (iseq < b->core.l_qseq && len) {
371 if ((next_op = next_cigar_op(cigar, &ncigar, cig_skip,
372 &iseq, &cig_ind, &cig_op,
373 &cig_len)) < 0)
374 return -1;
375
376 if (next_op != BAM_CMATCH &&
377 next_op != BAM_CEQUAL) {
378 print_error("MD2ref",
379 "MD:Z and CIGAR are incompatible");
380 return -1;
381 }
382
383 if (iref < ref_len)
384 ref[iref] = seq_nt16_str[bam_seqi(seq, iseq)];
385 iseq++;
386 iref++;
387 len--;
388 }
389 } else if (*MD == '^') {
390 // deletion
391 MD++;
392 while (*MD && isalpha(*MD)) {
393 if ((next_op = next_cigar_op(cigar, &ncigar, cig_skip,
394 &iseq, &cig_ind, &cig_op,
395 &cig_len)) < 0)
396 return -1;
397
398 if (next_op != BAM_CDEL) {
399 print_error("MD2ref",
400 "MD:Z and CIGAR are incompatible");
401 return -1;
402 }
403
404 if (iref < ref_len)
405 ref[iref] = *MD;
406
407 MD++;
408 iref++;
409 }
410 } else {
411 // substitution
412 if ((next_op = next_cigar_op(cigar, &ncigar, cig_skip,
413 &iseq, &cig_ind, &cig_op,
414 &cig_len)) < 0)
415 return -1;
416
417 if (next_op != BAM_CMATCH && next_op != BAM_CDIFF) {
418 print_error("MD2ref", "MD:Z and CIGAR are incompatible");
419 return -1;
420 }
421 if (iref < ref_len)
422 ref[iref] = *MD;
423
424 MD++;
425 iref++;
426 iseq++;
427 }
428 }
429
430 return 1;
431 }
432
433 static int MD2ref(samFile *in, sam_hdr_t *h, hts_idx_t *idx, char *reg,
434 FILE *outfp, int verbose) {
435 bam1_t *b = bam_init1();
436 int r, last_tid = -99;
437 size_t ref_len = 0;
438 char *ref = NULL;
439 int ret = -1;
440
441 hts_itr_t *iter = NULL;
442 if (idx && reg) {
443 iter = sam_itr_querys(idx, h, reg);
444 if (!iter) {
445 print_error("reference", "failed to parse region '%s'", reg);
446 goto err;
447 }
448 }
449
450 while ((r = iter
451 ? sam_itr_next(in, iter, b)
452 : sam_read1(in, h, b)) >= 0) {
453 // check b->core.tid and flush old seq.
454 if (b->core.tid != last_tid) {
455 if (last_tid >= 0)
456 if (dump_ref(h, iter, last_tid, ref, ref_len, outfp,
457 verbose) < 0)
458 goto err;
459
460 last_tid = b->core.tid;
461 ref_len = sam_hdr_tid2len(h, last_tid);
462 if (ref_len) {
463 char *ref2 = realloc(ref, ref_len);
464 if (!ref2)
465 goto err;
466 else
467 ref = ref2;
468 memset(ref, 'N', ref_len);
469 }
470 }
471
472 if (build_ref(b, ref, ref_len) < 0)
473 goto err;
474 }
475
476 if (last_tid >= 0) {
477 if (dump_ref(h, iter, last_tid, ref, ref_len, outfp, verbose) < 0)
478 goto err;
479 } else if (reg) {
480 // no data present, but we explicitly asked for the reference so
481 // report it still as Ns.
482 ref_len = MIN(iter->end, sam_hdr_tid2len(h, iter->tid));
483 ref = malloc(ref_len);
484 memset(ref, 'N', ref_len);
485 if (!ref)
486 goto err;
487 if (dump_ref(h, iter, iter->tid, ref, ref_len, outfp, verbose) < 0)
488 goto err;
489 }
490
491 if (r < -1)
492 goto err;
493
494 ret = 0;
495
496 err:
497 if (iter)
498 hts_itr_destroy(iter);
499 bam_destroy1(b);
500 free(ref);
501 return ret;
502 }
503
504 int main_reference(int argc, char *argv[])
505 {
506 int c, usage = 0, verbose = 1, use_embedded = 0;
507 sam_hdr_t *h = 0;
508 samFile *in = NULL;
509 hts_idx_t *idx = NULL;
510 sam_global_args ga;
511 FILE *outfp = samtools_stdout;
512 char *reg = NULL;
513
514 static const struct option lopts[] = {
515 {"output", required_argument, NULL, 'o'},
516 {"quiet", no_argument, NULL, 'q'},
517 {"embedded", no_argument, NULL, 'e'},
518 {"region", required_argument, NULL, 'r'},
519 SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'),
520 { NULL, 0, NULL, 0 }
521 };
522
523 sam_global_args_init(&ga);
524
525 while ((c = getopt_long(argc, argv, "@:qo:er:", lopts, NULL)) >= 0) {
526 switch (c) {
527 case 'o':
528 if (!(outfp = fopen(optarg, "w"))) {
529 perror(optarg);
530 goto err;
531 }
532 break;
533
534 case 'q':
535 verbose = 0;
536 break;
537
538 case 'e':
539 use_embedded = 1;
540 break;
541
542 case 'r':
543 reg = optarg;
544 break;
545
546 default:
547 if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
548 /* else fall-through */
549 case '?': usage=1; break;
550 }
551 }
552
553 if ((optind == argc && isatty(0)) || usage) {
554 fprintf(samtools_stdout, "Usage: samtools reference [-@ N] [-r region] [-e] [-q] [-o out.fa] [in.cram]\n");
555 return 0;
556 }
557
558 char *fn = optind < argc ? argv[optind] : "-";
559 if (!(in = sam_open(fn, "r"))) {
560 print_error_errno("reference", "failed to open file '%s'", fn);
561 return 1;
562 }
563
564 if (ga.nthreads > 0)
565 hts_set_threads(in, ga.nthreads);
566
567 if (!(h = sam_hdr_read(in)))
568 goto err;
569
570 if (reg) {
571 idx = sam_index_load(in, fn);
572 if (!idx) {
573 print_error_errno("reference", "Failed to load the index");
574 goto err;
575 }
576 }
577
578 int ret = use_embedded
579 ? cram2ref(in, h, idx, reg, outfp, verbose)
580 : MD2ref(in, h, idx, reg, outfp, verbose);
581
582 sam_hdr_destroy(h);
583 if (outfp != samtools_stdout)
584 fclose(outfp);
585 if (idx)
586 hts_idx_destroy(idx);
587 sam_close(in);
588
589 return ret;
590
591 err:
592 if (idx)
593 hts_idx_destroy(idx);
594 if (in)
595 sam_close(in);
596 if (h)
597 sam_hdr_destroy(h);
598
599 return 1;
600 }