#!/bin/bash
#
#################################################
# batch settings for CCLM run on mistral at DKRZ
#################################################
#
#SBATCH --job-name=cclm_@{EXPID}_@{YYYY}@{MM}
#SBATCH --partition=compute2,compute  # Specify partition name for job execution
#SBATCH --mem=0
#SBATCH --purge-slurm-env
#SBATCH -c 2
##SBATCH --nodes=@{NODES}
#SBATCH --ntasks=@{NP}
#SBATCH --time=00-01:59:00
#SBATCH --exclusive
#SBATCH --output=@{JOBLOGFILE}%j
#SBATCH --error=@{JOBLOGFILE}%j
#SBATCH --mail-user=@{EMAIL_ADDRESS}
#SBATCH --account=@{PROJECT_ACCOUNT}

# ulimit: the setting of the stack size instead of using "ulimit -s unlimited",
#         together with the --propagate=STACK in the "srun" command (see below),
#         speeds up the job considerably; in my test cases between 10% and 15%;
#         the value 102400 is the default maximum stack size on MISTRAL
#
ulimit -s 102400

export OMPI_MCA_coll_fca_priority=95
export OMPI_MCA_coll_fca_enable=1
#
export FORT_BUFFERED=true
export decfort_dump_flag=true
#
export MXM_LOG_LEVEL=ERROR

set -e

if [ $(echo @{NEXT_DATE} | cut -c7-10) -eq 0100 ]
then
  echo START @{YYYY} @{MM}  >> @{WORKDIR}/@{EXPID}/joblogs/cclm/finish_joblist
else
 echo START @{YYYY} @{MM} $(cat @{PFDIR}/@{EXPID}/date.log | cut -c7-8) >> @{WORKDIR}/@{EXPID}/joblogs/cclm/finish_joblist
fi

HOUT_INC=(@{HOUT_INC})
NOUTDIR=0  # counter for output directories

cd @{WORKDIR}/@{EXPID}/joboutputs/cclm/@{YYYY_MM}

####################
#  compute time and grid width/size dependent parameters
#    you may also replace these by your own values
####################

