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