Merge branch 'upstream'
[samtools.git] / bam_sort.c
1 #include <stdlib.h>
2 #include <ctype.h>
3 #include <assert.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include "bam.h"
8 #include "ksort.h"
9
10 static int g_is_by_qname = 0;
11
12 static inline int strnum_cmp(const char *a, const char *b)
13 {
14         char *pa, *pb;
15         pa = (char*)a; pb = (char*)b;
16         while (*pa && *pb) {
17                 if (isdigit(*pa) && isdigit(*pb)) {
18                         long ai, bi;
19                         ai = strtol(pa, &pa, 10);
20                         bi = strtol(pb, &pb, 10);
21                         if (ai != bi) return ai<bi? -1 : ai>bi? 1 : 0;
22                 } else {
23                         if (*pa != *pb) break;
24                         ++pa; ++pb;
25                 }
26         }
27         if (*pa == *pb)
28                 return (pa-a) < (pb-b)? -1 : (pa-a) > (pb-b)? 1 : 0;
29         return *pa<*pb? -1 : *pa>*pb? 1 : 0;
30 }
31
32 #define HEAP_EMPTY 0xffffffffffffffffull
33
34 typedef struct {
35         int i;
36         uint64_t pos;
37         bam1_t *b;
38 } heap1_t;
39
40 static inline int heap_lt(const heap1_t a, const heap1_t b)
41 {
42         if (g_is_by_qname) {
43                 int t;
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);
48 }
49
50 KSORT_INIT(heap, heap1_t, heap_lt)
51
52 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
53 {
54         int tempi;
55         char *temps;
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;
58 }
59
60 /*!
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
68
69   @discussion Padding information may NOT correctly maintained. This
70   function is NOT thread safe.
71  */
72 void bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn)
73 {
74         bamFile fpout, *fp;
75         heap1_t *heap;
76         bam_header_t *hout = 0;
77         bam_header_t *hheaders = NULL;
78         int i, j;
79
80         if (headers) {
81                 tamFile fpheaders = sam_open(headers);
82                 if (fpheaders == 0) {
83                         fprintf(stderr, "[bam_merge_core] Cannot open file `%s'. Continue anyway.\n", headers);
84                 } else {
85                         hheaders = sam_header_read(fpheaders);
86                         sam_close(fpheaders);
87                 }
88         }
89
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) {
94                 heap1_t *h;
95                 bam_header_t *hin;
96                 assert(fp[i] = bam_open(fn[i], "r"));
97                 hin = bam_header_read(fp[i]);
98                 if (i == 0) { // the first SAM
99                         hout = hin;
100                         if (hheaders) {
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);
110                                 }
111                                 swap_header_text(hout, hheaders);
112                                 bam_header_destroy(hheaders);
113                                 hheaders = NULL;
114                         }
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]);
118                                 exit(1);
119                         }
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]);
124                                         exit(1);
125                                 }
126                         }
127                         bam_header_destroy(hin);
128                 }
129                 h = heap + i;
130                 h->i = i;
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;
135         }
136         fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
137         assert(fpout);
138         bam_header_write(fpout, hout);
139         bam_header_destroy(hout);
140
141         ks_heapmake(heap, n, heap);
142         while (heap->pos != HEAP_EMPTY) {
143                 bam1_t *b = heap->b;
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);
150                         heap->b = 0;
151                 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
152                 ks_heapadjust(heap, 0, n, heap);
153         }
154
155         for (i = 0; i != n; ++i) bam_close(fp[i]);
156         bam_close(fpout);
157         free(fp); free(heap);
158 }
159 int bam_merge(int argc, char *argv[])
160 {
161         int c, is_by_qname = 0;
162         char *fn_headers = NULL;
163
164         while ((c = getopt(argc, argv, "h:n")) >= 0) {
165                 switch (c) {
166                 case 'h': fn_headers = strdup(optarg); break;
167                 case 'n': is_by_qname = 1; break;
168                 }
169         }
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");
178                 return 1;
179         }
180         bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1);
181         free(fn_headers);
182         return 0;
183 }
184
185 typedef bam1_t *bam1_p;
186
187 static inline int bam1_lt(const bam1_p a, const bam1_p b)
188 {
189         if (g_is_by_qname) {
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));
193 }
194 KSORT_INIT(sort, bam1_p, bam1_lt)
195
196 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h)
197 {
198         char *name;
199         int i;
200         bamFile fp;
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"));
206         free(name);
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);
210         bam_close(fp);
211 }
212
213 /*!
214   @abstract Sort an unsorted BAM file based on the chromosome order
215   and the leftmost position of an alignment
216
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)
222
223   @discussion It may create multiple temporary subalignment files
224   and then merge them by calling bam_merge_core(). This function is
225   NOT thread safe.
226  */
227 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
228 {
229         int n, ret, k, i;
230         size_t mem;
231         bam_header_t *header;
232         bamFile fp;
233         bam1_t *b, **buf;
234
235         g_is_by_qname = is_by_qname;
236         n = k = 0; mem = 0;
237         fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
238         assert(fp);
239         header = bam_header_read(fp);
240         buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
241         // write sub files
242         for (;;) {
243                 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
244                 b = buf[k];
245                 if ((ret = bam_read1(fp, b)) < 0) break;
246                 mem += ret;
247                 ++k;
248                 if (mem >= max_mem) {
249                         sort_blocks(n++, k, buf, prefix, header);
250                         mem = 0; k = 0;
251                 }
252         }
253         if (ret != -1)
254                 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
255         if (n == 0) sort_blocks(-1, k, buf, prefix, header);
256         else { // then merge
257                 char **fns, *fnout;
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);
266                 }
267                 bam_merge_core(is_by_qname, fnout, 0, n, fns);
268                 free(fnout);
269                 for (i = 0; i < n; ++i) {
270                         unlink(fns[i]);
271                         free(fns[i]);
272                 }
273                 free(fns);
274         }
275         for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
276                 if (buf[k]) {
277                         free(buf[k]->data);
278                         free(buf[k]);
279                 }
280         }
281         free(buf);
282         bam_header_destroy(header);
283         bam_close(fp);
284 }
285
286 int bam_sort(int argc, char *argv[])
287 {
288         size_t max_mem = 500000000;
289         int c, is_by_qname = 0;
290         while ((c = getopt(argc, argv, "nm:")) >= 0) {
291                 switch (c) {
292                 case 'n': is_by_qname = 1; break;
293                 case 'm': max_mem = atol(optarg); break;
294                 }
295         }
296         if (optind + 2 > argc) {
297                 fprintf(stderr, "Usage: samtools sort [-n] [-m <maxMem>] <in.bam> <out.prefix>\n");
298                 return 1;
299         }
300         bam_sort_core(is_by_qname, argv[optind], argv[optind+1], max_mem);
301         return 0;
302 }