#!/bin/sh

# run from directory where this script is
cd `echo $0 | sed 's/\(.*\)\/.*/\1/'` # extract pathname
EXAMPLE_DIR=`pwd`

# check whether ECHO has the -e option
if test "`echo -e`" = "-e" ; then ECHO=echo ; else ECHO="echo -e" ; fi

$ECHO
$ECHO "$EXAMPLE_DIR : starting"
$ECHO
$ECHO "This example shows how to use pw.x and ph.x to compute IR and Raman spectra"
$ECHO "for a CO2 molecule and for ZnO in the Wurtzite structure."
$ECHO "After the calculation, a gnuplot window posp up with both spectra."
$ECHO "NOTE: Raman calculation currently disabled (not implemented for GGA)."
$ECHO " "

# set the needed environment variables
. ../../../environment_variables

# Uncomment the following line if you want to calculate in parallel and the PARA_PREFIX was not set
#PARA_PREFIX="mpirun -np 8 "


# required executables and pseudopotentials
BIN_LIST="pw.x ph.x dynmat.x"
PSEUDO_LIST=" C.pbe-hgh.UPF O.pbe-hgh.UPF Zn.pbe-d-hgh.UPF"


$ECHO
$ECHO "  executables directory: $BIN_DIR"
$ECHO "  pseudo directory:      $PSEUDO_DIR"
$ECHO "  temporary directory:   $TMP_DIR"
$ECHO "  checking that needed directories and files exist...\c"

# check for directories
for DIR in "$BIN_DIR" "$PSEUDO_DIR" ; do
    if test ! -d $DIR ; then
        $ECHO
        $ECHO "ERROR: $DIR not existent or not a directory"
        $ECHO "Aborting"
        exit 1
    fi
done
for DIR in "$TMP_DIR" "$EXAMPLE_DIR/results" ; do
    if test ! -d $DIR ; then
        mkdir $DIR
    fi
done
cd $EXAMPLE_DIR/results

# check for executables
for FILE in $BIN_LIST ; do
    if test ! -x $BIN_DIR/$FILE ; then
        $ECHO
        $ECHO "ERROR: $BIN_DIR/$FILE not existent or not executable"
        $ECHO "Aborting"
        exit 1
    fi
done

# check for pseudopotentials
for FILE in $PSEUDO_LIST ; do
    if test ! -r $PSEUDO_DIR/$FILE ; then
       $ECHO
       $ECHO "Downloading $FILE to $PSEUDO_DIR...\c"
            $WGET $PSEUDO_DIR/$FILE $NETWORK_PSEUDO/$FILE 2> /dev/null
    fi
    if test $? != 0; then
        $ECHO
        $ECHO "ERROR: $PSEUDO_DIR/$FILE not existent or not readable"
        $ECHO "Aborting"
        exit 1
    fi
done
$ECHO " done"


$ECHO
# how to run executables
PW_COMMAND="$PARA_PREFIX $BIN_DIR/pw.x $PARA_POSTFIX"
$ECHO "  running pw.x as: $PW_COMMAND"
PH_COMMAND="$PARA_PREFIX $BIN_DIR/ph.x $PARA_POSTFIX"
$ECHO "  running ph.x as: $PH_COMMAND"
DM_COMMAND=" $BIN_DIR/dynmat.x"
$ECHO "  running dynmat.x as: $DM_COMMAND"
$ECHO

# check for gnuplot
GP_COMMAND=`which gnuplot 2>/dev/null`
if [ "$GP_COMMAND" = "" ]; then
        $ECHO
        $ECHO "gnuplot not in PATH"
        $ECHO "Results will not be plotted"
fi


# clean TMP_DIR
$ECHO "  cleaning $TMP_DIR...\c"
rm -rf $TMP_DIR/CO2*
rm -rf $TMP_DIR/_ph0/CO2*
$ECHO " done"


# self-consistent calculation for CO2
cat > co2.scf.in << EOF
&CONTROL
  calculation  = "scf",
  prefix       = "CO2",
  pseudo_dir   = "$PSEUDO_DIR",
  outdir       = "$TMP_DIR",
/
&SYSTEM
  ibrav     = 1,
  celldm(1) =14.0,
  nat       = 3,
  ntyp      = 2,
  ecutwfc   = 80.D0, !better 120
/
&ELECTRONS
  conv_thr    = 1.D-8,
  mixing_beta = 0.7,
/
&IONS
/
ATOMIC_SPECIES
  C 12.010  C.pbe-hgh.UPF
  O 15.999  O.pbe-hgh.UPF
ATOMIC_POSITIONS (angstrom)
C        3.000042068   3.000042068   3.544613556
O        3.835408973   3.835408973   3.543705292
O        2.164548959   2.164548959   3.543681153
K_POINTS (automatic)
1 1 1 0 0 0
EOF

$ECHO "  running the SCF for CO2...\c"
$PW_COMMAND < co2.scf.in > co2.scf.out
check_failure $?
$ECHO " done"

# self-consistent phonon calculation with ph.x for CO2
cat > co2.ph.in << EOF
Normal modes for CO2
 &inputph
  tr2_ph=1.0d-14,
  prefix='CO2',
  amass(1)=12.010,
  amass(2)=15.999,
  outdir='$TMP_DIR'
  epsil=.true.,
  trans=.true.,
  asr=.true.
  ! lraman=.true.
  fildyn='dmat.co2'
 /
 0.0 0.0 0.0
EOF
$ECHO "  running phonon calculation of CO2...\c"
$PH_COMMAND < co2.ph.in > co2.ph.out
check_failure $?
$ECHO " done"

# extract phonon data with dynmat.x
cat > co2.dm.in << EOF
 &input fildyn='dmat.co2', asr='zero-dim' /
