#!/bin/bash
#MSUB -r NemoAtm        # nom de la requete
#MSUB -o NemoAtm.out    # nom du fichier de sortie
#MSUB -e NemoAtm.out    # nom du fichier de sortie
#MSUB -eo
#MSUB -n 16             # Reservation des processeurs pour le job
#MSUB -T 1800           # Limite temps (en secondes)
#MSUB -q standard
#MSUB -Q test
#MSUB -p devcmip6

### ===========================================================================
###
### Creates interpolation weights between ORCA and DYNAMICO grids
### Interpolates ORCA mask to DYNAMICO grid
###
### ===========================================================================
##
##  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.
##

##
## Configuration
## ===========================================================================

#
# Defines models
# ==============
OCE=ORCA2.3
OCE=eORCA1.2
#OCE=ORCA025

ATM=dynamico30
#ATM=dynamico40
#ATM=dynamico450
#ATM=LMD9695
#ATM=LMD144X142



#
# Defines OCE grids to handle
# ===========================

OCEGRIDS="T" # " UV

### ===========================================================================
###
### You should not change anything below this line ....
###
### ===========================================================================
SUBMIT_DIR=$(pwd)

# Defines computer
# ================
[[ $(hostname) = curie* ]] && arch=curie

case ${arch} in
    ( curie | irene ) 
    module load netcdf/4.3.3.1_hdf5_parallel
    module load nco/4.4.8
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${SCRATCHDIR}/TMP/${OCE}x${ATM}
    ;;
    ( * )
    exit -1
    ;;
esac


set -vx ; set -e

mkdir -p ${TMPDIR}/${OCE}x${ATM} || exit 1
cd       ${TMPDIR}/${OCE}x${ATM} || exit 1
rm -f *

#
# Suffixes
# ---------------------------------------------------------------------------
ocegrids=${OCEGRIDS~}

case ${OCE} in
    ( *ORC*) oce=orc ;;
esac
case ${ATM} in
    ( *dynamico*    ) atm=ico ;;
    ( *lmd* | *LMD* ) atm=lmd ;;
esac

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

##
## NEMO T point towards ATM - 1st order
## ===========================================================================
cp ${SUBMIT_DIR}/bin/interpol.exe                 .
cp ${SUBMIT_DIR}/iodef_t${oce}_to_t${atm}_1storder.xml   iodef.xml

cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc  .
cp ${R_IN}/ATM/${ATM}/${ATM}_grid.nc .

ln -s ${OCE}_coordinates_mask.nc  oce_grid.nc
ln -s ${ATM}_grid.nc              atm_grid.nc

sed --in-place -e 's/"mask_[TUV]"/"mask_T"/g' -e "s/[tuv]${oce}/t${oce}/" -e 's/_...order/_1storder/g' -e 's/order="."/order="1"/' iodef.xml
time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=no

##
## Correct spurious values (extremes)
## ===========================================================================
cat <<EOF > correction_masque.nco
where (OceFrac <   0.00001 )  OceFrac=OceFrac.get_miss() ;
where (OceFrac >   0.99999 )  OceFrac=1.0 ;
OceFrac.delete_miss() ;
// Fill masked values to land values
where (OceFrac >  1.0 )  OceFrac=0.0 ;
where (OceFrac <  0.0 )  OceFrac=0.0 ; 
EOF
ncap2 -h --overwrite --script-file correction_masque.nco t${oce}_to_t${atm}_1storder.nc tmp_t${oce}_to_t${atm}_1storder.nc ; mv tmp_t${oce}_to_t${atm}_1storder.nc t${oce}_to_t${atm}_1storder.nc
ncatted -h -a missing_value,OceFrac,d,,"" -a _FillValue,OceFrac,d,,"" t${oce}_to_t${atm}_1storder.nc

##
##  Creates mask on ATM grid
## ===========================================================================
cp t${oce}_to_t${atm}_1storder.nc  t${oce}_to_t${atm}_1storder_mask.nc
ncks -h --overwrite                      -v OceFrac               t${oce}_to_t${atm}_1storder_mask.nc  ${ATM}_grid_maskFrom_${OCE}.nc
ncks -h --append                         -v aire                  atm_grid.nc                          ${ATM}_grid_maskFrom_${OCE}.nc
[[ ${atm} = *ico* ]] && ncks -h --append -v bounds_lon,bounds_lat atm_grid.nc                          ${ATM}_grid_maskFrom_${OCE}.nc

