#!/bin/bash
#SBATCH --account=cpc-s2s
#SBATCH --qos=batch
#SBATCH --nodes=1
#SBATCH --ntasks=1
#SBATCH -J finalPlots
#SBATCH --time=01:00:00         # Each task has the full 8 hours
#SBATCH -o zallplots.out
#SBATCH -e zallplots.err
##SBATCH --exclusive
#SBATCH --mail-user=zewdu.segele@noaa.gov
##SBATCH --mail-type=BEGIN,END,FAIL
#SBATCH --mail-type=FAIL

module purge
#module load spack-managed-x86-64_v3
module load contrib pyncl
#!/bin/bash

echo `date`

##### for target domain in Central America 
latS=-13.5
latN=24.5
lonW=20.5
lonE=53.0
region="eAfrica"

#### SST Domain for Indian Ocean to the Atlantic
lonWeof=50.
lonEeof=340.
latSeof=-20.
latNeof=20.

##### Number of SST and Precip EOFs
numeof=6

#### Model intitial date and forecast period
startmon=5
sznlen=4
ilead=1

obsstartmon=$((ilead + startmon))
obsendmon=$((obsstartmon + sznlen - 1))

currentyr=2026
seasonname="JJAS"

#### For R
testLength=5
trainLength=30
leave3Out=TRUE
runserial=FALSE
obst="MSWEP"
#obst="LOCAL"

#### For ploting -- Change country
mycountry="ETH"  # Costa Rica
yrsstsc=1991
yrsstec=2020
WMOshpfiles="/work/noaa/cpc-s2s/zewdu/shpfiles/WMO_basemap.shp"
WMOshpfiles="/cpc/int_desk/IndianOcean/shpfiles/WMO_basemap.shp"

### For obsevations
firstyr=1991
endyr=2025
monthly=True
isstate=False
obsres=0.25
obsprecip="prec${seasonname}_${firstyr}-${endyr}${obst}.nc"

### Diagnostics
printProb=False
printProbRaw=False
#Diagnostic Domain for Costa Rica
tlats=9.
tlatn=10.
tlonw=40.0 
tlone=41.0 

#### For both R and NCL
###########
szn4mon=False
leadi=$ilead
leadf=$((ilead + sznlen - 1))

allmodelNames=(canesm5 gem5nemo nasa ccsm4 cfsv2 cesm1 ensmean)

###### Select from these
#allprdctors=(MGI ATL3 Nino34 WVG IOD SIOD PCS1 PCS2 PCS3 PCS4 PCS5 PCS6 PCR1 PCR2 PCR3 PCR4 PCR5 PCR6 ALLP_INT)

slctprdctors=(MGI ATL3 Nino34 WVG IOD SIOD PCS1 PCS2 PCS3 PCS4 PCS5 PCS6 PCR1 PCR2 PCR3 PCR4 PCR5 PCR6 ALLP_INT)
allprdctors=$slctprdctors
##############################################

###########################