EOF
$ECHO " Extracting phonon data with dynmat...\c"
$DM_COMMAND < co2.dm.in > co2.dm.out
check_failure $?
$ECHO " done"


$ECHO "The data for spectrum is after '# mode   [cm-1]    [THz]      IR' on  co2.dm.out"
awk 'NR==1,/mode/{next}/DYNMAT/,NR==0{next}{print}' co2.dm.out > plotdata_co2.dat

$ECHO "Trying to plot it with gnuplot..."


cat > plot_command_co2.cmd << EOF
 set lmargin 8
 set rmargin 3
 
 set multiplot
 set key left top
 set origin 0.0,0.5
 set size 1,0.5
 set yrange [0:] 
 set format x ""
 set tmargin 1
 plot 'plotdata_co2.dat' u (\$2):(\$3) title ' CO2-RAMAN' w i lw 2

 set key left bottom
 set origin 0.0,0.0
 set size 1,0.587
 set yrange [0:] reverse
 set format x
 set xlabel "Wavenumber [cm-1]"
 set bmargin 3
 set ylabel "Intensity" offset 0,5
 plot 'plotdata_co2.dat' u (\$2):(\$4) title 'CO2-IR' w i lw 2 lc 2 
 set nomultiplot
EOF


if [ "$GP_COMMAND" = "" ]; then
    $ECHO "No plot will be produced, because gnuplot was not found in the \$PATH "
    break
else
  $GP_COMMAND -persist plot_command_co2.cmd &
   
fi

# clean TMP_DIR
$ECHO "  cleaning $TMP_DIR...\c"
rm -rf $TMP_DIR/ZNO*
rm -rf $TMP_DIR/_ph0/ZNO*
$ECHO " done"



# self-consistent calculation for Wurtzite (ZnO)
cat > zno.scf.in << EOF
&CONTROL
  calculation  = "scf",
  prefix       = "ZNO",
  pseudo_dir   = "$PSEUDO_DIR",
  outdir       = "$TMP_DIR",
/
&SYSTEM
  ibrav=0, celldm(1) =6.330582528, nat=4, ntyp= 2,
  occupations='smearing', smearing='gauss', degauss=0.02,
  ecutwfc =80.0, !better 140
/
&ELECTRONS
  mixing_mode='plain'
  mixing_beta = 0.5,
  startingwfc='random',
  conv_thr =  1.0d-8
/
CELL_PARAMETERS alat
  1.55820896     0.00000000     0.00000000
  0.00000000     0.86602540     -0.50000000
  0.00000000     0.00000000     1.00000000
ATOMIC_SPECIES
  Zn 65.409  Zn.pbe-d-hgh.UPF
  O  15.999  O.pbe-hgh.UPF
ATOMIC_POSITIONS (alat)
Zn       2.010975287   0.487933254  -0.051360548
Zn       1.234717421   0.199473387   0.448322227
O        1.051679030   0.488287222  -0.051814333
O        1.830251369   0.199830262   0.448810714
K_POINTS (automatic)
2 2 2 0 0 0

EOF

$ECHO "  running the SCF for Wurtzite...\c"
$PW_COMMAND < zno.scf.in > zno.scf.out
check_failure $?
$ECHO " done"

# self-consistent phonon calculation with ph.x for Wurtzite
cat > zno.ph.in << EOF
Normal modes for Wurtzite
 &inputph
  tr2_ph=1.0d-14,
  prefix='ZNO',
  amass(1)=65.409,
  amass(2)=15.999,
  outdir='$TMP_DIR'
  epsil=.false.,
  ! lraman=.true.
  trans=.true.,
  asr=.true.
  fildyn='dmat.zno'
 /
 0.0 0.0 0.0
EOF
$ECHO "  running phonon calculation of ZnO...\c"
$PH_COMMAND < zno.ph.in > zno.ph.out
check_failure $?
$ECHO " done"

# extract phonon data with dynmat.x
cat > zno.dm.in << EOF
 &input fildyn='dmat.zno', asr='zero-dim' /
EOF
$ECHO " Extracting phonon data with dynmat...\c"
$DM_COMMAND < zno.dm.in > zno.dm.out
check_failure $?
$ECHO " done"


$ECHO "The data for spectrum is after '# mode   [cm-1]    [THz]      IR' on  zno.dm.out"
awk 'NR==1,/mode/{next}/DYNMAT/,NR==0{next}{print}' zno.dm.out > plotdata_zno.dat

$ECHO "Trying to plot it with gnuplot..."


cat > plot_command_zno.cmd << EOF
 set lmargin 8
 set rmargin 3

 set multiplot
 set key left top
 set origin 0.0,0.5
 set size 1,0.5
 set yrange [0:] 
 set format x ""
 set tmargin 1
 plot 'plotdata_zno.dat' u (\$2):(\$3) title ' ZnO-RAMAN' w i lw 2

 set key left bottom
 set origin 0.0,0.0
 set size 1,0.587
 set yrange [0:] reverse
 set format x
 set xlabel "Frequency [cm-1]"
 set bmargin 3
 set ylabel "Intensity" offset 0,5
 plot 'plotdata_zno.dat' u (\$2):(\$4) title 'ZnO-IR' w i lw 2 lc 2 
 set nomultiplot
EOF


if [ "$GP_COMMAND" = "" ]; then
    $ECHO "No plot will be produced, because gnuplot was not found in the \$PATH "
    break
else
  $GP_COMMAND -persist plot_command_zno.cmd &
   
fi


$ECHO "The results on the ZnO spectrum can be compared with"
$ECHO "http://www.nature.com/srep/2013/131021/srep02999/pdf/srep02999.pdf"
$ECHO " providing acceptable values for such a cheap calculation."




$ECHO
$ECHO "$EXAMPLE_DIR: done"
