# W_rapper is a super simple python wrapper for W
# Andrei Perhinschi - September 2010

# W_rapper records all of the reccomendations made by
# W into a file placed within a directory called results/
# created in the current directory. W_rapper needs to be
# run from the root directory of W with write privileges

# Usage: python W_wrapper.py <dataset> <test project> <times to run W>
# Example: python W_wrapper.py nasa93 ground

#!/usr/bin/python

import os, sys, time

def median(aList):
	size = len(aList)
	if size % 2 == 1:
		return aList[(size - 1)/2]
	else:
		return (aList[size/2 - 1] + aList[size/2] ) / 2

# this checks for the correct number of command line
# arguments but does nothing to make sure they are valid
if len(sys.argv) == 5:
	
	command = "discretize=15 bash w " + sys.argv[1] + " " + sys.argv[2]
else:
	
	print "Error: Wrong number of arguments"
	print "Usage: python W_wrapper.py <dataset> <test project> <times to run W> <total runs>\n"
	exit()

# initial variables
run = 1
supRun = 1
results = 0
suffix1 = "Reduction Summary-----------"
suffix2 = "Recommendations------------"
stat = ""
percent = ""
stats = []
percents = []
sums = []
lists = []
total_runs = int(sys.argv[3])
super_runs = int(sys.argv[4])
now_read = str(time.asctime())
now_num = str(time.time())
## filename = "results/results_" + now_num + ".txt"
filename = "results2/"+ sys.argv[1] + "_" + sys.argv[2] + "_x" + sys.argv[3] + "(5-15).txt"
header = "W RESULTS FILE\n\n" + \
		"Creation date: " + now_read + "\n" + \
		"Test project: " + sys.argv[2] + "\n" + \
		"Dataset: " + sys.argv[1] + "\n" + \
		"W was run " + sys.argv[3] + " times\n" + \
		"This many times " + sys.argv[4] + "\n\n"

# setting up output directory
try:
	
	os.mkdir ("results2")
	print "Results directory created under current directory\n"
except OSError:
	
	print "Results directory already exists..."


# output file handler
try:
	
	out = open(filename, "w")
	out.write(header)
except IOError:
	
	print "Error: You lack permission to write files here\n"
	exit()

# set the limit of this while loop to 
# however many times you want to run W
print "run"
while supRun <= super_runs:
	while run <= total_runs:

		demo = os.popen(command)
		lines = demo.readlines()
	
		for line in lines:
		
			# true if recommended values are on next line
			if line.find(suffix1) >= 0:	 	
				# set sentinel var and move on to the line we want
				results = 1
				continue
			if line.find(suffix2) >= 0:	 	
				# Kill sentinel var
				results = 0
				continue
			
			# when this evaluates true, the previous loop will have
			# ran once and made sure the line we are on now is the
			# one containing W's recommendations
			if results == 1:
				
				# print W output to stdout and file
				stat = line.split(':', 1)
				percent = stat[1].split('%', 1)
				stat = stat[0].strip()
				percent = percent[0].strip()
				percent = int(percent)
				if run == 1:
					stats.append(stat)
				percents.append(percent)
		run += 1
	i = 0
	itBy = len(stats)
	tmp = []
	for aClass in stats:
		j = i
		aSum = 0
		while (j < len(percents)):
			aSum += percents[j]
			tmp.append(percents[j])
			j += itBy
		sums.append(aSum)
		tmp.sort()
		lists.append(tmp)
		tmp = []
		i += 1
	i = 0
	for aSum in sums:
		sums[i] = aSum / (run -1)
		i += 1
	i = 0
	tmpStr = "%22s%7s%7s%7s%7s%7s%7s%7s" % ("Class", "Avg", "Med", "Q1", "Q3", "Spread", "Min", "Max")
	#tmpStr = "%22s%7s%7s%7s%7s" % ("Class", "Avg", "Med", "Min", "Max")
	print tmpStr
	out.write(tmpStr)
	out.write("\n")
	for aClass in stats:
		tmpList = lists[i]
		tmpMin = min(tmpList)
		tmpMax = max(tmpList)
		tmpQ1 = median(tmpList[0:(len(tmpList)/2)])
		tmpQ3 = median(tmpList[(len(tmpList)/2):len(tmpList)])
		tmpSpr = tmpQ3 - tmpQ1
		tmpStr = "%22s%7d%7d%7d%7d%7d%7d%7d" % (aClass, sums[i], median(tmpList), tmpQ1, tmpQ3, tmpSpr, tmpMin, tmpMax)	
		#tmpStr = "%22s%7d%7d%7d%7d" % (aClass, sums[i], median(tmpList), tmpMin, tmpMax)
		print tmpStr
		out.write(tmpStr)
		out.write("\n")
		i += 1
	
	out.write("\n")
	stats = []
	percents = []
	sums = []
	lists = []
	tmp = []
	supRun += 1
	run = 1
out.close()



	
			    




