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 static inline int heap_lt(const heap1_t a, const heap1_t b)
44 if (a.b == 0 || b.b == 0) return a.b == 0? 1 : 0;
45 t = strnum_cmp(bam1_qname(a.b), bam1_qname(b.b));
46 return (t > 0 || (t == 0 && a.pos > b.pos));
47 } else return (a.pos > b.pos);
50 KSORT_INIT(heap, heap1_t, heap_lt)
52 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
56 tempi = h1->l_text, h1->l_text = h2->l_text, h2->l_text = tempi;
57 temps = h1->text, h1->text = h2->text, h2->text = temps;
61 @abstract Merge multiple sorted BAM.
62 @param is_by_qname whether to sort by query name
63 @param out output BAM file name
64 @param headers name of SAM file from which to copy '@' header lines,
65 or NULL to copy them from the first file to be merged
66 @param n number of files to be merged
67 @param fn names of files to be merged
69 @discussion Padding information may NOT correctly maintained. This
70 function is NOT thread safe.
72 void bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn)
76 bam_header_t *hout = 0;
77 bam_header_t *hheaders = NULL;
81 tamFile fpheaders = sam_open(headers);
83 fprintf(stderr, "[bam_merge_core] Cannot open file `%s'. Continue anyway.\n", headers);
85 hheaders = sam_header_read(fpheaders);
90 g_is_by_qname = by_qname;
91 fp = (bamFile*)calloc(n, sizeof(bamFile));
92 heap = (heap1_t*)calloc(n, sizeof(heap1_t));
93 for (i = 0; i != n; ++i) {
96 assert(fp[i] = bam_open(fn[i], "r"));
97 hin = bam_header_read(fp[i]);
98 if (i == 0) { // the first SAM
101 // If the text headers to be swapped in include any @SQ headers,
102 // check that they are consistent with the existing binary list
103 // of reference information.
104 if (hheaders->n_targets > 0) {
105 if (hout->n_targets != hheaders->n_targets)
106 fprintf(stderr, "[bam_merge_core] number of @SQ headers in `%s' differs from number of target sequences", headers);
107 for (j = 0; j < hout->n_targets; ++j)
108 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0)
109 fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence", hheaders->target_name[j], headers);
111 swap_header_text(hout, hheaders);
112 bam_header_destroy(hheaders);
115 } else { // validate multiple baf
116 if (hout->n_targets != hin->n_targets) {
117 fprintf(stderr, "[bam_merge_core] file '%s' has different number of target sequences. Abort!\n", fn[i]);
120 for (j = 0; j < hout->n_targets; ++j) {
121 if (strcmp(hout->target_name[j], hin->target_name[j])) {
122 fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'. Abort!\n",
123 hout->target_name[j], hin->target_name[j], fn[i]);
127 bam_header_destroy(hin);
131 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
132 if (bam_read1(fp[i], h->b) >= 0)
133 h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
134 else h->pos = HEAP_EMPTY;
136 fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
138 bam_header_write(fpout, hout);
139 bam_header_destroy(hout);
141 ks_heapmake(heap, n, heap);
142 while (heap->pos != HEAP_EMPTY) {
144 bam_write1_core(fpout, &b->core, b->data_len, b->data);
145 if ((j = bam_read1(fp[heap->i], b)) >= 0) {
146 heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
147 } else if (j == -1) {
148 heap->pos = HEAP_EMPTY;
149 free(heap->b->data); free(heap->b);
151 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
152 ks_heapadjust(heap, 0, n, heap);
155 for (i = 0; i != n; ++i) bam_close(fp[i]);
157 free(fp); free(heap);
159 int bam_merge(int argc, char *argv[])
161 int c, is_by_qname = 0;
162 char *fn_headers = NULL;
164 while ((c = getopt(argc, argv, "h:n")) >= 0) {
166 case 'h': fn_headers = strdup(optarg); break;
167 case 'n': is_by_qname = 1; break;
170 if (optind + 2 >= argc) {
171 fprintf(stderr, "\n");
172 fprintf(stderr, "Usage: samtools merge [-n] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
173 fprintf(stderr, "Options: -n sort by read names\n");
174 fprintf(stderr, " -h FILE copy the header in FILE to <out.bam> [in1.bam]\n\n");
175 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
176 fprintf(stderr, " must provide the correct header with -h, or uses Picard which properly maintains\n");
177 fprintf(stderr, " the header dictionary in merging.\n\n");
180 bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1);
185 typedef bam1_t *bam1_p;
187 static inline int bam1_lt(const bam1_p a, const bam1_p b)
190 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
191 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
192 } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
194 KSORT_INIT(sort, bam1_p, bam1_lt)
196 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h)
201 ks_mergesort(sort, k, buf, 0);
202 name = (char*)calloc(strlen(prefix) + 20, 1);
203 if (n >= 0) sprintf(name, "%s.%.4d.bam", prefix, n);
204 else sprintf(name, "%s.bam", prefix);
205 assert(fp = bam_open(name, "w"));
207 bam_header_write(fp, h);
208 for (i = 0; i < k; ++i)
209 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
214 @abstract Sort an unsorted BAM file based on the chromosome order
215 and the leftmost position of an alignment
217 @param is_by_qname whether to sort by query name
218 @param fn name of the file to be sorted
219 @param prefix prefix of the output and the temporary files; upon
220 sucessess, prefix.bam will be written.
221 @param max_mem approxiate maximum memory (very inaccurate)
223 @discussion It may create multiple temporary subalignment files
224 and then merge them by calling bam_merge_core(). This function is
227 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
231 bam_header_t *header;
235 g_is_by_qname = is_by_qname;
237 fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
239 header = bam_header_read(fp);
240 buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
243 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
245 if ((ret = bam_read1(fp, b)) < 0) break;
248 if (mem >= max_mem) {
249 sort_blocks(n++, k, buf, prefix, header);
254 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
255 if (n == 0) sort_blocks(-1, k, buf, prefix, header);
258 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
259 sort_blocks(n++, k, buf, prefix, header);
260 fnout = (char*)calloc(strlen(prefix) + 20, 1);
261 sprintf(fnout, "%s.bam", prefix);
262 fns = (char**)calloc(n, sizeof(char*));
263 for (i = 0; i < n; ++i) {
264 fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
265 sprintf(fns[i], "%s.%.4d.bam", prefix, i);
267 bam_merge_core(is_by_qname, fnout, 0, n, fns);
269 for (i = 0; i < n; ++i) {
275 for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
282 bam_header_destroy(header);
286 int bam_sort(int argc, char *argv[])
288 size_t max_mem = 500000000;
289 int c, is_by_qname = 0;
290 while ((c = getopt(argc, argv, "nm:")) >= 0) {
292 case 'n': is_by_qname = 1; break;
293 case 'm': max_mem = atol(optarg); break;
296 if (optind + 2 > argc) {
297 fprintf(stderr, "Usage: samtools sort [-n] [-m <maxMem>] <in.bam> <out.prefix>\n");
300 bam_sort_core(is_by_qname, argv[optind], argv[optind+1], max_mem);