#!/usr/bin/env perl
# $Id: extract_EST,v 1.2 2006/12/19 13:15:06 c4chris Exp $

################################################################################
#
# evaluate_model
# --------------
# 
# Claudio Lottaz, SIB-ISREC, Claudio.Lottaz@isb-sib.ch
# Christian Iseli, LICR ITO, Christian.Iseli@licr.org
#
# Copyright (c) 1999 Swiss Institute of Bioinformatics. All rights reserved.
#
################################################################################

use strict;
use FASTAFile;
use Symbol;

# global configuration
my $winsegshuffle_dbsize = 10000000; # the size for shuffled databases

# global variables
my $verbose = 1;
my $norna = 0;
my $optionsfile = '';
my $forcedtuplesize = undef;
my $forcedminmask = undef;
my $forcedpseudocounts = undef;
my $forcedminscore = undef;
my $forcedstartlength = undef;
my $forcedstartpreroll = undef;
my $forcedstoplength = undef;
my $forcedstoppreroll = undef;
my $forcedsmatfile = undef;
my $forceestscanparams = undef;

my $datadir = '.';
my $filestem = '';
my $program = "estscan";

require "build_model_utils.pl";

################################################################################
#
#   Check command-line for switches
#

my $usage = "Usage: evaluate_model [options] <conf-files>\n" .
    "       where options are:\n" .
    "        -q        don't log on terminal\n" .
    "        -O <str>  options passed to program\n" .
    "        -o <file> options file\n" .
    "        -n        skip evaluation on mRNAs\n" .
    "        -t <int>  force tuple size, overwrites entry in config-files\n" .
    "        -M <file> force score matrices file\n" .
    "        -m <int>  force minimal mask, overwrites entry in config-files\n" .
    "        -P <file> force program name (or file)\n" .
    "        -p <int>  force pseudocounts, overwrites entry in config-files\n" .
    "        -s <int>  force minimal score, overwrites entry in config-files\n" .
    "        -l <int>  force length of start profile (in codons/triplets)\n" .
    "        -r <int>  force start profile's preroll in 5'UTR (in codons/triplets)\n" .
    "        -L <int>  force length of stop profile (in codons/triplets)\n" .
    "        -R <int>  force sop profile's preroll in 5'UTR (in codons/triplets)\n" .
    "More information  is obtained using 'perldoc evaluate_model'\n";

