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