]> git.donarmstrong.com Git - samtools.git/blob - bam_sort.c
* samtools-0.1.5-28 (r444)
[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 /*!
53   @abstract    Merge multiple sorted BAM.
54   @param  is_by_qname whether to sort by query name
55   @param  out  output BAM file name
56   @param  n    number of files to be merged
57   @param  fn   names of files to be merged
58
59   @discussion Padding information may NOT correctly maintained. This
60   function is NOT thread safe.
61  */
62 void bam_merge_core(int by_qname, const char *out, int n, char * const *fn)
63 {
64         bamFile fpout, *fp;
65         heap1_t *heap;
66         bam_header_t *hout = 0;
67         int i, j;
68
69         g_is_by_qname = by_qname;
70         fp = (bamFile*)calloc(n, sizeof(bamFile));
71         heap = (heap1_t*)calloc(n, sizeof(heap1_t));
72         for (i = 0; i != n; ++i) {
73                 heap1_t *h;
74                 bam_header_t *hin;
75                 assert(fp[i] = bam_open(fn[i], "r"));
76                 hin = bam_header_read(fp[i]);
77                 if (i == 0) hout = hin;
78                 else { // validate multiple baf
79                         if (hout->n_targets != hin->n_targets) {
80                                 fprintf(stderr, "[bam_merge_core] file '%s' has different number of target sequences. Abort!\n", fn[i]);
81                                 exit(1);
82                         }
83                         for (j = 0; j < hout->n_targets; ++j) {
84                                 if (strcmp(hout->target_name[j], hin->target_name[j])) {
85                                         fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'. Abort!\n",
86                                                         hout->target_name[j], hin->target_name[j], fn[i]);
87                                         exit(1);
88                                 }
89                                 if (hout->target_len[j] != hin->target_len[j])
90                                         fprintf(stderr, "[bam_merge_core] different target sequence length: %d != %d in file '%s'. Continue.\n",
91                                                         hout->target_len[j], hin->target_len[j], fn[i]);
92                         }
93                         bam_header_destroy(hin);
94                 }
95                 h = heap + i;
96                 h->i = i;
97                 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
98                 if (bam_read1(fp[i], h->b) >= 0)
99                         h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
100                 else h->pos = HEAP_EMPTY;
101         }
102         fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
103         assert(fpout);
104         bam_header_write(fpout, hout);
105         bam_header_destroy(hout);
106
107         ks_heapmake(heap, n, heap);
108         while (heap->pos != HEAP_EMPTY) {
109                 bam1_t *b = heap->b;
110                 bam_write1_core(fpout, &b->core, b->data_len, b->data);
111                 if ((j = bam_read1(fp[heap->i], b)) >= 0) {
112                         heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
113                 } else if (j == -1) {
114                         heap->pos = HEAP_EMPTY;
115                         free(heap->b->data); free(heap->b);
116                         heap->b = 0;
117                 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
118                 ks_heapadjust(heap, 0, n, heap);
119         }
120
121         for (i = 0; i != n; ++i) bam_close(fp[i]);
122         bam_close(fpout);
123         free(fp); free(heap);
124 }
125 int bam_merge(int argc, char *argv[])
126 {
127         int c, is_by_qname = 0;
128         while ((c = getopt(argc, argv, "n")) >= 0) {
129                 switch (c) {
130                 case 'n': is_by_qname = 1; break;
131                 }
132         }
133         if (optind + 2 >= argc) {
134                 fprintf(stderr, "Usage: samtools merge [-n] <out.bam> <in1.bam> <in2.bam> [...]\n");
135                 return 1;
136         }
137         bam_merge_core(is_by_qname, argv[optind], argc - optind - 1, argv + optind + 1);
138         return 0;
139 }
140
141 typedef bam1_t *bam1_p;
142
143 static inline int bam1_lt(const bam1_p a, const bam1_p b)
144 {
145         if (g_is_by_qname) {
146                 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
147                 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
148         } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
149 }
150 KSORT_INIT(sort, bam1_p, bam1_lt)
151
152 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h)
153 {
154         char *name;
155         int i;
156         bamFile fp;
157         ks_mergesort(sort, k, buf, 0);
158         name = (char*)calloc(strlen(prefix) + 20, 1);
159         if (n >= 0) sprintf(name, "%s.%.4d.bam", prefix, n);
160         else sprintf(name, "%s.bam", prefix);
161         assert(fp = bam_open(name, "w"));
162         free(name);
163         bam_header_write(fp, h);
164         for (i = 0; i < k; ++i)
165                 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
166         bam_close(fp);
167 }
168
169 /*!
170   @abstract Sort an unsorted BAM file based on the chromosome order
171   and the leftmost position of an alignment
172
173   @param  is_by_qname whether to sort by query name
174   @param  fn       name of the file to be sorted
175   @param  prefix   prefix of the output and the temporary files; upon
176                            sucessess, prefix.bam will be written.
177   @param  max_mem  approxiate maximum memory (very inaccurate)
178
179   @discussion It may create multiple temporary subalignment files
180   and then merge them by calling bam_merge_core(). This function is
181   NOT thread safe.
182  */
183 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
184 {
185         int n, ret, k, i;
186         size_t mem;
187         bam_header_t *header;
188         bamFile fp;
189         bam1_t *b, **buf;
190
191         g_is_by_qname = is_by_qname;
192         n = k = 0; mem = 0;
193         fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
194         assert(fp);
195         header = bam_header_read(fp);
196         buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
197         // write sub files
198         for (;;) {
199                 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
200                 b = buf[k];
201                 if ((ret = bam_read1(fp, b)) < 0) break;
202                 mem += ret;
203                 ++k;
204                 if (mem >= max_mem) {
205                         sort_blocks(n++, k, buf, prefix, header);
206                         mem = 0; k = 0;
207                 }
208         }
209         if (ret != -1)
210                 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
211         if (n == 0) sort_blocks(-1, k, buf, prefix, header);
212         else { // then merge
213                 char **fns, *fnout;
214                 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
215                 sort_blocks(n++, k, buf, prefix, header);
216                 fnout = (char*)calloc(strlen(prefix) + 20, 1);
217                 sprintf(fnout, "%s.bam", prefix);
218                 fns = (char**)calloc(n, sizeof(char*));
219                 for (i = 0; i < n; ++i) {
220                         fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
221                         sprintf(fns[i], "%s.%.4d.bam", prefix, i);
222                 }
223                 bam_merge_core(is_by_qname, fnout, n, fns);
224                 free(fnout);
225                 for (i = 0; i < n; ++i) {
226 //                      unlink(fns[i]);
227                         free(fns[i]);
228                 }
229                 free(fns);
230         }
231         for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
232                 if (buf[k]) {
233                         free(buf[k]->data);
234                         free(buf[k]);
235                 }
236         }
237         free(buf);
238         bam_header_destroy(header);
239         bam_close(fp);
240 }
241
242 int bam_sort(int argc, char *argv[])
243 {
244         size_t max_mem = 500000000;
245         int c, is_by_qname = 0;
246         while ((c = getopt(argc, argv, "nm:")) >= 0) {
247                 switch (c) {
248                 case 'n': is_by_qname = 1; break;
249                 case 'm': max_mem = atol(optarg); break;
250                 }
251         }
252         if (optind + 2 > argc) {
253                 fprintf(stderr, "Usage: samtools sort [-n] [-m <maxMem>] <in.bam> <out.prefix>\n");
254                 return 1;
255         }
256         bam_sort_core(is_by_qname, argv[optind], argv[optind+1], max_mem);
257         return 0;
258 }