#!/bin/sh
# batch processing commands
#PBS -l walltime=119:59:00
#PBS -lselect=1:ncpus=12:mem=48000MB
#PBS -j oe
#PBS -q pqph
#PBS -m n
#set the -m to -ae to get the email

#MODIFICATION of the .rng script. Runs code to create an optimially tuned range-seperated hybrid functional for the input system,
#and outputs the SPE calculation + a .out file which details the optimisation procedure (the range seperation parameter mu is optimised)
#This .rng gets called by the gf_OTRSH function

#IMPORTANT OPTIONS(relevant ones get printed in .out file):
xc_funct="CAM-B3LYP"    #base exchange +  correlation functionals to use in standard g09 format (e.g "BLYP" "PBEPBE" "SVWN" etc.)
#xc_funct="PBEPBE"
P5_val=0.81     #P5 value in the "User defined functional" part of g09 website. Determines amount of non-local correlation (advise you use the default for a functional,last value of ScaDFX in an output file)
#P5_val=1.00
#alpha_val=0.19  #short range HF exchange. Represents same quantity as alpha does in original CAM-B3LYP paper
#beta_val=0.81   #alpha+beta = long range HF exchange. Beta represents same quantity as in original CAM-B3LYP paper
alpha_val=0
beta_val=1
#Initial search range. NOTE: the code will look outside this range if neccesary, but it makes it faster if the minimum occurs in this range (preferably near the middle of the range)
mu_lower=0.1    #Lower end of initial mu search range (mu=range sep parameter).
mu_upper=0.2    #Upper end of initial mu search range (mu=range sep parameter).
es_mult=2       #multiplicity of the ionised state (set non-ionised state multiplicity in the original .com file)
max_cycles=25	#maximum mu values that will be tried before optimisation terminates
min_step=0.001  #Minimum change in mu between optimisation cycles
max_step=0.03 #maximum change in mu between optimisation cycles
#
module load gaussian/g09-d01
module load python/3.4.2

# check for a checkpoint file-from .rng. Couldnt be bothered to remove.
#
# variable PBS_O_WORKDIR=directory from which the job was submited.
   test -r $PBS_O_WORKDIR/${in%.com}.chk
   if [ $? -eq 0 ]
   then
     echo "located $PBS_O_WORKDIR/${in%.com}.chk"
     cp $PBS_O_WORKDIR/${in%.com}.chk $TMPDIR/.
   else
     echo "no checkpoint file $PBS_O_WORKDIR/${in%.com}.chk"
   fi
#
# run gaussian
#
# g09 $PBS_O_WORKDIR/${in}
#  g09 $TMPDIR/${in}

#Setting up/running the initial .com runs.
cp $PBS_O_WORKDIR/${in}.com $TMPDIR/
base_fname=$TMPDIR/${in}.com #The original .com file
init_OTRSH.py	$base_fname $xc_funct $P5_val $alpha_val $beta_val $mu_lower $mu_upper $es_mult   #Sets up all initial files
#Sorting out the .chk names in new files
file1=${base_fname/.com/_gsstate_muhigh.com}
file2=${base_fname/.com/_gsstate_mulow.com}
file3=${base_fname/.com/_ionstate_muhigh.com}
file4=${base_fname/.com/_ionstate_mulow.com}
mkdir /$PBS_O_WORKDIR/temp_files_${in} #Holds intermediatary files, allows monitoring of job somewhat
#sed -i "s/chk=.*chk/chk="${file1/.com/.chk}"/" ${file1}
#$TMPDIR/tempfile1>${file1}
#sed "s/%chk=.*chk/%chk=${file2/.com/.chk}/" ${file2}>${file2}
#echo ${file2}
#$TMPDIR/tempfile2>${file2}
#sed "s/%chk=.*chk/%chk=${file3/.com/.chk}/" ${file3}>$TMPDIR/tempfile3
#$TMPDIR/tempfile3>${file3}
#sed "s/%chk=.*chk/%chk=${file4/.com/.chk}/" ${file4}>$TMPDIR/tempfile4
#$TMPDIR/tempfile4>${file4}

g09 $file1
g09 $file2
g09 $file3
g09 $file4
optimiser_OTRSH.py $base_fname $max_cycles $min_step $max_step	#Import results from initial jobs + work out next mu param to try