cat <<EOF > creation_masque.nco
where (OceFrac >  0.0 )  OceFrac=1 ;
where (OceFrac <= 0.0 )  OceFrac=0 ;
EOF
ncap2 -h --overwrite --script-file creation_masque.nco t${oce}_to_t${atm}_1storder_mask.nc tmp_t${oce}_to_t${atm}_1storder_mask.nc ; mv tmp_t${oce}_to_t${atm}_1storder_mask.nc t${oce}_to_t${atm}_1storder_mask.nc
ncrename -h -v OceFrac,OceMask t${oce}_to_t${atm}_1storder_mask.nc

ncks -h --append  -v OceMask t${oce}_to_t${atm}_1storder_mask.nc   ${ATM}_grid_maskFrom_${OCE}.nc

##
## NEMO T point towards ATM - 2nd order
## ===========================================================================
sed --in-place -e 's/"mask_[TUV]"/"mask_T"/g' -e "s/[tuv]${oce}/t${oce}/" -e 's/_...order/_2ndorder/g' -e 's/order="."/order="2"/' iodef.xml
#time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes
 
##
## ATM towards NEMO T point - 1st order
## ===========================================================================
cp ${SUBMIT_DIR}/iodef_t${atm}_to_t${oce}_1storder.xml           iodef.xml
sed --in-place -e 's/"mask_[TUV]"/"mask_T"/g' -e "s/[tuv]${oce}/t${oce}/" -e 's/_...order/_1storder/g' -e 's/order="."/order="1"/' iodef.xml
time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes

##
## ATM towards NEMO U Point - 1st order
## ===========================================================================
sed --in-place -e 's/"mask_[TUV]"/"mask_U"/g' -e "s/[tuv]${oce}/u${oce}/" -e 's/_...order/_1storder/g' -e 's/order="."/order="1"/' iodef.xml
#time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes

##
## ATM towards NEMO V Point - 1st order
## ===========================================================================
sed --in-place -e 's/"mask_[TUV]"/"mask_V"/g' -e "s/[tuv]${oce}/v${oce}/" -e 's/_...order/_1storder/g' -e 's/order="."/order="1"/' iodef.xml
#time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes

##
## ATM verstowards NEMO T point - 2nd order
## ===========================================================================
sed --in-place -e 's/"mask_[TUV]"/"mask_T"/g' -e "s/[tuv]${oce}/t${oce}/" -e 's/_...order/_2ndorder/g' -e 's/order="."/order="2"/' iodef.xml
#/usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes


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


##
## Add time axis and coordinates information
## (needed if files need to be read by XIOS)
## ===========================================================================
if [[ ${atm} = ico ]] ; then
    cat <<EOF > add_time.nco
defdim("time_counter",1) ;
OceFrac [time_counter,cell] = OceFrac (:) ;
OceMask [time_counter,cell] = OceMask (:) ;
EOF
    ncap2 -O -h -S add_time.nco     ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
    ncks -O --mk_rec time_counter   ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
    ncatted -h \
	    -a coordinates,OceFrac,c,c,"time_counter cell" \
            -a coordinates,OceMask,c,c,"time_counter cell" \
            -a coordinates,aire,c,c,"time_counter cell"    ${ATM}_grid_maskFrom_${OCE}.nc
fi
if [[ ${atm} = lmd ]] ; then
    cat <<EOF > add_time.nco
defdim("time_counter",1) ;
OceFrac [time_counter,lat,lon] = OceFrac (:,:) ;
OceMask [time_counter,lat,lon] = OceMask (:,:) ;
EOF
    ncap2 -O -h -S add_time.nco     ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc  ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
    ncks -O --mk_rec time_counter   ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc  ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
    ncatted -h \
	    -a coordinates,OceFrac,c,c,"time_counter lat lon" \
            -a coordinates,OceMask,c,c,"time_counter lat lon" \
            -a coordinates,aire,c,c,"time_counter lat lon"    ${ATM}_grid_maskFrom_${OCE}.nc
fi

##
## Add some information in file headers
## ===========================================================================

