#!/bin/bash
#set -v

#--script to check water conservation in the IPSL coupled model
#--author: Olivier Boucher
#--30/11/2016
#--updated 10/05/2019
#--updated July 2020 => Gurvan says dOCE_vol has to be computed with rho_oce/rho_liq

#--only work for NEMO 1 degree ! mods needed for NEMO025

#--direxp: directory of experiment up to experiment type
#--exp: name of experiment
#--yearbeg: first year of budget analysis (skip first year of experiment because of issues with some diagnostics)
#--yearend: last year of budget analysis
#--yearinc: time resolution (in year) of output files in OUTPUT
#--for a good precision consider at least a period of 50 or 100 years

direxp="/ccc/store/cont003/gencmip6/p86caub/IGCM_OUT/IPSLCM6/DEVT/piControl/"
exp="VALID-CM622-LR.01"
yearbeg=1890
yearend=1899
yearinc=10

#--set maketimeseries to true to force rewriting temporary files 
#maketimeseries=false
maketimeseries=true

host=`echo $HOSTNAME |cut -c 1-3`

if [ $host == 'ada' ]; then 
  #--IDRIS
  #--module load cdo
  module unload cdo
  module load cdo/1.6.5
  module load netcdf
  #--output directory where to store the temporary files needed for the analysis
  dirout=$WORKDIR

elif [ $host == 'ire' ]; then 
  #--TGCC
  #--assume cdo is loaded
  #--output directory where to store the temporary files needed for the analysis
  dirout=$CCCWORKDIR

else
  echo 'Machine not supported'
  exit

fi

#--name of output file 
fileout='waterbudget_'${exp}'_'${yearbeg}'_'${yearend}'.out'
echo Output will be redirected to $fileout
rm -f ${fileout}

echo 'Dealing with ' $direxp/$exp > ${fileout}
echo >> ${fileout}

#--here I assume there are 360 or 365 days per year on average
#--a better script would diagnose the number of days from the netcdf files 
nbdayinyr=365
nbmthinyr=12

#--model output directories
dir_atm_day=${direxp}${exp}"/ATM/Output/DA/"
dir_atm_mth=${direxp}${exp}"/ATM/Output/MO/"
dir_oce_day=${direxp}${exp}"/OCE/Output/DA/"
dir_oce_mth=${direxp}${exp}"/OCE/Output/MO/"
dir_ice_day=${direxp}${exp}"/ICE/Output/DA/"
dir_ice_mth=${direxp}${exp}"/ICE/Output/MO/"
dir_srf_day=${direxp}${exp}"/SRF/Output/DA/"
dir_srf_mth=${direxp}${exp}"/SRF/Output/MO/"

echo 'The analysis relies on files from the following model output directories' >> ${fileout}
echo $dir_atm_day >> ${fileout}
echo $dir_atm_mth >> ${fileout}
echo $dir_oce_day >> ${fileout}
echo $dir_oce_mth >> ${fileout}
echo $dir_ice_day >> ${fileout}
echo $dir_ice_mth >> ${fileout}
echo $dir_srf_day >> ${fileout}
echo $dir_srf_mth >> ${fileout}

#--number of years for the budget analysis
nbyear=$((${yearend}-${yearbeg}+1))

#--water density (kg/m3) ORCHIDEE
rho_liq=1000.0 
#--ice density (kg/m3) in LIM3
rho_ice=917.0 
#--snow density (kg/m3) in LIM3
rho_sno=330.0
#--ocean water density (kg/m3) in NEMO
rho_oce=1027.
#--average ratio of salty water to fresh water
#fresh2salt=1.035
#--conversion from /day to /s 
day2sec=86400.
#--approximated conversion factor from m sea to Sv
ssh2sv=`python -c "print 4.*3.14159*6370000.*6370000.*0.7/1.e6"`

#--temporary output files
fileoceout=dq_oce_${exp}_extracted_${yearbeg}_${yearend}_short.nc
fileatmout=dq_atm_${exp}_extracted_${yearbeg}_${yearend}_short.nc
filesrfout=dq_srf_${exp}_extracted_${yearbeg}_${yearend}_short.nc

