Debian Codegraph @

samtools/bam_markdup.c

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