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