#!/bin/bash
### ===========================================================================
###
### Creates grids.nc, masks.nc and areas.nc for OASIS-MCT
###
### ===========================================================================
##
##  Warning, to install, configure, run, use any of Olivier Marti's
##  software or to read the associated documentation you'll need at least
##  one (1) brain in a reasonably working order. Lack of this implement
##  will void any warranties (either express or implied).
##  O. Marti assumes no responsability for errors, omissions,
##  data loss, or any other consequences caused directly or indirectly by
##  the usage of his software by incorrectly or partially configured
##  personal.
##
###
### Documentation : https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/MOSAIX
###
## SVN information
#  $Author: omamce $
#  $Date: 2018-03-12 11:17:59 +0100 (Mon, 12 Mar 2018) $
#  $Revision: 3625 $
#  $Id: CreateOasisGrids.bash 3625 2018-03-12 10:17:59Z omamce $
#  $HeadURL$

##
## Default configuration (may be overrided by command line parameters)
## ===========================================================================
OCE=ORCA2.3
# OCE=eORCA1.2
ATM=ICO30
#ATM=ICO40
# ATM=ICO450
# ATM=LMD144142
# ATM=LMD9695

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

# Defines computer
# ================
if [[ $(hostname) = curie* ]] ; then arch=curie ; center=tgcc ; fi
if [[ $(hostname) = irene* ]] ; then arch=irene ; center=tgcc ; fi
PROGRAM=$(basename ${0})

