Debian Codegraph @

bcftools/vcfsort.c.pysam.c

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