Debian Codegraph @

samtools/bam_sort.c

raw symbols SCIP
1 /* bam_sort.c -- sorting and merging.
2
3 Copyright (C) 2008-2024 Genome Research Ltd.
4 Portions copyright (C) 2009-2012 Broad Institute.
5
6 Author: Heng Li <[email protected]>
7 Author: Martin Pollard <[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
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE. */
26
27 #include <config.h>
28
29 #include <stdbool.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <time.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #include <getopt.h>
40 #include <assert.h>
41 #include <pthread.h>
42 #include <inttypes.h>
43 #include "htslib/ksort.h"
44 #include "htslib/hts_os.h"
45 #include "htslib/khash.h"
46 #include "htslib/klist.h"
47 #include "htslib/kstring.h"
48 #include "htslib/sam.h"
49 #include "htslib/hts_endian.h"
50 #include "htslib/cram.h"
51 #include "htslib/thread_pool.h"
52 #include "sam_opts.h"
53 #include "samtools.h"
54 #include "bedidx.h"
55 #include "bam.h"
56
57 //#define DEBUG_MINHASH
58
59 #define BAM_BLOCK_SIZE 2*1024*1024
60 #define MAX_TMP_FILES 64
61
62 // Struct which contains the sorting key for TemplateCoordinate sort.
63 typedef struct {
64 int tid1;
65 int tid2;
66 hts_pos_t pos1;
67 hts_pos_t pos2;
68 bool neg1;
69 bool neg2;
70 const char *library;
71 char *mid;
72 char *name;
73 bool is_upper_of_pair;
74 } template_coordinate_key_t;
75
76 // Struct to store fixed buffers of template coordinate keys
77 typedef struct {
78 size_t n; // the # of keys stored
79 size_t m; // the # of buffers allocated
80 size_t buffer_size; // # the fixed size of each buffer
81 template_coordinate_key_t **buffers; // the list of buffers
82 } template_coordinate_keys_t;
83
84 // Gets the idx'th key; does not OOB check
85 static template_coordinate_key_t* template_coordinate_keys_get(template_coordinate_keys_t *keys, size_t idx) {
86 size_t buffer_idx = idx / keys->buffer_size; // the index of the buffer to retrieve in buffer
87 size_t buffer_offset = idx % keys->buffer_size; // the offset into the given buffer to retrieve
88 //assert(buffer_idx < keys->m);
89 //assert(buffer_offset < keys->buffer_size);
90 return &keys->buffers[buffer_idx][buffer_offset];
91 }
92
93 // Rellocates the buffers to hold at least max_k entries
94 static int template_coordinate_keys_realloc(template_coordinate_keys_t *keys, int max_k) {
95 size_t cur_m = keys->m;
96 keys->m += 0x100;
97 //assert(keys->m > cur_m);
98 //assert(keys->m * keys->buffer_size >= max_k);
99 if ((keys->buffers = realloc(keys->buffers, keys->m * sizeof(template_coordinate_key_t*))) == NULL) {
100 print_error("sort", "couldn't reallocate memory for template coordinate key buffers");
101 return -1;
102 }
103 // allocate space for new buffers
104 int j;
105 for (j = cur_m; j < keys->m; ++j) {
106 if ((keys->buffers[j]= malloc(sizeof(template_coordinate_key_t) * keys->buffer_size)) == NULL) {
107 print_error("sort", "couldn't allocate memory for template coordinate key buffer");
108 return -1;
109 }
110 }
111 return 0;
112 }
113
114
115 // Struct which contains the a record, and the pointer to the sort tag (if any) or
116 // a combined ref / position / strand.
117 // Used to speed up sorts (coordinate, by-tag, and template-coordinate).
118 typedef struct bam1_tag {
119 bam1_t *bam_record;
120 union {
121 const uint8_t *tag;
122 uint8_t pos_tid[12];
123 template_coordinate_key_t *key;
124 } u;
125 } bam1_tag;
126
127 /* Minimum memory required in megabytes before sort will attempt to run. This
128 is to prevent accidents where failing to use the -m option correctly results
129 in the creation of a temporary file for each read in the input file.
130 Don't forget to update the man page if you change this. */
131 const size_t SORT_MIN_MEGS_PER_THREAD = 1;
132
133 /* Default per-thread memory for sort. Must be >= SORT_MIN_MEGS_PER_THREAD.
134 Don't forget to update the man page if you change this. */
135 const size_t SORT_DEFAULT_MEGS_PER_THREAD = 768;
136
137 #if !defined(__DARWIN_C_LEVEL) || __DARWIN_C_LEVEL < 900000L
138 #define NEED_MEMSET_PATTERN4
139 #endif
140
141 #ifdef NEED_MEMSET_PATTERN4
142 void memset_pattern4(void *target, const void *pattern, size_t size) {
143 uint32_t* target_iter = target;
144 size_t loops = size/4;
145 size_t i;
146 for (i = 0; i < loops; ++i) {
147 memcpy(target_iter, pattern, 4);
148 ++target_iter;
149 }
150 if (size%4 != 0)
151 memcpy(target_iter, pattern, size%4);
152 }
153 #endif
154
155 KHASH_INIT(c2c, char*, char*, 1, kh_str_hash_func, kh_str_hash_equal)
156 KHASH_INIT(cset, char*, char, 0, kh_str_hash_func, kh_str_hash_equal)
157 KHASH_MAP_INIT_STR(c2i, int)
158 KHASH_MAP_INIT_STR(const_c2c, char *)
159
160 #define hdrln_free_char(p)
161 KLIST_INIT(hdrln, char*, hdrln_free_char)
162
163 static template_coordinate_key_t* template_coordinate_key(bam1_t *b, template_coordinate_key_t *key, sam_hdr_t *hdr, khash_t(const_c2c) *lib_lookup);
164
165 typedef enum {Coordinate, QueryName, TagCoordinate, TagQueryName, MinHash, TemplateCoordinate} SamOrder;
166 static SamOrder g_sam_order = Coordinate;
167 static int natural_sort = 1; // not ASCII, but alphanumeric: a12b > a7b
168 static char g_sort_tag[2] = {0,0};
169
170 #define is_digit(c) ((c)<='9' && (c)>='0')
171 static int strnum_cmp(const char *_a, const char *_b)
172 {
173 if (!natural_sort)
174 return strcmp(_a,_b);
175
176 const unsigned char *a = (const unsigned char*)_a, *b = (const unsigned char*)_b;
177 const unsigned char *pa = a, *pb = b;
178 while (*pa && *pb) {
179 if (!is_digit(*pa) || !is_digit(*pb)) {
180 if (*pa != *pb)
181 return (int)*pa - (int)*pb;
182 ++pa; ++pb;
183 } else {
184 // skip leading zeros
185 while (*pa == '0') ++pa;
186 while (*pb == '0') ++pb;
187
188 // skip matching digits
189 while (is_digit(*pa) && *pa == *pb)
190 pa++, pb++;
191
192 // Now mismatching, so see which ends the number sooner
193 int diff = (int)*pa - (int)*pb;
194 while (is_digit(*pa) && is_digit(*pb))
195 pa++, pb++;
196
197 if (is_digit(*pa))
198 return 1; // pa still going, so larger
199 else if (is_digit(*pb))
200 return -1; // pb still going, so larger
201 else if (diff)
202 return diff; // same length, so earlier diff
203 }
204 }
205 return *pa? 1 : *pb? -1 : 0;
206 }
207
208 #define HEAP_EMPTY (UINT64_MAX >> 1)
209
210 typedef struct {
211 int i;
212 uint32_t tid;
213 uint64_t pos:63, rev:1, idx;
214 bam1_tag entry;
215 } heap1_t;
216
217 static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b);
218 static inline int bam1_cmp_by_minhash(const bam1_tag a, const bam1_tag b);
219 static inline int bam1_cmp_template_coordinate(const bam1_tag a, const bam1_tag b);
220 static khash_t(const_c2c) * lookup_libraries(sam_hdr_t *header);
221 static void lib_lookup_destroy(khash_t(const_c2c) *lib_lookup);
222
223 // Function to compare reads in the heap and determine which one is < the other
224 // Note, unlike the bam1_cmp_by_X functions which return <0, 0, >0 this
225 // is strictly 0 or 1 only.
226 static inline int heap_lt(const heap1_t a, const heap1_t b)
227 {
228 if (!a.entry.bam_record)
229 return 1;
230 if (!b.entry.bam_record)
231 return 0;
232
233 int t, fa, fb;
234 switch (g_sam_order) {
235 case Coordinate:
236 if (a.tid != b.tid) return a.tid > b.tid;
237 if (a.pos != b.pos) return a.pos > b.pos;
238 if (a.rev != b.rev) return a.rev > b.rev;
239 break;
240 case QueryName:
241 t = strnum_cmp(bam_get_qname(a.entry.bam_record), bam_get_qname(b.entry.bam_record));
242 if (t != 0) return t > 0;
243 fa = a.entry.bam_record->core.flag;
244 fb = b.entry.bam_record->core.flag;
245 // Sort order is READ1, READ2, (PRIMARY), SUPPLEMENTARY, SECONDARY
246 // Get the bits in this order so sort is a natural a-b
247 fa = ((fa&0xc0)<<8)|((fa&0x100)<<3)|((fa&0x800)>>3);
248 fb = ((fb&0xc0)<<8)|((fb&0x100)<<3)|((fb&0x800)>>3);
249 if (fa != fb) return fa > fb;
250 break;
251 case TagQueryName:
252 case TagCoordinate:
253 t = bam1_cmp_by_tag(a.entry, b.entry);
254 if (t != 0) return t > 0;
255 break;
256 case MinHash:
257 t = bam1_cmp_by_minhash(a.entry, b.entry);
258 if (t != 0) return t > 0;
259 break;
260 case TemplateCoordinate:
261 t = bam1_cmp_template_coordinate(a.entry, b.entry);
262 if (t != 0) return t > 0;
263 break;
264 default:
265 print_error("heap_lt", "unknown sort order: %d", g_sam_order);
266 break;
267 }
268
269 // This compares by position (i/idx'th read) in the input file(s)
270 if (a.i != b.i) return a.i > b.i;
271 return a.idx > b.idx;
272 }
273
274 KSORT_INIT(heap, heap1_t, heap_lt)
275
276 typedef struct merged_header {
277 sam_hdr_t *hdr;
278 kstring_t out_rg;
279 kstring_t out_pg;
280 kstring_t out_co;
281 char **target_name;
282 uint32_t *target_len;
283 size_t n_targets;
284 size_t targets_sz;
285 khash_t(c2i) *sq_tids;
286 khash_t(cset) *rg_ids;
287 khash_t(cset) *pg_ids;
288 bool have_hd;
289 } merged_header_t;
290
291 typedef struct trans_tbl {
292 int32_t n_targets;
293 int* tid_trans;
294 kh_c2c_t* rg_trans;
295 kh_c2c_t* pg_trans;
296 bool lost_coord_sort;
297 } trans_tbl_t;
298
299 static void trans_tbl_destroy(trans_tbl_t *tbl) {
300 khiter_t iter;
301
302 free(tbl->tid_trans);
303
304 /*
305 * The values for the tbl->rg_trans and tbl->pg_trans hashes are pointers
306 * to keys in the rg_ids and pg_ids sets of the merged_header_t, so
307 * they should not be freed here.
308 *
309 * The keys are unique to each hash entry, so they do have to go.
310 */
311
312 for (iter = kh_begin(tbl->rg_trans); iter != kh_end(tbl->rg_trans); ++iter) {
313 if (kh_exist(tbl->rg_trans, iter)) {
314 free(kh_key(tbl->rg_trans, iter));
315 }
316 }
317 for (iter = kh_begin(tbl->pg_trans); iter != kh_end(tbl->pg_trans); ++iter) {
318 if (kh_exist(tbl->pg_trans, iter)) {
319 free(kh_key(tbl->pg_trans, iter));
320 }
321 }
322
323 kh_destroy(c2c,tbl->rg_trans);
324 kh_destroy(c2c,tbl->pg_trans);
325 }
326
327 /*
328 * Create a merged_header_t struct.
329 */
330
331 static merged_header_t * init_merged_header(void) {
332 merged_header_t *merged_hdr;
333
334 merged_hdr = calloc(1, sizeof(*merged_hdr));
335 if (merged_hdr == NULL) return NULL;
336
337 merged_hdr->hdr = sam_hdr_init();
338 if (!merged_hdr->hdr) goto fail;
339
340 merged_hdr->targets_sz = 16;
341 merged_hdr->target_name = malloc(merged_hdr->targets_sz
342 * sizeof(*merged_hdr->target_name));
343 if (NULL == merged_hdr->target_name) goto fail;
344
345 merged_hdr->target_len = malloc(merged_hdr->targets_sz
346 * sizeof(*merged_hdr->target_len));
347 if (NULL == merged_hdr->target_len) goto fail;
348
349 merged_hdr->sq_tids = kh_init(c2i);
350 if (merged_hdr->sq_tids == NULL) goto fail;
351
352 merged_hdr->rg_ids = kh_init(cset);
353 if (merged_hdr->rg_ids == NULL) goto fail;
354
355 merged_hdr->pg_ids = kh_init(cset);
356 if (merged_hdr->pg_ids == NULL) goto fail;
357
358 return merged_hdr;
359
360 fail:
361 perror("[init_merged_header]");
362 kh_destroy(cset, merged_hdr->pg_ids);
363 kh_destroy(cset, merged_hdr->rg_ids);
364 kh_destroy(c2i, merged_hdr->sq_tids);
365 free(merged_hdr->target_name);
366 free(merged_hdr->target_len);
367 sam_hdr_destroy(merged_hdr->hdr);
368 free(merged_hdr);
369 return NULL;
370 }
371
372 /* Some handy kstring manipulating functions */
373
374 // Append char range to kstring
375 static inline int range_to_ks(const char *src, int from, int to,
376 kstring_t *dest) {
377 return kputsn(src + from, to - from, dest) != to - from;
378 }
379
380 // Append a kstring to a kstring
381 static inline int ks_to_ks(kstring_t *src, kstring_t *dest) {
382 return kputsn(ks_str(src), ks_len(src), dest) != ks_len(src);
383 }
384
385 /*
386 * Generate a unique ID by appending a random suffix to a given prefix.
387 * existing_ids is the set of IDs that are already in use.
388 * If always_add_suffix is true, the suffix will always be included.
389 * If false, prefix will be returned unchanged if it isn't in existing_ids.
390 */
391
392 static int gen_unique_id(char *prefix, khash_t(cset) *existing_ids,
393 bool always_add_suffix, kstring_t *dest) {
394 khiter_t iter;
395
396 if (!always_add_suffix) {
397 // Try prefix on its own first
398 iter = kh_get(cset, existing_ids, prefix);
399 if (iter == kh_end(existing_ids)) { // prefix isn't used yet
400 dest->l = 0;
401 if (kputs(prefix, dest) == EOF) return -1;
402 return 0;
403 }
404 }
405
406 do {
407 dest->l = 0;
408 ksprintf(dest, "%s-%08lX", prefix, lrand48());
409 iter = kh_get(cset, existing_ids, ks_str(dest));
410 } while (iter != kh_end(existing_ids));
411
412 return 0;
413 }
414
415 /*
416 * Add the @HD line to the new header
417 * In practice the @HD line will come from the first input header.
418 */
419
420 static int trans_tbl_add_hd(merged_header_t* merged_hdr,
421 sam_hdr_t *translate) {
422 kstring_t hd_line = { 0, 0, NULL };
423 int res;
424
425 // TODO: handle case when @HD needs merging.
426 if (merged_hdr->have_hd) return 0;
427
428 res = sam_hdr_find_hd(translate, &hd_line);
429 if (res < -1) {
430 print_error("merge", "failed to get @HD line from header");
431 return -1;
432 }
433
434 if (res < 0) // Not found
435 return 0;
436
437 if (sam_hdr_add_lines(merged_hdr->hdr, hd_line.s, hd_line.l) < 0) {
438 print_error("merge", "failed to add @HD line to new header");
439 free(hd_line.s);
440 return -1;
441 }
442
443 free(hd_line.s);
444 merged_hdr->have_hd = true;
445
446 return 0;
447 }
448
449 /*
450 * Add @SQ records to the translation table.
451 *
452 * Go through the target list for the input header. Any new targets found
453 * are added to the output header target list. At the same time, a mapping
454 * from the input to output target ids is stored in tbl.
455 *
456 * If any new targets are found, the header text is scanned to find the
457 * corresponding @SQ records. They are then copied into the
458 * merged_hdr->out_text kstring (which will eventually become the
459 * output header text).
460 *
461 * Returns 0 on success, -1 on failure.
462 */
463
464 static int trans_tbl_add_sq(merged_header_t* merged_hdr, sam_hdr_t *translate,
465 trans_tbl_t* tbl) {
466 int32_t i;
467 int min_tid = -1, res;
468 kstring_t sq_line = { 0, 0, NULL }, sq_sn = { 0, 0, NULL };
469
470 // Fill in the tid part of the translation table, adding new targets
471 // to the merged header as we go.
472
473 for (i = 0; i < sam_hdr_nref(translate); ++i) {
474 int trans_tid;
475 sq_sn.l = 0;
476 res = sam_hdr_find_tag_pos(translate, "SQ", i, "SN", &sq_sn);
477 if (res < 0) {
478 print_error("merge", "failed to get @SQ SN #%d from header", i + 1);
479 goto fail;
480 }
481
482 trans_tid = sam_hdr_name2tid(merged_hdr->hdr, sq_sn.s);
483 if (trans_tid < -1) {
484 print_error("merge", "failed to lookup ref");
485 goto fail;
486 }
487
488 if (trans_tid < 0) {
489 // Append missing entries to out_hdr
490 sq_line.l = 0;
491 res = sam_hdr_find_line_id(translate, "SQ", "SN", sq_sn.s, &sq_line);
492 if (res < 0) {
493 print_error("merge", "failed to get @SQ SN:%s from header", sq_sn.s);
494 goto fail;
495 }
496
497 trans_tid = sam_hdr_nref(merged_hdr->hdr);
498
499 res = sam_hdr_add_lines(merged_hdr->hdr, sq_line.s, sq_line.l);
500 if (res < 0) {
501 print_error("merge", "failed to add @SQ SN:%s to new header", sq_sn.s);
502 goto fail;
503 }
504 }
505 tbl->tid_trans[i] = trans_tid;
506
507 if (tbl->tid_trans[i] > min_tid) {
508 min_tid = tbl->tid_trans[i];
509 } else {
510 tbl->lost_coord_sort = true;
511 }
512 }
513
514 free(sq_line.s);
515 free(sq_sn.s);
516
517 return 0;
518
519 fail:
520 free(sq_line.s);
521 free(sq_sn.s);
522 return -1;
523 }
524
525 /*
526 * Common code for setting up RG and PG record ID tag translation.
527 *
528 * is_rg is true for RG translation, false for PG.
529 * translate is the input bam header
530 * merge is true if tags with the same ID are to be merged.
531 * known_ids is the set of IDs already in the output header.
532 * id_map is the translation map from input header IDs to output header IDs
533 * If override is set, it will be used to replace the existing ID (RG only)
534 *
535 * known_ids and id_map have entries for the new IDs added to them.
536 *
537 * Return value is a linked list of header lines with the translated IDs,
538 * or NULL if something went wrong (probably out of memory).
539 *
540 */
541
542 static klist_t(hdrln) * trans_rg_pg(bool is_rg, sam_hdr_t *translate,
543 bool merge, khash_t(cset)* known_ids,
544 khash_t(c2c)* id_map, char *override) {
545 khiter_t iter;
546 int num_ids, i;
547 const char *rec_type = is_rg ? "RG" : "PG";
548 klist_t(hdrln) *hdr_lines;
549
550 hdr_lines = kl_init(hdrln);
551
552 // Search through translate's header
553 num_ids = sam_hdr_count_lines(translate, rec_type);
554 if (num_ids < 0)
555 goto fail;
556
557 for (i = 0; i < num_ids; i++) {
558 kstring_t orig_id = { 0, 0, NULL }; // ID in original header
559 kstring_t transformed_id = { 0, 0, NULL }; // ID in output header
560 char *map_value; // Value to store in id_map
561 bool id_changed; // Have we changed the ID?
562 bool not_found_in_output; // ID isn't in the output header (yet)
563
564 if (sam_hdr_find_tag_pos(translate, rec_type, i, "ID", &orig_id) < 0)
565 goto fail;
566
567 // is our matched ID in our output ID set already?
568 iter = kh_get(cset, known_ids, ks_str(&orig_id));
569 not_found_in_output = (iter == kh_end(known_ids));
570
571 if (override) {
572 // Override original ID (RG only)
573 #ifdef OVERRIDE_DOES_NOT_MERGE
574 if (gen_unique_id(override, known_ids, false, &transformed_id))
575 goto memfail;
576 not_found_in_output = true; // As ID now unique
577 #else
578 if (kputs(override, &transformed_id) == EOF) goto memfail;
579 // Know about override already?
580 iter = kh_get(cset, known_ids, ks_str(&transformed_id));
581 not_found_in_output = (iter == kh_end(known_ids));
582 #endif
583 id_changed = true;
584 } else {
585 if ( not_found_in_output || merge) {
586 // Not in there or merging so can add it as 1-1 mapping
587 if (ks_to_ks(&orig_id, &transformed_id)) goto memfail;
588 id_changed = false;
589 } else {
590 // It's in there so we need to transform it by appending
591 // a random number to the id
592 if (gen_unique_id(ks_str(&orig_id), known_ids,
593 true, &transformed_id))
594 goto memfail;
595 id_changed = true;
596 not_found_in_output = true; // As ID now unique
597 }
598 }
599
600 // Does this line need to go into our output header?
601 if (not_found_in_output) {
602 // Take matched line and replace ID with transformed_id
603 kstring_t new_hdr_line = { 0, 0, NULL };
604 if (sam_hdr_find_line_id(translate, rec_type,
605 "ID", ks_str(&orig_id), &new_hdr_line) < 0){
606 goto fail;
607 }
608
609 if (id_changed) {
610 char *idp = strstr(ks_str(&new_hdr_line), "\tID:"), *id_end;
611 ptrdiff_t id_offset, id_len;
612 if (!idp) {
613 print_error("merge", "failed to find ID in \"%s\"\n",
614 ks_str(&new_hdr_line));
615 goto fail;
616 }
617 idp += 4;
618 for (id_end = idp; *id_end >= '\n'; id_end++) {}
619
620 id_offset = idp - new_hdr_line.s;
621 id_len = id_end - idp;
622
623 if (id_len < transformed_id.l) {
624 if (ks_resize(&new_hdr_line, new_hdr_line.l
625 + transformed_id.l - id_len + 1/*nul*/))
626 goto fail;
627 }
628 if (id_len != transformed_id.l) {
629 memmove(new_hdr_line.s + id_offset + transformed_id.l,
630 new_hdr_line.s + id_offset + id_len,
631 new_hdr_line.l - id_offset - id_len + 1);
632 }
633 memcpy(new_hdr_line.s + id_offset, transformed_id.s,
634 transformed_id.l);
635 }
636
637 // append line to output linked list
638 char** ln = kl_pushp(hdrln, hdr_lines);
639 *ln = ks_release(&new_hdr_line); // Give away to linked list
640
641 // Need to add it to known_ids set
642 int in_there = 0;
643 iter = kh_put(cset, known_ids, ks_str(&transformed_id), &in_there);
644 if (in_there < 0) goto memfail;
645 assert(in_there > 0); // Should not already be in the map
646 map_value = ks_release(&transformed_id);
647 } else {
648 // Use existing string in id_map
649 assert(kh_exist(known_ids, iter));
650 map_value = kh_key(known_ids, iter);
651 free(ks_release(&transformed_id));
652 }
653
654 // Insert it into our translation map
655 int in_there = 0;
656 iter = kh_put(c2c, id_map, ks_release(&orig_id), &in_there);
657 kh_value(id_map, iter) = map_value;
658 }
659
660 // If there are no RG lines in the file and we are overriding add one
661 if (is_rg && override && hdr_lines->size == 0) {
662 kstring_t new_id = {0, 0, NULL};
663 kstring_t line = {0, 0, NULL};
664 kstring_t empty = {0, 0, NULL};
665 int in_there = 0;
666 char** ln;
667
668 // Get the new ID
669 if (gen_unique_id(override, known_ids, false, &new_id))
670 goto memfail;
671
672 // Make into a header line and add to linked list
673 ksprintf(&line, "@RG\tID:%s", ks_str(&new_id));
674 ln = kl_pushp(hdrln, hdr_lines);
675 *ln = ks_release(&line);
676
677 // Put into known_ids set
678 iter = kh_put(cset, known_ids, ks_str(&new_id), &in_there);
679 if (in_there < 0) goto memfail;
680 assert(in_there > 0); // Should be a new entry
681
682 // Put into translation map (key is empty string)
683 if (kputs("", &empty) == EOF) goto memfail;
684 iter = kh_put(c2c, id_map, ks_release(&empty), &in_there);
685 if (in_there < 0) goto memfail;
686 assert(in_there > 0); // Should be a new entry
687 kh_value(id_map, iter) = ks_release(&new_id);
688 }
689
690 return hdr_lines;
691
692 memfail:
693 perror(__func__);
694 fail:
695 if (hdr_lines) kl_destroy(hdrln, hdr_lines);
696 return NULL;
697 }
698
699 /*
700 * Common code for completing RG and PG record translation.
701 *
702 * Input is a list of header lines, and the mapping from input to
703 * output @PG record IDs.
704 *
705 * RG and PG records can contain tags that cross-reference to other @PG
706 * records. This fixes the tags to contain the new IDs before adding
707 * them to the output header text.
708 */
709
710 static int finish_rg_pg(bool is_rg, klist_t(hdrln) *hdr_lines,
711 khash_t(c2c)* pg_map, kstring_t *out_text) {
712 const char *search = is_rg ? "\tPG:" : "\tPP:";
713 khiter_t idx;
714 char *line = NULL;
715
716 while ((kl_shift(hdrln, hdr_lines, &line)) == 0) {
717 char *id = strstr(line, search); // Look for tag to fix
718 int pos1 = 0, pos2 = 0;
719 char *new_id = NULL;
720
721 if (id) {
722 // Found a tag. Look up the value in the translation map
723 // to see what it should be changed to in the output file.
724 char *end, tmp;
725
726 id += 4; // Point to value
727 end = strchr(id, '\t'); // Find end of tag
728 if (!end) end = id + strlen(id);
729
730 tmp = *end;
731 *end = '\0'; // Temporarily get the value on its own.
732
733 // Look-up in translation table
734 idx = kh_get(c2c, pg_map, id);
735 if (idx == kh_end(pg_map)) {
736 // Not found, warn.
737 fprintf(stderr, "[W::%s] Tag %s%s not found in @PG records\n",
738 __func__, search + 1, id);
739 } else {
740 // Remember new id and splice points on original string
741 new_id = kh_value(pg_map, idx);
742 pos1 = id - line;
743 pos2 = end - line;
744 }
745
746 *end = tmp; // Restore string
747 }
748
749 // Copy line to output:
750 // line[0..pos1), new_id (if not NULL), line[pos2..end), '\n'
751
752 if (pos1 && range_to_ks(line, 0, pos1, out_text)) goto memfail;
753 if (new_id && kputs(new_id, out_text) == EOF) goto memfail;
754 if (kputs(line + pos2, out_text) == EOF) goto memfail;
755 if (kputc('\n', out_text) == EOF) goto memfail;
756 free(line); // No longer needed
757 line = NULL;
758 }
759
760 return 0;
761
762 memfail:
763 perror(__func__);
764 free(line); // Prevent leakage as no longer on list
765 return -1;
766 }
767
768 /*
769 * Build the translation table for an input *am file. This stores mappings
770 * which allow IDs to be converted from those used in the input file
771 * to the ones which will be used in the output. The mappings are for:
772 * Reference sequence IDs (for @SQ records)
773 * @RG record ID tags
774 * @PG record ID tags
775 *
776 * At the same time, new header text is built up by copying records
777 * from the input bam file. This will eventually become the header for
778 * the output file. When copied, the ID tags for @RG and @PG records
779 * are replaced with their values. The @PG PP: and @RG PG: tags
780 * are also modified if necessary.
781 *
782 * merged_hdr holds state on the output header (which IDs are present, etc.)
783 * translate is the input header
784 * tbl is the translation table that gets filled in.
785 * merge_rg controls merging of @RG records
786 * merge_pg controls merging of @PG records
787 * If rg_override is not NULL, it will be used to replace the existing @RG ID
788 *
789 * Returns 0 on success, -1 on failure.
790 */
791
792 static int trans_tbl_init(merged_header_t* merged_hdr, sam_hdr_t* translate,
793 trans_tbl_t* tbl, bool merge_rg, bool merge_pg,
794 bool copy_co, char* rg_override)
795 {
796 kstring_t lines = { 0, 0, NULL };
797 klist_t(hdrln) *rg_list = NULL;
798 klist_t(hdrln) *pg_list = NULL;
799
800 tbl->n_targets = sam_hdr_nref(translate);
801 tbl->rg_trans = tbl->pg_trans = NULL;
802 tbl->tid_trans = (int*)calloc(tbl->n_targets ? tbl->n_targets : 1,
803 sizeof(int));
804 if (tbl->tid_trans == NULL) goto memfail;
805 tbl->rg_trans = kh_init(c2c);
806 if (tbl->rg_trans == NULL) goto memfail;
807 tbl->pg_trans = kh_init(c2c);
808 if (tbl->pg_trans == NULL) goto memfail;
809
810 tbl->lost_coord_sort = false;
811
812 // Get the @HD record (if not there already).
813 if (trans_tbl_add_hd(merged_hdr, translate)) goto fail;
814
815 // Fill in map and add header lines for @SQ records
816 if (trans_tbl_add_sq(merged_hdr, translate, tbl)) goto fail;
817
818 // Get translated header lines and fill in map for @RG records
819 rg_list = trans_rg_pg(true, translate, merge_rg, merged_hdr->rg_ids,
820 tbl->rg_trans, rg_override);
821 if (!rg_list) goto fail;
822
823 // Get translated header lines and fill in map for @PG records
824 pg_list = trans_rg_pg(false, translate, merge_pg, merged_hdr->pg_ids,
825 tbl->pg_trans, NULL);
826 if (!pg_list) goto fail;
827
828 // Fix-up PG: tags in the new @RG records and add to output
829 if (finish_rg_pg(true, rg_list, tbl->pg_trans, &merged_hdr->out_rg))
830 goto fail;
831
832 // Fix-up PP: tags in the new @PG records and add to output
833 lines.l = 0;
834 if (finish_rg_pg(false, pg_list, tbl->pg_trans, &merged_hdr->out_pg))
835 goto fail;
836
837 kl_destroy(hdrln, rg_list); rg_list = NULL;
838 kl_destroy(hdrln, pg_list); pg_list = NULL;
839
840 if (copy_co) {
841 // Just append @CO headers without translation
842 int num_co = sam_hdr_count_lines(translate, "CO"), i;
843 if (num_co < 0)
844 goto fail;
845
846 for (i = 0; i < num_co; i++) {
847 if (sam_hdr_find_line_pos(translate, "CO", i, &lines) < 0)
848 goto fail;
849 if (ks_to_ks(&lines, &merged_hdr->out_co))
850 goto fail;
851 if (kputc('\n', &merged_hdr->out_co) < 0)
852 goto fail;
853 }
854 }
855
856 free(lines.s);
857
858 return 0;
859
860 memfail:
861 perror(__func__);
862 fail:
863 trans_tbl_destroy(tbl);
864 if (rg_list) kl_destroy(hdrln, rg_list);
865 if (pg_list) kl_destroy(hdrln, pg_list);
866 free(lines.s);
867 return -1;
868 }
869
870 static int finish_merged_header(merged_header_t *merged_hdr) {
871 if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_rg),
872 ks_len(&merged_hdr->out_rg)) < 0)
873 return -1;
874 if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_pg),
875 ks_len(&merged_hdr->out_pg)) < 0)
876 return -1;
877 if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_co),
878 ks_len(&merged_hdr->out_co)) < 0)
879 return -1;
880
881 return 0;
882 }
883
884 /*
885 * Free a merged_header_t struct and all associated data.
886 *
887 * Note that the keys to the rg_ids and pg_ids sets are also used as
888 * values in the translation tables. This function should therefore not
889 * be called until the translation tables are no longer needed.
890 */
891
892 static void free_merged_header(merged_header_t *merged_hdr) {
893 size_t i;
894 khiter_t iter;
895 if (!merged_hdr) return;
896 free(ks_release(&merged_hdr->out_rg));
897 free(ks_release(&merged_hdr->out_pg));
898 free(ks_release(&merged_hdr->out_co));
899 if (merged_hdr->target_name) {
900 for (i = 0; i < merged_hdr->n_targets; i++) {
901 free(merged_hdr->target_name[i]);
902 }
903 free(merged_hdr->target_name);
904 }
905 free(merged_hdr->target_len);
906 kh_destroy(c2i, merged_hdr->sq_tids);
907
908 if (merged_hdr->rg_ids) {
909 for (iter = kh_begin(merged_hdr->rg_ids);
910 iter != kh_end(merged_hdr->rg_ids); ++iter) {
911 if (kh_exist(merged_hdr->rg_ids, iter))
912 free(kh_key(merged_hdr->rg_ids, iter));
913 }
914 kh_destroy(cset, merged_hdr->rg_ids);
915 }
916
917 if (merged_hdr->pg_ids) {
918 for (iter = kh_begin(merged_hdr->pg_ids);
919 iter != kh_end(merged_hdr->pg_ids); ++iter) {
920 if (kh_exist(merged_hdr->pg_ids, iter))
921 free(kh_key(merged_hdr->pg_ids, iter));
922 }
923 kh_destroy(cset, merged_hdr->pg_ids);
924 }
925
926 free(merged_hdr);
927 }
928
929 static void bam_translate(bam1_t* b, trans_tbl_t* tbl)
930 {
931 // Update target id if not unmapped tid
932 if ( b->core.tid >= 0 ) { b->core.tid = tbl->tid_trans[b->core.tid]; }
933 if ( b->core.mtid >= 0 ) { b->core.mtid = tbl->tid_trans[b->core.mtid]; }
934
935 // If we have a RG update it
936 uint8_t *rg = bam_aux_get(b, "RG");
937 if (rg) {
938 char* decoded_rg = bam_aux2Z(rg);
939 khiter_t k = kh_get(c2c, tbl->rg_trans, decoded_rg);
940 if (k != kh_end(tbl->rg_trans)) {
941 char* translate_rg = kh_value(tbl->rg_trans,k);
942 bam_aux_del(b, rg);
943 if (translate_rg) {
944 bam_aux_append(b, "RG", 'Z', strlen(translate_rg) + 1,
945 (uint8_t*)translate_rg);
946 }
947 } else {
948 char *tmp = strdup(decoded_rg);
949 fprintf(stderr,
950 "[bam_translate] RG tag \"%s\" on read \"%s\" encountered "
951 "with no corresponding entry in header, tag lost. "
952 "Unknown tags are only reported once per input file for "
953 "each tag ID.\n",
954 decoded_rg, bam_get_qname(b));
955 bam_aux_del(b, rg);
956 // Prevent future whinges
957 if (tmp) {
958 int in_there = 0;
959 k = kh_put(c2c, tbl->rg_trans, tmp, &in_there);
960 if (in_there > 0) kh_value(tbl->rg_trans, k) = NULL;
961 }
962 }
963 }
964
965 // If we have a PG update it
966 uint8_t *pg = bam_aux_get(b, "PG");
967 if (pg) {
968 char* decoded_pg = bam_aux2Z(pg);
969 khiter_t k = kh_get(c2c, tbl->pg_trans, decoded_pg);
970 if (k != kh_end(tbl->pg_trans)) {
971 char* translate_pg = kh_value(tbl->pg_trans,k);
972 bam_aux_del(b, pg);
973 if (translate_pg) {
974 bam_aux_append(b, "PG", 'Z', strlen(translate_pg) + 1,
975 (uint8_t*)translate_pg);
976 }
977 } else {
978 char *tmp = strdup(decoded_pg);
979 fprintf(stderr,
980 "[bam_translate] PG tag \"%s\" on read \"%s\" encountered "
981 "with no corresponding entry in header, tag lost. "
982 "Unknown tags are only reported once per input file for "
983 "each tag ID.\n",
984 decoded_pg, bam_get_qname(b));
985 bam_aux_del(b, pg);
986 // Prevent future whinges
987 if (tmp) {
988 int in_there = 0;
989 k = kh_put(c2c, tbl->pg_trans, tmp, &in_there);
990 if (in_there > 0) kh_value(tbl->pg_trans, k) = NULL;
991 }
992 }
993 }
994 }
995
996 int* rtrans_build(int n, int n_targets, trans_tbl_t* translation_tbl)
997 {
998 // Create reverse translation table for tids
999 int* rtrans = (int*)malloc(sizeof(int32_t)*n*n_targets);
1000 const int32_t NOTID = INT32_MIN;
1001 if (!rtrans) return NULL;
1002 memset_pattern4((void*)rtrans, &NOTID, sizeof(int32_t)*n*n_targets);
1003 int i;
1004 for (i = 0; i < n; ++i) {
1005 int j;
1006 for (j = 0; j < (translation_tbl+i)->n_targets; ++j) {
1007 if ((translation_tbl+i)->tid_trans[j] != -1) {
1008 rtrans[i*n_targets + (translation_tbl+i)->tid_trans[j]] = j;
1009 }
1010 }
1011 }
1012
1013 return rtrans;
1014 }
1015
1016 #define MERGE_RG 1 // Attach RG tag based on filename
1017 #define MERGE_UNCOMP 2 // Generate uncompressed BAM
1018 #define MERGE_LEVEL1 4 // Compress the BAM at level 1 (fast) mode
1019 #define MERGE_FORCE 8 // Overwrite output BAM if it exists
1020 #define MERGE_COMBINE_RG 16 // Combine RG tags frather than redefining them
1021 #define MERGE_COMBINE_PG 32 // Combine PG tags frather than redefining them
1022 #define MERGE_FIRST_CO 64 // Use only first file's @CO headers (sort cmd only)
1023
1024
1025 static hts_reglist_t *duplicate_reglist(const hts_reglist_t *rl, int rn) {
1026 if (!rl)
1027 return NULL;
1028
1029 hts_reglist_t *new_rl = calloc(rn, sizeof(hts_reglist_t));
1030 if (!new_rl)
1031 return NULL;
1032
1033 int i;
1034 for (i=0; i < rn; i++) {
1035 new_rl[i].tid = rl[i].tid;
1036 new_rl[i].count = rl[i].count;
1037 new_rl[i].min_beg = rl[i].min_beg;
1038 new_rl[i].max_end = rl[i].max_end;
1039
1040 new_rl[i].reg = rl[i].reg;
1041 new_rl[i].intervals = malloc(new_rl[i].count * sizeof(hts_pair_pos_t));
1042 if (!new_rl[i].intervals) {
1043 hts_reglist_free(new_rl, i);
1044 return NULL;
1045 }
1046 memcpy(new_rl[i].intervals, rl[i].intervals, new_rl[i].count * sizeof(hts_pair_pos_t));
1047 }
1048
1049 return new_rl;
1050 }
1051
1052 /*
1053 * How merging is handled
1054 *
1055 * If a header is defined use we will use that as our output header
1056 * otherwise we use the first header from the first input file.
1057 *
1058 * Now go through each file and create a translation table for that file for:
1059 * -RG
1060 * -tid
1061 * -PG tags
1062 *
1063 * Then whenever we read a record from a bam we translate that read before
1064 * stashing it in the hash.
1065 *
1066 * In the actual merge, a read is read from each input file, translated and
1067 * stashed in the hash. This assumes that all input files are sorted in the
1068 * same way. Next we just extract the next position ordered read from the
1069 * hash, and replace it if there are still reads left in it's source input
1070 * file. Finally we write our chosen read it to the output file.
1071 */
1072
1073 /*!
1074 @abstract Merge multiple sorted BAM.
1075 @param sam_order the order in which the data was sorted
1076 @param sort_tag if non-null, the tag that data was sorted by
1077 @param out output BAM file name
1078 @param mode sam_open() mode to be used to create the final output file
1079 (overrides level settings from UNCOMP and LEVEL1 flags)
1080 @param headers name of SAM file from which to copy '@' header lines,
1081 or NULL to copy them from the first file to be merged
1082 @param n number of files to be merged
1083 @param fn names of files to be merged
1084 @param flag flags that control how the merge is undertaken
1085 @param reg region to merge
1086 @param n_threads number of threads to use (passed to htslib)
1087 @param cmd command name (used in print_error() etc)
1088 @param in_fmt format options for input files
1089 @param out_fmt output file format and options
1090 @param write_index create the index, together with the output file
1091 @param arg_list command string for PG line
1092 @param no_pg if 1, do not add a new PG line
1093 @discussion Padding information may NOT correctly maintained. This
1094 function is NOT thread safe.
1095 */
1096 int bam_merge_core2(SamOrder sam_order, char* sort_tag, const char *out, const char *mode,
1097 const char *headers, int n, char * const *fn, char * const *fn_idx,
1098 const char *fn_bed, int flag, const char *reg, int n_threads,
1099 const char *cmd, const htsFormat *in_fmt, const htsFormat *out_fmt,
1100 int write_index, char *arg_list, int no_pg)
1101 {
1102 samFile *fpout, **fp = NULL;
1103 heap1_t *heap = NULL;
1104 sam_hdr_t *hout = NULL;
1105 sam_hdr_t *hin = NULL;
1106 int i, j, *RG_len = NULL;
1107 uint64_t idx = 0;
1108 char **RG = NULL;
1109 hts_itr_t **iter = NULL;
1110 sam_hdr_t **hdr = NULL;
1111 trans_tbl_t *translation_tbl = NULL;
1112 int *rtrans = NULL;
1113 char *out_idx_fn = NULL;
1114 void *hreg = NULL;
1115 hts_reglist_t *lreg = NULL;
1116 merged_header_t *merged_hdr = init_merged_header();
1117 if (!merged_hdr) return -1;
1118 refs_t *refs = NULL;
1119 template_coordinate_keys_t *keys = NULL;
1120 khash_t(const_c2c) *lib_lookup = NULL;
1121
1122 // Is there a specified pre-prepared header to use for output?
1123 if (headers) {
1124 samFile* fpheaders = sam_open(headers, "r");
1125 if (fpheaders == NULL) {
1126 print_error_errno(cmd, "cannot open \"%s\"", headers);
1127 return -1;
1128 }
1129 hin = sam_hdr_read(fpheaders);
1130 sam_close(fpheaders);
1131 if (hin == NULL) {
1132 print_error(cmd, "couldn't read headers from \"%s\"", headers);
1133 goto mem_fail;
1134 }
1135 }
1136
1137 g_sam_order = sam_order;
1138 if (sam_order == TagQueryName || sam_order == TagCoordinate) {
1139 g_sort_tag[0] = sort_tag[0];
1140 g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0';
1141 }
1142
1143 fp = (samFile**)calloc(n, sizeof(samFile*));
1144 if (!fp) goto mem_fail;
1145 heap = (heap1_t*)calloc(n, sizeof(heap1_t));
1146 if (!heap) goto mem_fail;
1147 iter = (hts_itr_t**)calloc(n, sizeof(hts_itr_t*));
1148 if (!iter) goto mem_fail;
1149 hdr = (sam_hdr_t**)calloc(n, sizeof(sam_hdr_t*));
1150 if (!hdr) goto mem_fail;
1151 translation_tbl = (trans_tbl_t*)calloc(n, sizeof(trans_tbl_t));
1152 if (!translation_tbl) goto mem_fail;
1153 RG = (char**)calloc(n, sizeof(char*));
1154 if (!RG) goto mem_fail;
1155
1156 // prepare RG tag from file names
1157 if (flag & MERGE_RG) {
1158 RG_len = (int*)calloc(n, sizeof(int));
1159 if (!RG_len) goto mem_fail;
1160 for (i = 0; i != n; ++i) {
1161 int l = strlen(fn[i]);
1162 const char *s = fn[i];
1163 if (l > 4 && (strcmp(s + l - 4, ".bam") == 0 || strcmp(s + l - 4, ".sam") == 0)) l -= 4;
1164 if (l > 5 && strcmp(s + l - 5, ".cram") == 0) l -= 5;
1165 for (j = l - 1; j >= 0; --j) if (s[j] == '/') break;
1166 ++j; l -= j;
1167 RG[i] = (char*)calloc(l + 1, 1);
1168 if (!RG[i]) goto mem_fail;
1169 RG_len[i] = l;
1170 strncpy(RG[i], s + j, l);
1171 }
1172 }
1173
1174 if (hin) {
1175 // Populate merged_hdr from the pre-prepared header
1176 trans_tbl_t dummy;
1177 int res;
1178 res = trans_tbl_init(merged_hdr, hin, &dummy, flag & MERGE_COMBINE_RG,
1179 flag & MERGE_COMBINE_PG, true, NULL);
1180 trans_tbl_destroy(&dummy);
1181 if (res) return -1; // FIXME: memory leak
1182 }
1183
1184 // open and read the header from each file
1185 for (i = 0; i < n; ++i) {
1186 sam_hdr_t *hin;
1187 fp[i] = sam_open_format(fn[i], "r", in_fmt);
1188 if (fp[i] == NULL) {
1189 print_error_errno(cmd, "fail to open \"%s\"", fn[i]);
1190 goto fail;
1191 }
1192 hts_set_opt(fp[i], HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
1193 hin = sam_hdr_read(fp[i]);
1194 if (hin == NULL) {
1195 print_error(cmd, "failed to read header from \"%s\"", fn[i]);
1196 goto fail;
1197 }
1198
1199 if (trans_tbl_init(merged_hdr, hin, translation_tbl+i,
1200 flag & MERGE_COMBINE_RG, flag & MERGE_COMBINE_PG,
1201 (flag & MERGE_FIRST_CO)? (i == 0) : true,
1202 RG[i]))
1203 goto fail;
1204
1205 hdr[i] = hin;
1206
1207 int order_ok = 1;
1208 if ((translation_tbl+i)->lost_coord_sort && (sam_order == Coordinate || sam_order == MinHash)) {
1209 fprintf(stderr, "[bam_merge_core] Order of targets in file %s caused coordinate sort to be lost\n", fn[i]);
1210 order_ok = 0;
1211 }
1212
1213 if (!refs)
1214 refs = cram_get_refs(fp[i]);
1215
1216 if (order_ok && refs && hts_set_opt(fp[i], CRAM_OPT_SHARED_REF, refs))
1217 goto fail;
1218 }
1219
1220 // Did we get an @HD line?
1221 if (!merged_hdr->have_hd) {
1222 fprintf(stderr, "[W::%s] No @HD tag found.\n", __func__);
1223 /* FIXME: Should we add an @HD line here, and if so what should
1224 we put in it? Ideally we want a way of getting htslib to tell
1225 us the SAM version number to assume given no @HD line. Is
1226 it also safe to assume that the output is coordinate sorted?
1227 SO: is optional so we don't have to have it.*/
1228 /* ksprintf(&merged_hdr->out_hd, "@HD\tVN:1.5\tSO:coordinate\n"); */
1229 }
1230
1231 // Transform the header into standard form
1232 if (finish_merged_header(merged_hdr) < 0)
1233 goto fail;
1234
1235 hout = merged_hdr->hdr;
1236 if (!hout)
1237 goto fail;
1238
1239 // If we're only merging a specified region move our iters to start at that point
1240 int tid, nreg;
1241 hts_pos_t beg, end;
1242
1243 if (fn_bed) {
1244 hreg = bed_read(fn_bed);
1245 if (!hreg) {
1246 fprintf(stderr, "[%s] Could not read BED file: \"%s\"\n", __func__, fn_bed);
1247 goto fail;
1248 }
1249 bed_unify(hreg);
1250 lreg = bed_reglist(hreg, ALL, &nreg);
1251 if (!lreg || !nreg) {
1252 fprintf(stderr, "[%s] Null or empty region list\n", __func__);
1253 goto fail;
1254 }
1255 } else if (reg) {
1256 rtrans = rtrans_build(n, sam_hdr_nref(hout), translation_tbl);
1257 if (!rtrans) goto mem_fail;
1258
1259 if (!sam_parse_region(hout, reg, &tid, &beg, &end, 0)) {
1260 fprintf(stderr, "[%s] Badly formatted region or unknown reference name: \"%s\"\n", __func__, reg);
1261 goto fail;
1262 }
1263
1264 }
1265
1266 if (reg || fn_bed) {
1267 hts_idx_t *reg_idx = NULL;
1268 for (i = 0; i < n; ++i) {
1269
1270 // If index filename has not been specified, look in the BAM folder
1271 if (fn_idx != NULL) {
1272 reg_idx = sam_index_load2(fp[i], fn[i], fn_idx[i]);
1273 } else {
1274 reg_idx = sam_index_load(fp[i], fn[i]);
1275 }
1276 if (reg_idx == NULL) {
1277 fprintf(stderr, "[%s] failed to load index for %s. Random alignment retrieval only works for indexed BAM or CRAM files.\n",
1278 __func__, fn[i]);
1279 free(rtrans);
1280 rtrans = NULL;
1281 goto fail;
1282 }
1283
1284 int mapped_tid = INT32_MIN;
1285 if (fn_bed) {
1286 hts_reglist_t *rl = duplicate_reglist(lreg, nreg);
1287 iter[i] = sam_itr_regions(reg_idx, hdr[i], rl, nreg);
1288 } else {
1289 // (rtrans[i*n+tid]) Look up what hout tid translates to in input tid space
1290 mapped_tid = rtrans[i*sam_hdr_nref(hout)+tid];
1291 if (mapped_tid != INT32_MIN) {
1292 iter[i] = sam_itr_queryi(reg_idx, mapped_tid, beg, end);
1293 } else {
1294 iter[i] = sam_itr_queryi(reg_idx, HTS_IDX_NONE, 0, 0);
1295 }
1296 }
1297
1298 if (iter[i] == NULL) {
1299 if (fn_bed) {
1300 fprintf(stderr, "[%s] failed to get multi-region iterator "
1301 "{%s, %s}\n", __func__, fn[i], fn_bed);
1302 } else {
1303 if (mapped_tid != INT32_MIN) {
1304 fprintf(stderr,
1305 "[%s] failed to get iterator over "
1306 "{%s, %d, %"PRIhts_pos", %"PRIhts_pos"}\n",
1307 __func__, fn[i], mapped_tid, beg, end);
1308 } else {
1309 fprintf(stderr,
1310 "[%s] failed to get iterator over "
1311 "{%s, HTS_IDX_NONE, 0, 0}\n",
1312 __func__, fn[i]);
1313 }
1314 }
1315 hts_idx_destroy(reg_idx);
1316 free(rtrans);
1317 rtrans = NULL;
1318 goto fail;
1319 }
1320
1321 hts_idx_destroy(reg_idx);
1322 }
1323
1324 free(rtrans);
1325 rtrans = NULL;
1326 }
1327
1328 // Make sure that there's enough memory for template coordinate keys, one per file to read
1329 if (sam_order == TemplateCoordinate) {
1330 if ((keys = malloc(sizeof(template_coordinate_keys_t))) == NULL) {
1331 print_error(cmd, "could not allocate memory for the top-level keys");
1332 goto mem_fail;
1333 }
1334 keys->n = 0;
1335 keys->m = 0;
1336 keys->buffer_size = 0x10000;
1337 keys->buffers = NULL;
1338 // Make sure that there's enough memory for template coordinate keys, one per file to read
1339 if (keys->n + n >= keys->m * keys->buffer_size) {
1340 if (template_coordinate_keys_realloc(keys, keys->n + n) < 0) goto mem_fail;
1341 }
1342 lib_lookup = lookup_libraries(hout);
1343 if (!lib_lookup) {
1344 goto mem_fail;
1345 }
1346 }
1347
1348 // Load the first read from each file into the heap
1349 for (i = 0; i < n; ++i) {
1350 heap1_t *h = heap + i;
1351 int res;
1352 h->i = i;
1353 h->entry.bam_record = bam_init1();
1354 h->entry.u.tag = NULL;
1355 if (!h->entry.bam_record) goto mem_fail;
1356 res = iter[i] ? sam_itr_next(fp[i], iter[i], h->entry.bam_record) : sam_read1(fp[i], hdr[i], h->entry.bam_record);
1357 if (res >= 0) {
1358 bam_translate(h->entry.bam_record, translation_tbl + i);
1359 h->tid = h->entry.bam_record->core.tid;
1360 h->pos = (uint64_t)(h->entry.bam_record->core.pos + 1);
1361 h->rev = bam_is_rev(h->entry.bam_record);
1362 h->idx = idx++;
1363 if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) {
1364 h->entry.u.tag = bam_aux_get(h->entry.bam_record, g_sort_tag);
1365 } else if (g_sam_order == TemplateCoordinate) {
1366 template_coordinate_key_t *key = template_coordinate_keys_get(keys, i); // get the next key to use
1367 h->entry.u.key = template_coordinate_key(h->entry.bam_record, key, hout, lib_lookup); // update the key
1368 if (h->entry.u.key == NULL) goto fail; // key could not be created, error out
1369 } else {
1370 h->entry.u.tag = NULL;
1371 }
1372 }
1373 else if (res == -1 && (!iter[i] || iter[i]->finished)) {
1374 h->pos = HEAP_EMPTY;
1375 bam_destroy1(h->entry.bam_record);
1376 h->entry.bam_record = NULL;
1377 h->entry.u.tag = NULL;
1378 h->entry.u.key = NULL;
1379 } else {
1380 print_error(cmd, "failed to read first record from \"%s\"", fn[i]);
1381 goto fail;
1382 }
1383 }
1384
1385 // Open output file and write header
1386 if ((fpout = sam_open_format(out, mode, out_fmt)) == 0) {
1387 print_error_errno(cmd, "failed to create \"%s\"", out);
1388 return -1;
1389 }
1390 hts_set_opt(fpout, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
1391 if (!no_pg && sam_hdr_add_pg(hout, "samtools",
1392 "VN", samtools_version(),
1393 arg_list ? "CL": NULL,
1394 arg_list ? arg_list : NULL,
1395 NULL)) {
1396 print_error(cmd, "failed to add PG line to the header of \"%s\"", out);
1397 sam_close(fpout);
1398 return -1;
1399 }
1400 if (sam_hdr_write(fpout, hout) != 0) {
1401 print_error_errno(cmd, "failed to write header to \"%s\"", out);
1402 sam_close(fpout);
1403 return -1;
1404 }
1405 if (write_index) {
1406 if (!(out_idx_fn = auto_index(fpout, out, hout))){
1407 sam_close(fpout);
1408 return -1;
1409 }
1410 }
1411 if (!(flag & MERGE_UNCOMP)) hts_set_threads(fpout, n_threads);
1412
1413 if (refs && hts_set_opt(fpout, CRAM_OPT_SHARED_REF, refs))
1414 goto fail;
1415
1416 // Begin the actual merge
1417 ks_heapmake(heap, n, heap);
1418 while (heap->pos != HEAP_EMPTY) {
1419 bam1_t *b = heap->entry.bam_record;
1420 if (flag & MERGE_RG) {
1421 uint8_t *rg = bam_aux_get(b, "RG");
1422 if (rg) bam_aux_del(b, rg);
1423 bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]);
1424 }
1425 if (sam_write1(fpout, hout, b) < 0) {
1426 print_error_errno(cmd, "failed writing to \"%s\"", out);
1427 sam_close(fpout);
1428 free(out_idx_fn);
1429 return -1;
1430 }
1431 if ((j = (iter[heap->i]? sam_itr_next(fp[heap->i], iter[heap->i], b) : sam_read1(fp[heap->i], hdr[heap->i], b))) >= 0) {
1432 bam_translate(b, translation_tbl + heap->i);
1433 heap->tid = b->core.tid;
1434 heap->pos = (uint64_t)(b->core.pos + 1);
1435 heap->rev = bam_is_rev(b);
1436 heap->idx = idx++;
1437 if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) {
1438 heap->entry.u.tag = bam_aux_get(heap->entry.bam_record, g_sort_tag);
1439 } else if (g_sam_order == TemplateCoordinate) {
1440 template_coordinate_key_t *key = template_coordinate_keys_get(keys, heap->i); // get the next key to use
1441 heap->entry.u.key = template_coordinate_key(heap->entry.bam_record, key, hout, lib_lookup); // update the key
1442 if (heap->entry.u.key == NULL) goto fail; // key could not be created, error out
1443 } else {
1444 heap->entry.u.tag = NULL;
1445 }
1446 } else if (j == -1 && (!iter[heap->i] || iter[heap->i]->finished)) {
1447 heap->pos = HEAP_EMPTY;
1448 bam_destroy1(heap->entry.bam_record);
1449 heap->entry.bam_record = NULL;
1450 heap->entry.u.tag = NULL;
1451 } else {
1452 print_error(cmd, "\"%s\" is truncated", fn[heap->i]);
1453 goto fail;
1454 }
1455 ks_heapadjust(heap, 0, n, heap);
1456 }
1457
1458 if (write_index) {
1459 if (sam_idx_save(fpout) < 0) {
1460 print_error_errno("merge", "writing index failed");
1461 goto fail;
1462 }
1463 }
1464 free(out_idx_fn);
1465
1466 // Clean up and close
1467 if (flag & MERGE_RG) {
1468 for (i = 0; i != n; ++i) free(RG[i]);
1469 free(RG_len);
1470 }
1471 for (i = 0; i < n; ++i) {
1472 trans_tbl_destroy(translation_tbl + i);
1473 hts_itr_destroy(iter[i]);
1474 sam_hdr_destroy(hdr[i]);
1475 sam_close(fp[i]);
1476 }
1477 sam_hdr_destroy(hin);
1478 sam_hdr_destroy(hout);
1479 free_merged_header(merged_hdr);
1480 hts_reglist_free(lreg, nreg);
1481 bed_destroy(hreg);
1482 free(RG); free(translation_tbl); free(fp); free(heap); free(iter); free(hdr);
1483 if (sam_close(fpout) < 0) {
1484 print_error_errno(cmd, "error closing output file \"%s\"", out);
1485 return -1;
1486 }
1487 if (keys != NULL) {
1488 for (i = 0; i < keys->m; ++i) {
1489 free(keys->buffers[i]);
1490 }
1491 free(keys->buffers);
1492 free(keys);
1493 }
1494 lib_lookup_destroy(lib_lookup);
1495 return 0;
1496
1497 mem_fail:
1498 print_error(cmd, "Out of memory");
1499
1500 fail:
1501 if (flag & MERGE_RG) {
1502 if (RG) {
1503 for (i = 0; i != n; ++i) free(RG[i]);
1504 }
1505 free(RG_len);
1506 }
1507 for (i = 0; i < n; ++i) {
1508 if (translation_tbl && translation_tbl[i].tid_trans) trans_tbl_destroy(translation_tbl + i);
1509 if (iter && iter[i]) hts_itr_destroy(iter[i]);
1510 if (hdr && hdr[i]) sam_hdr_destroy(hdr[i]);
1511 if (fp && fp[i]) sam_close(fp[i]);
1512 if (heap && heap[i].entry.bam_record) bam_destroy1(heap[i].entry.bam_record);
1513 }
1514 if (hout) sam_hdr_destroy(hout);
1515 free(RG);
1516 free(translation_tbl);
1517 free(hdr);
1518 hts_reglist_free(lreg, nreg);
1519 bed_destroy(hreg);
1520 free(iter);
1521 free(heap);
1522 free(fp);
1523 free(rtrans);
1524 free(out_idx_fn);
1525 if (keys != NULL) {
1526 for (i = 0; i < keys->m; ++i) {
1527 free(keys->buffers[i]);
1528 }
1529 free(keys->buffers);
1530 free(keys);
1531 }
1532 lib_lookup_destroy(lib_lookup);
1533 return -1;
1534 }
1535
1536 // Unused here but may be used by legacy samtools-using third-party code
1537 int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn, int flag, const char *reg)
1538 {
1539 char mode[12];
1540 strcpy(mode, "wb");
1541 if (flag & MERGE_UNCOMP) strcat(mode, "0");
1542 else if (flag & MERGE_LEVEL1) strcat(mode, "1");
1543 SamOrder sam_order = by_qname ? QueryName : Coordinate;
1544 return bam_merge_core2(sam_order, NULL, out, mode, headers, n, fn, NULL, NULL, flag, reg, 0, "merge", NULL, NULL, 0, NULL, 1);
1545 }
1546
1547 static void merge_usage(FILE *to)
1548 {
1549 fprintf(to,
1550 "Usage: samtools merge [options] -o <out.bam> [options] <in1.bam> ... <inN.bam>\n"
1551 " or: samtools merge [options] <out.bam> <in1.bam> ... <inN.bam>\n"
1552 "\n"
1553 "Options:\n"
1554 " -n Input files are sorted by read name (natural)\n"
1555 " -N Input files are sorted by read name (ASCII)\n"
1556 " -t TAG Input files are sorted by TAG value\n"
1557 " -r Attach RG tag (inferred from file names)\n"
1558 " -u Uncompressed BAM output\n"
1559 " -f Overwrite the output BAM if exist\n"
1560 " -o FILE Specify output file via option instead of <out.bam> argument\n"
1561 " -1 Compress level 1\n"
1562 " -l INT Compression level, from 0 to 9 [-1]\n"
1563 " -R STR Merge file in the specified region STR [all]\n"
1564 " -h FILE Copy the header in FILE to <out.bam> [in1.bam]\n"
1565 " -c Combine @RG headers with colliding IDs [alter IDs to be distinct]\n"
1566 " -p Combine @PG headers with colliding IDs [alter IDs to be distinct]\n"
1567 " -s VALUE Override random seed\n"
1568 " -b FILE List of input BAM filenames, one per line [null]\n"
1569 " -X Use customized index files\n"
1570 " -L FILE Specify a BED file for multiple region filtering [null]\n"
1571 " --no-PG do not add a PG line\n"
1572 " --template-coordinate Input files are sorted by template-coordinate\n");
1573 sam_global_opt_help(to, "-.O..@..");
1574 }
1575
1576 int bam_merge(int argc, char *argv[])
1577 {
1578 int c, flag = 0, ret = 0, level = -1, has_index_file = 0;
1579 char *fn_headers = NULL, *reg = NULL, mode[12];
1580 char *sort_tag = NULL, *fnout = NULL, *arg_list = NULL;
1581 long random_seed = (long)time(NULL);
1582 char** fn = NULL;
1583 char** fn_idx = NULL, *fn_bed = NULL;
1584 int fn_size = 0, no_pg = 0;
1585 SamOrder sam_order = Coordinate;
1586
1587 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
1588 static const struct option lopts[] = {
1589 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
1590 { "threads", required_argument, NULL, '@' },
1591 {"no-PG", no_argument, NULL, 1},
1592 { "template-coordinate", no_argument, NULL, 2},
1593 { NULL, 0, NULL, 0 }
1594 };
1595
1596 if (argc == 1) {
1597 merge_usage(stdout);
1598 return 0;
1599 }
1600
1601 while ((c = getopt_long(argc, argv, "h:nNru1R:o:f@:l:cps:b:O:t:XL:", lopts, NULL)) >= 0) {
1602 switch (c) {
1603 case 'r': flag |= MERGE_RG; break;
1604 case 'f': flag |= MERGE_FORCE; break;
1605 case 'h': fn_headers = optarg; break;
1606 case 'N': natural_sort = 0; // fall through
1607 case 'n': sam_order = QueryName; break;
1608 case 'o': fnout = optarg; break;
1609 case 't': sort_tag = optarg; break;
1610 case '1': flag |= MERGE_LEVEL1; level = 1; break;
1611 case 'u': flag |= MERGE_UNCOMP; level = 0; break;
1612 case 'R': reg = strdup(optarg); break;
1613 case 'l': level = atoi(optarg); break;
1614 case 'c': flag |= MERGE_COMBINE_RG; break;
1615 case 'p': flag |= MERGE_COMBINE_PG; break;
1616 case 's': random_seed = atol(optarg); break;
1617 case 'X': has_index_file = 1; break; // -X flag for index filename
1618 case 'L': fn_bed = optarg; break;
1619 case 'b': {
1620 // load the list of files to read
1621 if (has_index_file) {
1622 fprintf(stderr,"Error: The -b option cannot be combined with -X\n");
1623 ret = 1; goto end;
1624 }
1625 int nfiles;
1626 char **fn_read = hts_readlines(optarg, &nfiles);
1627 if (fn_read) {
1628 // Append to end of array
1629 fn = realloc(fn, (fn_size+nfiles) * sizeof(char*));
1630 if (fn == NULL) { ret = 1; goto end; }
1631 memcpy(fn+fn_size, fn_read, nfiles * sizeof(char*));
1632 fn_size += nfiles;
1633 free(fn_read);
1634 }
1635 else {
1636 print_error("merge", "Invalid file list \"%s\"", optarg);
1637 ret = 1;
1638 }
1639 break;
1640 }
1641 case 1: no_pg = 1; break;
1642 case 2: sam_order = TemplateCoordinate; break;
1643 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1644 /* else fall-through */
1645 case '?': merge_usage(stderr); return 1;
1646 }
1647 }
1648
1649 if (sort_tag != NULL) {
1650 sam_order = sam_order == QueryName ? TagQueryName : TagCoordinate;
1651 }
1652
1653 if (fnout == NULL && argc - optind >= 1) {
1654 fnout = argv[optind];
1655 optind++;
1656 }
1657 if (fnout == NULL) {
1658 print_error("merge", "You must at least specify the output file");
1659 merge_usage(stderr);
1660 return 1;
1661 }
1662
1663 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
1664 print_error("merge", "failed to create arg_list");
1665 return 1;
1666 }
1667
1668 hts_srand48(random_seed);
1669 if (!(flag & MERGE_FORCE) && strcmp(fnout, "-") != 0) {
1670 struct stat sbuf;
1671 if (stat(fnout, &sbuf) == 0 && S_ISREG(sbuf.st_mode)) {
1672 fprintf(stderr, "[%s] File '%s' exists. Please apply '-f' to overwrite. Abort.\n", __func__, fnout);
1673 ret = 1;
1674 goto end;
1675 }
1676 }
1677
1678 int nargcfiles = 0;
1679 if (has_index_file) { // Calculate # of input BAM files
1680 if ((argc - optind) % 2 != 0) {
1681 fprintf(stderr, "Odd number of filenames detected! Each BAM file should have an index file\n");
1682 ret = 1;
1683 goto end;
1684 }
1685 nargcfiles = (argc - optind) / 2;
1686 } else {
1687 nargcfiles = argc - optind;
1688 }
1689
1690 if (nargcfiles > 0) {
1691 // Add argc files to end of array
1692 fn = realloc(fn, (fn_size+nargcfiles) * sizeof(char*));
1693 if (fn == NULL) { ret = 1; goto end; }
1694 memcpy(fn+fn_size, argv + optind, nargcfiles * sizeof(char*));
1695
1696 if(has_index_file) {
1697 fn_idx = realloc(fn_idx, nargcfiles * sizeof(char*));
1698 if (fn_idx == NULL) { ret = 1; goto end; }
1699 memcpy(fn_idx+fn_size, argv + nargcfiles + optind, nargcfiles * sizeof(char*));
1700 }
1701 }
1702 if (fn_size+nargcfiles < 1) {
1703 print_error("merge", "You must specify at least one (and usually two or more) input files");
1704 merge_usage(stderr);
1705 ret = 1;
1706 goto end;
1707 }
1708
1709 if (reg && fn_bed) {
1710 print_error("merge", "You must specify either a BED file or a region");
1711 ret = 1;
1712 goto end;
1713 }
1714 strcpy(mode, "wb");
1715 sam_open_mode(mode+1, fnout, NULL);
1716 if (level >= 0) sprintf(strchr(mode, '\0'), "%d", level < 9? level : 9);
1717 if (bam_merge_core2(sam_order, sort_tag, fnout, mode, fn_headers,
1718 fn_size+nargcfiles, fn, fn_idx, fn_bed, flag, reg, ga.nthreads,
1719 "merge", &ga.in, &ga.out, ga.write_index, arg_list, no_pg) < 0)
1720 ret = 1;
1721
1722 end:
1723 if (fn_size > 0) {
1724 int i;
1725 for (i=0; i<fn_size; i++) free(fn[i]);
1726 }
1727 free(fn);
1728 free(fn_idx);
1729 free(reg);
1730 free(arg_list);
1731 sam_global_args_free(&ga);
1732 return ret;
1733 }
1734
1735 /***************
1736 * BAM sorting *
1737 ***************/
1738
1739
1740 typedef struct {
1741 size_t from;
1742 size_t to;
1743 } buf_region;
1744
1745 /* Simplified version of bam_merge_core2() for merging part-sorted
1746 temporary files. No need for header merging or translation,
1747 it just needs to read data into the heap and push it out again. */
1748
1749 static inline int heap_add_read(heap1_t *heap, int nfiles, samFile **fp,
1750 int num_in_mem, buf_region *in_mem,
1751 bam1_tag *buf, template_coordinate_keys_t *keys,
1752 uint64_t *idx, sam_hdr_t *hout,
1753 khash_t(const_c2c) *lib_lookup) {
1754 int i = heap->i, res;
1755 if (i < nfiles) { // read from file
1756 res = sam_read1(fp[i], hout, heap->entry.bam_record);
1757 if (res >= 0 && g_sam_order == TemplateCoordinate) { // file read OK and TemplateCoordinate order
1758 // It is assumed that there are nfiles more keys allocated than keys->n; see allocation in bam_merge_simple
1759 template_coordinate_key_t *key = template_coordinate_keys_get(keys, keys->n + i); // get the next key to use
1760 heap->entry.u.key = template_coordinate_key(heap->entry.bam_record, key, hout, lib_lookup); // update the key
1761 if (heap->entry.u.key == NULL) res = -1; // key could not be created, error out
1762 }
1763 } else { // read from memory
1764 if (in_mem[i - nfiles].from < in_mem[i - nfiles].to) {
1765 size_t from = in_mem[i - nfiles].from;
1766 heap->entry.bam_record = buf[from].bam_record;
1767 if (g_sam_order == TemplateCoordinate) heap->entry.u.key = buf[from].u.key;
1768 in_mem[i - nfiles].from++;
1769 res = 0;
1770 } else {
1771 res = -1;
1772 }
1773 }
1774 if (res >= 0) {
1775 heap->tid = heap->entry.bam_record->core.tid;
1776 heap->pos = (uint64_t)(heap->entry.bam_record->core.pos + 1);
1777 heap->rev = bam_is_rev(heap->entry.bam_record);
1778 heap->idx = (*idx)++;
1779 if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) {
1780 heap->entry.u.tag = bam_aux_get(heap->entry.bam_record, g_sort_tag);
1781 } else if (g_sam_order != TemplateCoordinate) {
1782 heap->entry.u.tag = NULL;
1783 heap->entry.u.key = NULL;
1784 }
1785 } else if (res == -1) {
1786 heap->pos = HEAP_EMPTY;
1787 if (i < nfiles) bam_destroy1(heap->entry.bam_record);
1788 heap->entry.bam_record = NULL;
1789 heap->entry.u.tag = NULL;
1790 heap->entry.u.key = NULL;
1791 } else {
1792 return -1;
1793 }
1794 return 0;
1795 }
1796
1797 static int bam_merge_simple(SamOrder sam_order, char *sort_tag, const char *out,
1798 const char *mode, sam_hdr_t *hout,
1799 int n, char * const *fn, int num_in_mem,
1800 buf_region *in_mem, bam1_tag *buf,
1801 template_coordinate_keys_t *keys,
1802 khash_t(const_c2c) *lib_lookup,
1803 htsThreadPool *htspool,
1804 const char *cmd, const htsFormat *in_fmt,
1805 const htsFormat *out_fmt, char *arg_list, int no_pg,
1806 int write_index, int final_out) {
1807 samFile *fpout = NULL, **fp = NULL;
1808 heap1_t *heap = NULL;
1809 uint64_t idx = 0;
1810 int i, heap_size = n + num_in_mem;
1811 char *out_idx_fn = NULL;
1812
1813 if (sam_order == TagQueryName || sam_order == TagCoordinate) {
1814 g_sort_tag[0] = sort_tag[0];
1815 g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0';
1816 }
1817 if (n > 0) {
1818 fp = (samFile**)calloc(n, sizeof(samFile*));
1819 if (!fp) goto mem_fail;
1820 }
1821 heap = (heap1_t*)calloc(heap_size, sizeof(heap1_t));
1822 if (!heap) goto mem_fail;
1823
1824 // Make sure that there's enough memory for template coordinate keys, one per file to read
1825 if (keys && keys->n + n >= keys->m * keys->buffer_size) {
1826 if (template_coordinate_keys_realloc(keys, keys->n + n) < 0) goto mem_fail;
1827 }
1828
1829 // Open each file, read the header and put the first read into the heap
1830 for (i = 0; i < heap_size; i++) {
1831 sam_hdr_t *hin;
1832 heap1_t *h = &heap[i];
1833
1834 if (i < n) {
1835 fp[i] = sam_open_format(fn[i], "r", in_fmt);
1836 if (fp[i] == NULL) {
1837 print_error_errno(cmd, "fail to open \"%s\"", fn[i]);
1838 goto fail;
1839 }
1840 hts_set_opt(fp[i], HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
1841 if (htspool->pool)
1842 hts_set_opt(fp[i], HTS_OPT_THREAD_POOL, htspool);
1843
1844 // Read header ...
1845 hin = sam_hdr_read(fp[i]);
1846 if (hin == NULL) {
1847 print_error(cmd, "failed to read header from \"%s\"", fn[i]);
1848 goto fail;
1849 }
1850 // ... and throw it away as we don't really need it
1851 sam_hdr_destroy(hin);
1852 }
1853
1854 // Get a read into the heap
1855 h->i = i;
1856 h->entry.u.tag = NULL;
1857 h->entry.u.key = NULL;
1858 if (i < n) {
1859 h->entry.bam_record = bam_init1();
1860 if (!h->entry.bam_record) goto mem_fail;
1861 }
1862 if (heap_add_read(h, n, fp, num_in_mem, in_mem, buf, keys, &idx, hout,
1863 lib_lookup) < 0) {
1864 assert(i < n);
1865 print_error(cmd, "failed to read first record from \"%s\"", fn[i]);
1866 goto fail;
1867 }
1868 }
1869
1870 // Open output file and write header
1871 if ((fpout = sam_open_format(out, mode, out_fmt)) == 0) {
1872 print_error_errno(cmd, "failed to create \"%s\"", out);
1873 return -1;
1874 }
1875 hts_set_opt(fpout, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
1876
1877 if (!no_pg && sam_hdr_add_pg(hout, "samtools",
1878 "VN", samtools_version(),
1879 arg_list ? "CL": NULL,
1880 arg_list ? arg_list : NULL,
1881 NULL)) {
1882 print_error(cmd, "failed to add PG line to the header of \"%s\"", out);
1883 sam_close(fpout);
1884 return -1;
1885 }
1886
1887 if (htspool->pool)
1888 hts_set_opt(fpout, HTS_OPT_THREAD_POOL, htspool);
1889
1890 if (sam_hdr_write(fpout, hout) != 0) {
1891 print_error_errno(cmd, "failed to write header to \"%s\"", out);
1892 sam_close(fpout);
1893 return -1;
1894 }
1895
1896 if (write_index) {
1897 if (!(out_idx_fn = auto_index(fpout, out, hout))){
1898 sam_close(fpout);
1899 return -1;
1900 }
1901 }
1902
1903 // Now do the merge
1904 ks_heapmake(heap, heap_size, heap);
1905 while (heap->pos != HEAP_EMPTY) {
1906 bam1_t *b = heap->entry.bam_record;
1907 if (g_sam_order == MinHash && b->core.tid == -1 && final_out) {
1908 // Remove the cached minhash value
1909 b->core.pos = -1;
1910 b->core.mpos = -1;
1911 b->core.isize = 0;
1912 }
1913 if (sam_write1(fpout, hout, b) < 0) {
1914 print_error_errno(cmd, "failed writing to \"%s\"", out);
1915 goto fail;
1916 }
1917 if (heap_add_read(heap, n, fp, num_in_mem, in_mem, buf, keys, &idx,
1918 hout, lib_lookup) < 0) {
1919 assert(heap->i < n);
1920 print_error(cmd, "Error reading \"%s\" : %s",
1921 fn[heap->i], strerror(errno));
1922 goto fail;
1923 }
1924 ks_heapadjust(heap, 0, heap_size, heap);
1925 }
1926 // Clean up and close
1927 for (i = 0; i < n; i++) {
1928 if (sam_close(fp[i]) != 0) {
1929 print_error(cmd, "Error on closing \"%s\" : %s",
1930 fn[i], strerror(errno));
1931 }
1932 }
1933 free(fp);
1934 free(heap);
1935
1936 if (write_index) {
1937 if (sam_idx_save(fpout) < 0) {
1938 print_error_errno("merge", "writing index failed");
1939 goto fail;
1940 }
1941 free(out_idx_fn);
1942 }
1943
1944 if (sam_close(fpout) < 0) {
1945 print_error_errno(cmd, "error closing output file \"%s\"", out);
1946 return -1;
1947 }
1948 return 0;
1949 mem_fail:
1950 print_error(cmd, "Out of memory");
1951
1952 fail:
1953 for (i = 0; i < n; i++) {
1954 if (fp && fp[i]) sam_close(fp[i]);
1955 }
1956 for (i = 0; i < heap_size; i++) {
1957 if (heap && heap[i].i < n && heap[i].entry.bam_record)
1958 bam_destroy1(heap[i].entry.bam_record);
1959 }
1960 free(fp);
1961 free(heap);
1962 if (fpout) sam_close(fpout);
1963 free(out_idx_fn);
1964 return -1;
1965 }
1966
1967 // Function to compare reads and determine which one is < or > the other
1968 // Handle sort-by-pos and sort-by-name. Used as the secondary sort in bam1_lt_by_tag, if reads are equivalent by tag.
1969 // Returns a value less than, equal to or greater than zero if a is less than,
1970 // equal to or greater than b, respectively.
1971 static inline int bam1_cmp_core(const bam1_tag a, const bam1_tag b)
1972 {
1973 uint64_t pa, pb;
1974 if (!a.bam_record) return 1;
1975 if (!b.bam_record) return 0;
1976
1977 if (g_sam_order == QueryName || g_sam_order == TagQueryName) {
1978 int t = strnum_cmp(bam_get_qname(a.bam_record), bam_get_qname(b.bam_record));
1979 if (t != 0) return t;
1980 int af = a.bam_record->core.flag;
1981 int bf = b.bam_record->core.flag;
1982 // Sort order is READ1, READ2, (PRIMARY), SUPPLEMENTARY, SECONDARY
1983 // Get the bits in this order so sort is a natural a-b
1984 af = ((af&0xc0)<<8)|((af&0x100)<<3)|((af&0x800)>>3);
1985 bf = ((bf&0xc0)<<8)|((bf&0x100)<<3)|((bf&0x800)>>3);
1986 return af - bf;
1987 } else {
1988 pa = a.bam_record->core.tid;
1989 pb = b.bam_record->core.tid;
1990
1991 if (pa == pb) {
1992 pa = (uint64_t)(a.bam_record->core.pos+1);
1993 pb = (uint64_t)(b.bam_record->core.pos+1);
1994 }
1995
1996 if (pa == pb) {
1997 pa = bam_is_rev(a.bam_record);
1998 pb = bam_is_rev(b.bam_record);
1999 }
2000
2001 return pa < pb ? -1 : (pa > pb ? 1 : 0);
2002 }
2003 }
2004
2005 uint8_t normalize_type(const uint8_t* aux) {
2006 if (*aux == 'c' || *aux == 'C' || *aux == 's' || *aux == 'S' || *aux == 'i' || *aux == 'I') {
2007 return 'c';
2008 } else if (*aux == 'f' || *aux == 'd') {
2009 return 'f';
2010 } else if (*aux == 'H' || *aux == 'Z') {
2011 return 'H';
2012 } else {
2013 return *aux;
2014 }
2015 }
2016
2017 // Sort record by tag, using pos or read name as a secondary key if tags are identical. Reads not carrying the tag sort first.
2018 // Tags are first sorted by the type character (in case the types differ), or by the appropriate comparator for that type if they agree.
2019 // Returns a value less than, equal to or greater than zero if a is less than,
2020 // equal to or greater than b, respectively.
2021 static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b)
2022 {
2023 const uint8_t* aux_a = a.u.tag;
2024 const uint8_t* aux_b = b.u.tag;
2025
2026 if (aux_a == NULL && aux_b != NULL) {
2027 return -1;
2028 } else if (aux_a != NULL && aux_b == NULL) {
2029 return 1;
2030 } else if (aux_a == NULL && aux_b == NULL) {
2031 return bam1_cmp_core(a,b);
2032 }
2033
2034 // 'Normalize' the letters of the datatypes to a canonical letter,
2035 // so that comparison of different types
2036 // forms a correct total ordering.
2037 uint8_t a_type = normalize_type(aux_a);
2038 uint8_t b_type = normalize_type(aux_b);
2039
2040 if (a_type != b_type) {
2041 // Fix int to float comparisons by using bam_aux2f() to read the int
2042 if (a_type == 'c' && b_type == 'f') {
2043 a_type = 'f';
2044 } else if (a_type == 'f' && b_type == 'c') {
2045 b_type = 'f';
2046 } else {
2047 // Unfixable mismatched types
2048 return a_type < b_type ? -1 : 1;
2049 }
2050 }
2051
2052 if (a_type == 'c') {
2053 int64_t va = bam_aux2i(aux_a);
2054 int64_t vb = bam_aux2i(aux_b);
2055 if (va != vb) return va < vb ? -1 : 1;
2056 return bam1_cmp_core(a, b);
2057 } else if (a_type == 'f') {
2058 double va = bam_aux2f(aux_a);
2059 double vb = bam_aux2f(aux_b);
2060 if (va != vb) return va < vb ? -1 : 1;
2061 return bam1_cmp_core(a, b);
2062 } else if (a_type == 'A') {
2063 unsigned char va = bam_aux2A(aux_a);
2064 unsigned char vb = bam_aux2A(aux_b);
2065 if (va != vb) return va < vb ? -1 : 1;
2066 return bam1_cmp_core(a, b);
2067 } else if (a_type == 'H') {
2068 int t = strcmp(bam_aux2Z(aux_a), bam_aux2Z(aux_b));
2069 if (t) return t;
2070 return bam1_cmp_core(a, b);
2071 } else {
2072 return bam1_cmp_core(a,b);
2073 }
2074 }
2075
2076 // Sort by minimiser (stored in bam1_tag.u.pos).
2077 // If equal, sort by position.
2078 //
2079 // The 64-bit sort key is split over the bam pos and isize fields.
2080 // This permits it to survive writing to temporary file and coming back.
2081
2082 #ifdef DEBUG_MINHASH
2083 static int ntot = 0, nmis = 0, ndup = 0;
2084 #endif
2085
2086 static inline int bam1_cmp_by_minhash(const bam1_tag a, const bam1_tag b)
2087 {
2088 const bam1_t *A = a.bam_record;
2089 const bam1_t *B = b.bam_record;
2090
2091 if (!A) return 1;
2092 if (!B) return 0;
2093
2094 if (A->core.tid != -1 || B->core.tid != -1) return bam1_cmp_core(a,b);
2095
2096 const uint64_t m_a = (((uint64_t)A->core.pos)<<31)|(uint32_t)A->core.mpos;
2097 const uint64_t m_b = (((uint64_t)B->core.pos)<<31)|(uint32_t)B->core.mpos;
2098
2099 if (m_a < m_b) // by hash
2100 return -1;
2101 else if (m_a > m_b)
2102 return 1;
2103
2104 // Bigger pos with size minhash means starts further to left
2105 else if (A->core.isize > B->core.isize) // by hash location in seq
2106 return -1;
2107 else if (A->core.isize < B->core.isize)
2108 return 1;
2109 else
2110 return bam1_cmp_core(a,b);
2111 }
2112
2113 // compares to molecular identifiers, ignoring any trailing slash and subsequent single-character
2114 // * if mid1 is less than mid2, then -1 will be returned
2115 // * if mid1 is greater than mid2, then 1 will be returned
2116 static inline int template_coordinate_key_compare_mid(const char* mid1, const char* mid2) {
2117 size_t i = 0;
2118 size_t len1 = strlen(mid1);
2119 size_t len2 = strlen(mid2);
2120 size_t shortest;
2121
2122 // Snip off trailing slash followed by a single character, if present
2123 if (len1 >= 2 && mid1[len1-2] == '/') len1 -= 2;
2124 if (len2 >= 2 && mid2[len2-2] == '/') len2 -= 2;
2125 shortest = len1 < len2 ? len1 : len2;
2126
2127 // find first mismatching character
2128 while (i < shortest && mid1[i] == mid2[i]) i++;
2129
2130 // compare last characters
2131 if (i == len1 && i < len2) return -1; // mid1 shorter
2132 if (i == len2 && i < len1) return 1; // mid2 shorter
2133 if (i == len1 && i == len2) return 0; // all characters match
2134 if (mid1[i] < mid2[i]) return -1; // mid1 earlier
2135 else return 1;
2136 }
2137
2138
2139 // Builds a key use to sort in TemplateCoordinate order. Returns NULL if the key could not be created (e.g. MC
2140 // tag is missing), otherwise the pointer to the provided key.
2141 static template_coordinate_key_t* template_coordinate_key(bam1_t *b, template_coordinate_key_t *key, sam_hdr_t *hdr, khash_t(const_c2c) *lib_lookup) {
2142 uint8_t *data;
2143 char *rg;
2144 khiter_t k;
2145
2146 // defaults
2147 key->tid1 = key->tid2 = INT32_MAX;
2148 key->pos1 = key->pos2 = HTS_POS_MAX;
2149 key->neg1 = key->neg2 = false;
2150 key->mid = "";
2151
2152 // update values
2153 rg = (char *)bam_aux_get(b, "RG");
2154 if (rg && rg[0] == 'Z'
2155 &&(k = kh_get(const_c2c, lib_lookup, rg + 1)) < kh_end(lib_lookup)) {
2156 key->library = kh_value(lib_lookup, k);
2157 } else {
2158 key->library = "";
2159 }
2160 key->name = bam_get_qname(b);
2161 if (!(b->core.flag & BAM_FUNMAP)) { // read is mapped, update coordinates
2162 key->tid1 = b->core.tid;
2163 key->neg1 = bam_is_rev(b);
2164 key->pos1 = (key->neg1) ? unclipped_end(b) : unclipped_start(b);
2165 }
2166 if (b->core.flag & BAM_FPAIRED && !(b->core.flag & BAM_FMUNMAP)) { // mate is mapped, update coordinates
2167 char *cigar;
2168 if ((data = bam_aux_get(b, "MC"))) {
2169 if (!(cigar = bam_aux2Z(data))) {
2170 fprintf(stderr, "[bam_sort] error: MC tag wrong type. Please use the MC tag provided by samtools fixmate.\n");
2171 return NULL;
2172 }
2173 } else {
2174 fprintf(stderr, "[bam_sort] error: no MC tag. Please run samtools fixmate on file first.\n");
2175 return NULL;
2176 }
2177 key->tid2 = b->core.mtid;
2178 key->neg2 = bam_is_mrev(b);
2179 key->pos2 = (key->neg2) ? unclipped_other_end(b->core.mpos, cigar) : unclipped_other_start(b->core.mpos, cigar);
2180 }
2181
2182 if ((data = bam_aux_get(b, "MI"))) {
2183 if (!(key->mid=bam_aux2Z(data))) {
2184 fprintf(stderr, "[bam_sort] error: MI tag wrong type (not a string).\n");
2185 return NULL;
2186 }
2187 }
2188
2189 // set is_upper_of_pair, and swap if we get the same key regardless of which end
2190 // of the pair it is
2191 if (key->tid1 < key->tid2
2192 || (key->tid1 == key->tid2 && key->pos1 < key->pos2)
2193 || (key->tid1 == key->tid2 && key->pos1 == key->pos2 && !key->neg1)) {
2194 key->is_upper_of_pair = false;
2195 } else {
2196 key->is_upper_of_pair = true;
2197 // swap
2198 int tmp_tid;
2199 hts_pos_t tmp_pos;
2200 bool tmp_neg;
2201 tmp_tid = key->tid1;
2202 key->tid1 = key->tid2;
2203 key->tid2 = tmp_tid;
2204 tmp_pos = key->pos1;
2205 key->pos1 = key->pos2;
2206 key->pos2 = tmp_pos;
2207 tmp_neg = key->neg1;
2208 key->neg1 = key->neg2;
2209 key->neg2 = tmp_neg;
2210 }
2211
2212 return key;
2213 }
2214
2215 // Function to compare reads and determine which one is < or > the other
2216 // Handles template-coordinate, which sorts by:
2217 // 1. the earlier unclipped 5' coordinate of the read pair
2218 // 2. the higher unclipped 5' coordinate of the read pair
2219 // 3. library (from read group)
2220 // 4. the molecular identifier (if present)
2221 // 5. read name
2222 // 6. if unpaired, or if R1 has the lower coordinates of the pair
2223 // Returns a value less than, equal to or greater than zero if a is less than,
2224 // equal to or greater than b, respectively.
2225 static inline int bam1_cmp_template_coordinate(const bam1_tag a, const bam1_tag b)
2226 {
2227 if (!a.bam_record) return 1;
2228 if (!b.bam_record) return 0;
2229
2230 const template_coordinate_key_t* key_a = a.u.key;
2231 const template_coordinate_key_t* key_b = b.u.key;
2232
2233 int retval = 0;
2234 if (0 == retval) retval = key_a->tid1 - key_b->tid1;
2235 if (0 == retval) retval = key_a->tid2 - key_b->tid2;
2236 if (0 == retval) retval = key_a->pos1 < key_b->pos1 ? -1 : (key_a->pos1 > key_b->pos1 ? 1 : 0);
2237 if (0 == retval) retval = key_a->pos2 < key_b->pos2 ? -1 : (key_a->pos2 > key_b->pos2 ? 1 : 0);
2238 if (0 == retval) retval = key_a->neg1 == key_b->neg1 ? 0 : (key_a->neg1 ? -1 : 1);
2239 if (0 == retval) retval = key_a->neg2 == key_b->neg2 ? 0 : (key_a->neg2 ? -1 : 1);
2240 if (0 == retval) retval = strcmp(key_a->library, key_b->library);
2241 if (0 == retval) retval = template_coordinate_key_compare_mid(key_a->mid, key_b->mid);
2242 if (0 == retval) retval = strcmp(key_a->name, key_b->name);
2243 if (0 == retval) retval = key_a->is_upper_of_pair == key_b->is_upper_of_pair ? 0 : (key_a->is_upper_of_pair ? 1 : -1);
2244 return retval < 0 ? -1 : (retval > 0 ? 1 : 0);
2245 }
2246
2247
2248 // Function to compare reads and determine which one is < the other
2249 // Handle sort-by-pos, sort-by-name, sort-by-tag, or sort-by-template-coordinate.
2250 static inline int bam1_lt(const bam1_tag a, const bam1_tag b)
2251 {
2252 switch (g_sam_order) {
2253 case Coordinate:
2254 case QueryName:
2255 return bam1_cmp_core(a, b) < 0;
2256 case TagQueryName:
2257 case TagCoordinate:
2258 return bam1_cmp_by_tag(a, b) < 0;
2259 case MinHash:
2260 return bam1_cmp_by_minhash(a, b) < 0;
2261 case TemplateCoordinate:
2262 return bam1_cmp_template_coordinate(a, b) < 0;
2263 default:
2264 return bam1_cmp_core(a,b) < 0;
2265 }
2266 }
2267
2268
2269
2270 KSORT_INIT(sort, bam1_tag, bam1_lt)
2271
2272 typedef struct {
2273 size_t buf_len;
2274 bam1_tag *buf;
2275 const sam_hdr_t *h;
2276 int error;
2277 int large_pos;
2278 int minimiser_kmer;
2279 bool try_rev;
2280 bool no_squash;
2281 } worker_t;
2282
2283 // Returns 0 for success
2284 // -1 for failure
2285 static int write_buffer(const char *fn, const char *mode, size_t l, bam1_tag *buf,
2286 const sam_hdr_t *h, int n_threads, const htsFormat *fmt,
2287 int clear_minhash, char *arg_list, int no_pg, int write_index)
2288 {
2289 size_t i;
2290 samFile* fp;
2291 char *out_idx_fn = NULL;
2292
2293 fp = sam_open_format(fn, mode, fmt);
2294 if (fp == NULL) return -1;
2295 hts_set_opt(fp, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
2296 if (!no_pg && sam_hdr_add_pg((sam_hdr_t *)h, "samtools", "VN", samtools_version(),
2297 arg_list ? "CL": NULL,
2298 arg_list ? arg_list : NULL,
2299 NULL)) {
2300 goto fail;
2301 }
2302 if (sam_hdr_write(fp, h) != 0) goto fail;
2303
2304 if (write_index)
2305 if (!(out_idx_fn = auto_index(fp, fn, (sam_hdr_t *)h))) goto fail;
2306
2307 if (n_threads > 1) hts_set_threads(fp, n_threads);
2308 for (i = 0; i < l; ++i) {
2309 bam1_t *b = buf[i].bam_record;
2310 if (clear_minhash && b->core.tid == -1) {
2311 // To see the position for debugging
2312 // b->core.pos = ((((uint64_t)b->core.pos)<<31)|(uint32_t)b->core.mpos) + b->core.isize;
2313 // Remove the cached minhash value
2314 b->core.pos = -1;
2315 b->core.mpos = -1;
2316 b->core.isize = 0;
2317 }
2318 if (sam_write1(fp, h, b) < 0) goto fail;
2319 }
2320
2321 if (write_index) {
2322 if (sam_idx_save(fp) < 0) {
2323 print_error_errno("merge", "writing index failed");
2324 goto fail;
2325 }
2326 free(out_idx_fn);
2327 }
2328
2329
2330 if (sam_close(fp) < 0) return -1;
2331 return 0;
2332 fail:
2333 sam_close(fp);
2334 free(out_idx_fn);
2335 return -1;
2336 }
2337
2338 #define NUMBASE 256
2339
2340 static int ks_radixsort(size_t n, bam1_tag *buf, const sam_hdr_t *h)
2341 {
2342 int curr = 0, ret = -1;
2343 ssize_t i;
2344 bam1_tag *buf_ar2[2], *bam_a, *bam_b;
2345 uint64_t max_pos = 1;
2346 uint32_t max_tid = 1, tid_bytes = 0, pos_bytes = 0, byte = 0;
2347 uint32_t tid_shift_l, tid_shift_r;
2348 int nref = sam_hdr_nref(h);
2349
2350 // Count number of bytes needed for biggest tid and pos
2351 // Notes: Add 1 to core.pos so always positive.
2352 // Convert unmapped tid (-1) to number of references so unmapped
2353 // sort to the end.
2354 for (i = 0; i < n; i++) {
2355 bam1_t *b = buf[i].bam_record;
2356 uint32_t tid = b->core.tid == -1 ? nref : b->core.tid;
2357 uint64_t pos = ((uint64_t)(b->core.pos + 1) << 1) | bam_is_rev(b);
2358 if (max_tid < tid)
2359 max_tid = tid;
2360 if (max_pos < pos)
2361 max_pos = pos;
2362 }
2363
2364 for (; max_pos > 0; max_pos >>= 8) pos_bytes++;
2365 for (; max_tid > 0; max_tid >>= 8) tid_bytes++;
2366 assert(pos_bytes + tid_bytes < sizeof(buf[0].u.pos_tid));
2367
2368 tid_shift_l = pos_bytes * 8;
2369 tid_shift_r = 64 - tid_shift_l;
2370
2371 // Write position and tid into bam1_tag::u::pos_tid using minimum number
2372 // of bytes required. Values are stored little-endian so that we
2373 // get a least-significant digit (byte) radix sort.
2374 for (i = 0; i < n; i++) {
2375 bam1_t *b = buf[i].bam_record;
2376 uint32_t tid = b->core.tid == -1 ? nref : b->core.tid;
2377 // 'pos' here includes as many bytes of tid as will fit
2378 // in the space remaining above pos_bytes. The rest of tid
2379 // is written out separately.
2380 uint64_t pos = (bam_is_rev(b) |
2381 ((uint64_t)(b->core.pos + 1) << 1) |
2382 (tid_shift_l < 64 ? (uint64_t) tid << tid_shift_l : 0));
2383 u64_to_le(pos, buf[i].u.pos_tid);
2384 u32_to_le(tid_shift_r < 32 ? tid >> tid_shift_r : 0,
2385 &buf[i].u.pos_tid[8]);
2386 }
2387
2388 buf_ar2[0] = buf;
2389 buf_ar2[1] = (bam1_tag *)malloc(sizeof(bam1_tag) * n);
2390 if (buf_ar2[1] == NULL) {
2391 print_error("sort", "couldn't allocate memory for temporary buf");
2392 goto err;
2393 }
2394
2395 // Least-significant digit radix sort (where "digits" are bytes)
2396 for (byte = 0; byte < pos_bytes + tid_bytes; byte++) {
2397 size_t remainders[NUMBASE] = { 0 };
2398 bam_a = buf_ar2[curr]; bam_b = buf_ar2[1-curr];
2399 for (i = 0; i < n; ++i)
2400 remainders[bam_a[i].u.pos_tid[byte]]++;
2401 for (i = 1; i < NUMBASE; ++i)
2402 remainders[i] += remainders[i - 1];
2403 for (i = n - 1; i >= 0; i--) {
2404 size_t j = --remainders[bam_a[i].u.pos_tid[byte]];
2405 bam_b[j] = bam_a[i];
2406 }
2407 curr = 1 - curr;
2408 }
2409 if (curr == 1) {
2410 bam1_tag *end = buf + n;
2411 bam_a = buf_ar2[0]; bam_b = buf_ar2[1];
2412 while (bam_a < end) *bam_a++ = *bam_b++;
2413 }
2414
2415 ret = 0;
2416 err:
2417 free(buf_ar2[1]);
2418 return ret;
2419 }
2420
2421 KHASH_MAP_INIT_INT64(kmer, int64_t)
2422 static khash_t(kmer) *kmer_h = NULL;
2423
2424 // Punt homopolymers somewhere central in the hash space
2425 #define XOR 0xdead7878beef7878
2426
2427 /*
2428 * Computes the minhash of a sequence using forward strand and if requested
2429 * reverse strand.
2430 *
2431 * This is used as a sort key for unmapped data, to collate like sequences
2432 * together and to improve compression ratio.
2433 *
2434 * The minhash is returned and *pos filled out with location of this hash
2435 * key in the sequence if pos != NULL.
2436 */
2437 static uint64_t minhash(bam1_t *b, int kmer, int window, int *curr_pos,
2438 int *end, int *is_rev, int try_fwd, int try_rev,
2439 int no_squash) {
2440 uint64_t hashf = 0, minhashf = UINT64_MAX;
2441 int minhashpf = *curr_pos, i, j;
2442 uint64_t mask = (1L<<(2*kmer))-1;
2443 uint8_t *seq = bam_get_seq(b);
2444 int len = b->core.l_qseq;
2445 uint64_t xor = XOR & mask;
2446
2447 if (is_rev) *is_rev = 0;
2448
2449 // Lookup tables for bam_seqi to 0123 fwd/rev hashes
2450 // =ACM GRSV TWYH KDBN
2451 #define X 0
2452 static unsigned char L[16] = {
2453 X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X,
2454 };
2455 uint64_t R[16] = {
2456 X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X,
2457 };
2458 for (i = 0; i < 16; i++)
2459 R[i] <<= 2*(kmer-1);
2460
2461 int i_start = *curr_pos;
2462 int i_end = MIN(i_start + window, len);
2463 int last_base = -1;
2464
2465 if (try_fwd) {
2466 // Initialise hash keys
2467 for (i = i_start, j = 0; j < kmer-1 && i < i_end; i++) {
2468 int base = bam_seqi(seq, i);
2469 // collapse homopolymers
2470 if (no_squash || last_base != base) {
2471 last_base = base;
2472 hashf = (hashf<<2) | L[base];
2473 j++;
2474 }
2475 }
2476
2477 // Loop to find minimum
2478 if (no_squash) {
2479 for (; i < i_end; i++) {
2480 int base = bam_seqi(seq, i);
2481 hashf = (hashf<<2) | L[base];
2482 uint64_t hashfx = (hashf ^ XOR) & mask;
2483 if (minhashf > hashfx)
2484 minhashf = hashfx, minhashpf = i;
2485 }
2486 } else {
2487 for (; i < i_end; i++) {
2488 int base = bam_seqi(seq, i);
2489 if (last_base != base) {
2490 last_base = base;
2491 hashf = (hashf<<2) | L[base];
2492 uint64_t hashfx = (hashf ^ XOR) & mask;
2493 if (minhashf > hashfx)
2494 minhashf = hashfx, minhashpf = i;
2495 }
2496 }
2497 }
2498 }
2499
2500 // Same as above for the reverse strand.
2501 // Not used for now, but we may wish to consider indexing in both
2502 // strands, recording the strand in value (pos), and comparing in one
2503 // strand only. Right now we compare on both against a single-stranded
2504 // index.
2505 if (try_rev) {
2506 uint64_t hashr = 0, minhashr = UINT64_MAX;
2507 int minhashpr = *curr_pos;
2508 int last_base = -1;
2509
2510 for (i = i_start, j = 0; j < kmer-1 && i < len; i++) {
2511 int base = bam_seqi(seq, i);
2512 if (no_squash || last_base != base) {
2513 last_base = base;
2514 hashr = (hashr>>2) | R[base];
2515 j++;
2516 }
2517 }
2518
2519 if (no_squash) {
2520 for (; i < i_end; i++) {
2521 int base = bam_seqi(seq, i);
2522 hashr = (hashr>>2) | R[base];
2523 if (minhashr > (hashr^xor))
2524 minhashr = (hashr^xor), minhashpr = len-i+kmer-2;
2525 }
2526 } else {
2527 for (; i < i_end; i++) {
2528 int base = bam_seqi(seq, i);
2529 if (last_base != base) {
2530 last_base = base;
2531 hashr = (hashr>>2) | R[base];
2532 if (minhashr > (hashr^xor))
2533 minhashr = (hashr^xor), minhashpr = len-i+kmer-2;
2534 }
2535 }
2536 }
2537
2538 if (minhashr < minhashf) {
2539 minhashf = minhashr;
2540 minhashpf = minhashpr;
2541 if (is_rev) *is_rev = 1;
2542 }
2543 }
2544
2545 // "*curr_pos = minhashpf" is faster here, but is sometimes
2546 // poorer in compression. Eg 10 million novaseq records with
2547 // 75.1MB vs 76.9MB cram BA field.
2548 //*curr_pos = minhashpf;
2549 *curr_pos = minhashpf - (kmer-1);
2550 if (end) *end = (i_end == len);
2551 return minhashf;
2552 }
2553
2554 #define UNIQ_BIT 60
2555 #define UNIQ_TEST(x) (((x) & (1ULL<<UNIQ_BIT))==0)
2556 #define UNIQ_MASK ((1ULL<<UNIQ_BIT)-1)
2557 static int build_minhash_index(char *fn, int kmer, int window, int no_squash) {
2558 int ret = 1;
2559 samFile *in;
2560 sam_hdr_t *h = NULL;
2561 bam1_t *b = NULL;
2562
2563 in = sam_open(fn, "r");
2564 if (!in) {
2565 perror(fn);
2566 return 1;
2567 }
2568
2569 kmer_h = kh_init(kmer);
2570 if (!kmer_h)
2571 goto err;
2572
2573 if (!(h = sam_hdr_read(in)))
2574 goto err;
2575
2576 if (!(b = bam_init1()))
2577 goto err;
2578
2579 int r;
2580 uint64_t tpos = 0;
2581 while ((r = sam_read1(in, h, b)) >= 0) {
2582 //fprintf(stderr, "LEN\t%d\t%s\n", b->core.l_qseq, bam_get_qname(b));
2583 uint64_t hashf;
2584 int pos = 0, end = 0;
2585 khiter_t k;
2586 int ret;
2587
2588 if (b->core.l_qseq < window)
2589 continue;
2590
2591 // fwd
2592 while (!end) {
2593 int last_pos = pos;
2594 hashf = minhash(b, kmer, window, &pos, &end, NULL, 1, 0,
2595 no_squash);
2596 k = kh_put(kmer, kmer_h, hashf, &ret);
2597 kh_value(kmer_h, k) = tpos+pos + (((uint64_t)!ret)<<UNIQ_BIT);
2598 pos = MAX(last_pos+kmer, pos+1);
2599 //pos++; Slower, but indexes a bit better?
2600 }
2601 tpos += b->core.l_qseq;
2602
2603 // We could also add reverse keys to the index here.
2604 // This would avoid reverse complementing during the matching stage.
2605 // We'd need to add a flag (another high bit of kh_value) to indicate
2606 // strand.
2607 // I'm unsure if this is a good trade-off or not.
2608
2609 // // rev
2610 // pos = 0; end = 0;
2611 // while (!end) {
2612 // hashf = minhash(b, kmer, window, &pos, &end, NULL, 0, 1,
2613 // no_squash);
2614 // k = kh_put(kmer, kmer_h, hashf, &ret);
2615 // kh_value(kmer_h, k) = tpos+pos + (((uint64_t)!ret)<<UNIQ_BIT);
2616 // pos++;
2617 // }
2618 //
2619 // tpos += b->core.l_qseq;
2620 }
2621 if (r < -1)
2622 goto err;
2623
2624 ret = 0;
2625 err:
2626 if (b) bam_destroy1(b);
2627 if (h) sam_hdr_destroy(h);
2628 sam_close(in);
2629
2630 return ret;
2631 }
2632
2633 /*
2634 * A variant of minhash that compares against a previously built index.
2635 *
2636 * We follow the same steps of scanning through this sequence to find the
2637 * minimum hash, but we prefer hash keys that have unique placement in the
2638 * index, or if not unique, then non-uniquely placed, over ones that
2639 * are absent from the index.
2640 */
2641 static uint64_t minhash_with_idx(bam1_t *b, int kmer, int *pos, int *rev,
2642 bool try_rev) {
2643 uint64_t hashf = 0, minhashf = UINT64_MAX, minhashfi = UINT64_MAX;
2644 uint64_t minhashfd = UINT64_MAX;
2645 int minhashpf = 0, minhashpfi = 0, minhashpfd = 0, i, j;
2646 uint64_t mask = (1L<<(2*kmer))-1;
2647 unsigned char *seq = bam_get_seq(b);
2648 int len = b->core.l_qseq;
2649 const uint64_t xor = XOR & mask;
2650
2651 // Lookup tables for bam_seqi to 0123 fwd/rev hashes
2652 // =ACM GRSV TWYH KDBN
2653 #define X 0
2654 unsigned char L[16] = {
2655 X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X,
2656 };
2657 uint64_t R[16] = {
2658 X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X,
2659 };
2660 for (i = 0; i < 16; i++)
2661 R[i] <<= 2*(kmer-1);
2662
2663 // Initialise hash keys
2664 for (i = j = 0; j < kmer-1 && i < len; i++, j++) {
2665 int base = bam_seqi(seq, i);
2666 hashf = (hashf<<2) | L[base];
2667 }
2668
2669 // Loop to find minimum
2670 int found_f = 0, found_r = 0;
2671 for (; i < len; i++) {
2672 int base = bam_seqi(seq, i);
2673 hashf = ((hashf<<2) | L[base]) & mask;
2674 const uint64_t hashfx = hashf^xor;
2675
2676 // Priority for sorting
2677 // 1. Unique key in index
2678 // 2. Dup key in index
2679 // 3. Everything else
2680 int index = 0;
2681 if (minhashfi > hashfx || (found_f < 2 && minhashfd > hashfx)) {
2682 khiter_t k = kh_get(kmer, kmer_h, hashfx);
2683 if (k != kh_end(kmer_h))
2684 index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1;
2685 }
2686 found_f |= index;
2687 switch (index) {
2688 case 2: minhashfi = hashfx, minhashpfi = i; break;
2689 case 1: minhashfd = hashfx, minhashpfd = i; break;
2690
2691 default:
2692 if (minhashf > hashfx)
2693 minhashf = hashfx, minhashpf = i;
2694 }
2695 }
2696
2697 if (minhashfi != UINT64_MAX)
2698 minhashf = minhashfi, minhashpf = minhashpfi;
2699 else if (minhashfd != UINT64_MAX)
2700 minhashf = minhashfd, minhashpf = minhashpfd;
2701
2702 // Same as above for the reverse strand
2703 int dir = 0;
2704 if (try_rev) {
2705 uint64_t hashr = 0, minhashr = UINT64_MAX, minhashri = UINT64_MAX;
2706 uint64_t minhashrd = UINT64_MAX;
2707 int minhashpr = 0, minhashpri = 0, minhashprd = 0;
2708
2709 for (i = j = 0; j < kmer-1 && i < len; i++, j++) {
2710 int base = bam_seqi(seq, i);
2711 hashr = (hashr>>2) | R[base];
2712 }
2713 for (; i < len; i++) {
2714 int base = bam_seqi(seq, i);
2715 hashr = (hashr>>2) | R[base];
2716 const uint64_t hashrx = hashr^xor;
2717
2718 int index = 0;
2719 if (minhashri > hashrx || (found_r < 2 && minhashrd > hashrx)) {
2720 khiter_t k = kh_get(kmer, kmer_h, hashrx);
2721 if (k != kh_end(kmer_h))
2722 index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1;
2723 }
2724 found_r |= index;
2725 switch (index) {
2726 case 2: minhashri = hashrx, minhashpri = i; break;
2727 case 1: minhashrd = hashrx, minhashprd = i; break;
2728
2729 default:
2730 if (minhashr > hashrx)
2731 minhashr = hashrx, minhashpr = i;
2732 }
2733 }
2734 if (minhashri != UINT64_MAX)
2735 minhashr = minhashri, minhashpr = minhashpri;
2736 else if (minhashrd != UINT64_MAX)
2737 minhashr = minhashrd, minhashpr = minhashprd;
2738
2739 // Pick reverse if better mapping
2740 if ((minhashf > minhashr) || (!found_f && found_r)) {
2741 if (!found_f || found_r) {
2742 minhashf = minhashr;
2743 minhashpf = b->core.l_qseq - minhashpr + kmer - 2;
2744 dir = 1;
2745 }
2746 }
2747 }
2748
2749 #ifdef DEBUG_MINHASH
2750 ntot++;
2751 khiter_t k = kh_get(kmer, kmer_h, minhashf);
2752 if (k != kh_end(kmer_h)) {
2753 if (!UNIQ_TEST(kh_value(kmer_h, k)))
2754 ndup++;
2755 minhashf = kh_value(kmer_h, k) & UNIQ_MASK;
2756 } else {
2757 nmis++;
2758 }
2759 #else
2760 // For indexed kmers, our hash key is the position the kmer
2761 // occurs in the concatenated reference rather than the hash itself.
2762 khiter_t k = kh_get(kmer, kmer_h, minhashf);
2763 if (k != kh_end(kmer_h))
2764 minhashf = kh_value(kmer_h, k) & UNIQ_MASK;
2765 #endif
2766
2767 if (rev) *rev = dir;
2768 if (pos) *pos = minhashpf;
2769
2770 return minhashf != UINT64_MAX ? minhashf : 0;
2771 }
2772
2773 // As per minhash_with_idx but with homopolymer squashing enabled.
2774 // This function is duplicated to remove conditionals and speed up the
2775 // hashing code. (Minus the ifdef-ed out code, which is kept above mainly
2776 // for posterity.)
2777 static uint64_t minhash_with_idx_squash(bam1_t *b, int kmer, int *pos,
2778 int *rev, bool try_rev) {
2779 uint64_t hashf = 0, minhashf = UINT64_MAX, minhashfi = UINT64_MAX;
2780 uint64_t minhashfd = UINT64_MAX;
2781 int minhashpf = 0, minhashpfi = 0, minhashpfd = 0, i, j;
2782 uint64_t mask = (1L<<(2*kmer))-1;
2783 unsigned char *seq = bam_get_seq(b);
2784 int len = b->core.l_qseq;
2785 const uint64_t xor = XOR & mask;
2786
2787 // Lookup tables for bam_seqi to 0123 fwd/rev hashes
2788 // =ACM GRSV TWYH KDBN
2789 #define X 0
2790 unsigned char L[16] = {
2791 X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X,
2792 };
2793 uint64_t R[16] = {
2794 X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X,
2795 };
2796 for (i = 0; i < 16; i++)
2797 R[i] <<= 2*(kmer-1);
2798
2799 // Initialise hash keys
2800 int last_base = -1;
2801 for (i = j = 0; j < kmer-1 && i < len; i++) {
2802 int base = bam_seqi(seq, i);
2803 if (base == last_base)
2804 continue;
2805 last_base = base;
2806 j++;
2807 hashf = (hashf<<2) | L[base];
2808 }
2809
2810 // Loop to find minimum
2811 int found_f = 0, found_r = 0;
2812 for (; i < len; i++) {
2813 int base = bam_seqi(seq, i);
2814 if (base == last_base)
2815 continue;
2816 last_base = base;
2817 hashf = ((hashf<<2) | L[base]) & mask;
2818 const uint64_t hashfx = hashf^xor;
2819
2820 // Priority for sorting
2821 // 1. Unique key in index
2822 // 2. Dup key in index
2823 // 3. Everything else
2824 int index = 0;
2825 if (minhashfi > hashfx || (found_f < 2 && minhashfd > hashfx)) {
2826 khiter_t k = kh_get(kmer, kmer_h, hashfx);
2827 if (k != kh_end(kmer_h))
2828 index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1;
2829 }
2830 found_f |= index;
2831 switch (index) {
2832 case 2: minhashfi = hashfx, minhashpfi = i; break;
2833 case 1: minhashfd = hashfx, minhashpfd = i; break;
2834
2835 default:
2836 if (minhashf > hashfx)
2837 minhashf = hashfx, minhashpf = i;
2838 }
2839 }
2840
2841 if (minhashfi != UINT64_MAX)
2842 minhashf = minhashfi, minhashpf = minhashpfi;
2843 else if (minhashfd != UINT64_MAX)
2844 minhashf = minhashfd, minhashpf = minhashpfd;
2845
2846 // Same as above for the reverse strand
2847 int dir = 0;
2848 if (try_rev) {
2849 uint64_t hashr = 0, minhashr = UINT64_MAX, minhashri = UINT64_MAX;
2850 uint64_t minhashrd = UINT64_MAX;
2851 int minhashpr = 0, minhashpri = 0, minhashprd = 0;
2852 int last_base = -1;
2853
2854 for (i = j = 0; j < kmer-1 && i < len; i++) {
2855 int base = bam_seqi(seq, i);
2856 if (base == last_base)
2857 continue;
2858 last_base = base;
2859 j++;
2860 hashr = (hashr>>2) | R[base];
2861 }
2862 for (; i < len; i++) {
2863 int base = bam_seqi(seq, i);
2864 if (base == last_base)
2865 continue;
2866 last_base = base;
2867 hashr = (hashr>>2) | R[base];
2868 const uint64_t hashrx = hashr^xor;
2869
2870 int index = 0;
2871 if (minhashri > hashrx || (found_r < 2 && minhashrd > hashrx)) {
2872 khiter_t k = kh_get(kmer, kmer_h, hashrx);
2873 if (k != kh_end(kmer_h))
2874 index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1;
2875 }
2876 found_r |= index;
2877 switch (index) {
2878 case 2: minhashri = hashrx, minhashpri = i; break;
2879 case 1: minhashrd = hashrx, minhashprd = i; break;
2880
2881 default:
2882 if (minhashr > hashrx)
2883 minhashr = hashrx, minhashpr = i;
2884 }
2885 }
2886 if (minhashri != UINT64_MAX)
2887 minhashr = minhashri, minhashpr = minhashpri;
2888 else if (minhashrd != UINT64_MAX)
2889 minhashr = minhashrd, minhashpr = minhashprd;
2890
2891 // Pick reverse if better mapping
2892 if ((minhashf > minhashr) || (!found_f && found_r)) {
2893 if (!found_f || found_r) {
2894 minhashf = minhashr;
2895 minhashpf = b->core.l_qseq - minhashpr + kmer - 2;
2896 dir = 1;
2897 }
2898 }
2899 }
2900
2901 #ifdef DEBUG_MINHASH
2902 ntot++;
2903 khiter_t k = kh_get(kmer, kmer_h, minhashf);
2904 if (k != kh_end(kmer_h)) {
2905 if (!UNIQ_TEST(kh_value(kmer_h, k)))
2906 ndup++;
2907 minhashf = kh_value(kmer_h, k) & UNIQ_MASK;
2908 } else {
2909 nmis++;
2910 }
2911 #else
2912 // For indexed kmers, our hash key is the position the kmer
2913 // occurs in the concatenated reference rather than the hash itself.
2914 khiter_t k = kh_get(kmer, kmer_h, minhashf);
2915 if (k != kh_end(kmer_h))
2916 minhashf = kh_value(kmer_h, k) & UNIQ_MASK;
2917 #endif
2918
2919 if (rev) *rev = dir;
2920 if (pos) *pos = minhashpf;
2921
2922 return minhashf != UINT64_MAX ? minhashf : 0;
2923 }
2924
2925 //--- Start of candidates to punt to htslib
2926 /*!
2927 * @abstract
2928 * Extracts the sequence (in current alignment orientation) from
2929 * a bam record and places it in buf, which is nul terminated.
2930 *
2931 * @param b The bam structure
2932 * @param buf A buffer at least b->core.l_qseq+1 bytes long
2933 */
2934 static void bam_to_seq(bam1_t *b, char *buf) {
2935 int i;
2936 uint8_t *seq = bam_get_seq(b);
2937 for (i = 0; i < b->core.l_qseq; i++)
2938 buf[i] = seq_nt16_str[bam_seqi(seq, i)];
2939 buf[i] = 0;
2940 }
2941
2942 /*!
2943 * @abstract
2944 * Writes a new sequence, of length b->core.l_qseq, to a BAM record.
2945 *
2946 * If a sequence of a new length is required the caller must first make
2947 * room for it by updating the bam1_t struct.
2948 *
2949 * @param b The bam structure
2950 * @param buf A buffer at least b->core.l_qseq bytes long
2951 */
2952 static void seq_to_bam(bam1_t *b, char *buf) {
2953 int i;
2954 uint8_t *seq = bam_get_seq(b);
2955 for (i = 0; i < b->core.l_qseq; i++)
2956 bam_set_seqi(seq, i, seq_nt16_table[(unsigned char)buf[i]]);
2957 }
2958
2959 /*!
2960 * @abstract Reverse complements a BAM record.
2961 *
2962 * It's possible to do this inline, but complex due to the 4-bit sequence
2963 * encoding. For now I take the dumb approach.
2964 *
2965 * @param b Pointer to a BAM alignment
2966 *
2967 * @return 0 on success, -1 on failure (ENOMEM)
2968 */
2969 static int reverse_complement(bam1_t *b) {
2970 static char comp[256] = {
2971 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//00
2972 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//10
2973 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//20
2974 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//30
2975
2976 // * * * * E F * * I J * L * * O
2977 '@','T','V','G', 'H','E','F','C', 'D','I','H','M', 'L','K','N','O',//40
2978 //P Q * * * * * * X Y Z [ \ ] ^ _
2979 'P','Q','Y','S', 'A','A','B','W', 'X','Y','Z','[','\\','[','^','_',//50
2980 //` * * * * E F * * I J * L * * O
2981 '`','t','v','g', 'h','e','f','c', 'd','i','j','m', 'l','k','n','o',//60
2982 //P Q * * * * * * X Y Z { | } ~ DEL
2983 'p','q','y','s', 'a','a','b','w', 'x','y','z','{', '|','}','~',127,//70
2984
2985 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//80
2986 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//90
2987 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//A0
2988 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//B0
2989
2990 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//C0
2991 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//D0
2992 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//E0
2993 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//F0
2994 };
2995 char seq_[10000], *seq = seq_;
2996 uint8_t *qual = bam_get_qual(b);
2997 int i, j;
2998
2999 if (b->core.l_qseq >= 10000)
3000 if (!(seq = malloc(b->core.l_qseq+1)))
3001 return -1;
3002
3003 bam_to_seq(b, seq);
3004
3005 for (i = 0, j = b->core.l_qseq-1; i < j; i++, j--) {
3006 unsigned char tmp = seq[i];
3007 seq[i] = comp[(unsigned char)seq[j]];
3008 seq[j] = comp[tmp];
3009 tmp = qual[i];
3010 qual[i] = qual[j];
3011 qual[j] = tmp;
3012 }
3013 if (i ==j)
3014 seq[i] = comp[(unsigned char)seq[i]];
3015
3016 seq_to_bam(b, seq);
3017
3018 if (seq != seq_)
3019 free(seq);
3020
3021 b->core.flag ^= 0x10;
3022
3023 return 0;
3024 }
3025 //--- End of candidates to punt to htslib
3026
3027
3028 static inline void worker_minhash(worker_t *w) {
3029 int i;
3030 for (i = 0; i < w->buf_len; i++) {
3031 bam1_t *b = w->buf[i].bam_record;
3032 if (b->core.tid != -1)
3033 continue;
3034
3035 int pos = 0, rev = 0;
3036 uint64_t mh = kmer_h
3037 ? (w->no_squash
3038 ? minhash_with_idx(b, w->minimiser_kmer, &pos, &rev,
3039 w->try_rev)
3040 : minhash_with_idx_squash(b, w->minimiser_kmer, &pos, &rev,
3041 w->try_rev)
3042 )
3043 : minhash(b, w->minimiser_kmer, b->core.l_qseq,
3044 &pos, NULL, &rev, 1, w->try_rev, w->no_squash);
3045 if (rev)
3046 reverse_complement(b);
3047
3048 if (!kmer_h) {
3049 mh += 1LL<<30;
3050 pos = 65535-pos >= 0 ? 65535-pos : 0;
3051 } else {
3052 mh -= pos;
3053 pos = 0;
3054 }
3055
3056
3057 // Store 64-bit hash in unmapped pos and mpos fields.
3058 // The position of hash is in isize, which we use for
3059 // resolving ties when sorting by hash key.
3060 // These are unused for completely unmapped data and
3061 // will be reset during final output.
3062 b->core.pos = (mh>>31) & 0x7fffffff;
3063 b->core.mpos = mh&0x7fffffff;
3064 b->core.isize = pos;
3065 }
3066 }
3067
3068 static void *worker(void *data)
3069 {
3070 worker_t *w = (worker_t*)data;
3071 w->error = 0;
3072
3073 switch (g_sam_order) {
3074 case Coordinate:
3075 if (ks_radixsort(w->buf_len, w->buf, w->h) < 0) {
3076 w->error = errno;
3077 return NULL;
3078 }
3079 break;
3080 case MinHash:
3081 worker_minhash(w);
3082 // fall-through
3083 default:
3084 ks_mergesort(sort, w->buf_len, w->buf, 0);
3085 }
3086
3087 return 0;
3088 }
3089
3090 static int sort_blocks(size_t k, bam1_tag *buf, const sam_hdr_t *h,
3091 int n_threads, buf_region *in_mem,
3092 int large_pos, int minimiser_kmer, bool try_rev,
3093 bool no_squash)
3094 {
3095 int i;
3096 size_t pos, rest;
3097 pthread_t *tid;
3098 pthread_attr_t attr;
3099 worker_t *w;
3100 int n_failed = 0;
3101
3102 if (n_threads < 1) n_threads = 1;
3103 if (k < n_threads * 64) n_threads = 1; // use a single thread if we only sort a small batch of records
3104 pthread_attr_init(&attr);
3105 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
3106 w = (worker_t*)calloc(n_threads, sizeof(worker_t));
3107 if (!w) return -1;
3108 tid = (pthread_t*)calloc(n_threads, sizeof(pthread_t));
3109 if (!tid) { free(w); return -1; }
3110 pos = 0; rest = k;
3111 for (i = 0; i < n_threads; ++i) {
3112 w[i].buf_len = rest / (n_threads - i);
3113 w[i].buf = &buf[pos];
3114 w[i].h = h;
3115 w[i].large_pos = large_pos;
3116 w[i].minimiser_kmer = minimiser_kmer;
3117 w[i].try_rev = try_rev;
3118 w[i].no_squash = no_squash;
3119 in_mem[i].from = pos;
3120 in_mem[i].to = pos + w[i].buf_len;
3121 pos += w[i].buf_len; rest -= w[i].buf_len;
3122 pthread_create(&tid[i], &attr, worker, &w[i]);
3123 }
3124 for (i = 0; i < n_threads; ++i) {
3125 pthread_join(tid[i], 0);
3126 if (w[i].error != 0) {
3127 errno = w[i].error;
3128 print_error_errno("sort", "failed to sort block %d", i);
3129 n_failed++;
3130 }
3131 }
3132 free(w);
3133 free(tid);
3134
3135 return n_failed ? -1 : n_threads;
3136 }
3137
3138 static void lib_lookup_destroy(khash_t(const_c2c) *lib_lookup) {
3139 khiter_t k;
3140 if (lib_lookup == NULL)
3141 return;
3142 for (k = kh_begin(lib_lookup); k < kh_end(lib_lookup); k++) {
3143 if (kh_exist(lib_lookup, k))
3144 free(kh_value(lib_lookup, k));
3145 }
3146 kh_destroy(const_c2c, lib_lookup);
3147 }
3148
3149 // Build an RG to LB lookup table, for the template coordinate sort.
3150 // Returns a populated hash table (which may be empty) on success;
3151 // NULL on failure.
3152 static khash_t(const_c2c) * lookup_libraries(sam_hdr_t *header)
3153 {
3154 khash_t(const_c2c) *lib_lookup = kh_init(const_c2c);
3155 kstring_t lib_name = KS_INITIALIZE;
3156 int num_rg, i, res;
3157 if (!lib_lookup)
3158 return NULL;
3159
3160 // Iterate through any RG lines and look for library information
3161 num_rg = sam_hdr_count_lines(header, "RG");
3162 if (num_rg < 0)
3163 goto fail;
3164
3165 for (i = 0; i < num_rg; i++) {
3166 const char *rg_id = sam_hdr_line_name(header, "RG", i);
3167 khiter_t k;
3168 if (!rg_id)
3169 goto fail;
3170 res = sam_hdr_find_tag_pos(header, "RG", i, "LB", &lib_name);
3171 if (res < -1) // Error
3172 goto fail;
3173 if (res < 0 || !lib_name.s) // No LB tag
3174 continue;
3175 // Add to lookup table
3176 k = kh_put(const_c2c, lib_lookup, rg_id, &res);
3177 if (res < 0) // Error
3178 goto fail;
3179 if (res > 0) { // Inserted
3180 kh_value(lib_lookup, k) = ks_release(&lib_name);
3181 }
3182 }
3183
3184 free(lib_name.s);
3185
3186 return lib_lookup;
3187
3188 fail:
3189 lib_lookup_destroy(lib_lookup);
3190 free(lib_name.s);
3191 return NULL;
3192 }
3193
3194 /*!
3195 @abstract Sort an unsorted BAM file based on the provided sort order
3196
3197 @param sam_order the order in which the sort should occur
3198 @param sort_tag the tag to use if sorting by Tag
3199 @param minimiser_kmer the kmer size when sorting by MinHash
3200 @param try_rev try reverse strand when sorting by MinHash
3201 @param fn name of the file to be sorted
3202 @param prefix prefix of the temporary files (prefix.NNNN.bam are written)
3203 @param fnout name of the final output file to be written
3204 @param modeout sam_open() mode to be used to create the final output file
3205 @param max_mem approxiate maximum memory (very inaccurate)
3206 @param in_fmt input file format options
3207 @param out_fmt output file format and options
3208 @param arg_list command string for PG line
3209 @param no_pg if 1, do not add a new PG line
3210 @paran write_index create index for the output file
3211 @return 0 for successful sorting, negative on errors
3212
3213 @discussion It may create multiple temporary subalignment files
3214 and then merge them by calling bam_merge_simple(). This function is
3215 NOT thread safe.
3216 */
3217 int bam_sort_core_ext(SamOrder sam_order, char* sort_tag, int minimiser_kmer,
3218 bool try_rev, bool no_squash, const char *fn,
3219 const char *prefix, const char *fnout,
3220 const char *modeout, size_t _max_mem, int n_threads,
3221 const htsFormat *in_fmt, const htsFormat *out_fmt,
3222 char *arg_list, int no_pg, int write_index)
3223 {
3224 int ret = -1, res, i, nref, n_files = 0, n_big_files = 0, fn_counter = 0;
3225 size_t max_k, k, max_mem, bam_mem_offset;
3226 sam_hdr_t *header = NULL;
3227 samFile *fp = NULL;
3228 bam1_tag *buf = NULL;
3229 template_coordinate_keys_t *keys = NULL;
3230 bam1_t *b = bam_init1();
3231 uint8_t *bam_mem = NULL;
3232 char **fns = NULL;
3233 size_t fns_size = 0;
3234 const char *new_so = NULL;
3235 const char *new_go = NULL;
3236 const char *new_ss = NULL;
3237 buf_region *in_mem = NULL;
3238 khash_t(const_c2c) *lib_lookup = NULL;
3239 htsThreadPool htspool = { NULL, 0 };
3240 int num_in_mem = 0;
3241 int large_pos = 0;
3242
3243 if (!b) {
3244 print_error("sort", "couldn't allocate memory for bam record");
3245 return -1;
3246 }
3247
3248 if (n_threads < 2) n_threads = 1;
3249 g_sam_order = sam_order;
3250 if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) {
3251 g_sort_tag[0] = sort_tag[0];
3252 g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0';
3253 }
3254
3255 if (sam_order == TemplateCoordinate) {
3256 if ((keys = malloc(sizeof(template_coordinate_keys_t))) == NULL) {
3257 print_error("sort", "could not allocate memory for the top-level keys");
3258 goto err;
3259 }
3260 keys->n = 0;
3261 keys->m = 0;
3262 keys->buffer_size = 0x10000;
3263 keys->buffers = NULL;
3264 }
3265
3266 max_mem = _max_mem * n_threads;
3267 buf = NULL;
3268 fp = sam_open_format(fn, "r", in_fmt);
3269 if (fp == NULL) {
3270 print_error_errno("sort", "can't open \"%s\"", fn);
3271 goto err;
3272 }
3273 hts_set_opt(fp, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE);
3274 header = sam_hdr_read(fp);
3275 if (header == NULL) {
3276 print_error("sort", "failed to read header from \"%s\"", fn);
3277 goto err;
3278 }
3279
3280 // Inspect the header looking for long chromosomes
3281 // If there is one, we need to write temporary files in SAM format
3282 nref = sam_hdr_nref(header);
3283 for (i = 0; i < nref; i++) {
3284 if (sam_hdr_tid2len(header, i) > INT32_MAX)
3285 large_pos = 1;
3286 }
3287
3288 // Also check the output format is large position compatible
3289 if (large_pos) {
3290 int compatible = (out_fmt->format == sam
3291 || (out_fmt->format == cram
3292 && out_fmt->version.major >= 4)
3293 || (out_fmt->format == unknown_format
3294 && modeout[0] == 'w'
3295 && (modeout[1] == 'z' || modeout[1] == '\0')));
3296 if (!compatible) {
3297 print_error("sort", "output format is not compatible with very large references");
3298 goto err;
3299 }
3300 }
3301
3302 if (g_sam_order == TemplateCoordinate) {
3303 lib_lookup = lookup_libraries(header);
3304 if (!lib_lookup)
3305 goto err;
3306 }
3307
3308 switch (g_sam_order) {
3309 case Coordinate:
3310 new_so = "coordinate";
3311 break;
3312 case QueryName:
3313 new_so = "queryname";
3314 new_ss = natural_sort
3315 ? "queryname:natural"
3316 : "queryname:lexicographical";
3317 break;
3318 case MinHash:
3319 new_so = "coordinate";
3320 new_ss = "coordinate:minhash";
3321 break;
3322 case TagQueryName:
3323 case TagCoordinate:
3324 new_so = "unknown";
3325 break;
3326 case TemplateCoordinate:
3327 new_so = "unsorted";
3328 new_go = "query";
3329 new_ss = "unsorted:template-coordinate";
3330 break;
3331 default:
3332 new_so = "unknown";
3333 break;
3334 }
3335
3336 if (new_ss == NULL && new_go == NULL) { // just SO
3337 if ((-1 == sam_hdr_update_hd(header, "SO", new_so))
3338 && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION, "SO", new_so, NULL))
3339 ) {
3340 print_error("sort", "failed to change sort order header to 'SO:%s'\n", new_so);
3341 goto err;
3342 }
3343 } else if (new_ss != NULL && new_go == NULL) { // update SO and SS, but not GO
3344 if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "SS", new_ss))
3345 && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION,
3346 "SO", new_so, "SS", new_ss, NULL))
3347 ) {
3348 print_error("sort", "failed to change sort order header to 'SO:%s SS:%s'\n",
3349 new_so, new_ss);
3350 goto err;
3351 }
3352 } else if (new_ss == NULL && new_go != NULL) { // update SO and GO, but not SS
3353 if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "GO", new_go))
3354 && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION,
3355 "SO", new_so, "GO", new_go, NULL))
3356 ) {
3357 print_error("sort", "failed to change sort order header to 'SO:%s GO:%s'\n",
3358 new_so, new_go);
3359 goto err;
3360 }
3361 } else { // update SO, GO, and SS
3362 if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "GO", new_go, "SS", new_ss))
3363 && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION,
3364 "SO", new_so, "GO", new_go, "SS", new_ss, NULL))
3365 ) {
3366 print_error("sort", "failed to change sort order header to 'SO:%s GO:%s SS:%s'\n",
3367 new_so, new_go, new_ss);
3368 goto err;
3369 }
3370 }
3371
3372 if (new_go == NULL) {
3373 if (-1 == sam_hdr_remove_tag_hd(header, "GO")) {
3374 print_error("sort", "failed to delete group order in header\n");
3375 goto err;
3376 }
3377 }
3378 if (new_ss == NULL) {
3379 if (-1 == sam_hdr_remove_tag_hd(header, "SS")) {
3380 print_error("sort", "failed to delete sub sort in header\n");
3381 goto err;
3382 }
3383 }
3384
3385 if (n_threads > 1) {
3386 htspool.pool = hts_tpool_init(n_threads);
3387 if (!htspool.pool) {
3388 print_error_errno("sort", "failed to set up thread pool");
3389 goto err;
3390 }
3391 hts_set_opt(fp, HTS_OPT_THREAD_POOL, &htspool);
3392 }
3393
3394 if ((bam_mem = malloc(max_mem)) == NULL) {
3395 print_error("sort", "couldn't allocate memory for bam_mem");
3396 goto err;
3397 }
3398
3399 in_mem = calloc(n_threads > 0 ? n_threads : 1, sizeof(in_mem[0]));
3400 if (!in_mem) goto err;
3401
3402 // write sub files
3403 k = max_k = bam_mem_offset = 0;
3404 size_t name_len = strlen(prefix) + 30;
3405 while ((res = sam_read1(fp, header, b)) >= 0) {
3406 int mem_full = 0;
3407
3408 if (k == max_k) {
3409 bam1_tag *new_buf;
3410 max_k = max_k? max_k<<1 : 0x10000;
3411 if ((new_buf = realloc(buf, max_k * sizeof(bam1_tag))) == NULL) {
3412 print_error("sort", "couldn't allocate memory for buf");
3413 goto err;
3414 }
3415 buf = new_buf;
3416 }
3417 if (sam_order == TemplateCoordinate && k >= keys->m * keys->buffer_size) {
3418 if (template_coordinate_keys_realloc(keys, k + 1) == -1) {
3419 goto err;
3420 }
3421 }
3422
3423 // Check if the BAM record will fit in the memory limit
3424 if (bam_mem_offset + sizeof(*b) + b->l_data < max_mem) {
3425 // Copy record into the memory block
3426 buf[k].bam_record = (bam1_t *)(bam_mem + bam_mem_offset);
3427 *buf[k].bam_record = *b;
3428 buf[k].bam_record->data = (uint8_t *)((char *)buf[k].bam_record + sizeof(bam1_t));
3429 memcpy(buf[k].bam_record->data, b->data, b->l_data);
3430 // store next BAM record in next 8-byte-aligned address after
3431 // current one
3432 bam_mem_offset = (bam_mem_offset + sizeof(*b) + b->l_data + 8 - 1) & ~((size_t)(8 - 1));
3433 } else {
3434 // Add a pointer to the remaining record
3435 buf[k].bam_record = b;
3436 mem_full = 1;
3437 }
3438
3439 // Set the tag if sorting by tag, or the key for template cooridinate sorting
3440 switch (g_sam_order) {
3441 case TagQueryName:
3442 case TagCoordinate:
3443 buf[k].u.tag = bam_aux_get(buf[k].bam_record, g_sort_tag);
3444 break;
3445 case TemplateCoordinate:
3446 ++keys->n;
3447 template_coordinate_key_t *key = template_coordinate_keys_get(keys, k);
3448 buf[k].u.key = template_coordinate_key(buf[k].bam_record, key, header, lib_lookup);
3449 if (buf[k].u.key == NULL) goto err;
3450 break;
3451 default:
3452 buf[k].u.tag = NULL;
3453 buf[k].u.key = NULL;
3454 }
3455 ++k;
3456
3457 if (mem_full) {
3458 if (hts_resize(char *, n_files + 1, &fns_size, &fns, 0) < 0)
3459 goto err;
3460
3461 int sort_res = sort_blocks(k, buf, header, n_threads,
3462 in_mem, large_pos, minimiser_kmer,
3463 try_rev, no_squash);
3464 if (sort_res < 0)
3465 goto err;
3466
3467 fns[n_files] = calloc(name_len, 1);
3468 if (!fns[n_files])
3469 goto err;
3470 const int MAX_TRIES = 1000;
3471 int tries = 0, merge_res = -1;
3472 char *sort_by_tag = (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) ? sort_tag : NULL;
3473 int consolidate_from = n_files;
3474 if (n_files - n_big_files >= MAX_TMP_FILES/2)
3475 consolidate_from = n_big_files;
3476 else if (n_files >= MAX_TMP_FILES)
3477 consolidate_from = 0;
3478
3479 for (;;) {
3480 if (tries) {
3481 snprintf(fns[n_files], name_len, "%s.%.4d-%.3d.bam",
3482 prefix, fn_counter, tries);
3483 } else {
3484 snprintf(fns[n_files], name_len, "%s.%.4d.bam", prefix,
3485 fn_counter);
3486 }
3487 if (bam_merge_simple(g_sam_order, sort_by_tag, fns[n_files],
3488 large_pos ? "wzx1" : "wbx1", header,
3489 n_files - consolidate_from,
3490 &fns[consolidate_from], n_threads,
3491 in_mem, buf, keys,
3492 lib_lookup, &htspool, "sort", NULL, NULL,
3493 NULL, 1, 0, 0) >= 0) {
3494 merge_res = 0;
3495 break;
3496 }
3497 if (errno == EEXIST && tries < MAX_TRIES) {
3498 tries++;
3499 } else {
3500 break;
3501 }
3502 }
3503 fn_counter++;
3504 if (merge_res < 0) {
3505 if (errno != EEXIST)
3506 unlink(fns[n_files]);
3507 free(fns[n_files]);
3508 goto err;
3509 }
3510
3511 if (consolidate_from < n_files) {
3512 for (i = consolidate_from; i < n_files; i++) {
3513 unlink(fns[i]);
3514 free(fns[i]);
3515 }
3516 fns[consolidate_from] = fns[n_files];
3517 n_files = consolidate_from;
3518 n_big_files = consolidate_from + 1;
3519 }
3520
3521 n_files++;
3522 k = 0;
3523 if (keys != NULL) keys->n = 0;
3524 bam_mem_offset = 0;
3525
3526 }
3527 }
3528 if (res != -1) {
3529 print_error("sort", "truncated file. Aborting");
3530 goto err;
3531 }
3532
3533 // Sort last records
3534 if (k > 0) {
3535 num_in_mem = sort_blocks(k, buf, header, n_threads,
3536 in_mem, large_pos, minimiser_kmer, try_rev,
3537 no_squash);
3538 if (num_in_mem < 0) goto err;
3539 } else {
3540 num_in_mem = 0;
3541 }
3542
3543 // write the final output
3544 if (n_files == 0 && num_in_mem < 2) { // a single block
3545 if (write_buffer(fnout, modeout, k, buf, header, n_threads, out_fmt,
3546 minimiser_kmer, arg_list, no_pg, write_index) != 0) {
3547 print_error_errno("sort", "failed to create \"%s\"", fnout);
3548 goto err;
3549 }
3550 } else { // then merge
3551 fprintf(stderr,
3552 "[bam_sort_core] merging from %d files and %d in-memory blocks...\n",
3553 n_files, num_in_mem);
3554 // Paranoia check - all temporary files should have a name
3555 for (i = 0; i < n_files; ++i) {
3556 if (!fns[i]) {
3557 print_error("sort",
3558 "BUG: no name stored for temporary file %d", i);
3559 abort();
3560 }
3561 }
3562 char *sort_by_tag = (sam_order == TagQueryName || sam_order == TagCoordinate) ? sort_tag : NULL;
3563 if (bam_merge_simple(sam_order, sort_by_tag, fnout, modeout, header,
3564 n_files, fns, num_in_mem, in_mem, buf, keys,
3565 lib_lookup, &htspool, "sort", in_fmt, out_fmt,
3566 arg_list, no_pg, write_index, 1) < 0) {
3567 // Propagate bam_merge_simple() failure; it has already emitted a
3568 // message explaining the failure, so no further message is needed.
3569 goto err;
3570 }
3571 }
3572
3573 ret = 0;
3574
3575 err:
3576 // free
3577 if (fns) {
3578 for (i = 0; i < n_files; ++i) {
3579 if (fns[i]) {
3580 unlink(fns[i]);
3581 free(fns[i]);
3582 }
3583 }
3584 free(fns);
3585 }
3586 bam_destroy1(b);
3587 free(buf);
3588 if (keys != NULL) {
3589 for (i = 0; i < keys->m; ++i) {
3590 free(keys->buffers[i]);
3591 }
3592 free(keys->buffers);
3593 free(keys);
3594 }
3595 free(bam_mem);
3596 free(in_mem);
3597 lib_lookup_destroy(lib_lookup);
3598 sam_hdr_destroy(header);
3599 if (fp) sam_close(fp);
3600 if (htspool.pool)
3601 hts_tpool_destroy(htspool.pool);
3602
3603 return ret;
3604 }
3605
3606 // Unused here but may be used by legacy samtools-using third-party code
3607 int bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
3608 {
3609 int ret;
3610 char *fnout = calloc(strlen(prefix) + 4 + 1, 1);
3611 if (!fnout) return -1;
3612 sprintf(fnout, "%s.bam", prefix);
3613 SamOrder sam_order = is_by_qname ? QueryName : Coordinate;
3614 g_sam_order = sam_order;
3615 ret = bam_sort_core_ext(sam_order, NULL, 0, false, true, fn, prefix,
3616 fnout, "wb", max_mem, 0, NULL, NULL, NULL, 1, 0);
3617 free(fnout);
3618 return ret;
3619 }
3620
3621 static void sort_usage(FILE *fp)
3622 {
3623 fprintf(fp,
3624 "Usage: samtools sort [options...] [in.bam]\n"
3625 "Options:\n"
3626 " -l INT Set compression level, from 0 (uncompressed) to 9 (best)\n"
3627 " -u Output uncompressed data (equivalent to -l 0)\n"
3628 " -m INT Set maximum memory per thread; suffix K/M/G recognized [768M]\n"
3629 " -M Use minimiser for clustering unaligned/unplaced reads\n"
3630 " -R Do not use reverse strand (only compatible with -M)\n"
3631 " -K INT Kmer size to use for minimiser [20]\n"
3632 " -I FILE Order minimisers by their position in FILE FASTA\n"
3633 " -w INT Window size for minimiser indexing via -I ref.fa [100]\n"
3634 " -H Squash homopolymers when computing minimiser\n"
3635 " -n Sort by read name (natural): cannot be used with samtools index\n"
3636 " -N Sort by read name (ASCII): cannot be used with samtools index\n"
3637 " -t TAG Sort by value of TAG. Uses position as secondary index (or read name if -n is set)\n"
3638 " -o FILE Write final output to FILE rather than standard output\n"
3639 " -T PREFIX Write temporary files to PREFIX.nnnn.bam\n"
3640 " --no-PG\n"
3641 " Do not add a PG line\n"
3642 " --template-coordinate\n"
3643 " Sort by template-coordinate\n");
3644 sam_global_opt_help(fp, "-.O..@..");
3645 }
3646
3647 static void complain_about_memory_setting(size_t max_mem) {
3648 char *suffix = "";
3649 const size_t nine_k = 9<<10;
3650 if (max_mem > nine_k) { max_mem >>= 10; suffix = "K"; }
3651 if (max_mem > nine_k) { max_mem >>= 10; suffix = "M"; }
3652
3653 fprintf(stderr,
3654 "[bam_sort] -m setting (%zu%s bytes) is less than the minimum required (%zuM).\n\n"
3655 "Trying to run with -m too small can lead to the creation of a very large number\n"
3656 "of temporary files. This may make sort fail due to it exceeding limits on the\n"
3657 "number of files it can have open at the same time.\n\n"
3658 "Please check your -m parameter. It should be an integer followed by one of the\n"
3659 "letters K (for kilobytes), M (megabytes) or G (gigabytes). You should ensure it\n"
3660 "is at least the minimum above, and much higher if you are sorting a large file.\n",
3661 max_mem, suffix, SORT_MIN_MEGS_PER_THREAD);
3662 }
3663
3664 int bam_sort(int argc, char *argv[])
3665 {
3666 size_t max_mem = SORT_DEFAULT_MEGS_PER_THREAD << 20;
3667 int c, nargs, ret, o_seen = 0, level = -1, no_pg = 0;
3668 SamOrder sam_order = Coordinate;
3669 bool by_tag = false;
3670 int minimiser_kmer = 20;
3671 bool try_rev = true;
3672 char* sort_tag = NULL, *arg_list = NULL;
3673 char *fnout = "-", modeout[12];
3674 kstring_t tmpprefix = { 0, 0, NULL };
3675 struct stat st;
3676 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
3677 int window = 100;
3678 char *minimiser_ref = NULL;
3679 int no_squash = 1;
3680
3681 static const struct option lopts[] = {
3682 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
3683 { "threads", required_argument, NULL, '@' },
3684 {"no-PG", no_argument, NULL, 1},
3685 { "template-coordinate", no_argument, NULL, 2},
3686 { NULL, 0, NULL, 0 }
3687 };
3688
3689 while ((c = getopt_long(argc, argv, "l:m:nNo:O:T:@:t:MI:K:uRw:H", lopts, NULL)) >= 0) {
3690 switch (c) {
3691 case 'o': fnout = optarg; o_seen = 1; break;
3692 case 'N': natural_sort = 0; // fall through
3693 case 'n': sam_order = QueryName; break;
3694 case 't': by_tag = true; sort_tag = optarg; break;
3695 case 'm': {
3696 char *q;
3697 max_mem = strtol(optarg, &q, 0);
3698 if (*q == 'k' || *q == 'K') max_mem <<= 10;
3699 else if (*q == 'm' || *q == 'M') max_mem <<= 20;
3700 else if (*q == 'g' || *q == 'G') max_mem <<= 30;
3701 break;
3702 }
3703 case 'T': kputs(optarg, &tmpprefix); break;
3704 case 'l': level = atoi(optarg); break;
3705 case 'u': level = 0; break;
3706 case 1: no_pg = 1; break;
3707 case 2: sam_order = TemplateCoordinate; break;
3708 case 'M': sam_order = MinHash; break;
3709 case 'I':
3710 sam_order = MinHash; // implicit option
3711 minimiser_ref = optarg;
3712 break;
3713 case 'H': no_squash = 0; break;
3714
3715 case 'w': window = atoi(optarg); break;
3716
3717 case 'R': try_rev = false; break;
3718 case 'K':
3719 minimiser_kmer = atoi(optarg);
3720 if (minimiser_kmer < 1)
3721 minimiser_kmer = 1;
3722 else if (minimiser_kmer > 31)
3723 minimiser_kmer = 31;
3724 break;
3725
3726 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
3727 /* else fall-through */
3728 case '?': sort_usage(stderr); ret = EXIT_FAILURE; goto sort_end;
3729 }
3730 }
3731
3732 if (minimiser_ref) {
3733 fprintf(stderr, "Building index ... ");
3734 fflush(stderr);
3735 if (build_minhash_index(minimiser_ref, minimiser_kmer, window,
3736 no_squash)) {
3737 ret = EXIT_FAILURE;
3738 goto sort_end;
3739 }
3740 fprintf(stderr, "done\n");
3741 }
3742
3743 // Change sort order if tag sorting is requested. Must update based on secondary index
3744 if (by_tag) {
3745 sam_order = sam_order == QueryName ? TagQueryName : TagCoordinate;
3746 }
3747
3748 nargs = argc - optind;
3749 if (nargs == 0 && isatty(STDIN_FILENO)) {
3750 sort_usage(stdout);
3751 ret = EXIT_SUCCESS;
3752 goto sort_end;
3753 }
3754 else if (nargs >= 2) {
3755 // If exactly two, user probably tried to specify legacy <out.prefix>
3756 if (nargs == 2)
3757 fprintf(stderr, "[bam_sort] Use -T PREFIX / -o FILE to specify temporary and final output files\n");
3758
3759 sort_usage(stderr);
3760 ret = EXIT_FAILURE;
3761 goto sort_end;
3762 }
3763
3764 if (ga.write_index && sam_order != Coordinate) {
3765 fprintf(stderr, "[W::bam_sort] Ignoring --write-index as it only works for position sorted files.\n");
3766 ga.write_index = 0;
3767 }
3768
3769 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
3770 print_error("sort", "failed to create arg_list");
3771 return 1;
3772 }
3773
3774 if (max_mem < (SORT_MIN_MEGS_PER_THREAD << 20)) {
3775 complain_about_memory_setting(max_mem);
3776 ret = EXIT_FAILURE;
3777 goto sort_end;
3778 }
3779
3780 strcpy(modeout, "wb");
3781 sam_open_mode(modeout+1, fnout, NULL);
3782 if (level >= 0) sprintf(strchr(modeout, '\0'), "%d", level < 9? level : 9);
3783
3784 if (tmpprefix.l == 0) {
3785 if (strcmp(fnout, "-") != 0) {
3786 char *idx = strstr(fnout, HTS_IDX_DELIM);
3787 kputsn(fnout, idx ? idx - fnout : strlen(fnout), &tmpprefix);
3788 kputs(".tmp", &tmpprefix);
3789 } else {
3790 kputc('.', &tmpprefix);
3791 }
3792 }
3793 if (stat(tmpprefix.s, &st) == 0 && S_ISDIR(st.st_mode)) {
3794 unsigned t = ((unsigned) time(NULL)) ^ ((unsigned) clock());
3795 if (tmpprefix.s[tmpprefix.l-1] != '/') kputc('/', &tmpprefix);
3796 ksprintf(&tmpprefix, "samtools.%d.%u.tmp", (int) getpid(), t % 10000);
3797 }
3798
3799 ret = bam_sort_core_ext(sam_order, sort_tag,
3800 (sam_order == MinHash) ? minimiser_kmer : 0,
3801 try_rev, no_squash,
3802 (nargs > 0) ? argv[optind] : "-",
3803 tmpprefix.s, fnout, modeout, max_mem, ga.nthreads,
3804 &ga.in, &ga.out, arg_list, no_pg, ga.write_index);
3805 if (ret >= 0)
3806 ret = EXIT_SUCCESS;
3807 else {
3808 char dummy[4];
3809 // If we failed on opening the input file & it has no .bam/.cram/etc
3810 // extension, the user probably tried legacy -o <infile> <out.prefix>
3811 if (ret == -2 && o_seen && nargs > 0 && sam_open_mode(dummy, argv[optind], NULL) < 0)
3812 fprintf(stderr, "[bam_sort] Note the <out.prefix> argument has been replaced by -T/-o options\n");
3813
3814 ret = EXIT_FAILURE;
3815 }
3816
3817 #ifdef DEBUG_MINHASH
3818 fprintf(stderr, "Missed %.1f%%, dup %.1f%%\n",
3819 100.0*nmis/(ntot+.1),
3820 100.0*ndup/(ntot+.1));
3821 #endif
3822
3823 sort_end:
3824 free(tmpprefix.s);
3825 free(arg_list);
3826 sam_global_args_free(&ga);
3827
3828 return ret;
3829 }