]> git.donarmstrong.com Git - samtools.git/blob - bam_sort.c
* merge files region-by-region. work on small examples but more tests are needed.
[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, idx;
37         bam1_t *b;
38 } heap1_t;
39
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))))
41
42 static inline int heap_lt(const heap1_t a, const heap1_t b)
43 {
44         if (g_is_by_qname) {
45                 int t;
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);
50 }
51
52 KSORT_INIT(heap, heap1_t, heap_lt)
53
54 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
55 {
56         int tempi;
57         char *temps;
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;
60 }
61
62 #define MERGE_RG     1
63 #define MERGE_UNCOMP 2
64
65 /*!
66   @abstract    Merge multiple sorted BAM.
67   @param  is_by_qname whether to sort by query name
68   @param  out  output BAM file name
69   @param  headers  name of SAM file from which to copy '@' header lines,
70                    or NULL to copy them from the first file to be merged
71   @param  n    number of files to be merged
72   @param  fn   names of files to be merged
73
74   @discussion Padding information may NOT correctly maintained. This
75   function is NOT thread safe.
76  */
77 int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn,
78                                         int flag, const char *reg)
79 {
80         bamFile fpout, *fp;
81         heap1_t *heap;
82         bam_header_t *hout = 0;
83         bam_header_t *hheaders = NULL;
84         int i, j, *RG_len = 0;
85         uint64_t idx = 0;
86         char **RG = 0;
87         bam_iter_t *iter = 0;
88
89         if (headers) {
90                 tamFile fpheaders = sam_open(headers);
91                 if (fpheaders == 0) {
92                         fprintf(stderr, "[bam_merge_core] Cannot open file `%s'. Continue anyway.\n", headers);
93                 } else {
94                         hheaders = sam_header_read(fpheaders);
95                         sam_close(fpheaders);
96                 }
97         }
98
99         g_is_by_qname = by_qname;
100         fp = (bamFile*)calloc(n, sizeof(bamFile));
101         heap = (heap1_t*)calloc(n, sizeof(heap1_t));
102         iter = (bam_iter_t*)calloc(n, sizeof(bam_iter_t));
103         // prepare RG tag
104         if (flag & MERGE_RG) {
105                 RG = (char**)calloc(n, sizeof(void*));
106                 RG_len = (int*)calloc(n, sizeof(int));
107                 for (i = 0; i != n; ++i) {
108                         int l = strlen(fn[i]);
109                         const char *s = fn[i];
110                         if (l > 4 && strcmp(s + l - 4, ".bam") == 0) l -= 4;
111                         for (j = l - 1; j >= 0; --j) if (s[j] == '/') break;
112                         ++j; l -= j;
113                         RG[i] = calloc(l + 1, 1);
114                         RG_len[i] = l;
115                         strncpy(RG[i], s + j, l);
116                 }
117         }
118         // read the first
119         for (i = 0; i != n; ++i) {
120                 bam_header_t *hin;
121                 fp[i] = bam_open(fn[i], "r");
122                 if (fp[i] == 0) {
123                         int j;
124                         fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
125                         for (j = 0; j < i; ++j) bam_close(fp[j]);
126                         free(fp); free(heap);
127                         // FIXME: possible memory leak
128                         return -1;
129                 }
130                 hin = bam_header_read(fp[i]);
131                 if (i == 0) { // the first SAM
132                         hout = hin;
133                         if (hheaders) {
134                                 // If the text headers to be swapped in include any @SQ headers,
135                                 // check that they are consistent with the existing binary list
136                                 // of reference information.
137                                 if (hheaders->n_targets > 0) {
138                                         if (hout->n_targets != hheaders->n_targets)
139                                                 fprintf(stderr, "[bam_merge_core] number of @SQ headers in `%s' differs from number of target sequences", headers);
140                                         for (j = 0; j < hout->n_targets; ++j)
141                                                 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0)
142                                                         fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence", hheaders->target_name[j], headers);
143                                 }
144                                 swap_header_text(hout, hheaders);
145                                 bam_header_destroy(hheaders);
146                                 hheaders = NULL;
147                         }
148                 } else { // validate multiple baf
149                         if (hout->n_targets != hin->n_targets) {
150                                 fprintf(stderr, "[bam_merge_core] file '%s' has different number of target sequences. Abort!\n", fn[i]);
151                                 exit(1);
152                         }
153                         for (j = 0; j < hout->n_targets; ++j) {
154                                 if (strcmp(hout->target_name[j], hin->target_name[j])) {
155                                         fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'. Abort!\n",
156                                                         hout->target_name[j], hin->target_name[j], fn[i]);
157                                         exit(1);
158                                 }
159                         }
160                         bam_header_destroy(hin);
161                 }
162         }
163
164         if (reg) {
165                 int tid, beg, end;
166                 if (bam_parse_region(hout, reg, &tid, &beg, &end) < 0) {
167                         fprintf(stderr, "[%s] Malformated region string or undefined reference name\n", __func__);
168                         return -1;
169                 }
170                 for (i = 0; i < n; ++i) {
171                         bam_index_t *idx;
172                         idx = bam_index_load(fn[i]);
173                         iter[i] = bam_iter_query(idx, tid, beg, end);
174                         bam_index_destroy(idx);
175                 }
176         }
177
178         for (i = 0; i < n; ++i) {
179                 heap1_t *h = heap + i;
180                 h->i = i;
181                 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
182                 if (bam_iter_read(fp[i], iter[i], h->b) >= 0) {
183                         h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
184                         h->idx = idx++;
185                 }
186                 else h->pos = HEAP_EMPTY;
187         }
188         if (flag & MERGE_UNCOMP) {
189                 fpout = strcmp(out, "-")? bam_open(out, "wu") : bam_dopen(fileno(stdout), "wu");
190         } else {
191                 fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
192         }
193         if (fpout == 0) {
194                 fprintf(stderr, "[%s] fail to create the output file.\n", __func__);
195                 return -1;
196         }
197         bam_header_write(fpout, hout);
198         bam_header_destroy(hout);
199
200         ks_heapmake(heap, n, heap);
201         while (heap->pos != HEAP_EMPTY) {
202                 bam1_t *b = heap->b;
203                 if ((flag & MERGE_RG) && bam_aux_get(b, "RG") == 0)
204                         bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]);
205                 bam_write1_core(fpout, &b->core, b->data_len, b->data);
206                 if ((j = bam_iter_read(fp[heap->i], iter[heap->i], b)) >= 0) {
207                         heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
208                         heap->idx = idx++;
209                 } else if (j == -1) {
210                         heap->pos = HEAP_EMPTY;
211                         free(heap->b->data); free(heap->b);
212                         heap->b = 0;
213                 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
214                 ks_heapadjust(heap, 0, n, heap);
215         }
216
217         if (flag & MERGE_RG) {
218                 for (i = 0; i != n; ++i) free(RG[i]);
219                 free(RG); free(RG_len);
220         }
221         for (i = 0; i != n; ++i) {
222                 bam_iter_destroy(iter[i]);
223                 bam_close(fp[i]);
224         }
225         bam_close(fpout);
226         free(fp); free(heap); free(iter);
227         return 0;
228 }
229
230 int bam_merge(int argc, char *argv[])
231 {
232         int c, is_by_qname = 0, flag = 0;
233         char *fn_headers = NULL, *reg = 0;
234
235         while ((c = getopt(argc, argv, "h:nruR:")) >= 0) {
236                 switch (c) {
237                 case 'r': flag |= MERGE_RG; break;
238                 case 'h': fn_headers = strdup(optarg); break;
239                 case 'n': is_by_qname = 1; break;
240                 case 'u': flag |= MERGE_UNCOMP; break;
241                 case 'R': reg = strdup(optarg); break;
242                 }
243         }
244         if (optind + 2 >= argc) {
245                 fprintf(stderr, "\n");
246                 fprintf(stderr, "Usage:   samtools merge [-nr] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
247                 fprintf(stderr, "Options: -n       sort by read names\n");
248                 fprintf(stderr, "         -r       attach RG tag (inferred from file names)\n");
249                 fprintf(stderr, "         -u       uncompressed BAM output\n");
250                 fprintf(stderr, "         -R STR   merge file in the specified region STR [all]\n");
251                 fprintf(stderr, "         -h FILE  copy the header in FILE to <out.bam> [in1.bam]\n\n");
252                 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
253                 fprintf(stderr, "      must provide the correct header with -h, or uses Picard which properly maintains\n");
254                 fprintf(stderr, "      the header dictionary in merging.\n\n");
255                 return 1;
256         }
257         bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1, flag, reg);
258         free(reg);
259         free(fn_headers);
260         return 0;
261 }
262
263 typedef bam1_t *bam1_p;
264
265 static inline int bam1_lt(const bam1_p a, const bam1_p b)
266 {
267         if (g_is_by_qname) {
268                 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
269                 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
270         } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
271 }
272 KSORT_INIT(sort, bam1_p, bam1_lt)
273
274 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h, int is_stdout)
275 {
276         char *name;
277         int i;
278         bamFile fp;
279         ks_mergesort(sort, k, buf, 0);
280         name = (char*)calloc(strlen(prefix) + 20, 1);
281         if (n >= 0) sprintf(name, "%s.%.4d.bam", prefix, n);
282         else sprintf(name, "%s.bam", prefix);
283         fp = is_stdout? bam_dopen(fileno(stdout), "w") : bam_open(name, "w");
284         if (fp == 0) {
285                 fprintf(stderr, "[sort_blocks] fail to create file %s.\n", name);
286                 free(name);
287                 // FIXME: possible memory leak
288                 return;
289         }
290         free(name);
291         bam_header_write(fp, h);
292         for (i = 0; i < k; ++i)
293                 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
294         bam_close(fp);
295 }
296
297 /*!
298   @abstract Sort an unsorted BAM file based on the chromosome order
299   and the leftmost position of an alignment
300
301   @param  is_by_qname whether to sort by query name
302   @param  fn       name of the file to be sorted
303   @param  prefix   prefix of the output and the temporary files; upon
304                            sucessess, prefix.bam will be written.
305   @param  max_mem  approxiate maximum memory (very inaccurate)
306
307   @discussion It may create multiple temporary subalignment files
308   and then merge them by calling bam_merge_core(). This function is
309   NOT thread safe.
310  */
311 void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t max_mem, int is_stdout)
312 {
313         int n, ret, k, i;
314         size_t mem;
315         bam_header_t *header;
316         bamFile fp;
317         bam1_t *b, **buf;
318
319         g_is_by_qname = is_by_qname;
320         n = k = 0; mem = 0;
321         fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
322         if (fp == 0) {
323                 fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
324                 return;
325         }
326         header = bam_header_read(fp);
327         buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
328         // write sub files
329         for (;;) {
330                 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
331                 b = buf[k];
332                 if ((ret = bam_read1(fp, b)) < 0) break;
333                 mem += ret;
334                 ++k;
335                 if (mem >= max_mem) {
336                         sort_blocks(n++, k, buf, prefix, header, 0);
337                         mem = 0; k = 0;
338                 }
339         }
340         if (ret != -1)
341                 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
342         if (n == 0) sort_blocks(-1, k, buf, prefix, header, is_stdout);
343         else { // then merge
344                 char **fns, *fnout;
345                 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
346                 sort_blocks(n++, k, buf, prefix, header, 0);
347                 fnout = (char*)calloc(strlen(prefix) + 20, 1);
348                 if (is_stdout) sprintf(fnout, "-");
349                 else sprintf(fnout, "%s.bam", prefix);
350                 fns = (char**)calloc(n, sizeof(char*));
351                 for (i = 0; i < n; ++i) {
352                         fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
353                         sprintf(fns[i], "%s.%.4d.bam", prefix, i);
354                 }
355                 bam_merge_core(is_by_qname, fnout, 0, n, fns, 0, 0);
356                 free(fnout);
357                 for (i = 0; i < n; ++i) {
358                         unlink(fns[i]);
359                         free(fns[i]);
360                 }
361                 free(fns);
362         }
363         for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
364                 if (buf[k]) {
365                         free(buf[k]->data);
366                         free(buf[k]);
367                 }
368         }
369         free(buf);
370         bam_header_destroy(header);
371         bam_close(fp);
372 }
373
374 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
375 {
376         bam_sort_core_ext(is_by_qname, fn, prefix, max_mem, 0);
377 }
378
379 int bam_sort(int argc, char *argv[])
380 {
381         size_t max_mem = 500000000;
382         int c, is_by_qname = 0, is_stdout = 0;
383         while ((c = getopt(argc, argv, "nom:")) >= 0) {
384                 switch (c) {
385                 case 'o': is_stdout = 1; break;
386                 case 'n': is_by_qname = 1; break;
387                 case 'm': max_mem = atol(optarg); break;
388                 }
389         }
390         if (optind + 2 > argc) {
391                 fprintf(stderr, "Usage: samtools sort [-on] [-m <maxMem>] <in.bam> <out.prefix>\n");
392                 return 1;
393         }
394         bam_sort_core_ext(is_by_qname, argv[optind], argv[optind+1], max_mem, is_stdout);
395         return 0;
396 }