###... dt is calculated linear from 360s for dlon=0.44
###       it is checked whether dt fits into 1h=3600s,
###       in case not dt is reduced by 1s until dt fits into 3600
DT=$(python -c "dt=int(300*@{DLON}/0.44)
while (3600%dt > 0) :
  dt=dt-1

print dt")

###... rlwidth = 10-15 times grid mesh size (12 is used here),
###              but smaller then 0.25 times minimum of domain extensions (in m)
###              A factor of 111111 is used to convert degrees into meter
RLWIDTH=$(python -c "print int(min(@{DLON}*111111*12,(@{IE_TOT}-1)*@{DLON}*111111/4,(@{JE_TOT}-1)*@{DLON}*111111/4))").

###... set namelist parameter dependent on netCDF parallel output
if [ @{NPIO} -eq 0 ]
then
  LASYNC_IO=.FALSE.
  NUM_IOPE_PERCOMM=0
else
  LASYNC_IO=.TRUE.
  NUM_IOPE_PERCOMM=1
fi

echo The following parameters are computed for the CCLM namelist
echo dt = ${DT}
echo rldwidth = ${RLWIDTH}

#################################################
# cat together the INPUT*-files
#################################################

cat > INPUT_ORG << end_input_org
 &LMGRID
  startlat_tot = @{STARTLAT_TOT},
  startlon_tot = @{STARTLON_TOT},
  pollat = @{POLLAT},
  pollon = @{POLLON},
  polgam = @{POLGAM},
  dlon=@{DLON},
  dlat=@{DLAT},
  ie_tot=@{IE_TOT},
  je_tot=@{JE_TOT},
  ke_tot=@{KE_TOT},
 /END
 &RUNCTL
  dt=25,
  hstart=@{HSTART}, hstop=@{HNEXT},
  ydate_ini='@{YDATE_START}', ydate_end='@{YDATE_STOP}',
  nprocx= @{NPX}, nprocy= @{NPY}, nprocio=@{NPIO},
  num_iope_percomm = ${NUM_IOPE_PERCOMM},
  nproma=16,
  hincmxt=@{HINCMXT},
  hincmxu=@{HINCMXU},
  itype_calendar=@{ITYPE_CALENDAR},
  lartif_data = .FALSE.,
  ldatatypes=.FALSE.,
  ldump_ascii=.FALSE.,
  lreorder=.FALSE.,
  lreproduce=.TRUE.,
  ltime_barrier=.FALSE.,
  luseobs=.FALSE.,
  luse_rttov=.FALSE.,
  ldiagnos=.TRUE.,
  ldebug_io=.FALSE.,
  linit_fields=.FALSE.,
  nboundlines=3,
  ncomm_type=1,   !3
  itype_timing=4,
  idbg_level=100,
/END
 &TUNING
  clc_diag  =   0.5,
  pat_len   = 500.0,
  tur_len   = 150.0,
  rlam_heat =   1.0,
  rlam_mom  =   0.0,
  rat_lam   =   1.0,
  rat_can   =   1.0,
  rat_sea   =  20.0,
  c_lnd     =   2.0,
  c_soil    =   1.0,
  c_sea     =   1.5,
  z0m_dia   =   0.2,
  crsmin    = 150.0,
  qc0       =   0.0002,
  q_crit    =   1.6,
  mu_rain   =   0.5,
  rain_n0_factor = 0.1,
  v0snow    =    20,
  tkhmin    =   0.4,
  tkmmin    =   0.4,
  a_hshr    =   1.0,
  gkwake    =   0.8,
 /
end_input_org

cat > INPUT_IO  << end_input_io
 &IOCTL
  lasync_io=${LASYNC_IO},
  yform_read='ncdf',
  lbdclim=.TRUE.,
  nhour_restart=@{HNEXT},@{HNEXT},@{HINC},
  ydir_restart='@{RESDIR}/'
  ytunit_restart='d',
  ngribout=${HOUT_INC[0]},
  yncglob_institution="CESR University of Kassel Germany",
  yncglob_title="COSMO5.0_CLM15 simulation (0.0275 Deg) with ERA-Interim forcing (direct), FPSC tuned setup",
  yncglob_project_id = "DFG",
  yncglob_experiment_id ="COSMO-CLM v6.0",
  yncglob_source = "$(basename @{CCLM_EXE})",
  yncglob_contact = "Evgenii Churiulin, Merja Toelle",
  yncglob_references = "http://www.clm-community.eu/, http://www.uni-kassel.de",
  ncglob_realization = 1,
 /END
 &DATABASE
 /END
 &GRIBIN
  hincbound=@{HINCBOUND},
  lchkini=.TRUE.,
  lchkbd =.TRUE.,
  lbdana = .FALSE.,
  ytunitbd='d',
  lan_t_so0  = .TRUE.,
  lan_t_snow = .TRUE.,
  lan_t_cl   = .TRUE.,
  lan_w_snow = .TRUE.,
  lan_w_i    = .TRUE.,
  lan_w_cl   = .TRUE.,
  lan_vio3   = .TRUE.,
  lan_hmo3   = .TRUE.,
  lan_plcov  = .TRUE.,
  lan_lai    = .TRUE.,
  lan_rootdp = .TRUE.,
  lan_rho_snow= .FALSE.,
  lana_qi = .TRUE.,
  llb_qi = .TRUE.,
  lana_qr_qs = .FALSE., !true
  llb_qr_qs = .FALSE.,  !true
  lana_rho_snow  = .FALSE.,
  ydirini='@{YDIRINI}/',
  ydirbd='@{INPDIR}/@{YYYY_MM}/',
 /END
 &GRIBOUT  ! out01
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck = .TRUE.,
  luvmasspoint=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarml='SNOW_GSP','SNOW_CON','RAIN_GSP','RAIN_CON','GRAU_GSP','TOT_PREC','AEVAP_S',
            'RUNOFF_G','RUNOFF_S','CAPE_ML','CIN_ML',
 /END
 &GRIBOUT  ! out02
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarml='ALHFL_S','ALHFL_BS','ALHFL_PL','ALWD_S','ALWU_S','ASHFL_S','ASOD_T','ASOB_T','ASOB_S','ATHB_T','ATHB_S',
           'ASWDIFD_S ','ASWDIFU_S','ASWDIR_S','CLCT','CLCT_AV','DURSUN','QV_2M','QV_S','T_2M','T_S','U_10M','V_10M',
           'RELHUM_2M','ALB_RAD','TQC ','TQI','TQV','TQG','HPBL','T_SO','T_SNOW',
           'RSTOM',

 /END
 &GRIBOUT  ! out03
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  lzint_above_ground=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarzl='U','V',
  zlev=100.,
 /END
 &GRIBOUT  ! out04
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarpl='QV','T','U','V','FI','OMEGA','W',
  plev=200.,500.,700.,850.,925.,1000.,
 /END
 &GRIBOUT  ! out05
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  l_fi_pmsl_smooth=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarml = 'PMSL','PS','W_SNOW','H_SNOW','W_SO',
 /END
 &GRIBOUT  ! out06
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarml='TMAX_2M','TMIN_2M','VMAX_10M','VABSMX_10M',
 /END
 &GRIBOUT  ! out07
  hcomb=@{HSTART},@{HNEXT},${HOUT_INC[$((NOUTDIR+=1))]},
  ytunit='d',
  ysuffix='',
  yform_write='ncdf',
  lwrite_const= @{LWRITE_CONST},
  lcheck =.TRUE.,
  luvmasspoint=.TRUE.,
  ydir='@{OUTDIR}/@{YYYY_MM}/out$(printf %02d $NOUTDIR)/',
  yvarml='Z0','ROOTDP','LAI','PLCOV','FR_LAND','ICE','EMIS','RSMIN','URBAN','FOR_D','FOR_E','NDVI','HSURF','FIS','SOILTYP','LU_CLASS_FRACTION','ALB_DIF12',
 /END
end_input_io

cat > INPUT_DYN << end_input_dyn
 &DYNCTL
  epsass=0.15, betasw=0.4, lspubc=.TRUE.,
  hd_corr_t_bd=0.75,
  hd_corr_u_bd=0.75,
  hd_corr_p_bd=0.75,
  hd_corr_trcr_bd=0.0,
  hd_corr_u_in=1.0,
  hd_corr_t_in=1.00,
  hd_corr_p_in=1.00,
  hd_corr_trcr_in=1.0,
  l_diff_smag=.TRUE.,
  itype_hdiff=2,  hd_dhmax=250,
  ikrylow_si=20, lsemi_imp=.FALSE., l2tls=.TRUE., lcond=.TRUE.,
  itype_outflow_qrsg=2,
  lexpl_lbc=.TRUE.,
  itype_lbc_qrsg=1,
  itype_fast_waves=2,
  itype_bbc_w=114,
  y_scalar_advect='BOTT2_STRANG',
  ldiabf_lh=.TRUE.,
  ldyn_bbc=.FALSE.,
  nrdtau=5,
  rlwidth=10000.,!60000.
  irunge_kutta=1,
  iadv_order=5,
  itheta_adv=0,
 /END
end_input_dyn
cat > INPUT_PHY << end_input_phy
&PHYCTL
     lgsp=.TRUE.,
      ldiniprec=.FALSE.,
      itype_gscp=4,
    lrad=.TRUE.,
!     lradtopo=.FALSE.
      lradtopo=.TRUE.
      nradcoarse=1,
      lradf_avg=.FALSE.,
!     nradcoarse=2,
!     lradf_avg=.TRUE.,
      hincrad=0.25,
      lforest = @{LFOREST},
!     ico2_rad=8,
      ico2_rad=10,
      icldm_rad=4,
    ltur=.TRUE.,
      limpltkediff=.TRUE.,
      ninctura=1,
      ltkesso=.TRUE.,
!     lexpcor=.FALSE.,
      lexpcor=.TRUE.,
      ltmpcor=.FALSE.,
      lnonloc=.FALSE.,
      lcpfluc=.FALSE.,
      itype_turb=3,
      imode_turb=1,
      icldm_turb=2,
    itype_tran=2,
      imode_tran=1,
      itype_wcld=2,
      icldm_tran=0,
      itype_synd=2,
      lprfcor=.FALSE.,
   lsoil=.TRUE.,
!     itype_evsl=2,
      itype_evsl=4,
      itype_trvg=2,
      lmulti_layer=.TRUE.,
      lmelt=.TRUE.,
      lmelt_var=.TRUE.,
!     czbot_w_so=2.5,
      czbot_w_so=4.0,
      ke_soil = @{KE_SOIL},
    czml_soil=@{CZML_SOIL},
    lconv=.TRUE.,
      nincconv=10,
      itype_conv=3
      lconv_inst=.TRUE.,
      lcape=.FALSE.,
    lsso=.FALSE.,
    lseaice=.FALSE.,
!   llake=.FALSE.,
    llake=@{LLAKE},
!   itype_albedo=1,
    itype_albedo=3,
    itype_aerosol=1,
!   itype_heatcond=1
    itype_heatcond=2
 /END
end_input_phy

cat > INPUT_DIA << end_input_dia
 &DIACTL
   n0meanval=0, nincmeanval=24,
  lgplong=.FALSE., lgpshort=.FALSE., lgpspec=.FALSE.,
  n0gp=0,  hincgp=0.25,itype_diag_gusts=4,
 stationlist_tot= 0, 0, 53.633,  9.983, 'Hamburg',
                  0, 0, 52.220, 14.135, 'Lindenberg_Obs',
                  0, 0, 50.32, 8.413,   'Linden',
                  0, 0, 50.5049024, 6.3313825, 'TR32-Wuestebach',
                  0, 0, 50.8658, 6.4473, 'TR32-Selhausen',
                  0, 0, 50.621914, 6.304126, 'TR32-Rollesbroich',
 /END
end_input_dia

cat > INPUT_INI << end_input_ini
 &INICTL
  ndfi=2,
  tspan=  600.0, taus=  600.0,
  dtbak=15.0, dtfwd=15.0,
 /END
end_input_ini

cat > INPUT_ASS << end_input_ass
 &NUDGING
  lnudge  =.FALSE.,
 /END
end_input_ass

#################################################
# run the program
#################################################

echo ----- start CCLM

srun -l --propagate=STACK --cpu_bind=verbose,cores --distribution=block:cyclic @{CCLM_EXE}

echo ----- CCLM finished

if [ $(echo @{NEXT_DATE} | cut -c7-10) -eq 0100 ]
then

  #... in case of partial month jobs reset the first date in date.log to the beginning of the
  #...   month. This is required for arch and post jobs
  if [[ ($(echo @{INC_DATE} | cut -c 4-5) -eq 0) &&  ($(echo @{INC_DATE} | cut -c 7-8) -eq 0) ]]
  then :
  else
    echo $(echo @{CURRENT_DATE} | cut -c1-6)0100 > @{PFDIR}/@{EXPID}/date.log
  fi

#################################################
# submit archive job
#################################################
  cd @{PFDIR}/@{EXPID} ; subchain arch

  echo cclm @{YYYY}_@{MM} FINISHED $(date) >> @{PFDIR}/@{EXPID}/chain_status.log

  echo "END  " @{YYYY} @{MM} >> @{WORKDIR}/@{EXPID}/joblogs/cclm/finish_joblist

else

  #################################################
  # submit next cclm partial month job
  #################################################

  #... save job output files in a subdirectory to prevent overwriting
  SUBDIR=$(cat @{PFDIR}/@{EXPID}/date.log | cut -c7-8)
  if [ ! -d @{WORKDIR}/@{EXPID}/joboutputs/cclm/@{YYYY_MM}/${SUBDIR} ]
  then
    mkdir @{WORKDIR}/@{EXPID}/joboutputs/cclm/@{YYYY_MM}/${SUBDIR}
  fi
  find @{WORKDIR}/@{EXPID}/joboutputs/cclm/@{YYYY_MM} -maxdepth 1 -type f -exec mv {} @{WORKDIR}/@{EXPID}/joboutputs/cclm/@{YYYY_MM}/${SUBDIR} \;
  #... update date.log
  echo @{NEXT_DATE} > @{PFDIR}/@{EXPID}/date.log
  echo cclm @{YYYY}_@{MM} FINISHED $(date) until @{NEXT_DATE} >> @{PFDIR}/@{EXPID}/chain_status.log

  cd @{PFDIR}/@{EXPID} ; subchain cclm

  echo "END  " @{YYYY} @{MM} ${SUBDIR} >> @{WORKDIR}/@{EXPID}/joblogs/cclm/finish_joblist

fi