#---PREPARE ATMOS FILE 
if [ ${maketimeseries} = true ] || [ ! -e ${dirout}/${fileatmout} ] ; then 
  #--delete all yearly files that may be there from a previous execution of the script
  rm -f ${dirout}/${fileatmout} ${dirout}/dq_atm_${exp}_extracted_????.nc
  #--loop on years
  for year1 in $(seq $yearbeg $yearinc $yearend) 
  do
    year2=$((year1+yearinc-1))
    file_atm=$dir_atm_mth$exp'_'$year1'0101_'$year2'123?_1M_histmth.nc'
    #--this diags may not be in the time series so I extract them
    #--some are not needed though
    echo cdo -L yearmonmean -selname,aire,pourc_lic,wevap_ter,wevap_oce,wevap_lic,wevap_sic,wsnow_lic,wsnow_sic,wsnow_oce,wsnow_ter,wrain_lic,wrain_sic,wrain_ter,wrain_oce,wbilo_ter,wbilo_oce,wbilo_lic,wbilo_sic,evap,precip,snow,msnow,runofflic ${file_atm} ${dirout}/dq_atm_${exp}_extracted_${year1}.nc
    cdo -L yearmonmean -selname,aire,pourc_lic,wevap_ter,wevap_oce,wevap_lic,wevap_sic,wsnow_lic,wsnow_sic,wsnow_oce,wsnow_ter,wrain_lic,wrain_sic,wrain_ter,wrain_oce,wbilo_ter,wbilo_oce,wbilo_lic,wbilo_sic,evap,precip,snow,runofflic ${file_atm} ${dirout}/dq_atm_${exp}_extracted_${year1}.nc
  done
  cdo -L mergetime ${dirout}/dq_atm_${exp}_extracted_????.nc ${dirout}/${fileatmout}
  rm -f ${dirout}/dq_atm_${exp}_extracted_????.nc
fi

#---PREPARE OCE FILE
if [ ${maketimeseries} = true ] || [ ! -e ${dirout}/${fileoceout} ] ; then
  #--delete all yearly files that may be there from a previous execution of the script
  rm -f ${dirout}/${fileoceout} ${dirout}/dq_oce_${exp}_extracted_????.nc
  #--loop on years
  for year1 in $(seq $yearbeg $yearinc $yearend)
  do
    year2=$((year1+yearinc-1))
    file_oce=$dir_oce_mth$exp'_'$year1'0101_'$year2'123?_1M_grid_T.nc'
    #--this diags may not be in the time series so I extract them
    cdo -L yearmonmean -selname,emp_oce,emp_ice,friver,calving,iceshelf,iceberg ${file_oce} ${dirout}/dq_oce_${exp}_extracted_${year1}.nc
  done
  cdo -L mergetime ${dirout}/dq_oce_${exp}_extracted_????.nc ${dirout}/${fileoceout}
  rm -f ${dirout}/dq_oce_${exp}_extracted_????.nc
fi

#---PREPARE SURFACE FILE
if [ ${maketimeseries} = true ] || [ ! -e ${dirout}/${filesrfout} ] ; then 
  #--delete all yearly files that may be there from a previous execution of the script
  rm -f ${dirout}/${filesrfout} ${dirout}/dq_srf_${exp}_extracted_????.nc
  rm -f ${dirout}/dq0_srf_${exp}_extracted_????.nc ${dirout}/dq_contfrac_${exp}_extracted_????.nc
  #--loop on years
  for year1 in $(seq $yearbeg $yearinc $yearend)
  do
    year2=$((year1+yearinc-1))
    file_srf=$dir_srf_mth$exp'_'$year1'0101_'$year2'123?_1M_sechiba_history.nc'
    #--this diags may not be in the time series so I extract them
    rm -f ${dirout}/contfrac.nc ${dirout}/maxveget.nc ${dirout}/summaxveget.nc
    cdo -L selname,Contfrac ${file_srf} ${dirout}/contfrac.nc
    cdo -L selname,maxvegetfrac ${file_srf} ${dirout}/maxveget.nc
    cdo -L vertsum ${dirout}/maxveget.nc ${dirout}/summaxveget.nc
    cdo -L yearmonmean ${dirout}/summaxveget.nc ${dirout}/summaxvegetmean.nc
    cdo -L yearmonmean -selname,Areas,evap,evapnu,evapflo,inter,transpir,riverflow,coastalflow,rain,snowf,subli,snow,vegetfrac,DelSoilMoist_daily,DelIntercept_daily,DelSWE_daily,delstreamr_daily,delfastr_daily,delslowr_daily,delfloodr_daily,delpondr_daily,dellakevol_daily ${file_srf} ${dirout}/dq0_srf_${exp}_extracted_${year1}.nc
    cdo -L merge ${dirout}/summaxvegetmean.nc ${dirout}/contfrac.nc ${dirout}/dq0_srf_${exp}_extracted_${year1}.nc ${dirout}/dq_srf_${exp}_extracted_${year1}.nc
  done
  cdo -L mergetime ${dirout}/dq_srf_${exp}_extracted_????.nc ${dirout}/${filesrfout}
  rm -f ${dirout}/dq0_srf_${exp}_extracted_????.nc ${dirout}/dq_srf_${exp}_extracted_????.nc
  rm -f ${dirout}/contfrac.nc ${dirout}/maxveget.nc ${dirout}/summaxveget.nc
