Debian Codegraph @

samtools/bam_sort.c.pysam.c

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