# Uploaded samtools version 0.1.14-1.
[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, compress_level = -1, 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:h1Ho: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': compress_level = 0; break;
107                 case '1': compress_level = 1; break;
108                 case 'l': g_library = strdup(optarg); break;
109                 case 'r': g_rg = strdup(optarg); break;
110                 case 'R': fn_rg = strdup(optarg); break;
111                 case 'x': of_type = BAM_OFHEX; break;
112                 case 'X': of_type = BAM_OFSTR; break;
113                 case '?': is_long_help = 1; break;
114                 case 'T': fn_ref = strdup(optarg); is_bamin = 0; break;
115                 default: return usage(is_long_help);
116                 }
117         }
118         if (compress_level >= 0) is_bamout = 1;
119         if (is_header_only) is_header = 1;
120         if (is_bamout) strcat(out_mode, "b");
121         else {
122                 if (of_type == BAM_OFHEX) strcat(out_mode, "x");
123                 else if (of_type == BAM_OFSTR) strcat(out_mode, "X");
124         }
125         if (is_bamin) strcat(in_mode, "b");
126         if (is_header) strcat(out_mode, "h");
127         if (compress_level >= 0) {
128                 char tmp[2];
129                 tmp[0] = compress_level + '0'; tmp[1] = '\0';
130                 strcat(out_mode, tmp);
131         }
132         if (argc == optind) return usage(is_long_help); // potential memory leak...
133
134         // read the list of read groups
135         if (fn_rg) {
136                 FILE *fp_rg;
137                 char buf[1024];
138                 int ret;
139                 g_rghash = kh_init(rg);
140                 fp_rg = fopen(fn_rg, "r");
141                 while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but bear me...
142                         kh_put(rg, g_rghash, strdup(buf), &ret); // we'd better check duplicates...
143                 fclose(fp_rg);
144         }
145
146         // generate the fn_list if necessary
147         if (fn_list == 0 && fn_ref) fn_list = samfaipath(fn_ref);
148         // open file handlers
149         if ((in = samopen(argv[optind], in_mode, fn_list)) == 0) {
150                 fprintf(stderr, "[main_samview] fail to open \"%s\" for reading.\n", argv[optind]);
151                 ret = 1;
152                 goto view_end;
153         }
154         if (in->header == 0) {
155                 fprintf(stderr, "[main_samview] fail to read the header from \"%s\".\n", argv[optind]);
156                 ret = 1;
157                 goto view_end;
158         }
159         if (!is_count && (out = samopen(fn_out? fn_out : "-", out_mode, in->header)) == 0) {
160                 fprintf(stderr, "[main_samview] fail to open \"%s\" for writing.\n", fn_out? fn_out : "standard output");
161                 ret = 1;
162                 goto view_end;
163         }
164         if (is_header_only) goto view_end; // no need to print alignments
165
166         if (argc == optind + 1) { // convert/print the entire file
167                 bam1_t *b = bam_init1();
168                 int r;
169                 while ((r = samread(in, b)) >= 0) { // read one alignment from `in'
170                         if (!__g_skip_aln(in->header, b)) {
171                                 if (slx2sngr) sol2sanger(b);
172                                 if (!is_count) samwrite(out, b); // write the alignment to `out'
173                                 count++;
174                         }
175                 }
176                 if (r < -1) {
177                         fprintf(stderr, "[main_samview] truncated file.\n");
178                         ret = 1;
179                 }
180                 bam_destroy1(b);
181         } else { // retrieve alignments in specified regions
182                 int i;
183                 bam_index_t *idx = 0;
184                 if (is_bamin) idx = bam_index_load(argv[optind]); // load BAM index
185                 if (idx == 0) { // index is unavailable
186                         fprintf(stderr, "[main_samview] random alignment retrieval only works for indexed BAM files.\n");
187                         ret = 1;
188                         goto view_end;
189                 }
190                 for (i = optind + 1; i < argc; ++i) {
191                         int tid, beg, end, result;
192                         bam_parse_region(in->header, argv[i], &tid, &beg, &end); // parse a region in the format like `chr2:100-200'
193                         if (tid < 0) { // reference name is not found
194                                 fprintf(stderr, "[main_samview] region \"%s\" specifies an unknown reference name. Continue anyway.\n", argv[i]);
195                                 continue;
196                         }
197                         // fetch alignments
198                         if (is_count) {
199                                 count_func_data_t count_data = { in->header, &count };
200                                 result = bam_fetch(in->x.bam, idx, tid, beg, end, &count_data, count_func);
201                         } else
202                                 result = bam_fetch(in->x.bam, idx, tid, beg, end, out, view_func);
203                         if (result < 0) {
204                                 fprintf(stderr, "[main_samview] retrieval of region \"%s\" failed due to truncated file or corrupt BAM index file\n", argv[i]);
205                                 ret = 1;
206                                 break;
207                         }
208                 }
209                 bam_index_destroy(idx); // destroy the BAM index
210         }
211
212 view_end:
213         if (is_count && ret == 0) {
214                 printf("%d\n", count);
215         }
216         // close files, free and return
217         free(fn_list); free(fn_ref); free(fn_out); free(g_library); free(g_rg); free(fn_rg);
218         if (g_rghash) {
219                 khint_t k;
220                 for (k = 0; k < kh_end(g_rghash); ++k)
221                         if (kh_exist(g_rghash, k)) free((char*)kh_key(g_rghash, k));
222                 kh_destroy(rg, g_rghash);
223         }
224         samclose(in);
225         if (!is_count)
226                 samclose(out);
227         return ret;
228 }
229
230 static int usage(int is_long_help)
231 {
232         fprintf(stderr, "\n");
233         fprintf(stderr, "Usage:   samtools view [options] <in.bam>|<in.sam> [region1 [...]]\n\n");
234         fprintf(stderr, "Options: -b       output BAM\n");
235         fprintf(stderr, "         -h       print header for the SAM output\n");
236         fprintf(stderr, "         -H       print header only (no alignments)\n");
237         fprintf(stderr, "         -S       input is SAM\n");
238         fprintf(stderr, "         -u       uncompressed BAM output (force -b)\n");
239         fprintf(stderr, "         -1       fast compression (force -b)\n");
240         fprintf(stderr, "         -x       output FLAG in HEX (samtools-C specific)\n");
241         fprintf(stderr, "         -X       output FLAG in string (samtools-C specific)\n");
242         fprintf(stderr, "         -c       print only the count of matching records\n");
243         fprintf(stderr, "         -t FILE  list of reference names and lengths (force -S) [null]\n");
244         fprintf(stderr, "         -T FILE  reference sequence file (force -S) [null]\n");
245         fprintf(stderr, "         -o FILE  output file name [stdout]\n");
246         fprintf(stderr, "         -R FILE  list of read groups to be outputted [null]\n");
247         fprintf(stderr, "         -f INT   required flag, 0 for unset [0]\n");
248         fprintf(stderr, "         -F INT   filtering flag, 0 for unset [0]\n");
249         fprintf(stderr, "         -q INT   minimum mapping quality [0]\n");
250         fprintf(stderr, "         -l STR   only output reads in library STR [null]\n");
251         fprintf(stderr, "         -r STR   only output reads in read group STR [null]\n");
252         fprintf(stderr, "         -?       longer help\n");
253         fprintf(stderr, "\n");
254         if (is_long_help)
255                 fprintf(stderr, "Notes:\n\
256 \n\
257   1. By default, this command assumes the file on the command line is in\n\
258      the BAM format and it prints the alignments in SAM. If `-t' is\n\
259      applied, the input file is assumed to be in the SAM format. The\n\
260      file supplied with `-t' is SPACE/TAB delimited with the first two\n\
261      fields of each line consisting of the reference name and the\n\
262      corresponding sequence length. The `.fai' file generated by `faidx'\n\
263      can be used here. This file may be empty if reads are unaligned.\n\
264 \n\
265   2. SAM->BAM conversion: `samtools view -bT ref.fa in.sam.gz'.\n\
266 \n\
267   3. BAM->SAM conversion: `samtools view in.bam'.\n\
268 \n\
269   4. A region should be presented in one of the following formats:\n\
270      `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n\
271      specified, the input alignment file must be an indexed BAM file.\n\
272 \n\
273   5. Option `-u' is preferred over `-b' when the output is piped to\n\
274      another samtools command.\n\
275 \n\
276   6. In a string FLAG, each character represents one bit with\n\
277      p=0x1 (paired), P=0x2 (properly paired), u=0x4 (unmapped),\n\
278      U=0x8 (mate unmapped), r=0x10 (reverse), R=0x20 (mate reverse)\n\
279      1=0x40 (first), 2=0x80 (second), s=0x100 (not primary), \n\
280      f=0x200 (failure) and d=0x400 (duplicate). Note that `-x' and\n\
281      `-X' are samtools-C specific. Picard and older samtools do not\n\
282      support HEX or string flags.\n\
283 \n");
284         return 1;
285 }
286
287 int main_import(int argc, char *argv[])
288 {
289         int argc2, ret;
290         char **argv2;
291         if (argc != 4) {
292                 fprintf(stderr, "Usage: bamtk import <in.ref_list> <in.sam> <out.bam>\n");
293                 return 1;
294         }
295         argc2 = 6;
296         argv2 = calloc(6, sizeof(char*));
297         argv2[0] = "import", argv2[1] = "-o", argv2[2] = argv[3], argv2[3] = "-bt", argv2[4] = argv[1], argv2[5] = argv[2];
298         ret = main_samview(argc2, argv2);
299         free(argv2);
300         return ret;
301 }