#!/bin/bash

########################################################################
# HighTune bench.sh
# Author : Hourdin et al., frederic.hourdin@lmd.jussieu.fr
# This is both an automatic bench for the highTune tools and
# a guide on who to use it.
# Many applications can be run directly with thiis script
########################################################################

#-----------------------------------------------------------------------
# Reproduce the cases of HighTune paper II
# -------------------------------------------------
#
# ./bench.sh -wdir ArtII1 -waves "`seq 1 20`" -param param_ArtII1 -metrics "ARMCU_REF_zav-400-600-theta_7_9,ARMCU_REF_zav-400-600-qv_7_9,ARMCU_REF_nebmax_7_9,RICO_REF_nebmax_19_25,SANDU_REF_neb4zave_50_60"
#
# ./bench.sh -wdir ArtII2 -waves "`seq 1 40`" -param param_ArtII2 -sample_size 3000000 -sample_size_next_design 90 -metrics "ARMCU_REF_zav-400-600-theta_7_9,ARMCU_REF_zav-400-600-qv_7_9,IHOP_REF_zav-400-600-theta_7_9,ARMCU_REF_nebzave_7_9,ARMCU_REF_neb4zave_7_9,ARMCU_REF_nebmax_7_9,RICO_REF_nebmax_19_25,SANDU_SLOW_neb4zave_50_60,SANDU_REF_neb4zave_50_60,SANDU_REF_nebzave_50_60,SANDU_FAST_neb4zave_50_60"
#-----------------------------------------------------------------------


########################################################################
# 0/ Initialisation and contols
########################################################################

# 0.1/ Default values
model=LMDZ
metrics="ARMCU_REF_zav-400-600-qv_7_9 RICO_REF_nebmax_19_25 SANDU_REF_neb4zave_50_60"
metrics=RICO_REF_nebmax_9_9
param=param
waves=1 # could be waves=`seq 1 15`, waves="1 2 3"
serie="" 
sample_size=300000
sample_size_next_design=45

# 0.2/ Control of the HighTune tree
if [ `pwd | grep -o HighTune | wc -l` -gt 1 ]
then
  echo "Careful: the HighTune string appears more than once in your current directory:"
  pwd
  echo "This is going to be a problem! Make sure it appears only once!"
  # some sed commands won't work otherwise; this should be improved.
  exit
fi

# 0.3/ options
while (($# > 0)) ; do
        case $1 in
          -serie) serie=$2 ; shift ; shift ;; # useful for ecRad runs 
          -wdir) wdir=$2 ; shift ; shift ;;
          -param) param=$2 ; shift ; shift ;;
          -sample_size) sample_size=$2 ; shift ; shift ;;
          -sample_size_next_design) sample_size_next_design=$2 ; shift ; shift ;;
          -waves)  waves="$2"  ; shift ; shift ;;
          -model) model=$2 ; shift ; shift ;;
          -metrics) metrics="`echo $2 | sed -e 's/,/ /g'`" ; shift ; shift ;;
          -h|-help|--help) echo Usage: $0 "[-param param_file] [-waves "1 [2 3 ...]"] [-wdir DIRNAME] [-sample_size sample_size] [-model model] [-metrics metrics1,metrics2,...] or directly "$0 model"" ; cat <<eod
-param param_file : param_file contains the name, the min/max/nominal values, and the mode of exploration Linear/Log
                    of the parameters
-wdir WDIR        : the history matching sequence will be run on WORK/WDIR
-waves WAVES      : WAVES is a sequence of numbers. 1 ; "1 2 3" ; "\`seq 1 20\`" 
                    Can start at N+1 if waves 1 to N are already done
-sample_size SAMPLESIZE : sample size for the NROY graphics
-sample_size_next_design SAMPLESIZENEX : sample size for next design
-model MODEL      : name of MODEL, available on models/
-metrics METRICS  : METRICS is a list of metrics separated by "," or " "
eod
                exit 0 ;;
          *) model=$1 ; shift ;;
        esac
done

# 0.4/ Temporary trick to be able to compare old (ExeterUQ) and new (ExeterUQ_MOGP) Exeter tools
# To be removed as soon as the new versions are stabilized (2020/07/20)
ExeterUQ=ExeterUQ_MOGP # ExeterUQ=ExeterUQ to come back to the old version
sed -i'' -e 's/^ExeterUQ=.*.$/ExeterUQ='$ExeterUQ'/' setup.sh

# 0.5/ Seting up the case with setup.sh.
# Simulation to be run on WORK/$wdir
if [ "$wdir" = "" ] ; then wdir=BENCH$model ; fi

################################################################################
# Continue an existing experiment
################################################################################