UUID=$(uuid)
NCO="$(ncks --version |& tail -1|sed 's/ncks //')"
for InFile in *${oce}_to_*${atm}_*.nc *${atm}_to_*${oce}_*.nc ${ATM}_grid_maskFrom_${OCE}.nc ; do
    ncatted -h \
	    --attribute uuid,global,d,,                                           \
	    --attribute LongName,global,d,,                                       \
	    --attribute nco_openmp_thread_number,global,d,,                       \
	    --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 Institution,global,o,c,"IPSL"                             \
	    --attribute Ocean,global,o,c,"${OCE}"                                 \
	    --attribute Atmosphere,global,o,c,"${ATM}"                            \
	    --attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}') " \
	    --attribute originalFiles,global,o,c,"${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc"      \
	    --attribute associatedFiles,global,o,c,"grids_${OCE}x${ATM}.nc areas_${OCE}x${ATM}.nc masks_${OCE}x${ATM}.nc" \
	    --attribute directory,global,o,c,"$(pwd)"                             \
	    --attribute description,global,o,c,"Fields needed by OASIS-MCT"       \
	    --attribute title,global,o,c,"${type}_${OCE}x${ATM}.nc"               \
	    --attribute timeStamp,global,o,c,"$(date)"                            \
	    --attribute uuid,global,o,c,"${UUID}"                                 \
	    --attribute HOSTNAME,global,o,c,"$(hostname)"                         \
	    --attribute LOGNAME,global,o,c,"$(whoami)"                            \
	    --attribute NCO,global,o,c,"NCO ${NCO}"                               \
	    --attribute OS,global,o,c,"$(uname -o)"                               \
	    --attribute release,global,o,c,"$(uname -r)"                          \
	    --attribute hardware,global,o,c,"$(uname -i)"                         \
	    --attribute directory,global,o,c,"$(pwd)"                             \
	    --attribute description,global,o,c,"Generated with XIOS"              \
	    --attribute Comment,global,o,c,"Preliminary attempt - Do not trust !" \
	    ${InFile}
done


##
## Update and complete weights file to fit OASIS requested format
## ===========================================================================
cat <<EOF > add_dim.nco
defdim("num_wgts",1) ;
weight[n_weight, num_wgts] = weight ;
EOF

for file in rmp_*${oce}_to_*${atm}_*.nc rmp_*${atm}_to_*${oce}_*.nc ; do
    mv ${file} xios_${file}
    ncap2 --fl_fmt=${FL_FMT} -h --script-file add_dim.nco xios_${file} ${file}
    
    ncrename -h --dimension n_weight,num_links   ${file}
    ncrename -h --variable  src_idx,src_address  ${file}
    ncrename -h --variable  dst_idx,dst_address  ${file}
    ncrename -h --variable  weight,remap_matrix  ${file}
    case ${file} in
	( *1storder.nc ) ncatted -h --attribute map_method,global,o,c,"Conservative Remapping - 1st order"  ${file} ;;
	( *2ndorder.nc ) ncatted -h --attribute map_method,global,o,c,"Conservative Remapping - 2nd order"  ${file} ;;
    esac
    ncatted -h --attribute conventions,global,o,c,"SCRIP"                            ${file}
    ncatted -h --attribute normalization,global,o,c,"none"                           ${file}
    
    case ${file} in
	( rmp_*${oce}_to_t${atm}_* )
	ncatted -h \
		--attribute title,global,o,c,"Weights ${OCE} to ${ATM}"           \
		--attribute source_grid,global,o,c,"curvilinear"                  \
		--attribute dest_grid,global,o,c,"unstructured"                   \
		${file}	
	;;
	( rmp_*${atm}_to_*${oce}_* )
	ncatted -h \
		--attribute title,global,o,c,"Weights ${ATM} to ${OCE}"           \
		--attribute source_grid,global,o,c,"unstructured"                 \
		--attribute dest_grid,global,o,c,"curvilinear"                    \
		${file}
	;;
    esac
done

##
## Save results
## ===========================================================================
cp ${ATM}_grid_maskFrom_${OCE}.nc ${SUBMIT_DIR}
for order in 1st # 2nd
do
    cp t${oce}_to_t${atm}_${order}order.nc     ${SUBMIT_DIR}/t${OCE}_to_t${ATM}_${order}order.nc
    cp rmp_t${oce}_to_t${atm}_${order}order.nc ${SUBMIT_DIR}/rmp_t${OCE}_to_t${ATM}_${order}order.nc
    for grid in ${ocegrids} ; do
	cp rmp_t${atm}_to_${grid}${oce}_${order}order.nc ${SUBMIT_DIR}/rmp_t${ATM}_to_${grid}${OCE}_${order}order.nc
	cp t${atm}_to_${grid}${oce}_${order}order.nc     ${SUBMIT_DIR}/t${ATM}_to_${grid}${OCE}_${order}order.nc
    done
done

##
## Creates and save auxiliary files for OASIS
## ===========================================================================
bash ${SUBMIT_DIR}/GenerateOasisGrids.bash --oce ${OCE} --atm ${ATM}

cp areas_${OCE}_${ATM}.nc ${SUBMIT_DIR}
cp grids_${OCE}_${ATM}.nc ${SUBMIT_DIR}
cp masks_${OCE}_${ATM}.nc ${SUBMIT_DIR}


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

