]> git.donarmstrong.com Git - samtools.git/blob - bam_sort.c
* samtools-0.1.6-2 (r457)
[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                 fp[i] = bam_open(fn[i], "r");
97                 if (fp[i] == 0) {
98                         int j;
99                         fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
100                         for (j = 0; j < i; ++j) bam_close(fp[j]);
101                         free(fp); free(heap);
102                         // FIXME: possible memory leak
103                         return;
104                 }
105                 hin = bam_header_read(fp[i]);
106                 if (i == 0) { // the first SAM
107                         hout = hin;
108                         if (hheaders) {
109                                 // If the text headers to be swapped in include any @SQ headers,
110                                 // check that they are consistent with the existing binary list
111                                 // of reference information.
112                                 if (hheaders->n_targets > 0) {
113                                         if (hout->n_targets != hheaders->n_targets)
114                                                 fprintf(stderr, "[bam_merge_core] number of @SQ headers in `%s' differs from number of target sequences", headers);
115                                         for (j = 0; j < hout->n_targets; ++j)
116                                                 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0)
117                                                         fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence", hheaders->target_name[j], headers);
118                                 }
119                                 swap_header_text(hout, hheaders);
120                                 bam_header_destroy(hheaders);
121                                 hheaders = NULL;
122                         }
123                 } else { // validate multiple baf
124                         if (hout->n_targets != hin->n_targets) {
125                                 fprintf(stderr, "[bam_merge_core] file '%s' has different number of target sequences. Abort!\n", fn[i]);
126                                 exit(1);
127                         }
128                         for (j = 0; j < hout->n_targets; ++j) {
129                                 if (strcmp(hout->target_name[j], hin->target_name[j])) {
130                                         fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'. Abort!\n",
131                                                         hout->target_name[j], hin->target_name[j], fn[i]);
132                                         exit(1);
133                                 }
134                         }
135                         bam_header_destroy(hin);
136                 }
137                 h = heap + i;
138                 h->i = i;
139                 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
140                 if (bam_read1(fp[i], h->b) >= 0)
141                         h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)h->b->core.pos<<1 | bam1_strand(h->b);
142                 else h->pos = HEAP_EMPTY;
143         }
144         fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
145         assert(fpout);
146         bam_header_write(fpout, hout);
147         bam_header_destroy(hout);
148
149         ks_heapmake(heap, n, heap);
150         while (heap->pos != HEAP_EMPTY) {
151                 bam1_t *b = heap->b;
152                 bam_write1_core(fpout, &b->core, b->data_len, b->data);
153                 if ((j = bam_read1(fp[heap->i], b)) >= 0) {
154                         heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)b->core.pos<<1 | bam1_strand(b);
155                 } else if (j == -1) {
156                         heap->pos = HEAP_EMPTY;
157                         free(heap->b->data); free(heap->b);
158                         heap->b = 0;
159                 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
160                 ks_heapadjust(heap, 0, n, heap);
161         }
162
163         for (i = 0; i != n; ++i) bam_close(fp[i]);
164         bam_close(fpout);
165         free(fp); free(heap);
166 }
167 int bam_merge(int argc, char *argv[])
168 {
169         int c, is_by_qname = 0;
170         char *fn_headers = NULL;
171
172         while ((c = getopt(argc, argv, "h:n")) >= 0) {
173                 switch (c) {
174                 case 'h': fn_headers = strdup(optarg); break;
175                 case 'n': is_by_qname = 1; break;
176                 }
177         }
178         if (optind + 2 >= argc) {
179                 fprintf(stderr, "\n");
180                 fprintf(stderr, "Usage:   samtools merge [-n] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
181                 fprintf(stderr, "Options: -n       sort by read names\n");
182                 fprintf(stderr, "         -h FILE  copy the header in FILE to <out.bam> [in1.bam]\n\n");
183                 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
184                 fprintf(stderr, "      must provide the correct header with -h, or uses Picard which properly maintains\n");
185                 fprintf(stderr, "      the header dictionary in merging.\n\n");
186                 return 1;
187         }
188         bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1);
189         free(fn_headers);
190         return 0;
191 }
192
193 typedef bam1_t *bam1_p;
194
195 static inline int bam1_lt(const bam1_p a, const bam1_p b)
196 {
197         if (g_is_by_qname) {
198                 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
199                 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos))));
200         } else return (((uint64_t)a->core.tid<<32|a->core.pos) < ((uint64_t)b->core.tid<<32|b->core.pos));
201 }
202 KSORT_INIT(sort, bam1_p, bam1_lt)
203
204 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h)
205 {
206         char *name;
207         int i;
208         bamFile fp;
209         ks_mergesort(sort, k, buf, 0);
210         name = (char*)calloc(strlen(prefix) + 20, 1);
211         if (n >= 0) sprintf(name, "%s.%.4d.bam", prefix, n);
212         else sprintf(name, "%s.bam", prefix);
213         fp = bam_open(name, "w");
214         if (fp == 0) {
215                 fprintf(stderr, "[sort_blocks] fail to create file %s.\n", name);
216                 free(name);
217                 // FIXME: possible memory leak
218                 return;
219         }
220         free(name);
221         bam_header_write(fp, h);
222         for (i = 0; i < k; ++i)
223                 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
224         bam_close(fp);
225 }
226
227 /*!
228   @abstract Sort an unsorted BAM file based on the chromosome order
229   and the leftmost position of an alignment
230
231   @param  is_by_qname whether to sort by query name
232   @param  fn       name of the file to be sorted
233   @param  prefix   prefix of the output and the temporary files; upon
234                            sucessess, prefix.bam will be written.
235   @param  max_mem  approxiate maximum memory (very inaccurate)
236
237   @discussion It may create multiple temporary subalignment files
238   and then merge them by calling bam_merge_core(). This function is
239   NOT thread safe.
240  */
241 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
242 {
243         int n, ret, k, i;
244         size_t mem;
245         bam_header_t *header;
246         bamFile fp;
247         bam1_t *b, **buf;
248
249         g_is_by_qname = is_by_qname;
250         n = k = 0; mem = 0;
251         fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
252         if (fp == 0) {
253                 fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
254                 return;
255         }
256         header = bam_header_read(fp);
257         buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
258         // write sub files
259         for (;;) {
260                 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
261                 b = buf[k];
262                 if ((ret = bam_read1(fp, b)) < 0) break;
263                 mem += ret;
264                 ++k;
265                 if (mem >= max_mem) {
266                         sort_blocks(n++, k, buf, prefix, header);
267                         mem = 0; k = 0;
268                 }
269         }
270         if (ret != -1)
271                 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
272         if (n == 0) sort_blocks(-1, k, buf, prefix, header);
273         else { // then merge
274                 char **fns, *fnout;
275                 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
276                 sort_blocks(n++, k, buf, prefix, header);
277                 fnout = (char*)calloc(strlen(prefix) + 20, 1);
278                 sprintf(fnout, "%s.bam", prefix);
279                 fns = (char**)calloc(n, sizeof(char*));
280                 for (i = 0; i < n; ++i) {
281                         fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
282                         sprintf(fns[i], "%s.%.4d.bam", prefix, i);
283                 }
284                 bam_merge_core(is_by_qname, fnout, 0, n, fns);
285                 free(fnout);
286                 for (i = 0; i < n; ++i) {
287                         unlink(fns[i]);
288                         free(fns[i]);
289                 }
290                 free(fns);
291         }
292         for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
293                 if (buf[k]) {
294                         free(buf[k]->data);
295                         free(buf[k]);
296                 }
297         }
298         free(buf);
299         bam_header_destroy(header);
300         bam_close(fp);
301 }
302
303 int bam_sort(int argc, char *argv[])
304 {
305         size_t max_mem = 500000000;
306         int c, is_by_qname = 0;
307         while ((c = getopt(argc, argv, "nm:")) >= 0) {
308                 switch (c) {
309                 case 'n': is_by_qname = 1; break;
310                 case 'm': max_mem = atol(optarg); break;
311                 }
312         }
313         if (optind + 2 > argc) {
314                 fprintf(stderr, "Usage: samtools sort [-n] [-m <maxMem>] <in.bam> <out.prefix>\n");
315                 return 1;
316         }
317         bam_sort_core(is_by_qname, argv[optind], argv[optind+1], max_mem);
318         return 0;
319 }