fi

#---------------------------------------------------------------------------------
echo >> ${fileout}
echo 'NOTE all numbers are in Sv (1 Sv = 10^6 m3/s) of freshwater' >> ${fileout}
echo 'NOTE 0.001 Sv = 8.8 mm sea level rise per century' >> ${fileout}
echo >> ${fileout}
echo 'We are dealing with years from' $yearbeg 'to' $yearend ', or' $nbyear 'years'>> ${fileout}
if [ $nbyear -lt 30 ] ; then
  echo 'WARNING: at least 30 years are needed for a good accuracy because of some approximations made' >> ${fileout}
else 
  echo 'This is good, the longer the more acurate because of some approximations made' >> ${fileout}
fi
echo >> ${fileout}
echo 'TER=land OCE=ocean SIC=sea-ice LIC=land ice' >> ${fileout}
echo >> ${fileout}
#
#--using daily data when possible, otherwise monthly
file_atm_daybeg=$dir_atm_day$exp'_'$yearbeg'0101_????123?_1D_histday.nc'
file_atm_dayend=$dir_atm_day$exp'_????0101_'$yearend'123?_1D_histday.nc'
file_atm_mthbeg=$dir_atm_mth$exp'_'$yearbeg'0101_????123?_1M_histmth.nc'
file_atm_mthend=$dir_atm_mth$exp'_????0101_'$yearend'123?_1M_histmth.nc'
#
file_srf_daybeg=$dir_srf_day$exp'_'$yearbeg'0101_????123?_1D_sechiba_history.nc'
file_srf_dayend=$dir_srf_day$exp'_????0101_'$yearend'123?_1D_sechiba_history.nc'
file_srf_mthbeg=$dir_srf_mth$exp'_'$yearbeg'0101_????123?_1M_sechiba_history.nc'
file_srf_mthend=$dir_srf_mth$exp'_????0101_'$yearend'123?_1M_sechiba_history.nc'
#
file_oce_daybeg=$dir_oce_day$exp'_'$yearbeg'0101_????123?_1D_scalar.nc'
file_oce_dayend=$dir_oce_day$exp'_????0101_'$yearend'123?_1D_scalar.nc'
file_oce_mthbeg=$dir_oce_mth$exp'_'$yearbeg'0101_????123?_1M_scalar.nc'
file_oce_mthend=$dir_oce_mth$exp'_????0101_'$yearend'123?_1M_scalar.nc'
#
file_ice_daybeg=$dir_ice_day$exp'_'$yearbeg'0101_????123?_1D_icemod.nc'
file_ice_dayend=$dir_ice_day$exp'_????0101_'$yearend'123?_1D_icemod.nc'
file_ice_mthbeg=$dir_ice_mth$exp'_'$yearbeg'0101_????123?_1M_icemod.nc'
file_ice_mthend=$dir_ice_mth$exp'_????0101_'$yearend'123?_1M_icemod.nc'
#
#---------------------------------------------------------------------------------
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--NEMO change in stores (for the records)' >> ${fileout}
#--note that the total number of days of the run should be diagnosed rather than assumed
#--here the result is in Sv 
#
#--change in ocean volume in freshwater equivalent
if [ -e ${file_oce_daybeg} ]; then
  maxtimestep=`ncdump -h ${file_oce_dayend} | grep currently | grep -o -E '[0-9]+'`
  OCE_vol_daybeg=`cdo -L outputf,%12.10g,10 -seltimestep,1 -selvar,scvoltot ${file_oce_daybeg}`
  OCE_vol_dayend=`cdo -L outputf,%12.10g,10 -seltimestep,${maxtimestep} -selvar,scvoltot ${file_oce_dayend}`
  echo 'OCE vol beg =' ${OCE_vol_daybeg} >> ${fileout}
  echo 'OCE vol end =' ${OCE_vol_dayend} >> ${fileout}
  dOCE_vol=`python -c "print  ${rho_oce}/${rho_liq}*(${OCE_vol_dayend}-${OCE_vol_daybeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e6"`
