99e2ac93b1c73fd37525bc963fcc4959a571cf9f
[samtools.git] / misc / wgsim_eval.pl
1 #!/usr/bin/perl -w
2
3 # Contact: lh3
4 # Version: 0.1.3
5
6 use strict;
7 use warnings;
8 use Getopt::Std;
9
10 &wgsim_eval;
11 exit;
12
13 sub wgsim_eval {
14   my %opts;
15   getopts('pc', \%opts);
16   die("Usage: wgsim_eval.pl [-pc] <in.sam>\n") if (@ARGV == 0 && -t STDIN);
17   my (@c0, @c1);
18   my ($max_q, $flag) = (0, 0);
19   my $gap = 5;
20   $flag |= 1 if (defined $opts{p});
21   $flag |= 2 if (defined $opts{c});
22   while (<>) {
23         my @t = split;
24         my $line = $_;
25         my ($q, $is_correct, $chr, $left, $rght) = (int($t[4]/10), 1, $t[2], $t[3], $t[3]);
26         $max_q = $q if ($q > $max_q);
27         # right coordinate
28         $_ = $t[5]; s/(\d+)[MDN]/$rght+=$1,'x'/eg;
29         --$rght;
30         # correct for soft clipping
31         $left -= $1 if (/^(\d+)S/);
32         $rght += $1 if (/(\d+)S$/);
33         # skip unmapped reads
34         next if (($t[1]&0x4) || $chr eq '*');
35         # parse read name and check
36         if ($t[0] =~ /^(\S+)_(\d+)_(\d+)_/) {
37           if ($1 ne $chr) { # different chr
38                 $is_correct = 0;
39           } else {
40                 if ($flag & 2) {
41                   if (($t[1]&0x40) && !($t[1]&0x10)) { # F3, forward
42                         $is_correct = 0 if (abs($2 - $left) > $gap);
43                   } elsif (($t[1]&0x40) && ($t[1]&0x10)) { # F3, reverse
44                         $is_correct = 0 if (abs($3 - $rght) > $gap);
45                   } elsif (($t[1]&0x80) && !($t[1]&0x10)) { # R3, forward
46                         $is_correct = 0 if (abs($3 - $left) > $gap);
47                   } else { # R3, reverse
48                         $is_correct = 0 if (abs($2 - $rght) > $gap);
49                   }
50                 } else {
51                   if ($t[1] & 0x10) { # reverse
52                         $is_correct = 0 if (abs($3 - $rght) > $gap); # in case of indels that are close to the end of a reads
53                   } else {
54                         $is_correct = 0 if (abs($2 - $left) > $gap);
55                   }
56                 }
57           }
58         } else {
59           warn("[wgsim_eval] read '$t[0]' was not generated by wgsim?\n");
60           next;
61         }
62         ++$c0[$q];
63         ++$c1[$q] unless ($is_correct);
64         print STDERR $line if (($flag&1) && !$is_correct && $q > 0);
65   }
66   # print
67   my ($cc0, $cc1) = (0, 0);
68   for (my $i = $max_q; $i >= 0; --$i) {
69         $c0[$i] = 0 unless (defined $c0[$i]);
70         $c1[$i] = 0 unless (defined $c1[$i]);
71         $cc0 += $c0[$i]; $cc1 += $c1[$i];
72         printf("%.2dx %12d / %-12d  %12d  %.3e\n", $i, $c1[$i], $c0[$i], $cc0, $cc1/$cc0);
73   }
74 }