#!/bin/bash
#modified WELL-elbow barr script

#changed site loop -->loop over the 10 positions
#used pes program instead of vdW

location=()
#location should contain u v theta phi
location+=("Atom 0.0 0.0 0.0 0.0")			#TOP
location+=("Atom 0.5 0.0 0.0 0.0")			#Bridge
location+=("Atom 0.66666666 0.33333333 0.0 0.0") 	#HCP
location+=("Atom 0.33333333 0.16666666 0.0 0.0")	#T2H
location+=("Atom 0.5 0.16666666 0.0 0.0")		#e
location+=("Atom 0.16666666 0.0 0.0 0.0")		#t
location+=("Atom 0.33333333 0.0 0.0 0.0")		#eta
location+=("Atom 0.16666666 -0.16666666 0.0 0.0")	#T2F
location+=("Atom 0.33333333 -0.16666666 0.0 0.0")	#e'
location+=("Atom 0.33333333 -0.33333333 0.0 0.0") 	#FCC
location+=("Atom 0.0 0.0 0.0 0.0")                      #TOP

#Checked positions using VESTA -->correct
#cp /home/guido/VASP/scripts/pes .
#for i in {0..9}
#do 
#  ./pes 3.6287 3 6 20 fix 0.00000 2.09503 4.18699 6.28615 8.37945 10.46748 ${location[$i]} 3 0 | tail -1
#  ./pes 3.6287 1 4 20 fix 0.00000 2.09503 4.18699 6.28615 ${location[$i]} 3 0 | tail -1
#done

#echo
#echo
#./pes 3.6287 3 6 20 fix 0.00000 2.09503 4.18699 6.28615 8.37945 10.46748 ${location[$i]}  
#./pes 3.6287 1 4 20 fix 0.00000 2.09503 4.18699 6.28615 ${location[$i]} 3 0
#rm pes
#exit 1

#relevant paths and variable
runname="AT"
smearing="MP"           #eg FE=FERMI MP=Methfessel Paxton TH=tetrahedron
sigma="0.2"
functional="DF2"        #functional to use: DF1=vdW-DF1 or DF2=vdW-DF2
uc=3                    #unit cell type eg. 1 2 or 3 for 1x1x1 2x2x2 or 3x3x3 bulk cell
kptype="Gamma"          #type of kpoint mesh Gamma, Monckhorst --> GAMMA for HEXAGONAL
Dvac=20                 #vacuum distance
walltime="8"           #walltime (h) 
LREALtag="Auto"         #projection scheme, can be: .TRUE. .FALSE. or Auto 
GGAtag="XC"
PARAM1="0.0"
ecut=450
a3D="3.63999" #B86SRP68-DF2
Dvac=20
#loop over layers
layers="6"              #at the moment only 5 6 7 layes can be retrieved from summary file 

#Kpoint range for which to perform calculations
kpoints="11"  				