nprdFirst=$(( ${#slctprdctors[@]} - 1 ))

#######################
join_by_comma() {
  local IFS=","
  echo "$*"
}

quote_items_for_r() {
  local out=()
  for x in "$@"; do
    out+=("\"$x\"")
  done
  local IFS=","
  echo "c(${out[*]})"
}

quote_items_for_ncl() {
  local out=()
  for x in "$@"; do
    out+=("\"$x\"")
  done
  local IFS=","
  echo "(/${out[*]}/)"
}

allmodelNamesR=$(quote_items_for_r "${allmodelNames[@]}")
allmodelNamesNCL=$(quote_items_for_ncl "${allmodelNames[@]}")
slctPrdctrR=$(quote_items_for_r "${slctprdctors[@]}")
allprdctorNCL=$(quote_items_for_ncl "${allprdctors[@]}")
slctprdctrNCL=$(quote_items_for_ncl "${slctprdctors[@]}")

parentDir=$(dirname "$(pwd)") 
workdir="`pwd`"

##########
##### 5. Plot individual single model probabilities
##############

constant=".ncl"

for v in "${slctprdctors[@]}"; do
    outfile="plotSingleModel${v}${constant}"

    cat > paramsSingle.ncl <<EOF
PRDCTR        = "${v}"
iLead          = $ilead
Szn4Month      = $szn4mon
iMonth         = $startmon
STATE          = $isstate
currentYr      = $currentyr
SEASON         = "$seasonname"
latS           = $latS
latN           = $latN
lonW           = $lonW
lonE           = $lonE
COUNTRY        = "$mycountry"
Res            = $obsres
printProb      = $printProb
printProbRaw   = $printProbRaw
tlats          = $tlats
tlatn          = $tlatn
tlonw          = $tlonw
tlone          = $tlone
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
f1shp       = "$WMOshpfiles"
REGION      = "$region"
EOF
    cat paramsSingle.ncl templateShapeFileNames.ncl templateIndividualProb.ncl > "$outfile"
    ncl "$workdir/$outfile"
    echo $outfile
done

############################
##### 6. Plot individual average model probabilities
constant=".ncl"

for v in "${slctprdctors[@]}"; do
    outfile="plotAvgModel${v}${constant}"

    cat > paramsAvg.ncl <<EOF
PRDCTR        = "${v}"
iLead          = $ilead
Szn4Month      = $szn4mon
iMonth         = $startmon
STATE          = $isstate
currentYr      = $currentyr
startmon       = $obsstartmon
SEASON         = "$seasonname"
latS           = $latS
latN           = $latN
lonW           = $lonW
lonE           = $lonE
COUNTRY        = "$mycountry"
Res            = $obsres
printProb      = $printProb
printProbRaw   = $printProbRaw
tlats          = $tlats
tlatn          = $tlatn
tlonw          = $tlonw
tlone          = $tlone
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
f1shp       = "$WMOshpfiles"
REGION      = "$region"
EOF

    cat paramsAvg.ncl templateShapeFileNames.ncl templateEnsProb.ncl > "$outfile"
    ncl "$workdir/$outfile"
    echo $outfile
done

############################
##### 7. Plot Average Predictors Skills for indiviual models and ensemble

cat > paramsAllSkill.ncl <<EOF
PRDCTRall      = $slctprdctrNCL
iLead          = $ilead
Szn4Month      = $szn4mon
iMonth         = $startmon
STATE          = $isstate
currentYr      = $currentyr
startmon       = $obsstartmon
SEASON         = "$seasonname"
latS           = $latS
latN           = $latN
lonW           = $lonW
lonE           = $lonE
COUNTRY        = "$mycountry"
Res            = $obsres
printProb      = $printProb
printProbRaw   = $printProbRaw
tlats          = $tlats
tlatn          = $tlatn
tlonw          = $tlonw
tlone          = $tlone
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
f1shp       = "$WMOshpfiles"
REGION      = "$region"
EOF

cat paramsAllSkill.ncl templateShapeFileNames.ncl templateSingleAvgPrdctors.ncl > plotAvgPrdctorsSkill.ncl

ncl $workdir/plotAvgPrdctorsSkill.ncl
    
############################
##### 8. Plot Average Predictors Skills for indiviual models and ensemble

cat > paramsSkillWtd.ncl <<EOF
PRDCTRall      = $slctprdctrNCL
iLead          = $ilead
Szn4Month      = $szn4mon
iMonth         = $startmon
STATE          = $isstate
currentYr      = $currentyr
startmon       = $obsstartmon
SEASON         = "$seasonname"
latS           = $latS
latN           = $latN
lonW           = $lonW
lonE           = $lonE
COUNTRY        = "$mycountry"
Res            = $obsres
printProb      = $printProb
printProbRaw   = $printProbRaw
tlats          = $tlats
tlatn          = $tlatn
tlonw          = $tlonw
tlone          = $tlone
nprdFirst      = $nprdFirst
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
f1shp       = "$WMOshpfiles"
REGION      = "$region"
EOF

cat paramsSkillWtd.ncl templateShapeFileNames.ncl templateEnsSkill.ncl > plotSkillWtdAvg.ncl

ncl $workdir/plotSkillWtdAvg.ncl


############################


echo `date`
