Debian Codegraph @

bcftools/vcfindex.c.pysam.c

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