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