Debian Codegraph @

samtools/bam_rmdup.c

raw symbols SCIP
1 /* bam_rmdup.c -- duplicate read detection.
2
3 Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd.
4 Portions copyright (C) 2009 Broad Institute.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <config.h>
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <zlib.h>
32 #include <unistd.h>
33 #include "htslib/sam.h"
34 #include "sam_opts.h"
35 #include "samtools.h"
36 #include "bam.h" // for bam_get_library
37
38 typedef bam1_t *bam1_p;
39
40 #include "htslib/khash.h"
41 KHASH_SET_INIT_STR(name)
42 KHASH_MAP_INIT_INT64(pos, bam1_p)
43
44 #define BUFFER_SIZE 0x40000
45
46 typedef struct {
47 uint64_t n_checked, n_removed;
48 khash_t(pos) *best_hash;
49 } lib_aux_t;
50 KHASH_MAP_INIT_STR(lib, lib_aux_t)
51
52 typedef struct {
53 int n, max;
54 bam1_t **a;
55 } tmp_stack_t;
56
57 static inline void stack_insert(tmp_stack_t *stack, bam1_t *b)
58 {
59 if (stack->n == stack->max) {
60 stack->max = stack->max? stack->max<<1 : 0x10000;
61 stack->a = (bam1_t**)realloc(stack->a, sizeof(bam1_t*) * stack->max);
62 }
63 stack->a[stack->n++] = b;
64 }
65
66 static inline int dump_best(tmp_stack_t *stack, samFile *out, sam_hdr_t *hdr)
67 {
68 int i;
69 for (i = 0; i != stack->n; ++i) {
70 if (sam_write1(out, hdr, stack->a[i]) < 0) return -1;
71 bam_destroy1(stack->a[i]);
72 stack->a[i] = NULL;
73 }
74 stack->n = 0;
75 return 0;
76 }
77
78 static inline void clear_stack(tmp_stack_t *stack) {
79 int i;
80 if (!stack->a) return;
81 for (i = 0; i != stack->n; ++i) {
82 bam_destroy1(stack->a[i]);
83 }
84 }
85
86 static void clear_del_set(khash_t(name) *del_set)
87 {
88 khint_t k;
89 for (k = kh_begin(del_set); k < kh_end(del_set); ++k)
90 if (kh_exist(del_set, k))
91 free((char*)kh_key(del_set, k));
92 kh_clear(name, del_set);
93 }
94
95 static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib)
96 {
97 khint_t k = kh_get(lib, aux, lib);
98 if (k == kh_end(aux)) {
99 int ret;
100 char *p = strdup(lib);
101 lib_aux_t *q;
102 k = kh_put(lib, aux, p, &ret);
103 q = &kh_val(aux, k);
104 q->n_checked = q->n_removed = 0;
105 q->best_hash = kh_init(pos);
106 return q;
107 } else return &kh_val(aux, k);
108 }
109
110 static void clear_best(khash_t(lib) *aux, int max)
111 {
112 khint_t k;
113 for (k = kh_begin(aux); k != kh_end(aux); ++k) {
114 if (kh_exist(aux, k)) {
115 lib_aux_t *q = &kh_val(aux, k);
116 if (kh_size(q->best_hash) >= max)
117 kh_clear(pos, q->best_hash);
118 }
119 }
120 }
121
122 static inline int sum_qual(const bam1_t *b)
123 {
124 int i, q;
125 uint8_t *qual = bam_get_qual(b);
126 for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i];
127 return q;
128 }
129
130 int bam_rmdup_core(samFile *in, sam_hdr_t *hdr, samFile *out)
131 {
132 bam1_t *b = NULL;
133 int last_tid = -1, last_pos = -1, r;
134 tmp_stack_t stack;
135 khint_t k;
136 khash_t(lib) *aux = NULL;
137 khash_t(name) *del_set = NULL;
138
139 memset(&stack, 0, sizeof(tmp_stack_t));
140 aux = kh_init(lib);
141 del_set = kh_init(name);
142 b = bam_init1();
143 if (!aux || !del_set || !b) {
144 perror(__func__);
145 goto fail;
146 }
147
148 kh_resize(name, del_set, 4 * BUFFER_SIZE);
149 while ((r = sam_read1(in, hdr, b)) >= 0) {
150 bam1_core_t *c = &b->core;
151 if (c->tid != last_tid || last_pos != c->pos) {
152 if (dump_best(&stack, out, hdr) < 0) goto write_fail; // write the result
153 clear_best(aux, BUFFER_SIZE);
154 if (c->tid != last_tid) {
155 clear_best(aux, 0);
156 if (kh_size(del_set)) { // check
157 fprintf(stderr, "[bam_rmdup_core] %llu unmatched pairs\n", (long long)kh_size(del_set));
158 clear_del_set(del_set);
159 }
160 if ((int)c->tid == -1) { // append unmapped reads
161 if (sam_write1(out, hdr, b) < 0) goto write_fail;
162 while ((r = sam_read1(in, hdr, b)) >= 0) {
163 if (sam_write1(out, hdr, b) < 0) goto write_fail;
164 }
165 break;
166 }
167 last_tid = c->tid;
168 fprintf(stderr, "[bam_rmdup_core] processing reference %s...\n", sam_hdr_tid2name(hdr, c->tid));
169 }
170 }
171 if (!(c->flag&BAM_FPAIRED) || (c->flag&(BAM_FUNMAP|BAM_FMUNMAP)) || (c->mtid >= 0 && c->tid != c->mtid)) {
172 if (sam_write1(out, hdr, b) < 0) goto write_fail;
173 } else if (c->isize > 0) { // paired, head
174 uint64_t key = (uint64_t)c->pos<<32 | c->isize;
175 const char *lib;
176 lib_aux_t *q;
177 int ret;
178 lib = bam_get_library(hdr, b);
179 q = lib? get_aux(aux, lib) : get_aux(aux, "\t");
180 ++q->n_checked;
181 k = kh_put(pos, q->best_hash, key, &ret);
182 if (ret < 0) goto fail;
183 if (ret == 0) { // found in best_hash
184 bam1_t *p = kh_val(q->best_hash, k);
185 ++q->n_removed;
186 if (sum_qual(p) < sum_qual(b)) { // the current alignment is better; this can be accelerated in principle
187 kh_put(name, del_set, strdup(bam_get_qname(p)), &ret); // p will be removed
188 if (ret < 0) goto fail;
189 if (bam_copy1(p, b) == NULL) goto fail; // replaced as b
190 } else kh_put(name, del_set, strdup(bam_get_qname(b)), &ret); // b will be removed
191 if (ret < 0) goto fail;
192 if (ret == 0)
193 fprintf(stderr, "[bam_rmdup_core] inconsistent BAM file for pair '%s'. Continue anyway.\n", bam_get_qname(b));
194 } else { // not found in best_hash
195 kh_val(q->best_hash, k) = bam_dup1(b);
196 stack_insert(&stack, kh_val(q->best_hash, k));
197 }
198 } else { // paired, tail
199 k = kh_get(name, del_set, bam_get_qname(b));
200 if (k != kh_end(del_set)) {
201 free((char*)kh_key(del_set, k));
202 kh_del(name, del_set, k);
203 } else {
204 if (sam_write1(out, hdr, b) < 0) goto write_fail;
205 }
206 }
207 last_pos = c->pos;
208 }
209 if (r < -1) {
210 fprintf(stderr, "[%s] failed to read input file\n", __func__);
211 goto fail;
212 }
213
214 for (k = kh_begin(aux); k != kh_end(aux); ++k) {
215 if (kh_exist(aux, k)) {
216 lib_aux_t *q = &kh_val(aux, k);
217 if (dump_best(&stack, out, hdr) < 0) goto write_fail;
218 fprintf(stderr, "[bam_rmdup_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed,
219 (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k));
220 kh_destroy(pos, q->best_hash);
221 free((char*)kh_key(aux, k));
222 kh_del(lib, aux, k);
223 }
224 }
225 kh_destroy(lib, aux);
226
227 clear_del_set(del_set);
228 kh_destroy(name, del_set);
229 free(stack.a);
230 bam_destroy1(b);
231 return 0;
232
233 write_fail:
234 print_error_errno("rmdup", "failed to write record");
235 fail:
236 clear_stack(&stack);
237 free(stack.a);
238 if (aux) {
239 for (k = kh_begin(aux); k != kh_end(aux); ++k) {
240 if (kh_exist(aux, k)) {
241 lib_aux_t *q = &kh_val(aux, k);
242 kh_destroy(pos, q->best_hash);
243 free((char*)kh_key(aux, k));
244 }
245 }
246 kh_destroy(lib, aux);
247 }
248 if (del_set) {
249 clear_del_set(del_set);
250 kh_destroy(name, del_set);
251 }
252 bam_destroy1(b);
253 return 1;
254 }
255
256 int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se);
257
258 static int rmdup_usage(void) {
259 fprintf(stderr, "\n");
260 fprintf(stderr, "Usage: samtools rmdup [-sS] <input.srt.bam> <output.bam>\n\n");
261 fprintf(stderr, "Option: -s rmdup for SE reads\n");
262 fprintf(stderr, " -S treat PE reads as SE in rmdup (force -s)\n");
263
264 sam_global_opt_help(stderr, "-....--.");
265 return 1;
266 }
267
268 int bam_rmdup(int argc, char *argv[])
269 {
270 int c, ret, is_se = 0, force_se = 0;
271 samFile *in, *out;
272 sam_hdr_t *header;
273 char wmode[3] = {'w', 'b', 0};
274 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
275
276 static const struct option lopts[] = {
277 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'),
278 { NULL, 0, NULL, 0 }
279 };
280
281 while ((c = getopt_long(argc, argv, "sS", lopts, NULL)) >= 0) {
282 switch (c) {
283 case 's': is_se = 1; break;
284 case 'S': force_se = is_se = 1; break;
285 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
286 /* else fall-through */
287 case '?': return rmdup_usage();
288 }
289 }
290 if (optind + 2 > argc)
291 return rmdup_usage();
292
293 in = sam_open_format(argv[optind], "r", &ga.in);
294 if (!in) {
295 print_error_errno("rmdup", "failed to open \"%s\" for input", argv[optind]);
296 return 1;
297 }
298 header = sam_hdr_read(in);
299 if (header == NULL || sam_hdr_nref(header) == 0) {
300 fprintf(stderr, "[bam_rmdup] input SAM does not have header. Abort!\n");
301 return 1;
302 }
303
304 sam_open_mode(wmode+1, argv[optind+1], NULL);
305 out = sam_open_format(argv[optind+1], wmode, &ga.out);
306 if (!out) {
307 print_error_errno("rmdup", "failed to open \"%s\" for output", argv[optind+1]);
308 return 1;
309 }
310 if (sam_hdr_write(out, header) < 0) {
311 print_error_errno("rmdup", "failed to write header");
312 return 1;
313 }
314
315 if (is_se) ret = bam_rmdupse_core(in, header, out, force_se);
316 else ret = bam_rmdup_core(in, header, out);
317
318 sam_hdr_destroy(header);
319 sam_close(in);
320 if (sam_close(out) < 0) {
321 fprintf(stderr, "[bam_rmdup] error closing output file\n");
322 ret = 1;
323 }
324 return ret;
325 }