else
  maxtimestep=`ncdump -h ${file_oce_mthend} | grep currently | grep -o -E '[0-9]+'`
  OCE_vol_mthbeg=`cdo -L outputf,%12.10g,10 -seltimestep,1 -selvar,scvoltot ${file_oce_mthbeg}`
  OCE_vol_mthend=`cdo -L outputf,%12.10g,10 -seltimestep,${maxtimestep} -selvar,scvoltot ${file_oce_mthend}`
  echo 'OCE vol beg =' ${OCE_vol_mthbeg} >> ${fileout}
  echo 'OCE vol end =' ${OCE_vol_mthend} >> ${fileout}
  dOCE_vol=`python -c "print  ${rho_oce}/${rho_liq}*(${OCE_vol_mthend}-${OCE_vol_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e6"`
fi
echo 'These estimates of d OCE (converted to Sv) are approximate'  >> ${fileout}
echo 'd OCE vol (Sv) =' ${dOCE_vol} >> ${fileout}
#--
#--computing sea-ice and snow-on-sea-ice volume
#--it would be better to compute from daily files but for now only monthly files available
#--here we get a volume of ice (m3 of ice) by multiplying depth with surface
if [ -e ${file_ice_daybeg} ]; then
  echo  >> ${fileout}
else
  maxtimestep=`ncdump -h ${file_ice_mthend} | grep currently | grep -o -E '[0-9]+'`
  SIC_volice_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,sivolu ${file_ice_mthbeg} -gridarea ${file_ice_mthbeg}`
  SIC_volice_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,sivolu ${file_ice_mthend} -gridarea ${file_ice_mthend}`
  #--converting to freswater volume
  #--note that the total number of days of the run should be diagnosed rather than assumed
  dSIC_volice=`python -c "print ${rho_ice}/${rho_liq}*(${SIC_volice_mthend}-${SIC_volice_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e6"`
  #--same for snow on sea-ice (m3 on snow)
  SIC_volsno_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,snvolu ${file_ice_mthbeg} -gridarea ${file_ice_mthbeg}`
  SIC_volsno_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,snvolu ${file_ice_mthend} -gridarea ${file_ice_mthend}`
  #--converting to freswater volume
  #--so we get change in sea-ice and snow in Sv
  dSIC_volsno=`python -c "print ${rho_sno}/${rho_liq}*(${SIC_volsno_mthend}-${SIC_volsno_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e6"`