#WELL  -->When WELL is selected the Rrange is Req from gasphase calculation
Rrange="0.0"
ZrangeALL="-1.133 -1.195 -1.06 -0.925 -0.79 -0.655 -0.52 -0.385 -0.29 -0.25 -0.155 -0.115 -0.1 0.0 0.1 0.115 0.155 0.25 0.29 0.385 0.425 0.56 0.695 0.83 0.965 1.1 1.235 1.37 1.505 1.64 1.775 1.91 2.045 2.18 2.315 2.45 2.585 2.72 2.855 2.9 3.125 3.26 3.395 3.53 3.665 3.8 3.935 4.07 4.205 4.34 4.475 4.61 4.745 4.88 5.0 5.15 5.3 5.45 5.6 5.75 5.9 6.05 6.20 6.35 6.50 6.65 6.9 7.2 7.5 7.8 8.2"
ZrangeTOP="0.0 -1.133 -1.195 -1.06 -1.000 -0.975 -0.950 -0.925 -0.900 -0.875 -0.850 -0.825 -0.800 -0.775 -0.750 -0.725 -0.700 -0.675 -0.650 -0.625 -0.600 -0.575 -0.550 -0.525 -0.500 -0.475 -0.450 -0.425 -0.400 -0.375 -0.350 -0.325 -0.300 -0.275 -0.250 -0.225 -0.200 -0.175 -0.150 -0.125 -0.100 -0.075 -0.050 -.025  0.025 0.050 0.075 0.100 0.125 0.150 0.175 0.200 0.225 0.250 0.275 0.300 0.325 0.350 0.375 0.400 0.425 0.450 0.475 0.500 0.525 0.550 0.575 0.600 0.625 0.650 0.675 0.700 0.725 0.750 0.775 0.800 0.825 0.850 0.875 0.900 0.925 0.950 0.975 1.000 1.025 1.050 1.075 1.100 1.125 1.150 1.175 1.200 1.225 1.250 1.275 1.300 1.325 1.350 1.375 1.400 1.425 1.450 1.475 1.500 1.525 1.550 1.575 1.600 1.625 1.650 1.675 1.700 1.725 1.750 1.775 1.800 1.825 1.850 1.875 1.900 1.925 1.950 1.975 2.000 2.025 2.050 2.075 2.100 2.125 2.18 2.315 2.45 2.585 2.72 2.855 2.9 3.125 3.26 3.395 3.53 3.665 3.8 3.935 4.07 4.205 4.34 4.475 4.61 4.745 4.88 5.0 5.15 5.3 5.45 5.6 5.75 5.9 6.05 6.20 6.35 6.50 6.65 6.9 7.2 7.5 7.8 8.2"
#rangeTOP="6.9 7.2 7.5 7.8"
#ZrangeALL="6.9 7.2 7.5 7.8"
Rrelax="NO"
count = 0
#echo "sites= $sites"
echo "Zrange= $Zrange "
for site in 0 1 2 3 4 5 6 7 8 9 
do
  if [ $site == "0" ]; then
    Zrange=$ZrangeTOP
  else
    Zrange=$ZrangeALL
  fi

  mkdir site${site}
  echo ${location[$site]}
  echo " Zrange= $Zrange "
  for Z in $Zrange
  do  
    ((count++))
  done
done
echo "total amount of jobs = $count "
echo "--------------------------------------------------------------------------------------"
echo
echo "CORRECT?  YES/NO"
#WhereYouAnIdiot=oops
#read WhereYouAnIdiot
#echo " WhereYouAnIdiot = $WhereYouAnIdiot "
#if [ "$WhereYouAnIdiot" != "YES" ]
#then 
#  echo "exiting script"
#  exit 1
#fi
#echo

#structure of summary file
echo "#site | Z | Rin[A] | Rcalc[A] | DFx | GGA | param1 | uc | KP | ENCUT[eV] | smear | SIGMA | a3Din[A] | a3Dcalc[A] | layers | Dvac[A] | TotalE[eV] | E(s->0)[eV]| entropy[eV] | pressure[KB] | h | theta | phi | Z(A) col=lays " >> ${runname}-summary.dat
kpmax=0
counter=0
for site in 0 1 2 3 4 5 6 7 8 9    
  do
  if [ $site == "0" ]; then
    Zrange=$ZrangeTOP
  else 
    Zrange=$ZrangeALL
  fi
  for Z in $Zrange
  do
    for R in $Rrange
    do
      for kp in $kpoints
      do
        for lay in $layers
        do

#systematic name of the sub folders
naming="${runname}-site${site}-Z${Z}-l${lay}-k${kp}-e${ecut}-s${sigma}" #CHECK GASPHASE NAMING

cd site${site}

mkdir ${naming}
cd ${naming}
echo ${naming}

if [ $GGAtag == "XC" ]; then
  cat >XCFUNC<<!
3
0.68 41  
0.32 117
1.0 12 
!
fi

if [ "$walltime" -le "8" ]
then
  que="small"
else
  que="long"
fi

#create Job file
cat >Job<<!
#!/bin/bash
#PBS -lwalltime=${walltime}:00:00  
#PBS -S /bin/bash
#PBS -lnodes=1:ppn=16
#PBS -N ${naming}
#PBS -q ${que}

