Debian Codegraph @

samtools/reset.c.pysam.c

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