Debian Codegraph @

samtools/reset.c

raw symbols SCIP
1 /* reset.c -- removes aligner updates and reference data from input sam /
2 bam / cram file and makes read data raw for new processing
3
4 Copyright (C) 2022 - 2024 Genome Research Ltd.
5
6 Author: Vasudeva Sarma <[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 */
27
28 #include <config.h>
29
30 #include "samtools.h"
31 #include "htslib/sam.h"
32 #include "sam_opts.h"
33 #include "htslib/thread_pool.h"
34 #include "htslib/khash.h"
35 #include "sam_utils.h"
36 #include <unistd.h>
37
38 #define TAGNUM(X) (((X)[0] << 8) | (X)[1]) //to create key for aux tags, like type key in htslib
39 #define LONG_OPT(X) (128 + (X)) //to handle long and short options with same char
40
41 #define RESET_KEEPDUPFLAG 1 //keep dup flag as such, as in initial implementation
42
43 typedef struct conf_data
44 {
45 int keepRGs; //RG line handling
46 int noPGentry; //PG line for reset op or not
47 int ctrlFlags; //control flags
48 auxhash_t aux_keep; //SET that holds the aux tags to be retained
49 auxhash_t aux_remove; //SET that holds the aux tags to be removed
50 char *pgid; //PG id onwards which to be removed
51 } conf_data;
52
53 /// usage - print the usage
54 /** @param fp pointer to the file / terminal to which usage to be dumped
55 returns nothing
56 */
57 static void usage(FILE *fp)
58 {
59 fprintf(fp, "Usage: samtools reset [options]\n\
60 -o FILE Output file\n\
61 -x, --remove-tag STR\n\
62 Aux tags to be removed\n\
63 --keep-tag STR\n\
64 Aux tags to be retained. Equivalent to -x ^STR\n\
65 --reject-PG ID\n\
66 Removes PG line with ID matching to input and succeeding PG lines\n\
67 --no-RG To have RG lines or not\n\
68 --no-PG To have PG entry or not for reset operation\n\
69 --dupflag\n\
70 Keeps the duplicate flag as it is\n");
71
72 sam_global_opt_help(fp, "--O--@--");
73 return;
74 }
75
76 /// update_aux_conf - update the user given aux tag configuration with defaults
77 /** @param config - pointer to conf_data
78 returns nothing
79 */
80 void update_aux_conf(conf_data *config)
81 {
82 const char rg[] = "RG";
83 const char *default_tags[] = {"AS", "CC", "CG", "CP", "H1", "H2", "HI", "H0", "IH",
84 "MC", "MD", "MQ", "NM", "SA", "TS"};
85 khint_t iter = 0;
86 int ret = 0, i = 0;
87
88 if (!config)
89 return;
90
91 if (!config->aux_keep && !config->aux_remove) {
92 //none of aux tag filter in use, create remove filter
93 config->aux_remove = kh_init(aux_exists);
94 }
95 if (config->aux_keep) {
96 //keep set in use, remove RG if present
97 if (!config->keepRGs) {
98 iter = kh_get(aux_exists, config->aux_keep, TAGNUM(rg));
99 if (iter != kh_end(config->aux_keep)) {
100 kh_del(aux_exists, config->aux_keep, iter);
101 }
102 }
103 }
104 if (config->aux_remove) {
105 if (!config->keepRGs) {
106 //remove set in use, add RG if not present
107 iter = kh_get(aux_exists, config->aux_remove, TAGNUM(rg));
108 if (iter == kh_end(config->aux_remove)) {
109 kh_put(aux_exists, config->aux_remove, TAGNUM(rg), &ret);
110 }
111 }
112 //add the default tags if not present in remove set
113 //note, keep has priority and this may not be honoured
114 for (i = 0; i < sizeof(default_tags) / sizeof(default_tags[0]); ++i) {
115 iter = kh_get(aux_exists, config->aux_remove, TAGNUM(default_tags[i]));
116 if (iter == kh_end(config->aux_remove)) {
117 kh_put(aux_exists, config->aux_remove, TAGNUM(default_tags[i]), &ret);
118 }
119 }
120 }
121 }
122
123 /// removeauxtags - remove aux tags in bam data which are not present in acceptable tag set
124 /** @param bamdata - pointer to the bamdata from which needs the filtering
125 * @param config - pointer to conf_data
126 returns nothing
127 */
128 void removeauxtags(bam1_t *bamdata, conf_data *config)
129 {
130 uint8_t *auxdata = NULL;
131 const char *tag = NULL;
132 khint_t iter = 0;
133
134 if (!bamdata || !config)
135 return;
136
137 for (auxdata = bam_aux_first(bamdata); auxdata; ) {
138 tag = bam_aux_tag(auxdata);
139 if (config->aux_keep) { //keep option or remove option with ^ in use
140 iter = kh_get(aux_exists, config->aux_keep, TAGNUM(tag));
141 if (iter == kh_end(config->aux_keep)) { //not present in keep, remove
142 auxdata = bam_aux_remove(bamdata, auxdata);
143 }
144 else { //present, keep
145 auxdata = bam_aux_next(bamdata, auxdata);
146 }
147 }
148 else if (config->aux_remove) { //remove option in use
149 iter = kh_get(aux_exists, config->aux_remove, TAGNUM(tag));
150 if (iter != kh_end(config->aux_remove)) { //present in remove, remove
151 auxdata = bam_aux_remove(bamdata, auxdata);
152 }
153 else { //not present, keep
154 auxdata = bam_aux_next(bamdata, auxdata);
155 }
156 }
157 //else impossible
158 }
159 }
160
161 /// getRGlines - add RG lines from input header to output header
162 /** @param in_samhdr - pointer to input sam header data
163 * @param out_samhdr - pointer to output sam header data
164 returns 1 on failure 0 on success
165 */
166 int getRGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr)
167 {
168 kstring_t line = KS_INITIALIZE;
169 int i = 0, ret = 0, count = 0;
170 const char rg[] = "RG";
171
172 if (!in_samhdr || !out_samhdr) {
173 fprintf(stderr, "Invalid parameters in getRGlines!\n");
174 return 1;
175 }
176
177 if (-1 == (count = sam_hdr_count_lines(in_samhdr, rg))) {
178 fprintf(stderr, "Failed to get RG count!\n");
179 return 1;
180 }
181
182 for (i = 0; i < count; ++i)
183 {
184 ks_clear(&line);
185 if (sam_hdr_find_line_pos(in_samhdr, rg, i, &line)) {
186 fprintf(stderr, "Failed to get RG data!\n");
187 ret = 1;
188 break;
189 }
190 if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) {
191 fprintf(stderr, "Failed to add RG data!\n");
192 ret = 1;
193 break;
194 }
195 }
196 ks_free(&line);
197
198 return ret;
199 }
200
201 /// getPGlines - add PG lines from input header to output header based on user option
202 /** @param in_samhdr - pointer to input sam header data
203 * @param out_samhdr - pointer to output sam header data
204 * @param config - pointer to internal configuration data
205 * @param argdump - string containing dump of command line invocation
206 returns 1 on failure 0 on success
207 */
208 int getPGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr, conf_data *config, const char *argdump)
209 {
210 kstring_t line = KS_INITIALIZE, id = KS_INITIALIZE;
211 int i = 0, ret = 0, count = 0;
212 const char pg[] = "PG";
213
214 if (!in_samhdr || !out_samhdr || !config) {
215 fprintf(stderr, "Invalid parameters in getPGlines!\n");
216 return 1;
217 }
218
219 if (-1 == (count = sam_hdr_count_lines(in_samhdr, pg))) {
220 fprintf(stderr, "Failed to get PG count!\n");
221 return 1;
222 }
223
224 if (config->pgid && config->pgid[0]) { //when reject-PG is given, and is not empty, remove given pg onwards
225 for (i = 0; i < count; ++i) {
226 if (sam_hdr_find_tag_pos(in_samhdr, pg, i, "ID", &id)) {
227 fprintf(stderr, "Failed to get PG entry fields for line %d!\n", i + 1);
228 break;
229 }
230
231 if (!strcmp(id.s, config->pgid))
232 break;
233
234 //either current PG is prior to rejected one or all PGs are in, get PG line and add
235 ks_clear(&line);
236 if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) {
237 fprintf(stderr, "Failed to get PG data at %d!\n", i + 1);
238 ret = 1;
239 break;
240 }
241
242 //add to output
243 if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) {
244 fprintf(stderr, "Failed to add PG data!\n");
245 ret = 1;
246 break;
247 }
248 }
249 }
250 else { //keep all
251 for (i = 0; i < count; ++i) {
252 if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) {
253 fprintf(stderr, "Failed to get PG data at %d!\n", i + 1);
254 ret = 1;
255 break;
256 }
257 //line has the required PG data
258 if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) {
259 fprintf(stderr, "Failed to add PG data!\n");
260 ret = 1;
261 break;
262 }
263 }
264 }
265
266 if (!ret && !config->noPGentry) {
267 //add PG entry with reset command
268 if (-1 == (ret = sam_hdr_add_pg(out_samhdr, "samtools", "CL", argdump, NULL))) {
269 fprintf(stderr, "Failed to set PG entry!\n");
270 }
271 }
272 ks_free(&line);
273 ks_free(&id);
274
275 return ret;
276 }
277
278 /// reset - do the reset of data and create output; create output header with required rg/pg data, add bamdata with flags set to unmapped, pair info and orientation reset,
279 // reerse and complement alignment if required
280 /** @param infile - input samfile pointer
281 * @param outfile - output sam file pointer
282 * @param config - pointer to internal configuration data
283 * @param args - string containing dump of command line invocation
284 returns 1 on failure 0 on success
285 */
286 int reset(samFile *infile, samFile *outfile, conf_data *config, char *args)
287 {
288 sam_hdr_t *in_samhdr = NULL, *out_samhdr = NULL;
289 int ret = EXIT_FAILURE, ret_r = 0, ret_w = 0, i = 0;
290 bam1_t *bamdata = NULL, *outdata = NULL;
291 kstring_t querydata = KS_INITIALIZE, qualdata = KS_INITIALIZE;
292 char *sp = NULL, *qp = NULL;
293 uint8_t *bamquery = NULL, *bamqual = NULL;
294
295 if (!infile || !outfile) {
296 fprintf(stderr, "Invalid parameters in reset!\n");
297 goto error;
298 }
299
300 //read input header
301 in_samhdr = sam_hdr_read(infile);
302 if (!in_samhdr)
303 {
304 fprintf(stderr, "Failed to read header from file!\n");
305 goto error;
306 }
307 //create output header
308 if (!(out_samhdr = sam_hdr_init()))
309 {
310 fprintf(stderr, "Failed to create output header!\n");
311 goto error;
312 }
313
314 //add version to output header
315 if (-1 == sam_hdr_add_line(out_samhdr,"HD", "VN", SAM_FORMAT_VERSION, NULL)) {
316 fprintf(stderr, "Failed to set header data!\n");
317 goto error;
318 }
319 //add RG / PG lines if configured
320 if ((config->keepRGs && getRGlines(in_samhdr, out_samhdr)) ||
321 getPGlines(in_samhdr, out_samhdr, config, args)) {
322 goto error;
323 }
324
325 //write output header
326 if (sam_hdr_write(outfile, out_samhdr)) {
327 print_error_errno("reset", "Output header write failed (%d)!\n", errno);
328 goto error;
329 }
330
331 bamdata = bam_init1(); //input bam
332 outdata = bam_init1(); //output bam
333 if (!bamdata || !outdata)
334 {
335 fprintf(stderr, "Failed to allocate data memory!\n");
336 goto error;
337 }
338
339 errno = 0; i = 0;
340 sp = NULL; qp = NULL;
341 bamquery = NULL; bamqual = NULL;
342
343 //get bam data, make updates and dump to output
344 while (0 <= (ret_r = sam_read1(infile, in_samhdr, bamdata)))
345 {
346 sp = NULL; qp = NULL;
347 bamquery = NULL; bamqual = NULL;
348
349 // read data
350 if (bamdata->core.flag & BAM_FSECONDARY || bamdata->core.flag & BAM_FSUPPLEMENTARY) {
351 continue;
352 }
353 //update flags
354 uint16_t flags = bamdata->core.flag & ~BAM_FPROPER_PAIR; //reset pair info
355 flags |= BAM_FUNMAP; //mark as unmapped
356 if (bamdata->core.flag & BAM_FPAIRED) {
357 flags |= BAM_FMUNMAP; //mark mate as unmapped, if it was a pair
358 }
359 flags &= ~BAM_FMREVERSE; //reset mate orientation
360 if (!(config->ctrlFlags & RESET_KEEPDUPFLAG)) {
361 flags &= ~BAM_FDUP; //reset dup flag from alignment
362 }
363
364 if (0 > ks_resize(&querydata, bamdata->core.l_qseq) ||
365 0 > ks_resize(&qualdata, bamdata->core.l_qseq)) {
366 fprintf(stderr, "Failed to get allocate memory!\n");
367 ret_r = -4;
368 break;
369 }
370 ks_clear(&querydata);
371 ks_clear(&qualdata);
372
373 sp = ks_str(&querydata);
374 qp = ks_str(&qualdata);
375 bamquery = bam_get_seq(bamdata);
376 bamqual = bam_get_qual(bamdata);
377 if (bamdata->core.flag & BAM_FREVERSE) {
378 //sequence data ordered as reverse complemented, reorder/complement sequence and quality data as read and clear the flag
379 for (i = bamdata->core.l_qseq - 1; i >= 0; --i) {
380 *sp++ = "=TGKCYSBAWRDMHVN"[bam_seqi(bamquery, i)];
381 *qp++ = bamqual[i];
382 }
383 flags &= ~BAM_FREVERSE; //reset flag as well
384 }
385 else {
386 //data in read order itself
387 for (i = 0; i < bamdata->core.l_qseq ; ++i) {
388 *sp++ = seq_nt16_str[bam_seqi(bamquery, i)];
389 }
390 memcpy(qp, bam_get_qual(bamdata), bamdata->core.l_qseq);
391 }
392
393 removeauxtags(bamdata, config);
394 if (0 > (ret_w = bam_set1(outdata, bamdata->core.l_qname - bamdata->core.l_extranul - 1, bam_get_qname(bamdata), flags, -1, -1, 0, 0, NULL, -1, -1, 0, bamdata->core.l_qseq, querydata.s, qualdata.s, bam_get_l_aux(bamdata)))) {
395 print_error_errno("reset", "Failed to set output data (%d)!\n", errno);
396 break;
397 }
398
399 memcpy(bam_get_aux(outdata), bam_get_aux(bamdata), bam_get_l_aux(bamdata));
400 outdata->l_data += bam_get_l_aux(bamdata);
401
402 errno = 0;
403 //write bam data to output
404 if (0 > (ret_w = sam_write1(outfile, out_samhdr, outdata)))
405 {
406 print_error_errno("reset", "Failed to write output data (%d)!\n", errno);
407 break;
408 }
409 // wrote the data, continue read/write cycle
410 errno = 0;
411 }
412
413 if (-1 > ret_r || 0 > ret_w) {
414 //some error
415 fprintf(stderr, "Error during %s!\n", (-1 > ret_r)? "read" : "write");
416 }
417 else {
418 // no error!
419 ret = EXIT_SUCCESS;
420 }
421
422 error:
423 // clean up and return result
424 if (in_samhdr)
425 sam_hdr_destroy(in_samhdr);
426 if (out_samhdr)
427 sam_hdr_destroy(out_samhdr);
428
429 if (bamdata)
430 bam_destroy1(bamdata);
431 if (outdata)
432 bam_destroy1(outdata);
433
434 if (qualdata.s)
435 ks_free(&qualdata);
436 if (querydata.s)
437 ks_free(&querydata);
438 return ret;
439 }
440
441 /// cleanup - free up allocations made
442 /** @param config - pointer to internal configuration data
443 returns nothing
444 */
445 void cleanup(conf_data *config)
446 {
447 if (config->aux_keep) {
448 kh_destroy(aux_exists, config->aux_keep);
449 config->aux_keep = NULL;
450 }
451 if (config->aux_remove) {
452 kh_destroy(aux_exists, config->aux_remove);
453 config->aux_remove = NULL;
454 }
455 }
456
457 /// main_reset - starts the reset of data
458 /** @param argc - count of arguments
459 * @param argv - pointer to array of arguments
460 returns 1 on failure 0 on success
461 */
462 int main_reset(int argc, char *argv[])
463 {
464 static const struct option lopts[] = {
465 SAM_OPT_GLOBAL_OPTIONS('-', '-', 'O', '-', '-', '@'), //let output format and thread count be given by user - long options
466 {"keep-tag", required_argument, NULL, LONG_OPT('x')}, //aux tags to be retained, supports ^ STR
467 {"remove-tag", required_argument, NULL, 'x'}, //aux tags to be removed
468 {"no-RG", no_argument, NULL, 1}, //no RG lines in output, default is to keep them
469 //reject PG lines from input, default is to keep them (i.e. option not given); without optional filename, all PGs removed and those given in file are filtered when optional filename is given
470 {"reject-PG", required_argument, NULL, 'p'}, //reject entries from this PG onwards
471 {"no-PG", no_argument, NULL, 2}, //do not add PG entry for reset operation, default is to add it
472 {"dupflag", no_argument, NULL, 3}, //keep the dup flag as it is - as in initial reset implementation
473 {NULL, 0, NULL, 0}
474 };
475 samFile *infile = NULL, *outfile = NULL;
476 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
477 htsThreadPool tpool = {NULL, 0};
478 const char *inname = NULL, *outname = NULL;
479 int c = 0, ret = EXIT_FAILURE;
480 char outmode[4] = "w", *args = NULL;
481 conf_data resetconf = {1, 0, 0, NULL, NULL, NULL}; //keep RGs and PGs by default, ctrlflags = 0
482
483 //samtools reset -o outfile -x/--remove-tag ... --keep-tag ... --threads=n --output-fmt=fmt --no-RG --reject-PG pgid --no-PG [<infile>]
484 while ((c = getopt_long(argc, argv, "o:@:x:O:", lopts, NULL)) >= 0)
485 {
486 switch (c)
487 {
488 case 1: //--no-RG
489 if (!resetconf.keepRGs) {
490 usage(stderr); //already given!
491 goto exit;
492 }
493 resetconf.keepRGs = 0;
494 break;
495 case 2: //--no-PG
496 if (resetconf.noPGentry) {
497 usage(stderr); //already given!
498 goto exit;
499 }
500 resetconf.noPGentry = 1;
501 break;
502 case 3: //keep dup flag as it is / no reset
503 resetconf.ctrlFlags |= RESET_KEEPDUPFLAG;
504 break;
505 case 'p': //--reject-PG=<id>
506 if (resetconf.pgid) {
507 usage(stderr); //already given!
508 goto exit;
509 }
510 resetconf.pgid = optarg;
511 break;
512 case 'o': //output file name
513 if (outname) { //already given!
514 usage(stderr);
515 goto exit;
516
517 }
518 outname = optarg;
519 break;
520 case 'x': //remove aux tag
521 if (*optarg == '^') { //remove all except given ones!
522 if (parse_aux_list(&resetconf.aux_keep, optarg+1, "main_reset")) {
523 usage(stderr);
524 goto exit;
525 }
526 }
527 else { //remove given ones
528 if (parse_aux_list(&resetconf.aux_remove, optarg, "main_reset")) {
529 usage(stderr);
530 goto exit;
531 }
532 }
533 break;
534 case LONG_OPT('x'): //keep aux tags
535 if (parse_aux_list(&resetconf.aux_keep, optarg, "main_reset")) {
536 usage(stderr);
537 goto exit;
538 }
539 break;
540 // handle standard samtool options like thread count, verbosity...
541 default:
542 if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0)
543 break;
544 // else fall-through
545 // couldn't parse or unknown options, show usage!
546 case '?': //unknown options found!
547 usage(stderr);
548 goto exit;
549 break;
550 }
551 }
552
553 if (argc == 1 && isatty(STDIN_FILENO)) {
554 //no args and input is stdin -- it is the usage check
555 usage(stdout);
556 ret = EXIT_SUCCESS;
557 goto exit;
558 }
559 //else have other args or input from redirection/pipe/other device -- validate and work
560
561 if (!outname)
562 outname = "-";
563
564 //check and fail if unnecessary parameters are given
565 c = argc - optind;
566 if (c > 1) {
567 usage(stderr);
568 goto exit;
569 }
570
571 if (c == 1) {
572 inname = argv[optind];
573 }
574 else {
575 inname = "-";
576 }
577
578 //update aux tag configuration
579 update_aux_conf(&resetconf);
580 //set output file format based on name
581 sam_open_mode(outmode + 1, outname, NULL);
582
583 //open input and output files
584 infile = sam_open(inname, "r");
585 outfile = sam_open_format(outname, outmode, &ga.out);
586 if (!infile || !outfile) {
587 fprintf(stderr, "Could not open %s%s%s\n", !infile ? inname : "", (!infile && !outfile)? ", " : "", !outfile ? outname : "");
588 goto exit;
589 }
590
591 // set the thread count if given as argument
592 if (ga.nthreads > 0)
593 {
594 if (!(tpool.pool = hts_tpool_init(ga.nthreads)))
595 {
596 fprintf(stderr, "\nFailed to setup thread pool\n");
597 goto exit;
598 }
599
600 hts_set_opt(infile, HTS_OPT_THREAD_POOL, &tpool);
601 hts_set_opt(outfile, HTS_OPT_THREAD_POOL, &tpool);
602 }
603
604 args = stringify_argv(argc + 1, argv - 1); //to dump invocation in PG line
605
606 //do the reset!
607 ret = reset(infile, outfile, &resetconf, args);
608
609 exit:
610 if (args)
611 free(args);
612 if (infile)
613 sam_close(infile);
614 if (outfile)
615 sam_close(outfile);
616 if (tpool.pool)
617 hts_tpool_destroy(tpool.pool);
618 cleanup(&resetconf);
619 sam_global_args_free(&ga);
620
621 return ret;
622 }