while ($ARGV[0] =~ m/^-/) {
    if ($ARGV[0] eq '-q') { shift; $verbose = 0; next; }
    if ($ARGV[0] eq '-n') { shift; $norna = 1; next; }
    if ($ARGV[0] eq '-O') { shift; $forceestscanparams = shift; next; }
    if ($ARGV[0] eq '-o') { shift; $optionsfile        = shift; next; }
    if ($ARGV[0] eq '-t') { shift; $forcedtuplesize    = shift; next; }
    if ($ARGV[0] eq '-M') { shift; $forcedsmatfile     = shift; next; }
    if ($ARGV[0] eq '-m') { shift; $forcedminmask      = shift; next; }
    if ($ARGV[0] eq '-P') { shift; $program            = shift; next; }
    if ($ARGV[0] eq '-p') { shift; $forcedpseudocounts = shift; next; }
    if ($ARGV[0] eq '-s') { shift; $forcedminscore     = shift; next; }
    if ($ARGV[0] eq '-l') { shift; $forcedstartlength  = shift; next; }
    if ($ARGV[0] eq '-r') { shift; $forcedstartpreroll = shift; next; }
    if ($ARGV[0] eq '-L') { shift; $forcedstoplength   = shift; next; }
    if ($ARGV[0] eq '-R') { shift; $forcedstoppreroll  = shift; next; }
    die "Unrecognized switch: $ARGV[0]\n$usage";
}
if ($#ARGV < 0) { die "No configuration file specified\n$usage"; }

################################################################################
#
#   Main-loop through all specified config-files
#

my $parFile;
while($parFile = shift) { 
    my($organism, $dbfiles, $ugdata, $estdata, $datadir2, $filestem2, 
       $rnafile, $estfile, $estcdsfile, $estutrfile, $trainingfile, $testfile, 
       $utrfile, $cdsfile, $tuplesize, $minmask, $pseudocounts, $minscore, 
       $startlength, $startpreroll, $stoplength, $stoppreroll, $smatfile,
       $estscanparams, $nb_isochores, $isochore_borders) =
	   readConfig($parFile, $forcedtuplesize, $forcedminmask, $forcedpseudocounts, 
		      $forcedminscore, $forcedstartlength, $forcedstartpreroll,
		      $forcedstoplength, $forcedstoppreroll, $verbose);
    if (defined $forcedsmatfile) {
      $smatfile = $forcedsmatfile;
    }
    if (defined $forceestscanparams) {
      $estscanparams = $forceestscanparams;
    }
    log_open("readconfig.log");
    $datadir = $datadir2; $filestem = $filestem2;
    showConfig($parFile, $organism, $dbfiles, $ugdata, $estdata, $datadir, 
	       $rnafile, $estfile, $estcdsfile, $estutrfile, $trainingfile, $testfile, 
	       $utrfile, $cdsfile, $tuplesize, $minmask, $pseudocounts, $minscore, 
	       $startlength, $startpreroll, $stoplength, $stoppreroll, $smatfile, 
	       $estscanparams, $nb_isochores, $isochore_borders);
    log_close();

    die "Unsupported...  Please fix me";

    # read options-file, each line contains a set of options
    my $o; my @options;
    if ($optionsfile eq "") { push(@options, $estscanparams); }
    else {
	my $fh = gensym;
	open($fh, $optionsfile);
	@options = <$fh>;
	close($fh);
    }

    log_open("extract_EST.log");
    log_print("\nUsing $program to scan EST/mRNA\n");
    extract_ESTs($estdata, $organism, $estfile);
    estimateFalseNegative($smatfile, $estfile, $cdsfile, $estscanparams);
    estimateFalsePositive($organism, $smatfile, $estdata, $estscanparams);
    log_close();
    print "$parFile done.\n";
}

exit 0;

################################################################################
#
#   Estimate false negative rate compared to megablast
#

sub extract_ESTs {
    # From a large collection of ESTs in FASTA format ($estdata)
    # filters the entries for the given species ($organism) and
    # selects randomly entries dispersed over the whole collection
    # until the wanted size of the generated file is reached
    # ($dbsize).

    my($estdata, $organism, $estfile) = @_;

    # check if done
    log_print(" - Extracting EST entries...");
    if (-s $estfile) { log_print(" - $estfile already exists"); return; }

    my($file, $fileSeqs);
    my $totSeqs = 0; my $totLen = 0;
    my(@infiles) = glob($estdata);
    my $estdbsize = 0;
    foreach $file (@infiles) { my @s = stat($file); $estdbsize += $s[7]; }
    my $acceptrate = $winsegshuffle_dbsize / $estdbsize;
    if ($acceptrate < 0.01) { $acceptrate = 0.01; }
    log_print("   accept rate is $acceptrate");
    my $outfh = gensym; open($outfh, ">$estfile");
    while($totLen < $winsegshuffle_dbsize) {
	foreach $file (@infiles) {
	    my $src = FASTAFile->new("$file"); $src->openStream;
	    log_print(" - reading in $file...");
	    my $e;
	    while(defined ($e = $src->getNext)) {
		if (($e->{_seqHead} =~ m/$organism/) && (rand() < $acceptrate)) { 
		    $fileSeqs++;
		    $totLen += length($e->{_seq});
		    $e->printFASTA($outfh);
		}
		if ($totLen > $winsegshuffle_dbsize) { last; }
	    }
	    close($src->{_BTFfile});
	    log_print("   selected $fileSeqs sequences so far");
	    if ($totLen > $winsegshuffle_dbsize) { last; }
	}
    }
    
    # close files
    close($outfh);
}

sub estimateFalseNegative {
    # Determine matches of coding sequences from test files
    # in ESTs using megablast. Find how many are not detected
    # by ESTScan as an estimate of false negative rate.

    my ($smatfile, $estfile, $cdsfile, $estscanparams) = @_;

    log_print("\nEstimate false negative rate...");

    # generate blast library containing the est data
    if (-s "$datadir/Evaluate/estdb.nsq") { 
	log_print(" - formatted blast database already exists, skipped");
    }
    else {
	log_print(" - formatting blast database from $estfile..."); 
	symlink($estfile, "$datadir/Evaluate/estdb.seq");
	system("cd $datadir/Evaluate;  rm formatdb.log; " .
	       "formatdb -i estdb.seq -p F -n estdb");
    }

    # match est-data against cds data using megablast
    my $cdsvsestfile = "$datadir/Evaluate/cdsvsest.mbl";
    if (-s $cdsvsestfile) { log_print(" - $cdsvsestfile already exists, skipped"); }
    else {
	log_print(" - matching coding sequences ($cdsfile) against ESTs...");
	system("cd $datadir/Evaluate; megablast -d estdb -i $cdsfile > $cdsvsestfile");
    }

    my $e;
    my $nbMatched = 0;
    log_print("   found $nbMatched matches, now writing...");
    my $matchedFile = "$datadir/Evaluate/mblmatched.seq";
    if (-s $matchedFile) { 
	log_print("   $matchedFile already exists, skipped."); 
	$nbMatched = `grep -c '>' $matchedFile`; chop($nbMatched);
    }
    else {
	# read matches from megablast output
	log_print(" - collecting metched ESTs...");
	my %storedEsts;
	my $mblfh = gensym; open($mblfh, "$cdsvsestfile");
	while(<$mblfh>) {
	    my($est,$direction,$cds,$estStart,$cdsStart,$estEnd,$cdsEnd,$mismatch) =
		m/^\'([^\']*)\'==\'([+|-])([^\']*)\' \((\S+) (\S+) (\S+) (\S+)\) (\S+)/;
	    my $matchLength = ($cdsEnd - $cdsStart);
	    ($est) = $est =~ m/\|([^\|]*)\|/;
	    if ($matchLength < 100) { next; }
	    if (($mismatch / $matchLength) > 0.05) { next; }
	    if (exists($storedEsts{$est})) { next; }
	    $storedEsts{$est} = 1;
	    $nbMatched++;
	}
	close($mblfh);

	# generate FASTA-file with matched ESTs
	my $matchedfh = gensym; open($matchedfh, ">$matchedFile");
	my $src = FASTAFile->new("$estfile"); $src->openStream;
	while(defined($e = $src->getNext)) {
	    if (exists($storedEsts{$e->ac})) { $e->printFASTA($matchedfh); }
	    delete($storedEsts{$e->ac});
	}
	close($src->{_BTFfile});
    }
    if ($nbMatched == 0) {
	log_print("   no matches found in EST data, skipped");
	return;
    }

    # compute predictions for matched ESTs
    my $prcfile = "$datadir/Evaluate/prc$filestem.seq";
    if (-s $prcfile)  { log_print(" - $prcfile already exists, skipped"); }
    else {
	log_print(" - predicting CDS for matched ESTs...");
	system("$program $estscanparams -M $smatfile $matchedFile > $prcfile");
    }
    my $nbPrc = `grep -c '>' $prcfile`; chop($nbPrc);
    log_print("   found $nbPrc predicted coding sequences");
    log_print("   estimated false negative rate: " . (1.0 - $nbPrc/$nbMatched));
}

################################################################################
#
#   Estimate false positive rate on window segment shuffled EST-data
#

sub estimateFalsePositive {
    # Estimates false positive rate on window segment shuffled ESTs.

    my ($organism, $smatfile, $lengths_ref, $estdata, $estscanparams) = @_;
    my @lengths = @{$lengths_ref};
    log_print("\nEstimate false positive rate on shuffled est-data...");

    # collect another set of ESTs
    my $estfile = "$datadir/Evaluate/ests.seq";
    if (-s $estfile) { log_print(" - $estfile already exists, skipped"); }
    else {
	my $dbsize = 0;
	my $estfh = gensym; open($estfh, ">$estfile");
	my($file, $fileSeqs);
	my $totSeqs = 0;
	my(@infiles) = glob($estdata);
	my $estdbsize = 0;
	foreach $file (@infiles) { my @s = stat($file); $estdbsize += $s[7]; }
	my $acceptrate = $winsegshuffle_dbsize / $estdbsize;
	log_print("   accept rate is $acceptrate");
	while($dbsize < $winsegshuffle_dbsize) {
	    foreach $file (@infiles) {
		$fileSeqs = 0;
		my $src = FASTAFile->new("$file"); $src->openStream;
		log_print(" - reading $file...");
		my $e;
		while(defined ($e = $src->getNext)) {
		    if (($e->{_seqHead} =~ m/$organism/) && (rand() < $acceptrate)) {
			$fileSeqs++;
			$dbsize += length($e->{_seq});
			$e->printFASTA($estfh);
		    }
		    if ($dbsize > $winsegshuffle_dbsize) { last; }
		}
		close($src->{_BTFfile});
		$totSeqs += $fileSeqs;
		log_print("   selected $fileSeqs sequences so far ($dbsize nucleotides)");
		if ($dbsize > $winsegshuffle_dbsize) { last; }
	    }
	}
	close($estfh);
	log_print(" - written $totSeqs in $estfile");
    }

    my $length;
    my $totalPredicted = 0; my $totalPredictedStart = 0; my $totalShuffled = 0;
    foreach $length (@lengths) {
	log_print(" - computing for length $length...");

	# shuffle data
	my $shuffledFile = "$datadir/Shuffled/testset$length.seq";
	if (-s $shuffledFile) { log_print("   shuffled data already exists, skipped"); }
	else { 
	    log_print("   shuffling EST-data...");
	    system("winsegshuffle 500000 $length < $estfile > $shuffledFile"); 
	}
	my $nbShuffled = `grep -c '>' $shuffledFile`; chop($nbShuffled);
	$totalShuffled += $nbShuffled;
	if ($nbShuffled == 0) {
	    log_print("   no shuffled data written for $length from $estfile, skipped");
	    next;
	}

	# predict 
	my $prcfile = "$datadir/Evaluate/prc$filestem\_shuffled$length.seq";
	if (-s $prcfile) { log_print("   $prcfile already exists, skipped"); }
	else {
	    log_print("   predicting coding on shuffled files...");
	    system("$program $estscanparams -M $smatfile $shuffledFile > $prcfile");
	}
	my $nbPrc = `grep -c '>' $prcfile`; chop($nbPrc);
	log_print("   estimated false positive rate: " . 
		  sprintf("%6.4f", $nbPrc/$nbShuffled) . 
		  " ($nbPrc predicted in $nbShuffled shuffled seqs)");
	$totalPredicted += $nbPrc;
    }
    if ($totalShuffled == 0) { log_print(" - no shuffled data written, skipped"); }
    else {
	log_print(" - average estimated false positive rate: " . 
		  sprintf("%6.4f", $totalPredicted/$totalShuffled) . 
		  " ($totalPredicted predicted in $totalShuffled shuffled seqs)");
    }
}

################################################################################
#
#   Documentation
#

=head1 NAME

evaluate_model - evaluate an ESTScan model generated by build_model

=head1 SYNOPSIS

evaluate_model [options] <config-files...>

=head1 DESCRIPTION

evaluate_model evaluates the performance of an ESTscan model. It uses
the same directory structure as build_model, knows most of
build_model's command line switches and read the same configuration
files. ESTScan's performance is evluated in terms of false positive
and negative rates on the nucleotide level, as well as prediction
accuracy for start and stop sites. The script reads configuration
files on the comannd line and performs the following steps for each of
them:

 - Extract untranslated regions from test mRNA
 - Evaluate false positive rate.  evaluate false negative
 - Evaluate false negative rate as well as start and stop prediction
   accuracy on test mRNAs
 - Find entirely untranslated and partially coding ESTs using UniGene
 - Evaluate false positive rate on untranslated ESTs
 - Evaluate false negative rate as well as start and stop prediction
   accuracy on partially coding ESTs

The evaluation is carried out on two kinds of data: mRNA data and EST
data. The first three steps work on mRNA the latter on ESTs. When
using RNA, two computational experiments are made. On one hand all
untranslate regions of the test set of mRNAs are extracted and then
analyzed in order to find the false positive rate on nucleotide as
well as on sequence level. On the other hand, the complete test mRNAs
are analyzed to estimate false positive and false negative rates on a
nucleotide level. Moreover, distance distributions between prediction
and annotation of start and stop sites are computed and histograms
generated as gnuplot scripts and data files.

The data needed for evluation using ESTs is extracted using UniGene.
UniGene clusters are used to determine ESTs from untranslated regions
and coding sequence respectively. This is done by matching the ESTs of
a given cluster against its full-length mRNA with megablast and then
determining where the match occurs relative to the annotated coding
sequence. For each category, coding and non-coding, a single EST is
chosen per cluster, in order to avoid redundancy. The matching
location also allows to determine where coding sequences start and end
in partially coding ESTs. The same annotation in FASTA headers is used
as for mRNAs. The sets of coding and non-coding ESTs are used to
perform the same computational experiments as those done with mRNA
data.

Files which already exist are reused. If an existing file is to be
recomputed, it must deleted before running the script again. For
instance, if a particular collection of mRNA or EST sequences should
be used instead of data extracted by evaluate_model, providing these
in FASTA format under the name of the mRNA file (where evaluate_model
would store the extracted data) is enough. The same procedure can be
applied to provide hand picked test data. However, in mRNA and EST
data used for test and training, evaluate_model expects annotations of
coding sequence start and stop in the header as two integer values
following the tag 'CDS:'.The first integer points to the first
nucleotide of the CDS, the second to the last. Thus the length of the
CDS is <stop> - <start> + 1. The position counting starts with 1.

=head1 DIRECTORY STRUCTURE

evaluate_model uses the same directory structure as build_model, the
root of which is given in the configuration file. From this root it
adds the subdirectory 'Evaluate', which contains all result files.
mRNA and EST data as well as test and training data files are dposited
in the data-root directory if not otherwise specified in the
configuration file.

=head1 OPTIONS AND CONFIGURATION FILE

The same command options except '-e' and variables in configuration
files as for build_model can be used. They are essentially used to
find the proper model and to create different files for different
models in a systematic manner. However, there is one additional
option:

 -o <optionsfiles>
    An options file contains a set of ESTScan commandline switches per
    line. For each line of the file the evaluation is performed
    once. The script and data files generated at each run are removed
    in this mode, the results can only be collected in the Report
    file. If '-o' is not specified, evaluation is performed using
    ESTScan's default parameters (except for the matric to be
    evaluated, of course).

Additional parameters defined in the configuration files for
evaluate_model are listed here:

 * $ugdata
   Name of the file(s) containing data about unigene clusters.
   If this is not defined, no evaluation is currently implemented.

$filestem is used to generate many filenames. It is generated
automatically according to the tuplesize, the minmask and the
pseudocounts applied to generate them.

=head1 REQUIREMENTS

During analysis of UniGene clusters and evaluation of the generated
tables some external packages are used to collect and compare
sequences. evaluate_model relies on 'megablast' to determine where
ESTs match on full-length mRNA sequences. The 'fetch' utility is used
to find the EST and mRNA entries. This tool needs a properly indexed
version of EMBL and RefSeq flatfiles. Use 'indexer' for this. Both tools
are part of the BTLib toolset.

=head1 AUTHOR

Claudio Lottaz, SIB-ISREC, Claudio.Lottaz@isb-sib.ch

=cut

#
#   End of file
#
################################################################################
