Debian Codegraph @

samtools/bamshuf.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bamshuf.c -- collate subcommand.
4
5 Copyright (C) 2012 Broad Institute.
6 Copyright (C) 2013, 2015-2019,2023 Genome Research Ltd.
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 <unistd.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <assert.h>
35 #include <errno.h>
36 #ifdef _WIN32
37 # define WIN32_LEAN_AND_MEAN
38 # include <windows.h>
39 #endif
40 #include "htslib/sam.h"
41 #include "htslib/hts.h"
42 #include "htslib/ksort.h"
43 #include "samtools.h"
44 #include "htslib/thread_pool.h"
45 #include "sam_opts.h"
46 #include "htslib/khash.h"
47
48 #define DEF_CLEVEL 1
49
50 static inline unsigned hash_Wang(unsigned key)
51 {
52 key += ~(key << 15);
53 key ^= (key >> 10);
54 key += (key << 3);
55 key ^= (key >> 6);
56 key += ~(key << 11);
57 key ^= (key >> 16);
58 return key;
59 }
60
61 static inline unsigned hash_X31_Wang(const char *s)
62 {
63 unsigned h = *s;
64 if (h) {
65 for (++s ; *s; ++s) h = (h << 5) - h + *s;
66 return hash_Wang(h);
67 } else return 0;
68 }
69
70 typedef struct {
71 unsigned key;
72 bam1_t *b;
73 } elem_t;
74
75 static inline int elem_lt(elem_t x, elem_t y)
76 {
77 if (x.key < y.key) return 1;
78 if (x.key == y.key) {
79 int t;
80 t = strcmp(bam_get_qname(x.b), bam_get_qname(y.b));
81 if (t < 0) return 1;
82 return (t == 0 && ((x.b->core.flag>>6&3) < (y.b->core.flag>>6&3)));
83 } else return 0;
84 }
85
86 KSORT_INIT(bamshuf, elem_t, elem_lt)
87
88
89 typedef struct {
90 int written;
91 bam1_t *b;
92 } bam_item_t;
93
94 typedef struct {
95 bam1_t *bam_pool;
96 bam_item_t *items;
97 size_t size;
98 size_t index;
99 } bam_list_t;
100
101 typedef struct {
102 bam_item_t *bi;
103 } store_item_t;
104
105 KHASH_MAP_INIT_STR(bam_store, store_item_t)
106
107
108 static bam_item_t *store_bam(bam_list_t *list) {
109 size_t old_index = list->index;
110
111 list->items[list->index++].written = 0;
112
113 if (list->index >= list->size)
114 list->index = 0;
115
116 return &list->items[old_index];
117 }
118
119
120 static int write_bam_needed(bam_list_t *list) {
121 return !list->items[list->index].written;
122 }
123
124
125 static void mark_bam_as_written(bam_list_t *list) {
126 list->items[list->index].written = 1;
127 }
128
129
130 static int create_bam_list(bam_list_t *list, size_t max_size) {
131 size_t i;
132
133 list->size = list->index = 0;
134 list->items = NULL;
135 list->bam_pool = NULL;
136
137 if ((list->items = malloc(max_size * sizeof(bam_item_t))) == NULL) {
138 return 1;
139 }
140
141 if ((list->bam_pool = calloc(max_size, sizeof(bam1_t))) == NULL) {
142 return 1;
143 }
144
145 for (i = 0; i < max_size; i++) {
146 list->items[i].b = &list->bam_pool[i];
147 list->items[i].written = 1;
148 }
149
150 list->size = max_size;
151 list->index = 0;
152
153 return 0;
154 }
155
156
157 static void destroy_bam_list(bam_list_t *list) {
158 size_t i;
159
160 for (i = 0; i < list->size; i++) {
161 free(list->bam_pool[i].data);
162 }
163
164 free(list->bam_pool);
165 free(list->items);
166 }
167
168
169 static inline int write_to_bin_file(bam1_t *bam, int64_t *count, samFile **bin_files, char **names, sam_hdr_t *header, int files) {
170 uint32_t x;
171
172 x = hash_X31_Wang(bam_get_qname(bam)) % files;
173
174 if (sam_write1(bin_files[x], header, bam) < 0) {
175 print_error_errno("collate", "Couldn't write to intermediate file \"%s\"", names[x]);
176 return 1;
177 }
178
179 ++count[x];
180
181 return 0;
182 }
183
184
185 static int bamshuf(const char *fn, int n_files, const char *pre, int clevel,
186 int is_stdout, const char *output_file, int fast, int store_max, sam_global_args *ga, char *arg_list, int no_pg)
187 {
188 samFile *fp, *fpw = NULL, **fpt = NULL;
189 char **fnt = NULL, modew[8];
190 bam1_t *b = NULL;
191 int i, counter, l, r;
192 sam_hdr_t *h = NULL;
193 int64_t j, max_cnt = 0, *cnt = NULL;
194 elem_t *a = NULL;
195 htsThreadPool p = {NULL, 0};
196
197 if (ga->nthreads > 0) {
198 if (!(p.pool = hts_tpool_init(ga->nthreads))) {
199 print_error_errno("collate", "Error creating thread pool\n");
200 return 1;
201 }
202 }
203
204 // Read input, distribute reads pseudo-randomly into n_files temporary
205 // files.
206 fp = sam_open_format(fn ? fn : "-", "r", &ga->in);
207 if (fp == NULL) {
208 print_error_errno("collate", "Cannot open input file \"%s\"", fn);
209 return 1;
210 }
211 if (p.pool) hts_set_opt(fp, HTS_OPT_THREAD_POOL, &p);
212
213 h = sam_hdr_read(fp);
214 if (h == NULL) {
215 fprintf(samtools_stderr, "Couldn't read header for '%s'\n", fn);
216 goto fail;
217 }
218
219 if ((-1 == sam_hdr_update_hd(h, "SO", "unsorted", "GO", "query"))
220 && (-1 == sam_hdr_add_line(h, "HD", "VN", SAM_FORMAT_VERSION, "SO", "unsorted", "GO", "query", NULL))
221 ) {
222 print_error("collate", "failed to update HD line\n");
223 goto fail;
224 }
225
226 // open final output file
227 l = strlen(pre);
228
229 sprintf(modew, "wb%d", (clevel >= 0 && clevel <= 9)? clevel : DEF_CLEVEL);
230
231 if (!is_stdout && !output_file) { // output to a file (name based on prefix)
232 char *fnw = (char*)calloc(l + 5, 1);
233 if (!fnw) goto mem_fail;
234 if (ga->out.format == unknown_format)
235 sprintf(fnw, "%s.bam", pre); // "wb" above makes BAM the default
236 else
237 sprintf(fnw, "%s.%s", pre, hts_format_file_extension(&ga->out));
238 fpw = sam_open_format(fnw, modew, &ga->out);
239 free(fnw);
240 } else if (output_file) { // output to a given file
241 modew[0] = 'w'; modew[1] = '\0';
242 sam_open_mode(modew + 1, output_file, NULL);
243 j = strlen(modew);
244 snprintf(modew + j, sizeof(modew) - j, "%d",
245 (clevel >= 0 && clevel <= 9)? clevel : DEF_CLEVEL);
246 fpw = sam_open_format(output_file, modew, &ga->out);
247 } else fpw = sam_open_format("-", modew, &ga->out); // output to samtools_stdout
248 if (fpw == NULL) {
249 if (is_stdout) print_error_errno("collate", "Cannot open standard output");
250 else print_error_errno("collate", "Cannot open output file \"%s.bam\"", pre);
251 goto fail;
252 }
253 if (p.pool) hts_set_opt(fpw, HTS_OPT_THREAD_POOL, &p);
254
255 if (!no_pg && sam_hdr_add_pg(h, "samtools",
256 "VN", samtools_version(),
257 arg_list ? "CL": NULL,
258 arg_list ? arg_list : NULL,
259 NULL)) {
260 print_error("collate", "failed to add PG line to header of \"%s\"", output_file);
261 goto fail;
262 }
263
264 if (sam_hdr_write(fpw, h) < 0) {
265 print_error_errno("collate", "Couldn't write header");
266 goto fail;
267 }
268
269 fnt = (char**)calloc(n_files, sizeof(char*));
270 if (!fnt) goto mem_fail;
271 fpt = (samFile**)calloc(n_files, sizeof(samFile*));
272 if (!fpt) goto mem_fail;
273 cnt = (int64_t*)calloc(n_files, 8);
274 if (!cnt) goto mem_fail;
275
276 for (i = counter = 0; i < n_files; ++i) {
277 fnt[i] = (char*)calloc(l + 20, 1);
278 if (!fnt[i]) goto mem_fail;
279 do {
280 sprintf(fnt[i], "%s.%04d.bam", pre, counter++);
281 fpt[i] = sam_open(fnt[i], "wxb1");
282 } while (!fpt[i] && errno == EEXIST);
283 if (fpt[i] == NULL) {
284 print_error_errno("collate", "Cannot open intermediate file \"%s\"", fnt[i]);
285 goto fail;
286 }
287 if (p.pool) hts_set_opt(fpt[i], HTS_OPT_THREAD_POOL, &p);
288 if (sam_hdr_write(fpt[i], h) < 0) {
289 print_error_errno("collate", "Couldn't write header to intermediate file \"%s\"", fnt[i]);
290 goto fail;
291 }
292 }
293
294 if (fast) {
295 khash_t(bam_store) *stored = kh_init(bam_store);
296 khiter_t itr;
297 bam_list_t list;
298 int err = 0;
299 if (!stored) goto mem_fail;
300
301 if (store_max < 2) store_max = 2;
302
303 if (create_bam_list(&list, store_max)) {
304 fprintf(samtools_stderr, "[collate[ ERROR: unable to create bam list.\n");
305 err = 1;
306 goto fast_fail;
307 }
308
309 while ((r = sam_read1(fp, h, list.items[list.index].b)) >= 0) {
310 int ret;
311 bam1_t *b = list.items[list.index].b;
312 int readflag = b->core.flag & (BAM_FREAD1 | BAM_FREAD2);
313
314 // strictly paired reads only
315 if (!(b->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) && (readflag == BAM_FREAD1 || readflag == BAM_FREAD2)) {
316
317 itr = kh_get(bam_store, stored, bam_get_qname(b));
318
319 if (itr == kh_end(stored)) {
320 // new read
321 itr = kh_put(bam_store, stored, bam_get_qname(b), &ret);
322
323 if (ret > 0) { // okay to go ahead store it
324 kh_value(stored, itr).bi = store_bam(&list);
325
326 // see if the next one on the list needs to be written out
327 if (write_bam_needed(&list)) {
328 if (write_to_bin_file(list.items[list.index].b, cnt, fpt, fnt, h, n_files) < 0) {
329 fprintf(samtools_stderr, "[collate] ERROR: could not write line.\n");
330 err = 1;
331 goto fast_fail;
332 } else {
333 mark_bam_as_written(&list);
334
335 itr = kh_get(bam_store, stored, bam_get_qname(list.items[list.index].b));
336
337 if (itr != kh_end(stored)) {
338 kh_del(bam_store, stored, itr);
339 } else {
340 fprintf(samtools_stderr, "[collate] ERROR: stored value not in hash.\n");
341 err = 1;
342 goto fast_fail;
343 }
344 }
345 }
346 } else if (ret == 0) {
347 fprintf(samtools_stderr, "[collate] ERROR: value already in hash.\n");
348 err = 1;
349 goto fast_fail;
350 } else {
351 fprintf(samtools_stderr, "[collate] ERROR: unable to store in hash.\n");
352 err = 1;
353 goto fast_fail;
354 }
355 } else { // we have a match
356 // write out the reads in R1 R2 order
357 bam1_t *r1, *r2;
358
359 if (b->core.flag & BAM_FREAD1) {
360 r1 = b;
361 r2 = kh_value(stored, itr).bi->b;
362 } else {
363 r1 = kh_value(stored, itr).bi->b;
364 r2 = b;
365 }
366
367 if (sam_write1(fpw, h, r1) < 0) {
368 fprintf(samtools_stderr, "[collate] ERROR: could not write r1 alignment.\n");
369 err = 1;
370 goto fast_fail;
371 }
372
373 if (sam_write1(fpw, h, r2) < 0) {
374 fprintf(samtools_stderr, "[collate] ERROR: could not write r2 alignment.\n");
375 err = 1;
376 goto fast_fail;
377 }
378
379 mark_bam_as_written(&list);
380
381 // remove stored read
382 kh_value(stored, itr).bi->written = 1;
383 kh_del(bam_store, stored, itr);
384 }
385 }
386 }
387
388 for (list.index = 0; list.index < list.size; list.index++) {
389 if (write_bam_needed(&list)) {
390 bam1_t *b = list.items[list.index].b;
391
392 if (write_to_bin_file(b, cnt, fpt, fnt, h, n_files)) {
393 err = 1;
394 goto fast_fail;
395 } else {
396 itr = kh_get(bam_store, stored, bam_get_qname(b));
397 kh_del(bam_store, stored, itr);
398 }
399 }
400 }
401
402 fast_fail:
403 if (err) {
404 for (itr = kh_begin(stored); itr != kh_end(stored); ++itr) {
405 if (kh_exist(stored, itr)) {
406 kh_del(bam_store, stored, itr);
407 }
408 }
409
410 kh_destroy(bam_store, stored);
411 destroy_bam_list(&list);
412 goto fail;
413 } else {
414 kh_destroy(bam_store, stored);
415 destroy_bam_list(&list);
416 }
417
418 } else {
419 b = bam_init1();
420 if (!b) goto mem_fail;
421
422 while ((r = sam_read1(fp, h, b)) >= 0) {
423 if (write_to_bin_file(b, cnt, fpt, fnt, h, n_files)) {
424 bam_destroy1(b);
425 goto fail;
426 }
427 }
428
429 bam_destroy1(b);
430 }
431
432 if (r < -1) {
433 fprintf(samtools_stderr, "Error reading input file\n");
434 goto fail;
435 }
436 for (i = 0; i < n_files; ++i) {
437 // Close split output
438 r = sam_close(fpt[i]);
439 fpt[i] = NULL;
440 if (r < 0) {
441 fprintf(samtools_stderr, "Error on closing '%s'\n", fnt[i]);
442 return 1;
443 }
444
445 // Find biggest count
446 if (max_cnt < cnt[i]) max_cnt = cnt[i];
447 }
448 free(fpt);
449 fpt = NULL;
450 sam_close(fp);
451 fp = NULL;
452
453 // merge
454 a = malloc(max_cnt * sizeof(elem_t));
455 if (!a) goto mem_fail;
456 for (j = 0; j < max_cnt; ++j) {
457 a[j].b = bam_init1();
458 if (!a[j].b) { max_cnt = j; goto mem_fail; }
459 }
460
461 for (i = 0; i < n_files; ++i) {
462 int64_t c = cnt[i];
463 fp = sam_open_format(fnt[i], "r", &ga->in);
464 if (NULL == fp) {
465 print_error_errno("collate", "Couldn't open \"%s\"", fnt[i]);
466 goto fail;
467 }
468 if (p.pool) hts_set_opt(fp, HTS_OPT_THREAD_POOL, &p);
469 sam_hdr_destroy(sam_hdr_read(fp)); // Skip over header
470
471 // Slurp in one of the split files
472 for (j = 0; j < c; ++j) {
473 if (sam_read1(fp, h, a[j].b) < 0) {
474 fprintf(samtools_stderr, "Error reading '%s'\n", fnt[i]);
475 goto fail;
476 }
477 a[j].key = hash_X31_Wang(bam_get_qname(a[j].b));
478 }
479 sam_close(fp);
480 unlink(fnt[i]);
481 free(fnt[i]);
482 fnt[i] = NULL;
483
484 ks_introsort(bamshuf, c, a); // Shuffle all the reads
485
486 // Write them out again
487 for (j = 0; j < c; ++j) {
488 if (sam_write1(fpw, h, a[j].b) < 0) {
489 print_error_errno("collate", "Error writing to output");
490 goto fail;
491 }
492 }
493 }
494
495 sam_hdr_destroy(h);
496 for (j = 0; j < max_cnt; ++j) bam_destroy1(a[j].b);
497 free(a); free(fnt); free(cnt);
498 sam_global_args_free(ga);
499 if (sam_close(fpw) < 0) {
500 fprintf(samtools_stderr, "Error on closing output\n");
501 return 1;
502 }
503
504 if (p.pool) hts_tpool_destroy(p.pool);
505 return 0;
506
507 mem_fail:
508 fprintf(samtools_stderr, "Out of memory\n");
509
510 fail:
511 if (fp) sam_close(fp);
512 if (fpw) sam_close(fpw);
513 if (h) sam_hdr_destroy(h);
514 for (i = 0; i < n_files; ++i) {
515 if (fnt) free(fnt[i]);
516 if (fpt && fpt[i]) sam_close(fpt[i]);
517 }
518 if (a) {
519 for (j = 0; j < max_cnt; ++j) bam_destroy1(a[j].b);
520 free(a);
521 }
522 free(fnt);
523 free(fpt);
524 free(cnt);
525 if (p.pool) hts_tpool_destroy(p.pool);
526 sam_global_args_free(ga);
527 return 1;
528 }
529
530 static int usage(FILE *fp, int n_files, int reads_store) {
531 fprintf(fp,
532 "Usage: samtools collate [options...] <in.bam> [<prefix>]\n\n"
533 "Options:\n"
534 " -O Output to samtools_stdout\n"
535 " -o Output file name (use prefix if not set)\n"
536 " -u Uncompressed BAM output\n"
537 " -f Fast (only primary alignments)\n"
538 " -r Working reads stored (with -f) [%d]\n" // reads_store
539 " -l INT Compression level [%d]\n" // DEF_CLEVEL
540 " -n INT Number of temporary files [%d]\n" // n_files
541 " -T PREFIX\n"
542 " Write temporary files to PREFIX.nnnn.bam\n"
543 " --no-PG do not add a PG line\n",
544 reads_store, DEF_CLEVEL, n_files);
545
546 sam_global_opt_help(fp, "-....@-.");
547 fprintf(fp,
548 " <prefix> is required unless the -o or -O options are used.\n");
549
550 return 1;
551 }
552
553 char *generate_prefix(const char *out_fn) {
554 char *prefix;
555 unsigned int pid = getpid();
556
557 if (out_fn && !(*out_fn == '-' && out_fn[1] == '\0')) {
558 // <out_fn>.<collate><pid>.<nnnn>.<bam>
559 size_t plen = strlen(out_fn) + 50;
560 if (!(prefix = malloc(plen))) {
561 perror("collate");
562 return NULL;
563 }
564 snprintf(prefix, plen, "%s.collate%x", out_fn, pid);
565 return prefix;
566 }
567
568 #ifdef _WIN32
569 # define PREFIX_LEN (MAX_PATH + 16)
570 DWORD ret;
571 prefix = calloc(PREFIX_LEN, sizeof(*prefix));
572 if (!prefix) {
573 perror("collate");
574 return NULL;
575 }
576 ret = GetTempPathA(MAX_PATH, prefix);
577 if (ret > MAX_PATH || ret == 0) {
578 fprintf(samtools_stderr,
579 "[E::collate] Couldn't get path for temporary files.\n");
580 free(prefix);
581 return NULL;
582 }
583 snprintf(prefix + ret, PREFIX_LEN - ret, "\\%x", pid);
584 return prefix;
585 #else
586 char *tmp_env = getenv("TMPDIR");
587 if (!tmp_env)
588 tmp_env = "/tmp";
589
590 size_t prefix_len = strlen(tmp_env)+20;
591 prefix = malloc(prefix_len);
592 if (!prefix) {
593 perror("collate");
594 return NULL;
595 }
596 snprintf(prefix, prefix_len, "%s/collate%x", tmp_env, pid);
597
598 return prefix;
599 #endif
600 }
601
602 int main_bamshuf(int argc, char *argv[])
603 {
604 int c, n_files = 64, clevel = DEF_CLEVEL, is_stdout = 0, is_un = 0, fast_coll = 0, reads_store = 10000, ret, pre_mem = 0, no_pg = 0;
605 const char *output_file = NULL;
606 char *prefix = NULL, *arg_list = NULL;
607 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
608 static const struct option lopts[] = {
609 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'),
610 {"no-PG", no_argument, NULL, 1},
611 { NULL, 0, NULL, 0 }
612 };
613
614 while ((c = getopt_long(argc, argv, "n:l:uOo:@:fr:T:", lopts, NULL)) >= 0) {
615 switch (c) {
616 case 'n': n_files = atoi(optarg); break;
617 case 'l': clevel = atoi(optarg); break;
618 case 'u': is_un = 1; break;
619 case 'O': is_stdout = 1; break;
620 case 'o': output_file = optarg; break;
621 case 'f': fast_coll = 1; break;
622 case 'r': reads_store = atoi(optarg); break;
623 case 'T': prefix = optarg; break;
624 case 1: no_pg = 1; break;
625 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
626 /* else fall-through */
627 case '?': return usage(samtools_stderr, n_files, reads_store);
628 }
629 }
630 if (is_un) clevel = 0;
631 if (argc >= optind + 2) prefix = argv[optind+1];
632 if (argc == optind) {
633 if (argc > 1 || !isatty(STDIN_FILENO))
634 fprintf(samtools_stderr, "collate: no input filename specified.\n");
635 return usage(argc > 1 || !isatty(STDIN_FILENO) ? samtools_stderr : samtools_stdout,
636 n_files, reads_store);
637 }
638 if (!(prefix || is_stdout || output_file))
639 return usage(samtools_stderr, n_files, reads_store);
640 if (is_stdout && output_file) {
641 fprintf(samtools_stderr, "collate: -o and -O options cannot be used together.\n");
642 return usage(samtools_stderr, n_files, reads_store);
643 }
644 if (!prefix) {
645 prefix = generate_prefix(output_file);
646 pre_mem = 1;
647 }
648
649 if (!prefix) return EXIT_FAILURE;
650
651 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
652 print_error("collate", "failed to create arg_list");
653 return 1;
654 }
655
656 ret = bamshuf(argv[optind], n_files, prefix, clevel, is_stdout,
657 output_file, fast_coll, reads_store, &ga, arg_list, no_pg);
658
659 if (pre_mem) free(prefix);
660 free(arg_list);
661
662 return ret;
663 }