# workdirectory
WORKDIR=\$PBS_O_WORKDIR
#make all nodes go to workdir
cd \${WORKDIR}

# make scratch directory
SCRATCH=/scratch/\${USER}/\${PBS_JOBID}
mkdir \${SCRATCH}
# copy files from one to other
scp -r \${WORKDIR}/* \${SCRATCH}/.

#go to scratch
cd \${SCRATCH}

#execute vasp with the generated input fules
mpiexec vasp-LIBXC

rm vasp-LIBXC

# copy files back
scp -r \${SCRATCH}/* \${WORKDIR}/.
#clean scratch
rm -r \${SCRATCH}/*

#go to workdir
cd \${WORKDIR}
rm vasp-LIBXC

#save relevant data to file summary.dat
#DO NOT FORGET escape characters!

#total energy 
E=\`tail -1 OSZICAR | awk '{print \$3}'\`
#entropy
entropy=\`grep EENTRO OUTCAR | tail -1 | awk '{print \$5}'\`
#E(s->0)
ES0=\`grep sigma OUTCAR | tail -1 | awk '{print \$7}'\`

#calculate a3D
a3D1=\`awk "NR==2" CONTCAR\`
a3D2=\`awk "NR==3" CONTCAR | awk '{print \$1}'\`
a3Dcalc=\`echo "scale=5; ( \$a3D1 * \$a3D2 * sqrt(2) / $uc ) / 1" | bc -l \`

#calculate z of atoms--------------------------------
#first the scaling factor
z3D1=\`awk "NR==2" CONTCAR\`
z3D2=\`awk "NR==5" CONTCAR | awk '{print \$3}'\`
Ztot=\`echo "( \$z3D1 * \$z3D2 ) " | bc -l\`

#then the other atoms
nr=10     #line with first atom position in CONTCAR
i=1
#each layer = 1 atom in primitive (111) cell -> totat = uc *uc *layer
totatoms=\`echo " $uc * $uc * $lay " | bc -l \`
Zatoms=\`awk "NR==10" CONTCAR | awk '{print \$3}'\`
Zold=\$Zatoms
while [ "\$i" -lt "\$totatoms" ]
do
  nr=\$((\$nr + 1))
  i=\$((\$i + 1))
  Znew=\`awk "NR==\$nr" CONTCAR | awk '{print \$3}'\`

  if [ "\$Znew" != "\$Zold" ]
  then
    Zold=\$Znew
    Znew=\`echo "scale=5; ( \$Znew * \$Ztot ) / 1" | bc -l \`
    Zatoms="\$Zatoms \$Znew"
  fi
done #while
#----------------------------------------------------

#pressure
P=\`grep -m 1 pressure OUTCAR | awk '{print \$4}'\`
#----------------------------------------------------

#----------------------------------------------------

calctime=\`grep "System time (sec):" OUTCAR | awk '{print \$4}'\`
calctime=\`echo "scale=1; ((\$calctime * 1000) / 60 ) / 60 " | bc -l \`


#print results to summary
echo "$site $Z $functional $GGAtag $PARAM1 $uc $kp $ecut $smearing $sigma $a3D \$a3Dcalc $lay $Dvac \$E \$ES0 \$entropy \$P \$calctime \$Zatoms " >> ../${runname}-summary.dat
!

#create kpoints file [MP for bulk / GAMMA for hexagonal]
cat >KPOINTS<<!
Automatic Mesh
0
$kptype
$kp $kp 1
0. 0. 0.
!

if [ $Rrelax == "YES" ]; then
  IBRION="1 "
else
  IBRION="-1 "
fi
#create INCAR file - DO NOT USE TABS IN INCAR FILE!!!!! 
cat >INCAR<<!
SYSTEM = Cu-LA_REL SPBXX-vdW-${functional} ${uc}x${uc} Dvac=${Dvac}

PREC=Accurate
ALGO=Fast               #this selects a mixture of algorithms, inlcuding ialgo38
LREAL=${LREALtag}       #projection operators

NELM=60                 #number of SCF steps 
NELMIN=3                #minimum SCF steps
NELMDL=-8              #number of steps H is not updated on start

ISTART=0                #start from scratch
INIWAV=1                #fill wave function with random numbers


IBRION=$IBRION
ISIF=1                 

EDIFF=1.E-5             #global break conidition SC-loop
ENCUT=$ecut             #plain wave cutoff [eV]

LCHARGE = .FALSE.       #do not write charge density dile
LWAVE = .FALSE.         #do write wave function file

NPAR = 2                #recommended for parallelization
LPLANE=.TRUE.          #recommended for parallelization
NSIM=4                  #recommended for parallelization


!
#add smearing type to INCAR
if [ "$smearing" == "FE" ]
then
  echo "#Fermi smearing " >> INCAR
  echo "ISMEAR=-1 " >> INCAR 
  echo "SIGMA=${sigma} " >> INCAR
elif [ "$smearing" == "MP" ]
then
  echo "#Methfessel Paxton smearing " >> INCAR
  echo "ISMEAR=1 " >> INCAR
  echo "SIGMA=${sigma} " >> INCAR
elif [ "$smearing" == "TH" ] 
then
  echo "#Tetrahedron smearing " >> INCAR
  echo "ISMEAR=-5 " >> INCAR
else
  echo "NO VALID SMEARING SELECTED! "
  exit 1
fi

#add DF type to INCAR
if [ "$functional" == "DF1" ]
then
  echo "#vdW-DF1 functional - Dion et al. " >> INCAR
  echo "GGA=${GGAtag}  " >> INCAR
  echo "LUSE_VDW=.TRUE. " >> INCAR
  echo "AGGAC=0.0000 " >> INCAR
  echo "PARAM1=${PARAM1}  " >> INCAR
elif [ "$functional" == "DF2" ]
then
  echo "#vdW-DF2 functional - Lee et al. " >> INCAR
  echo "GGA=${GGAtag}  " >> INCAR
  echo "LUSE_VDW=.TRUE. " >> INCAR
  echo "Zab_vdW=-1.8867 " >> INCAR
  echo "AGGAC=0.0000 " >> INCAR
  echo "PARAM1=${PARAM1}  " >> INCAR
elif [ "$functional" == "DF2.2" ]
then 
  echo "#good luck with your DF experiment! ">> INCAR
  echo "GGA=${GGAtag}  " >> INCAR
  echo "LUSE_VDW=.TRUE.  " >> INCAR
  echo "Zab_vdW=-2.2 " >> INCAR
  echo "AGGAC=0.0000 " >> INCAR
  echo "PARAM1=${PARAM1}  " >> INCAR
elif [ "$functional" == "DF1.4" ]
then
  echo "#good luck with your DF experiment! ">> INCAR
  echo "GGA=${GGAtag}  " >> INCAR
  echo "Zab_vdW=-1.4 " >> INCAR
  echo "LUSE_VDW=.TRUE.  " >> INCAR
  echo "AGGAC=0.0000 " >> INCAR
  echo "PARAM1=${PARAM1}  " >> INCAR
elif [ "$functional" == "DFoptPBE" ] 
then
  echo "#optPBE vdW " >> INCAR
  echo "GGA=BO " >> INCAR
  echo "PARAM1 = 0.1833333333 " >> INCAR
  echo "PARAM2 = 0.2200000000 " >> INCAR
  echo "LUSE_VDW = .TRUE. " >> INCAR
  echo "AGGAC=0.0000 " >> INCAR
elif [ "$functional" == "NO" ]
then
  echo "#no vdW " >> INCAR
  echo "GGA=${GGAtag} " >>INCAR
  echo "PARAM1=${PARAM1}  " >> INCAR
else
  echo "NO VALID vdW-DF selected! "
  exit 1
fi

#PAW potentials needed Copy correct POTCAR file
cat /home/guido/VASP/PseudopotentialsVASP/PAWPBE/Cu/POTCAR /home/guido/VASP/PseudopotentialsVASP/PAWPBE/H/POTCAR > POTCAR
#copy vdW-kernel file
cp /home/guido/VASP/PseudopotentialsVASP/vdw_kernel.bindat .
#copy vasp executable
cp /home/guido/VASP/VASP-LIBXC/vasp.5.3.5/vasp-LIBXC .

#create POSCAR using POSCAR script
cp /home/guido/VASP/scripts/pes .
totatom=`echo " ($uc * $uc * $lay ) + 9 + 2" | bc -l `
#  ./pes 3.6287 3 6 20 fix 0.00000 2.09503 4.18699 6.28615 8.37945 10.46748 ${location[$i]} 12 0 | tail -1
#./pes $a3D $uc $lay $Dvac fix 0.00000 2.09503 4.18699 6.28615 8.37945 10.46748 ${location[$site]} $Z $R > POSCAR #SRPsol75-DF2
#./pes $a3D $uc $lay $Dvac fix 0.00000 2.09861 4.19334 6.29482 8.39086 10.48173 ${location[$site]} $Z $R > POSCAR #SRPsol70-DF2
#./pes $a3D $uc $lay $Dvac fix 0.00000 2.10224 4.20037 6.30562 8.40488 10.49969 ${location[$site]} $Z $R > POSCAR #SRPsol65-DF2
./pes $a3D $uc $lay $Dvac fix 0.00000 2.10154 4.19923 6.30387 8.40225 10.49567 ${location[$site]} $Z $R > POSCAR #B86SRP68-DF2
echo " " >> POSCAR
rm pes

if [ $kp -gt $kpmax ]; then
  kpmax=$kp
fi

qsub Job
((counter++))
cd .. 
cd ..
        done #lay
      done #kp
    done #R
  done #Z
done #site

exit 1
#retrieve highest kp
#loop over layers -> gas reference for each amount of layers
#theta and phi should not matter
#site should not matter
#cp everything except kp file -> create new KP file according to kpmax
#gasphase reference calculation
Zgas=`echo "scale=2; $Dvac / 2" | bc -l `
for lay in $layers
do 
  ((counter++))
  mkdir ${runname}-GAS-Z${Zgas}-R${Req}-t${theta}-p${phi}-l${lay}-k${kp}-e${ecut}-s${sigma}
  cd ${runname}-GAS-Z${Zgas}-R${Req}-t${theta}-p${phi}-l${lay}-k${kp}-e${ecut}-s${sigma}
  echo "${runname}-GAS-Z${Zgas}-R${Req}-t${theta}-p${phi}-l${lay}-k${kp}-e${ecut}-s${sigma}"
  cp ../${naming}/INCAR .
  cp ../${naming}/POTCAR .
  #cp ../${naming}/KPOINTS .
  cp ../${naming}/vdw_kernel.bindat .
  cp ../${naming}/vasp-LIBXC .
cat >KPOINTS<<!
Automatic Mesh
0
$kptype
$kpmax $kpmax 1
0. 0. 0.
!
  if [ $GGAtag == "XC" ]; then
    cp ../${naming}/XCFUNC .
  fi
  less ../${naming}/Job | head -4 > Job
  echo "#PBS -N GAS" >> Job
  Jobl=`wc -l ../${naming}/Job | awk '{print $1}'`
  Jobl=`echo "$Jobl -5" | bc -l `
  less ../${naming}/Job | tail -$Jobl | head -$(($Jobl-1)) >> Job
  echo "echo \"#GAS $Zgas $Req \$Rcalc $functional $GGAtag $PARAM1 $uc $kp $ecut $smearing $sigma $a3D \$a3Dcalc $lay $Dvac \$E \$ES0 \$entropy \$P \$Zatoms \" >> ../${runname}-summary.dat" >> Job
  #bottom two lines of poscar script have fixed position for H
  totatom=`echo " ($uc * $uc * $lay ) + 9 " | bc -l `
  cp /home/guido/VASP/scripts/vdW .
  ./vdW $a3D $uc $lay $Dvac fix $layerpos $Req BtH $Zgas $theta $phi | head -${totatom} > POSCAR
  ./vdW $a3D $uc $lay $Dvac fix $layerpos $Req BtH $Zgas $theta $phi | tail -2 >> POSCAR
  rm vdW
  #qsub Job
  cd ..
done
echo "total jobs = $counter "
