Debian Codegraph @

samtools/bam_fastq.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_fastq.c -- FASTA and FASTQ file generation
4
5 Copyright (C) 2009-2017, 2019-2020, 2023-2024 Genome Research Ltd.
6 Portions copyright (C) 2009, 2011, 2012 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 notices 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 #include <config.h>
29
30 #include <stdlib.h>
31 #include <string.h>
32 #include <strings.h>
33 #include <stdbool.h>
34 #include <ctype.h>
35 #include <assert.h>
36 #include <inttypes.h>
37 #include <unistd.h>
38 #include <float.h>
39
40 #include "htslib/sam.h"
41 #include "htslib/klist.h"
42 #include "htslib/kstring.h"
43 #include "htslib/bgzf.h"
44 #include "htslib/thread_pool.h"
45 #include "htslib/khash.h"
46 #include "samtools.h"
47 #include "sam_opts.h"
48
49 KHASH_SET_INIT_STR(str)
50 typedef khash_t(str) strhash_t;
51
52 #define DEFAULT_BARCODE_TAG "BC"
53 #define DEFAULT_QUALITY_TAG "QT"
54 #define INDEX_SEPARATOR "+"
55
56 int8_t seq_comp_table[16] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
57 static void bam2fq_usage(FILE *to, const char *command)
58 {
59 int fq = strcasecmp("fastq", command) == 0 || strcasecmp("bam2fq", command) == 0;
60 fprintf(to,
61 "Usage: samtools %s [options...] <in.bam>\n", command);
62 fprintf(to,
63 "\n"
64 "Description:\n"
65 "Converts a SAM, BAM or CRAM to %s format.\n"
66 "\n"
67 "Options:\n"
68 " -0 FILE write reads designated READ_OTHER to FILE\n"
69 " -1 FILE write reads designated READ1 to FILE\n"
70 " -2 FILE write reads designated READ2 to FILE\n"
71 " -o FILE write reads designated READ1 or READ2 to FILE\n"
72 " note: if a singleton file is specified with -s, only\n"
73 " paired reads will be written to the -1 and -2 files.\n"
74 " -d, --tag TAG[:VAL]\n"
75 " only include reads containing TAG, optionally with value VAL\n"
76 " -D, --tag-file STR:FILE\n"
77 " only include reads containing TAG, with a value listed in FILE\n"
78 " -f, --require-flags INT\n"
79 " only include reads with all of the FLAGs in INT present [0]\n" // F&x == x
80 " -F, --excl[ude]-flags INT\n"
81 " only include reads with none of the FLAGs in INT present [0x900]\n" // F&x == 0
82 " --rf, --incl[ude]-flags INT\n"
83 " only include reads with any of the FLAGs in INT present [0]\n" // !(F&x == 0)
84 " -G INT only EXCLUDE reads with all of the FLAGs in INT present [0]\n" // !(F&x == x)
85 " -n don't append /1 and /2 to the read name\n"
86 " -N always append /1 and /2 to the read name\n",
87 fq ? "FASTQ" : "FASTA");
88 if (fq) fprintf(to,
89 " -O output quality in the OQ tag if present\n");
90 fprintf(to,
91 " -s FILE write singleton reads designated READ1 or READ2 to FILE\n"
92 " -t copy RG, BC and QT tags to the %s header line\n",
93 fq ? "FASTQ" : "FASTA");
94 fprintf(to,
95 " -T TAGLIST copy arbitrary tags to the %s header line, '*' for all\n",
96 fq ? "FASTQ" : "FASTA");
97 if (fq) fprintf(to,
98 " -v INT default quality score if not given in file [1]\n"
99 " -i add Illumina Casava 1.8 format entry to header (eg 1:N:0:ATCACG)\n"
100 " -c INT compression level [0..9] to use when writing bgzf files [1]\n"
101 " --i1 FILE write first index reads to FILE\n"
102 " --i2 FILE write second index reads to FILE\n"
103 " --barcode-tag TAG\n"
104 " Barcode tag [" DEFAULT_BARCODE_TAG "]\n"
105 " --quality-tag TAG\n"
106 " Quality tag [" DEFAULT_QUALITY_TAG "]\n"
107 " --index-format STR\n"
108 " How to parse barcode and quality tags\n\n");
109 sam_global_opt_help(to, "-.--.@-.");
110 fprintf(to,
111 "\n"
112 "The files will be automatically compressed if the file names have a .gz\n"
113 "or .bgzf extension. The input to this program must be collated by name.\n"
114 "Run 'samtools collate' or 'samtools sort -n' to achieve this.\n"
115 "\n"
116 "Reads are designated READ1 if FLAG READ1 is set and READ2 is not set.\n"
117 "Reads are designated READ2 if FLAG READ1 is not set and READ2 is set.\n"
118 "Otherwise reads are designated READ_OTHER (both flags set or both flags unset).\n"
119 "Run 'samtools flags' for more information on flag codes and meanings.\n");
120 fprintf(to,
121 "\n"
122 "The index-format string describes how to parse the barcode and quality tags.\n"
123 "It is made up of 'i' or 'n' followed by a length or '*'. For example:\n"
124 " i14i8 The first 14 characters are index 1, the next 8 are index 2\n"
125 " n8i14 Ignore the first 8 characters, and use the next 14 for index 1\n\n"
126 "If the tag contains a separator, then the numeric part can be replaced with\n"
127 "'*' to mean 'read until the separator or end of tag', for example:\n"
128 " i*i* Break the tag at the separator into index 1 and index 2\n"
129 " n*i* Ignore the left part of the tag until the separator,\n"
130 " then use the second part of the tag as index 1\n");
131 fprintf(to,
132 "\n"
133 "Examples:\n"
134 "To get just the paired reads in separate files, use:\n"
135 " samtools %s -1 pair1.%s -2 pair2.%s -0 /dev/null -s /dev/null -n in.bam\n"
136 "\nTo get all non-supplementary/secondary reads in a single file, redirect\n"
137 "the output:\n"
138 " samtools %s in.bam > all_reads.%s\n",
139 command, fq ? "fq" : "fa", fq ? "fq" : "fa",
140 command, fq ? "fq" : "fa");
141 }
142
143 typedef enum { READ_UNKNOWN = 0, READ_1 = 1, READ_2 = 2 } readpart;
144 typedef enum { FASTA, FASTQ } fastfile;
145 typedef struct bam2fq_opts {
146 char *fnse;
147 char *fnr[3];
148 char *fn_input; // pointer to input filename in argv do not free
149 bool has12, has12always, use_oq, copy_tags, illumina_tag;
150 int flag_on, flag_off, flag_alloff, flag_anyon;
151 sam_global_args ga;
152 fastfile filetype;
153 int def_qual;
154 char *barcode_tag;
155 char *quality_tag;
156 char *index_file[2];
157 char *index_format;
158 char *extra_tags;
159 char compression_level;
160 const char *filter_tag; // -d opt
161 strhash_t *filter_tag_vals;
162 } bam2fq_opts_t;
163
164 typedef struct bam2fq_state {
165 samFile *fp;
166 samFile *fpse;
167 samFile *fpr[3];
168 samFile *fpi[3];
169 samFile *hstdout;
170 sam_hdr_t *h;
171 bool has12, use_oq, copy_tags, illumina_tag;
172 int flag_on, flag_off, flag_alloff, flag_anyon;
173 fastfile filetype;
174 int def_qual;
175 char *index_sequence;
176 char compression_level;
177 htsThreadPool p;
178 } bam2fq_state_t;
179
180 // Adds a single tag value to the filter tag value hash
181 static int add_tag_value(bam2fq_opts_t *opts, char *val) {
182 if (!opts->filter_tag_vals) {
183 if (!(opts->filter_tag_vals = kh_init(str)))
184 return -1;
185 }
186
187 if (!(val = strdup(val)))
188 return -1;
189
190 int ret = 0;
191 kh_put(str, opts->filter_tag_vals, val, &ret);
192 if (ret <= 0)
193 free(val);
194
195 return ret < 0 ? -1 : 0;
196 }
197
198 // Adds multiple values, listed in a file
199 static int add_tag_file(bam2fq_opts_t *opts, char *fn) {
200 FILE *fp;
201 kstring_t ks = {0,0};
202
203 if (!(fp = fopen(fn, "r"))) {
204 print_error_errno("fastq", "failed to open \"%s\" for reading", fn);
205 return -1;
206 }
207
208 while (ks.l = 0, kgetline(&ks, (kgets_func *)fgets, fp) >= 0) {
209 if (add_tag_value(opts, ks.s) < 0) {
210 ks_free(&ks);
211 return -1;
212 }
213 }
214
215 ks_free(&ks);
216 return 0;
217 }
218
219 static readpart which_readpart(const bam1_t *b)
220 {
221 if ((b->core.flag & BAM_FREAD1) && !(b->core.flag & BAM_FREAD2)) {
222 return READ_1;
223 } else if ((b->core.flag & BAM_FREAD2) && !(b->core.flag & BAM_FREAD1)) {
224 return READ_2;
225 } else {
226 return READ_UNKNOWN;
227 }
228 }
229
230 static void free_opts(bam2fq_opts_t *opts)
231 {
232 if (opts->filter_tag_vals) {
233 khint_t k;
234 for (k = 0; k < kh_end(opts->filter_tag_vals); k++)
235 if (kh_exist(opts->filter_tag_vals, k))
236 free((char *)kh_key(opts->filter_tag_vals, k));
237
238 kh_destroy(str, opts->filter_tag_vals);
239 }
240 free(opts);
241 }
242
243 // Make mnemonic distinct values for longoption-only options
244 #define LONGOPT(c) ((c) + 128)
245
246 // return true if valid
247 static bool parse_opts(int argc, char *argv[], bam2fq_opts_t** opts_out)
248 {
249 // Parse args
250 bam2fq_opts_t* opts = calloc(1, sizeof(bam2fq_opts_t));
251 opts->has12 = true;
252 opts->has12always = false;
253 opts->filetype = FASTQ;
254 opts->def_qual = 1;
255 opts->barcode_tag = NULL;
256 opts->quality_tag = NULL;
257 opts->index_format = NULL;
258 opts->index_file[0] = NULL;
259 opts->index_file[1] = NULL;
260 opts->extra_tags = NULL;
261 opts->compression_level = 1;
262 opts->flag_off = BAM_FSECONDARY|BAM_FSUPPLEMENTARY;
263
264 int c;
265 sam_global_args_init(&opts->ga);
266 static const struct option lopts[] = {
267 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'),
268 {"require-flags", required_argument, NULL, 'f'},
269 {"excl-flags", required_argument, NULL, 'F'},
270 {"exclude-flags", required_argument, NULL, 'F'},
271 // following the same convention as view: g exists as a longoption_only
272 // argument, accessible from the command line as --rf/--incl[ude]-flags
273 {"rf", required_argument, NULL, LONGOPT('g')},
274 {"incl-flags", required_argument, NULL, LONGOPT('g')},
275 {"include-flags", required_argument, NULL, LONGOPT('g')},
276 {"i1", required_argument, NULL, 1},
277 {"I1", required_argument, NULL, 1},
278 {"i2", required_argument, NULL, 2},
279 {"I2", required_argument, NULL, 2},
280 {"if", required_argument, NULL, 3},
281 {"IF", required_argument, NULL, 3},
282 {"index-format", required_argument, NULL, 3},
283 {"barcode-tag", required_argument, NULL, 'b'},
284 {"quality-tag", required_argument, NULL, 'q'},
285 {"tag", required_argument, NULL, 'd'},
286 {"tag-file", required_argument, NULL, 'D'},
287 { NULL, 0, NULL, 0 }
288 };
289 while ((c = getopt_long(argc, argv, "0:1:2:o:f:F:G:niNOs:c:tT:v:@:d:D:",
290 lopts, NULL)) > 0) {
291 switch (c) {
292 case 'b': opts->barcode_tag = optarg; break;
293 case 'q': opts->quality_tag = optarg; break;
294 case 1 : opts->index_file[0] = optarg; break;
295 case 2 : opts->index_file[1] = optarg; break;
296 case 3 : opts->index_format = optarg; break;
297 case '0': opts->fnr[0] = optarg; break;
298 case '1': opts->fnr[1] = optarg; break;
299 case '2': opts->fnr[2] = optarg; break;
300 case 'o': opts->fnr[1] = optarg; opts->fnr[2] = optarg; break;
301 case 'f': opts->flag_on |= strtol(optarg, 0, 0); break;
302 // note that flag_off does not have |= because it has a default
303 // value of 0x900 which needs to be replaced by the optarg
304 case 'F': opts->flag_off = strtol(optarg, 0, 0); break;
305 case 'G': opts->flag_alloff |= strtol(optarg, 0, 0); break;
306 case LONGOPT('g'): opts->flag_anyon |= strtol(optarg, 0, 0); break;
307 case 'n': opts->has12 = false; break;
308 case 'N': opts->has12always = true; break;
309 case 'O': opts->use_oq = true; break;
310 case 's': opts->fnse = optarg; break;
311 case 't': opts->copy_tags = true; break;
312 case 'i': opts->illumina_tag = true; break;
313 case 'c':
314 opts->compression_level = atoi(optarg);
315 if (opts->compression_level < 0)
316 opts->compression_level = 0;
317 if (opts->compression_level > 9)
318 opts->compression_level = 9;
319 break;
320 case 'T': opts->extra_tags = optarg; break;
321 case 'v': opts->def_qual = atoi(optarg); break;
322
323 case 'd':
324 if (strlen(optarg) < 2 ||
325 (strlen(optarg) > 2 && optarg[2] != ':')) {
326 print_error("fastq",
327 "Invalid \"tag:value\" option: \"%s\"",
328 optarg);
329 free_opts(opts);
330 return false;
331 }
332
333 if (opts->filter_tag && memcmp(opts->filter_tag, optarg, 2)) {
334 print_error("fastq", "Different tag type specified "
335 "to before");
336 free_opts(opts);
337 return false;
338 }
339
340 if (strlen(optarg) >= 3)
341 add_tag_value(opts, optarg+3);
342 opts->filter_tag = optarg;
343 break;
344
345 case 'D':
346 // Allow ";" as delimiter besides ":" to support MinGW CLI POSIX
347 // path translation as described at:
348 // http://www.mingw.org/wiki/Posix_path_conversion
349 if (strlen(optarg) < 4
350 || (optarg[2] != ':' && optarg[2] != ';')) {
351 print_error("view", "Invalid \"tag:file\" option: \"%s\"",
352 optarg);
353 free_opts(opts);
354 return false;
355 }
356
357 if (opts->filter_tag && memcmp(opts->filter_tag, optarg, 2)) {
358 print_error("fastq", "Different tag type specified "
359 "to before");
360 free_opts(opts);
361 return false;
362 }
363
364 if (strlen(optarg) >= 3) {
365 if (add_tag_file(opts, optarg+3) < 0) {
366 free_opts(opts);
367 return false;
368 }
369 }
370 opts->filter_tag = optarg;
371 break;
372
373 case '?':
374 bam2fq_usage(samtools_stderr, argv[0]);
375 free_opts(opts);
376 return false;
377 default:
378 if (parse_sam_global_opt(c, optarg, lopts, &opts->ga) != 0) {
379 bam2fq_usage(samtools_stderr, argv[0]);
380 free_opts(opts);
381 return false;
382 }
383 break;
384 }
385 }
386
387 if (opts->fnr[1] || opts->fnr[2]) opts->has12 = false;
388 if (opts->has12always) opts->has12 = true;
389
390 if (!opts->barcode_tag) opts->barcode_tag = DEFAULT_BARCODE_TAG;
391 if (!opts->quality_tag) opts->quality_tag = DEFAULT_QUALITY_TAG;
392
393 int nIndex = 0;
394 if (opts->index_format) {
395 char *s;
396 for (s = opts->index_format; *s; s++) {
397 if (*s == 'i') nIndex++;
398 }
399 }
400 if (nIndex>2) {
401 fprintf(samtools_stderr,"Invalid index format: more than 2 indexes\n");
402 bam2fq_usage(samtools_stderr, argv[0]);
403 free_opts(opts);
404 return false;
405 }
406
407 if (opts->index_file[1] && !opts->index_file[0]) {
408 fprintf(samtools_stderr, "Index one specified, but index two not given\n");
409 bam2fq_usage(samtools_stderr, argv[0]);
410 free_opts(opts);
411 return false;
412 }
413
414 if (opts->illumina_tag && !nIndex) {
415 fprintf(samtools_stderr, "You must specify an index format (--index-format) with the Illumina Casava (-i) option\n");
416 bam2fq_usage(samtools_stderr, argv[0]);
417 free_opts(opts);
418 return false;
419 }
420
421 if (nIndex==0 && opts->index_file[0]) {
422 fprintf(samtools_stderr, "index_format not specified, but index file given\n");
423 bam2fq_usage(samtools_stderr, argv[0]);
424 free_opts(opts);
425 return false;
426 }
427
428 if (opts->def_qual < 0 || 93 < opts->def_qual) {
429 fprintf(samtools_stderr, "Invalid -v default quality %i, allowed range 0 to 93\n", opts->def_qual);
430 bam2fq_usage(samtools_stderr, argv[0]);
431 free_opts(opts);
432 return false;
433 }
434
435 const char* type_str = argv[0];
436 if (strcasecmp("fastq", type_str) == 0 ||
437 strcasecmp("bam2fq", type_str) == 0) {
438 opts->filetype = FASTQ;
439 } else if (strcasecmp("fasta", type_str) == 0) {
440 opts->filetype = FASTA;
441 } else {
442 print_error("bam2fq", "Unrecognised type call \"%s\", this should be impossible... but you managed it!", type_str);
443 bam2fq_usage(samtools_stderr, argv[0]);
444 free_opts(opts);
445 return false;
446 }
447
448 if (argc == optind && isatty(STDIN_FILENO)) {
449 bam2fq_usage(samtools_stdout, argv[0]);
450 free_opts(opts);
451 return true;
452 }
453
454 if (argc - optind > 1) {
455 fprintf(samtools_stderr, "Too many arguments.\n");
456 bam2fq_usage(samtools_stderr, argv[0]);
457 free_opts(opts);
458 return false;
459 }
460 opts->fn_input = argc > optind ? argv[optind] : "-";
461 *opts_out = opts;
462 return true;
463 }
464
465 void set_sam_opts(samFile *fp, bam2fq_state_t *state,
466 const bam2fq_opts_t *opts) {
467 if (state->has12)
468 hts_set_opt(fp, FASTQ_OPT_RNUM, 1);
469
470 if (state->illumina_tag)
471 hts_set_opt(fp, FASTQ_OPT_CASAVA, 1);
472
473 hts_set_opt(fp, FASTQ_OPT_BARCODE, opts->barcode_tag);
474
475 if (opts->extra_tags && (*opts->extra_tags == '*' || *opts->extra_tags == '\0'))
476 hts_set_opt(fp, FASTQ_OPT_AUX, NULL);
477 else {
478 kstring_t tag_list = {0,0};
479 if (state->copy_tags)
480 kputs("RG,BC,QT", &tag_list);
481 if (opts->extra_tags) {
482 if (tag_list.l)
483 kputc(',', &tag_list);
484 kputs(opts->extra_tags, &tag_list);
485 }
486 if (tag_list.l)
487 hts_set_opt(fp, FASTQ_OPT_AUX, tag_list.s);
488 ks_free(&tag_list);
489 }
490 }
491
492 // Open a file as normal or gzipped based on filename.
493 // Note we always use bgzf and don't bother to attempt non-blocked
494 // gzip streams. This is a departure from the old fastq code.
495 static samFile *sam_open_z(char *fn, char *mode, bam2fq_state_t *state) {
496 char modez[6];
497 strcpy(modez, mode);
498
499 size_t l = strlen(fn);
500 if ((l > 3 && strcmp(fn+l-3, ".gz") == 0) ||
501 (l > 4 && strcmp(fn+l-4, ".bgz") == 0) ||
502 (l > 5 && strcmp(fn+l-5, ".bgzf") == 0)) {
503 char m[3] = {'z', state->compression_level+'0', '\0'};
504 strcat(modez, m);
505 }
506
507 samFile *fp = sam_open(fn, modez);
508 if (!fp)
509 return NULL;
510
511 if (state->p.pool)
512 hts_set_thread_pool(fp, &state->p);
513
514 return fp;
515 }
516
517 static bool init_state(const bam2fq_opts_t* opts, bam2fq_state_t** state_out)
518 {
519 char *mode = opts->filetype == FASTA ? "wF" : "wf";
520
521 bam2fq_state_t* state = calloc(1, sizeof(bam2fq_state_t));
522 if (!state)
523 return false;
524 state->flag_on = opts->flag_on;
525 state->flag_off = opts->flag_off;
526 state->flag_alloff = opts->flag_alloff;
527 state->flag_anyon = opts->flag_anyon;
528 state->has12 = opts->has12;
529 state->use_oq = opts->use_oq;
530 state->illumina_tag = opts->illumina_tag;
531 state->copy_tags = opts->copy_tags;
532 state->filetype = opts->filetype;
533 state->def_qual = opts->def_qual;
534 state->index_sequence = NULL;
535 state->hstdout = NULL;
536 state->compression_level = opts->compression_level;
537
538 state->fp = sam_open_format(opts->fn_input, "r", &opts->ga.in);
539 if (state->fp == NULL) {
540 print_error_errno("bam2fq","Cannot read file \"%s\"", opts->fn_input);
541 free(state);
542 return false;
543 }
544
545 state->p.pool = NULL;
546 if (opts->ga.nthreads > 0) {
547 if (!(state->p.pool = hts_tpool_init(opts->ga.nthreads))) {
548 fprintf(samtools_stderr, "Failed to create thread pool\n");
549 free(state);
550 return false;
551 }
552 state->p.qsize = opts->ga.nthreads*2;
553 hts_set_thread_pool(state->fp, &state->p);
554 }
555
556 uint32_t rf = SAM_QNAME | SAM_FLAG | SAM_SEQ | SAM_QUAL;
557 if (opts->use_oq || opts->extra_tags || opts->index_file[0])
558 rf |= SAM_AUX;
559 if (opts->filter_tag) {
560 if (memcmp(opts->filter_tag, "NM", 2) == 0 ||
561 memcmp(opts->filter_tag, "MD", 2) == 0)
562 rf |= SAM_AUX | SAM_SEQ;
563 else if (memcmp(opts->filter_tag, "RG", 2) == 0)
564 rf |= SAM_RGAUX;
565 else
566 rf |= SAM_AUX;
567 }
568 if (hts_set_opt(state->fp, CRAM_OPT_REQUIRED_FIELDS, rf)) {
569 fprintf(samtools_stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n");
570 free(state);
571 return false;
572 }
573 if (hts_set_opt(state->fp, CRAM_OPT_DECODE_MD, 0)) {
574 fprintf(samtools_stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
575 free(state);
576 return false;
577 }
578 if (opts->fnse) {
579 if (!(state->fpse = sam_open_z(opts->fnse, mode, state))) {
580 print_error_errno("bam2fq", "Cannot open singleton file \"%s\"", opts->fnse);
581 free(state);
582 return false;
583 }
584 set_sam_opts(state->fpse, state, opts);
585 }
586
587 if (opts->ga.reference) {
588 if (hts_set_fai_filename(state->fp, opts->ga.reference) != 0) {
589 print_error_errno("bam2fq", "cannot load reference \"%s\"", opts->ga.reference);
590 free(state);
591 return false;
592 }
593 }
594
595 // single, read1, read2
596 int i, j;
597 for (i = 0; i < 3; ++i) {
598 if (opts->fnr[i]) {
599 for (j = 0; j < i; j++)
600 if (opts->fnr[j] && strcmp(opts->fnr[j], opts->fnr[i]) == 0)
601 break;
602 if (j == i) {
603 if (!(state->fpr[i] = sam_open_z(opts->fnr[i], mode, state))) {
604 print_error_errno("bam2fq", "Cannot open r%d file \"%s\"",
605 i, opts->fnr[i]);
606 free(state);
607 return false;
608 }
609 set_sam_opts(state->fpr[i], state, opts);
610 } else {
611 state->fpr[i] = state->fpr[j];
612 }
613 } else {
614 if (!state->hstdout) {
615 if (!(state->hstdout = sam_open_z("-", mode, state))) {
616 print_error_errno("bam2fq", "Cannot open STDOUT");
617 free(state);
618 return false;
619 }
620 set_sam_opts(state->hstdout, state, opts);
621 autoflush_if_stdout(state->hstdout, "-");
622 }
623 state->fpr[i] = state->hstdout;
624 }
625 }
626
627 // index 1, index 2
628 for (i = 0; i < 2; i++) {
629 state->fpi[i] = NULL;
630 if (opts->index_file[i]) {
631 for (j = 0; j < 3; j++)
632 if (opts->fnr[j] && strcmp(opts->fnr[j], opts->index_file[i]) == 0)
633 break;
634 for (j -= 3; j >= 0 && j < i; j++)
635 if (opts->index_file[j] && strcmp(opts->index_file[j], opts->index_file[i]) == 0)
636 break;
637 if (i == j) {
638 if (!(state->fpi[i] = sam_open_z(opts->index_file[i], mode,
639 state))) {
640 print_error_errno("bam2fq", "Cannot open i%d file \"%s\"",
641 i+1, opts->index_file[i]);
642 free(state);
643 return false;
644 }
645 set_sam_opts(state->fpi[i], state, opts);
646 } else if (j < 0) {
647 state->fpi[i] = state->fpr[j+3];
648 } else {
649 state->fpi[i] = state->fpi[j];
650 }
651 }
652 }
653
654 state->h = sam_hdr_read(state->fp);
655 if (state->h == NULL) {
656 fprintf(samtools_stderr, "Failed to read header for \"%s\"\n", opts->fn_input);
657 free(state);
658 return false;
659 }
660
661 *state_out = state;
662 return true;
663 }
664
665 static bool destroy_state(const bam2fq_opts_t *opts, bam2fq_state_t *state, int* status)
666 {
667 bool valid = true;
668 sam_hdr_destroy(state->h);
669 check_sam_close("bam2fq", state->fp, opts->fn_input, "file", status);
670 if (state->fpse && sam_close(state->fpse) < 0) {
671 print_error_errno("bam2fq", "Error closing singleton file \"%s\"", opts->fnse);
672 valid = false;
673 }
674
675 int i, j;
676 for (i = 0; i < 3; ++i) {
677 if (state->fpr[i] != state->hstdout) {
678 for (j = 0; j < i; j++)
679 if (state->fpr[i] == state->fpr[j])
680 break;
681 if (j == i && sam_close(state->fpr[i])) {
682 print_error_errno("bam2fq", "Error closing r%d file \"%s\"", i, opts->fnr[i]);
683 valid = false;
684 }
685 }
686 }
687 if (state->hstdout) {
688 release_autoflush(state->hstdout);
689 if (sam_close(state->hstdout) < 0) {
690 print_error_errno("bam2fq", "Error closing STDOUT");
691 valid = false;
692 }
693 }
694 for (i = 0; i < 2; i++) {
695 for (j = 0; j < 3; j++)
696 if (state->fpi[i] == state->fpr[j])
697 break;
698 for (j -= 3; j >= 0 && j < i; j++)
699 if (state->fpi[i] == state->fpi[j])
700 break;
701 if (j == i && state->fpi[i] && sam_close(state->fpi[i]) < 0) {
702 print_error_errno("bam2fq", "Error closing i%d file \"%s\"", i+1, opts->index_file[i]);
703 valid = false;
704 }
705 }
706 free(state->index_sequence);
707 if (state->p.pool)
708 hts_tpool_destroy(state->p.pool);
709 free(state);
710 return valid;
711 }
712
713 static inline bool filter_it_out(const bam1_t *b, const bam2fq_state_t *state,
714 bam2fq_opts_t *opts)
715 {
716 if (opts->filter_tag) {
717 uint8_t *s = bam_aux_get(b, opts->filter_tag);
718 if (!s)
719 return true;
720
721 if (opts->filter_tag_vals) {
722 char t[32], *val = t;
723 switch (*s) {
724 case 'i': case 'I':
725 case 's': case 'S':
726 case 'c': case 'C':
727 if (snprintf(t, 32, "%"PRId64, bam_aux2i(s)) <= 0)
728 return true;
729 break;
730
731 case 'f':
732 // Comparing floats is hard.
733 // Eg (double)0.1 - (double)0.1f is -1.5e-9.
734 // Given BAM binary encoding is float however, just keep it.
735 // This means rounding errors will (hopefully) always be the
736 // same and basic equality still works.
737 if (snprintf(t, 32, "%f", (float)bam_aux2f(s)) <= 0)
738 return true;
739 break;
740
741 case 'A':
742 t[0] = s[1];
743 t[1] = 0;
744 break;
745
746 case 'Z': case 'H':
747 val = (char *)s+1;
748 break;
749
750 default:
751 // Anything unsupported fails the filter match too.
752 return true;
753 }
754
755 khint_t k = kh_get(str, opts->filter_tag_vals, val);
756 if (k == kh_end(opts->filter_tag_vals))
757 return 1; // tag value not found
758 }
759 }
760
761 return ((b->core.flag&(state->flag_on)) != state->flag_on // or reads indicated by filter flags
762 || (b->core.flag&(state->flag_off)) != 0
763 || (((b->core.flag&(state->flag_anyon)) == 0) && (state->flag_anyon != 0))
764 || (b->core.flag&(state->flag_alloff) && (b->core.flag&(state->flag_alloff)) == state->flag_alloff));
765
766 }
767
768 int write_index_rec(samFile *fp, bam1_t *b, bam2fq_state_t *state,
769 bam2fq_opts_t* opts, char *seq, int seq_len,
770 char *qual, int qual_len) {
771 if (!fp || !b || !seq_len)
772 return 0;
773
774 int ret = -1;
775 bam1_t *b2 = bam_init1(); // FIXME: reuse
776 if (!b2)
777 return -1;
778
779 size_t aux_len = b->data + b->l_data - bam_get_aux(b);
780 if (bam_set1(b2, b->core.l_qname, bam_get_qname(b),
781 (b->core.flag | BAM_FUNMAP) & ~BAM_FREVERSE,
782 -1, -1, 0, // refid, pos, mapq
783 0, NULL, // cigar
784 -1, -1, 0, // rnext, pnext, tlen
785 seq_len, seq, qual,
786 aux_len) < 0)
787 goto err;
788
789 uint8_t *q = bam_get_qual(b2);
790 if (qual) {
791 int i;
792 for (i = 0; i < seq_len; i++)
793 q[i] -= '!';
794 } else {
795 memset(q, opts->def_qual, seq_len);
796 }
797
798 memcpy(bam_get_aux(b2), bam_get_aux(b), aux_len);
799 b2->l_data += aux_len;
800 if (sam_write1(fp, state->h, b2) < 0)
801 goto err;
802
803 ret = 0;
804 err:
805 if (b2)
806 bam_destroy1(b2);
807 return ret;
808 }
809
810 int output_index(bam1_t *b1, bam1_t *b2, bam2fq_state_t *state,
811 bam2fq_opts_t* opts) {
812 bam1_t *b = b1 ? b1 : b2;
813
814 char *ifmt = opts->index_format;
815 if (!ifmt)
816 ifmt = "i*i*";
817
818 // Get seq / qual elements
819 char *bc = NULL, *qt = NULL;
820 if (b1)
821 bc = (char *)bam_aux_get(b1, opts->barcode_tag);
822 if (b2 && !bc)
823 bc = (char *)bam_aux_get(b2, opts->barcode_tag);
824 if (!bc)
825 return 0;
826 else
827 bc++; // skip Z
828
829 if (b1)
830 qt = (char *)bam_aux_get(b1, opts->quality_tag);
831 if (b2 && !qt)
832 qt = (char *)bam_aux_get(b2, opts->quality_tag);
833 if (qt && strlen(bc) != strlen(qt)-1)
834 qt = NULL;
835 else if (qt)
836 qt++;
837
838 int inum = 0;
839 while (inum < 2) {
840 char fc = *ifmt++;
841 if (!fc)
842 break; // ran out of index-format
843
844 long len, rem = 0;
845 if (isdigit(*ifmt)) {
846 rem = len = strtol(ifmt, &ifmt, 10);
847 } else {
848 ifmt++;
849 len = 0;
850 }
851
852 char *bc_end = bc, *qt_end = qt;
853 if (qt) {
854 while (len ? *bc_end && rem-- : isalpha(*bc_end))
855 bc_end++, qt_end++;
856 } else {
857 while (len ? *bc_end && rem-- : isalpha(*bc_end))
858 bc_end++;
859 }
860
861 switch (fc) {
862 case 'n':
863 // skip
864 bc = bc_end + (len==0);
865 if (qt)
866 qt = qt_end + (len==0);
867 break;
868
869 case 'i':
870 if (write_index_rec(state->fpi[inum], b, state, opts,
871 bc, bc_end-bc, qt, qt_end-qt) < 0)
872 return -1;
873 bc = bc_end + (len==0);
874 if (qt)
875 qt = qt_end + (len==0);
876 inum++;
877 break;
878
879 default:
880 fprintf(samtools_stderr, "Unknown index-format code\n");
881 return -1;
882 }
883 }
884
885 return 0;
886 }
887
888 static int flush_rec(bam2fq_state_t *state, bam2fq_opts_t* opts,
889 bam1_t *b[4], int score[3], int best[3],
890 int64_t *n_singletons) {
891 // Paired data, with 1 or 2 ends present.
892 if (score[1] > 0 && score[2] > 0) {
893 // If CASAVA tag is required and barcode is only on R1,
894 // copy it to R2
895 if (state->illumina_tag) {
896 char *tag;
897 if ((tag = (char *)bam_aux_get(b[best[1]],
898 opts->barcode_tag)))
899 if (bam_aux_update_str(b[best[2]],
900 opts->barcode_tag,
901 strlen(tag), tag+1) < 0)
902 goto err;
903 if ((tag = (char *)bam_aux_get(b[best[1]],
904 opts->quality_tag)))
905 if (bam_aux_update_str(b[best[2]],
906 opts->quality_tag,
907 strlen(tag), tag+1) < 0)
908 goto err;
909
910 }
911 if (sam_write1(state->fpr[1], state->h, b[best[1]]) < 0)
912 goto err;
913 if (sam_write1(state->fpr[2], state->h, b[best[2]]) < 0)
914 goto err;
915
916 if (output_index(b[best[1]], b[best[2]], state, opts) < 0)
917 goto err;
918 } else if (score[1] > 0 || score[2] > 0) {
919 if (state->fpse) {
920 // print whichever one exists to fpse
921 if (score[1] > 0) {
922 if (sam_write1(state->fpse, state->h, b[best[1]]) < 0)
923 goto err;
924 } else {
925 if (sam_write1(state->fpse, state->h, b[best[2]]) < 0)
926 goto err;
927 }
928 ++(*n_singletons);
929 } else {
930 if (score[1] > 0) {
931 if (sam_write1(state->fpr[1], state->h, b[best[1]]) < 0)
932 goto err;
933 } else {
934 if (sam_write1(state->fpr[2], state->h, b[best[2]]) < 0)
935 goto err;
936 }
937 }
938
939 if (output_index(score[1] > 0 ? b[best[1]] : NULL,
940 score[2] > 0 ? b[best[2]] : NULL,
941 state, opts) < 0)
942 goto err;
943 }
944
945 if (score[0]) { // single ended data (neither READ1 nor READ2)
946 if (sam_write1(state->fpr[0], state->h, b[best[0]]) < 0)
947 goto err;
948
949 if (output_index(b[best[0]], NULL, state, opts) < 0)
950 goto err;
951 }
952
953 return 0;
954
955 err:
956 return -1;
957 }
958
959 static bool bam2fq_mainloop(bam2fq_state_t *state, bam2fq_opts_t* opts)
960 {
961 int n;
962 char *current_qname = NULL;
963 int64_t n_reads = 0, n_singletons = 0; // Statistics
964 int score[3];
965 int at_eof;
966 bool valid = false;
967 int best[3] = {-1, -1, -1}; // map R0, R1, single to b[] indices;
968 // indexed by [readpart]
969 bam1_t *b[4]; // 3 readparts, plus current record
970
971 for (n = 0; n < 4; n++) {
972 if (!(b[n] = bam_init1())) {
973 perror("[bam2fq_mainloop] Malloc error for bam record buffer.");
974 return false;
975 }
976 }
977
978 n = 0;
979 while (true) {
980 int res = sam_read1(state->fp, state->h, b[n]);
981 if (res < -1) {
982 print_error("bam2fq", "Failed to read bam record");
983 goto err;
984 }
985 at_eof = res < 0;
986
987 if (!at_eof && filter_it_out(b[n], state, opts))
988 continue;
989 if (!at_eof) {
990 ++n_reads;
991
992 // Handle -O option: use OQ for qual
993 uint8_t *oq;
994 if (state->use_oq && (oq = bam_aux_get(b[n],"OQ")) && *oq == 'Z') {
995 int i, l = strlen((char *)++oq);
996 uint8_t *qual = bam_get_qual(b[n]);
997 for (i = 0; i < l && i < b[n]->core.l_qseq; i++)
998 qual[i] = oq[i] - '!';
999 }
1000 }
1001
1002 if (at_eof
1003 || !current_qname
1004 || (strcmp(current_qname, bam_get_qname(b[n])) != 0)) {
1005 // New name, so flush best examples of previous name.
1006 if (current_qname)
1007 if (flush_rec(state, opts, b, score, best, &n_singletons) < 0)
1008 goto err;
1009
1010 current_qname = bam_get_qname(b[n]);
1011 score[0] = score[1] = score[2] = 0;
1012
1013 if (at_eof) { break; }
1014 }
1015
1016 // Prefer a copy of the read that has base qualities
1017 int b_score = bam_get_qual(b[n])[0] != 0xff? 2 : 1;
1018 readpart rp = which_readpart(b[n]);
1019 if (score[rp] < b_score) {
1020 score[rp] = b_score;
1021 // Record b[n] slot for best copy of readpair and find a new
1022 // slot for next bam read
1023 best[rp] = n;
1024 int used_slot[4] = {0}, i;
1025 for (i = 0; i < 3; i++)
1026 if (best[i] >= 0)
1027 used_slot[best[i]] = 1;
1028 for (i = 0; i < 4 && used_slot[i]; i++)
1029 ;
1030 n = i;
1031 }
1032 }
1033
1034 valid = true;
1035 err:
1036 if (!valid)
1037 print_error_errno("bam2fq", "Error writing to FASTx files.");
1038
1039 for (n = 0; n < 4; n++)
1040 bam_destroy1(b[n]);
1041
1042 fprintf(samtools_stderr, "[M::%s] discarded %" PRId64 " singletons\n",
1043 __func__, n_singletons);
1044 fprintf(samtools_stderr, "[M::%s] processed %" PRId64 " reads\n",
1045 __func__, n_reads);
1046
1047 return valid;
1048 }
1049
1050 int main_bam2fq(int argc, char *argv[])
1051 {
1052 int status = EXIT_FAILURE;
1053 bam2fq_opts_t* opts = NULL;
1054 bam2fq_state_t* state = NULL;
1055
1056 bool valid = parse_opts(argc, argv, &opts);
1057 if (!valid || opts == NULL) return valid ? EXIT_SUCCESS : EXIT_FAILURE;
1058
1059 if (!init_state(opts, &state)) goto err;
1060
1061 if (!bam2fq_mainloop(state,opts)) goto err;
1062
1063 if (!destroy_state(opts, state, &status)) goto err;
1064
1065 status = EXIT_SUCCESS;
1066 err:
1067 sam_global_args_free(&opts->ga);
1068 free_opts(opts);
1069
1070 return status;
1071 }