Debian Codegraph @

samtools/bam_markdup.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_markdup.c -- Mark duplicates from a coord sorted file that has gone
4 through fixmates with the mate scoring option on.
5
6 Copyright (C) 2017-2023 Genome Research Ltd.
7
8 Author: Andrew Whitwham <[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 Estimate library size derived from Picard DuplicationMetrics.java
29 Copyright (c) 2009,2018 The Broad Institute. MIT license.
30 */
31
32 #include <config.h>
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <time.h>
40 #include <sys/stat.h>
41 #include <math.h>
42 #include <regex.h>
43 #include "htslib/thread_pool.h"
44 #include "htslib/sam.h"
45 #include "sam_opts.h"
46 #include "samtools.h"
47 #include "htslib/khash.h"
48 #include "htslib/klist.h"
49 #include "htslib/kstring.h"
50 #include "tmp_file.h"
51 #include "bam.h"
52
53
54 typedef struct {
55 samFile *in;
56 samFile *out;
57 char *prefix;
58 int remove_dups;
59 int32_t max_length;
60 int do_stats;
61 int supp;
62 int tag;
63 int opt_dist;
64 int no_pg;
65 int clear;
66 int mode;
67 int write_index;
68 int include_fails;
69 int check_chain;
70 char *stats_file;
71 char *arg_list;
72 char *out_fn;
73 regex_t *rgx;
74 int rgx_x;
75 int rgx_y;
76 int rgx_t;
77 char *barcode;
78 regex_t *bc_rgx;
79 int read_groups;
80 int json;
81 int dc;
82 } md_param_t;
83
84 typedef struct {
85 hts_pos_t this_coord;
86 hts_pos_t other_coord;
87 int32_t this_ref;
88 int32_t other_ref;
89 int32_t barcode;
90 int32_t read_group;
91 int8_t single;
92 int8_t leftmost;
93 int8_t orientation;
94 } key_data_t;
95
96 typedef struct read_queue_s {
97 key_data_t pair_key;
98 key_data_t single_key;
99 bam1_t *b;
100 struct read_queue_s *duplicate;
101 struct read_queue_s *original;
102 int dc;
103 hts_pos_t pos;
104 int dup_checked;
105 int read_group;
106 } read_queue_t;
107
108 typedef struct {
109 read_queue_t *p;
110 } in_hash_t;
111
112 typedef struct {
113 char *name;
114 char type;
115 int read_group;
116 } dup_map_t;
117
118 typedef struct {
119 bam1_t *b;
120 int64_t score;
121 int64_t mate_score;
122 long x;
123 long y;
124 int opt;
125 int beg;
126 int end;
127 int len;
128 } check_t;
129
130 typedef struct {
131 check_t *c;
132 size_t size;
133 size_t length;
134 } check_list_t;
135
136 typedef struct {
137 long reading;
138 long writing;
139 long excluded;
140 long duplicate;
141 long single;
142 long pair;
143 long single_dup;
144 long examined;
145 long optical;
146 long single_optical;
147 long np_duplicate;
148 long np_opt_duplicate;
149 } stats_block_t;
150
151 static khint32_t do_hash(unsigned char *key, khint32_t len);
152
153 static khint_t hash_key(key_data_t key) {
154 int i = 0;
155 khint_t hash;
156
157 if (key.single) {
158 unsigned char sig[21];
159
160 memcpy(sig + i, &key.this_ref, 4); i += 4;
161 memcpy(sig + i, &key.this_coord, 8); i += 8;
162 memcpy(sig + i, &key.orientation, 1); i += 1;
163 memcpy(sig + i, &key.barcode, 4); i += 4;
164 memcpy(sig + i, &key.read_group, 4); i += 4;
165
166 hash = do_hash(sig, i);
167 } else {
168 unsigned char sig[34];
169
170 memcpy(sig + i, &key.this_ref, 4); i += 4;
171 memcpy(sig + i, &key.this_coord, 8); i += 8;
172 memcpy(sig + i, &key.other_ref, 4); i += 4;
173 memcpy(sig + i, &key.other_coord, 8); i += 8;
174 memcpy(sig + i, &key.leftmost, 1); i += 1;
175 memcpy(sig + i, &key.orientation, 1); i += 1;
176 memcpy(sig + i, &key.barcode, 4); i += 4;
177 memcpy(sig + i, &key.read_group, 4); i += 4;
178
179 hash = do_hash(sig, i);
180 }
181
182 return hash;
183 }
184
185
186 static int key_equal(key_data_t a, key_data_t b) {
187 int match = 1;
188
189 if (a.this_coord != b.this_coord)
190 match = 0;
191 else if (a.orientation != b.orientation)
192 match = 0;
193 else if (a.this_ref != b.this_ref)
194 match = 0;
195 else if (a.single != b.single)
196 match = 0;
197 else if (a.barcode != b.barcode)
198 match = 0;
199 else if (a.read_group != b.read_group)
200 match = 0;
201
202 if (!a.single) {
203 if (a.other_coord != b.other_coord)
204 match = 0;
205 else if (a.leftmost != b.leftmost)
206 match = 0;
207 else if (a.other_ref != b.other_ref)
208 match = 0;
209 }
210
211 return match;
212 }
213
214
215 #define __free_queue_element(p)
216
217 // Orientations (prime numbers to feed to hashing algorithm)
218 #define O_FF 2
219 #define O_RR 3
220 #define O_FR 5
221 #define O_RF 7
222
223 // Left or rightmost
224 #define R_LE 11
225 #define R_RI 13
226
227 #define BMD_WARNING_MAX 10
228
229 #define MD_MIN_QUALITY 15
230
231 // Duplicate finding mode
232 #define MD_MODE_TEMPLATE 0
233 #define MD_MODE_SEQUENCE 1
234
235 KHASH_INIT(reads, key_data_t, in_hash_t, 1, hash_key, key_equal) // read map hash
236 KLIST_INIT(read_queue, read_queue_t, __free_queue_element) // the reads buffer
237 KHASH_MAP_INIT_STR(duplicates, dup_map_t) // map of duplicates for supplementary dup id
238 KHASH_MAP_INIT_STR(read_groups, int) // read group lookup
239
240 /* The Bob Jenkins one_at_a_time hash to reduce the key to a 32 bit value. */
241
242 static khint32_t do_hash(unsigned char *key, khint32_t len) {
243 khint32_t hash, i;
244
245 for (hash = 0, i = 0; i < len; ++i) {
246 hash += key[i];
247 hash += (hash << 10);
248 hash ^= (hash >> 6);
249 }
250
251 hash += (hash << 3);
252 hash ^= (hash >> 11);
253 hash += (hash << 15);
254
255 return hash;
256 }
257
258
259 /* Get mate score from tag. */
260
261 static int64_t get_mate_score(bam1_t *b) {
262 uint8_t *data;
263 int64_t score;
264
265 if ((data = bam_aux_get(b, "ms"))) {
266 score = bam_aux2i(data);
267 } else {
268 print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
269 return -1;
270 }
271
272 return score;
273 }
274
275
276 /* Calc current score from quality. */
277
278 static int64_t calc_score(bam1_t *b)
279 {
280 int64_t score = 0;
281 uint8_t *qual = bam_get_qual(b);
282 int i;
283
284 for (i = 0; i < b->core.l_qseq; i++) {
285 if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
286 }
287
288 return score;
289 }
290
291
292 /* Create a signature hash of the current read and its pair.
293 Uses the unclipped start (or end depending on orientation),
294 the reference id, orientation and whether the current
295 read is leftmost of the pair. */
296
297
298 static int make_pair_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) {
299 hts_pos_t this_coord, this_end, other_coord, other_end, leftmost;
300 int32_t this_ref, other_ref, barcode = 0;
301 int8_t orientation, left_read;
302 uint8_t *data;
303 char *cig, *bar;
304 long incoming_warnings = *warnings;
305
306 this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash
307 other_ref = bam->core.mtid + 1;
308
309 this_coord = unclipped_start(bam);
310 this_end = unclipped_end(bam);
311
312 if ((data = bam_aux_get(bam, "MC"))) {
313 if (!(cig = bam_aux2Z(data))) {
314 print_error("markdup", "error, MC tag wrong type. Please use the MC tag provided by samtools fixmate.\n");
315 return 1;
316 }
317
318 other_end = unclipped_other_end(bam->core.mpos, cig);
319 other_coord = unclipped_other_start(bam->core.mpos, cig);
320 } else {
321 print_error("markdup", "error, no MC tag. Please run samtools fixmate on file first.\n");
322 return 1;
323 }
324
325 // work out orientations
326 if (param->mode == MD_MODE_TEMPLATE) {
327
328 if (this_ref != other_ref) {
329 leftmost = this_ref < other_ref;
330 } else {
331 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
332 if (!bam_is_rev(bam)) {
333 leftmost = this_coord <= other_coord;
334 } else {
335 leftmost = this_end <= other_end;
336 }
337 } else {
338 if (bam_is_rev(bam)) {
339 leftmost = this_end <= other_coord;
340 } else {
341 leftmost = this_coord <= other_end;
342 }
343 }
344 }
345
346 // pair orientation
347 if (leftmost) {
348 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
349 other_coord = other_end;
350
351 if (!bam_is_rev(bam)) {
352 if (bam->core.flag & BAM_FREAD1) {
353 orientation = O_FF;
354 } else {
355 orientation = O_RR;
356 }
357 } else {
358 if (bam->core.flag & BAM_FREAD1) {
359 orientation = O_RR;
360 } else {
361 orientation = O_FF;
362 }
363 }
364 } else {
365 if (!bam_is_rev(bam)) {
366 orientation = O_FR;
367 other_coord = other_end;
368 } else {
369 orientation = O_RF;
370 this_coord = this_end;
371 }
372 }
373 } else {
374 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
375 this_coord = this_end;
376
377 if (!bam_is_rev(bam)) {
378 if (bam->core.flag & BAM_FREAD1) {
379 orientation = O_RR;
380 } else {
381 orientation = O_FF;
382 }
383 } else {
384 if (bam->core.flag & BAM_FREAD1) {
385 orientation = O_FF;
386 } else {
387 orientation = O_RR;
388 }
389 }
390 } else {
391 if (!bam_is_rev(bam)) {
392 orientation = O_RF;
393 other_coord = other_end;
394 } else {
395 orientation = O_FR;
396 this_coord = this_end;
397 }
398 }
399 }
400 } else { // MD_MODE_SEQUENCE
401
402 if (this_ref != other_ref) {
403 leftmost = this_ref - other_ref;
404 } else {
405 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
406 if (!bam_is_rev(bam)) {
407 leftmost = this_coord - other_coord;
408 } else {
409 leftmost = this_end - other_end;
410 }
411 } else {
412 if (bam_is_rev(bam)) {
413 leftmost = this_end - other_coord;
414 } else {
415 leftmost = this_coord - other_end;
416 }
417 }
418 }
419
420 if (leftmost < 0) {
421 leftmost = 1;
422 } else if (leftmost > 0) {
423 leftmost = 0;
424 } else {
425 // tie breaks
426
427 if (bam->core.pos == bam->core.mpos) {
428 if (bam->core.flag & BAM_FREAD1) {
429 leftmost = 1;
430 } else {
431 leftmost = 0;
432 }
433 } else if (bam->core.pos < bam->core.mpos) {
434 leftmost = 1;
435 } else {
436 leftmost = 0;
437 }
438 }
439
440 // pair orientation
441 if (leftmost) {
442 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
443
444 if (!bam_is_rev(bam)) {
445 orientation = O_FF;
446 } else {
447 orientation = O_RR;
448 }
449 } else {
450 if (!bam_is_rev(bam)) {
451 orientation = O_FR;
452 } else {
453 orientation = O_RF;
454 }
455 }
456 } else {
457 if (bam_is_rev(bam) == bam_is_mrev(bam)) {
458
459 if (!bam_is_rev(bam)) {
460 orientation = O_RR;
461 } else {
462 orientation = O_FF;
463 }
464 } else {
465 if (!bam_is_rev(bam)) {
466 orientation = O_RF;
467 } else {
468 orientation = O_FR;
469 }
470 }
471 }
472
473 if (!bam_is_rev(bam)) {
474 this_coord = unclipped_start(bam);
475 } else {
476 this_coord = unclipped_end(bam);
477 }
478
479 if (!bam_is_mrev(bam)) {
480 other_coord = unclipped_other_start(bam->core.mpos, cig);
481 } else {
482 other_coord = unclipped_other_end(bam->core.mpos, cig);
483 }
484 }
485
486 if (!leftmost)
487 left_read = R_RI;
488 else
489 left_read = R_LE;
490
491 if (param->barcode) {
492 if ((data = bam_aux_get(bam, param->barcode))) {
493 if (!(bar = bam_aux2Z(data))) {
494 (*warnings)++;
495
496 if (*warnings <= BMD_WARNING_MAX) {
497 print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode);
498 }
499 } else {
500 barcode = do_hash((unsigned char *)bar, strlen(bar));
501 }
502 }
503 } else if (param->bc_rgx) {
504 int result;
505 regmatch_t matches[3];
506 size_t max_matches = 2;
507 char *qname = bam_get_qname(bam);
508
509 if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) {
510 int bc_start, bc_end;
511
512 bc_start = matches[1].rm_so;
513 bc_end = matches[1].rm_eo;
514
515 if (bc_start != -1) {
516 barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start);
517 } else {
518 (*warnings)++;
519
520 if (*warnings <= BMD_WARNING_MAX) {
521 print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname);
522 }
523 }
524 } else {
525 (*warnings)++;
526
527 if (*warnings <= BMD_WARNING_MAX) {
528 char warn_msg[256];
529
530 regerror(result, param->bc_rgx, warn_msg, 256);
531 print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname);
532 }
533 }
534 }
535
536 if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) {
537 print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n",
538 *warnings);
539 }
540
541 key->single = 0;
542 key->this_ref = this_ref;
543 key->this_coord = this_coord;
544 key->other_ref = other_ref;
545 key->other_coord = other_coord;
546 key->leftmost = left_read;
547 key->orientation = orientation;
548 key->barcode = barcode;
549 key->read_group = rg_num;
550
551 return 0;
552 }
553
554
555 /* Create a signature hash of single read (or read with an unmatched pair).
556 Uses unclipped start (or end depending on orientation), reference id,
557 and orientation. */
558
559 static void make_single_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) {
560 hts_pos_t this_coord;
561 int32_t this_ref, barcode = 0;
562 int8_t orientation;
563 uint8_t *data;
564 char *bar;
565 long incoming_warnings = *warnings;
566
567 this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash
568
569 if (bam_is_rev(bam)) {
570 this_coord = unclipped_end(bam);
571 orientation = O_RR;
572 } else {
573 this_coord = unclipped_start(bam);
574 orientation = O_FF;
575 }
576
577 if (param->barcode) {
578 if ((data = bam_aux_get(bam, param->barcode))) {
579 if (!(bar = bam_aux2Z(data))) {
580 (*warnings)++;
581
582 if (*warnings <= BMD_WARNING_MAX) {
583 print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode);
584 }
585 } else {
586 barcode = do_hash((unsigned char *)bar, strlen(bar));
587 }
588 }
589 } else if (param->bc_rgx) {
590 int result;
591 regmatch_t matches[3];
592 size_t max_matches = 2;
593 char *qname = bam_get_qname(bam);
594
595 if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) {
596 int bc_start, bc_end;
597
598 bc_start = matches[1].rm_so;
599 bc_end = matches[1].rm_eo;
600
601 if (bc_start != -1) {
602 barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start);
603 } else {
604 (*warnings)++;
605
606 if (*warnings <= BMD_WARNING_MAX) {
607 print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname);
608 }
609 }
610 } else {
611 (*warnings)++;
612
613 if (*warnings <= BMD_WARNING_MAX) {
614 char warn_msg[256];
615
616 regerror(result, param->bc_rgx, warn_msg, 256);
617 print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname);
618 }
619 }
620 }
621
622 if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) {
623 print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n",
624 *warnings);
625 }
626
627
628 key->single = 1;
629 key->this_ref = this_ref;
630 key->this_coord = this_coord;
631 key->orientation = orientation;
632 key->barcode = barcode;
633 key->read_group = rg_num;
634 }
635
636
637 /* Add the duplicate name to a hash if it does not exist. */
638
639 static int add_duplicate(khash_t(duplicates) *d_hash, bam1_t *dupe, char *orig_name, char type, int group) {
640 khiter_t d;
641 int ret;
642
643 d = kh_get(duplicates, d_hash, bam_get_qname(dupe));
644
645 if (d == kh_end(d_hash)) {
646 char *name = strdup(bam_get_qname(dupe));
647 if (name) {
648 d = kh_put(duplicates, d_hash, name, &ret);
649 } else {
650 ret = -1;
651 }
652
653 if (ret >= 0) {
654 if (orig_name) {
655 if (ret == 0) {
656 // replace old name
657 free(kh_value(d_hash, d).name);
658 free(name);
659 }
660
661 kh_value(d_hash, d).name = strdup(orig_name);
662
663 if (kh_value(d_hash, d).name == NULL) {
664 print_error("markdup", "error, unable to allocate memory for duplicate original name.\n");
665 return 1;
666 }
667 } else {
668 kh_value(d_hash, d).name = NULL;
669 }
670
671 kh_value(d_hash, d).type = type;
672 kh_value(d_hash, d).read_group = group;
673 } else {
674 print_error("markdup", "error, unable to store supplementary duplicates.\n");
675 free(name);
676 return 1;
677 }
678 }
679
680 return 0;
681 }
682
683
684 /* Get coordinates from the standard Illumina style read names.
685 Returned values are of the x and y coordinates and a section of
686 the read name to test (t) for string equality e.g. lane and tile part. */
687
688 static int get_coordinates_colons(md_param_t *param, const char *qname, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
689 int sep = 0;
690 int pos = 0;
691 int xpos = 0, ypos = 0;
692 char *end;
693
694 while (qname[pos]) {
695 if (qname[pos] == ':') {
696 sep++;
697
698 if (sep == 2) {
699 xpos = pos + 1;
700 } else if (sep == 3) {
701 ypos = pos + 1;
702 } else if (sep == 4) { // HiSeq style names
703 xpos = ypos;
704 ypos = pos + 1;
705 } else if (sep == 5) { // Newer Illumina format
706 xpos = pos + 1;
707 } else if (sep == 6) {
708 ypos = pos + 1;
709 }
710 }
711
712 pos++;
713 }
714
715 /* The most current Illumina read format at time of writing is:
716 @machine:run:flowcell:lane:tile:x:y:UMI or
717 @machine:run:flowcell:lane:tile:x:y
718
719 Counting the separating colons gives us a quick format check.
720 Older name formats have fewer elements.
721 */
722
723 if (!(sep == 3 || sep == 4 || sep == 6 || sep == 7)) {
724 (*warnings)++;
725
726 if (*warnings <= BMD_WARNING_MAX) {
727 print_error("markdup", "warning, cannot decipher read name %s for optical duplicate marking.\n", qname);
728 }
729
730 return 1;
731 } else {
732 *x_coord = strtol(qname + xpos, &end, 10);
733
734 if ((qname + xpos) == end) {
735 (*warnings)++;
736
737 if (*warnings <= BMD_WARNING_MAX) {
738 print_error("markdup", "warning, cannot decipher x coordinate in %s .\n", qname);
739 }
740
741 return 1;
742 }
743
744 *y_coord = strtol(qname + ypos, &end, 10);
745
746 if ((qname + ypos) == end) {
747 (*warnings)++;
748
749 if (*warnings <= BMD_WARNING_MAX) {
750 print_error("markdup", "warning, cannot decipher y coordinate in %s .\n", qname);
751 }
752
753 return 1;
754 }
755
756 *t_beg = 0;
757 *t_end = xpos;
758 }
759
760 return 0;
761 }
762
763 /* Get the coordinates from the read name.
764 Returned values are of the x and y coordinates and an optional section of
765 the read name to test (t) for string equality e.g. lane and tile part. */
766
767 static inline int get_coordinates_regex(md_param_t *param, const char *qname, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
768 regmatch_t matches[5];
769 size_t max_matches = 5;
770 int xpos, ypos, xend, yend, xlen, ylen;
771 char coord[255];
772 char *end;
773
774 if (!param->rgx_t)
775 max_matches = 4;
776
777 if (regexec(param->rgx, qname, max_matches, matches, 0))
778 return -1;
779
780 xpos = matches[param->rgx_x].rm_so;
781 ypos = matches[param->rgx_y].rm_so;
782
783 if (param->rgx_t) {
784 *t_beg = matches[param->rgx_t].rm_so;
785 *t_end = matches[param->rgx_t].rm_eo;
786 } else {
787 *t_beg = *t_end = 0;
788 }
789
790 if (xpos == -1 || ypos == -1 || *t_beg == -1)
791 return -1;
792
793 xend = matches[param->rgx_x].rm_eo;
794 yend = matches[param->rgx_y].rm_eo;
795
796 if ((xlen = xend - xpos) > 254) {
797 (*warnings)++;
798
799 if (*warnings <= BMD_WARNING_MAX) {
800 print_error("markdup", "warning, x coordinate string longer than allowed qname length in %s (%d long).\n", qname, xlen);
801 }
802
803 return 1;
804 }
805
806 strncpy(coord, qname + xpos, xlen);
807 coord[xlen] = '\0';
808 *x_coord = strtol(coord, &end, 10);
809
810 if (coord == end) {
811 (*warnings)++;
812
813 if (*warnings <= BMD_WARNING_MAX) {
814 print_error("markdup", "warning, cannot decipher x coordinate in %s (%s).\n", qname, coord);
815 }
816
817 return 1;
818 }
819
820 if ((ylen = yend - ypos) > 254) {
821 (*warnings)++;
822
823 if (*warnings <= BMD_WARNING_MAX) {
824 print_error("markdup", "warning, y coordinate string longer than allowed qname length in %s (%d long).\n", qname, ylen);
825 }
826
827 return 1;
828 }
829
830 strncpy(coord, qname + ypos, ylen);
831 coord[ylen] = '\0';
832 *y_coord = strtol(coord, &end, 10);
833
834 if (coord == end) {
835 (*warnings)++;
836
837 if (*warnings <= BMD_WARNING_MAX) {
838 print_error("markdup", "warning, cannot decipher y coordinate in %s (%s).\n", qname, coord);
839 }
840
841 return 1;
842 }
843
844 return 0;
845 }
846
847
848 static int get_coordinates(md_param_t *param, const char *name, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
849 int ret = 1;
850
851 if (param->rgx == NULL) {
852 ret = get_coordinates_colons(param, name, t_beg, t_end, x_coord, y_coord, warnings);
853 } else {
854 ret = get_coordinates_regex(param, name, t_beg, t_end, x_coord, y_coord, warnings);
855 }
856
857 return ret;
858 }
859
860
861 /* Using the coordinates from the read name, see whether the duplicated read is
862 close enough (set by max_dist) to the original to be counted as optical.*/
863
864 static int is_optical_duplicate(md_param_t *param, bam1_t *ori, bam1_t *dup, long max_dist, long *warnings) {
865 int ret = 0;
866 char *original, *duplicate;
867 long ox, oy, dx, dy;
868 int o_beg = 0, o_end = 0, d_beg = 0, d_end = 0;
869
870 original = bam_get_qname(ori);
871 duplicate = bam_get_qname(dup);
872
873 if (get_coordinates(param, original, &o_beg, &o_end, &ox, &oy, warnings)) {
874 return ret;
875 }
876
877 if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) {
878 return ret;
879 }
880
881 int o_len = o_end - o_beg;
882 int d_len = d_end - d_beg;
883
884 if ((o_len == d_len) && memcmp(original + o_beg, duplicate + d_beg, o_len) == 0) {
885 long xdiff, ydiff;
886
887 if (ox > dx) {
888 xdiff = ox - dx;
889 } else {
890 xdiff = dx - ox;
891 }
892
893 if (xdiff <= max_dist) {
894 // still might be optical
895
896 if (oy > dy) {
897 ydiff = oy - dy;
898 } else {
899 ydiff = dy - oy;
900 }
901
902 if (ydiff <= max_dist) ret = 1;
903 }
904 }
905
906 return ret;
907 }
908
909
910 /* Using the coordinates from the Illumina read name, see whether the duplicated read is
911 close enough (set by max_dist) to the original to be counted as optical.
912
913 This function needs the values from the first read to be already calculated. */
914
915 static int optical_duplicate_partial(md_param_t *param, const char *name, const int o_beg, const int o_end, const long ox, const long oy, bam1_t *dup, check_t *c, long max_dist, long *warnings) {
916 int ret = 0;
917 char *duplicate;
918 int d_beg = 0, d_end = 0;
919 long dx, dy;
920
921 duplicate = bam_get_qname(dup);
922
923 if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) {
924 return ret;
925 }
926
927 int o_len = o_end - o_beg;
928 int d_len = d_end - d_beg;
929
930 if ((o_len == d_len) && memcmp(name + o_beg, duplicate + d_beg, o_len) == 0) {
931 // the initial parts match, look at the numbers
932 long xdiff, ydiff;
933
934 if (ox > dx) {
935 xdiff = ox - dx;
936 } else {
937 xdiff = dx - ox;
938 }
939
940 if (xdiff <= max_dist) {
941 // still might be optical
942
943 if (oy > dy) {
944 ydiff = oy - dy;
945 } else {
946 ydiff = dy - oy;
947 }
948
949 if (ydiff <= max_dist) ret = 1;
950 }
951 }
952
953 c->x = dx;
954 c->y = dy;
955 c->beg = d_beg;
956 c->end = d_end;
957 c->len = d_end - d_beg;
958
959 return ret;
960 }
961
962
963 /* Mark the read as a duplicate and update the duplicate hash (if needed) */
964 static int mark_duplicates(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *ori, bam1_t *dup,
965 int read_group, long *optical, long *warn) {
966 char dup_type = 0;
967 long incoming_warnings = *warn;
968
969 dup->core.flag |= BAM_FDUP;
970
971 if (param->tag) {
972 if (bam_aux_update_str(dup, "do", strlen(bam_get_qname(ori)) + 1, bam_get_qname(ori))) {
973 print_error("markdup", "error, unable to append 'do' tag.\n");
974 return -1;
975 }
976 }
977
978 if (param->opt_dist) { // mark optical duplicates
979 if (is_optical_duplicate(param, ori, dup, param->opt_dist, warn)) {
980 bam_aux_update_str(dup, "dt", 3, "SQ");
981 dup_type = 'O';
982 (*optical)++;
983 } else {
984 // not an optical duplicate
985 bam_aux_update_str(dup, "dt", 3, "LB");
986 }
987 }
988
989 if ((*warn == BMD_WARNING_MAX) && (incoming_warnings != *warn)) {
990 print_error("markdup", "warning, %ld decipher read name warnings. New warnings will not be reported.\n",
991 *warn);
992 }
993
994 if (param->supp) {
995 if (bam_aux_get(dup, "SA") || (dup->core.flag & BAM_FMUNMAP) || bam_aux_get(dup, "XA")) {
996 char *original = NULL;
997
998 if (param->tag) {
999 original = bam_get_qname(ori);
1000 }
1001
1002 if (add_duplicate(dup_hash, dup, original, dup_type, read_group))
1003 return -1;
1004 }
1005 }
1006
1007 return 0;
1008 }
1009
1010
1011 /* If the duplicate type has changed to optical then retag and duplicate hash. */
1012 static inline int optical_retag(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *b, int paired, stats_block_t *stats) {
1013 int ret = 0;
1014
1015 if (bam_aux_update_str(b, "dt", 3, "SQ")) {
1016 print_error("markdup", "error, unable to update 'dt' tag.\n");
1017 ret = -1;
1018 }
1019
1020 if (paired) {
1021 stats->optical++;
1022 } else {
1023 stats->single_optical++;
1024 }
1025
1026 if (param->supp) {
1027 // Change the duplicate type
1028
1029 if (bam_aux_get(b, "SA") || (b->core.flag & BAM_FMUNMAP)
1030 || bam_aux_get(b, "XA")) {
1031 khiter_t d;
1032
1033 d = kh_get(duplicates, dup_hash, bam_get_qname(b));
1034
1035 if (d == kh_end(dup_hash)) {
1036 // error, name should already be in dup hash
1037 print_error("markdup", "error, duplicate name %s not found in hash.\n",
1038 bam_get_qname(b));
1039 ret = -1;
1040 } else {
1041 kh_value(dup_hash, d).type = 'O';
1042 }
1043 }
1044 }
1045
1046 return ret;
1047 }
1048
1049
1050 /* Check all duplicates of the highest quality read (the "original") for consistancy. Also
1051 pre-calculate any values for use in check_duplicate_chain later.
1052 Returns 0 on success, >0 on coordinate reading error (program can continue) or
1053 <0 on an error (program should not continue. */
1054 static int check_chain_against_original(md_param_t *param, khash_t(duplicates) *dup_hash, read_queue_t *ori,
1055 check_list_t *list, long *warn, stats_block_t *stats) {
1056
1057 int ret = 0, coord_fail = 0;
1058 char *ori_name = bam_get_qname(ori->b);
1059 read_queue_t *current = ori->duplicate;
1060 int t_beg = 0, t_end = 0;
1061 long x, y;
1062
1063 if (param->opt_dist) {
1064 coord_fail = get_coordinates(param, ori_name, &t_beg, &t_end, &x, &y, warn);
1065 }
1066
1067 list->length = 0;
1068
1069 while (current) {
1070 check_t *c;
1071
1072 if (list->length >= list->size) {
1073 check_t *tmp;
1074
1075 list->size *= 2;
1076
1077 if (!(tmp = realloc(list->c, list->size * sizeof(check_t)))) {
1078 print_error("markdup", "error, Unable to expand optical check list.\n");
1079 return -1;
1080 }
1081
1082 list->c = tmp;
1083 }
1084
1085 c = &list->c[list->length];
1086
1087 c->b = current->b;
1088 c->x = -1;
1089 c->y = -1;
1090 c->opt = 0;
1091 c->score = 0;
1092 c->mate_score = 0;
1093 current->dup_checked = 1;
1094
1095 if (param->tag) {
1096 uint8_t *data;
1097
1098 // at this stage all duplicates should have a do tag
1099 if ((data = bam_aux_get(current->b, "do")) != NULL) {
1100 // see if we need to change the tag
1101 char *old_name = bam_aux2Z(data);
1102
1103 if (old_name) {
1104 if (strcmp(old_name, ori_name) != 0) {
1105 if (bam_aux_update_str(current->b, "do", strlen(ori_name) + 1, (const char *)ori_name)) {
1106 print_error("markdup", "error, unable to update 'do' tag.\n");
1107 ret = -1;
1108 break;
1109 }
1110 }
1111 } else {
1112 print_error("markdup", "error, 'do' tag has wrong type for read %s.\n", bam_get_qname(current->b));
1113 ret = -1;
1114 break;
1115 }
1116 }
1117 }
1118
1119 if (param->opt_dist && !coord_fail) {
1120 uint8_t *data;
1121 char *dup_type;
1122 int is_opt = 0;
1123 int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP);
1124
1125 if ((data = bam_aux_get(current->b, "dt"))) {
1126 if ((dup_type = bam_aux2Z(data))) {
1127 if (strcmp(dup_type, "SQ") == 0) {
1128 c->opt = 1;
1129 }
1130 }
1131 }
1132
1133 // need to run this to get the duplicates x and y scores
1134 is_opt = optical_duplicate_partial(param, ori_name, t_beg, t_end, x, y, current->b, c, param->opt_dist, warn);
1135
1136 if (!c->opt && is_opt) {
1137 if (optical_retag(param, dup_hash, current->b, current_paired, stats)) {
1138 ret = -1;
1139 break;
1140 }
1141
1142 c->opt = 1;
1143 }
1144
1145 c->score = calc_score(current->b);
1146
1147 if (current_paired) {
1148 if ((c->mate_score = get_mate_score(current->b)) == -1) {
1149 print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1150 ret = -1;
1151 break;
1152 }
1153 }
1154 }
1155
1156 current = current->duplicate;
1157 list->length++;
1158 }
1159
1160 if (!ret && coord_fail)
1161 ret = coord_fail;
1162
1163 ori->dup_checked = 1;
1164
1165 return ret;
1166 }
1167
1168
1169 static int chain_sort(const void *a, const void *b) {
1170 check_t *ac = (check_t *) a;
1171 check_t *bc = (check_t *) b;
1172 int ret;
1173
1174 if ((ret = ac->len - bc->len))
1175 return ret;
1176 else if ((ret = memcmp(bam_get_qname(ac->b) + ac->beg, bam_get_qname(bc->b) + bc->beg, ac->len)))
1177 return ret;
1178
1179 return (ac->x - bc->x);
1180 }
1181
1182
1183 /* Check all the duplicates against each other to see if they are optical duplicates. */
1184 static int check_duplicate_chain(md_param_t *param, khash_t(duplicates) *dup_hash, check_list_t *list,
1185 long *warn, stats_block_t *stats) {
1186 int ret = 0;
1187 size_t curr = 0;
1188
1189 qsort(list->c, list->length, sizeof(list->c[0]), chain_sort);
1190
1191 while (curr < list->length - 1) {
1192 check_t *base = &list->c[curr];
1193 char *base_name = bam_get_qname(base->b);
1194 int end_name_match = curr;
1195
1196 // find the end of the matching name parts
1197 while (++end_name_match < list->length) {
1198 check_t *chk = &list->c[end_name_match];
1199
1200 if ((base->len == chk->len) && memcmp(base_name + base->beg, bam_get_qname(chk->b) + chk->beg, base->len) != 0)
1201 break;
1202 }
1203
1204 while (curr < end_name_match) {
1205 size_t count = curr;
1206 check_t *current = &list->c[curr];
1207 int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP);
1208
1209 while (++count < end_name_match && (list->c[count].x - current->x <= param->opt_dist)) {
1210 // while close enough along the x coordinate
1211 check_t *chk = &list->c[count];
1212
1213 if (current->opt && chk->opt)
1214 continue;
1215
1216 long ydiff;
1217
1218 if (current->y > chk->y) {
1219 ydiff = current->y - chk->y;
1220 } else {
1221 ydiff = chk->y - current->y;
1222 }
1223
1224 if (ydiff > param->opt_dist)
1225 continue;
1226
1227 // optical duplicates
1228 int chk_dup = 0;
1229 int chk_paired = (chk->b->core.flag & BAM_FPAIRED) && !(chk->b->core.flag & BAM_FMUNMAP);
1230
1231 if (current_paired != chk_paired) {
1232 if (!chk_paired) {
1233 // chk is single vs pair, this is a dup.
1234 chk_dup = 1;
1235 }
1236 } else {
1237 // do it by scores
1238 int64_t cur_score, chk_score;
1239
1240 if ((current->b->core.flag & BAM_FQCFAIL) != (chk->b->core.flag & BAM_FQCFAIL)) {
1241 if (current->b->core.flag & BAM_FQCFAIL) {
1242 cur_score = 0;
1243 chk_score = 1;
1244 } else {
1245 cur_score = 1;
1246 chk_score = 0;
1247 }
1248 } else {
1249 cur_score = current->score;
1250 chk_score = chk->score;
1251
1252 if (current_paired) {
1253 // they are pairs so add mate scores.
1254 chk_score += chk->mate_score;
1255 cur_score += current->mate_score;
1256 }
1257 }
1258
1259 if (cur_score == chk_score) {
1260 if (strcmp(bam_get_qname(chk->b), bam_get_qname(current->b)) < 0) {
1261 chk_score++;
1262 } else {
1263 chk_score--;
1264 }
1265 }
1266
1267 if (cur_score > chk_score) {
1268 chk_dup = 1;
1269 }
1270 }
1271
1272 if (chk_dup) {
1273 // the duplicate is the optical duplicate
1274 if (!chk->opt) { // only change if not already an optical duplicate
1275 if (optical_retag(param, dup_hash, chk->b, chk_paired, stats)) {
1276 ret = -1;
1277 goto fail;
1278 }
1279
1280 chk->opt = 1;
1281 }
1282 } else {
1283 if (!current->opt) {
1284 if (optical_retag(param, dup_hash, current->b, current_paired, stats)) {
1285 ret = -1;
1286 goto fail;
1287 }
1288
1289 current->opt = 1;
1290 }
1291 }
1292 }
1293
1294 curr++;
1295 }
1296 }
1297
1298 fail:
1299 return ret;
1300 }
1301
1302
1303 /* Where there is more than one duplicate go down the list and check for optical duplicates and change
1304 do tags (where used) to point to original (non-duplicate) read. */
1305 static int find_duplicate_chains(md_param_t *param, read_queue_t *in_read , khash_t(duplicates) *dup_hash, check_list_t *dup_list,
1306 long *warn, stats_block_t *stats) {
1307 int ret = 0;
1308
1309 while (in_read->original) in_read = in_read->original;
1310
1311 // check against the original for tagging and optical duplication
1312 if ((ret = check_chain_against_original(param, dup_hash, in_read, dup_list, warn, stats + in_read->read_group))) {
1313 if (ret < 0) { // real error
1314 ret = -1;
1315 } else { // coordinate decoding error
1316 ret = 0;
1317 }
1318 } else {
1319 // check the rest of the duplicates against each other for optical duplication
1320 if (param->opt_dist && check_duplicate_chain(param, dup_hash, dup_list, warn, stats + in_read->read_group)) {
1321 ret = -1;
1322 }
1323 }
1324
1325 return ret;
1326 }
1327
1328
1329 /*
1330 Function to use when estimating library size.
1331
1332 This is based on an approximate formula for the coverage of a set
1333 obtained after sampling it a given number of times with replacement.
1334
1335 x = number of items in the set (the number of unique fragments in the library)
1336
1337 c = number of unique items (unique read pairs observed)
1338
1339 n = number of items samples (total number of read pairs)
1340
1341 c and n are known; x is unknown.
1342
1343 As n -> infinity, the coverage (c/x) can be given as:
1344
1345 c / x = 1 - exp(-n / x) (see https://math.stackexchange.com/questions/32800)
1346
1347 This needs to be solved for x, so it is rearranged to put both terms on the
1348 left side and estimate_library_size() finds a value of x which gives a
1349 result of zero (or as close as it can get).
1350 */
1351 static inline double coverage_equation(double x, double c, double n) {
1352 return c / x - 1 + exp(-n / x);
1353 }
1354
1355
1356 /* estimate the library size, based on the Picard code in DuplicationMetrics.java*/
1357 static unsigned long estimate_library_size(unsigned long paired_reads, unsigned long paired_duplicate_reads, unsigned long optical) {
1358 unsigned long estimated_size = 0;
1359 unsigned long non_optical_pairs = (paired_reads - optical) / 2;
1360 unsigned long unique_pairs = (paired_reads - paired_duplicate_reads) / 2;
1361 unsigned long duplicate_pairs = (paired_duplicate_reads - optical) / 2;
1362
1363 if ((non_optical_pairs && duplicate_pairs && unique_pairs) && (non_optical_pairs > duplicate_pairs)) {
1364 double m = 1;
1365 double M = 100;
1366 int i;
1367
1368 if (coverage_equation(m * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) < 0) {
1369 print_error("markdup", "warning, unable to calculate estimated library size.\n");
1370 return estimated_size;
1371 }
1372
1373 while (coverage_equation(M * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) > 0) {
1374 M *= 10;
1375 }
1376
1377 for (i = 0; i < 40; i++) {
1378 double r = (m + M) / 2;
1379 double u = coverage_equation(r * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs);
1380
1381 if (u > 0) {
1382 m = r;
1383 } else if (u < 0) {
1384 M = r;
1385 } else {
1386 break;
1387 }
1388 }
1389
1390 estimated_size = (unsigned long)(unique_pairs * (m + M) / 2);
1391 } else {
1392 print_error("markdup", "warning, unable to calculate estimated library size."
1393 " Read pairs %ld should be greater than duplicate pairs %ld,"
1394 " which should both be non zero.\n",
1395 non_optical_pairs, duplicate_pairs);
1396 }
1397
1398 return estimated_size;
1399 }
1400
1401
1402 static void write_stats(FILE *fp, const char *title, const char *title_con, stats_block_t *stats) {
1403 unsigned long els;
1404
1405 els = estimate_library_size(stats->pair, stats->duplicate, stats->optical);
1406
1407 if (title) {
1408 fprintf(fp, "%s%s\n", title, title_con);
1409 }
1410
1411 fprintf(fp,
1412 "READ: %ld\n"
1413 "WRITTEN: %ld\n"
1414 "EXCLUDED: %ld\n"
1415 "EXAMINED: %ld\n"
1416 "PAIRED: %ld\n"
1417 "SINGLE: %ld\n"
1418 "DUPLICATE PAIR: %ld\n"
1419 "DUPLICATE SINGLE: %ld\n"
1420 "DUPLICATE PAIR OPTICAL: %ld\n"
1421 "DUPLICATE SINGLE OPTICAL: %ld\n"
1422 "DUPLICATE NON PRIMARY: %ld\n"
1423 "DUPLICATE NON PRIMARY OPTICAL: %ld\n"
1424 "DUPLICATE PRIMARY TOTAL: %ld\n"
1425 "DUPLICATE TOTAL: %ld\n"
1426 "ESTIMATED_LIBRARY_SIZE: %ld\n", stats->reading, stats->writing, stats->excluded, stats->examined, stats->pair, stats->single,
1427 stats->duplicate, stats->single_dup, stats->optical, stats->single_optical, stats->np_duplicate, stats->np_opt_duplicate,
1428 stats->single_dup + stats->duplicate, stats->single_dup + stats->duplicate + stats->np_duplicate, els);
1429 }
1430
1431
1432 static void write_json_stats(FILE *fp, const char *offset, const char *group_name, stats_block_t *stats, const char *end) {
1433 unsigned long els;
1434
1435 els = estimate_library_size(stats->pair, stats->duplicate, stats->optical);
1436
1437 if (group_name) {
1438 fprintf(fp, "%s\"READ GROUP\": \"%s\",\n", offset, group_name);
1439 }
1440
1441 fprintf(fp, "%s\"READ\": %ld,\n", offset, stats->reading);
1442 fprintf(fp, "%s\"WRITTEN\": %ld,\n", offset, stats->writing);
1443 fprintf(fp, "%s\"EXCLUDED\": %ld,\n", offset, stats->excluded);
1444 fprintf(fp, "%s\"EXAMINED\": %ld,\n", offset, stats->examined);
1445 fprintf(fp, "%s\"PAIRED\": %ld,\n", offset, stats->pair);
1446 fprintf(fp, "%s\"SINGLE\": %ld,\n", offset, stats->single);
1447 fprintf(fp, "%s\"DUPLICATE PAIR\": %ld,\n", offset, stats->duplicate);
1448 fprintf(fp, "%s\"DUPLICATE SINGLE\": %ld,\n", offset, stats->single_dup);
1449 fprintf(fp, "%s\"DUPLICATE PAIR OPTICAL\": %ld,\n", offset, stats->optical);
1450 fprintf(fp, "%s\"DUPLICATE SINGLE OPTICAL\": %ld,\n", offset, stats->single_optical);
1451 fprintf(fp, "%s\"DUPLICATE NON PRIMARY\": %ld,\n", offset, stats->np_duplicate);
1452 fprintf(fp, "%s\"DUPLICATE NON PRIMARY OPTICAL\": %ld,\n", offset, stats->np_opt_duplicate);
1453 fprintf(fp, "%s\"DUPLICATE PRIMARY TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate);
1454 fprintf(fp, "%s\"DUPLICATE TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate + stats->np_duplicate);
1455 fprintf(fp, "%s\"ESTIMATED_LIBRARY_SIZE\": %ld", offset, els);
1456
1457 if (end) {
1458 fprintf(fp, "%s", end);
1459 }
1460 }
1461
1462
1463 /* Compare the reads near each other (coordinate sorted) and try to spot the duplicates.
1464 Generally the highest quality scoring is chosen as the original and all others the duplicates.
1465 The score is based on the sum of the quality values (<= 15) of the read and its mate (if any).
1466 While single reads are compared to only one read of a pair, the pair will chosen as the original.
1467 The comparison is done on position and orientation, see above for details.
1468
1469 Marking the supplementary reads of a duplicate as also duplicates takes an extra file read/write
1470 step. This is because the duplicate can occur before the primary read.*/
1471
1472 static int bam_mark_duplicates(md_param_t *param) {
1473 bam_hdr_t *header = NULL;
1474 khiter_t k;
1475 khash_t(reads) *pair_hash = kh_init(reads);
1476 khash_t(reads) *single_hash = kh_init(reads);
1477 klist_t(read_queue) *read_buffer = kl_init(read_queue);
1478 kliter_t(read_queue) *rq;
1479 khash_t(duplicates) *dup_hash = kh_init(duplicates);
1480 khash_t(read_groups) *rg_hash = kh_init(read_groups);
1481 int32_t prev_tid;
1482 hts_pos_t prev_coord;
1483 read_queue_t *in_read;
1484 int ret;
1485 stats_block_t *stats, *stat_array = NULL;
1486 int num_groups = 0;
1487 long opt_warnings = 0, bc_warnings = 0;
1488 tmp_file_t temp;
1489 char *idx_fn = NULL;
1490 int exclude = 0;
1491 check_list_t dup_list = {NULL, 0, 0};
1492
1493 if (!pair_hash || !single_hash || !read_buffer || !dup_hash || !rg_hash) {
1494 print_error("markdup", "error, unable to allocate memory to initialise structures.\n");
1495 goto fail;
1496 }
1497
1498 if ((header = sam_hdr_read(param->in)) == NULL) {
1499 print_error("markdup", "error reading header\n");
1500 goto fail;
1501 }
1502
1503 // accept unknown, unsorted or coordinate sort order, but error on queryname sorted.
1504 // only really works on coordinate sorted files.
1505 kstring_t str = KS_INITIALIZE;
1506 if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "queryname")) {
1507 print_error("markdup", "error, queryname sorted, must be sorted by coordinate.\n");
1508 ks_free(&str);
1509 goto fail;
1510 }
1511 ks_free(&str);
1512
1513 if (!param->no_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(),
1514 param->arg_list ? "CL" : NULL,
1515 param->arg_list ? param->arg_list : NULL,
1516 NULL) != 0) {
1517 print_error("markdup", "warning, unable to add @PG line to header.\n");
1518 }
1519
1520 if (sam_hdr_write(param->out, header) < 0) {
1521 print_error("markdup", "error writing header.\n");
1522 goto fail;
1523 }
1524 if (param->write_index) {
1525 if (!(idx_fn = auto_index(param->out, param->out_fn, header)))
1526 goto fail;
1527 }
1528
1529 if (param->read_groups) {
1530 num_groups = sam_hdr_count_lines(header, "RG");
1531 int g_ret = 0;
1532
1533 if (num_groups > 0) {
1534 int i;
1535
1536 for (i = 0; i < num_groups; i++) {
1537 const char *rg_key;
1538 khiter_t rg;
1539
1540 rg_key = sam_hdr_line_name(header, "RG", i);
1541
1542 if (rg_key) {
1543 rg = kh_get(read_groups, rg_hash, rg_key);
1544
1545 if (rg == kh_end(rg_hash)) { // new entry
1546 rg = kh_put(read_groups, rg_hash, rg_key, &g_ret);
1547
1548 if (g_ret > 0) {
1549 kh_value(rg_hash, rg) = i + 1;
1550 } else {
1551 print_error("markdup", "error, unable to populate read group ids. "
1552 "Read groups will not be used\n");
1553 g_ret = -1;
1554 break;
1555 }
1556 } else {
1557 print_error("markdup", "error, duplicate read group ids %s."
1558 "Read groups will not be used\n", rg_key);
1559 g_ret = -1;
1560 break;
1561 }
1562 } else {
1563 print_error("markdup", "error, Unable to retrieve read group at position %d."
1564 "Read groups will not be used\n", i);
1565 g_ret = -1;
1566 break;
1567 }
1568 }
1569 } else {
1570 print_error("markdup", "error, no read groups found.\n");
1571 g_ret = -1;
1572 }
1573
1574 if (g_ret < 0) {
1575 print_error("markdup", "error, read groups will not be used.\n");
1576 param->read_groups = 0;
1577 num_groups = 0;
1578 }
1579 }
1580
1581 // stat_array[0] will be for ungrouped reads
1582 stat_array = calloc(num_groups + 1, sizeof(stats_block_t));
1583
1584 if (stat_array == NULL) {
1585 print_error("markdup", "error, unable to allocate memory for stats.\n");
1586 goto fail;
1587 }
1588
1589 // used for coordinate order checks
1590 prev_tid = prev_coord = 0;
1591
1592 // get the buffer going
1593 in_read = kl_pushp(read_queue, read_buffer);
1594 if (!in_read) {
1595 print_error("markdup", "error, unable to allocate memory to hold reads.\n");
1596 goto fail;
1597 }
1598
1599 // handling supplementary reads needs a temporary file
1600 if (param->supp) {
1601 if (tmp_file_open_write(&temp, param->prefix, 1)) {
1602 print_error("markdup", "error, unable to open tmp file %s.\n", param->prefix);
1603 goto fail;
1604 }
1605 }
1606
1607 if ((in_read->b = bam_init1()) == NULL) {
1608 print_error("markdup", "error, unable to allocate memory for alignment.\n");
1609 goto fail;
1610 }
1611
1612 if (param->check_chain && !(param->tag || param->opt_dist))
1613 param->check_chain = 0;
1614
1615 if (param->check_chain) {
1616 dup_list.size = 128;
1617 dup_list.c = NULL;
1618
1619 if ((dup_list.c = malloc(dup_list.size * sizeof(check_t))) == NULL) {
1620 print_error("markdup", "error, unable to allocate memory for dup_list.\n");
1621 goto fail;
1622 }
1623 }
1624
1625 while ((ret = sam_read1(param->in, header, in_read->b)) >= 0) {
1626
1627 // do some basic coordinate order checks
1628 if (in_read->b->core.tid >= 0) { // -1 for unmapped reads
1629 if (in_read->b->core.tid < prev_tid ||
1630 ((in_read->b->core.tid == prev_tid) && (in_read->b->core.pos < prev_coord))) {
1631 print_error("markdup", "error, not in coordinate sorted order.\n");
1632 goto fail;
1633 }
1634 }
1635
1636 prev_coord = in_read->pos = in_read->b->core.pos;
1637 prev_tid = in_read->b->core.tid;
1638 in_read->pair_key.single = 1;
1639 in_read->single_key.single = 0;
1640 in_read->duplicate = NULL;
1641 in_read->original = NULL;
1642 in_read->dup_checked = 0;
1643 in_read->read_group = 0;
1644 in_read->dc = 1;
1645
1646 if (param->read_groups) {
1647 uint8_t *data;
1648 char *rg;
1649
1650 if ((data = bam_aux_get(in_read->b, "RG"))) {
1651 if ((rg = bam_aux2Z(data))) {
1652 khiter_t r;
1653
1654 r = kh_get(read_groups, rg_hash, rg);
1655
1656 if (r != kh_end(rg_hash)) {
1657 in_read->read_group = kh_value(rg_hash, r);
1658 }
1659 }
1660 }
1661 }
1662
1663 stats = stat_array + in_read->read_group;
1664
1665 stats->reading++;
1666
1667 if (param->clear && (in_read->b->core.flag & BAM_FDUP)) {
1668 uint8_t *data;
1669
1670 in_read->b->core.flag ^= BAM_FDUP;
1671
1672 if ((data = bam_aux_get(in_read->b, "dt")) != NULL) {
1673 bam_aux_del(in_read->b, data);
1674 }
1675
1676 if ((data = bam_aux_get(in_read->b, "do")) != NULL) {
1677 bam_aux_del(in_read->b, data);
1678 }
1679 }
1680
1681 if (param->include_fails) {
1682 exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP);
1683 } else {
1684 exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP | BAM_FQCFAIL);
1685 }
1686
1687 // read must not be secondary, supplementary, unmapped or (possibly) failed QC
1688 if (!(in_read->b->core.flag & exclude)) {
1689 stats->examined++;
1690
1691
1692 // look at the pairs first
1693 if ((in_read->b->core.flag & BAM_FPAIRED) && !(in_read->b->core.flag & BAM_FMUNMAP)) {
1694 int ret, mate_tmp;
1695 key_data_t pair_key;
1696 key_data_t single_key;
1697 in_hash_t *bp;
1698
1699 if (make_pair_key(param, &pair_key, in_read->b, in_read->read_group, &bc_warnings)) {
1700 print_error("markdup", "error, unable to assign pair hash key.\n");
1701 goto fail;
1702 }
1703
1704 make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings);
1705
1706 stats->pair++;
1707 in_read->pos = single_key.this_coord; // cigar/orientation modified pos
1708
1709 // put in singles hash for checking against non paired reads
1710 k = kh_put(reads, single_hash, single_key, &ret);
1711
1712 if (ret > 0) { // new
1713 // add to single duplicate hash
1714 bp = &kh_val(single_hash, k);
1715 bp->p = in_read;
1716 in_read->single_key = single_key;
1717 } else if (ret == 0) { // exists
1718 // look at singles only for duplication marking
1719 bp = &kh_val(single_hash, k);
1720
1721 if (!(bp->p->b->core.flag & BAM_FPAIRED) || (bp->p->b->core.flag & BAM_FMUNMAP)) {
1722 // singleton will always be marked duplicate even if
1723 // scores more than one read of the pair
1724 bam1_t *dup = bp->p->b;
1725
1726 if (param->check_chain) {
1727 in_read->duplicate = bp->p;
1728 bp->p->original = in_read;
1729 }
1730
1731 bp->p = in_read;
1732 bp->p->dc += 1;
1733
1734 if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings))
1735 goto fail;
1736
1737 stats->single_dup++;
1738 }
1739 } else {
1740 print_error("markdup", "error, single hashing failure for paired read.\n");
1741 goto fail;
1742 }
1743
1744 // now do the pair
1745 k = kh_put(reads, pair_hash, pair_key, &ret);
1746
1747 if (ret > 0) { // new
1748 // add to the pair hash
1749 bp = &kh_val(pair_hash, k);
1750 bp->p = in_read;
1751 in_read->pair_key = pair_key;
1752 } else if (ret == 0) {
1753 int64_t old_score, new_score, tie_add = 0;
1754 bam1_t *dup = NULL;
1755
1756 bp = &kh_val(pair_hash, k);
1757
1758 if ((bp->p->b->core.flag & BAM_FQCFAIL) != (in_read->b->core.flag & BAM_FQCFAIL)) {
1759 if (bp->p->b->core.flag & BAM_FQCFAIL) {
1760 old_score = 0;
1761 new_score = 1;
1762 } else {
1763 old_score = 1;
1764 new_score = 0;
1765 }
1766 } else {
1767 if ((mate_tmp = get_mate_score(bp->p->b)) == -1) {
1768 print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1769 goto fail;
1770 } else {
1771 old_score = calc_score(bp->p->b) + mate_tmp;
1772 }
1773
1774 if ((mate_tmp = get_mate_score(in_read->b)) == -1) {
1775 print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1776 goto fail;
1777 } else {
1778 new_score = calc_score(in_read->b) + mate_tmp;
1779 }
1780 }
1781
1782 // choose the highest score as the original
1783 // and add it to the pair hash, mark the other as duplicate
1784
1785 if (new_score == old_score) {
1786 if (strcmp(bam_get_qname(in_read->b), bam_get_qname(bp->p->b)) < 0) {
1787 tie_add = 1;
1788 } else {
1789 tie_add = -1;
1790 }
1791 }
1792
1793 if (new_score + tie_add > old_score) { // swap reads
1794 dup = bp->p->b;
1795 in_read->dc += bp->p->dc;
1796
1797 if (param->check_chain) {
1798
1799 if (in_read->duplicate) {
1800 read_queue_t *current = in_read->duplicate;
1801
1802 while (current->duplicate) {
1803 current = current->duplicate;
1804 }
1805
1806 current->duplicate = bp->p;
1807 } else {
1808 in_read->duplicate = bp->p;
1809 }
1810
1811 bp->p->original = in_read;
1812 }
1813
1814 bp->p = in_read;
1815 } else {
1816 if (param->check_chain) {
1817 if (bp->p->duplicate) {
1818 if (in_read->duplicate) {
1819 read_queue_t *current = bp->p->duplicate;
1820
1821 while (current->duplicate) {
1822 current = current->duplicate;
1823 }
1824
1825 current->duplicate = in_read->duplicate;
1826 }
1827
1828 in_read->duplicate = bp->p->duplicate;
1829 }
1830
1831 bp->p->duplicate = in_read;
1832 in_read->original = bp->p;
1833 }
1834
1835 dup = in_read->b;
1836 bp->p->dc += 1;
1837 }
1838
1839 if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->optical, &opt_warnings))
1840 goto fail;
1841
1842 stats->duplicate++;
1843 } else {
1844 print_error("markdup", "error, pair hashing failure.\n");
1845 goto fail;
1846 }
1847 } else { // do the single (or effectively single) reads
1848 int ret;
1849 key_data_t single_key;
1850 in_hash_t *bp;
1851
1852 make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings);
1853
1854 stats->single++;
1855 in_read->pos = single_key.this_coord; // cigar/orientation modified pos
1856
1857 k = kh_put(reads, single_hash, single_key, &ret);
1858
1859 if (ret > 0) { // new
1860 bp = &kh_val(single_hash, k);
1861 bp->p = in_read;
1862 in_read->single_key = single_key;
1863 } else if (ret == 0) { // exists
1864 bp = &kh_val(single_hash, k);
1865
1866 if ((bp->p->b->core.flag & BAM_FPAIRED) && !(bp->p->b->core.flag & BAM_FMUNMAP)) {
1867 // if matched against one of a pair just mark as duplicate
1868
1869 if (param->check_chain) {
1870 if (bp->p->duplicate) {
1871 in_read->duplicate = bp->p->duplicate;
1872 }
1873
1874 bp->p->duplicate = in_read;
1875 in_read->original = bp->p;
1876 }
1877
1878 bp->p->dc += 1;
1879
1880 if (mark_duplicates(param, dup_hash, bp->p->b, in_read->b, in_read->read_group, &stats->single_optical, &opt_warnings))
1881 goto fail;
1882
1883 } else {
1884 int64_t old_score, new_score;
1885 bam1_t *dup = NULL;
1886
1887 old_score = calc_score(bp->p->b);
1888 new_score = calc_score(in_read->b);
1889
1890 // choose the highest score as the original, add it
1891 // to the single hash and mark the other as duplicate
1892 if (new_score > old_score) { // swap reads
1893 dup = bp->p->b;
1894 in_read->dc += bp->p->dc;
1895
1896 if (param->check_chain) {
1897 in_read->duplicate = bp->p;
1898 bp->p->original = in_read;
1899 }
1900
1901 bp->p = in_read;
1902 } else {
1903 if (param->check_chain) {
1904 if (bp->p->duplicate) {
1905 in_read->duplicate = bp->p->duplicate;
1906 }
1907
1908 bp->p->duplicate = in_read;
1909 in_read->original = bp->p;
1910 }
1911
1912 bp->p->dc += 1;
1913 dup = in_read->b;
1914 }
1915
1916 if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings))
1917 goto fail;
1918 }
1919
1920 stats->single_dup++;
1921 } else {
1922 print_error("markdup", "error, single hashing failure for single read.\n");
1923 goto fail;
1924 }
1925 }
1926 } else {
1927 stats->excluded++;
1928 }
1929
1930 // loop through the stored reads and write out those we
1931 // no longer need
1932 rq = kl_begin(read_buffer);
1933 while (rq != kl_end(read_buffer)) {
1934 in_read = &kl_val(rq);
1935
1936 /* keep a moving window of reads based on coordinates and max read length. Any unaligned reads
1937 should just be written as they cannot be matched as duplicates. */
1938 if (in_read->pos + param->max_length > prev_coord && in_read->b->core.tid == prev_tid && (prev_tid != -1 || prev_coord != -1)) {
1939 break;
1940 }
1941
1942 if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) {
1943 if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) {
1944 print_error("markdup", "error, duplicate checking failed.\n");
1945 goto fail;
1946 }
1947 }
1948
1949 if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) {
1950 if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
1951 bam_aux_update_int(in_read->b, "dc", in_read->dc);
1952 }
1953 if (param->supp) {
1954 if (tmp_file_write(&temp, in_read->b)) {
1955 print_error("markdup", "error, writing temp output failed.\n");
1956 goto fail;
1957 }
1958 } else {
1959 if (sam_write1(param->out, header, in_read->b) < 0) {
1960 print_error("markdup", "error, writing output failed.\n");
1961 goto fail;
1962 }
1963 }
1964
1965 stat_array[in_read->read_group].writing++;
1966 }
1967
1968 // remove from hash
1969 if (in_read->pair_key.single == 0) {
1970 k = kh_get(reads, pair_hash, in_read->pair_key);
1971 kh_del(reads, pair_hash, k);
1972 }
1973
1974 if (in_read->single_key.single == 1) {
1975 k = kh_get(reads, single_hash, in_read->single_key);
1976 kh_del(reads, single_hash, k);
1977 }
1978
1979 kl_shift(read_queue, read_buffer, NULL);
1980 bam_destroy1(in_read->b);
1981 rq = kl_begin(read_buffer);
1982 }
1983
1984 // set the next one up for reading
1985 in_read = kl_pushp(read_queue, read_buffer);
1986 if (!in_read) {
1987 print_error("markdup", "error, unable to allocate memory for read in queue.\n");
1988 goto fail;
1989 }
1990
1991 if ((in_read->b = bam_init1()) == NULL) {
1992 print_error("markdup", "error, unable to allocate memory for alignment.\n");
1993 goto fail;
1994 }
1995 }
1996
1997 if (ret < -1) {
1998 print_error("markdup", "error, truncated input file.\n");
1999 goto fail;
2000 }
2001
2002 // write out the end of the list
2003 rq = kl_begin(read_buffer);
2004 while (rq != kl_end(read_buffer)) {
2005 in_read = &kl_val(rq);
2006
2007 if (bam_get_qname(in_read->b)) { // last entry will be blank
2008 if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) {
2009 if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) {
2010 print_error("markdup", "error, duplicate checking failed.\n");
2011 goto fail;
2012 }
2013 }
2014
2015 if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) {
2016 if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
2017 bam_aux_update_int(in_read->b, "dc", in_read->dc);
2018 }
2019
2020 if (param->supp) {
2021 if (tmp_file_write(&temp, in_read->b)) {
2022 print_error("markdup", "error, writing temp output failed on final write.\n");
2023 goto fail;
2024 }
2025 } else {
2026 if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
2027 bam_aux_update_int(in_read->b, "dc", in_read->dc);
2028 }
2029
2030 if (sam_write1(param->out, header, in_read->b) < 0) {
2031 print_error("markdup", "error, writing output failed on final write.\n");
2032 goto fail;
2033 }
2034 }
2035
2036 stat_array[in_read->read_group].writing++;
2037 }
2038 }
2039
2040 kl_shift(read_queue, read_buffer, NULL);
2041 bam_destroy1(in_read->b);
2042 rq = kl_begin(read_buffer);
2043 }
2044
2045 if (param->supp) {
2046 bam1_t *b;
2047
2048 if (tmp_file_end_write(&temp)) {
2049 print_error("markdup", "error, unable to end tmp writing.\n");
2050 goto fail;
2051 }
2052
2053 // read data from temp file and mark duplicate supplementary alignments
2054
2055 if (tmp_file_begin_read(&temp)) {
2056 goto fail;
2057 }
2058
2059 b = bam_init1();
2060
2061 while ((ret = tmp_file_read(&temp, b)) > 0) {
2062
2063 if ((b->core.flag & BAM_FSUPPLEMENTARY) || (b->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FSECONDARY)) {
2064
2065 k = kh_get(duplicates, dup_hash, bam_get_qname(b));
2066
2067 if (k != kh_end(dup_hash)) {
2068
2069 b->core.flag |= BAM_FDUP;
2070 stat_array[kh_val(dup_hash, k).read_group].np_duplicate++;
2071
2072 if (param->tag && kh_val(dup_hash, k).name) {
2073 if (bam_aux_update_str(b, "do", strlen(kh_val(dup_hash, k).name) + 1, (char*)kh_val(dup_hash, k).name)) {
2074 print_error("markdup", "error, unable to append supplementary 'do' tag.\n");
2075 goto fail;
2076 }
2077 }
2078
2079 if (param->opt_dist) {
2080 if (kh_val(dup_hash, k).type) {
2081 bam_aux_update_str(b, "dt", 3, "SQ");
2082 stat_array[kh_val(dup_hash, k).read_group].np_opt_duplicate++;
2083 } else {
2084 bam_aux_update_str(b, "dt", 3, "LB");
2085 }
2086 }
2087 }
2088 }
2089
2090 if (!param->remove_dups || !(b->core.flag & BAM_FDUP)) {
2091 if (param->dc && (b->core.flag & BAM_FDUP)) {
2092 uint8_t* data = bam_aux_get(b, "dc");
2093 if(data) bam_aux_del(b, data);
2094 }
2095 if (sam_write1(param->out, header, b) < 0) {
2096 print_error("markdup", "error, writing final output failed.\n");
2097 goto fail;
2098 }
2099 }
2100 }
2101
2102 if (ret == -1) {
2103 print_error("markdup", "error, failed to read tmp file.\n");
2104 goto fail;
2105 }
2106
2107 for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) {
2108 if (kh_exist(dup_hash, k)) {
2109 free(kh_val(dup_hash, k).name);
2110 free((char *)kh_key(dup_hash, k));
2111 kh_key(dup_hash, k) = NULL;
2112 }
2113 }
2114
2115 tmp_file_destroy(&temp);
2116 bam_destroy1(b);
2117 }
2118
2119 if (opt_warnings) {
2120 print_error("markdup", "warning, number of failed attempts to get coordinates from read names = %ld\n",
2121 opt_warnings);
2122 }
2123
2124 if (bc_warnings) {
2125 print_error("markdup", "warning, number of failed attempts to get barcodes = %ld\n", bc_warnings);
2126 }
2127
2128 if (param->do_stats) {
2129 FILE *fp;
2130 int file_open = 0;
2131 stats_block_t total;
2132 int i;
2133
2134 if (param->stats_file) {
2135 if (NULL == (fp = fopen(param->stats_file, "w"))) {
2136 print_error("markdup", "warning, cannot write stats to %s.\n", param->stats_file);
2137 fp = samtools_stderr;
2138 } else {
2139 file_open = 1;
2140 }
2141 } else {
2142 fp = samtools_stderr;
2143 }
2144
2145 total = stat_array[0];
2146
2147 if (param->read_groups) {
2148 for (i = 1; i <= num_groups; i++) {
2149 total.reading += stat_array[i].reading;
2150 total.writing += stat_array[i].writing;
2151 total.excluded += stat_array[i].excluded;
2152 total.duplicate += stat_array[i].duplicate;
2153 total.single += stat_array[i].single;
2154 total.pair += stat_array[i].pair;
2155 total.single_dup += stat_array[i].single_dup;
2156 total.examined += stat_array[i].examined;
2157 total.optical += stat_array[i].optical;
2158 total.single_optical += stat_array[i].single_optical;
2159 total.np_duplicate += stat_array[i].np_duplicate;
2160 total.np_opt_duplicate += stat_array[i].np_opt_duplicate;
2161 }
2162 }
2163
2164 if (!param->json) {
2165 write_stats(fp, "COMMAND: ", param->arg_list, &total);
2166 fprintf(fp, "\n");
2167
2168 if (param->read_groups) {
2169 if (stat_array[0].reading) {
2170 write_stats(fp, "READ GROUP: ", "ungrouped", stat_array);
2171 fprintf(fp, "\n");
2172 }
2173
2174 for (i = 0; i < num_groups; i++) {
2175 write_stats(fp, "READ GROUP: ", sam_hdr_line_name(header, "RG", i), stat_array + i + 1);
2176 fprintf(fp, "\n");
2177 }
2178 }
2179 } else {
2180 char space4[] = " ";
2181 char space8[] = " ";
2182 char space12[] = " ";
2183
2184 fprintf(fp, "{\n");
2185 fprintf(fp, "%s\"COMMAND\": \"%s\",\n", space4, param->arg_list);
2186 write_json_stats(fp, space4, NULL, &total, param->read_groups ? ",\n" : "\n");
2187
2188 if (param->read_groups) {
2189 fprintf(fp, "%s\"READ GROUPS\": [\n", space4);
2190
2191 if (stat_array[0].reading) {
2192 fprintf(fp, "%s{\n", space8);
2193 write_json_stats(fp, space12, "ungrouped", stat_array, "\n");
2194 fprintf(fp, "%s},\n", space8);
2195 }
2196
2197 for (i = 0; i < num_groups; i++) {
2198 fprintf(fp, "%s{\n", space8);
2199
2200 write_json_stats(fp, space12, sam_hdr_line_name(header, "RG", i), stat_array + i + 1, "\n");
2201
2202 if (i < num_groups -1 ) {
2203 fprintf(fp, "%s},\n", space8);
2204 } else {
2205 fprintf(fp, "%s}\n", space8);
2206 }
2207 }
2208
2209 fprintf(fp, "%s]\n", space4);
2210 }
2211
2212 fprintf(fp, "}\n");
2213 }
2214
2215 if (file_open) {
2216 fclose(fp);
2217 }
2218 }
2219
2220 if (param->write_index) {
2221 if (sam_idx_save(param->out) < 0) {
2222 print_error_errno("markdup", "error, writing index failed");
2223 goto fail;
2224 }
2225 }
2226
2227 if (param->check_chain && (param->tag || param->opt_dist))
2228 free(dup_list.c);
2229
2230 free(idx_fn);
2231 free(stat_array);
2232 kh_destroy(reads, pair_hash);
2233 kh_destroy(reads, single_hash);
2234 kl_destroy(read_queue, read_buffer);
2235 kh_destroy(duplicates, dup_hash);
2236 kh_destroy(read_groups, rg_hash);
2237 sam_hdr_destroy(header);
2238
2239 return 0;
2240
2241 fail:
2242 for (rq = kl_begin(read_buffer); rq != kl_end(read_buffer); rq = kl_next(rq))
2243 bam_destroy1(kl_val(rq).b);
2244 kl_destroy(read_queue, read_buffer);
2245
2246 for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) {
2247 if (kh_exist(dup_hash, k)) {
2248 free((char *)kh_key(dup_hash, k));
2249 }
2250 }
2251 kh_destroy(duplicates, dup_hash);
2252 kh_destroy(read_groups, rg_hash);
2253
2254 if (param->check_chain && (param->tag || param->opt_dist))
2255 free(dup_list.c);
2256
2257 free(idx_fn);
2258 free(stat_array);
2259 kh_destroy(reads, pair_hash);
2260 kh_destroy(reads, single_hash);
2261 sam_hdr_destroy(header);
2262 return 1;
2263 }
2264
2265
2266 static int markdup_usage(void) {
2267 fprintf(samtools_stderr, "\n");
2268 fprintf(samtools_stderr, "Usage: samtools markdup <input.bam> <output.bam>\n\n");
2269 fprintf(samtools_stderr, "Option: \n");
2270 fprintf(samtools_stderr, " -r Remove duplicate reads\n");
2271 fprintf(samtools_stderr, " -l INT Max read length (default 300 bases)\n");
2272 fprintf(samtools_stderr, " -S Mark supplementary alignments of duplicates as duplicates (slower).\n");
2273 fprintf(samtools_stderr, " -s Report stats.\n");
2274 fprintf(samtools_stderr, " -f NAME Write stats to named file. Implies -s.\n");
2275 fprintf(samtools_stderr, " --json Output stats in JSON. Also implies -s\n");
2276 fprintf(samtools_stderr, " -T PREFIX Write temporary files to PREFIX.samtools.nnnn.nnnn.tmp.\n");
2277 fprintf(samtools_stderr, " -d INT Optical distance (if set, marks with dt tag)\n");
2278 fprintf(samtools_stderr, " -c Clear previous duplicate settings and tags.\n");
2279 fprintf(samtools_stderr, " -m --mode TYPE Duplicate decision method for paired reads.\n"
2280 " TYPE = t measure positions based on template start/end (default).\n"
2281 " s measure positions based on sequence start.\n");
2282 fprintf(samtools_stderr, " -u Output uncompressed data\n");
2283 fprintf(samtools_stderr, " --include-fails Include quality check failed reads.\n");
2284 fprintf(samtools_stderr, " --no-PG Do not add a PG line\n");
2285 fprintf(samtools_stderr, " --no-multi-dup Reduced duplicates of duplicates checking.\n");
2286 fprintf(samtools_stderr, " --read-coords STR Regex for coords from read name.\n");
2287 fprintf(samtools_stderr, " --coords-order STR Order of regex elements. txy (default). With t being a part of\n"
2288 " the read names that must be equal and x/y being coordinates.\n");
2289 fprintf(samtools_stderr, " --barcode-tag STR Use barcode a tag that duplicates much match.\n");
2290 fprintf(samtools_stderr, " --barcode-name Use the UMI/barcode in the read name (eigth colon delimited part).\n");
2291 fprintf(samtools_stderr, " --barcode-rgx STR Regex for barcode in the readname (alternative to --barcode-name).\n");
2292 fprintf(samtools_stderr, " --use-read-groups Use the read group tags in duplicate matching.\n");
2293 fprintf(samtools_stderr, " -t Mark primary duplicates with the name of the original in a \'do\' tag."
2294 " Mainly for information and debugging.\n");
2295 fprintf(samtools_stderr, " --duplicate-count Record the original primary read duplication count(include itself) in a \'dc\' tag.\n");
2296
2297 sam_global_opt_help(samtools_stderr, "-.O..@..");
2298
2299 fprintf(samtools_stderr, "\nThe input file must be coordinate sorted and must have gone"
2300 " through fixmates with the mate scoring option on.\n");
2301
2302 return 1;
2303 }
2304
2305
2306 int bam_markdup(int argc, char **argv) {
2307 int c, ret, bc_name = 0;
2308 char wmode[4] = {'w', 0, 0, 0};
2309 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
2310 htsThreadPool p = {NULL, 0};
2311 kstring_t tmpprefix = {0, 0, NULL};
2312 struct stat st;
2313 unsigned int t;
2314 char *regex = NULL, *bc_regex = NULL;
2315 char *regex_order = "txy";
2316 md_param_t param = {NULL, NULL, NULL, 0, 300, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2317 1, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0};
2318
2319 static const struct option lopts[] = {
2320 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
2321 {"include-fails", no_argument, NULL, 1001},
2322 {"no-PG", no_argument, NULL, 1002},
2323 {"mode", required_argument, NULL, 'm'},
2324 {"no-multi-dup", no_argument, NULL, 1003},
2325 {"read-coords", required_argument, NULL, 1004},
2326 {"coords-order", required_argument, NULL, 1005},
2327 {"barcode-tag", required_argument, NULL, 1006},
2328 {"barcode-name", no_argument, NULL, 1007},
2329 {"barcode-rgx", required_argument, NULL, 1008},
2330 {"use-read-groups", no_argument, NULL, 1009},
2331 {"json", no_argument, NULL, 1010},
2332 {"duplicate-count", no_argument, NULL, 1011},
2333 {NULL, 0, NULL, 0}
2334 };
2335
2336 while ((c = getopt_long(argc, argv, "rsl:StT:O:@:f:d:cm:u", lopts, NULL)) >= 0) {
2337 switch (c) {
2338 case 'r': param.remove_dups = 1; break;
2339 case 'l': param.max_length = atoi(optarg); break;
2340 case 's': param.do_stats = 1; break;
2341 case 'T': kputs(optarg, &tmpprefix); break;
2342 case 'S': param.supp = 1; break;
2343 case 't': param.tag = 1; break;
2344 case 'f': param.stats_file = optarg; param.do_stats = 1; break;
2345 case 'd': param.opt_dist = atoi(optarg); break;
2346 case 'c': param.clear = 1; break;
2347 case 'm':
2348 if (strcmp(optarg, "t") == 0) {
2349 param.mode = MD_MODE_TEMPLATE;
2350 } else if (strcmp(optarg, "s") == 0) {
2351 param.mode = MD_MODE_SEQUENCE;
2352 } else {
2353 print_error("markdup", "error, unknown mode '%s'.\n", optarg);
2354 return markdup_usage();
2355 }
2356
2357 break;
2358 case 'u': wmode[1] = '0'; break;
2359 case 1001: param.include_fails = 1; break;
2360 case 1002: param.no_pg = 1; break;
2361 case 1003: param.check_chain = 0; break;
2362 case 1004: regex = optarg; break;
2363 case 1005: regex_order = optarg; break;
2364 case 1006: param.barcode = optarg; break;
2365 case 1007: bc_name = 1; break;
2366 case 1008: bc_name = 1, bc_regex = optarg; break;
2367 case 1009: param.read_groups = 1; break;
2368 case 1010: param.json = 1; param.do_stats = 1; break;
2369 case 1011: param.dc = 1; break;
2370 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
2371 /* else fall-through */
2372 case '?': return markdup_usage();
2373 }
2374 }
2375
2376 if (optind + 2 > argc)
2377 return markdup_usage();
2378
2379 if (param.barcode && bc_name) {
2380 print_error("markdup", "error, cannot specify --barcode-tag and "
2381 "--barcode-name (or --barcode-rgx) at same time.\n");
2382 return 1;
2383 }
2384
2385 if (param.opt_dist < 0) param.opt_dist = 0;
2386 if (param.max_length < 0) param.max_length = 300;
2387
2388 if (regex) {
2389 int result;
2390
2391 // set the order the elements of the regex are assigned to.
2392 // x and y being coordinates, t being any other important part of the read
2393 // e.g. tile and lane
2394 // x and y order does not matter as long as it is consistent
2395
2396 if ((strncmp(regex_order, "txy", 3) == 0) || (strncmp(regex_order, "tyx", 3) == 0)) {
2397 param.rgx_t = 1;
2398 param.rgx_x = 2;
2399 param.rgx_y = 3;
2400 } else if ((strncmp(regex_order, "xyt", 3) == 0) || (strncmp(regex_order, "yxt", 3) == 0)) {
2401 param.rgx_x = 1;
2402 param.rgx_y = 2;
2403 param.rgx_t = 3;
2404 } else if ((strncmp(regex_order, "xty", 3) == 0) || (strncmp(regex_order, "ytx", 3) == 0)) {
2405 param.rgx_x = 1;
2406 param.rgx_t = 2;
2407 param.rgx_y = 3;
2408 } else if ((strncmp(regex_order, "xy", 2) == 0) || (strncmp(regex_order, "yx", 2) == 0)) {
2409 param.rgx_x = 1;
2410 param.rgx_y = 2;
2411 param.rgx_t = 0;
2412 } else {
2413 print_error("markdup", "error, could not recognise regex coordinate order \"%s\".\n", regex_order);
2414 return 1;
2415 }
2416
2417 if ((param.rgx = malloc(sizeof(regex_t))) == NULL) {
2418 print_error("markdup", "error, could not allocate memory for regex.\n");
2419 return 1;
2420 }
2421
2422 if ((result = regcomp(param.rgx, regex, REG_EXTENDED))) {
2423 char err_msg[256];
2424
2425 regerror(result, param.rgx, err_msg, 256);
2426 print_error("markdup", "error, regex fail \"%s\"\n", err_msg);
2427 free(param.rgx);
2428 return 1;
2429 }
2430 }
2431
2432 if (bc_name) {
2433 int result;
2434
2435 /* From Illumina UMI documentation: "The UMI sequence is located in the
2436 eighth colon-delimited field of the read name (QNAME)". */
2437 char *rgx = "[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:([!-?A-~]+)";
2438
2439 if ((param.bc_rgx = malloc(sizeof(regex_t))) == NULL) {
2440 print_error("markdup", "error, could not allocate memory for barcode regex.\n");
2441 return 1;
2442 }
2443
2444 if (bc_regex) {
2445 rgx = bc_regex;
2446 }
2447
2448 if ((result = regcomp(param.bc_rgx, rgx, REG_EXTENDED))) {
2449 char err_msg[256];
2450
2451 regerror(result, param.bc_rgx, err_msg, 256);
2452 print_error("markdup", "error, barcode regex fail \"%s\"\n", err_msg);
2453 free(param.bc_rgx);
2454 return 1;
2455 }
2456 }
2457
2458 param.in = sam_open_format(argv[optind], "r", &ga.in);
2459
2460 if (!param.in) {
2461 print_error_errno("markdup", "error, failed to open \"%s\" for input", argv[optind]);
2462 return 1;
2463 }
2464
2465 strcat(wmode, "b"); // default if unknown suffix
2466 sam_open_mode(wmode + strlen(wmode)-1, argv[optind + 1], NULL);
2467 param.out = sam_open_format(argv[optind + 1], wmode, &ga.out);
2468
2469 if (!param.out) {
2470 print_error_errno("markdup", "error, failed to open \"%s\" for output", argv[optind + 1]);
2471 return 1;
2472 }
2473
2474 if (ga.nthreads > 0) {
2475 if (!(p.pool = hts_tpool_init(ga.nthreads))) {
2476 print_error("markdup", "error creating thread pool.\n");
2477 return 1;
2478 }
2479
2480 hts_set_opt(param.in, HTS_OPT_THREAD_POOL, &p);
2481 hts_set_opt(param.out, HTS_OPT_THREAD_POOL, &p);
2482 }
2483
2484 // actual stuff happens here
2485
2486 // we need temp files so fix up the name here
2487 if (tmpprefix.l == 0) {
2488
2489 if (strcmp(argv[optind + 1], "-") != 0)
2490 ksprintf(&tmpprefix, "%s.", argv[optind + 1]);
2491 else
2492 kputc('.', &tmpprefix);
2493 }
2494
2495 if (stat(tmpprefix.s, &st) == 0 && S_ISDIR(st.st_mode)) {
2496 if (tmpprefix.s[tmpprefix.l-1] != '/') kputc('/', &tmpprefix);
2497 }
2498
2499 t = ((unsigned) time(NULL)) ^ ((unsigned) clock());
2500 ksprintf(&tmpprefix, "samtools.%d.%u.tmp", (int) getpid(), t % 10000);
2501 param.prefix = tmpprefix.s;
2502
2503 param.arg_list = stringify_argv(argc + 1, argv - 1);
2504 param.write_index = ga.write_index;
2505 param.out_fn = argv[optind + 1];
2506
2507 ret = bam_mark_duplicates(&param);
2508
2509 sam_close(param.in);
2510
2511 if (sam_close(param.out) < 0) {
2512 print_error("markdup", "error closing output file.\n");
2513 ret = 1;
2514 }
2515
2516 if (p.pool) hts_tpool_destroy(p.pool);
2517
2518 if (param.rgx) {
2519 regfree(param.rgx);
2520 free(param.rgx);
2521 }
2522
2523 if (param.bc_rgx) {
2524 regfree(param.bc_rgx);
2525 free(param.bc_rgx);
2526 }
2527
2528 free(param.arg_list);
2529 free(tmpprefix.s);
2530 sam_global_args_free(&ga);
2531
2532 return ret;
2533 }