#!/usr/bin/python

#Python script to run the various newchg calculations

import os
from math import *

#Read data file containing calculations to do
file=open('calclist','r')
text=file.readlines()
file.close()
calclist=[]
#Strip lines beginning with comments and the comments from lines
for line in text:
  if line.find('#')!=0:
    cmt=line.find('#')
    calc=line[:cmt]
    if len(calc)>2:
      calclist.append(calc)


#Loop over calculations, do analysis
resultstext=[]
ErrorLog=[]
for calc in calclist:
  #Directory to which to return
  initdir=os.getcwd()

  #Get rough estimate of ligand name for queue and to make sure we don't run the water/vacuum calcs more than once for a given ligand
  dirs=calc.split('/')
  ligname=dirs[0].replace('single_','s')
  #Calculation number
  calcnum=dirs[1].replace('ori','')

  os.chdir('%s/complex_nochg%s' % (dirs[0],calcnum))
  os.system('analyze.py -t chg --nodisplay')
  os.chdir('../complex_restr%s' % (calcnum))
  os.system('analyze.py -t rst --nodisplay')
  
  #Read results
  os.chdir('..')
  store=True
  try:
    file=open('complex_nochg%s/result.txt' % calcnum,'r')
    text=file.readline()
    file.close()
    [chgval,chgunc]=text.split()
  except IOError:
    ErrorLog.append('Error; could not read charging for %s ori%s\n' % (dirs[0],calcnum))
    store=False
  try:
    file=open('complex_restr%s/result.txt' % calcnum,'r')
    text=file.readline()
    file.close()
    [rstval,rstunc]=text.split()
  except IOError:
    ErrorLog.append('Error; could not read restraining for %s ori%s\n' % (dirs[0],calcnum))
    store=False

  #Compute combined value
  tot=float(chgval)+float(rstval)
  totunc=sqrt(float(chgunc)**2+float(rstunc)**2)
  #Store
  resultstext.append('%s_%s \t%.2f \t%.3f\n' %(dirs[0],calcnum,tot,totunc))

  #Back to base dir
  os.chdir(initdir)

file=open('results.dat','w')
file.writelines(resultstext)
file.close()
file=open("ErrorLog.dat",'w')
file.writelines(ErrorLog)
file.close() 
