Debian Codegraph @

bcftools/vcfindex.c

raw symbols SCIP
1 /* vcfindex.c -- Index bgzip compressed VCF/BCF files for random access.
2
3 Copyright (C) 2014-2024 Genome Research Ltd.
4
5 Author: Shane McCarthy <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 DEALINGS IN THE SOFTWARE. */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <strings.h>
28 #include <unistd.h>
29 #include <getopt.h>
30 #include <htslib/vcf.h>
31 #include <htslib/tbx.h>
32 #include <sys/stat.h>
33 #define __STDC_FORMAT_MACROS
34 #include <inttypes.h>
35 #include <htslib/kstring.h>
36 #include <htslib/bgzf.h>
37 #include "bcftools.h"
38
39 #define BCF_LIDX_SHIFT 14
40
41 enum {
42 per_contig = 1,
43 all_contigs = 2,
44 total = 4
45 };
46
47 static void usage(void)
48 {
49 fprintf(stderr, "\n");
50 fprintf(stderr, "About: Index bgzip compressed VCF/BCF files for random access.\n");
51 fprintf(stderr, "Usage: bcftools index [options] <in.bcf>|<in.vcf.gz>\n");
52 fprintf(stderr, "\n");
53 fprintf(stderr, "Indexing options:\n");
54 fprintf(stderr, " -c, --csi generate CSI-format index for VCF/BCF files [default]\n");
55 fprintf(stderr, " -f, --force overwrite index if it already exists\n");
56 fprintf(stderr, " -m, --min-shift INT set minimal interval size for CSI indices to 2^INT [14]\n");
57 fprintf(stderr, " -o, --output FILE optional output index file name\n");
58 fprintf(stderr, " -t, --tbi generate TBI-format index for VCF files\n");
59 fprintf(stderr, " --threads INT use multithreading with INT worker threads [0]\n");
60 fprintf(stderr, "\n");
61 fprintf(stderr, "Stats options:\n");
62 fprintf(stderr, " -a, --all with --stats, print stats for all contigs even when zero\n");
63 fprintf(stderr, " -n, --nrecords print number of records based on existing index file\n");
64 fprintf(stderr, " -s, --stats print per contig stats based on existing index file\n");
65 fprintf(stderr, "\n");
66 exit(1);
67 }
68
69 int vcf_index_stats(char *fname, int stats)
70 {
71 const char **seq = NULL;
72 int tid, nseq = 0, ret = 0;
73 tbx_t *tbx = NULL;
74 bcf_hdr_t *hdr = NULL;
75 hts_idx_t *idx = NULL;
76 htsFile *fp = NULL;
77 uint64_t sum = 0;
78 char *fntemp = NULL, *fnidx = NULL;
79
80 /*
81 * First, has the user provided an index file? If per contig stats
82 * are requested, open the variant file (together with the index file,
83 * if provided), since the contig names can only be retrieved from its
84 * header. Otherwise, use just the corresponding index file to count
85 * the total number of records.
86 */
87 int len = strlen(fname);
88 int idx_only = 0;
89 if ( (fnidx = strstr(fname, HTS_IDX_DELIM)) != NULL ) {
90 fntemp = strdup(fname);
91 if ( !fntemp ) return 1;
92 fntemp[fnidx-fname] = 0;
93 fname = fntemp;
94 fnidx += strlen(HTS_IDX_DELIM);
95 }
96 else if ( len>4 && (!strcasecmp(".csi",fname+len-4) || !strcasecmp(".tbi",fname+len-4)) )
97 {
98 fnidx = fname;
99 fntemp = strdup(fname);
100 fname = fntemp;
101 fname[len-4] = 0;
102 idx_only = 1;
103 }
104
105 if ( stats&per_contig )
106 {
107 if ( idx_only )
108 {
109 struct stat buf;
110 if ( stat(fname, &buf)==0 ) idx_only = 0;
111 }
112
113 enum htsExactFormat fmt;
114 if ( !idx_only )
115 {
116 fp = hts_open(fname,"r");
117 if ( !fp ) {
118 fprintf(stderr,"Could not read %s\n", fname);
119 ret = 1; goto cleanup;
120 }
121 hdr = bcf_hdr_read(fp);
122 if ( !hdr ) {
123 fprintf(stderr,"Could not read the header: %s\n", fname);
124 ret = 1; goto cleanup;
125 }
126 fmt = hts_get_format(fp)->format;
127 }
128 else
129 {
130 int len = strlen(fnidx);
131 if ( !strcasecmp(".tbi",fnidx+len-4) ) fmt = vcf;
132 else fmt = bcf;
133 }
134
135 if ( fmt==vcf )
136 {
137 tbx = tbx_index_load2(fname, fnidx);
138 if ( !tbx ) { fprintf(stderr,"Could not load index for VCF: %s\n", fname); return 1; }
139 }
140 else if ( fmt==bcf )
141 {
142 idx = bcf_index_load2(fname, fnidx);
143 if ( !idx ) { fprintf(stderr,"Could not load index for BCF file: %s\n", fname); return 1; }
144 }
145 else
146 {
147 fprintf(stderr,"Could not detect the file type as VCF or BCF: %s\n", fname);
148 return 1;
149 }
150 }
151 else if ( fnidx )
152 {
153 char *ext = strrchr(fnidx, '.');
154 if ( ext && strcmp(ext, ".tbi") == 0 ) {
155 tbx = tbx_index_load2(fname, fnidx);
156 } else if ( ext && strcmp(ext, ".csi") == 0 ) {
157 idx = bcf_index_load2(fname, fnidx);
158 }
159 if ( !tbx && !idx ) {
160 fprintf(stderr,"Could not load index file '%s'\n", fnidx);
161 ret = 1; goto cleanup;
162 }
163 } else {
164 char *ext = strrchr(fname, '.');
165 if ( ext && strcmp(ext, ".bcf") == 0 ) {
166 idx = bcf_index_load(fname);
167 } else if ( ext && (ext-fname) > 4 && strcmp(ext-4, ".vcf.gz") == 0 ) {
168 tbx = tbx_index_load(fname);
169 }
170 }
171
172 if ( !tbx && !idx ) {
173 fprintf(stderr,"No index file could be found for '%s'. Use 'bcftools index' to create one\n", fname);
174 ret = 1; goto cleanup;
175 }
176
177 if ( tbx ) {
178 seq = tbx_seqnames(tbx, &nseq);
179 } else {
180 nseq = hts_idx_nseq(idx);
181 }
182 if ( !tbx && !hdr ) fprintf(stderr,"Warning: cannot determine contig names given the .csi index alone\n");
183 for (tid=0; tid<nseq; tid++)
184 {
185 uint64_t records, v;
186 int ret = hts_idx_get_stat(tbx ? tbx->idx : idx, tid, &records, &v);
187 sum += records;
188 if ( (stats&total) || (records == 0 && !(stats&all_contigs)) ) continue;
189 const char *ctg_name = tbx ? seq[tid] : hdr ? bcf_hdr_id2name(hdr, tid) : "n/a";
190 bcf_hrec_t *hrec = hdr ? bcf_hdr_get_hrec(hdr, BCF_HL_CTG, "ID", ctg_name, NULL) : NULL;
191 int hkey = hrec ? bcf_hrec_find_key(hrec, "length") : -1;
192 printf("%s\t%s\t", ctg_name, hkey<0?".":hrec->vals[hkey]);
193 if (ret >= 0) printf("%" PRIu64 "\n", records);
194 else printf(".\n");
195 }
196 if ( !sum )
197 {
198 // No counts found.
199 // Is this because index version has no stored count data, or no records?
200 bcf1_t *rec = bcf_init1();
201 if (fp && hdr && rec && bcf_read1(fp, hdr, rec) >= 0) {
202 fprintf(stderr,"index of %s does not contain any count metadata. Please re-index with a newer version of bcftools or tabix.\n", fname);
203 ret = 1;
204 }
205 bcf_destroy1(rec);
206 }
207 if ( (stats&total) && !ret ) {
208 printf("%" PRIu64 "\n", sum);
209 }
210
211 cleanup:
212 free(seq);
213 free(fntemp);
214 if ( fp && hts_close(fp)!=0 ) error("[%s] Error: close failed\n", __func__);
215 bcf_hdr_destroy(hdr);
216 if (tbx)
217 tbx_destroy(tbx);
218 if (idx)
219 hts_idx_destroy(idx);
220 return ret;
221 }
222
223 int main_vcfindex(int argc, char *argv[])
224 {
225 int c, force = 0, tbi = 0, stats = 0, n_threads = 0;
226 int min_shift = BCF_LIDX_SHIFT;
227 char *outfn = NULL;
228
229 static struct option loptions[] =
230 {
231 {"all",no_argument,NULL,'a'},
232 {"csi",no_argument,NULL,'c'},
233 {"tbi",no_argument,NULL,'t'},
234 {"force",no_argument,NULL,'f'},
235 {"min-shift",required_argument,NULL,'m'},
236 {"stats",no_argument,NULL,'s'},
237 {"nrecords",no_argument,NULL,'n'},
238 {"threads",required_argument,NULL,9},
239 {"output-file",required_argument,NULL,'o'},
240 {"output",required_argument,NULL,'o'},
241 {NULL, 0, NULL, 0}
242 };
243
244 char *tmp;
245 while ((c = getopt_long(argc, argv, "ctfm:snao:", loptions, NULL)) >= 0)
246 {
247 switch (c)
248 {
249 case 'c': tbi = 0; break;
250 case 't': tbi = 1; min_shift = 0; break;
251 case 'f': force = 1; break;
252 case 'm':
253 min_shift = strtol(optarg,&tmp,10);
254 if ( *tmp ) error("Could not parse argument: --min-shift %s\n", optarg);
255 break;
256 case 's': stats |= per_contig; break;
257 case 'n': stats |= total; break;
258 case 'a': stats |= all_contigs; break;
259 case 9:
260 n_threads = strtol(optarg,&tmp,10);
261 if ( *tmp ) error("Could not parse argument: --threads %s\n", optarg);
262 break;
263 case 'o': outfn = optarg; break;
264 default: usage();
265 }
266 }
267 if (!min_shift) tbi = 1;
268 if (stats > total)
269 {
270 fprintf(stderr, "[E::%s] expected only one of --stats or --nrecords options\n", __func__);
271 return 1;
272 }
273 if (tbi && min_shift>0)
274 {
275 fprintf(stderr, "[E::%s] min-shift option only expected for CSI indices \n", __func__);
276 return 1;
277 }
278 if (min_shift < 0 || min_shift > 30)
279 {
280 fprintf(stderr, "[E::%s] expected min_shift in range [0,30] (%d)\n", __func__, min_shift);
281 return 1;
282 }
283
284 char *fname = NULL;
285 if ( optind>=argc )
286 {
287 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
288 else usage();
289 }
290 else fname = argv[optind];
291 if (stats) return vcf_index_stats(fname, stats);
292
293 kstring_t idx_fname = {0,0,0};
294 if (outfn)
295 kputs(outfn,&idx_fname);
296 else
297 {
298 if (!strcmp(fname, "-")) { fprintf(stderr, "[E::%s] must specify an output path for index file when reading VCF/BCF from stdin\n", __func__); return 1; }
299 ksprintf(&idx_fname, "%s.%s", fname, tbi ? "tbi" : "csi");
300 }
301 if (!force)
302 {
303 // Before complaining about existing index, check if the VCF file isn't newer.
304 struct stat stat_tbi, stat_file;
305 if ( stat(idx_fname.s, &stat_tbi)==0 )
306 {
307 stat(fname, &stat_file);
308 if ( stat_file.st_mtime <= stat_tbi.st_mtime )
309 {
310 fprintf(stderr,"[E::%s] the index file exists. Please use '-f' to overwrite %s\n", __func__, idx_fname.s);
311 free(idx_fname.s);
312 return 1;
313 }
314 }
315
316 // check for truncated files, allow only with -f
317 BGZF *fp = bgzf_open(fname, "r");
318 if ( !fp ) error("index: failed to open %s\n", fname);
319 if ( bgzf_compression(fp)!=2 ) error("index: the file is not BGZF compressed, cannot index: %s\n", fname);
320 if ( bgzf_check_EOF(fp)!=1 ) error("index: the input is probably truncated, use -f to index anyway: %s\n", fname);
321 if ( bgzf_close(fp)!=0 ) error("index: close failed: %s\n", fname);
322 }
323
324 int ret = bcf_index_build3(fname, idx_fname.s, min_shift, n_threads);
325 free(idx_fname.s);
326 if (ret != 0) {
327 if (ret == -2)
328 error("index: failed to open \"%s\"\n", fname);
329 else if (ret == -3)
330 error("index: \"%s\" is in a format that cannot be usefully indexed\n", fname);
331 else
332 error("index: failed to create index for \"%s\"\n", fname);
333 }
334 return 0;
335 }