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