case ${arch} in
    ( curie | irene )
    set +vx
    module unload cdo nco ferret
    module unload netcdf hdf5
    module load python # /2.7.12
    module load netcdf/4.3.3.1_hdf5_parallel # Version for XIOS
    module load nco
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${SCRATCHDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    ;;
    ( * )
    exit -1
    ;;
esac
##
## Command line parameters
## ===========================================================================
set -o verbose
set -o xtrace

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -o=* | --oce=*    ) OCE=${1##*=}     ; echo OCE:${OCE}    ;;
	( -o   | --oce      ) shift ; OCE=${1} ; echo OCE:${OCE}    ;;
	( -a=* | --atm=*    ) ATM=${1##*=}     ; echo ATM:${ATM}    ;;
	( -a   | --atm      ) shift ; ATM=${1} ; echo ATM:${ATM}    ;;
	( -v | --verbose    ) set -o verbose   ;;
	( -x | --xtrace     ) set -o xtrace    ;;
	( -e                ) set -e           ;;
	( -V | --noverbose  ) set +o verbose   ;;
	( -X | --noxtrace   ) set +o xtrace    ;;
	( -E                ) set +e           ;;
	( -* ) echo ${Bold}"Unknown option : ${1}"${Norm} ; return 1 ;;
    esac
    shift
done

##
## Short names (grid names in Oasis) 
## ===========================================================================
case ${OCE} in
    ( *ORC*) oce=orc ;;
esac
case ${ATM} in
    ( *ICO*         ) atm=ico ;;
    ( *dynamico*    ) atm=ico ;;
    ( *lmd* | *LMD* ) atm=lmd ;;
esac

CplModel=${OCE}x${ATM}

##
## Get input files
## ===========================================================================
[[ -f ${OCE}_coordinates_mask.nc ]] || cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc  .
[[ -f ${ATM}_grid.nc             ]] || cp ${R_IN}/ATM/${ATM}/${ATM}_grid.nc                   .

#
# Format for OASIS-MCT files : should be NetCDF3 classic or NetCDF3 64 bits
# ---------------------------------------------------------------------------
FL_FMT=64bit

#
# Cleaning
# ----------------------------------------------------------------------------
rm -f grids_${CplModel}.nc masks_${CplModel}.nc areas_${CplModel}.nc
rm  -f *_tmp.nc

#
# Creates NetCDF3 version of input files
# ----------------------------------------------------------------------------
ncks --overwrite --fl_fmt=${FL_FMT} --history ${OCE}_coordinates_mask.nc      ${OCE}_coordinates_mask_${FL_FMT}.nc
ncks --overwrite --fl_fmt=${FL_FMT} --history ${ATM}_grid_maskFrom_${OCE}.nc  ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc
#
# Creates ocean fields
# ----------------------------------------------------------------------------

for OCEGRID in T U V ; do
    ncks --fl_fmt=${FL_FMT} -C --history --append -v nav_lon_grid_${OCEGRID},nav_lat_grid_${OCEGRID},bounds_lon_grid_${OCEGRID},bounds_lat_grid_${OCEGRID} ${OCE}_coordinates_mask_${FL_FMT}.nc grids_${CplModel}.nc
    ncks --fl_fmt=${FL_FMT} -C --history --append -v area_grid_${OCEGRID} ${OCE}_coordinates_mask_${FL_FMT}.nc areas_${CplModel}.nc
    # Inverts mask values and switch to integer
    ncks --fl_fmt=${FL_FMT} --history -C -v mask_${OCEGRID} ${OCE}_coordinates_mask_${FL_FMT}.nc mask_${OCEGRID}_tmp.nc
    ncatted --history \
	    --attribute coordinates,mask_${OCEGRID},d,,         \
	    --attribute online_operation,mask_${OCEGRID},d,,    \
	    --attribute cell_measures,mask_${OCEGRID},d,,       \
    mask_${OCEGRID}_tmp.nc
    
    ncap2 --fl_fmt=${FL_FMT} --history --append -s "mask_${OCEGRID}=int(1-mask_${OCEGRID});"    mask_${OCEGRID}_tmp.nc masks_${CplModel}.nc
    ncatted --history \
	    --attribute long_name,mask_${OCEGRID},o,c,"Land-sea mask" \
	    --attribute units,mask_${OCEGRID},o,c,"Land:1, Ocean:0"    masks_${CplModel}.nc
    # Change order of dimensions
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncpdq --permute nvertex_grid_${OCEGRID},y_grid_${OCEGRID},x_grid_${OCEGRID} grids_${CplModel}_tmp.nc grids_${CplModel}.nc
done

ncks --history --append -v lon,lat ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc grids_${CplModel}.nc

#
# We need to have different names for dimensions and variables
# ----------------------------------------------------------------------------
ncrename --history -v lon,alon   grids_${CplModel}.nc
ncrename --history -v lat,alat   grids_${CplModel}.nc

if [[ ${ATM} = dynamico* || ${ATM} = ICO* ]] ; then 
    ncks --fl_fmt=${FL_FMT} --history --append -v bounds_lon,bounds_lat ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc grids_${CplModel}.nc
fi

ncks --fl_fmt=${FL_FMT} --history -C --append -v aire   ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc areas_${CplModel}.nc
ncatted --history --attribute coordinates,aire,d,,     \
	--attribute _FillValue,aire,d,,                \
	--attribute missing_value,aire,d,,             \
	--attribute online_operation,aire,d,,          \
	--attribute units,aire,o,c,"m2"                \
	--attribute standard_name,aire,o,c,"cell_area" \
	areas_${CplModel}.nc

ncks --fl_fmt=${FL_FMT} --history -C -v OceMask         ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc OceMask_tmp.nc
ncatted --history \
	--attribute coordinates,OceMask,d,,         \
	--attribute online_operation,OceMask,d,,    \
	--attribute _FillValue,OceMask,d,,          \
	--attribute missing_value,OceMask,d,,       \
	OceMask_tmp.nc
ncap2 --fl_fmt=${FL_FMT} --history --append -s "OceMask=int(1-OceMask)"            OceMask_tmp.nc masks_${CplModel}.nc # For OASIS, ocean=0, land=1
ncatted --history \
	--attribute long_name,OceMask,o,c,"Land-sea mask"   \
	--attribute units,OceMask,o,c,"Land:1, Ocean:0"  masks_${CplModel}.nc

ncatted --history --attribute history,global,d,, grids_${CplModel}.nc
ncatted --history --attribute history,global,d,, masks_${CplModel}.nc
ncatted --history --attribute history,global,d,, areas_${CplModel}.nc

if [[ ${atm} = *dynamico* || ${atm} = ico* ]] ; then
    ncrename --history -d cell,ycell grids_${CplModel}.nc
    ncrename --history -d cell,ycell areas_${CplModel}.nc
    ncrename --history -d cell,ycell masks_${CplModel}.nc
fi
# if [[ ${atm} = *lmd* ]] ; then
#     ncrename -d lon,tlmdlon  grids_${CplModel}.nc
#     ncrename -d lat,tlmdlat  grids_${CplModel}.nc
#     ncrename -d lon,tlmdlon  masks_${CplModel}.nc
#     ncrename -d lat,tlmdlat  masks_${CplModel}.nc
#     ncrename -d lon,tlmdlon  areas_${CplModel}.nc
#     ncrename -d lat,tlmdlat  areas_${CplModel}.nc
# fi

#
# DYNAMICO grids :
#  - Set correct order of dimensions
#  - Add a dimension
# ----------------------------------------------------------------------------
if [[ ${atm} = dynamico* || ${atm} = ico* ]] ; then
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncpdq --permute nvertex,ycell,xcell  grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    cat <<EOF >add_dim.nco
//
defdim("xcell",1) ;
alat               [ycell,xcell] = alat       ;
alon               [ycell,xcell] = alon       ;
bounds_lat [nvertex,ycell,xcell] = bounds_lat ;
bounds_lon [nvertex,ycell,xcell] = bounds_lon ;
//
EOF
    
    ncap2 --fl_fmt=${FL_FMT} --history --append -S add_dim.nco  grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    
    mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
    ncap2 --fl_fmt=${FL_FMT} --history --append -s 'defdim("xcell",1) ; OceMask[time_counter,ycell,xcell]=OceMask(:,:)'  masks_${CplModel}_tmp.nc masks_${CplModel}.nc

    mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
    ncap2 --fl_fmt=${FL_FMT} --history --append -s 'defdim("xcell",1) ; aire[ycell,xcell]=aire(:) ; '                       areas_${CplModel}_tmp.nc areas_${CplModel}.nc
fi

#
# Some changes specific to LMDZ lon/lat grid
# ----------------------------------------------------------------------------
if [[ ${atm} = lmd* ]] ; then
    # Spreads lon and lat to get 2D fields
    # -----------------------------------------------------------------------
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncap2 --fl_fmt=${FL_FMT} --history --append -s "alon[lat,lon]=alon; alat[lat,lon]=alat"  grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    ncatted --history \
	    --attribute long_name,alon,o,c,"Longitude"    \
	    --attribute long_name,alat,o,c,"Latitude"     \
	    --attribute units,alon,o,c,"degrees_east"     \
	    --attribute units,alat,o,c,"degrees_north"    \
	    --attribute grid_type,alon,o,c,"P"            \
	    --attribute grid_type,alat,o,c,"P"            \
	    --attribute overlap,alon,o,i,0                \
	    --attribute overlap,alat,o,i,0                grids_${CplModel}.nc
    
    # Generates cell corners
    # -----------------------------------------------------------------------
cat <<EOF > add_bounds.nco
defdim ("nvertex_lmd", 4) ;
*delta_x = alon(0,1) - alon(0,0) ;
*delta_y = alat(1,0) - alat(0,0) ;
//
bounds_lon[nvertex_lmd,lat,lon] = 0.0 ;
bounds_lat[nvertex_lmd,lat,lon] = 0.0 ;
//
bounds_lon (0,:,:) = alon + delta_x*0.5 ;
bounds_lat (0,:,:) = alat + delta_y*0.5 ;
bounds_lon (1,:,:) = alon + delta_x*0.5 ;
bounds_lat (1,:,:) = alat - delta_y*0.5 ;
bounds_lon (2,:,:) = alon - delta_x*0.5 ;
bounds_lat (2,:,:) = alat - delta_y*0.5 ;
bounds_lon (3,:,:) = alon - delta_x*0.5 ;
bounds_lat (3,:,:) = alat + delta_y*0.5 ;
//
where (bounds_lat >  90.0 ) bounds_lat =  90.0 ;;
where (bounds_lat < -90.0 ) bounds_lat = -90.0 ;;
//
EOF
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncap2 --fl_fmt=${FL_FMT} --history -S add_bounds.nco -O grids_${CplModel}_tmp.nc grids_${CplModel}.nc
fi

#
# Generates grid "aone" : same as t-ocean grid, with surfaces set to 1
# This grid is used when field are quantities instead of fluxes (i.e river flow)
# ----------------------------------------------------------------------------
mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
ncap2 --fl_fmt=${FL_FMT} --history -s "aone_lon=alon; aone_lat=alat; bounds_aone_lon=bounds_lon; bounds_aone_lat=bounds_lat; " grids_${CplModel}_tmp.nc grids_${CplModel}.nc

mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
ncap2 --fl_fmt=${FL_FMT} --history -s "aone_aire=aire*0+1; " areas_${CplModel}_tmp.nc areas_${CplModel}.nc

mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
ncap2 --fl_fmt=${FL_FMT} --history -s "aone_mask=int(OceMask); " masks_${CplModel}_tmp.nc masks_${CplModel}.nc

#
# Final renaming
# ----------------------------------------------------------------------------
for OCEGRID in T U V
do
    ocegrid=${OCEGRID~} # To lowercase
    ncrename --history -v nav_lon_grid_${OCEGRID},${ocegrid}${oce}.lon     grids_${CplModel}.nc
    ncrename --history -v nav_lat_grid_${OCEGRID},${ocegrid}${oce}.lat     grids_${CplModel}.nc
    ncrename --history -v bounds_lon_grid_${OCEGRID},${ocegrid}${oce}.clo  grids_${CplModel}.nc
    ncrename --history -v bounds_lat_grid_${OCEGRID},${ocegrid}${oce}.cla  grids_${CplModel}.nc
    ncrename --history -v mask_${OCEGRID},${ocegrid}${oce}.msk             masks_${CplModel}.nc
    ncrename --history -v area_grid_${OCEGRID},${ocegrid}${oce}.srf        areas_${CplModel}.nc
    
    ncatted --history \
	    --attribute bounds,${ocegrid}${oce}.lon,m,c,"${ocegrid}${oce}.clo"  \
	    --attribute bounds,${ocegrid}${oce}.lat,m,c,"${ocegrid}${oce}.cla"  \
	    --attribute units,${ocegrid}${oce}.clo,o,c,"degrees_east"        \
	    --attribute units,${ocegrid}${oce}.clo,o,c,"degrees_north" grids_${CplModel}.nc
done

ncrename --history -v alon,t${atm}.lon           grids_${CplModel}.nc
ncrename --history -v alat,t${atm}.lat           grids_${CplModel}.nc
ncrename --history -v aone_lon,o${atm}.lon       grids_${CplModel}.nc
ncrename --history -v aone_lat,o${atm}.lat       grids_${CplModel}.nc
ncrename --history -v OceMask,t${atm}.msk        masks_${CplModel}.nc
ncrename --history -v aone_mask,o${atm}.msk      masks_${CplModel}.nc
ncrename --history -v aire,t${atm}.srf           areas_${CplModel}.nc
ncrename --history -v aone_aire,o${atm}.srf      areas_${CplModel}.nc

ncrename --history -v bounds_lon,t${atm}.clo        grids_${CplModel}.nc
ncrename --history -v bounds_lat,t${atm}.cla        grids_${CplModel}.nc
ncrename --history -v bounds_aone_lon,o${atm}.clo   grids_${CplModel}.nc
ncrename --history -v bounds_aone_lat,o${atm}.cla   grids_${CplModel}.nc

for atmgrid in t o ; do
    ncatted --history \
	    --attribute bounds,${atmgrid}${atm}.lon,c,c,"${atmgrid}${atm}.clo"   \
	    --attribute bounds,${atmgrid}${atm}.lat,c,c,"${atmgrid}${atm}.cla"   \
	    --attribute units,${atmgrid}${atm}.clo,o,c,"degrees_east"         \
	    --attribute units,${atmgrid}${atm}.cla,o,c,"degrees_north"        grids_${CplModel}.nc
done

##
## Change all NetCDF files to NetCDF 3 format
## ===========================================================================
for InFile in areas_${CplModel}.nc grids_${CplModel}.nc masks_${CplModel}.nc ; do
    if [[ $(ncdump -k ${InFile}) = *netCDF-4* ]] ; then
	mv ${InFile} tmp_${InFile}
	ncks --fl_fmt=${FL_FMT} --history  tmp_${InFile}  ${InFile}
    fi
done

##
## Add some useful information in NetCDF headers
## ===========================================================================
UUID=$(uuid)
NCO=$(ncks --version |& tail -1|sed 's/ncks //')
for type in areas masks grids ; do
    ncatted --history \
	    --attribute nco_openmp_thread_number,global,d,,            \
	    --attribute uuid,global,d,,                                \
	    --attribute LongName,global,d,,                            \
	    --attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	    --attribute Conventions,global,o,c,"CF-1.6"                \
	    --attribute source,global,o,c,"IPSL Earth system model"    \
	    --attribute group,global,o,c,"ICMC IPSL Climate Modelling Center" \
	    --attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}') " \
	    --attribute Institution,global,o,c,"IPSL https://www.ipsl.fr" \
	    --attribute Ocean,global,o,c,"${OCE} https://www.nemo-ocean.eu"  \
	    --attribute Atmosphere,global,o,c,"${ATM} http://lmdz.lmd.jussieu.fr" \
	    --attribute HOSTNAME,global,o,c,"$(hostname)"              \
	    --attribute LOGNAME,global,o,c,"$(whoami)"                 \
	    --attribute Program,global,o,c,"Generated by ${0}"         \
	    --attribute name,global,o,c,"${type}_${CplModel}.nc"     \
	    --attribute directory,global,o,c,"$(pwd)"                  \
	    --attribute description,global,o,c,"Fields needed by OASIS-MCT" \
	    --attribute title,global,o,c,"${type}_${CplModel}.nc"    \
	    --attribute timeStamp,global,o,c,"$(date)"                 \
	    --attribute associatedFiles,global,o,c,"grids_${CplModel}.nc areas_${CplModel}.nc masks_${CplModel}.nc" \
	    --attribute originalFiles,global,o,c,"${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc"\
	    --attribute uuid,global,o,c,"${UUID}"                      \
	    --attribute OS,global,o,c,"$(uname -o)"                    \
	    --attribute release,global,o,c,"$(uname -r)"               \
	    --attribute hardware,global,o,c,"$(uname -i)"              \
	    --attribute Comment,global,o,c,"Preliminary attempt - Do not trust !" \
	    --attribute	SVN_Author,global,o,c,"$Author: omamce $"                           \
            --attribute SVN_Date,global,o,c,"$Date: 2018-03-12 11:17:59 +0100 (Mon, 12 Mar 2018) $"                            \
	    --attribute SVN_Revision,global,o,c,"$Revision: 3625 $"                    \
	    --attribute SVN_Id,global,o,c,"$Id: CreateOasisGrids.bash 3625 2018-03-12 10:17:59Z omamce $"                                \
	    ${type}_${CplModel}.nc
done

##
## Cleaning
## ===========================================================================
#rm  *_tmp.nc ${OCE}_coordinates_mask_${FL_FMT}.nc ${ATM}_grid_maskFrom_${OCE}_${FL_FMT}.nc *.nco

exit
#
# Name of the dimensions ? 
# ----------------------------------------------------------------------------
for OCEGRID in T U V ; do
    ocegrid=${OCEGRID~} # Downcase name of grids
    ncrename --history -d  x_grid_${OCEGRID},x${ocegrid}${oce}         grids_${CplModel}.nc
    ncrename --history -d  y_grid_${OCEGRID},y${ocegrid}${oce}         grids_${CplModel}.nc
    ncrename --history -d  nvertex_grid_${OCEGRID},crn${ocegrid}${oce} grids_${CplModel}.nc
done

## ===========================================================================
##
##                               That's all folk's !!!
##
## ===========================================================================
