#!/usr/bin/python

# script to analyze Error.log in the context of actual returned WUs
# specifically, if there is an error reported, was the WU returned
# otherwise? How many subsequent generations are there? Are the 
# descendants likely to produce frameX.instabilities?

from os.path import abspath
from glob import glob

fahtoolspath=abspath("../modules/fah_adaptive_sampling/FAHTools/") 
server2dir=abspath(".") 
SVr="" # not used in this script
serverBinary="" # not used in this script
###################################################

import sys
sys.path.append( fahtoolspath )
from FAHTrajectory import *
#from ProjectConfigurationFile import *
from FAHServer import *
from FAHErrorLog import *

errlogfile=abspath( "Error.log" )

projectnumbers=sys.argv[1:]
if not projectnumbers :
	print "Usage: ./errorstats.py <projnum1> <projnum2> ..."
	sys.exit()

print "Parsing %s ..." % errlogfile
errlog = FAHErrorLog( errlogfile )

print "Parsing server configuration ..."
server=FAHServer( server2dir, serverBinary, SVr=SVr )
availableProjects = server.projects

for project in projectnumbers :
	try:
		errlist = errlog.wusbyproject[ int(project) ]
		currproj=availableProjects[ project ]

	except KeyError:
		print "project '%s' not found in Error.log or in project.conf" % project

	else :
		conf = ProjectConfigurationFile( currproj )
		keys = errlist.keys()
		for key in keys :
			( job, err ) = errlist[ key ]
	
			traj = FAHTrajectory( conf.filename, job['run'], job['clone'] )	
			print "job '%s' has error '%s'" % ( job, err ), 
	
			# tests
			# this gen = job['gen']
			# 1. is the current gen (traj.currentGen) greater than this gen?
			# 2. how many .instability files are there in this traj, after this gen?
	
			s = [] 
			# check for instability in current
			if traj[ job['gen'] ][ 'instability' ]:
				s.append( "found frame%d.instability" % job['gen'] )
	
			# check for instability in subsequent
			if traj.ngens > 1 :
				ninstab=0
				for i in range( job['gen']+1, traj.ngens ):
					if traj[i]['instability'] :
						ninstab += 1
				s.append("%d instabilities in gens %d to %d" % ( ninstab, job['gen']+1, traj.currentGen ))
	
			if traj.currentGen > job['gen'] :
				s.append("current tpr = frame%d.tpr " % traj.currentGen)
	
			print ( "%s, " * len( s ) )[:-2] % tuple( s )
	
