Debian Codegraph @

samtools/bam_index.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_index.c -- index and idxstats subcommands.
4
5 Copyright (C) 2008-2011, 2013-2016, 2018, 2019, 2023-2024 Genome Research Ltd.
6 Portions copyright (C) 2010 Broad Institute.
7 Portions copyright (C) 2013 Peter Cock, The James Hutton Institute.
8
9 Author: Heng Li <[email protected]>
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notices and this permission notice shall be included in
19 all copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 DEALINGS IN THE SOFTWARE. */
28
29 #include <config.h>
30
31 #include <htslib/hts.h>
32 #include <htslib/sam.h>
33 #include <htslib/hfile.h>
34 #include <htslib/khash.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <inttypes.h>
38 #include <unistd.h>
39 #include <getopt.h>
40
41 #include "samtools.h"
42 #include "sam_opts.h"
43
44 #define BAM_LIDX_SHIFT 14
45
46 static void index_usage(FILE *fp)
47 {
48 fprintf(fp,
49 "Usage: samtools index -M [-bc] [-m INT] <in1.bam> <in2.bam>...\n"
50 " or: samtools index [-bc] [-m INT] <in.bam> [out.index]\n"
51 "Options:\n"
52 " -b, --bai Generate BAI-format index for BAM files [default]\n"
53 " -c, --csi Generate CSI-format index for BAM files\n"
54 " -m, --min-shift INT Set minimum interval size for CSI indices to 2^INT [%d]\n"
55 " -M Interpret all filename arguments as files to be indexed\n"
56 " -o, --output FILE Write index to FILE [alternative to <out.index> in args]\n"
57 " -@, --threads INT Sets the number of threads [none]\n", BAM_LIDX_SHIFT);
58 }
59
60 // Returns 1 if the file does not exist or can be positively
61 // identified as an index file.
62 static int nonexistent_or_index(const char *fn)
63 {
64 int ret1, ret2;
65 htsFormat fmt;
66 hFILE *fp = hopen(fn, "r");
67 if (fp == NULL) return 1;
68
69 ret1 = hts_detect_format2(fp, fn, &fmt);
70 ret2 = hclose(fp);
71 if (ret1 < 0 || ret2 < 0) return 0;
72
73 return fmt.category == index_file;
74 }
75
76 int bam_index(int argc, char *argv[])
77 {
78 int csi = 0;
79 int min_shift = BAM_LIDX_SHIFT;
80 int multiple = 0;
81 int n_threads = 0;
82 int n_files, c, i, ret;
83 const char *fn_idx = NULL;
84
85 static const struct option lopts[] = {
86 SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'),
87 {"output", required_argument, NULL, 'o'},
88 {"bai", no_argument, NULL, 'b'},
89 {"csi", no_argument, NULL, 'c'},
90 {"min-shift", required_argument, NULL, 'm'},
91 { NULL, 0, NULL, 0 }
92 };
93
94 while ((c = getopt_long(argc, argv, "bcm:Mo:@:", lopts, NULL)) >= 0)
95 switch (c) {
96 case 'b': csi = 0; break;
97 case 'c': csi = 1; break;
98 case 'm': csi = 1; min_shift = atoi(optarg); break;
99 case 'M': multiple = 1; break;
100 case 'o': fn_idx = optarg; break;
101 case '@': n_threads = atoi(optarg); break;
102 default:
103 index_usage(samtools_stderr);
104 return 1;
105 }
106
107 n_files = argc - optind;
108
109 if (n_files == 0) {
110 index_usage(samtools_stdout);
111 return 0;
112 }
113
114 // Handle legacy synopsis
115 if (n_files == 2 && !fn_idx && nonexistent_or_index(argv[optind+1])) {
116 n_files = 1;
117 fn_idx = argv[optind+1];
118 }
119
120 if (n_files > 1 && !multiple) {
121 print_error("index", "use -M to enable indexing more than one alignment file");
122 return EXIT_FAILURE;
123 }
124
125 if (fn_idx && n_files > 1) {
126 // TODO In future we may allow %* placeholders or similar
127 print_error("index", "can't use -o with multiple input alignment files");
128 return EXIT_FAILURE;
129 }
130
131 for (i = optind; i < optind + n_files; i++) {
132 ret = sam_index_build3(argv[i], fn_idx, csi? min_shift : 0, n_threads);
133 if (ret < 0) {
134 if (ret == -2)
135 print_error_errno("index", "failed to open \"%s\"", argv[i]);
136 else if (ret == -3)
137 print_error("index", "\"%s\" is in a format that cannot be usefully indexed", argv[i]);
138 else if (ret == -4 && fn_idx)
139 print_error("index", "failed to create or write index \"%s\"", fn_idx);
140 else if (ret == -4)
141 print_error("index", "failed to create or write index");
142 else
143 print_error_errno("index", "failed to create index for \"%s\"", argv[i]);
144 return EXIT_FAILURE;
145 }
146 }
147
148 return EXIT_SUCCESS;
149 }
150
151 /*
152 * Cram indices do not contain mapped/unmapped record counts, so we have to
153 * decode each record and count. However we can speed this up as much as
154 * possible by using the required fields parameter.
155 *
156 * This prints the stats to samtools_stdout in the same manner than the BAM function
157 * does.
158 *
159 * Returns 0 on success,
160 * -1 on failure.
161 */
162 int slow_idxstats(samFile *fp, sam_hdr_t *header) {
163 int ret, last_tid = -2;
164 bam1_t *b = bam_init1();
165
166 if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, SAM_RNAME | SAM_FLAG))
167 return -1;
168
169 uint64_t (*count0)[2] = calloc(sam_hdr_nref(header)+1, sizeof(*count0));
170 uint64_t (*counts)[2] = count0+1;
171 if (!count0)
172 return -1;
173
174 while ((ret = sam_read1(fp, header, b)) >= 0) {
175 if (b->core.tid >= sam_hdr_nref(header) || b->core.tid < -1) {
176 free(count0);
177 return -1;
178 }
179
180 if (b->core.tid != last_tid) {
181 if (last_tid >= -1) {
182 if (counts[b->core.tid][0] + counts[b->core.tid][1]) {
183 print_error("idxstats", "file is not position sorted");
184 free(count0);
185 return -1;
186 }
187 }
188 last_tid = b->core.tid;
189 }
190
191 counts[b->core.tid][(b->core.flag & BAM_FUNMAP) ? 1 : 0]++;
192 }
193
194 if (ret == -1) {
195 int i;
196 for (i = 0; i < sam_hdr_nref(header); i++) {
197 fprintf(samtools_stdout, "%s\t%"PRId64"\t%"PRIu64"\t%"PRIu64"\n",
198 sam_hdr_tid2name(header, i),
199 (int64_t) sam_hdr_tid2len(header, i),
200 counts[i][0], counts[i][1]);
201 }
202 fprintf(samtools_stdout, "*\t0\t%"PRIu64"\t%"PRIu64"\n", counts[-1][0], counts[-1][1]);
203 }
204
205 free(count0);
206
207 bam_destroy1(b);
208
209 return (ret == -1) ? 0 : -1;
210 }
211
212 static void usage_exit(FILE *fp, int exit_status)
213 {
214 fprintf(fp, "Usage: samtools idxstats [options] <in.bam>\n"
215 " -X Include customized index file\n");
216 sam_global_opt_help(fp, "-.---@-.");
217 samtools_exit(exit_status);
218 }
219
220 int bam_idxstats(int argc, char *argv[])
221 {
222 hts_idx_t* idx;
223 sam_hdr_t* header;
224 samFile* fp;
225 int c, has_index_file = 0, file_names = 1;
226 char *index_name = NULL;
227
228 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
229 static const struct option lopts[] = {
230 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '@'),
231 {NULL, 0, NULL, 0}
232 };
233
234 while ((c = getopt_long(argc, argv, "@:X", lopts, NULL)) >= 0) {
235 switch (c) {
236 case 'X': has_index_file=1; break;
237 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
238 /* else fall-through */
239 case '?':
240 usage_exit(samtools_stderr, EXIT_FAILURE);
241 }
242 }
243
244 if (has_index_file) {
245 file_names = 2;
246 index_name = argv[optind + 1];
247 }
248
249 if (argc != optind + file_names) {
250 if (argc == optind) usage_exit(samtools_stdout, EXIT_SUCCESS);
251 else usage_exit(samtools_stderr, EXIT_FAILURE);
252 }
253
254 fp = sam_open_format(argv[optind], "r", &ga.in);
255 if (fp == NULL) {
256 print_error_errno("idxstats", "failed to open \"%s\"", argv[optind]);
257 return 1;
258 }
259 header = sam_hdr_read(fp);
260 if (header == NULL) {
261 print_error("idxstats", "failed to read header for \"%s\"", argv[optind]);
262 return 1;
263 }
264
265 if (hts_get_format(fp)->format != bam) {
266 slow_method:
267 if (ga.nthreads)
268 hts_set_threads(fp, ga.nthreads);
269
270 if (slow_idxstats(fp, header) < 0) {
271 print_error("idxstats", "failed to process \"%s\"", argv[optind]);
272 return 1;
273 }
274 } else {
275 idx = sam_index_load2(fp, argv[optind], index_name);
276 if (idx == NULL) {
277 print_error("idxstats", "fail to load index for \"%s\", "
278 "reverting to slow method", argv[optind]);
279 goto slow_method;
280 }
281
282 int i;
283 for (i = 0; i < sam_hdr_nref(header); ++i) {
284 // Print out contig name and length
285 fprintf(samtools_stdout, "%s\t%"PRId64, sam_hdr_tid2name(header, i), (int64_t) sam_hdr_tid2len(header, i));
286 // Now fetch info about it from the meta bin
287 uint64_t u, v;
288 hts_idx_get_stat(idx, i, &u, &v);
289 fprintf(samtools_stdout, "\t%" PRIu64 "\t%" PRIu64 "\n", u, v);
290 }
291 // Dump information about unmapped reads
292 fprintf(samtools_stdout, "*\t0\t0\t%" PRIu64 "\n", hts_idx_get_n_no_coor(idx));
293 hts_idx_destroy(idx);
294 }
295
296 sam_hdr_destroy(header);
297 sam_close(fp);
298 return 0;
299 }