File: roc-at-cutoff.pl

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (319 lines) | stat: -rwxr-xr-x 9,502 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/perl

#Copyright (C) 2006-2008 Keio University
#(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
#
#This file is part of Murasaki.
#
#Murasaki is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Murasaki is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.

use File::Basename;
use Getopt::Long;
use Pod::Usage;
#use Data::Dump qw{dump};

use strict;
my ($help,$man,$opt_prefix);

BEGIN {
  unshift(@INC,(fileparse($0))[1].'perlmodules');
}
use Murasaki;

my $opt_pred="tfidf";
my $samples;
my $fn;
my $format="png";
my $lwd=3;
my ($opt_log,$opt_clean,$opt_nofstats,$fstats,%avg,$drawAvg,$maxsamples,$nofn,$opt_pointsize,$opt_title,$opt_notitle,$opt_titlescale,$opt_legendscale);

GetOptions('help|?' => \$help, man => \$man, "predictor|x|stat=s"=>\$opt_pred,
	   'samples|n=i' => sub {
	     pod2usage(-verbose=>1,-exitstatus => 0,-msg => "Error: $_[0] must be at least 2") unless $_[1]>1;
	     $samples=$_[1];
	   },
	   'fn=i'=>\$fn,'log=s'=>\$opt_log, clean=>\$opt_clean, 'format=s'=>\$format,
	   'legendscale=f'=>\$opt_legendscale,
	   pdf=>sub{$format='pdf'},lwd=>\$lwd, nofstats=>\$opt_nofstats,
	   'pointsize=f'=>\$opt_pointsize,'title=s'=>\$opt_title,
	   'notitle'=>\$opt_notitle,'titlescale=f',\$opt_titlescale,
	   fstats=>\$fstats, 'avg:s%'=>sub{
	     $drawAvg=1;
	     $avg{$_[1]}=$_[2] if $#_>1},
	   'noavg'=>sub{$drawAvg=0},'maxsamples|maxn=i'=>\$maxsamples,nofn=>\$nofn
	  ) or pod2usage(-exitstatus => 1);;
pod2usage(1) if $help or $#ARGV<0;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

if(defined($samples)){
  $samples=int $samples;
  $samples>1 or die "Samples must be greater than 1";
}
if(defined($maxsamples)){
  $maxsamples=int $maxsamples;
  $maxsamples>1 or die "Samples must be greater than 1";
}

foreach my $file (@ARGV){
  my ($basename,$path,$suffix)=fileparse($file,qr/\.rocr?/);
  $path=~s!/$!!; #kill trailing / if any
  my $basefile="$path/$basename";
  my $rocrfile="$basefile.rocr";

  #attempt to grab a FN count from a filterstats file if we don't have one
  if(!$opt_nofstats){
    unless($fstats and -f $fstats){
      my @fstats=<$basefile.*.filterstat*>;
      $fstats=$#fstats>0 ? pickOne("Multiple filterstats files found:","Which should I use? ",@fstats):$fstats[0];
    }
    goto STARTSAMPLE unless -f $fstats;
    open(my $fstat_fh,$fstats);
    while(<$fstat_fh>){
      if(m/Initial stats:/){
	<$fstat_fh>; #junk line about # of anchors
      GETMEANS: while(<$fstat_fh>){
	  $avg{$1}=$2 if m/^(\w+) mean: (\d+\.?\d*)/;
	  last GETMEANS unless m/^\w+ mean:/;
	}
      }

      if(m/^Experimental Orthos:/){
	$_=<$fstat_fh>;
	$fn=$1 if m/FN: (\d+)/;
	last;
      }
    }
    print "Got FN=$fn from $fstats\n" if $fn;
    print "Found averages for: ".join(", ",sort keys %avg)."\n";
  }

 STARTSAMPLE:

  my (@fields);
  open(my $fh,$rocrfile) or die "Couldn't open $rocrfile";
  $_=<$fh>;
  chomp;
  @fields=split(/\t/,$_);
  print "Fields available: ".join(", ",@fields)."\n";

  my @preds=($opt_pred);
  if ($opt_pred eq 'all') {
    @preds=grep {$_ ne 'label'} @fields;
  }

  print "Making ROC graphs for @preds\n";
  foreach my $pred (@preds) {
    my $rocfile="$basefile.$pred.roc";
    my $rsrc="$basefile.$pred.R";
    my @outfields=($pred,qw{tpr fpr anchors spec});

    unless(-f $rocfile and !$opt_clean){ #reuse rocfile if there is one
      print "Sampling $rocrfile against $pred statistics\n";

      die "No rocr file: $rocrfile? Run filter.pl --rocr to make one..." unless -f $rocrfile;

      seek($fh,0,0);
      <$fh>; #chomp field header
      my ($predi)=grep {$fields[$_] eq $pred} (0..$#fields);
      die "Stats for $pred not in file..." unless defined $predi;
      my (@tp,@fp);
      while (<$fh>) {
	chomp;
	my @dat=split(/\t/,$_);
	my $lr=($dat[0]==1 ? \@tp : \@fp);
	push(@$lr,$dat[$predi]);
      }
    
      my @x;
      if (defined($samples)) {
	my ($min,$max)=(min(@tp,@fp),max(@tp,@fp));
	my $range=$max-$min;
	@x=map {$min+$_/$samples*$range} (0..$samples);
      } else {
	my %h=();
	foreach (@tp,@fp) {
	  $h{$_}=1;
	}
	my $n=scalar(keys %h);
	if(defined $maxsamples and $n>$maxsamples){
	  print "Maxsamples ($maxsamples) exceeded ($n found). Sampling linearly across $maxsamples.\n";
	  my ($min,$max)=(min(@tp,@fp),max(@tp,@fp));
	  my $range=$max-$min;
	  @x=map {$min+$_/$maxsamples*$range} (0..$maxsamples);
	}else{
	  @x=sort {$a<=>$b} keys %h;
	}
      }
    
      push(@outfields,qw{sens}) if defined $fn;
    
      open(my $ofh,">$rocfile") or die "Couldn't write to $rocfile";
      print $ofh join("\t",@outfields),"\n";
      my ($stp,$sfp)=(scalar(@tp),scalar(@fp));
      die "Can't calculate rates without tp ($stp) and fp ($sfp).\n" unless ($stp and $sfp);
      foreach my $x (@x) {
	my ($ftp,$ffp)=map {scalar(grep {$_>=$x} @$_)} (\@tp,\@fp);
	my ($tpr,$fpr,$anchors,$spec)=($ftp/$stp,$ffp/$sfp,($ftp+$ffp)/($stp+$sfp),($ftp/($ftp+$ffp)));
	my @outbits=($tpr,$fpr,$anchors,$spec);
	if (defined $fn) {
	  push(@outbits,($ftp/($stp+$fn)));
	}
	print $ofh join("\t",$x,@outbits) , "\n";
      }
      close $ofh;
    }
  
    my $legendpos=($opt_log=~m/x/) ? #if x is logscale
      "min(roc[,'$pred'])+(max(roc[,'$pred'])-min(roc[,'$pred']))/10":"max(roc[,'$pred'])*.8";
    my $pointsize=$opt_pointsize ? ",pointsize=$opt_pointsize":undef;
    my $outputter=$format ne 'pdf' ? 
      qq!bitmap(file="$rocfile.$format",type="png16m",width=10,height=7,res=96$pointsize)!:
	qq!pdf(file="$rocfile.$format",width=10,height=7$pointsize)!;

    my $title=$opt_title ? "'$opt_title'":"'$basename $pred ROC vs cutoff'";
    my @pars;
    if($opt_notitle){
      push(@pars,'mai=c(op$mai[1:2],rep(op$mai[4],2))');
      $title="";
    }elsif($opt_titlescale){
      push(@pars,"cex.main=op\$cex.main*$opt_titlescale");
      push(@pars,'mai=c(op$mai[1:2],op$mai[3]*'.$opt_titlescale.',op$mai[4])');
    }

    my ($paron,$paroff);
    if(scalar(@pars)){
      $paron="op <- par(no.readonly = TRUE);par(".join(",",@pars).")";
      $paroff="par(op)";
    }
    
    my $legendcex=$opt_legendscale ? $opt_legendscale:1;
    
    #do the R output
    open(my $R,">$rsrc");
    print $R <<ENDTEXT;

$outputter
roc<-read.delim('$rocfile')
$paron
plot(roc[,'$pred'],roc[,'tpr'],type='l',col=2,lwd=$lwd,xlab='$pred cutoff',ylab='Rate',main=$title,log='$opt_log')
lines(roc[,'$pred'],roc[,'fpr'],col=3,lwd=$lwd)
lines(roc[,'$pred'],roc[,'spec'],col=6,lty=2,lwd=$lwd);
c(min(roc[,'$pred']),$legendpos,max(roc[,'$pred']));
ENDTEXT

    if ($drawAvg and exists($avg{$pred})) {
      print $R <<ENDTEXT;
abline(v=$avg{$pred},lty=2,lwd=$lwd/2);
text($avg{$pred}*1.01,1,adj=c(0,1),labels="mean");
ENDTEXT
    }

    if(defined $fn and !$nofn) {
      print $R <<ENDTEXT;
lines(roc[,'$pred'],roc[,'sens'],col=5,lwd=3);

legend($legendpos,1,c("True Positive Rate","False Positive Rate","Sensitivity","Specificity"),col=c(2,3,5,6),lty=c(1,1,2,2),lwd=c($lwd,$lwd,$lwd/2,$lwd),cex=$legendcex)
ENDTEXT
    } else {
      print $R <<ENDTEXT;
legend($legendpos,1,c("True Positive Rate","False Positive Rate","Specificity"),col=c(2,3,6),lty=c(1,1,2),lwd=c($lwd,$lwd,$lwd),cex=$legendcex)
ENDTEXT
    }
    print $R "$paroff\n";
    close($R);
    system("R --vanilla < $rsrc");
  }
}


sub sum {
  my $sum=0;
  grep {$sum+=$_} @_;
  return $sum;
}

sub mean {
  my $total;
  foreach(@_){
    $total+=$_;
  }
  return $total/($#_+1);
}

sub min {
  my $best=$_[0];
  foreach(@_){
    $best=$_ if $_<$best;
  }
  return $best;
}

sub max {
  my $best=$_[0];
  foreach(@_){
    $best=$_ if $_>$best;
  }
  return $best;
}

sub pickOne {
  my ($ps1,$ps2,@opts)=@_;
  print $ps1."\n";
  print map {($_==0 ? "[$_]":" $_ ").": $opts[$_]\n"} 0..$#opts;
  my $res;
  do{
    print $ps2;
    $res=<STDIN>;
    chomp $res;
  }while($res && ($res<0 or $res>$#opts));
  return $opts[$res];
}

__END__

=head1 NAME

roc-at-cutoff.pl - computes ROC/sensitivity/specificity at various/all
thresholds

=head1 SYNOPSIS

cbtest.pl <input1> [input2 ...]

=head1 OPTIONS

Input file should be some alignment that has as a .rocr file
(presumably generated by filter.pl --rocr). Output is graphed
to <basename>.cutoff.roc.png.

sensitivity/specificity requires a false negative count,
and as such requires a .filterstats file.

 Other options:
--stat|predictor|x specifies what stat to use as a predictor
--samples|n sets number of samples (default is sample at each possible cutoff)
--maxsamples|maxn sets a max for n/samples
--clean forces a re-sampling of the .rocr file
--log can apply log scale to x or y or xy axes
--fn can specify a FN count for calculating sensitivity
--avg preload averages (normally found from filterstats)
  (note: averages no drawn by default, so specify --avg (with no args) to
   enable them)
--noavg don't plot the line for averages
--lwd can specify line weight
--format can specify output file format (default png)
--pdf set format to pdf
--nofstats disable searching for filterstats statistics
--nofn pretend not to have fn statistics (ie: skip sensitivity)
--fstats specify the filterstats file to use