# Use bzip2 compression for the binary packages and raised DH compat level.
[samtools.git] / sam_view.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <unistd.h>
5 #include <math.h>
6 #include "sam_header.h"
7 #include "sam.h"
8 #include "faidx.h"
9 #include "khash.h"
10 KHASH_SET_INIT_STR(rg)
11
12 // When counting records instead of printing them,
13 // data passed to the bam_fetch callback is encapsulated in this struct.
14 typedef struct {
15         bam_header_t *header;
16         int *count;
17 } count_func_data_t;
18
19 typedef khash_t(rg) *rghash_t;
20
21 rghash_t g_rghash = 0;
22 static int g_min_mapQ = 0, g_flag_on = 0, g_flag_off = 0;
23 static char *g_library, *g_rg;
24 static int g_sol2sanger_tbl[128];
25
26 static void sol2sanger(bam1_t *b)
27 {
28         int l;
29         uint8_t *qual = bam1_qual(b);
30         if (g_sol2sanger_tbl[30] == 0) {
31                 for (l = 0; l != 128; ++l) {
32                         g_sol2sanger_tbl[l] = (int)(10.0 * log(1.0 + pow(10.0, (l - 64 + 33) / 10.0)) / log(10.0) + .499);
33                         if (g_sol2sanger_tbl[l] >= 93) g_sol2sanger_tbl[l] = 93;
34                 }
35         }
36         for (l = 0; l < b->core.l_qseq; ++l) {
37                 int q = qual[l];
38                 if (q > 127) q = 127;
39                 qual[l] = g_sol2sanger_tbl[q];
40         }
41 }
42
43 static inline int __g_skip_aln(const bam_header_t *h, const bam1_t *b)
44 {
45         if (b->core.qual < g_min_mapQ || ((b->core.flag & g_flag_on) != g_flag_on) || (b->core.flag & g_flag_off))
46                 return 1;
47         if (g_rg || g_rghash) {
48                 uint8_t *s = bam_aux_get(b, "RG");
49                 if (s) {
50                         if (g_rg) return (strcmp(g_rg, (char*)(s + 1)) == 0)? 0 : 1;
51                         if (g_rghash) {
52                                 khint_t k = kh_get(rg, g_rghash, (char*)(s + 1));
53                                 return (k != kh_end(g_rghash))? 0 : 1;
54                         }
55                 }
56         }
57         if (g_library) {
58                 const char *p = bam_get_library((bam_header_t*)h, b);
59                 return (p && strcmp(p, g_library) == 0)? 0 : 1;
60         }
61         return 0;
62 }
63
64 // callback function for bam_fetch() that prints nonskipped records
65 static int view_func(const bam1_t *b, void *data)
66 {
67         if (!__g_skip_aln(((samfile_t*)data)->header, b))
68                 samwrite((samfile_t*)data, b);
69         return 0;
70 }
71
72 // callback function for bam_fetch() that counts nonskipped records
73 static int count_func(const bam1_t *b, void *data)
74 {
75         if (!__g_skip_aln(((count_func_data_t*)data)->header, b)) {
76                 (*((count_func_data_t*)data)->count)++;
77         }
78         return 0;
79 }
80
81 static int usage(int is_long_help);
82
83 int main_samview(int argc, char *argv[])
84 {
85         int c, is_header = 0, is_header_only = 0, is_bamin = 1, ret = 0, is_uncompressed = 0, is_bamout = 0, slx2sngr = 0, is_count = 0;
86         int of_type = BAM_OFDEC, is_long_help = 0;
87         int count = 0;
88         samfile_t *in = 0, *out = 0;
89         char in_mode[5], out_mode[5], *fn_out = 0, *fn_list = 0, *fn_ref = 0, *fn_rg = 0;
90
91         /* parse command-line options */
92         strcpy(in_mode, "r"); strcpy(out_mode, "w");
93         while ((c = getopt(argc, argv, "Sbct:hHo:q:f:F:ul:r:xX?T:CR:")) >= 0) {
94                 switch (c) {
95                 case 'c': is_count = 1; break;
96                 case 'C': slx2sngr = 1; break;
97                 case 'S': is_bamin = 0; break;
98                 case 'b': is_bamout = 1; break;
99                 case 't': fn_list = strdup(optarg); is_bamin = 0; break;
100                 case 'h': is_header = 1; break;
101                 case 'H': is_header_only = 1; break;
102                 case 'o': fn_out = strdup(optarg); break;
103                 case 'f': g_flag_on = strtol(optarg, 0, 0); break;
104                 case 'F': g_flag_off = strtol(optarg, 0, 0); break;
105                 case 'q': g_min_mapQ = atoi(optarg); break;
106                 case 'u': is_uncompressed = 1; break;
107                 case 'l': g_library = strdup(optarg); break;
108                 case 'r': g_rg = strdup(optarg); break;
109                 case 'R': fn_rg = strdup(optarg); break;
110                 case 'x': of_type = BAM_OFHEX; break;
111                 case 'X': of_type = BAM_OFSTR; break;
112                 case '?': is_long_help = 1; break;
113                 case 'T': fn_ref = strdup(optarg); is_bamin = 0; break;
114                 default: return usage(is_long_help);
115                 }
116         }
117         if (is_uncompressed) is_bamout = 1;
118         if (is_header_only) is_header = 1;
119         if (is_bamout) strcat(out_mode, "b");
120         else {
121                 if (of_type == BAM_OFHEX) strcat(out_mode, "x");
122                 else if (of_type == BAM_OFSTR) strcat(out_mode, "X");
123         }
124         if (is_bamin) strcat(in_mode, "b");
125         if (is_header) strcat(out_mode, "h");
126         if (is_uncompressed) strcat(out_mode, "u");
127         if (argc == optind) return usage(is_long_help); // potential memory leak...
128
129         // read the list of read groups
130         if (fn_rg) {
131                 FILE *fp_rg;
132                 char buf[1024];
133                 int ret;
134                 g_rghash = kh_init(rg);
135                 fp_rg = fopen(fn_rg, "r");
136                 while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but bear me...
137                         kh_put(rg, g_rghash, strdup(buf), &ret); // we'd better check duplicates...
138                 fclose(fp_rg);
139         }
140
141         // generate the fn_list if necessary
142         if (fn_list == 0 && fn_ref) fn_list = samfaipath(fn_ref);
143         // open file handlers
144         if ((in = samopen(argv[optind], in_mode, fn_list)) == 0) {
145                 fprintf(stderr, "[main_samview] fail to open \"%s\" for reading.\n", argv[optind]);
146                 ret = 1;
147                 goto view_end;
148         }
149         if (in->header == 0) {
150                 fprintf(stderr, "[main_samview] fail to read the header from \"%s\".\n", argv[optind]);
151                 ret = 1;
152                 goto view_end;
153         }
154         if (!is_count && (out = samopen(fn_out? fn_out : "-", out_mode, in->header)) == 0) {
155                 fprintf(stderr, "[main_samview] fail to open \"%s\" for writing.\n", fn_out? fn_out : "standard output");
156                 ret = 1;
157                 goto view_end;
158         }
159         if (is_header_only) goto view_end; // no need to print alignments
160
161         if (argc == optind + 1) { // convert/print the entire file
162                 bam1_t *b = bam_init1();
163                 int r;
164                 while ((r = samread(in, b)) >= 0) { // read one alignment from `in'
165                         if (!__g_skip_aln(in->header, b)) {
166                                 if (slx2sngr) sol2sanger(b);
167                                 if (!is_count) samwrite(out, b); // write the alignment to `out'
168                                 count++;
169                         }
170                 }
171                 if (r < -1) {
172                         fprintf(stderr, "[main_samview] truncated file.\n");
173                         ret = 1;
174                 }
175                 bam_destroy1(b);
176         } else { // retrieve alignments in specified regions
177                 int i;
178                 bam_index_t *idx = 0;
179                 if (is_bamin) idx = bam_index_load(argv[optind]); // load BAM index
180                 if (idx == 0) { // index is unavailable
181                         fprintf(stderr, "[main_samview] random alignment retrieval only works for indexed BAM files.\n");
182                         ret = 1;
183                         goto view_end;
184                 }
185                 for (i = optind + 1; i < argc; ++i) {
186                         int tid, beg, end, result;
187                         bam_parse_region(in->header, argv[i], &tid, &beg, &end); // parse a region in the format like `chr2:100-200'
188                         if (tid < 0) { // reference name is not found
189                                 fprintf(stderr, "[main_samview] region \"%s\" specifies an unknown reference name. Continue anyway.\n", argv[i]);
190                                 continue;
191                         }
192                         // fetch alignments
193                         if (is_count) {
194                                 count_func_data_t count_data = { in->header, &count };
195                                 result = bam_fetch(in->x.bam, idx, tid, beg, end, &count_data, count_func);
196                         } else
197                                 result = bam_fetch(in->x.bam, idx, tid, beg, end, out, view_func);
198                         if (result < 0) {
199                                 fprintf(stderr, "[main_samview] retrieval of region \"%s\" failed due to truncated file or corrupt BAM index file\n", argv[i]);
200                                 ret = 1;
201                                 break;
202                         }
203                 }
204                 bam_index_destroy(idx); // destroy the BAM index
205         }
206
207 view_end:
208         if (is_count && ret == 0) {
209                 printf("%d\n", count);
210         }
211         // close files, free and return
212         free(fn_list); free(fn_ref); free(fn_out); free(g_library); free(g_rg); free(fn_rg);
213         if (g_rghash) {
214                 khint_t k;
215                 for (k = 0; k < kh_end(g_rghash); ++k)
216                         if (kh_exist(g_rghash, k)) free((char*)kh_key(g_rghash, k));
217                 kh_destroy(rg, g_rghash);
218         }
219         samclose(in);
220         if (!is_count)
221                 samclose(out);
222         return ret;
223 }
224
225 static int usage(int is_long_help)
226 {
227         fprintf(stderr, "\n");
228         fprintf(stderr, "Usage:   samtools view [options] <in.bam>|<in.sam> [region1 [...]]\n\n");
229         fprintf(stderr, "Options: -b       output BAM\n");
230         fprintf(stderr, "         -h       print header for the SAM output\n");
231         fprintf(stderr, "         -H       print header only (no alignments)\n");
232         fprintf(stderr, "         -S       input is SAM\n");
233         fprintf(stderr, "         -u       uncompressed BAM output (force -b)\n");
234         fprintf(stderr, "         -x       output FLAG in HEX (samtools-C specific)\n");
235         fprintf(stderr, "         -X       output FLAG in string (samtools-C specific)\n");
236         fprintf(stderr, "         -c       print only the count of matching records\n");
237         fprintf(stderr, "         -t FILE  list of reference names and lengths (force -S) [null]\n");
238         fprintf(stderr, "         -T FILE  reference sequence file (force -S) [null]\n");
239         fprintf(stderr, "         -o FILE  output file name [stdout]\n");
240         fprintf(stderr, "         -R FILE  list of read groups to be outputted [null]\n");
241         fprintf(stderr, "         -f INT   required flag, 0 for unset [0]\n");
242         fprintf(stderr, "         -F INT   filtering flag, 0 for unset [0]\n");
243         fprintf(stderr, "         -q INT   minimum mapping quality [0]\n");
244         fprintf(stderr, "         -l STR   only output reads in library STR [null]\n");
245         fprintf(stderr, "         -r STR   only output reads in read group STR [null]\n");
246         fprintf(stderr, "         -?       longer help\n");
247         fprintf(stderr, "\n");
248         if (is_long_help)
249                 fprintf(stderr, "Notes:\n\
250 \n\
251   1. By default, this command assumes the file on the command line is in\n\
252      the BAM format and it prints the alignments in SAM. If `-t' is\n\
253      applied, the input file is assumed to be in the SAM format. The\n\
254      file supplied with `-t' is SPACE/TAB delimited with the first two\n\
255      fields of each line consisting of the reference name and the\n\
256      corresponding sequence length. The `.fai' file generated by `faidx'\n\
257      can be used here. This file may be empty if reads are unaligned.\n\
258 \n\
259   2. SAM->BAM conversion: `samtools view -bT ref.fa in.sam.gz'.\n\
260 \n\
261   3. BAM->SAM conversion: `samtools view in.bam'.\n\
262 \n\
263   4. A region should be presented in one of the following formats:\n\
264      `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n\
265      specified, the input alignment file must be an indexed BAM file.\n\
266 \n\
267   5. Option `-u' is preferred over `-b' when the output is piped to\n\
268      another samtools command.\n\
269 \n\
270   6. In a string FLAG, each character represents one bit with\n\
271      p=0x1 (paired), P=0x2 (properly paired), u=0x4 (unmapped),\n\
272      U=0x8 (mate unmapped), r=0x10 (reverse), R=0x20 (mate reverse)\n\
273      1=0x40 (first), 2=0x80 (second), s=0x100 (not primary), \n\
274      f=0x200 (failure) and d=0x400 (duplicate). Note that `-x' and\n\
275      `-X' are samtools-C specific. Picard and older samtools do not\n\
276      support HEX or string flags.\n\
277 \n");
278         return 1;
279 }
280
281 int main_import(int argc, char *argv[])
282 {
283         int argc2, ret;
284         char **argv2;
285         if (argc != 4) {
286                 fprintf(stderr, "Usage: bamtk import <in.ref_list> <in.sam> <out.bam>\n");
287                 return 1;
288         }
289         argc2 = 6;
290         argv2 = calloc(6, sizeof(char*));
291         argv2[0] = "import", argv2[1] = "-o", argv2[2] = argv[3], argv2[3] = "-bt", argv2[4] = argv[1], argv2[5] = argv[2];
292         ret = main_samview(argc2, argv2);
293         free(argv2);
294         return ret;
295 }