11 static int g_is_by_qname = 0;
13 static inline int strnum_cmp(const char *a, const char *b)
16 pa = (char*)a; pb = (char*)b;
18 if (isdigit(*pa) && isdigit(*pb)) {
20 ai = strtol(pa, &pa, 10);
21 bi = strtol(pb, &pb, 10);
22 if (ai != bi) return ai<bi? -1 : ai>bi? 1 : 0;
24 if (*pa != *pb) break;
29 return (pa-a) < (pb-b)? -1 : (pa-a) > (pb-b)? 1 : 0;
30 return *pa<*pb? -1 : *pa>*pb? 1 : 0;
33 #define HEAP_EMPTY 0xffffffffffffffffull
41 #define __pos_cmp(a, b) ((a).pos > (b).pos || ((a).pos == (b).pos && ((a).i > (b).i || ((a).i == (b).i && (a).idx > (b).idx))))
43 static inline int heap_lt(const heap1_t a, const heap1_t b)
47 if (a.b == 0 || b.b == 0) return a.b == 0? 1 : 0;
48 t = strnum_cmp(bam1_qname(a.b), bam1_qname(b.b));
49 return (t > 0 || (t == 0 && __pos_cmp(a, b)));
50 } else return __pos_cmp(a, b);
53 KSORT_INIT(heap, heap1_t, heap_lt)
55 static void swap_header_targets(bam_header_t *h1, bam_header_t *h2)
58 t.n_targets = h1->n_targets, h1->n_targets = h2->n_targets, h2->n_targets = t.n_targets;
59 t.target_name = h1->target_name, h1->target_name = h2->target_name, h2->target_name = t.target_name;
60 t.target_len = h1->target_len, h1->target_len = h2->target_len, h2->target_len = t.target_len;
63 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
67 tempi = h1->l_text, h1->l_text = h2->l_text, h2->l_text = tempi;
68 temps = h1->text, h1->text = h2->text, h2->text = temps;
72 #define MERGE_UNCOMP 2
73 #define MERGE_LEVEL1 4
76 @abstract Merge multiple sorted BAM.
77 @param is_by_qname whether to sort by query name
78 @param out output BAM file name
79 @param headers name of SAM file from which to copy '@' header lines,
80 or NULL to copy them from the first file to be merged
81 @param n number of files to be merged
82 @param fn names of files to be merged
84 @discussion Padding information may NOT correctly maintained. This
85 function is NOT thread safe.
87 int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn,
88 int flag, const char *reg)
92 bam_header_t *hout = 0;
93 bam_header_t *hheaders = NULL;
94 int i, j, *RG_len = 0;
100 tamFile fpheaders = sam_open(headers);
101 if (fpheaders == 0) {
102 const char *message = strerror(errno);
103 fprintf(stderr, "[bam_merge_core] cannot open '%s': %s\n", headers, message);
106 hheaders = sam_header_read(fpheaders);
107 sam_close(fpheaders);
110 g_is_by_qname = by_qname;
111 fp = (bamFile*)calloc(n, sizeof(bamFile));
112 heap = (heap1_t*)calloc(n, sizeof(heap1_t));
113 iter = (bam_iter_t*)calloc(n, sizeof(bam_iter_t));
115 if (flag & MERGE_RG) {
116 RG = (char**)calloc(n, sizeof(void*));
117 RG_len = (int*)calloc(n, sizeof(int));
118 for (i = 0; i != n; ++i) {
119 int l = strlen(fn[i]);
120 const char *s = fn[i];
121 if (l > 4 && strcmp(s + l - 4, ".bam") == 0) l -= 4;
122 for (j = l - 1; j >= 0; --j) if (s[j] == '/') break;
124 RG[i] = calloc(l + 1, 1);
126 strncpy(RG[i], s + j, l);
130 for (i = 0; i != n; ++i) {
132 fp[i] = bam_open(fn[i], "r");
135 fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
136 for (j = 0; j < i; ++j) bam_close(fp[j]);
137 free(fp); free(heap);
138 // FIXME: possible memory leak
141 hin = bam_header_read(fp[i]);
142 if (i == 0) { // the first BAM
144 } else { // validate multiple baf
145 int min_n_targets = hout->n_targets;
146 if (hin->n_targets < min_n_targets) min_n_targets = hin->n_targets;
148 for (j = 0; j < min_n_targets; ++j)
149 if (strcmp(hout->target_name[j], hin->target_name[j]) != 0) {
150 fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'\n",
151 hout->target_name[j], hin->target_name[j], fn[i]);
155 // If this input file has additional target reference sequences,
156 // add them to the headers to be output
157 if (hin->n_targets > hout->n_targets) {
158 swap_header_targets(hout, hin);
159 // FIXME Possibly we should also create @SQ text headers
160 // for the newly added reference sequences
163 bam_header_destroy(hin);
168 // If the text headers to be swapped in include any @SQ headers,
169 // check that they are consistent with the existing binary list
170 // of reference information.
171 if (hheaders->n_targets > 0) {
172 if (hout->n_targets != hheaders->n_targets) {
173 fprintf(stderr, "[bam_merge_core] number of @SQ headers in '%s' differs from number of target sequences\n", headers);
176 for (j = 0; j < hout->n_targets; ++j)
177 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0) {
178 fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence\n", hheaders->target_name[j], headers);
183 swap_header_text(hout, hheaders);
184 bam_header_destroy(hheaders);
189 if (bam_parse_region(hout, reg, &tid, &beg, &end) < 0) {
190 fprintf(stderr, "[%s] Malformated region string or undefined reference name\n", __func__);
193 for (i = 0; i < n; ++i) {
195 idx = bam_index_load(fn[i]);
196 iter[i] = bam_iter_query(idx, tid, beg, end);
197 bam_index_destroy(idx);
201 for (i = 0; i < n; ++i) {
202 heap1_t *h = heap + i;
204 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
205 if (bam_iter_read(fp[i], iter[i], h->b) >= 0) {
206 h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
209 else h->pos = HEAP_EMPTY;
211 if (flag & MERGE_UNCOMP) fpout = strcmp(out, "-")? bam_open(out, "wu") : bam_dopen(fileno(stdout), "wu");
212 else if (flag & MERGE_LEVEL1) fpout = strcmp(out, "-")? bam_open(out, "w1") : bam_dopen(fileno(stdout), "w1");
213 else fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
215 fprintf(stderr, "[%s] fail to create the output file.\n", __func__);
218 bam_header_write(fpout, hout);
219 bam_header_destroy(hout);
221 ks_heapmake(heap, n, heap);
222 while (heap->pos != HEAP_EMPTY) {
224 if (flag & MERGE_RG) {
225 uint8_t *rg = bam_aux_get(b, "RG");
226 if (rg) bam_aux_del(b, rg);
227 bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]);
229 bam_write1_core(fpout, &b->core, b->data_len, b->data);
230 if ((j = bam_iter_read(fp[heap->i], iter[heap->i], b)) >= 0) {
231 heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
233 } else if (j == -1) {
234 heap->pos = HEAP_EMPTY;
235 free(heap->b->data); free(heap->b);
237 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
238 ks_heapadjust(heap, 0, n, heap);
241 if (flag & MERGE_RG) {
242 for (i = 0; i != n; ++i) free(RG[i]);
243 free(RG); free(RG_len);
245 for (i = 0; i != n; ++i) {
246 bam_iter_destroy(iter[i]);
250 free(fp); free(heap); free(iter);
254 int bam_merge(int argc, char *argv[])
256 int c, is_by_qname = 0, flag = 0, ret = 0;
257 char *fn_headers = NULL, *reg = 0;
259 while ((c = getopt(argc, argv, "h:nru1R:")) >= 0) {
261 case 'r': flag |= MERGE_RG; break;
262 case 'h': fn_headers = strdup(optarg); break;
263 case 'n': is_by_qname = 1; break;
264 case '1': flag |= MERGE_LEVEL1; break;
265 case 'u': flag |= MERGE_UNCOMP; break;
266 case 'R': reg = strdup(optarg); break;
269 if (optind + 2 >= argc) {
270 fprintf(stderr, "\n");
271 fprintf(stderr, "Usage: samtools merge [-nr] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
272 fprintf(stderr, "Options: -n sort by read names\n");
273 fprintf(stderr, " -r attach RG tag (inferred from file names)\n");
274 fprintf(stderr, " -u uncompressed BAM output\n");
275 fprintf(stderr, " -1 compress level 1\n");
276 fprintf(stderr, " -R STR merge file in the specified region STR [all]\n");
277 fprintf(stderr, " -h FILE copy the header in FILE to <out.bam> [in1.bam]\n\n");
278 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
279 fprintf(stderr, " must provide the correct header with -h, or uses Picard which properly maintains\n");
280 fprintf(stderr, " the header dictionary in merging.\n\n");
283 if (bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1, flag, reg) < 0) ret = 1;
289 typedef bam1_t *bam1_p;
291 static inline int bam1_lt(const bam1_p a, const bam1_p b)
294 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
295 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
296 } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
298 KSORT_INIT(sort, bam1_p, bam1_lt)
300 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h, int is_stdout)
305 ks_mergesort(sort, k, buf, 0);
306 name = (char*)calloc(strlen(prefix) + 20, 1);
308 sprintf(name, "%s.%.4d.bam", prefix, n);
311 sprintf(name, "%s.bam", prefix);
314 fp = is_stdout? bam_dopen(fileno(stdout), mode) : bam_open(name, mode);
316 fprintf(stderr, "[sort_blocks] fail to create file %s.\n", name);
318 // FIXME: possible memory leak
322 bam_header_write(fp, h);
323 for (i = 0; i < k; ++i)
324 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
329 @abstract Sort an unsorted BAM file based on the chromosome order
330 and the leftmost position of an alignment
332 @param is_by_qname whether to sort by query name
333 @param fn name of the file to be sorted
334 @param prefix prefix of the output and the temporary files; upon
335 sucessess, prefix.bam will be written.
336 @param max_mem approxiate maximum memory (very inaccurate)
338 @discussion It may create multiple temporary subalignment files
339 and then merge them by calling bam_merge_core(). This function is
342 void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t max_mem, int is_stdout)
346 bam_header_t *header;
350 g_is_by_qname = is_by_qname;
352 fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
354 fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
357 header = bam_header_read(fp);
358 buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
361 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
363 if ((ret = bam_read1(fp, b)) < 0) break;
366 if (mem >= max_mem) {
367 sort_blocks(n++, k, buf, prefix, header, 0);
372 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
373 if (n == 0) sort_blocks(-1, k, buf, prefix, header, is_stdout);
376 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
377 sort_blocks(n++, k, buf, prefix, header, 0);
378 fnout = (char*)calloc(strlen(prefix) + 20, 1);
379 if (is_stdout) sprintf(fnout, "-");
380 else sprintf(fnout, "%s.bam", prefix);
381 fns = (char**)calloc(n, sizeof(char*));
382 for (i = 0; i < n; ++i) {
383 fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
384 sprintf(fns[i], "%s.%.4d.bam", prefix, i);
386 bam_merge_core(is_by_qname, fnout, 0, n, fns, 0, 0);
388 for (i = 0; i < n; ++i) {
394 for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
401 bam_header_destroy(header);
405 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
407 bam_sort_core_ext(is_by_qname, fn, prefix, max_mem, 0);
410 int bam_sort(int argc, char *argv[])
412 size_t max_mem = 500000000;
413 int c, is_by_qname = 0, is_stdout = 0;
414 while ((c = getopt(argc, argv, "nom:")) >= 0) {
416 case 'o': is_stdout = 1; break;
417 case 'n': is_by_qname = 1; break;
418 case 'm': max_mem = atol(optarg); break;
421 if (optind + 2 > argc) {
422 fprintf(stderr, "Usage: samtools sort [-on] [-m <maxMem>] <in.bam> <out.prefix>\n");
425 bam_sort_core_ext(is_by_qname, argv[optind], argv[optind+1], max_mem, is_stdout);