if [ -d WORK/$wdir ] ; then
    echo "Directory WORK/$wdir already exists. Do you want to continue (Y/n) ?"
    read answ
    if [ "$answ" = "n" ] ; then exit ; fi
    cd WORK/$wdir
    first_wtbd=`echo $waves | awk ' { print $1 } '`
    # Checking wether the sampling is available for WAVE$first_wtbd
    if [ ! -f WAVE$first_wtbd/Wave${first_wtbd}.RData_orig  -a ! -f Wave${first_wtbd}.RData ] ; then echo No Wave${first_wtbd}.RData file avaialable ; exit ; fi
    wavesdone="" ; for w in $waves ; do if [ -d WAVE$w ] ; then wavesdone="$wavesdone WAVE$w" ; fi ; done
    # Case were some of the waves tbd are there already
    lastwdone=`echo $wavesdone | awk ' { print $NF } ' | sed -e 's/WAVE//'`
    if [ $lastwdone != $first_wtbd ] ; then
	echo WAVES $wavesdone were already present
	echo From which wave do you really like to restart, the following ones being be saved as WAVEN_$$ "(0 to stop)"
	read first_wtbd
	waves="`seq $first_wtbd \`echo $waves | awk ' { print $NF } '\``"
    fi
    if [ ! -f Wave${first_wtbd}.RData ] ; then mv WAVE${first_wtbd}/Wave${first_wtbd}.RData_orig Wave${first_wtbd}.RData ; fi
    for w in $waves ; do if [ -d WAVE$w ] ; then mv WAVE$w WAVE${w}_$$ ; mv InputSpace_wave${w}.pdf InputSpace_wave${w}_$$.pdf  ; fi ; done # Saving previously run waves
else

################################################################################
# Running setup.sh for a new experiment
################################################################################

   ./setup.sh $model $wdir
   if [ $? != 0 ] ; then echo Error in setup.sh ; exit ; fi
fi

cd WORK/$wdir
. env.sh
for wave in $waves ; do

# Imposing a decreasing cutoff for the NROY definition (rather arbitrary)
if [ $wave -le  4 ] ; then cutoff=3. ; elif [ $wave -le 7 ] ; then cutoff=2.5 ; else cutoff=2. ; fi


echo '##########################################################'
echo 1/ Building design
echo '##########################################################'

if [ $wave = 1 ] ; then
  ./param2R.sh 15 3 $param
else 
  ./param2Rwave.sh $wave Wave$wave.RData
fi 

if [ $? != 0 ]; then
  echo "Error during param2R.sh"
  exit 1
fi


echo '##########################################################'
echo 2/ Running the requires SCM simulations
echo '##########################################################'

# extracting the list of required simulations from the list of metrics
# if metric first 3 chars = RAD, simu = RAD/CASE/SUBCASE  ; else simu = CASE/SUBCASE 
simus=`for m in $metrics ; do if [ ${m:0:3} != RAD ] ; then echo \`echo $m | awk -F_ ' {print $1"/"$2 } '\` ; else echo \`echo $m | awk -F_ ' {print $1"/"$2"/"$3 } '\` ; fi ; done | sort | uniq`
sed -i'' "s/WAVEN=.*/WAVEN="$wave"/g" expe_setup.R
./serie_${model}${serie}.sh $simus $wave

if [ $? != 0 ]; then
  echo "Error during serie_"${model}${serie}".sh"
  exit 1
fi



echo '##########################################################'
echo  3/ Computing metrics
echo '##########################################################'
  
./compute_metrics_csv.sh $metrics -wave $wave

if [ $? != 0 ]; then
  echo "Error during compute_metrics_csv.sh"
  exit 1
fi


echo '##########################################################'
echo  4/ Building emulators and estimating NROY space $wave
echo '##########################################################'
if [ "$ExeterUQ" = "ExeterUQ" ] ; then
   # Old call to emulator using stan. To be adandoned once first two
   # the first two papers (run with those codes) are accepted
   sed -i'' -e 's/^tau=.*.$/tau='$tau'/' -e 's/^sample_size=.*.$/sample_size='$sample_size'/' -e 's/^cutoff=.*.$/cutoff='$cutoff'/' -e 's/sample_size_next_design=.*.$/sample_size_next_design='$sample_size_next_design'/' htune_EmulatingMultiMetric.R
   Rscript htune_EmulatingMultiMetric.R -wave $wave
else
   Rscript htune_Emulating_Multi_Metric.R -wave $wave  -cutoff $cutoff -sample_size $sample_size -sample_size_next_design $sample_size_next_design
fi





echo '##########################################################'
echo 5/ Doing graphics for you. Then it will be tea time.
echo '##########################################################'
nmetrics=`echo $metrics | wc -w`
nparams=`wc -l $param | awk ' { print $1 } '`
if [ $nmetrics -gt 1 ] ; then pdfjam --nup ${nmetrics}x${nmetrics} WAVE$wave/Plots_Metrics.pdf --outfile tmp.pdf
else \cp -f WAVE$wave/Plots_Metrics.pdf tmp.pdf ; fi
pdfjam InputSpace_wave$wave.pdf WAVE$wave/Plots_LOO.pdf tmp.pdf --landscape --outfile WAVE$wave/synthesis.pdf
nsubplots=`echo $nmetrics | awk ' { print int(($1-1)^0.5) + 1 } '` ; echo $nsubplots
\rm -f tmp*pdf ; ii=1 ; for i in `seq -w 1 $nparams` ; do (( if = $ii + $nmetrics - 1 )) ; pdfjam --nup ${nsubplots}x${nsubplots} WAVE$wave/Plots_Metrics.pdf ${ii}-${if} --outfile tmp$i.pdf --landscape ; echo PPP $ii $if ; (( ii = $if + 1 )) ; done ; pdfjam tmp*.pdf --outfile WAVE$wave/PlotMetrics.pdf --landscape



#evince WAVE$wave/synthesis.pdf &
done
