Debian Codegraph @

samtools/bam_md.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_md.c -- calmd subcommand.
4
5 Copyright (C) 2009-2011, 2014-2015, 2019-2020, 2022 Genome Research Ltd.
6 Portions copyright (C) 2009-2011 Broad Institute.
7
8 Author: Heng Li <[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 <string.h>
33 #include <ctype.h>
34 #include <limits.h>
35 #include <errno.h>
36 #include <assert.h>
37 #include "htslib/faidx.h"
38 #include "htslib/sam.h"
39 #include "htslib/kstring.h"
40 #include "htslib/thread_pool.h"
41 #include "sam_opts.h"
42 #include "samtools.h"
43
44 #define USE_EQUAL 1
45 #define DROP_TAG 2
46 #define BIN_QUAL 4
47 #define UPDATE_NM 8
48 #define UPDATE_MD 16
49 #define HASH_QNM 32
50
51 typedef struct cached_ref_entry {
52 char *ref;
53 hts_pos_t len;
54 } cached_ref_entry;
55
56 typedef struct ref_cache {
57 cached_ref_entry *refs;
58 char *last_ref;
59 hts_pos_t last_len;
60 int nref;
61 int last_tid;
62 } ref_cache;
63
64 int bam_aux_drop_other(bam1_t *b, uint8_t *s);
65
66 static int bam_fillmd1_core(const char *ref_name, bam1_t *b, char *ref,
67 hts_pos_t ref_len, int flag, int max_nm,
68 int quiet_mode, uint32_t *skipped)
69 {
70 uint8_t *seq = bam_get_seq(b);
71 uint32_t *cigar = bam_get_cigar(b);
72 bam1_core_t *c = &b->core;
73 int i, qpos, matched = 0;
74 hts_pos_t rpos;
75 kstring_t str = KS_INITIALIZE;
76 int32_t old_nm_i = -1, nm = 0;
77 uint32_t err = 0;
78
79 if (c->l_qseq == 0) {
80 if (!quiet_mode) {
81 if (ref_name) {
82 fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment "
83 "record for '%s' at %s:%"PRIhts_pos", skipped\n",
84 bam_get_qname(b), ref_name, c->pos + 1);
85 } else {
86 fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment "
87 "record for '%s', skipped", bam_get_qname(b));
88 }
89 }
90 if (skipped) (*skipped)++;
91 return 0;
92 }
93
94 for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) {
95 int j, oplen = cigar[i]>>4, op = cigar[i]&0xf;
96 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
97 for (j = 0; j < oplen; ++j) {
98 int c1, c2, z = qpos + j;
99 if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0')
100 break; // out of bounds
101 c1 = bam_seqi(seq, z);
102 c2 = seq_nt16_table[(uint8_t)ref[rpos+j]];
103 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
104 if (flag&USE_EQUAL) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
105 ++matched;
106 } else {
107 err |= kputw(matched, &str) < 0;
108 err |= kputc(toupper(ref[rpos+j]), &str) < 0;
109 matched = 0; ++nm;
110 }
111 }
112 if (j < oplen) break;
113 rpos += oplen; qpos += oplen;
114 } else if (op == BAM_CDEL) {
115 err |= kputw(matched, &str) < 0;
116 err |= kputc('^', &str) < 0;
117 for (j = 0; j < oplen; ++j) {
118 if (rpos+j >= ref_len || ref[rpos+j] == '\0') break;
119 err |= kputc(toupper(ref[rpos+j]), &str) < 0;
120 }
121 matched = 0;
122 rpos += j; nm += j;
123 if (j < oplen) break;
124 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
125 qpos += oplen;
126 if (op == BAM_CINS) nm += oplen;
127 } else if (op == BAM_CREF_SKIP) {
128 rpos += oplen;
129 }
130 }
131 err |= kputw(matched, &str) < 0;
132 if (err) {
133 print_error_errno("calmd", "Couldn't build new MD string");
134 goto fail;
135 }
136 // apply max_nm
137 if (max_nm > 0 && nm >= max_nm) {
138 for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) {
139 int j, oplen = cigar[i]>>4, op = cigar[i]&0xf;
140 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
141 for (j = 0; j < oplen; ++j) {
142 int c1, c2, z = qpos + j;
143 if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0')
144 break; // out of bounds
145 c1 = bam_seqi(seq, z);
146 c2 = seq_nt16_table[(uint8_t)ref[rpos+j]];
147 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
148 seq[z/2] |= (z&1)? 0x0f : 0xf0;
149 bam_get_qual(b)[z] = 0;
150 }
151 }
152 if (j < oplen) break;
153 rpos += oplen; qpos += oplen;
154 } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) rpos += oplen;
155 else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) qpos += oplen;
156 }
157 }
158 // update NM
159 if ((flag & UPDATE_NM) && !(c->flag & BAM_FUNMAP)) {
160 uint8_t *old_nm = bam_aux_get(b, "NM");
161 if (old_nm) old_nm_i = bam_aux2i(old_nm);
162 if (!old_nm) {
163 if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0)
164 goto aux_fail;
165 }
166 else if (nm != old_nm_i) {
167 if (!quiet_mode) {
168 fprintf(samtools_stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam_get_qname(b), old_nm_i, nm);
169 }
170 if (bam_aux_del(b, old_nm) < 0) goto aux_fail;
171 if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0)
172 goto aux_fail;
173 }
174 }
175 // update MD
176 if ((flag & UPDATE_MD) && !(c->flag & BAM_FUNMAP)) {
177 uint8_t *old_md = bam_aux_get(b, "MD");
178 if (!old_md) {
179 if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0)
180 goto aux_fail;
181 } else {
182 int is_diff = 0;
183 if (strlen((char*)old_md+1) == str.l) {
184 for (i = 0; i < str.l; ++i)
185 if (toupper(old_md[i+1]) != toupper(str.s[i]))
186 break;
187 if (i < str.l) is_diff = 1;
188 } else is_diff = 1;
189 if (is_diff) {
190 if (!quiet_mode) {
191 fprintf(samtools_stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam_get_qname(b), old_md+1, str.s);
192 }
193 if (bam_aux_del(b, old_md) < 0) goto aux_fail;
194 if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0)
195 goto aux_fail;
196 }
197 }
198 }
199
200 // drop all tags but RG
201 if (flag&DROP_TAG) {
202 uint8_t *q = bam_aux_get(b, "RG");
203 bam_aux_drop_other(b, q);
204 }
205 // reduce the resolution of base quality
206 if (flag&BIN_QUAL) {
207 uint8_t *qual = bam_get_qual(b);
208 for (i = 0; i < b->core.l_qseq; ++i)
209 if (qual[i] >= 3) qual[i] = qual[i]/10*10 + 7;
210 }
211
212 free(str.s);
213 return 0;
214
215 aux_fail:
216 if (errno == ENOMEM) {
217 print_error("calmd", "Couldn't add aux tag (too long)");
218 } else if (errno == EINVAL) {
219 print_error("calmd", "Corrupt aux data");
220 } else {
221 print_error_errno("calmd", "Couldn't add aux tag");
222 }
223 fail:
224 free(str.s);
225 return -1;
226 }
227
228 int bam_fillmd1(bam1_t *b, char *ref, int flag, int quiet_mode)
229 {
230 return bam_fillmd1_core(NULL, b, ref, INT_MAX, flag, 0, quiet_mode, NULL);
231 }
232
233 // Get a new reference sequence.
234 // For position-sorted inputs, the previous reference should never be
235 // needed again and can be discarded to save memory. For other orderings,
236 // references are stored in a cache in case they're required in the future.
237 // The caching mode is turned on if the requested tid is less than the last
238 // one used, indicating the file ordering doesn't match the sequence dictionary.
239 static int get_ref(faidx_t *fai, sam_hdr_t *header, ref_cache *cache,
240 int tid, char **ref_out, const char **ref_name_out,
241 hts_pos_t *len_out)
242 {
243 char *ref = NULL;
244 const char *ref_name;
245 hts_pos_t len = 0;
246
247 // This should only be called when tid changes
248 assert(tid != cache->last_tid);
249
250 // Array lookup, should be fast
251 ref_name = sam_hdr_tid2name(header, tid);
252 *ref_name_out = ref_name;
253
254 // Return a cached entry, if available
255 if (cache->refs && tid >= 0 && tid < cache->nref
256 && cache->refs[tid].ref) {
257 assert(cache->last_ref == NULL);
258 *ref_out = cache->refs[tid].ref;
259 *len_out = cache->refs[tid].len;
260 cache->last_tid = tid;
261 return 0;
262 }
263
264 // Try to get the reference
265 if (ref_name)
266 ref = fai_fetch64(fai, ref_name, &len);
267
268 if (!ref) {
269 // Historically, calmd doesn't worry too much about missing refs
270 *ref_out = NULL;
271 *len_out = 0;
272 return 0;
273 }
274
275 if (!cache->refs && cache->last_tid > tid) {
276 // Going backwards throught the list of tids implies
277 // a non-position-ordered file, so turn on caching mode
278 cache->nref = sam_hdr_nref(header);
279 if (cache->nref < 0) {
280 print_error("calmd", "couldn't get number of refs from header");
281 return -1;
282 }
283 if (cache->nref > 0) {
284 cache->refs = calloc(cache->nref, sizeof(cache->refs[0]));
285 if (!cache->refs) {
286 print_error_errno("calmd",
287 "couldn't allocate reference cache");
288 return -1;
289 }
290 // Add the reference we already have as the first entry
291 if (cache->last_tid >= 0 && cache->last_tid < cache->nref) {
292 cache->refs[cache->last_tid].ref = cache->last_ref;
293 cache->refs[cache->last_tid].len = cache->last_len;
294 } else {
295 free(cache->last_ref);
296 }
297 cache->last_ref = NULL;
298 }
299 }
300
301 if (cache->refs) {
302 assert(cache->last_ref == NULL); // Shouldn't be set when caching
303 // Add the new reference to the cache
304 if (tid >= 0 && tid < cache->nref) {
305 cache->refs[tid].ref = ref;
306 cache->refs[tid].len = len;
307 }
308 } else {
309 // Streaming mode - free the last ref and replace it with this one
310 free(cache->last_ref);
311 cache->last_ref = ref;
312 cache->last_len = len;
313 }
314
315 *ref_out = ref;
316 *len_out = len;
317 cache->last_tid = tid;
318 return 0;
319 }
320
321 static void refs_destroy(ref_cache *cache) {
322 if (cache->refs) {
323 int i;
324 assert(cache->last_ref == NULL);
325 for (i = 0; i < cache->nref; i++)
326 free(cache->refs[i].ref);
327 free(cache->refs);
328 } else {
329 free(cache->last_ref);
330 }
331 }
332
333 int calmd_usage(void) {
334 fprintf(samtools_stderr,
335 "Usage: samtools calmd [-eubrAESQ] <aln.bam> <ref.fasta>\n"
336 "Options:\n"
337 " -e change identical bases to '='\n"
338 " -u uncompressed BAM output (for piping)\n"
339 " -b compressed BAM output\n"
340 " -S ignored (input format is auto-detected)\n"
341 " -A modify the quality string\n"
342 " -Q use quiet mode to output less debug info to samtools_stdout\n"
343 " -r compute the BQ tag (without -A) or cap baseQ by BAQ (with -A)\n"
344 " -E extended BAQ for better sensitivity but lower specificity\n"
345 " --no-PG do not add a PG line\n");
346
347 sam_global_opt_help(samtools_stderr, "-....@-.");
348 return 1;
349 }
350
351 int bam_fillmd(int argc, char *argv[])
352 {
353 int c, flt_flag, ret, is_bam_out, is_uncompressed, max_nm, is_realn, capQ, baq_flag, quiet_mode, no_pg = 0;
354 hts_pos_t len = 0;
355 htsThreadPool p = {NULL, 0};
356 samFile *fp = NULL, *fpout = NULL;
357 sam_hdr_t *header = NULL;
358 faidx_t *fai = NULL;
359 char *ref = NULL, mode_w[8], *ref_file, *arg_list = NULL;
360 ref_cache refs = { NULL, NULL, 0, 0, -2 };
361 const char *ref_name = NULL;
362 bam1_t *b = NULL;
363 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
364 uint32_t skipped = 0;
365
366 static const struct option lopts[] = {
367 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0,'@'),
368 {"no-PG", no_argument, NULL, 1},
369 { NULL, 0, NULL, 0 }
370 };
371
372 flt_flag = UPDATE_NM | UPDATE_MD;
373 is_bam_out = is_uncompressed = is_realn = max_nm = capQ = baq_flag = quiet_mode = 0;
374 strcpy(mode_w, "w");
375 while ((c = getopt_long(argc, argv, "EqQreuNhbSC:n:Ad@:", lopts, NULL)) >= 0) {
376 switch (c) {
377 case 'r': is_realn = 1; break;
378 case 'e': flt_flag |= USE_EQUAL; break;
379 case 'd': flt_flag |= DROP_TAG; break;
380 case 'q': flt_flag |= BIN_QUAL; break;
381 case 'h': flt_flag |= HASH_QNM; break;
382 case 'N': flt_flag &= ~(UPDATE_MD|UPDATE_NM); break;
383 case 'b': is_bam_out = 1; break;
384 case 'u': is_uncompressed = is_bam_out = 1; break;
385 case 'S': break;
386 case 'n': max_nm = atoi(optarg); break;
387 case 'C': capQ = atoi(optarg); break;
388 case 'A': baq_flag |= 1; break;
389 case 'E': baq_flag |= 2; break;
390 case 'Q': quiet_mode = 1; break;
391 case 1: no_pg = 1; break;
392 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
393 fprintf(samtools_stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c);
394 /* else fall-through */
395 case '?': return calmd_usage();
396 }
397 }
398 if (is_bam_out) strcat(mode_w, "b");
399 else strcat(mode_w, "h");
400 if (is_uncompressed) strcat(mode_w, "0");
401 if (optind + (ga.reference == NULL) >= argc)
402 return calmd_usage();
403 fp = sam_open_format(argv[optind], "r", &ga.in);
404 if (fp == NULL) {
405 print_error_errno("calmd", "Failed to open input file '%s'", argv[optind]);
406 return 1;
407 }
408
409 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
410 print_error("calmd", "failed to create arg_list");
411 return 1;
412 }
413
414 header = sam_hdr_read(fp);
415 if (header == NULL || sam_hdr_nref(header) == 0) {
416 // NB: if we have no SQ headers but have aligned data, then this will
417 // be caught during processing with e.g.
418 // "[E::sam_parse1] no SQ lines present in the header"
419 fprintf(samtools_stderr, "[bam_fillmd] warning: input SAM does not have "
420 "header, performing a no-op.\n");
421 }
422
423 fpout = sam_open_format(samtools_stdout_fn, mode_w, &ga.out);
424 if (fpout == NULL) {
425 print_error_errno("calmd", "Failed to open output");
426 goto fail;
427 }
428 if (!no_pg && sam_hdr_add_pg(header, "samtools",
429 "VN", samtools_version(),
430 arg_list ? "CL": NULL,
431 arg_list ? arg_list : NULL,
432 NULL)) {
433 print_error("calmd", "failed to add PG line to header");
434 goto fail;
435 }
436 if (sam_hdr_write(fpout, header) < 0) {
437 print_error_errno("calmd", "Failed to write sam header");
438 goto fail;
439 }
440
441 if (ga.nthreads > 0) {
442 if (!(p.pool = hts_tpool_init(ga.nthreads))) {
443 fprintf(samtools_stderr, "Error creating thread pool\n");
444 goto fail;
445 }
446 hts_set_opt(fp, HTS_OPT_THREAD_POOL, &p);
447 hts_set_opt(fpout, HTS_OPT_THREAD_POOL, &p);
448 }
449
450 ref_file = argc > optind + 1 ? argv[optind+1] : ga.reference;
451 fai = fai_load(ref_file);
452
453 if (!fai) {
454 print_error_errno("calmd", "Failed to open reference file '%s'", ref_file);
455 goto fail;
456 }
457
458 b = bam_init1();
459 if (!b) {
460 fprintf(samtools_stderr, "[bam_fillmd] Failed to allocate bam struct\n");
461 goto fail;
462 }
463 while ((ret = sam_read1(fp, header, b)) >= 0) {
464 if (b->core.tid >= 0) {
465 if (refs.last_tid != b->core.tid) {
466 if (get_ref(fai, header, &refs, b->core.tid,
467 &ref, &ref_name, &len) < 0) {
468 goto fail;
469 }
470 if (ref == 0) { // FIXME: Should this always be fatal?
471 fprintf(samtools_stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
472 ref_name ? ref_name : "(unknown)");
473 if (is_realn || capQ > 10) goto fail; // Would otherwise crash
474 }
475 }
476 if (is_realn) {
477 if (sam_prob_realn(b, ref, len, baq_flag) < -3) {
478 print_error_errno("calmd", "BAQ alignment failed");
479 goto fail;
480 }
481 }
482 if (capQ > 10) {
483 int q = sam_cap_mapq(b, ref, len, capQ);
484 if (b->core.qual > q) b->core.qual = q;
485 }
486 if (ref) {
487 if (bam_fillmd1_core(ref_name, b, ref, len, flt_flag, max_nm,
488 quiet_mode, &skipped) < 0)
489 goto fail;
490 }
491 }
492 if (sam_write1(fpout, header, b) < 0) {
493 print_error_errno("calmd", "failed to write to output file");
494 goto fail;
495 }
496 }
497 if (ret < -1) {
498 fprintf(samtools_stderr, "[bam_fillmd] Error reading input.\n");
499 goto fail;
500 }
501
502 if (skipped) {
503 fprintf(samtools_stderr, "[calmd] Warning: %"PRIu32" records skipped due "
504 "to no query sequence\n",
505 skipped);
506 }
507
508 bam_destroy1(b);
509 sam_hdr_destroy(header);
510
511 free(arg_list);
512 refs_destroy(&refs);
513 fai_destroy(fai);
514 sam_close(fp);
515 if (sam_close(fpout) < 0) {
516 fprintf(samtools_stderr, "[bam_fillmd] error when closing output file\n");
517 return 1;
518 }
519 if (p.pool) hts_tpool_destroy(p.pool);
520
521 return 0;
522
523 fail:
524 free(arg_list);
525 refs_destroy(&refs);
526 if (b) bam_destroy1(b);
527 if (header) sam_hdr_destroy(header);
528 if (fai) fai_destroy(fai);
529 if (fp) sam_close(fp);
530 if (fpout) sam_close(fpout);
531 if (p.pool) hts_tpool_destroy(p.pool);
532
533 return 1;
534 }