Debian Codegraph @

samtools/faidx.c.pysam.c

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