#!/usr/bin/perl

use strict;
use warnings;

use lib qw(Classes);

use ResultsManager;

###########################################################
#
# The script confronts the submitted models with the random
# models. The performance is based on the GDT_TS. 
# The random models were generated and avaluated by the 
# pipe-line: 
# (1) Grishin_genRandomModels.pl
# (2) Grishin_evalRandomModels.pl
# (3) Grishin_genSummaryRandomModel.pl
#
# The algorithm:
# For each target:
# (1) take the GDT scores of first models that servers 
#     submitted (exclude human models).
# (2) put the GDT score of the random control into the 
#     scores and generate a ranked list.
# (3) in the rank list, record the number of models above 
#     random controls.
# (4) calculate the average of GDT scores from the models 
#     above random control.
# 
# Output: 
# (1) the number of models above random controls, 
# (2) the average of GDT_TS from the models above random 
#     controls
#
###########################################################


my @TARGETS;
my %RAND_GDT;   # hash of gdt_ts's for random models
		# key - target; value - gdt_ts

my $summaryFile = "/local/CASP13/tmp_Grishin/Summary_RandomModels.gdt_ts.csv";

&readRandModels();

if (defined($ARGV[0])){
   my $t = $ARGV[0];
   if (exists($RAND_GDT{$t})){
	@TARGETS = ();
	push @TARGETS, $t;
   }
}
my $OUTFILE = "/local/CASP13/tmp_Grishin/Server_vs_RandomModels.gdt_ts.csv";
open OUT, "> $OUTFILE";

printf OUT "%-10s  %9s  %10s\n", 'Target', "No(>rand)", "AVR(>rand)";
my $resultsManager = new ResultsManager();
foreach my $t (@TARGETS){
   my ($count, $avrg) = &processTarget($resultsManager, $t);
   printf OUT "%-10s  %9d  %10.3f\n", $t, $count, $avrg;
#   last;
}
close OUT;


#----------------------------
# SUBROUTINES
#----------------------------

sub readRandModels{
    open F, "< $summaryFile";
	while(defined(my $l = <F>)){
		chomp $l; $l =~ s/^\s+//;
		my ($t, $gdt) = split(/\s+/, $l);
		$RAND_GDT{$t} = $gdt;
	}
    close F;
    @TARGETS = sort keys %RAND_GDT;
}

sub processTarget{
    my ($resultsManager, $target) = @_; 
    my $params = {
        groups_type => 'server',
        model => 1,
        target => $target,
	field => 're.gdt_ts_4',
	order => 'DESC'
	};
    my @results = $resultsManager->get_results($params);
    my $count = 0; # counts of models above the random control 
    my $avrg = 0;  # average value of GDT_TS of all models above random control
    foreach my $res (@results){
	if ($res->{GDT_TS_4} >= $RAND_GDT{$target}){
		$count++;
		$avrg += $res->{GDT_TS_4};
	}
    }
    if ($count > 0){
	return ($count,sprintf("%6.4f",$avrg/$count));
    } else {
	return (0, 0.0);
    }
}
