Debian Codegraph @

samtools/bam_import.c.pysam.c

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