Debian Codegraph @

samtools/bam_import.c

raw symbols SCIP
1 /* bam_import -- Import of FASTQ files.
2 *
3 * samtools import -1 a_1.fq -2 a_2.fq --i1 a_i1.fq --i2 a_i2.fq
4 * samtools import a_1.fq a_2.fq
5 * samtools import a_interleaved.fq
6 *
7 * Copyright (C) 2020-2021, 2023-2024 Genome Research Ltd.
8 *
9 * Author: James Bonfield <[email protected]>
10 */
11
12 /*
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notices and this permission notice shall be included in
21 all copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29 DEALINGS IN THE SOFTWARE.
30 */
31
32 // TODO: Store other non-aux comments; in new sam tag?
33
34 #include <config.h>
35 #include <ctype.h>
36
37 #include "htslib/sam.h"
38 #include "htslib/thread_pool.h"
39
40 #include "samtools.h"
41 #include "sam_opts.h"
42
43 static int usage(FILE *fp, int exit_status) {
44 fprintf(fp, "Usage: samtools import [options] [file.fastq ...]\n");
45 fprintf(fp, "\n");
46 fprintf(fp, "Options:\n");
47 fprintf(fp, " -s FILE Read paired-ended data from single FILE\n");
48 fprintf(fp, " -0 FILE Read single-ended data from FILE\n");
49 fprintf(fp, " -1 FILE Read-1 from FILE\n");
50 fprintf(fp, " -2 FILE Read-2 from FILE\n");
51 fprintf(fp, " --i1 FILE Index-1 from FILE\n");
52 fprintf(fp, " --i2 FILE Index-2 from FILE\n");
53 fprintf(fp, " -i Parse CASAVA identifier\n");
54 fprintf(fp, " --barcode-tag TAG\n");
55 fprintf(fp, " Tag to use with barcode sequences [BC]\n");
56 fprintf(fp, " --quality-tag TAG\n");
57 fprintf(fp, " Tag to use with barcode qualities [QT]\n");
58 fprintf(fp, " -N, --name2 Use 2nd field as read name (SRA format)\n");
59 fprintf(fp, " -r STRING Build up a complete @RG line\n");
60 fprintf(fp, " -R STRING Add a simple RG line of \"@RG\\tID:STRING\"\n");
61 fprintf(fp, " -T TAGLIST Parse tags in SAM format; list of '*' for all\n");
62 fprintf(fp, " -o FILE Output to FILE instead of stdout\n");
63 fprintf(fp, " -u Uncompressed output\n");
64 fprintf(fp, " --order TAG Store Nth record count in TAG\n");
65 fprintf(fp, "\n");
66 fprintf(fp, " --no-PG Do not add a PG line\n");
67 sam_global_opt_help(fp, "-.O.-@--");
68
69 fprintf(fp, "\nA single fastq file will be interpreted as -s, -0 or -1 depending on\n");
70 fprintf(fp, "file contents, and a pair of fastq files as \"-1 FILE1 -2 FILE2\".\n");
71
72 return exit_status;
73 }
74
75 // Order matters here as we want to read index elements before main
76 // sequences so on reading the seqs we can emit a fully annotated record.
77 enum fileno {
78 FQ_I1, FQ_I2, // index seqs for R1 and R2
79 FQ_R0, // single file and unpaired data (singled-ended tech).
80 FQ_R1, FQ_R2, // separate read1 and read2 files
81 FQ_SINGLE, // single file, but with read1 and/or read2 present.
82 FQ_END
83 };
84
85 typedef struct {
86 sam_global_args ga;
87 int no_pg;
88 char *fn[FQ_END], *fn_out;
89 int idx_both; // add index to READ2 too, not just READ1
90 int casava;
91 char *barcode_seq;
92 char *barcode_qual;
93 char *aux;
94 char *rg;
95 char *rg_line;
96 char *order;
97 int order_str;
98 int compress_level;
99 htsThreadPool p;
100 int name2;
101 } opts_t;
102
103 // Append a sequence and quality string from a BAM record to a BC:Z and
104 // QT:Z style aux tag string.
105 static int append_index(kstring_t *s, kstring_t *q, bam1_t *b) {
106 char *sp, *qp;
107 if (ks_resize(s, s->l + b->core.l_qseq+1 +1) < 0)
108 return -1;
109 if (ks_resize(q, q->l + b->core.l_qseq+1 +1) < 0)
110 return -1;
111
112 sp = s->s + s->l - (s->l > 0);
113 qp = q->s + q->l - (q->l > 0);
114
115 if (s->l)
116 *sp++ = '-';
117
118 if (q->l)
119 *qp++ = ' ';
120
121 int i;
122 uint8_t *seq = bam_get_seq(b);
123 uint8_t *qual = bam_get_qual(b);
124 for (i = 0; i < b->core.l_qseq; i++) {
125 *sp++ = seq_nt16_str[bam_seqi(seq, i)];
126 *qp++ = qual[i] + '!';
127 }
128 *sp++ = 0;
129 *qp++ = 0;
130
131 s->l = sp - s->s;
132 q->l = qp - q->s;
133
134 return 0;
135 }
136
137 static int import_fastq(int argc, char **argv, opts_t *opts) {
138 int i, n, ret = 0;
139 samFile *fp_in[FQ_END] = {NULL};
140 bam1_t *b = bam_init1();
141 int ids[FQ_END];
142 samFile *fp_out = NULL;
143 sam_hdr_t *hdr_out = NULL;
144 kstring_t index_str = {0,0};
145 kstring_t read_str = {0,0};
146 char *rg = opts->rg;
147 kstring_t rg_line = {0,0};
148 uint64_t read_num = 0;
149 kstring_t idx_seq = {0};
150 kstring_t idx_qual = {0};
151
152 // Any additional arguments are assumed to be r1 r2, as a
153 // short cut. We support reading index tags out of those too (eg
154 // Illumina CASAVA format), but if we do that we lack the barcode
155 // quality string.
156 //
157 // We also consider a read name ending in /1 or /2 to be a single
158 // file containing interleaved fastq records for both ends.
159 // These will be labeled as fn[FQ_R1] but adjusted during reading.
160 if (argc == 1)
161 opts->fn[FQ_SINGLE] = argv[0];
162 else
163 for (i = 0; i < 2; i++)
164 if (argc > i)
165 opts->fn[FQ_R1+i] = argv[i];
166
167 // Open all files
168 for (i = n = 0; i < FQ_END; i++) {
169 if (!opts->fn[i])
170 continue;
171 fp_in[i] = sam_open_format(opts->fn[i], "r", &opts->ga.in);
172 if (!fp_in[i]) {
173 perror(opts->fn[i]);
174 ret = -1;
175 goto err;
176 }
177 if (opts->p.pool)
178 hts_set_thread_pool(fp_in[i], &opts->p);
179 ids[n++] = i;
180
181 if (opts->name2)
182 hts_set_opt(fp_in[i], FASTQ_OPT_NAME2, 1);
183 if (opts->casava)
184 hts_set_opt(fp_in[i], FASTQ_OPT_CASAVA, 1);
185 if (opts->barcode_seq) // for auto-CASAVA parsing
186 hts_set_opt(fp_in[i], FASTQ_OPT_BARCODE, opts->barcode_seq);
187 if (opts->aux)
188 hts_set_opt(fp_in[i], FASTQ_OPT_AUX,
189 *opts->aux == '*' || *opts->aux == '\0'
190 ? NULL : opts->aux);
191
192 switch (i) {
193 case FQ_I1:
194 kputs("--i1 I1.fastq ", &read_str);
195 kputs("i*", &index_str);
196 break;
197 case FQ_I2:
198 kputs("--i2 I2.fastq ", &read_str);
199 kputs("i*", &index_str);
200 break;
201
202 case FQ_R0:
203 kputs("-0 unpaired.fastq ", &read_str);
204 break;
205
206 case FQ_R1:
207 kputs("-1 R1.fastq ", &read_str);
208 break;
209
210 case FQ_R2:
211 kputs("-2 R2.fastq ", &read_str);
212 break;
213
214 case FQ_SINGLE:
215 kputs("-N -o paired.fastq ", &read_str);
216 break;
217
218 default:
219 ks_clear(&read_str); // not reversible
220 kputs("", &read_str);
221 }
222 }
223 if (n == 0) {
224 bam_destroy1(b);
225 return usage(stdout, EXIT_SUCCESS);
226 }
227
228 char out_mode[10] = {'w', 0, 0};
229 if (opts->compress_level != -1)
230 out_mode[1] = '0' + opts->compress_level;
231 sam_open_mode(out_mode+strlen(out_mode), opts->fn_out, NULL);
232 fp_out = sam_open_format(opts->fn_out, out_mode, &opts->ga.out);
233 if (!fp_out) {
234 perror(opts->fn_out);
235 goto err;
236 }
237 autoflush_if_stdout(fp_out, opts->fn_out);
238 if (opts->p.pool)
239 hts_set_thread_pool(fp_out, &opts->p);
240
241 // Create header
242 if (ks_len(&read_str)) {
243 char CO[2100];
244 if (ks_len(&index_str))
245 snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s "
246 "--index-format=\"%s\"\n",
247 ks_str(&read_str), ks_str(&index_str));
248 else
249 snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s\n",
250 ks_str(&read_str));
251
252 hdr_out = sam_hdr_parse(strlen(CO), CO);
253 } else {
254 hdr_out = sam_hdr_init();
255 }
256
257 // Add a version line with the sort order to the output header
258 if (sam_hdr_add_line(hdr_out, "HD", "VN", SAM_FORMAT_VERSION, "SO", "unsorted", "GO", "query", NULL) < 0) {
259 fprintf(stderr, "Could not set SO and GO in the header.\n");
260 goto err;
261 }
262
263 if (!opts->no_pg) {
264 char *arg_list;
265 if (!(arg_list = stringify_argv(argc+1+optind, argv-1-optind))) {
266 print_error("view", "failed to create arg_list");
267 goto err;
268 }
269 if (sam_hdr_add_pg(hdr_out, "samtools",
270 "VN", samtools_version(),
271 arg_list ? "CL" : NULL,
272 arg_list ? arg_list : NULL,
273 NULL)) {
274 fprintf(stderr, "Failed to add PG line to the header");
275 free(arg_list);
276 goto err;
277 }
278
279 free(arg_list);
280 }
281
282 // Read group
283 if (opts->rg_line) {
284 if (*opts->rg_line != '@')
285 ksprintf(&rg_line, "@RG\t%s", opts->rg_line);
286 else
287 kputs(opts->rg_line, &rg_line);
288 } else if (opts->rg) {
289 ksprintf(&rg_line, "@RG\tID:%s", opts->rg);
290 }
291
292 if (ks_len(&rg_line)) {
293 if (sam_hdr_add_lines(hdr_out, ks_str(&rg_line), 0) < 0)
294 goto err;
295 rg = strstr(ks_str(&rg_line), "\tID:");
296 if (!rg) {
297 fprintf(stderr, "\"-r RG-LINE\" option contained no ID field\n");
298 goto err;
299 }
300 rg += 4;
301
302 i = 0;
303 while (rg[i] != '\t' && rg[i] != '\0')
304 i++;
305 rg[i] = 0;
306 }
307
308 if ((ret = sam_hdr_write(fp_out, hdr_out)) < 0)
309 goto err;
310
311
312 // Interleave / combine from n files (ids[0..n-1]).
313 int res = 0;
314 int eof = 0;
315 do {
316 idx_seq.l = idx_qual.l = 0;
317 for (i = 0; i < n; i++) {
318 if ((res = sam_read1(fp_in[ids[i]], NULL, b)) < 0) {
319 if (res == -1) {
320 eof++;
321 continue;
322 } else
323 break;
324 }
325
326 // index
327 if (ids[i] == FQ_I1 || ids[i] == FQ_I2) {
328 if (append_index(&idx_seq, &idx_qual, b) < 0) {
329 res = -1;
330 break;
331 }
332 continue;
333 }
334
335 // full read
336 if (idx_seq.l) {
337 if (opts->idx_both || ids[i] == FQ_SINGLE ||
338 ids[i] == FQ_R0 || ids[i] == FQ_R1) {
339 if (bam_aux_append(b, opts->barcode_seq, 'Z', idx_seq.l,
340 (uint8_t *)idx_seq.s) ||
341 bam_aux_append(b, opts->barcode_qual, 'Z', idx_qual.l,
342 (uint8_t *)idx_qual.s)) {
343 res = -1;
344 break;
345 }
346 }
347 }
348
349 switch(ids[i]) {
350 case FQ_R0:
351 // unpaired; no flags to declare
352 break;
353 case FQ_SINGLE:
354 // paired (but don't know if R1 or R2) or unpaired.
355 // We rely on the /1 and /2 read suffix parsing in htslib
356 // to distinguish the two cases, or CASAVA tags if
357 // explicitly enabled.
358 break;
359 case FQ_R1:
360 if ((b->core.flag & (BAM_FREAD1 | BAM_FREAD2)) == 0)
361 b->core.flag |= BAM_FREAD1;
362 b->core.flag |= BAM_FPAIRED;
363 if (i+1 < n && ids[i+1] == FQ_R2)
364 b->core.flag |= BAM_FMUNMAP;
365 break;
366 case FQ_R2:
367 b->core.flag |= BAM_FPAIRED | BAM_FREAD2;
368 if (i > 0 && ids[i-1] == FQ_R1)
369 b->core.flag |= BAM_FMUNMAP;
370 break;
371 }
372
373 if (rg) {
374 if (bam_aux_append(b, "RG", 'Z', strlen(rg)+1,
375 (uint8_t *)rg) < 0) {
376 ret = -1;
377 goto err;
378 }
379 }
380
381 if (opts->order) {
382 if (opts->order_str) {
383 char buf[25];
384 snprintf(buf, sizeof(buf), "%0*"PRIu64,
385 opts->order_str, read_num++);
386 if (bam_aux_update_str(b, opts->order,
387 strlen(buf), buf) < 0) {
388 ret = -1;
389 goto err;
390 }
391 } else {
392 if (bam_aux_update_int(b, opts->order, read_num++) < 0) {
393 ret = -1;
394 goto err;
395 }
396 if (read_num == UINT_MAX)
397 fprintf(stderr, "Warning: --order tag has overflowed."
398 " Consider using TAG:LENGTH instead\n");
399 }
400 }
401
402 res = sam_write1(fp_out, hdr_out, b);
403 }
404 } while (res >= 0);
405
406 if (res != -1) {
407 print_error("import", "truncated file. Aborting");
408 ret = res;
409 goto err;
410 }
411
412 if (eof != n) {
413 print_error("import", "input files with differing number of records");
414 ret = -1;
415 goto err;
416 }
417
418 // Close and return
419 ret = 0;
420 err:
421 bam_destroy1(b);
422 sam_hdr_destroy(hdr_out);
423 ks_free(&rg_line);
424 ks_free(&index_str);
425 ks_free(&read_str);
426 if (fp_out) {
427 release_autoflush(fp_out);
428 if (sam_close(fp_out) < 0) {
429 perror(opts->fn_out);
430 ret |= -1;
431 }
432 }
433 for (i = 0; i < FQ_END; i++) {
434 if (fp_in[i] && sam_close(fp_in[i]) < 0) {
435 perror(opts->fn[i]);
436 ret |= -1;
437 }
438 }
439 ks_free(&idx_seq);
440 ks_free(&idx_qual);
441
442 return ret;
443 }
444
445 int main_import(int argc, char *argv[]) {
446 int c;
447 opts_t opts = {
448 .no_pg = 0,
449 .ga = SAM_GLOBAL_ARGS_INIT,
450 .fn = {NULL},
451 .fn_out = "-",
452 .casava = 0,
453 .barcode_seq = "BC",
454 .barcode_qual = "QT",
455 .aux = NULL,
456 .rg = NULL,
457 .rg_line = NULL,
458 .order = NULL,
459 .order_str = 0,
460 .compress_level = -1,
461 .name2 = 0,
462 };
463 kstring_t rg = {0};
464
465 static const struct option lopts[] = {
466 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, '-', '@'),
467 {"no-PG", no_argument, NULL, 9},
468 {"i1", required_argument, NULL, 1},
469 {"i2", required_argument, NULL, 2},
470 {"r1", required_argument, NULL, '1'},
471 {"r2", required_argument, NULL, '2'},
472 {"rg", required_argument, NULL, 'R'},
473 {"rg-line", required_argument, NULL, 'r'},
474 {"order", required_argument, NULL, 3},
475 {"barcode-tag", required_argument, NULL, 4},
476 {"quality-tag", required_argument, NULL, 5},
477 {"name2", no_argument, NULL, 'N'},
478 { NULL, 0, NULL, 0 }
479 };
480
481 while ((c = getopt_long(argc, argv, "1:2:s:0:bhiT:r:R:o:O:u@:N", lopts, NULL)) >= 0) {
482 switch (c) {
483 case 'b': opts.idx_both = 1; break;
484 case '0': opts.fn[FQ_R0] = optarg; break;
485 case '1': opts.fn[FQ_R1] = optarg; break;
486 case '2': opts.fn[FQ_R2] = optarg; break;
487 case 1: opts.fn[FQ_I1] = optarg; break;
488 case 2: opts.fn[FQ_I2] = optarg; break;
489 case 's': opts.fn[FQ_SINGLE] = optarg; break;
490 case 'o': opts.fn_out = optarg; break;
491 case 'i': opts.casava = 1; break;
492 case 4: opts.barcode_seq = optarg; break;
493 case 5: opts.barcode_qual = optarg; break;
494 case 'T': opts.aux = optarg; break;
495 case 'u': opts.compress_level = 0; break;
496 case 'R': opts.rg = optarg; break;
497 case 'r':
498 if (*optarg != '@' && ks_len(&rg) == 0)
499 kputs("@RG", &rg);
500 if (ks_len(&rg))
501 kputc_('\t', &rg);
502 kputs(optarg, &rg);
503 opts.rg_line = rg.s;
504 break;
505
506 case 'N': opts.name2 = 1; break;
507
508 case 9: opts.no_pg = 1; break;
509 case 3:
510 opts.order = optarg;
511 if (strlen(optarg) > 3 && optarg[2] == ':')
512 opts.order_str = atoi(optarg+3);
513 break;
514
515 case 'h': return usage(stdout, EXIT_SUCCESS);
516 case '?': return usage(stderr, EXIT_FAILURE);
517
518 default:
519 if (parse_sam_global_opt(c, optarg, lopts, &opts.ga) != 0)
520 return usage(stderr, EXIT_FAILURE);
521 break;
522 }
523 }
524
525 if (opts.ga.nthreads > 0) {
526 if (!(opts.p.pool = hts_tpool_init(opts.ga.nthreads))) {
527 fprintf(stderr, "Failed to create thread pool\n");
528 if (rg.s)
529 free(rg.s);
530 return -1;;
531 }
532 }
533
534 int ret = import_fastq(argc-optind, argv+optind, &opts) ? 1 : 0;
535
536 if (rg.s)
537 free(rg.s);
538
539 if (opts.p.pool)
540 hts_tpool_destroy(opts.p.pool);
541
542 return ret;
543 }