opt_complete=0	#Turns to 1 once tuning is finished
base_dir=${base_fname%/*}
echo $base_dir
while [ $opt_complete -eq 0 ]
	do
	#Checking convergence
	if grep --quiet 'GRADIENT OPTIMISATION COMPLETE' ${base_fname/.com/_OTRSH.out}; then	#Two cchecks for whether opt is finished
		opt_complete=1
	fi
        if grep --quiet 'GRADIENT OPTIMISATION REACHED MAX CYCLES' ${base_fname/.com/_OTRSH.out}; then     #Two cchecks for whether opt is finished
                opt_complete=1
        fi
	#Now running calcs if optimisation wasnt completed+running a load of error checks on output files
	if [ $opt_complete -eq 0 ]; then
		file1=${base_fname/.com/_gsstate_mulow.com}
		file2=${base_fname/.com/_ionstate_mulow.com}
#		sed -i "s/%chk=.*chk/%chk=${file1/.com/.chk}/" ${file1}
#		sed "s/%chk=.*chk/%chk=${file1/.com/.chk}/" ${file1}>$TMPDIR/temp_file
#		$TMPDIR/temp_file>${file1}
#		sed -i "s/%chk=.*chk/%chk=${file2/.com/.chk}/" ${file2}
#		sed -i "s/%chk=.*chk/%chk=${file2/.com/.chk}/" ${file2}>$TMPDIR/temp_file
#		temp_file>${file2}
#		rm any previous .chk with same extension at this point DIR=${VAR%/*}
		rm ${file1/.com/.chk}
		rm ${file2/.com/.chk}
		g09 ${base_fname/.com/_gsstate_mulow.com}
		g09 ${base_fname/.com/_ionstate_mulow.com}
		sleep 1
		optimiser_OTRSH.py $base_fname $max_cycles $min_step $max_step
		cp ${base_fname/.com/_OTRSH.out} /$PBS_O_WORKDIR/.	#Copy the output file to input folder, allows constant monitoring of the job
                cp ${base_fname/.com/_ionstate_mulow.log}  /$PBS_O_WORKDIR/temp_files_${in}/ionstate_intermediate.log
                cp ${base_fname/.com/_gsstate_mulow.log}  /$PBS_O_WORKDIR/temp_files_${in}/gstate_intermediate.log		
                if grep --quiet 'Convergence failure' ${file1/.com/.log}; then #If convergence failure then need to kill job anoyingly
                        echo Script exiting due to a convergence failure in $file1
                        echo "Script exiting due to convergence failure(Probably) - check temp files">>${base_fname/.com/_OTRSH.out}
			cp ${base_fname/.com/_OTRSH.out} /$PBS_O_WORKDIR/.
                        exit 1
                fi
	
	        if grep --quiet 'Convergence failure' ${file2/.com/.log}; then #If convergence failure then need to kill job anoyingly
                        echo Script exiting due to a convergence failure in $file1
			echo "Script exiting due to convergence failure(Probably) - check temp files">>${base_fname/.com/_OTRSH.out}
			cp ${base_fname/.com/_OTRSH.out} /$PBS_O_WORKDIR/.
                        exit 1
                fi


		if grep --quiet 'Error termination' ${file1/.com/.log} ${file2/.com/.log}; then
			echo Script exiting due to a syntax error in input file
			echo "Script exiting due to a syntax error in input file(Probably)">>${base_fname/.com/_OTRSH.out}
			cp ${base_fname/.com/_OTRSH.out} /$PBS_O_WORKDIR/.
			exit 1
		fi


	fi
done




#renaming the final job, which represents the SPE with the tuned parameters
mv $file1 ${file1/_mulow.com/_mu_opt.com}
mv ${file1/_mulow.com/_mulow.chk} ${file1/_mulow.com/_mu_opt.chk}
mv ${file1/_mulow.com/_mulow.log} ${file1/_mulow.com/_mu_opt.log}

mv $file2 ${file2/_mulow.com/_mu_opt.com}
mv ${file2/_mulow.com/_mulow.chk} ${file2/_mulow.com/_mu_opt.chk}
mv ${file2/_mulow.com/_mulow.log} ${file2/_mulow.com/_mu_opt.log}


#Copying files back to input directory
  cp ${file1/_mulow.com/_mu_opt.com} /$PBS_O_WORKDIR/.
  cp ${file1/_mulow.com/_mu_opt.chk} /$PBS_O_WORKDIR/.
  cp ${file1/_mulow.com/_mu_opt.log} /$PBS_O_WORKDIR/.
  cp ${base_fname/.com/_OTRSH.out} /$PBS_O_WORKDIR/.
  cp ${file2/_mulow.com/_mu_opt.com} /$PBS_O_WORKDIR/.
  cp ${file2/_mulow.com/_mu_opt.chk} /$PBS_O_WORKDIR/. 
  cp ${file2/_mulow.com/_mu_opt.log} /$PBS_O_WORKDIR/.
  cp $TMPDIR/${in%.com}.chk /$PBS_O_WORKDIR/.
  cp $TMPDIR/${in%.com}.wfx /$PBS_O_WORKDIR/.
  cp $TMPDIR/points.off /$PBS_O_WORKDIR/.
  cp $TMPDIR/charge.off /$PBS_O_WORKDIR/.
#  cp *.chk /$PBS_O_WORKDIR/pbs_${in%.com}.chk
#  test -r $TMPDIR/fort.7
#  if [ $? -eq 0 ]
#  then
#    cp $TMPDIR/fort.7 /$PBS_O_WORKDIR/${in%.com}.mos
#  fi
# exit
