#!/usr/bin/python

# script to get stats on number of returned WUs
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 *

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

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

for project in projectnumbers :
	try:
		currproj=availableProjects[ project ]
	except KeyError :
		print "project '%s' not found" % project
	else:
		print "reading '%s' ... " % currproj,
		conf = ProjectConfigurationFile( currproj )
		xtclist=glob( "%s/RUN*/CLONE*/*xtc" % conf.datapath )
		instablist=glob( "%s/RUN*/CLONE*/*instability" % conf.datapath )
		nxtc = len( xtclist )
		ninst = len( instablist )
		if ninst+nxtc > 0 :
			frac = 100 * float(ninst)/( ninst + nxtc )
			n = ( nxtc, ninst, frac )
			print "found %d returned WUs and %d instabilities (%3.1f pct)" % n
		else:
		        n = ( nxtc, ninst )
			print "found %d returned WUs and %d instabilities" % n
