10 static int g_is_by_qname = 0;
12 static inline int strnum_cmp(const char *a, const char *b)
15 pa = (char*)a; pb = (char*)b;
17 if (isdigit(*pa) && isdigit(*pb)) {
19 ai = strtol(pa, &pa, 10);
20 bi = strtol(pb, &pb, 10);
21 if (ai != bi) return ai<bi? -1 : ai>bi? 1 : 0;
23 if (*pa != *pb) break;
28 return (pa-a) < (pb-b)? -1 : (pa-a) > (pb-b)? 1 : 0;
29 return *pa<*pb? -1 : *pa>*pb? 1 : 0;
32 #define HEAP_EMPTY 0xffffffffffffffffull
40 #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))))
42 static inline int heap_lt(const heap1_t a, const heap1_t b)
46 if (a.b == 0 || b.b == 0) return a.b == 0? 1 : 0;
47 t = strnum_cmp(bam1_qname(a.b), bam1_qname(b.b));
48 return (t > 0 || (t == 0 && __pos_cmp(a, b)));
49 } else return __pos_cmp(a, b);
52 KSORT_INIT(heap, heap1_t, heap_lt)
54 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
58 tempi = h1->l_text, h1->l_text = h2->l_text, h2->l_text = tempi;
59 temps = h1->text, h1->text = h2->text, h2->text = temps;
63 @abstract Merge multiple sorted BAM.
64 @param is_by_qname whether to sort by query name
65 @param out output BAM file name
66 @param headers name of SAM file from which to copy '@' header lines,
67 or NULL to copy them from the first file to be merged
68 @param n number of files to be merged
69 @param fn names of files to be merged
71 @discussion Padding information may NOT correctly maintained. This
72 function is NOT thread safe.
74 void bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn)
78 bam_header_t *hout = 0;
79 bam_header_t *hheaders = NULL;
84 tamFile fpheaders = sam_open(headers);
86 fprintf(stderr, "[bam_merge_core] Cannot open file `%s'. Continue anyway.\n", headers);
88 hheaders = sam_header_read(fpheaders);
93 g_is_by_qname = by_qname;
94 fp = (bamFile*)calloc(n, sizeof(bamFile));
95 heap = (heap1_t*)calloc(n, sizeof(heap1_t));
96 for (i = 0; i != n; ++i) {
99 fp[i] = bam_open(fn[i], "r");
102 fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
103 for (j = 0; j < i; ++j) bam_close(fp[j]);
104 free(fp); free(heap);
105 // FIXME: possible memory leak
108 hin = bam_header_read(fp[i]);
109 if (i == 0) { // the first SAM
112 // If the text headers to be swapped in include any @SQ headers,
113 // check that they are consistent with the existing binary list
114 // of reference information.
115 if (hheaders->n_targets > 0) {
116 if (hout->n_targets != hheaders->n_targets)
117 fprintf(stderr, "[bam_merge_core] number of @SQ headers in `%s' differs from number of target sequences", headers);
118 for (j = 0; j < hout->n_targets; ++j)
119 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0)
120 fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence", hheaders->target_name[j], headers);
122 swap_header_text(hout, hheaders);
123 bam_header_destroy(hheaders);
126 } else { // validate multiple baf
127 if (hout->n_targets != hin->n_targets) {
128 fprintf(stderr, "[bam_merge_core] file '%s' has different number of target sequences. Abort!\n", fn[i]);
131 for (j = 0; j < hout->n_targets; ++j) {
132 if (strcmp(hout->target_name[j], hin->target_name[j])) {
133 fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'. Abort!\n",
134 hout->target_name[j], hin->target_name[j], fn[i]);
138 bam_header_destroy(hin);
142 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
143 if (bam_read1(fp[i], h->b) >= 0) {
144 h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
147 else h->pos = HEAP_EMPTY;
149 fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
151 bam_header_write(fpout, hout);
152 bam_header_destroy(hout);
154 ks_heapmake(heap, n, heap);
155 while (heap->pos != HEAP_EMPTY) {
157 bam_write1_core(fpout, &b->core, b->data_len, b->data);
158 if ((j = bam_read1(fp[heap->i], b)) >= 0) {
159 heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
161 } else if (j == -1) {
162 heap->pos = HEAP_EMPTY;
163 free(heap->b->data); free(heap->b);
165 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
166 ks_heapadjust(heap, 0, n, heap);
169 for (i = 0; i != n; ++i) bam_close(fp[i]);
171 free(fp); free(heap);
173 int bam_merge(int argc, char *argv[])
175 int c, is_by_qname = 0;
176 char *fn_headers = NULL;
178 while ((c = getopt(argc, argv, "h:n")) >= 0) {
180 case 'h': fn_headers = strdup(optarg); break;
181 case 'n': is_by_qname = 1; break;
184 if (optind + 2 >= argc) {
185 fprintf(stderr, "\n");
186 fprintf(stderr, "Usage: samtools merge [-n] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
187 fprintf(stderr, "Options: -n sort by read names\n");
188 fprintf(stderr, " -h FILE copy the header in FILE to <out.bam> [in1.bam]\n\n");
189 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
190 fprintf(stderr, " must provide the correct header with -h, or uses Picard which properly maintains\n");
191 fprintf(stderr, " the header dictionary in merging.\n\n");
194 bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1);
199 typedef bam1_t *bam1_p;
201 static inline int bam1_lt(const bam1_p a, const bam1_p b)
204 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
205 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
206 } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
208 KSORT_INIT(sort, bam1_p, bam1_lt)
210 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h, int is_stdout)
215 ks_mergesort(sort, k, buf, 0);
216 name = (char*)calloc(strlen(prefix) + 20, 1);
217 if (n >= 0) sprintf(name, "%s.%.4d.bam", prefix, n);
218 else sprintf(name, "%s.bam", prefix);
219 fp = is_stdout? bam_dopen(fileno(stdout), "w") : bam_open(name, "w");
221 fprintf(stderr, "[sort_blocks] fail to create file %s.\n", name);
223 // FIXME: possible memory leak
227 bam_header_write(fp, h);
228 for (i = 0; i < k; ++i)
229 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
234 @abstract Sort an unsorted BAM file based on the chromosome order
235 and the leftmost position of an alignment
237 @param is_by_qname whether to sort by query name
238 @param fn name of the file to be sorted
239 @param prefix prefix of the output and the temporary files; upon
240 sucessess, prefix.bam will be written.
241 @param max_mem approxiate maximum memory (very inaccurate)
243 @discussion It may create multiple temporary subalignment files
244 and then merge them by calling bam_merge_core(). This function is
247 void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t max_mem, int is_stdout)
251 bam_header_t *header;
255 g_is_by_qname = is_by_qname;
257 fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
259 fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
262 header = bam_header_read(fp);
263 buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
266 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
268 if ((ret = bam_read1(fp, b)) < 0) break;
271 if (mem >= max_mem) {
272 sort_blocks(n++, k, buf, prefix, header, is_stdout);
277 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
278 if (n == 0) sort_blocks(-1, k, buf, prefix, header, is_stdout);
281 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
282 sort_blocks(n++, k, buf, prefix, header, is_stdout);
283 fnout = (char*)calloc(strlen(prefix) + 20, 1);
284 if (is_stdout) sprintf(fnout, "-");
285 else sprintf(fnout, "%s.bam", prefix);
286 fns = (char**)calloc(n, sizeof(char*));
287 for (i = 0; i < n; ++i) {
288 fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
289 sprintf(fns[i], "%s.%.4d.bam", prefix, i);
291 bam_merge_core(is_by_qname, fnout, 0, n, fns);
293 for (i = 0; i < n; ++i) {
299 for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
306 bam_header_destroy(header);
310 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
312 bam_sort_core_ext(is_by_qname, fn, prefix, max_mem, 0);
315 int bam_sort(int argc, char *argv[])
317 size_t max_mem = 500000000;
318 int c, is_by_qname = 0, is_stdout = 0;
319 while ((c = getopt(argc, argv, "nom:")) >= 0) {
321 case 'o': is_stdout = 1; break;
322 case 'n': is_by_qname = 1; break;
323 case 'm': max_mem = atol(optarg); break;
326 if (optind + 2 > argc) {
327 fprintf(stderr, "Usage: samtools sort [-on] [-m <maxMem>] <in.bam> <out.prefix>\n");
330 bam_sort_core_ext(is_by_qname, argv[optind], argv[optind+1], max_mem, is_stdout);