fi
echo 'd SIC ice (Sv)  =' ${dSIC_volice} >> ${fileout}
echo 'd SIC snow (Sv) =' ${dSIC_volsno} >> ${fileout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--NEMO fluxes (for the records)'  >> ${fileout}
#
file=$dirout'/'$fileoceout
echo EMP_OCE cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,emp_oce ${file} -gridarea ${file}
EMP_OCE=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,emp_oce ${file} -gridarea ${file}`
EMP_SIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,emp_ice ${file} -gridarea ${file}`
ICEBERG=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,iceberg ${file} -gridarea ${file}`
ICESHELF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,iceshelf ${file} -gridarea ${file}`
CALVING=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,calving ${file} -gridarea ${file}`
FRIVER=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -selindexbox,2,361,1,331 -mul -timavg -selname,friver ${file} -gridarea ${file}`
echo 'EMP_OCE=' $EMP_OCE >> ${fileout}
echo 'EMP_OCE + CALVING=' `python -c "print $EMP_OCE + $CALVING"` >> ${fileout}
echo 'EMP_SIC=' $EMP_SIC >> ${fileout}
echo 'EMP_OCE + EMP_SIC + CALVING =' `python -c "print $EMP_OCE + $EMP_SIC + $CALVING"` >> ${fileout}
echo 'ICEBERG =' $ICEBERG >> ${fileout}
echo 'ICESHELF=' $ICESHELF >> ${fileout}
echo 'CALVING =' $CALVING >> ${fileout}
echo 'FRIVER  =' $FRIVER >> ${fileout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
CREATED_OCESIC=`python -c "print ${dOCE_vol}+${dSIC_volice}+${dSIC_volsno}+${EMP_OCE}+${EMP_SIC}-${FRIVER}-${ICEBERG}-${ICESHELF}"`
echo 'WATER CREATED BY OCE+SIC is computed as' >> ${fileout}
echo 'dOCE_vol + dSIC_volice + dSIC_volsno + EMP_OCE + EMP_SIC - FRIVER - ICEBERG - ICESHELF' >> ${fileout}
echo 'and should be as small as possible, ideally ~ 0.001 Sv over a 50 to 100 year period'  >> ${fileout}
echo 'WATER CREATED BY OCE+SIC=' ${CREATED_OCESIC} >> ${fileout}
#
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--LMDZ changes in stores (for the records)' >> ${fileout}
echo 'should be less than 0.001 Sv for prw and even smaller for cloud water'  >> ${fileout}
#--change in precipitable water from the atmosphere daily and monthly files
#--compute sum weighted by gridcell area (kg/m2) then convert to Sv
if [ -e ${file_atm_daybeg} ]; then
  maxtimestep=`ncdump -h ${file_atm_dayend} | grep currently | grep -o -E '[0-9]+'`
  ATM_prw_daybeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prw ${file_atm_daybeg} -gridarea ${file_atm_daybeg}`
  ATM_prw_dayend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prw ${file_atm_dayend} -gridarea ${file_atm_dayend}`
  dATM_prw=`python -c "print (${ATM_prw_dayend}-${ATM_prw_daybeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
  #--now same with cloud liquid water (small term)
  ATM_prlw_daybeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prlw ${file_atm_daybeg} -gridarea ${file_atm_daybeg}`
  ATM_prlw_dayend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prlw ${file_atm_dayend} -gridarea ${file_atm_dayend}`
  dATM_prlw=`python -c "print (${ATM_prlw_dayend}-${ATM_prlw_daybeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
  #--now same with cloud ice water (small term)
  ATM_prsw_daybeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prsw ${file_atm_daybeg} -gridarea ${file_atm_daybeg}`
  ATM_prsw_dayend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prsw ${file_atm_dayend} -gridarea ${file_atm_dayend}`
  dATM_prsw=`python -c "print (${ATM_prsw_dayend}-${ATM_prsw_daybeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
else
  maxtimestep=`ncdump -h ${file_atm_mthend} | grep currently | grep -o -E '[0-9]+'`
  ATM_prw_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prw ${file_atm_mthbeg} -gridarea ${file_atm_mthbeg}`
  ATM_prw_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prw ${file_atm_mthend} -gridarea ${file_atm_mthend}`
  dATM_prw=`python -c "print (${ATM_prw_mthend}-${ATM_prw_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
  #
  ATM_prlw_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prlw ${file_atm_mthbeg} -gridarea ${file_atm_mthbeg}`
  ATM_prlw_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prlw ${file_atm_mthend} -gridarea ${file_atm_mthend}`
  dATM_prlw=`python -c "print (${ATM_prlw_mthend}-${ATM_prlw_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
  #
  ATM_prsw_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -selvar,prsw ${file_atm_mthbeg} -gridarea ${file_atm_mthbeg}`
  ATM_prsw_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -selvar,prsw ${file_atm_mthend} -gridarea ${file_atm_mthend}`
  dATM_prsw=`python -c "print (${ATM_prsw_mthend}-${ATM_prsw_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
  #
  ATM_snowlic_mthbeg=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,1 -expr,'msnow*pourc_lic/100.' ${file_atm_mthbeg} -gridarea ${file_atm_mthbeg}`
  ATM_snowlic_mthend=`cdo -L outputf,%12.10g,10 -fldsum -mul -seltimestep,${maxtimestep} -expr,'msnow*pourc_lic/100.' ${file_atm_mthend} -gridarea ${file_atm_mthend}`
  dATM_snowlic=`python -c "print (${ATM_snowlic_mthend}-${ATM_snowlic_mthbeg})/${nbyear}/${nbdayinyr}/${day2sec}/1.e9"`
fi
echo 'd ATM from prw  (Sv) =' ${dATM_prw} >> ${fileout}
echo 'd ATM from prlw (Sv) =' ${dATM_prlw} >> ${fileout}
echo 'd ATM from prsw (Sv) =' ${dATM_prsw} >> ${fileout}
dATM_tot=`python -c "print ${dATM_prw}+${dATM_prlw}+${dATM_prsw}"`
#
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--LMDZ fluxes (for the records)' >> ${fileout}
#--defining atmospheric file
file=${dirout}/${fileatmout}
#
#--atmospheric fluxes (converted to Sv)
PREC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=precip' ${file} -gridarea ${file}`
RAIN_OCE=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wrain_oce' ${file} -gridarea ${file}`
RAIN_SIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wrain_sic' ${file} -gridarea ${file}`
RAIN_TER=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wrain_ter' ${file} -gridarea ${file}`
RAIN_LIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wrain_lic' ${file} -gridarea ${file}`
SNOW=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=snow' ${file} -gridarea ${file}`
SNOW_OCE=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wsnow_oce' ${file} -gridarea ${file}`
SNOW_SIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wsnow_sic' ${file} -gridarea ${file}`
SNOW_TER=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wsnow_ter' ${file} -gridarea ${file}`
SNOW_LIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wsnow_lic' ${file} -gridarea ${file}`
EVAP=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=evap' ${file} -gridarea ${file}`
EVAP_OCE=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wevap_oce' ${file} -gridarea ${file}`
EVAP_SIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wevap_sic' ${file} -gridarea ${file}`
EVAP_TER=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wevap_ter' ${file} -gridarea ${file}`
EVAP_LIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=wevap_lic' ${file} -gridarea ${file}`
#--better to compute precip-evap then sum (rather than the other way around)
PRECMINUSEVAP=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=precip-evap' ${file} -gridarea ${file}`
echo 'PRECIP - EVAP should be < 0.0001 Sv'  >> ${fileout}
echo 'PRECIP - EVAP (Sv) =' ${PREC} '-' ${EVAP} '=' ${PRECMINUSEVAP} >> ${fileout}
echo 'Next three lines are optional' >> ${fileout} 
echo 'Numbers come in this order OCE + SIC + TER + LIC = TOTAL' >> ${fileout}
echo 'RAIN by tile and total (Sv) =' ${RAIN_OCE} '+' ${RAIN_SIC} '+' ${RAIN_TER} '+' ${RAIN_LIC} '=' \
                                    `python -c "print ${RAIN_OCE}+${RAIN_SIC}+${RAIN_TER}+${RAIN_LIC}"` >> ${fileout}
echo 'SNOW by tile and total (Sv) =' ${SNOW_OCE} '+' ${SNOW_SIC} '+' ${SNOW_TER} '+' ${SNOW_LIC} '=' \
                                    `python -c "print ${SNOW_OCE}+${SNOW_SIC}+${SNOW_TER}+${SNOW_LIC}"` >> ${fileout}
echo 'EVAP by tile and total (Sv) =' ${EVAP_OCE} '+' ${EVAP_SIC} '+' ${EVAP_TER} '+' ${EVAP_LIC} '=' \
                                    `python -c "print ${EVAP_OCE}+${EVAP_SIC}+${EVAP_TER}+${EVAP_LIC}"` >> ${fileout}
#--water budget by surface type as seen from atmosphere
echo 'Net water budget (evap-precip) by land surface type in LMDz' >> ${fileout}
BILO_TER=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -selvar,wbilo_ter ${file} -gridarea ${file}`
echo 'BILO TER (Sv)=' $BILO_TER >> ${fileout}
BILO_OCE=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -selvar,wbilo_oce ${file} -gridarea ${file}`
echo 'BILO OCE (Sv)=' $BILO_OCE >> ${fileout}
BILO_SIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -selvar,wbilo_sic ${file} -gridarea ${file}`
echo 'BILO SIC (Sv)=' $BILO_SIC >> ${fileout}
BILO_LIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -selvar,wbilo_lic ${file} -gridarea ${file}`
echo 'BILO LIC (Sv)=' $BILO_LIC >> ${fileout}
BILO_tot=`python -c "print $BILO_TER+$BILO_OCE+$BILO_SIC+$BILO_LIC"` >> ${fileout}
echo 'The BILO tot diag below should be similar (+/-5e-6) to PRECIP-EVAP above but with opposite sign' >> ${fileout}
echo 'BILO tot (Sv)=' $BILO_tot >> ${fileout}
echo 'The BILO OCE+SIC diag below should be the same (within <0.001 Sv) as EMP_OCE+EMP_ICE+CALVING above ' >> ${fileout}
echo 'BILO OCE+SIC (Sv)=' `python -c "print $BILO_OCE+$BILO_SIC"` >> ${fileout}
#--here we add PRLW and PRSW when they exist but these are small
CREATED_ATM=`python -c "print ${PRECMINUSEVAP}+${dATM_prw}+${dATM_prlw}+${dATM_prsw}"`
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo 'Water created in LMDZ should be < 0.001 Sv'  >> ${fileout}
echo 'WATER_CREATED_IN_ATM (Sv)=' ${CREATED_ATM} >> ${fileout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
#
echo '--LIC change in store and fluxes' >> ${fileout}
#--water going to the ocean
RUNOFFLIC=`cdo -L outputf,%12.8g,8 -divc,1.e9 -fldsum -mul -timavg -expr,'toto=runofflic*pourc_lic/100.' ${file} -gridarea ${file}`
echo 'Atmospheric calving can be different from that reaching the ocean because there is a buffer'  >> ${fileout}
echo 'CALVING atm (Sv)=' $RUNOFFLIC >> ${fileout}
dLIC_tot=`python -c "print -${BILO_LIC}-${RUNOFFLIC}"`
echo 'd LIC (Sv) = ' ${dLIC_tot} >> ${fileout}
#--by construction
CREATED_LIC=0
echo 'd LIC diagnosed from msnow (Sv) = ' ${dATM_snowlic} >> ${fileout}
#
#--------------------------------------------------------------------------------------------------------
#--SECHIBA budgets
file=${dirout}/${filesrfout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--SECHIBA change in stores' >> ${fileout}
#--changes in reservoirs - from tendencies
dSoilHum_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=(maxvegetfrac*DelSoilMoist_daily)*Contfrac' ${file} -gridarea ${file}`
dInterce_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=DelIntercept_daily*Contfrac' ${file} -gridarea ${file}`
dSWE_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=DelSWE_daily*Contfrac' ${file} -gridarea ${file}`
dStream_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=delstreamr_daily*Contfrac' ${file} -gridarea ${file}`
dFastR_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=delfastr_daily*Contfrac' ${file} -gridarea ${file}`
dSlowR_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=delslowr_daily*Contfrac' ${file} -gridarea ${file}`
dFlood_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=delfloodr_daily*Contfrac' ${file} -gridarea ${file}`
dPond_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=delpondr_daily*Contfrac' ${file} -gridarea ${file}`
dLake_in_Sv=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=dellakevol_daily*Contfrac' ${file} -gridarea ${file}`
echo 'dSTOCK Soil Hum (Sv)  =' $dSoilHum_in_Sv >> ${fileout}
echo 'dSTOCK Intercept (Sv) =' $dInterce_in_Sv >> ${fileout}
echo 'dSTOCK Snow (Sv)      =' $dSWE_in_Sv >> ${fileout}
echo 'dSTOCK Stream (Sv)    =' $dStream_in_Sv >> ${fileout}
echo 'dSTOCK FastR (Sv)     =' $dFastR_in_Sv >> ${fileout}
echo 'dSTOCK SlowR (Sv)     =' $dSlowR_in_Sv >> ${fileout}
echo 'dSTOCK Lake (Sv)      =' $dLake_in_Sv >> ${fileout}
echo 'dSTOCK Pond (Sv)      =' $dPond_in_Sv >> ${fileout}
echo 'dSTOCK Flood (Sv)     =' $dFlood_in_Sv >> ${fileout}
dSRF_tot=`python -c "print $dSoilHum_in_Sv+$dInterce_in_Sv+$dSWE_in_Sv+$dStream_in_Sv+$dFastR_in_Sv+$dSlowR_in_Sv+$dLake_in_Sv+$dPond_in_Sv+$dFlood_in_Sv"`
echo 'dSTOCK Total (Sv)     =' ${dSRF_tot} >> ${fileout}
#
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo '--SECHIBA fluxes' >> ${fileout}
EVAP_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -selvar,evap ${file} -gridarea ${file}`
echo 'EVAP SRF (Sv)=' ${EVAP_SRF} >> ${fileout}
EVAPNU_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -selvar,evapnu ${file} -gridarea ${file}`
EVAPFL_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -selvar,evapflo ${file} -gridarea ${file}`
SUBLIM_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -selvar,subli ${file} -gridarea ${file}`
TRANSP_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -vertsum -selvar,transpir ${file} -gridarea ${file}`
INTERC_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -vertsum -selvar,inter ${file} -gridarea ${file}`
echo 'This diagnoses how different is EVAP from the sum of known terms in SECHIBA' >> ${fileout}
echo 'The terms are evap bare soil, evap flooding plains, sublimation, transpiration, interception' >> ${fileout}
echo 'The difference with EVAP SRF should be small <0.0001 Sv' >> ${fileout}
echo 'EVAP TERMS SRF=' $EVAPNU_SRF '+' $EVAPFL_SRF '+' $SUBLIM_SRF '+' $TRANSP_SRF '+' $INTERC_SRF  >> ${fileout}
echo 'EVAP TOTAL SRF=' `python -c "print ${EVAPNU_SRF}+${EVAPFL_SRF}+${SUBLIM_SRF}+${TRANSP_SRF}+${INTERC_SRF}"` >> ${fileout}
#
echo 'RAINFALL SRF=' `cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=rain*Contfrac' ${file} -gridarea ${file}`  >> ${fileout}
echo 'SNOWFALL SRF=' `cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=snowf*Contfrac' ${file} -gridarea ${file}` >> ${fileout}
IN_SRF=`cdo -L outputf,%12.8g,8 -divc,1.e9 -divc,${day2sec} -fldsum -mul -timavg -expr,'toto=(rain+snowf-evap)*Contfrac' ${file} -gridarea ${file}` 
echo 'The SECH NET SRF (precip - evap over land) should be the same as BILO TER above but opposite sign' >> ${fileout}
echo 'SECH NET SRF=' ${IN_SRF} >> ${fileout}
#
#--flow to ocean (Sv)
FLOW=`cdo -L outputf,%12.8g,8 -divc,1.e6 -fldsum -timavg -expr,'toto=coastalflow+riverflow' ${file}`
echo 'FLOW to the ocean should the same (<0.0001 Sv) as FRIVER above' >> ${fileout}
echo 'FLOW to ocean (Sv)=' ${FLOW} >> ${fileout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
#--budget of SRF alltogether
CREATED_SRF=`python -c "print ${FLOW}-${IN_SRF}+${dSRF_tot}"`
echo 'Created water by ORCHIDEE should be < 0.0001 Sv' >> ${fileout}
echo 'WATER CREATED BY ORCHIDEE=' ${FLOW} '-' ${IN_SRF} '+' ${dSRF_tot} '=' ${CREATED_SRF} >> ${fileout}
#
echo '------------------------------------------------------------------------------------' >> ${fileout}
echo 'SUMMARY' >> ${fileout}
echo 'd ATM (Sv) =' ${dATM_tot}         >> ${fileout}
echo 'd LIC (Sv) =' ${dLIC_tot}         >> ${fileout}
echo 'd SRF (Sv) =' ${dSRF_tot}         >> ${fileout}
echo 'd OCE (Sv) =' ${dOCE_vol}         >> ${fileout}
echo 'd SIC ice  (Sv) =' ${dSIC_volice} >> ${fileout}
echo 'd SIC snow (Sv) =' ${dSIC_volsno} >> ${fileout}
CREATED_TOT1=`python -c "print ${dATM_tot}+${dLIC_tot}+${dSRF_tot}+${dOCE_vol}+${dSIC_volice}+${dSIC_volsno}"`
CREATED_TOT2=`python -c "print ${CREATED_OCESIC}+${CREATED_SRF}+${CREATED_ATM}+${CREATED_LIC}"`
echo 'Two different diagnostics of created water rate in the coupled model' >> ${fileout}
echo 'should be < 0.003 Sv in the current state of affairs' >> ${fileout}
echo 'WATER CREATED TOTAL (Sv) =' ${CREATED_TOT1} >> ${fileout}
echo 'WATER CREATED TOTAL (Sv) =' ${CREATED_TOT2} >> ${fileout}
echo '------------------------------------------------------------------------------------' >> ${fileout}
