]> git.donarmstrong.com Git - samtools.git/blob - bam_sort.c
updated the alphanum comparison function
[samtools.git] / bam_sort.c
1 #include <stdlib.h>
2 #include <ctype.h>
3 #include <assert.h>
4 #include <errno.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include "bam.h"
9 #include "ksort.h"
10
11 static int g_is_by_qname = 0;
12
13 static int strnum_cmp(const char *_a, const char *_b)
14 {
15         const unsigned char *a = (const unsigned char*)_a, *b = (const unsigned char*)_b;
16         const unsigned char *pa = a, *pb = b;
17         while (*pa && *pb) {
18                 if (isdigit(*pa) && isdigit(*pb)) {
19                         while (*pa == '0') ++pa;
20                         while (*pb == '0') ++pb;
21                         while (isdigit(*pa) && isdigit(*pb) && *pa == *pb) ++pa, ++pb;
22                         if (isdigit(*pa) && isdigit(*pb)) {
23                                 int i = 0;
24                                 while (isdigit(pa[i]) && isdigit(pb[i])) ++i;
25                                 return isdigit(pa[i])? 1 : isdigit(pb[i])? -1 : (int)*pa - (int)*pb;
26                         } else if (isdigit(*pa)) return 1;
27                         else if (isdigit(*pb)) return -1;
28                         else if (pa - a != pb - b) return pa - a < pb - b? 1 : -1;
29                 } else {
30                         if (*pa != *pb) return (int)*pa - (int)*pb;
31                         ++pa; ++pb;
32                 }
33         }
34         return *pa? 1 : *pb? -1 : 0;
35 }
36
37 #define HEAP_EMPTY 0xffffffffffffffffull
38
39 typedef struct {
40         int i;
41         uint64_t pos, idx;
42         bam1_t *b;
43 } heap1_t;
44
45 #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))))
46
47 static inline int heap_lt(const heap1_t a, const heap1_t b)
48 {
49         if (g_is_by_qname) {
50                 int t;
51                 if (a.b == 0 || b.b == 0) return a.b == 0? 1 : 0;
52                 t = strnum_cmp(bam1_qname(a.b), bam1_qname(b.b));
53                 return (t > 0 || (t == 0 && __pos_cmp(a, b)));
54         } else return __pos_cmp(a, b);
55 }
56
57 KSORT_INIT(heap, heap1_t, heap_lt)
58
59 static void swap_header_targets(bam_header_t *h1, bam_header_t *h2)
60 {
61         bam_header_t t;
62         t.n_targets = h1->n_targets, h1->n_targets = h2->n_targets, h2->n_targets = t.n_targets;
63         t.target_name = h1->target_name, h1->target_name = h2->target_name, h2->target_name = t.target_name;
64         t.target_len = h1->target_len, h1->target_len = h2->target_len, h2->target_len = t.target_len;
65 }
66
67 static void swap_header_text(bam_header_t *h1, bam_header_t *h2)
68 {
69         int tempi;
70         char *temps;
71         tempi = h1->l_text, h1->l_text = h2->l_text, h2->l_text = tempi;
72         temps = h1->text, h1->text = h2->text, h2->text = temps;
73 }
74
75 #define MERGE_RG     1
76 #define MERGE_UNCOMP 2
77 #define MERGE_LEVEL1 4
78 #define MERGE_FORCE  8
79
80 /*!
81   @abstract    Merge multiple sorted BAM.
82   @param  is_by_qname whether to sort by query name
83   @param  out  output BAM file name
84   @param  headers  name of SAM file from which to copy '@' header lines,
85                    or NULL to copy them from the first file to be merged
86   @param  n    number of files to be merged
87   @param  fn   names of files to be merged
88
89   @discussion Padding information may NOT correctly maintained. This
90   function is NOT thread safe.
91  */
92 int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn,
93                                         int flag, const char *reg)
94 {
95         bamFile fpout, *fp;
96         heap1_t *heap;
97         bam_header_t *hout = 0;
98         bam_header_t *hheaders = NULL;
99         int i, j, *RG_len = 0;
100         uint64_t idx = 0;
101         char **RG = 0;
102         bam_iter_t *iter = 0;
103
104         if (headers) {
105                 tamFile fpheaders = sam_open(headers);
106                 if (fpheaders == 0) {
107                         const char *message = strerror(errno);
108                         fprintf(stderr, "[bam_merge_core] cannot open '%s': %s\n", headers, message);
109                         return -1;
110                 }
111                 hheaders = sam_header_read(fpheaders);
112                 sam_close(fpheaders);
113         }
114
115         g_is_by_qname = by_qname;
116         fp = (bamFile*)calloc(n, sizeof(bamFile));
117         heap = (heap1_t*)calloc(n, sizeof(heap1_t));
118         iter = (bam_iter_t*)calloc(n, sizeof(bam_iter_t));
119         // prepare RG tag
120         if (flag & MERGE_RG) {
121                 RG = (char**)calloc(n, sizeof(void*));
122                 RG_len = (int*)calloc(n, sizeof(int));
123                 for (i = 0; i != n; ++i) {
124                         int l = strlen(fn[i]);
125                         const char *s = fn[i];
126                         if (l > 4 && strcmp(s + l - 4, ".bam") == 0) l -= 4;
127                         for (j = l - 1; j >= 0; --j) if (s[j] == '/') break;
128                         ++j; l -= j;
129                         RG[i] = calloc(l + 1, 1);
130                         RG_len[i] = l;
131                         strncpy(RG[i], s + j, l);
132                 }
133         }
134         // read the first
135         for (i = 0; i != n; ++i) {
136                 bam_header_t *hin;
137                 fp[i] = bam_open(fn[i], "r");
138                 if (fp[i] == 0) {
139                         int j;
140                         fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
141                         for (j = 0; j < i; ++j) bam_close(fp[j]);
142                         free(fp); free(heap);
143                         // FIXME: possible memory leak
144                         return -1;
145                 }
146                 hin = bam_header_read(fp[i]);
147                 if (i == 0) { // the first BAM
148                         hout = hin;
149                 } else { // validate multiple baf
150                         int min_n_targets = hout->n_targets;
151                         if (hin->n_targets < min_n_targets) min_n_targets = hin->n_targets;
152
153                         for (j = 0; j < min_n_targets; ++j)
154                                 if (strcmp(hout->target_name[j], hin->target_name[j]) != 0) {
155                                         fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'\n",
156                                                         hout->target_name[j], hin->target_name[j], fn[i]);
157                                         return -1;
158                                 }
159
160                         // If this input file has additional target reference sequences,
161                         // add them to the headers to be output
162                         if (hin->n_targets > hout->n_targets) {
163                                 swap_header_targets(hout, hin);
164                                 // FIXME Possibly we should also create @SQ text headers
165                                 // for the newly added reference sequences
166                         }
167
168                         bam_header_destroy(hin);
169                 }
170         }
171
172         if (hheaders) {
173                 // If the text headers to be swapped in include any @SQ headers,
174                 // check that they are consistent with the existing binary list
175                 // of reference information.
176                 if (hheaders->n_targets > 0) {
177                         if (hout->n_targets != hheaders->n_targets) {
178                                 fprintf(stderr, "[bam_merge_core] number of @SQ headers in '%s' differs from number of target sequences\n", headers);
179                                 if (!reg) return -1;
180                         }
181                         for (j = 0; j < hout->n_targets; ++j)
182                                 if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0) {
183                                         fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence\n", hheaders->target_name[j], headers);
184                                         if (!reg) return -1;
185                                 }
186                 }
187
188                 swap_header_text(hout, hheaders);
189                 bam_header_destroy(hheaders);
190         }
191
192         if (reg) {
193                 int tid, beg, end;
194                 if (bam_parse_region(hout, reg, &tid, &beg, &end) < 0) {
195                         fprintf(stderr, "[%s] Malformated region string or undefined reference name\n", __func__);
196                         return -1;
197                 }
198                 for (i = 0; i < n; ++i) {
199                         bam_index_t *idx;
200                         idx = bam_index_load(fn[i]);
201                         iter[i] = bam_iter_query(idx, tid, beg, end);
202                         bam_index_destroy(idx);
203                 }
204         }
205
206         for (i = 0; i < n; ++i) {
207                 heap1_t *h = heap + i;
208                 h->i = i;
209                 h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
210                 if (bam_iter_read(fp[i], iter[i], h->b) >= 0) {
211                         h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)((int32_t)h->b->core.pos+1)<<1 | bam1_strand(h->b);
212                         h->idx = idx++;
213                 }
214                 else h->pos = HEAP_EMPTY;
215         }
216         if (flag & MERGE_UNCOMP) fpout = strcmp(out, "-")? bam_open(out, "wu") : bam_dopen(fileno(stdout), "wu");
217         else if (flag & MERGE_LEVEL1) fpout = strcmp(out, "-")? bam_open(out, "w1") : bam_dopen(fileno(stdout), "w1");
218         else fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w");
219         if (fpout == 0) {
220                 fprintf(stderr, "[%s] fail to create the output file.\n", __func__);
221                 return -1;
222         }
223         bam_header_write(fpout, hout);
224         bam_header_destroy(hout);
225
226         ks_heapmake(heap, n, heap);
227         while (heap->pos != HEAP_EMPTY) {
228                 bam1_t *b = heap->b;
229                 if (flag & MERGE_RG) {
230                         uint8_t *rg = bam_aux_get(b, "RG");
231                         if (rg) bam_aux_del(b, rg);
232                         bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]);
233                 }
234                 bam_write1_core(fpout, &b->core, b->data_len, b->data);
235                 if ((j = bam_iter_read(fp[heap->i], iter[heap->i], b)) >= 0) {
236                         heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)((int)b->core.pos+1)<<1 | bam1_strand(b);
237                         heap->idx = idx++;
238                 } else if (j == -1) {
239                         heap->pos = HEAP_EMPTY;
240                         free(heap->b->data); free(heap->b);
241                         heap->b = 0;
242                 } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
243                 ks_heapadjust(heap, 0, n, heap);
244         }
245
246         if (flag & MERGE_RG) {
247                 for (i = 0; i != n; ++i) free(RG[i]);
248                 free(RG); free(RG_len);
249         }
250         for (i = 0; i != n; ++i) {
251                 bam_iter_destroy(iter[i]);
252                 bam_close(fp[i]);
253         }
254         bam_close(fpout);
255         free(fp); free(heap); free(iter);
256         return 0;
257 }
258
259 int bam_merge(int argc, char *argv[])
260 {
261         int c, is_by_qname = 0, flag = 0, ret = 0;
262         char *fn_headers = NULL, *reg = 0;
263
264         while ((c = getopt(argc, argv, "h:nru1R:f")) >= 0) {
265                 switch (c) {
266                 case 'r': flag |= MERGE_RG; break;
267                 case 'f': flag |= MERGE_FORCE; break;
268                 case 'h': fn_headers = strdup(optarg); break;
269                 case 'n': is_by_qname = 1; break;
270                 case '1': flag |= MERGE_LEVEL1; break;
271                 case 'u': flag |= MERGE_UNCOMP; break;
272                 case 'R': reg = strdup(optarg); break;
273                 }
274         }
275         if (optind + 2 >= argc) {
276                 fprintf(stderr, "\n");
277                 fprintf(stderr, "Usage:   samtools merge [-nr] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n");
278                 fprintf(stderr, "Options: -n       sort by read names\n");
279                 fprintf(stderr, "         -r       attach RG tag (inferred from file names)\n");
280                 fprintf(stderr, "         -u       uncompressed BAM output\n");
281                 fprintf(stderr, "         -f       overwrite the output BAM if exist\n");
282                 fprintf(stderr, "         -1       compress level 1\n");
283                 fprintf(stderr, "         -R STR   merge file in the specified region STR [all]\n");
284                 fprintf(stderr, "         -h FILE  copy the header in FILE to <out.bam> [in1.bam]\n\n");
285                 fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n");
286                 fprintf(stderr, "      must provide the correct header with -h, or uses Picard which properly maintains\n");
287                 fprintf(stderr, "      the header dictionary in merging.\n\n");
288                 return 1;
289         }
290         if (!(flag & MERGE_FORCE) && strcmp(argv[optind], "-")) {
291                 FILE *fp = fopen(argv[optind], "rb");
292                 if (fp != NULL) {
293                         fclose(fp);
294                         fprintf(stderr, "[%s] File '%s' exists. Please apply '-f' to overwrite. Abort.\n", __func__, argv[optind]);
295                         return 1;
296                 }
297         }
298         if (bam_merge_core(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1, flag, reg) < 0) ret = 1;
299         free(reg);
300         free(fn_headers);
301         return ret;
302 }
303
304 typedef bam1_t *bam1_p;
305
306 static inline int bam1_lt(const bam1_p a, const bam1_p b)
307 {
308         if (g_is_by_qname) {
309                 int t = strnum_cmp(bam1_qname(a), bam1_qname(b));
310                 return (t < 0 || (t == 0 && (((uint64_t)a->core.tid<<32|(a->core.pos+1)) < ((uint64_t)b->core.tid<<32|(b->core.pos+1)))));
311         } else return (((uint64_t)a->core.tid<<32|(a->core.pos+1)) < ((uint64_t)b->core.tid<<32|(b->core.pos+1)));
312 }
313 KSORT_INIT(sort, bam1_p, bam1_lt)
314
315 static void sort_blocks(int n, int k, bam1_p *buf, const char *prefix, const bam_header_t *h, int is_stdout)
316 {
317         char *name, mode[3];
318         int i;
319         bamFile fp;
320         ks_mergesort(sort, k, buf, 0);
321         name = (char*)calloc(strlen(prefix) + 20, 1);
322         if (n >= 0) {
323                 sprintf(name, "%s.%.4d.bam", prefix, n);
324                 strcpy(mode, "w1");
325         } else {
326                 sprintf(name, "%s.bam", prefix);
327                 strcpy(mode, "w");
328         }
329         fp = is_stdout? bam_dopen(fileno(stdout), mode) : bam_open(name, mode);
330         if (fp == 0) {
331                 fprintf(stderr, "[sort_blocks] fail to create file %s.\n", name);
332                 free(name);
333                 // FIXME: possible memory leak
334                 return;
335         }
336         free(name);
337         bam_header_write(fp, h);
338         for (i = 0; i < k; ++i)
339                 bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data);
340         bam_close(fp);
341 }
342
343 /*!
344   @abstract Sort an unsorted BAM file based on the chromosome order
345   and the leftmost position of an alignment
346
347   @param  is_by_qname whether to sort by query name
348   @param  fn       name of the file to be sorted
349   @param  prefix   prefix of the output and the temporary files; upon
350                            sucessess, prefix.bam will be written.
351   @param  max_mem  approxiate maximum memory (very inaccurate)
352
353   @discussion It may create multiple temporary subalignment files
354   and then merge them by calling bam_merge_core(). This function is
355   NOT thread safe.
356  */
357 void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t max_mem, int is_stdout)
358 {
359         int n, ret, k, i;
360         size_t mem;
361         bam_header_t *header;
362         bamFile fp;
363         bam1_t *b, **buf;
364
365         g_is_by_qname = is_by_qname;
366         n = k = 0; mem = 0;
367         fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
368         if (fp == 0) {
369                 fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
370                 return;
371         }
372         header = bam_header_read(fp);
373         buf = (bam1_t**)calloc(max_mem / BAM_CORE_SIZE, sizeof(bam1_t*));
374         // write sub files
375         for (;;) {
376                 if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
377                 b = buf[k];
378                 if ((ret = bam_read1(fp, b)) < 0) break;
379                 mem += ret;
380                 ++k;
381                 if (mem >= max_mem) {
382                         sort_blocks(n++, k, buf, prefix, header, 0);
383                         mem = 0; k = 0;
384                 }
385         }
386         if (ret != -1)
387                 fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
388         if (n == 0) sort_blocks(-1, k, buf, prefix, header, is_stdout);
389         else { // then merge
390                 char **fns, *fnout;
391                 fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n+1);
392                 sort_blocks(n++, k, buf, prefix, header, 0);
393                 fnout = (char*)calloc(strlen(prefix) + 20, 1);
394                 if (is_stdout) sprintf(fnout, "-");
395                 else sprintf(fnout, "%s.bam", prefix);
396                 fns = (char**)calloc(n, sizeof(char*));
397                 for (i = 0; i < n; ++i) {
398                         fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
399                         sprintf(fns[i], "%s.%.4d.bam", prefix, i);
400                 }
401                 bam_merge_core(is_by_qname, fnout, 0, n, fns, 0, 0);
402                 free(fnout);
403                 for (i = 0; i < n; ++i) {
404                         unlink(fns[i]);
405                         free(fns[i]);
406                 }
407                 free(fns);
408         }
409         for (k = 0; k < max_mem / BAM_CORE_SIZE; ++k) {
410                 if (buf[k]) {
411                         free(buf[k]->data);
412                         free(buf[k]);
413                 }
414         }
415         free(buf);
416         bam_header_destroy(header);
417         bam_close(fp);
418 }
419
420 void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem)
421 {
422         bam_sort_core_ext(is_by_qname, fn, prefix, max_mem, 0);
423 }
424
425
426 size_t bam_sort_get_max_mem(char *max_mem_string)
427 {
428         char c;
429         size_t max_mem;
430         size_t multiplier=1;
431         c=max_mem_string[strlen(max_mem_string)-1];
432         switch(c) {
433         case 'G':
434                 multiplier*=1024;
435         case 'M':
436                 multiplier*=1024;
437         case 'K':
438                 multiplier*=1024;
439         case 'B':
440                 max_mem_string[strlen(max_mem_string)-1]='\0';
441                 break;
442         default:
443                 break;
444         }
445         max_mem = multiplier * atol(max_mem_string);
446         // max_mem should be checked that it was not zero after atol!
447         return max_mem;
448 }
449
450 int bam_sort(int argc, char *argv[])
451 {
452         size_t max_mem = 500000000;
453         int c, is_by_qname = 0, is_stdout = 0;
454         while ((c = getopt(argc, argv, "nom:")) >= 0) {
455                 switch (c) {
456                 case 'o': is_stdout = 1; break;
457                 case 'n': is_by_qname = 1; break;
458                 case 'm': max_mem = bam_sort_get_max_mem(optarg); break;
459                 }
460         }
461         if (optind + 2 > argc) {
462                 fprintf(stderr, "Usage: samtools sort [-on] [-m <maxMem>] <in.bam> <out.prefix>\n");
463                 return 1;
464         }
465         bam_sort_core_ext(is_by_qname, argv[optind], argv[optind+1], max_mem, is_stdout);
466         return 0;
467 }