Debian Codegraph @

samtools/bam_rmdup.c.pysam.c

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