Debian Codegraph @

bcftools/vcfsort.c

raw symbols SCIP
1 /* vcfsort.c -- sort subcommand
2
3 Copyright (C) 2017-2024 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24
25 */
26
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <getopt.h>
30 #include <ctype.h>
31 #include <string.h>
32 #include <strings.h>
33 #include <errno.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <math.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #endif
41 #include <htslib/vcf.h>
42 #include <htslib/kstring.h>
43 #include <htslib/hts_os.h>
44 #include <htslib/hts_defs.h>
45 #include <htslib/bgzf.h>
46 #include "kheap.h"
47 #include "bcftools.h"
48
49 #define MAX_TMP_FILES_PER_LAYER 32
50 #define MERGE_LAYERS 12
51 #define MAX_TMP_FILES (MAX_TMP_FILES_PER_LAYER * MERGE_LAYERS)
52
53 typedef struct
54 {
55 char *fname;
56 htsFile *fh;
57 BGZF *bgz;
58 size_t idx;
59 bcf1_t *rec;
60 int is_merged;
61 }
62 blk_t;
63
64 typedef struct
65 {
66 size_t len;
67 hts_pos_t pos;
68 int rid;
69 float qual;
70 uint8_t data[];
71 }
72 packed_bcf_t;
73
74 typedef struct _args_t
75 {
76 bcf_hdr_t *hdr;
77 char **argv, *fname, *output_fname, *tmp_dir;
78 int argc, output_type, clevel;
79 size_t max_mem, mem;
80 packed_bcf_t **buf;
81 uint8_t *mem_block;
82
83 size_t nbuf, mbuf, nblk, tmp_count;
84 blk_t blk[MAX_TMP_FILES];
85 uint32_t tmp_layers[MERGE_LAYERS];
86 int write_index;
87 }
88 args_t;
89
90 void clean_files(args_t *args)
91 {
92 int i;
93 fprintf(stderr,"Cleaning\n");
94 for (i=0; i<MAX_TMP_FILES; i++)
95 {
96 blk_t *blk = &args->blk[i];
97 if ( blk->fname )
98 {
99 unlink(blk->fname);
100 free(blk->fname);
101 }
102 if ( blk->rec )
103 bcf_destroy(blk->rec);
104 }
105 rmdir(args->tmp_dir);
106 }
107 void HTS_FORMAT(HTS_PRINTF_FMT, 2, 3) HTS_NORETURN
108 clean_files_and_throw(args_t *args, const char *format, ...)
109 {
110 va_list ap;
111 va_start(ap, format);
112 vfprintf(stderr, format, ap);
113 va_end(ap);
114 clean_files(args);
115 exit(-1);
116 }
117
118 int cmp_bcf_pos(const void *aptr, const void *bptr)
119 {
120 bcf1_t *a = *((bcf1_t**)aptr);
121 bcf1_t *b = *((bcf1_t**)bptr);
122 if ( a->rid < b->rid ) return -1;
123 if ( a->rid > b->rid ) return 1;
124 if ( a->pos < b->pos ) return -1;
125 if ( a->pos > b->pos ) return 1;
126 return 0;
127 }
128 int cmp_bcf_pos_ref_alt(const void *aptr, const void *bptr)
129 {
130 bcf1_t *a = *((bcf1_t**)aptr);
131 bcf1_t *b = *((bcf1_t**)bptr);
132 if ( a->rid < b->rid ) return -1;
133 if ( a->rid > b->rid ) return 1;
134 if ( a->pos < b->pos ) return -1;
135 if ( a->pos > b->pos ) return 1;
136
137 // Sort the same chr:pos records lexicographically by ref,alt.
138 // This will be called rarely so should not slow the sorting down
139 // noticeably.
140
141 int i;
142 for (i=0; i<a->n_allele; i++)
143 {
144 if ( i >= b->n_allele ) return 1;
145 int ret = strcasecmp(a->d.allele[i],b->d.allele[i]);
146 if ( ret ) return ret;
147 }
148 if ( a->n_allele < b->n_allele ) return -1;
149 return 0;
150 }
151
152 static int cmp_packed_bcf_pos_ref_alt(const void *aptr, const void *bptr)
153 {
154 packed_bcf_t *a = *(packed_bcf_t **) aptr;
155 packed_bcf_t *b = *(packed_bcf_t **) bptr;
156
157 if ( a->rid < b->rid ) return -1;
158 if ( a->rid > b->rid ) return 1;
159 if ( a->pos < b->pos ) return -1;
160 if ( a->pos > b->pos ) return 1;
161
162 // Sort lexicographically by ref,alt. These are stored tab-separated
163 // as the first item in packed_bcf_t::data
164 return strcmp((char *) a->data, (char *) b->data);
165 }
166
167 static int cmp_packed_bcf_pos_ref_alt_stable(const void *aptr, const void *bptr)
168 {
169 // cmp_bcf_pos_ref_alt() with tie-breaker to make qsort stable
170 int res = cmp_packed_bcf_pos_ref_alt(aptr, bptr);
171 if (res != 0) return res;
172
173 // Got a tie - use the position in the original input to break it.
174 // As everything is read into a big memory buffer, for most records
175 // we can just compare the pointers directly. The exception is
176 // any record that didn't quite fit in the memory buffer, causing it to be
177 // flushed. Those are flagged by setting packed_bcf_t::len = SIZE_MAX, and
178 // as they were the last record in the segment, they should always sort
179 // after unflagged records.
180
181 packed_bcf_t *a = *(packed_bcf_t **) aptr;
182 packed_bcf_t *b = *(packed_bcf_t **) bptr;
183
184 if (a->len == SIZE_MAX) return 1;
185 if (b->len == SIZE_MAX) return -1;
186
187 return a < b ? -1 : 1;
188 }
189
190 static uint8_t *pack_unsigned(uint8_t *data, uint64_t val)
191 {
192 do {
193 *data++ = (val & 0x7f) | ((val > 0x7f) ? 0x80 : 0);
194 val >>= 7;
195 } while (val > 0);
196 return data;
197 }
198
199 static uint8_t *pack_hts_pos(uint8_t *data, hts_pos_t val)
200 {
201 uint64_t sign = val < 0;
202 uint64_t v = val < 0 ? -(val + 1) : val;
203 v = v << 1 | sign;
204 return pack_unsigned(data, v);
205 }
206
207 static uint8_t *pack_bcf_data(packed_bcf_t *dest, const bcf1_t *src,
208 int outside_buffer)
209 {
210 uint32_t i;
211 uint8_t *data = dest->data;
212 uint8_t *start = dest->data;
213 dest->pos = src->pos;
214 dest->rid = src->rid;
215 dest->qual = src->qual;
216
217 // Copy in alleles, for the comparison function
218 for (i = 0; i < src->n_allele; i++)
219 {
220 size_t l = strlen(src->d.allele[i]);
221 if (i > 0) *data++ = '\t';
222 memcpy(data, src->d.allele[i], l);
223 data += l;
224 }
225 *data++ = '\0';
226
227 if (outside_buffer)
228 {
229 dest->len = SIZE_MAX;
230 memcpy(data, &src, sizeof(src));
231 data += sizeof(src);
232 return data;
233 }
234
235 data = pack_hts_pos(data, src->rlen);
236 data = pack_unsigned(data, src->n_info);
237 data = pack_unsigned(data, src->n_allele);
238 data = pack_unsigned(data, src->n_fmt);
239 data = pack_unsigned(data, src->n_sample);
240 data = pack_unsigned(data, src->shared.l);
241 data = pack_unsigned(data, src->indiv.l);
242 if (src->shared.l)
243 memcpy(data, src->shared.s, src->shared.l);
244 data += src->shared.l;
245 if (src->indiv.l)
246 memcpy(data, src->indiv.s, src->indiv.l);
247 data += src->indiv.l;
248 dest->len = data - start;
249 return data;
250 }
251
252 static int write_packed_bcf(BGZF *fp, packed_bcf_t *src)
253 {
254 // Write pos, rid, qual
255 size_t len = src->data - (uint8_t *) &src->pos;
256 if (bgzf_write_small(fp, &src->pos, len) < len)
257 return -1;
258
259 // Skip the copy of the alleles
260 size_t skip = strlen((char *) src->data) + 1;
261
262 // Write everything else
263 if (src->len < SIZE_MAX)
264 {
265 // In main memory block
266 len = src->len - skip;
267 if (bgzf_write_small(fp, src->data + skip, len) < len)
268 return -1;
269 }
270 else
271 {
272 // Record didn't fit in the main block. To minimize the
273 // overflow, its packed_bcf_t data will be imcomplete. A pointer to
274 // its bcf1_t struct will have been placed after the allele data
275 // so we can finish the packing job and write it in the same format
276 // the rest of the data
277 bcf1_t *rec;
278 uint8_t tmp[100], *data = tmp;
279 memcpy(&rec, src->data + skip, sizeof(rec));
280
281 data = pack_hts_pos(data, rec->rlen);
282 data = pack_unsigned(data, rec->n_info);
283 data = pack_unsigned(data, rec->n_allele);
284 data = pack_unsigned(data, rec->n_fmt);
285 data = pack_unsigned(data, rec->n_sample);
286 data = pack_unsigned(data, rec->shared.l);
287 data = pack_unsigned(data, rec->indiv.l);
288 if (bgzf_write_small(fp, tmp, data - tmp) < data - tmp)
289 return -1;
290 if (rec->shared.l > 0 &&
291 bgzf_write_small(fp, rec->shared.s, rec->shared.l) < rec->shared.l)
292 return -1;
293 if (rec->indiv.l > 0 &&
294 bgzf_write_small(fp, rec->indiv.s, rec->indiv.l) < rec->indiv.l)
295 return -1;
296 }
297
298 return 0;
299 }
300
301 static uint64_t unpack_unsigned(BGZF *fp, int *err)
302 {
303 uint8_t data;
304 uint64_t val = 0;
305 uint32_t i = 0;
306
307 if (bgzf_read_small(fp, &data, sizeof(data)) <= 0)
308 goto short_read;
309
310 while (data & 0x80)
311 {
312 val |= (uint64_t)(data & 0x7f) << i;
313 i += 7;
314 if (bgzf_read_small(fp, &data, sizeof(data)) <= 0)
315 goto short_read;
316 }
317 val |= (uint64_t)data << i;
318 return val;
319
320 short_read:
321 *err = 1;
322 return 0;
323 }
324
325 static hts_pos_t unpack_hts_pos(BGZF *fp, int *err)
326 {
327 uint64_t v = unpack_unsigned(fp, err);
328
329 if ((v & 1) == 0)
330 return (hts_pos_t)(v >> 1);
331 else
332 return -(hts_pos_t)(v >> 1) - 1;
333 }
334
335 static int read_packed_bcf(BGZF *fp, bcf1_t *dest)
336 {
337 int err = 0;
338 packed_bcf_t tmp;
339 size_t len = tmp.data - (uint8_t *) &tmp.pos;
340
341 bcf_clear(dest);
342 ssize_t got = bgzf_read_small(fp, &tmp.pos, len);
343 if (got == 0)
344 return -1; // EOF
345 if (got < len)
346 return -2; // Error or short read
347 dest->pos = tmp.pos;
348 dest->rid = tmp.rid;
349 dest->qual = tmp.qual;
350 dest->rlen = unpack_hts_pos(fp, &err);
351 dest->n_info = unpack_unsigned(fp, &err);
352 dest->n_allele = unpack_unsigned(fp, &err);
353 dest->n_fmt = unpack_unsigned(fp, &err);
354 dest->n_sample = unpack_unsigned(fp, &err);
355 len = unpack_unsigned(fp, &err);
356 if (ks_resize(&dest->shared, len) != 0)
357 return -2;
358 dest->shared.l = len;
359 len = unpack_unsigned(fp, &err);
360 if (ks_resize(&dest->indiv, len) != 0)
361 return -2;
362 dest->indiv.l = len;
363 err |= bgzf_read_small(fp, dest->shared.s, dest->shared.l) < dest->shared.l;
364 err |= bgzf_read_small(fp, dest->indiv.s, dest->indiv.l) < dest->indiv.l;
365 return err == 0 ? 0 : -2;
366 }
367
368 void open_tmp_file(args_t *args, blk_t *blk, int is_merged)
369 {
370 kstring_t str = {0,0,0};
371 int tries = 1000;
372
373 blk->fh = NULL;
374 blk->bgz = NULL;
375
376 do {
377 if (ksprintf(ks_clear(&str), "%s/%05zd%s",
378 args->tmp_dir, args->tmp_count++,
379 is_merged ? ".bcf" : "") < 0) {
380 clean_files_and_throw(args, "%s", strerror(errno));
381 }
382
383 if (is_merged)
384 blk->fh = hts_open(str.s, "wbx1");
385 else
386 blk->bgz = bgzf_open(str.s, "wx1");
387 if ( blk->fh == NULL && blk->bgz == NULL && (errno != EEXIST || --tries <= 0)) {
388 clean_files_and_throw(args, "Cannot write %s: %s\n",
389 str.s, strerror(errno));
390 }
391 } while (blk->fh == NULL && blk->bgz == NULL);
392
393 blk->fname = ks_release(&str);
394 blk->idx = args->tmp_count - 1;
395 }
396
397 void do_partial_merge(args_t *args);
398
399 void buf_flush(args_t *args, bcf1_t *last_rec)
400 {
401 if ( !args->nbuf ) return;
402
403 qsort(args->buf, args->nbuf, sizeof(*args->buf), cmp_packed_bcf_pos_ref_alt_stable);
404
405 if (args->tmp_layers[0] >= MAX_TMP_FILES_PER_LAYER)
406 do_partial_merge(args);
407
408 assert(args->nblk < MAX_TMP_FILES);
409 blk_t *blk = &args->blk[args->nblk];
410 blk->is_merged = 0;
411 args->nblk++;
412 args->tmp_layers[0]++;
413
414 assert(blk->fname == NULL && blk->fh == NULL && blk->bgz == NULL);
415
416 open_tmp_file(args, blk, 0);
417 int i;
418 for (i=0; i<args->nbuf; i++)
419 {
420 if ( write_packed_bcf(blk->bgz, args->buf[i])!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,blk->fname);
421 }
422
423 if ( bgzf_close(blk->bgz)!=0 ) clean_files_and_throw(args, "[%s] Error: close failed .. %s\n", __func__,blk->fname);
424 blk->bgz = NULL;
425
426 args->nbuf = 0;
427 args->mem = 0;
428 }
429
430
431 static inline uint8_t *_align_up(uint8_t *ptr)
432 {
433 return (uint8_t*)(((size_t)ptr + 8 - 1) & ~((size_t)(8 - 1)));
434 }
435
436 #define varint_size(X) ((sizeof(X) * 8 + 7) / 7) // worst case
437
438 void buf_push(args_t *args, bcf1_t *rec)
439 {
440 size_t delta = sizeof(rec->pos)
441 + sizeof(rec->rid)
442 + sizeof(rec->qual)
443 + varint_size(rec->rlen)
444 + varint_size(2) // n_info
445 + varint_size(2) // n_allele
446 + varint_size(1) // n_fmt
447 + varint_size(3) // n_sample
448 + varint_size(rec->shared.l)
449 + varint_size(rec->indiv.l)
450 + rec->shared.l + rec->indiv.l
451 + rec->unpack_size[1] // Alleles
452 + 8; // the number of _align_up() calls
453
454 if ( delta > args->max_mem - args->mem )
455 {
456 packed_bcf_t *tmp = malloc(sizeof(*tmp) + rec->unpack_size[1] * sizeof(bcf1_t *));
457 if (!tmp)
458 clean_files_and_throw(args, "[%s] Out of memory\n", __func__);
459 pack_bcf_data(tmp, rec, 1);
460
461 args->nbuf++;
462 hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf);
463 args->buf[args->nbuf-1] = tmp;
464
465 buf_flush(args, rec);
466
467 free(tmp);
468 bcf_destroy(rec);
469 return;
470 }
471
472 // make sure nothing has changed in htslib
473 assert( rec->unpacked==BCF_UN_STR && !rec->d.flt && !rec->d.info && !rec->d.fmt && !rec->d.var );
474
475 uint8_t *ptr_beg = args->mem_block + args->mem;
476 uint8_t *ptr = _align_up(ptr_beg);
477 packed_bcf_t *packed_rec = (packed_bcf_t *) ptr;
478
479 ptr = pack_bcf_data(packed_rec, rec, 0);
480
481 args->nbuf++;
482 hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf);
483 args->buf[args->nbuf-1] = packed_rec;
484
485 delta = ptr - ptr_beg;
486 args->mem += delta;
487
488 assert( args->mem <= args->max_mem );
489
490 bcf_destroy(rec);
491 }
492
493 void sort_blocks(args_t *args)
494 {
495 htsFile *in = hts_open(args->fname, "r");
496 if ( !in ) clean_files_and_throw(args, "Could not read %s\n", args->fname);
497 args->hdr = bcf_hdr_read(in);
498 if ( !args->hdr) clean_files_and_throw(args, "Could not read VCF/BCF headers from %s\n", args->fname);
499
500 while ( 1 )
501 {
502 bcf1_t *rec = bcf_init();
503 int ret = bcf_read1(in, args->hdr, rec);
504 if ( ret < -1 ) clean_files_and_throw(args,"Error encountered while parsing the input\n");
505 if ( ret == -1 )
506 {
507 bcf_destroy(rec);
508 break;
509 }
510 if ( rec->errcode ) clean_files_and_throw(args,"Error encountered while parsing the input at %s:%"PRIhts_pos"\n",bcf_seqname(args->hdr,rec),rec->pos+1);
511 bcf_unpack(rec, BCF_UN_STR);
512 buf_push(args, rec);
513 }
514 buf_flush(args, NULL);
515 free(args->buf);
516
517 if ( hts_close(in)!=0 ) clean_files_and_throw(args,"Close failed: %s\n", args->fname);
518 }
519
520 static inline int blk_is_smaller(blk_t **aptr, blk_t **bptr)
521 {
522 blk_t *a = *aptr;
523 blk_t *b = *bptr;
524 int ret = cmp_bcf_pos_ref_alt(&a->rec, &b->rec);
525 if ( ret < 0 ) return 1;
526 if (ret == 0 && a->idx < b->idx) return 1;
527 return 0;
528 }
529 KHEAP_INIT(blk, blk_t*, blk_is_smaller)
530
531 void blk_read(args_t *args, khp_blk_t *bhp, bcf_hdr_t *hdr, blk_t *blk)
532 {
533 int ret;
534 if (blk->is_merged)
535 {
536 if ( !blk->fh ) return;
537 ret = bcf_read(blk->fh, hdr, blk->rec);
538 }
539 else
540 {
541 if ( !blk->bgz ) return;
542 ret = read_packed_bcf(blk->bgz, blk->rec);
543 }
544 if ( ret < -1 ) clean_files_and_throw(args, "Error reading %s\n", blk->fname);
545 if ( ret == -1 )
546 {
547 if (blk->is_merged)
548 {
549 if ( hts_close(blk->fh)!=0 ) clean_files_and_throw(args, "Close failed: %s\n", blk->fname);
550 blk->fh = NULL;
551 return;
552 }
553 else
554 {
555 if ( bgzf_close(blk->bgz) != 0)
556 clean_files_and_throw(args, "Close failed: %s\n", blk->fname);
557 blk->bgz = NULL;
558 return;
559 }
560 }
561 bcf_unpack(blk->rec, BCF_UN_STR);
562 khp_insert(blk, bhp, &blk);
563 }
564
565 void merge_blocks(args_t *args, htsFile *out, const char *output_fname,
566 int idx_fmt, size_t from)
567 {
568 khp_blk_t *bhp = khp_init(blk);
569 char *index_fn = NULL;
570 size_t i;
571
572 for (i=from; i<args->nblk; i++)
573 {
574 blk_t *blk = &args->blk[i];
575 if (blk->is_merged)
576 {
577 blk->fh = hts_open(blk->fname, "r");
578 if ( !blk->fh ) clean_files_and_throw(args, "Could not read %s: %s\n", blk->fname, strerror(errno));
579 bcf_hdr_t *hdr = bcf_hdr_read(blk->fh);
580 bcf_hdr_destroy(hdr);
581 }
582 else
583 {
584 blk->bgz = bgzf_open(blk->fname, "r");
585 if (!blk->bgz)
586 clean_files_and_throw(args, "Could not read %s: %s\n", blk->fname, strerror(errno));
587 }
588 blk_read(args, bhp, args->hdr, blk);
589 }
590
591 if ( bcf_hdr_write(out, args->hdr)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__, output_fname);
592
593 if (idx_fmt) {
594 if ( init_index2(out,args->hdr,output_fname,&index_fn,idx_fmt)<0 )
595 error("Error: failed to initialise index for %s\n",output_fname);
596 }
597
598 while ( bhp->ndat )
599 {
600 blk_t *blk = bhp->dat[0];
601 if ( bcf_write(out, args->hdr, blk->rec)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,args->output_fname);
602 khp_delete(blk, bhp);
603 blk_read(args, bhp, args->hdr, blk);
604 }
605 if ( idx_fmt )
606 {
607 if ( bcf_idx_save(out)<0 )
608 {
609 if ( hts_close(out)!=0 ) error("Error: close failed .. %s\n", output_fname);
610 error("Error: cannot write to index %s\n", index_fn);
611 }
612 free(index_fn);
613 }
614
615 for (i = from; i < args->nblk; i++)
616 {
617 blk_t *blk = &args->blk[i];
618 if (unlink(blk->fname) != 0)
619 clean_files_and_throw(args, "Couldn't remove temporary file %s\n", blk->fname);
620 free(blk->fname);
621 blk->fname = NULL;
622 }
623
624 khp_destroy(blk, bhp);
625 }
626
627 void do_partial_merge(args_t *args)
628 {
629 uint32_t to_layer = 0;
630 size_t to_merge = 0;
631
632 // Temp. files are arranged in layers of at most MAX_TMP_FILES_PER_LAYER.
633 // When a layer is full, it is merged into the next layer up. Each
634 // layer will therefore contain files with exponentially more records
635 // then the previous one, but will be merged exponentially less frequently.
636 // The result is that the overall complexity will remain O(n*log(n))
637 // even if we need to do lots of partial merges.
638
639 while (to_layer < MERGE_LAYERS
640 && args->tmp_layers[to_layer] >= MAX_TMP_FILES_PER_LAYER)
641 {
642 to_merge += args->tmp_layers[to_layer];
643 args->tmp_layers[to_layer] = 0;
644 to_layer++;
645 }
646
647 assert(to_merge > 0 && to_merge <= args->nblk);
648
649 if (to_layer == MERGE_LAYERS) {
650 // Edge case - if we've got here, we've completely used the
651 // temp file allocation, so merge absolutely everything and
652 // leave one file at the highest level. Strictly this breaks
653 // the O(n*log(n)) complexity, but unless MERGE_LAYERS and
654 // MAX_TMP_FILES_PER_LAYER are too small it would take so long
655 // to get here it should never actually happen...
656 assert(to_merge == MAX_TMP_FILES_PER_LAYER * MERGE_LAYERS);
657 to_layer = MERGE_LAYERS - 1;
658 }
659
660 blk_t tmp = { NULL };
661 open_tmp_file(args, &tmp, 1);
662 merge_blocks(args, tmp.fh, tmp.fname, 0, args->nblk - to_merge);
663 if (hts_close(tmp.fh) != 0)
664 clean_files_and_throw(args, "Close failed: %s\n", tmp.fname);
665
666 args->nblk -= to_merge;
667 assert(args->blk[args->nblk].fh == NULL);
668 assert(args->blk[args->nblk].fname == NULL);
669 args->blk[args->nblk].is_merged = 1;
670 args->blk[args->nblk].idx = tmp.idx;
671 args->blk[args->nblk++].fname = tmp.fname;
672 args->tmp_layers[to_layer]++;
673 }
674
675 void merge_to_output(args_t *args)
676 {
677 char wmode[8] = { 0 };
678 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
679 const char *output_fname = args->output_fname ? args->output_fname : "-";
680
681 htsFile *out = hts_open(output_fname, wmode);
682 if (!out) clean_files_and_throw(args, "[%s] Error: cannot open %s\n", __func__, output_fname);
683
684 fprintf(stderr,"Merging %zd temporary files\n", args->nblk);
685 merge_blocks(args, out, output_fname, args->write_index, 0);
686 fprintf(stderr,"Done\n");
687
688 if ( hts_close(out)!=0 )
689 clean_files_and_throw(args, "Close failed: %s\n", output_fname);
690
691 clean_files(args);
692 }
693
694 static void usage(args_t *args)
695 {
696 fprintf(stderr, "\n");
697 fprintf(stderr, "About: Sort VCF/BCF file.\n");
698 fprintf(stderr, "Usage: bcftools sort [OPTIONS] <FILE.vcf>\n");
699 fprintf(stderr, "\n");
700 fprintf(stderr, "Options:\n");
701 fprintf(stderr, " -m, --max-mem FLOAT[kMG] maximum memory to use [768M]\n"); // using metric units, 1M=1e6
702 fprintf(stderr, " -o, --output FILE output file name [stdout]\n");
703 fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
704
705 #ifdef _WIN32
706 fprintf(stderr, " -T, --temp-dir DIR temporary files [/bcftools.XXXXXX]\n");
707 #else
708 fprintf(stderr, " -T, --temp-dir DIR temporary files [/tmp/bcftools.XXXXXX]\n");
709 #endif
710 fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
711 fprintf(stderr, "\n");
712 exit(1);
713 }
714
715 size_t parse_mem_string(const char *str)
716 {
717 char *tmp;
718 double mem = strtod(str, &tmp);
719 if ( tmp==str ) error("Could not parse the memory string: \"%s\"\n", str);
720 if ( !strcasecmp("k",tmp) ) mem *= 1000;
721 else if ( !strcasecmp("m",tmp) ) mem *= 1000*1000;
722 else if ( !strcasecmp("g",tmp) ) mem *= 1000*1000*1000;
723 return mem;
724 }
725
726 static void init(args_t *args)
727 {
728 size_t i;
729 args->max_mem *= 0.9;
730 args->mem_block = malloc(args->max_mem);
731 if ( !args->mem_block ) error("Error: could not allocate %zu bytes of memory, try reducing --max-mem\n",args->max_mem);
732 args->mem = 0;
733
734 for (i = 0; i < MAX_TMP_FILES; i++)
735 {
736 args->blk[i].fname = NULL;
737 args->blk[i].rec = bcf_init();
738 if (!args->blk[i].rec)
739 clean_files_and_throw(args,"Couldn't allocate bcf record\n");
740 }
741
742
743 args->tmp_dir = init_tmp_prefix(args->tmp_dir);
744
745 #ifdef _WIN32
746 int ret = mkdir(mktemp(args->tmp_dir), 0700);
747 if ( ret ) error("mkdir(%s) failed: %s\n", args->tmp_dir,strerror(errno));
748 #else
749 char *tmp = mkdtemp(args->tmp_dir);
750 if ( !tmp ) error("mkdtemp(%s) failed: %s\n", args->tmp_dir,strerror(errno));
751 int ret = chmod(tmp, S_IRUSR|S_IWUSR|S_IXUSR);
752 if ( ret ) error("chmod(%s,S_IRUSR|S_IWUSR|S_IXUSR) failed: %s\n", args->tmp_dir,strerror(errno));
753 #endif
754
755 fprintf(stderr,"Writing to %s\n", args->tmp_dir);
756 }
757 static void destroy(args_t *args)
758 {
759 bcf_hdr_destroy(args->hdr);
760 free(args->mem_block);
761 free(args->tmp_dir);
762 free(args);
763 }
764
765 int main_sort(int argc, char *argv[])
766 {
767 int c;
768 args_t *args = (args_t*) calloc(1,sizeof(args_t));
769 args->argc = argc; args->argv = argv;
770 args->max_mem = 768*1000*1000;
771 args->output_fname = "-";
772 args->clevel = -1;
773
774 static struct option loptions[] =
775 {
776 {"max-mem",required_argument,NULL,'m'},
777 {"temp-dir",required_argument,NULL,'T'},
778 {"output-type",required_argument,NULL,'O'},
779 {"output-file",required_argument,NULL,'o'},
780 {"output",required_argument,NULL,'o'},
781 {"help",no_argument,NULL,'h'},
782 {"write-index",optional_argument,NULL,'W'},
783 {0,0,0,0}
784 };
785 char *tmp;
786 while ((c = getopt_long(argc, argv, "m:T:O:o:W::h?",loptions,NULL)) >= 0)
787 {
788 switch (c)
789 {
790 case 'm': args->max_mem = parse_mem_string(optarg); break;
791 case 'T': args->tmp_dir = optarg; break;
792 case 'o': args->output_fname = optarg; break;
793 case 'O':
794 switch (optarg[0]) {
795 case 'b': args->output_type = FT_BCF_GZ; break;
796 case 'u': args->output_type = FT_BCF; break;
797 case 'z': args->output_type = FT_VCF_GZ; break;
798 case 'v': args->output_type = FT_VCF; break;
799 default:
800 {
801 args->clevel = strtol(optarg,&tmp,10);
802 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
803 }
804 };
805 if ( optarg[1] )
806 {
807 args->clevel = strtol(optarg+1,&tmp,10);
808 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
809 }
810 break;
811 case 'W':
812 if (!(args->write_index = write_index_parse(optarg)))
813 error("Unsupported index format '%s'\n", optarg);
814 break;
815 case 'h':
816 case '?': usage(args); break;
817 default: error("Unknown argument: %s\n", optarg);
818 }
819 }
820
821 if ( optind>=argc )
822 {
823 if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-"; // reading from stdin
824 else usage(args);
825 }
826 else args->fname = argv[optind];
827
828 init(args);
829 sort_blocks(args);
830 merge_to_output(args);
831 destroy(args);
832
833 return 0;
834 }