#!/usr/bin/python
import os
import string
import types
import os.path
import sys

# Used by Read_res_file
def Get_line(input):
    line = input.readline()
    if line:
        line = string.split(line,'\n')[0]
    return line

# Extracts the statistics from the input file, averages them, and
# outputs the results in the result file
def Read_res_file(fname, resfile):
    input=open(fname, "r")
    #skip first 4 lines
    line = input.readline()
    line = input.readline()
    line = input.readline()
    line = input.readline()
    res = {}
    res["gen"] = 0
    res["conv"] = 0
    res["obj"] = 0
    maxf = {}
    maxf["fitness"] = 0
    maxf["values"] = ""
    maxf["ovalues"] = ""
    maxf["obj"] = 0
    trials = 0
    line = 1
    while line:
        line = input.readline()
        if not line:
            break
        line = string.split(line,'\n')[0]
        numbers = string.split(line,"\t")
        if not len(numbers) or numbers[0] == "":
            break
        trials = trials + 1
        for i in range(len(numbers)):
            numbers[i] = float(numbers[i])
        if not res.has_key("fitness"):
            res["fitness"] = []
            for i in range(len(numbers)-2):
                res["fitness"].append(0)
        for i in range(len(numbers)-2):
            res["fitness"][i] += numbers[i]
        res["gen"] += numbers[len(numbers) - 2]
        res["conv"] += numbers[len(numbers) - 1]
        # skip "Object values:"
        line = input.readline()
        if string.find(line, "Objective fitness:") == 0:
            line = input.readline()
            if not line:
                break
            number = float(string.split(line,"\n")[0])
            # skip "Real values:"
            line = input.readline()
            if not line:
                break
            line = input.readline()
            if not line:
                break
            res["obj"] += number
            if maxf["obj"] < number:
                maxf["obj"] = number
                maxf["ovalues"] = line
        if numbers[len(numbers) - 3] > maxf["fitness"]:
            maxf["fitness"] = numbers[len(numbers) - 3]
            maxf["values"] = line
        line = input.readline()
    line = ""
    for i in range(len(res["fitness"])):
        res["fitness"][i] /= trials
        line = "%s\t%g" %(line, res["fitness"][i])
    res["obj"] /= trials
    res["gen"] /= trials
    res["conv"] /= trials
    output = open(resfile, "w")
    output.write("Average results from \n%s\n\n" %(fname))
    output.write("Number of trials: %d\n\n" %(trials))
    output.write("Average evolution of the fitness:\n")
    output.write(line)
    output.write("\n\n")
    output.write("Average convergence generation: %g\n" %(res["gen"]))
    output.write("Average population homogeneity: %g\n\n" %(res["conv"]))
    output.write("Maximum fitness achieved: %g\n" %(maxf["fitness"]))
    output.write("Real values for this fitness:\n%s\n" %(maxf["values"]))
    output.write("Average objective fitness: %g\n" %(res["obj"]))
    output.write("Maximum objectivefitness achieved: %g\n" %(maxf["obj"]))
    output.write("Real values for this objective fitness:\n%s\n" %(maxf["ovalues"]))
    output.close()
        
if __name__ == '__main__' : 
    infile = ""
    outfile = ""
    argv = sys.argv
    if len(argv) > 1:
        infile = argv[1]
        if len(argv) > 2:
            outfile = argv[2]
    if not infile:
        print "enter the imput file within quotes"
        infile = input()
    if not outfile:
        print "enter the output file within quotes"
        outfile = input()
    Read_res_file(infile, outfile)
    
