Debian Codegraph @

samtools/faidx.c

raw symbols SCIP
1 /* faidx.c -- faidx subcommand.
2
3 Copyright (C) 2008, 2009, 2013, 2016, 2018-2020, 2022, 2024 Genome Research Ltd.
4 Portions copyright (C) 2011 Broad Institute.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE.
25
26 History:
27
28 * 2016-01-12: Pierre Lindenbaum @yokofakun : added options -o -n
29
30 */
31
32 #include <config.h>
33
34 #include <ctype.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <unistd.h>
39 #include <stdarg.h>
40 #include <errno.h>
41 #include <getopt.h>
42 #include <limits.h>
43 #include <htslib/faidx.h>
44 #include <htslib/hts.h>
45 #include <htslib/hfile.h>
46 #include <htslib/kstring.h>
47 #include <htslib/bgzf.h>
48 #include <htslib/thread_pool.h>
49 #include "sam_opts.h"
50 #include "samtools.h"
51
52 // Negative indicates the same as input data
53 #define DEFAULT_FASTA_LINE_LEN -60
54
55 #ifndef ABS
56 # define ABS(x) ((x)>=0?(x):-(x))
57 #endif
58
59 //new params required for output creation
60 typedef struct output {
61 int isbgzip; //is bgzip or uncompressed file
62 FILE *fp; //uncompressed file pointer
63 BGZF *bgzf_fp; //bgzf file pointer
64 sam_global_args *gopt; //options
65 kstring_t buffer;
66 } output;
67
68 static unsigned char comp_base[256] = {
69 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
70 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
71 32, '!', '"', '#', '$', '%', '&', '\'','(', ')', '*', '+', ',', '-', '.', '/',
72 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
73 '@', 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O',
74 'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', '[', '\\',']', '^', '_',
75 '`', 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o',
76 'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', '{', '|', '}', '~', 127,
77 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
78 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
79 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
80 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
81 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
82 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
83 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
84 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
85 };
86
87 static void reverse_complement(char *str, const hts_pos_t len) {
88 char c;
89 hts_pos_t i = 0, j = len - 1;
90
91 while (i <= j) {
92 c = str[i];
93 str[i] = comp_base[(unsigned char)str[j]];
94 str[j] = comp_base[(unsigned char)c];
95 i++;
96 j--;
97 }
98 }
99
100 static void reverse(char *str, const hts_pos_t len) {
101 char c;
102 hts_pos_t i = 0, j = len - 1;
103
104 while (i < j) {
105 c = str[i];
106 str[i] = str[j];
107 str[j] = c;
108 i++;
109 j--;
110 }
111 }
112
113 /// wrappedwrite - wraps the fwrite and bgzf_write
114 /** @param out - pointer to data required to write output
115 * @param buffer - data to write
116 * @param length - data length
117 * returns error or length written on success
118 */
119 static inline size_t wrappedwrite(output *out, const char *buffer, size_t length)
120 {
121 return out->isbgzip ? bgzf_write(out->bgzf_fp, buffer, length) :
122 fwrite(buffer, 1, length, out->fp);
123 }
124
125 static int write_line(faidx_t *faid, output *out, const char *line, const char *name,
126 const int ignore, const hts_pos_t length, const hts_pos_t seq_len) {
127 int id;
128 hts_pos_t beg, end;
129
130 if (seq_len < 0) {
131 fprintf(stderr, "[faidx] Failed to fetch sequence in %s\n", name);
132
133 if (ignore && seq_len == -2) {
134 return EXIT_SUCCESS;
135 } else {
136 return EXIT_FAILURE;
137 }
138 } else if (seq_len == 0) {
139 fprintf(stderr, "[faidx] Zero length sequence: %s\n", name);
140 } else if (fai_parse_region(faid, name, &id, &beg, &end, 0)
141 && (end < HTS_POS_MAX) && (seq_len != end - beg)) {
142 fprintf(stderr, "[faidx] Truncated sequence: %s\n", name);
143 }
144
145 hts_pos_t i, seq_sz = seq_len;
146
147 for (i = 0; i < seq_sz; i += length)
148 {
149 hts_pos_t len = i + length < seq_sz ? length : seq_sz - i;
150 if (wrappedwrite(out, line + i, len) < len ||
151 wrappedwrite(out, "\n", 1) < 1) {
152 print_error_errno("faidx", "failed to write output");
153 return EXIT_FAILURE;
154 }
155 }
156
157 return EXIT_SUCCESS;
158 }
159
160
161 static int write_output(faidx_t *faid, output *out, const char *name, const int ignore,
162 const hts_pos_t length, const int rev,
163 const char *pos_strand_name, const char *neg_strand_name,
164 enum fai_format_options format) {
165 hts_pos_t seq_len, wrap_len = length, len = 0;
166 char *seq = NULL, *qual = NULL;
167 int ret = EXIT_FAILURE;
168
169 if (wrap_len < 0)
170 wrap_len = fai_line_length(faid, name);
171 if (wrap_len <= 0)
172 wrap_len = HTS_POS_MAX;
173
174 seq = fai_fetch64(faid, name, &seq_len);
175 if (rev && seq_len > 0) {
176 reverse_complement(seq, seq_len);
177 }
178 //write the name
179 len = ksprintf(&out->buffer, "%c%s%s\n", format == FAI_FASTA ? '>' : '@', name, rev ? neg_strand_name : pos_strand_name);
180 if (wrappedwrite(out, out->buffer.s, out->buffer.l) < len) {
181 fprintf(stderr,"[faidx] Failed to write buffer\n");
182 goto exit;
183 }
184 ks_clear(&out->buffer);
185 //write bases
186 if ((ret = write_line(faid, out, seq, name, ignore, wrap_len, seq_len) == EXIT_FAILURE)) {
187 goto exit;
188 }
189
190 if (format == FAI_FASTQ) {
191 //write quality
192 qual = fai_fetchqual64(faid, name, &seq_len);
193 if (rev && seq_len > 0) {
194 reverse(qual, seq_len);
195 }
196
197 len = ksprintf(&out->buffer, "+\n");
198 if (wrappedwrite(out, out->buffer.s, out->buffer.l) < len) {
199 fprintf(stderr,"[faidx] Failed to write buffer\n");
200 goto exit;
201 }
202 ks_clear(&out->buffer);
203 if ((ret = write_line(faid, out, qual, name, ignore, wrap_len, seq_len) == EXIT_FAILURE)) {
204 goto exit;
205 }
206 }
207 ret = EXIT_SUCCESS;
208
209 exit:
210 if (seq) {
211 free(seq);
212 }
213 if (qual) {
214 free(qual);
215 }
216 return ret;
217 }
218
219
220 static int read_regions_from_file(faidx_t *faid, hFILE *in_file, output *out, const int ignore,
221 const hts_pos_t length, const int rev,
222 const char *pos_strand_name,
223 const char *neg_strand_name,
224 enum fai_format_options format) {
225 kstring_t line = {0, 0, NULL};
226 int ret = EXIT_FAILURE;
227
228 while (line.l = 0, kgetline(&line, (kgets_func *)hgets, in_file) >= 0) {
229 if ((ret = write_output(faid, out, line.s, ignore, length, rev, pos_strand_name, neg_strand_name, format)) == EXIT_FAILURE) {
230 break;
231 }
232 }
233
234 free(line.s);
235
236 return ret;
237 }
238
239 static int usage(FILE *fp, enum fai_format_options format, int exit_status)
240 {
241 char *tool, *file_type, *index_name;
242
243 if (format == FAI_FASTA) {
244 tool = "faidx <file.fa|file.fa.gz>";
245 file_type = "FASTA";
246 index_name = "file.fa";
247 } else {
248 tool = "fqidx <file.fq|file.fq.gz>";
249 file_type = "FASTQ";
250 index_name = "file.fq";
251 }
252
253 fprintf(fp, "Usage: samtools %s [<reg> [...]]\n", tool);
254 fprintf(fp, "Option: \n"
255 " -o, --output FILE Write %s to file.\n"
256 " -n, --length INT Length of %s sequence line. [60]\n"
257 " -c, --continue Continue after trying to retrieve missing region.\n"
258 " -r, --region-file FILE File of regions. Format is chr:from-to. One per line.\n"
259 " -i, --reverse-complement Reverse complement sequences.\n"
260 " --mark-strand TYPE Add strand indicator to sequence name\n"
261 " TYPE = rc for /rc on negative strand (default)\n"
262 " no for no strand indicator\n"
263 " sign for (+) / (-)\n"
264 " custom,<pos>,<neg> for custom indicator\n"
265 " --fai-idx FILE name of the index file (default %s.fai).\n"
266 " --gzi-idx FILE name of compressed file index (default %s.gz.gzi).\n",
267 file_type, file_type, index_name, index_name);
268
269
270 if (format == FAI_FASTA) {
271 fprintf(fp, " -f, --fastq File and index in FASTQ format.\n");
272 }
273
274 fprintf(fp, " -h, --help This message.\n");
275 sam_global_opt_help(fp, "---.-@--");
276
277 return exit_status;
278 }
279
280 int faidx_core(int argc, char *argv[], enum fai_format_options format)
281 {
282 int c, ignore_error = 0, rev = 0;
283 hts_pos_t line_len = DEFAULT_FASTA_LINE_LEN ;/* fasta line len */
284 char* output_file = NULL; /* output file (default is stdout ) */
285 char *region_file = NULL; // list of regions from file, one per line
286 char *pos_strand_name = ""; // Extension to add to name for +ve strand
287 char *neg_strand_name = "/rc"; // Extension to add to name for -ve strand
288 char *strand_names = NULL; // Used for custom strand annotation
289 char *fai_name = NULL; // specified index name
290 char *gzi_name = NULL; // specified compressed index name
291 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
292 int exit_status = EXIT_FAILURE, flushed = 0;
293 struct output out = { 0, stdout, NULL, &ga, KS_INITIALIZE}; //data required for output writing
294 faidx_t *fai = NULL;
295 hts_tpool *pool = NULL;
296
297 static const struct option lopts[] = {
298 SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', 0, '-', '@'), //output format opt and thread count - long options
299 { "output", required_argument, NULL, 'o' },
300 { "help", no_argument, NULL, 'h' },
301 { "length", required_argument, NULL, 'n' },
302 { "continue", no_argument, NULL, 'c' },
303 { "region-file", required_argument, NULL, 'r' },
304 { "fastq", no_argument, NULL, 'f' },
305 { "reverse-complement", no_argument, NULL, 'i' },
306 { "mark-strand", required_argument, NULL, 1000 },
307 { "fai-idx", required_argument, NULL, 1001 },
308 { "gzi-idx", required_argument, NULL, 1002 },
309 { NULL, 0, NULL, 0 }
310 };
311
312 while ((c = getopt_long(argc, argv, "ho:n:cr:fi@:", lopts, NULL)) >= 0) {
313 switch (c) {
314 case 'o':
315 {
316 output_file = optarg;
317 char *ext = strrchr(output_file, '.');
318 if (!ext) {
319 break;
320 }
321 if (!strcmp(ext, ".gz") || !strcmp(ext, ".bgz") || !strcmp(ext, ".bgzf")) {
322 out.isbgzip = 1; //bgzip output
323 }
324 break;
325 }
326 case 'n': line_len = strtol(optarg, NULL, 10);
327 if (line_len < 0) {
328 fprintf(stderr,"[faidx] bad line length '%s', using default:%d\n",optarg,ABS(DEFAULT_FASTA_LINE_LEN));
329 line_len= ABS(DEFAULT_FASTA_LINE_LEN);
330 }
331 break;
332 case 'c': ignore_error = 1; break;
333 case 'r': region_file = optarg; break;
334 case 'f': format = FAI_FASTQ; break;
335 case 'i': rev = 1; break;
336 case '?':
337 exit_status = usage(stderr, format, EXIT_FAILURE);
338 goto exit2;
339 break;
340 case 'h':
341 exit_status = usage(stdout, format, EXIT_SUCCESS);
342 goto exit2;
343 break;
344 case 1000:
345 if (strcmp(optarg, "no") == 0) {
346 pos_strand_name = neg_strand_name = "";
347 } else if (strcmp(optarg, "sign") == 0) {
348 pos_strand_name = "(+)";
349 neg_strand_name = "(-)";
350 } else if (strcmp(optarg, "rc") == 0) {
351 pos_strand_name = "";
352 neg_strand_name = "/rc";
353 } else if (strncmp(optarg, "custom,", 7) == 0) {
354 size_t len = strlen(optarg + 7);
355 size_t comma = strcspn(optarg + 7, ",");
356 free(strand_names);
357 strand_names = pos_strand_name = malloc(len + 2);
358 if (!strand_names) {
359 fprintf(stderr, "[faidx] Out of memory\n");
360 goto exit2;
361 }
362 neg_strand_name = pos_strand_name + comma + 1;
363 memcpy(pos_strand_name, optarg + 7, comma);
364 pos_strand_name[comma] = '\0';
365 if (comma < len)
366 memcpy(neg_strand_name, optarg + 7 + comma + 1,
367 len - comma);
368 neg_strand_name[len - comma] = '\0';
369 } else {
370 fprintf(stderr, "[faidx] Unknown --mark-strand option \"%s\"\n", optarg);
371 exit_status = usage(stderr, format, EXIT_FAILURE);
372 goto exit2;
373 }
374 break;
375 case 1001: fai_name = optarg; break;
376 case 1002: gzi_name = optarg; break;
377 // handle standard samtools options like thread count, compression level...
378 default:
379 if (parse_sam_global_opt(c, optarg, lopts, &ga)) {
380 fprintf(stderr, "[faidx] Invalid option \"%s\"\n", optarg);
381 goto exit2;
382 }
383 break;
384 }
385 }
386
387 if ( argc==optind ) {
388 exit_status = usage(stdout, format, EXIT_SUCCESS);
389 goto exit2;
390 }
391
392 if (optind+1 == argc && !region_file) {
393 if (output_file && !fai_name)
394 fai_name = output_file;
395
396 if (fai_build3(argv[optind], fai_name, gzi_name) != 0) {
397 if (fai_name)
398 fprintf(stderr, "[faidx] Could not build fai index %s", fai_name);
399 else
400 fprintf(stderr, "[faidx] Could not build fai index %s.fai", argv[optind]);
401
402 if (gzi_name)
403 fprintf(stderr, " or compressed index %s\n", gzi_name);
404 else
405 fprintf(stderr, "\n");
406
407 goto exit2;
408 }
409 exit_status = EXIT_SUCCESS;
410 goto exit2;
411 }
412
413 if (out.gopt->nthreads > 0) { //setup thread pool
414 if (!(pool = hts_tpool_init(out.gopt->nthreads))) {
415 fprintf(stderr, "Failed to setup thread pool\n");
416 }
417 }
418
419 fai = fai_load3_format(argv[optind], fai_name, gzi_name, FAI_CREATE, format);
420
421 if (!fai) {
422 if (fai_name)
423 fprintf(stderr, "[faidx] Could not load fai index %s", fai_name);
424 else
425 fprintf(stderr, "[faidx] Could not load fai index %s.fai", argv[optind]);
426
427 if (gzi_name)
428 fprintf(stderr, " or compressed index %s\n", gzi_name);
429 else
430 fprintf(stderr, "\n");
431
432 goto exit2;
433 }
434
435 if (pool) { //use thread pool if set
436 if (fai_thread_pool(fai, pool, 0)) {
437 fprintf(stderr, "Failed to set thread pool for reading\n");
438 }
439 }
440
441 /** output file provided by user */
442 if( output_file != NULL ) {
443 if( strcmp( output_file, argv[optind] ) == 0 ) {
444 fprintf(stderr,"[faidx] Same input/output : %s\n", output_file);
445 goto exit2;
446 }
447 if (!out.isbgzip) {
448 out.fp = fopen( output_file, "w" );
449 } else {
450 hts_opt *opts = (hts_opt *)(out.gopt->out.specific);
451 char mode[13] = "w";
452 int level = 4; //default compression level
453 while (opts) {
454 if (opts->opt == HTS_OPT_COMPRESSION_LEVEL) { //compression level
455 level = opts->val.i;
456 break;
457 }
458 opts = opts->next;
459 }
460 if (level >= 0) {
461 snprintf(mode, sizeof(mode), "w%d", level); //pass compression with mode
462 }
463 out.bgzf_fp = bgzf_open(output_file, mode);
464 }
465
466 if( (!out.isbgzip && out.fp == NULL) || (out.isbgzip && out.bgzf_fp == NULL)) {
467 fprintf(stderr,"[faidx] Cannot open \"%s\" for writing :%s.\n", output_file, strerror(errno) );
468 goto exit2;
469 }
470 if (out.isbgzip && pool) { //use thread pool if set
471 if (bgzf_thread_pool(out.bgzf_fp, pool, 0)) {
472 fprintf(stderr, "Failed to set thread pool for writing\n");
473 }
474 }
475 }
476
477 if (region_file) {
478 hFILE *rf;
479
480 if ((rf = hopen(region_file, "r"))) {
481 exit_status = read_regions_from_file(fai, rf, &out, ignore_error, line_len, rev, pos_strand_name, neg_strand_name, format);
482
483 if (hclose(rf) != 0) {
484 fprintf(stderr, "[faidx] Warning: failed to close %s", region_file);
485 }
486 if (exit_status == EXIT_FAILURE) {
487 goto exit1;
488 }
489 } else {
490 fprintf(stderr, "[faidx] Failed to open \"%s\" for reading.\n", region_file);
491 goto exit1;
492 }
493 }
494
495 exit_status = EXIT_SUCCESS;
496 while ( ++optind<argc && exit_status == EXIT_SUCCESS) {
497 exit_status = write_output(fai, &out, argv[optind], ignore_error, line_len, rev, pos_strand_name, neg_strand_name, format);
498 }
499
500 flushed = out.isbgzip ? bgzf_flush(out.bgzf_fp) : fflush(out.fp);
501 if (flushed == EOF) {
502 print_error_errno("faidx", "Failed to flush output\n");
503 exit_status = EXIT_FAILURE;
504 }
505
506 exit1:
507 if( output_file != NULL && !out.isbgzip) {
508 fclose(out.fp); //no need to check result as already flushed
509 } else if( output_file != NULL && out.isbgzip) {
510 if (bgzf_close(out.bgzf_fp) < 0) {
511 print_error_errno("faidx", "Failed to close output\n");
512 exit_status = EXIT_FAILURE;
513 }
514 }
515
516 exit2:
517 if (strand_names) {
518 free(strand_names);
519 }
520 if (fai) {
521 fai_destroy(fai);
522 }
523 if (pool) {
524 hts_tpool_destroy(pool);
525 }
526 sam_global_args_free(&ga);
527 ks_free(&out.buffer);
528
529 return exit_status;
530 }
531
532
533 int faidx_main(int argc, char *argv[]) {
534 return faidx_core(argc, argv, FAI_FASTA);
535 }
536
537
538 int fqidx_main(int argc, char *argv[]) {
539 return faidx_core(argc, argv, FAI_FASTQ);
540 }
541