# 2021-03 : Initial code [N. Jourdain, IGE-CNRS]
#====================================================================================

import numpy as np
import xarray as xr
import gsw
from .def_grids import grid_bounds_oce
from .def_attrs import rename_dimensions
from datetime import datetime

#====================================================================================
def load_oce_mod_fesom2(file_mesh_mask='fesom.mesh.diag.nc.nc',\
                      files_gridT='fesom_grid_T.nc',\
                      files_gridS='fesom_grid_S.nc',\
                      files_gridU='fesom_grid_U.nc',\
                      files_gridV='fesom_grid_V.nc',\
                      files_Tx='fesom_grid_tx.nc',\
                      files_Ty='fesom_grid_ty.nc',\
                      files_ssh='fesom_grid_tx.nc',\
                      files_fw='fesom_grid_ty.nc',\
                      files_fh='fesom_grid_ty.nc',\
                      files_SBC='fesom_flxT.nc',\
                      files_Aice='fesom_icemod.nc',\
                      files_Hice='fesom_icemod.nc',\
                      files_Uice='fesom_icemod.nc',\
                      files_Vice='fesom_icemod.nc',\
                      files_thdgr='fesom_icemod.nc',\
                      files_BSF='fesom_psi.nc',\
                      rho0=1026.0, teos10=False, region='Amundsen', parallel=False ):
   """ Read FESOM2 outputs and define an xarray dataset containing 
       all variables required in MISOMIP2.

       Input:

         file_mesh: mesh mask file [default='mesh_mask.nc']

         files_gridT: file or list of files containing the temperature and salinity variables

         files_gridU: file or list of files containing the x-velocity and related variables

         files_gridV: file or list of files containing the y-velocity and related variables

         files_ice: file or list of files containing the sea-ice variables [look for data in files_gridT if not provided]

         files_SBC: file or list of files containing the surface fluxes variables [look for data in files_gridT if not provided]

         files_BSF: file or list of files containing the barotropic streamfunction calculated at U-points, e.g. 
         using the cdfpsi function which is part of the [CDFTOOLS](https://github.com/meom-group/CDFTOOLS).
         [look for data in files_gridU if not provided]

         rho0 corresponds to rau0 value in NEMO's eosbn2.F90 i.e. reference volumic mass [kg m-thetaT3]

         teos10=False -> assumes the nemo outputs are in potential temperature & practical salinity (EOS80)
               =True  -> assumes the nemo outputs are in CT and AS and convert to PT and PS

       region = 'Amundsen' (default) or 'Weddell'

       parallel: If True, the open and preprocess steps of this function will be performed in parallel

       Output:
          xarray dataset of coordinates ("time", "z", "sxy") (sxy= one-dimensionalized horizontal space)

       Example1:
       ds = load_oce_mod_nemo()

       Example2:
       dir= 'datadir/model/'= lonmax+0.1)
       fT = [ dir+'nemo_y1990_grid_T.nc', dir+'nemo_y1991_grid_T.nc' ]
       fU = [ dir+'nemo_y1990_grid_U.nc', dir+'nemo_y1991_grid_U.nc' ]
       fV = [ dir+'nemo_y1990_grid_V.nc', dir+'nemo_y1991_grid_V.nc' ]
       fS = [ dir+'nemo_y1990_SBC.nc', dir+'nemo_y1991_SBC.nc' ]
       fI = [ dir+'nemo_y1990_icemod.nc', dir+'nemo_y1991_icemod.nc' ]
       fP = [ dir+'nemo_y1990_psi.nc', dir+'nemo_y1991_psi.nc' ]
       ds = load_oce_mod_nemo(files_gridT=fT,files_gridU=fU,files_gridV=fV,files_SBC=fS,files_ice=fI,files_BSF=fP,rho0=1028.0,teos10=True,region='Weddell')

   """

   startTime = datetime.now()

   # NB: as NEMO put _FillValues of zero where is it always zero and not a missing value -> do not use _FillValue (but disable scale/offset):

   ncM = xr.open_dataset(file_mesh_mask,decode_coords=False,mask_and_scale=False) ;# ncM=rename_dimensions(ncM); ncM=ncM.isel(time=0)
   # ncB = xr.open_dataset(file_bathy,decode_coords=False,mask_and_scale=False) ; ncB=rename_dimensions(ncB)
   ncT = xr.open_mfdataset(files_gridT,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncS = xr.open_mfdataset(files_gridS,decode_coords=False,mask_and_scale=False, parallel=parallel)

   ncU = xr.open_mfdataset(files_gridU,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncV = xr.open_mfdataset(files_gridV,decode_coords=False,mask_and_scale=False, parallel=parallel)

   ncTx = xr.open_mfdataset(files_Tx,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncTy = xr.open_mfdataset(files_Ty,decode_coords=False,mask_and_scale=False, parallel=parallel)
   
   ## ncS = xr.open_mfdataset(files_SBC,decode_coords=False,mask_and_scale=False, parallel=parallel);    #ncS=rename_dimensions(ncS)
   ncAI = xr.open_mfdataset(files_Aice,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncHI = xr.open_mfdataset(files_Hice,decode_coords=False,mask_and_scale=False, parallel=parallel)
   
   ncSSH = xr.open_mfdataset(files_ssh,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncFW = xr.open_mfdataset(files_fw,decode_coords=False,mask_and_scale=False, parallel=parallel)

   ncUI = xr.open_mfdataset(files_Uice,decode_coords=False,mask_and_scale=False, parallel=parallel)
   ncVI = xr.open_mfdataset(files_Vice,decode_coords=False,mask_and_scale=False, parallel=parallel)
   
   ncHF = xr.open_mfdataset(files_fh,decode_coords=False,mask_and_scale=False, parallel=parallel)

   ncTHDGR = xr.open_mfdataset(files_thdgr,decode_coords=False,mask_and_scale=False, parallel=parallel)

   #ncP = xr.open_mfdataset(files_BSF,decode_coords=False,mask_and_scale=False, parallel=parallel)

   mtime = ncT.time.shape[0]

   # longitude & latitude on U, V, T grids
   lonT = ncM.lon ; latT = ncM.lat
   
   # save original domain boundaries:
   domain_minlat = latT.min().values
   domain_maxlat = latT.max().values
   domain_minlon = lonT.min().values
   domain_maxlon = lonT.max().values

#####
   #----------
   # Reduce the size of ocean dataset

   [lonmin,lonmax,latmin,latmax] = grid_bounds_oce(region=region)
   wdeg = 2
   lonmin=lonmin - wdeg # take a bit more for interpolation
   lonmax=lonmax + wdeg
   latmin=latmin - wdeg
   latmax=latmax + wdeg

   south = np.where( (latT >= latmin) & (latT <= latmax) & (lonT >= lonmin) & (lonT <= lonmax) )
### ele
   
   ele = ncM.elements
   ele = ele-1
   xc =lonT[ele]
   yc =latT[ele]
   xcm =np.mean(xc,axis=0)
   ycm =np.mean(yc,axis=0)
   xstd = np.std(xc,axis=0)
   e = np.where( (ycm >= latmin - 0.1) & (ycm <= latmax + 0.1)
                & (xcm >= lonmin-0.1) & (xcm <= lonmax+0.1) &  (xstd < 5))
   xc = xc[:, e[0]]
   yc = yc[:, e[0]]

   xcm =np.mean(xc,axis=0)
   ycm =np.mean(yc,axis=0)

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

   lonT = lonT.values[south[0]]
   latT = latT.values[south[0]]

   # depth of U, V, T grids (neglecting the effects of partial steps in the interpolation)
   depTUV=ncM.nz1 * -1  # gdept_1d

   my = depTUV.shape[0]
   mx = lonT.shape[0]
    
     
   DEPTHO = ncM.zbar_n_bottom.values[south] *-1
   #  DEPTHO = xr.DataArray( np.zeros((my,mx))*np.nan, dims=['y', 'x'] )

   # Depth of ice shelf draft (if possible after NEMO's initialization, i.e. from mesh_mask) [m]:
   ulevel = ncM.ulevels_nod2D[south]-1
   DEPFLF = depTUV[ulevel].values
   #DEPFLF = xr.DataArray( np.zeros((my,mx))*np.nan, dims=['y', 'x'] )

   # ocean salinity [1.e-3]
   SS = ncS.salt.values[:,:,south[0]]
   Amask = np.where(SS == 0)
   Umask = np.where(SS[0,:,:] == 0)

   SS[Amask] = np.nan
   # SS = xr.DataArray( np.zeros((mtime,mz,my,mx))*np.nan, dims=['time', 'z', 'y', 'x'] )

   # ocean temperature [degC]= lonmax+0.1)
   TT = ncT.temp.values[:,:,south[0]]
   TT[Amask] = np.nan
   # TT = xr.DataArray( np.zeros((mtime,mz,my,mx))*np.nan, dims=['time', 'z', 'y', 'x'] )


   # sea bottom ocean temperature [degC]
   n_levels = ncM.nlevels_nod2D[south]-2

   nodes = np.arange(SS.shape[2])
   SSB = SS[:, n_levels, nodes]
   #  SSB = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   nodes = np.arange(TT.shape[2])
   TTB = TT[:, n_levels, nodes]
   #  TTB = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # ocean potential temperature and practical salinity :
   TOB = TTB
   SOB = SSB
   THETAO = TT
   SO = SS

   # ocean x-ward velocity [m s-1]
   UX = ncU.unod.values[:,:,south[0]]
   UX[Amask] = np.nan
   #  UX = xr.DataArray( np.zeros((mtime,mz,my,mx))*np.nan, dims=['time', 'z', 'y', 'x'] )

   # ocean y-ward velocity [m s-1]
   VY = ncV.vnod.values[:,:,south[0]]
   VY[Amask] = np.nan
   #  VY = xr.DataArray( np.zeros((mtime,mz,my,mx))*np.nan, dims=['time', 'z', 'y', 'x'] )

   # surface stress received by the ocean along x [W m-1]
   TAUX = ncTx.tx_sur.values[:,e[0]]
   # TAUX = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # surface stress received by the ocean along x [W m-1]
   TAUY = ncTy.ty_sur.values[:,e[0]]
   # TAUX = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )


   # Sea surface height [m]
   ZOS = ncSSH.ssh.values[:,south[0]]
   #  ZOS = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # ice shelf melt [kg m-2 s-1, positive for actual melting] :
   fw = ncFW.fw.values[:,south[0]] # m/s
   FICESHELF = fw.copy()
   FICESHELF[:, ulevel == 0] = 0
   FICESHELF =FICESHELF*-1000
   #  FICESHELF = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )


   # sea-ice concentration [0-100]
   SICONC = ncAI.a_ice.values[:,south[0]]*100.0
   SICONC[:, ulevel > 0] = np.nan
   #  SICONC = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )   

   # sea-ice volume per area [m]
   SIVOL = ncHI.m_ice.values[:,south[0]]
   SIVOL[:, ulevel > 0] = np.nan

   # sea-ice x-ward velocity [m/s]
   SIUX = ncUI.uice.values[:,south[0]]
   SIUX[:, ulevel > 0] = np.nan
   # SIUX = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # sea-ice y-ward velocity [m/s]
   SIVY = ncVI.vice.values[:,south[0]]
   SIVY[:, ulevel > 0] = np.nan
   # SIVY = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # Total heat flux received by the ocean surface (including ice-shelf/ocean interface) [W m-2] 
   # see Griffies et al. (2016, section K4-K5) NB: here, including correction if any unlike Griffies (to avoid 2 variables)
   HFDS = ncHF.fh.values[:,south[0]]
   HFDS[:, ulevel > 0] = np.nan
   #  HFDS = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )
   
   WFOCORR = np.ones([mtime,mx])*np.nan
   # Water flux entering the ocean due to sea-ice (melting-freezing) and surface correction (SSS restoring)
   # (= fsitherm + wfocorr in Griffies 2016 section K2) [kg m-2 s-1]
   WFOSICOR = ncTHDGR.thdgr.values[:,south[0]]  # sea ice change m/s
   WFOSICOR = WFOSICOR * -1000
   WFOSICOR[:, ulevel > 0] = np.nan

   #   WFOSICOR = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # Water flux entering the ocean due to rainfall, snowfall, condensation - evap, 
   # river runoff, iceberg and ice-shelf melt [kg m-2 s-1]  
   # (= pr+prs+evs+ficeberg+friver+ficeshelf in Griffies 2016, section K2)
   WFOATRLI = fw
   WFOATRLI[:, ulevel > 0] = np.nan
   #  WFOATRLI = xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )


########################
   # Ocean fraction at each level:
   LEVOFT = np.ones([my,mx])*100 #maskT*100.0
   LEVOFT[Umask] = np.nan
   
   # Ocean fraction at surface:
   SFTOF = np.ones([mx])*0
   SFTOF[ulevel == 0]=100 	
	
   #levels = xr.DataArray(
   #np.arange(LEVOFT.size["level"]),dims="level")
   #mask = levels > ulevel
   #LEVOFT = LEVOFT.where(~mask, 0)
# level indices (148, 1)
   #levels = np.arange(LEVOFT.shape[0])[:, None]
# mask: True where level is ABOVE ulevel
   #mask = levels > ulevel[None, :]

# apply
   #LEVOFT[mask] = 0
   
   LEVOFU = LEVOFT
   LEVOFV = LEVOFT

   # 2d ice-shelf fractoin:
   SFTFLF = np.ones([mx])*0#ncM.misf*1.e0
   SFTFLF[ulevel > 0]=100
   #   SFTFLF = SFTFLF.where( (SFTFLF > 1.5), 0.e0 )
   #   SFTFLF = SFTFLF.where( (SFTFLF < 1.5), 100. )

#############################################
################################
   def densityJM_components(t, s):
        """
        Compute Jackett & McDougall EOS components.
        
        Parameters
        ----------
        t : array-like
            Potential temperature
            s : array-like
            Salinity

        Returns
        -------
        bulk_0, bulk_pz, bulk_pz2, rhopot : arrays
        """

        t = np.asarray(t)
        s = np.asarray(s)

        s_sqrt = np.sqrt(s)

        # --- constants ---
        a0 = 19092.56
        at, at2, at3, at4 = 209.8925, -3.041638, -1.852732e-3, -1.361629e-5
        as_, ast, ast2, ast3 = 104.4077, -6.500517, 0.1553190, 2.326469e-4
        ass, asst, asst2 = -5.587545, 0.7390729, -1.909078e-2

        ap, apt, apt2, apt3 = -4.721788e-1, -1.028859e-2, 2.512549e-4, 5.939910e-7
        aps, apst, apst2, apss = 1.571896e-2, 2.598241e-4, -7.267926e-6, -2.042967e-3

        ap2, ap2t, ap2t2 = 1.045941e-5, -5.782165e-10, 1.296821e-7
        ap2s, ap2st, ap2st2 = -2.595994e-7, -1.248266e-9, -3.508914e-9

        b0 = 999.842594
        bt, bt2, bt3, bt4, bt5 = 6.793952e-2, -9.095290e-3, 1.001685e-4, -1.120083e-6, 6.536332e-9
        bs, bst, bst2, bst3, bst4 = 0.824493, -4.08990e-3, 7.64380e-5, -8.24670e-7, 5.38750e-9
        bss, bsst, bsst2, bss2 = -5.72466e-3, 1.02270e-4, -1.65460e-6, 4.8314e-4

        # --- bulk_0 ---
        bulk_0 = ( a0
        + t * (at + t * (at2 + t * (at3 + t * at4)))
        + s * ( as_  + t * (ast + t * (ast2 + t * ast3))
            + s_sqrt * (ass + t * (asst + t * asst2)) )  )

        # --- bulk_pz ---
        bulk_pz = ( ap
        + t * (apt + t * (apt2 + t * apt3))
        + s * (aps + t * (apst + t * apst2) + s_sqrt * apss)    )

        # --- bulk_pz2 ---
        bulk_pz2 = ( ap2
        + t * (ap2t + t * ap2t2)
        + s * (ap2s + t * (ap2st + t * ap2st2))    )

        # --- rhopot ---
        rhopot = (
            b0
            + t * (bt + t * (bt2 + t * (bt3 + t * (bt4 + t * bt5))))
            + s
            * (  bs
                + t * (bst + t * (bst2 + t * (bst3 + t * bst4)))
            + s_sqrt * (bss + t * (bsst + t * bsst2))
            + s * bss2  )    )

        return bulk_0, bulk_pz, bulk_pz2, rhopot


   # mass barotropic streamfunction
   # see Griffies et al. (2016, section H26): d(psi)/dy=-U (U: x-ward mass transport), d(psi)/dx=V (V: yward mass transport)
   # if ( "sobarstf" in ncP.data_vars ):
   #  MSFTBAROT = ncP.sobarstf * rho0
   # else:
   #  print('    WARNING :   No data found for MSFTBAROT  -->  filled with NaNs')
   MSFTBAROT = np.ones([mtime,mx])*np.nan # xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   FLANDICE = np.ones([mtime,mx])*np.nan#, dims=['time', 'y', 'x'] )
   # ice shelf dynamical driving (heat exchange velocity) [m s-1]:
   #  print('    WARNING :   No data found for DYDRFLF  -->  filled with NaNs')

   # 2d ice-shelf fractoin:
   ice_shelf = np.zeros([mx]) #* np.nan #ncM.misf*1.e0
   ice_shelf[ulevel > 0] = 1

   ice_shelf= ice_shelf[None, :]

   Usurf = UX[:, ulevel, nodes]
   Vsurf = VY[:, ulevel, nodes]
   VV = np.sqrt((Usurf*Usurf) + (Vsurf*Vsurf) )
   pr1 = 13.8**(2/3)
   cpi = 152.5+7.122*(273.15 -20)
   sak1 = np.sqrt(2.50e-2)
   re   = 10
   gats1= sak1 * VV
   gats2= 2.12 * np.log(gats1*re)-9
   gat  = gats1 / (gats2 + 12.5 * pr1)
   zice = -DEPFLF
   
   DYDRFLF = ice_shelf * VV * gat #xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] ) 

   # ice shelf thermal driving [degC]:
   #  print('    WARNING :   No data found for THDRFLF  -->  filled with NaNs')

   bulk_0, bulk_pz, bulk_pz2, rhopot = densityJM_components(TT[:, ulevel, nodes],SO[:, ulevel, nodes])
   Z_3d_n = zice[None, :]
   rho = bulk_0 + Z_3d_n * bulk_pz  + Z_3d_n * bulk_pz2
   rho = rho * rhopot/(rho +0.1 * Z_3d_n ) #- density_ref(nz,node)   
   # density_m_rho0 =rho
   rhoi = 920
   rhow = rho # density_m_rho0 + density_ref
   rhor = rhoi/rhow

   gas =  gats1 /(gats2+12.5 *2432.**(2./3.) ) 
   ep1  = 4180*gat
   ep2  = cpi * gas
   ep3  = 3.33e+5 *gas
   ep31 = -rhor*cpi*1.54e-6 /Z_3d_n # RG4190 / RG44027  ! CW
   ep4  = np.ones(VV.shape)*0.0901 + 7.61e-4 * Z_3d_n
   ep5  = gas/rhor

   sal = SO[:, ulevel, nodes]
   tf = -0.0575 * sal + ep4
   tin=TT[:, ulevel, nodes]
   tob= -20 
   
   mask = TT[:, ulevel, nodes] < tf
# allocate outputs
   ex1 = np.empty_like(tf)
   ex2 = np.empty_like(tf)
   ex3 = np.empty_like(tf)
   ex6 = np.empty_like(tf)

# --- case 1: tin < tf ---
   ex1[mask] = -0.0575 * (ep1[mask] + ep31[mask])
   ex2[mask] = ep1[mask] * (tin[mask] - ep4[mask]) + ep3[mask] + ep31[mask] * (tob - ep4[mask])
   ex3[mask] = ep3[mask] * sal[mask]
   ex6[mask] = 0.5

# --- case 2: tin >= tf ---
   ex1[~mask] = -0.0575 * (ep1[~mask] - ep2[~mask])
   ex2[~mask] = ep1[~mask] * (ep4[~mask] - tin[~mask]) + ep2[~mask] * (tob + -0.0575  * sal[~mask] - ep4[~mask]) - ep3[~mask]
   ex3[~mask] = sal[~mask] * (ep2[~mask] * (ep4[~mask] - tob) + ep3[~mask])
   ex6[~mask] = -0.5

# --- core computation ---
   ex4 = ex2 / ex1
   ex5 = ex3 / ex1

   sr1 = 0.25 * ex4**2 - ex5
   sr1 = np.maximum(sr1, 0.0)   # avoid sqrt of negative

   sr2 = ex6 * ex4

   sqrt_sr1 = np.sqrt(sr1)

   sf1 = sr2 + sqrt_sr1
   tf1 = -0.0575  * sf1 + ep4

   sf2 = sr2 - sqrt_sr1
   tf2 = -0.0575  * sf2 + ep4

# --- choose valid solution (s > 0) ---
   mask = sf1 > 0

   s_freez = np.where(mask, sf1, sf2)
   t_freez = np.where(mask, tf1, tf2)

   THDRFLF =  ice_shelf * (tin - t_freez ) # xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )

   # ice shelf haline driving [0.001]:
  
   HADRFLF = ice_shelf * (sal - s_freez) #xr.DataArray( np.zeros((mtime,my,mx))*np.nan, dims=['time', 'y', 'x'] )


####
   #----------
   # Create new xarray dataset including all useful variables:
   # reshaping (x,y) as 1-dimensional (sxy)

#   nxy=(jmax-jmin+1)*(imax-imin+1)

   newdepth=depTUV.values #*-1 
   newdepth[0]=0.0 # so that 1st level is taken at the surface without extrapolation

   time_conv=ncT.time.dtype
   if ( time_conv == 'datetime64[ns]' ):
     time_val = ncT.time.values # standard calendar 
   else:
     time_val = ncT.indexes['time'].to_datetimeindex().values # to enable dealing with non-standard calendar (e.g. noleap)
 
    # Domain mask (ones with a halo of nans), used not to interpolate beyond the original domain:
   halonan = np.ones((mx))#*np.nan
   #halonan[0,:] = np.nan ; halonan[-1,:] = np.nan
   #halonan[:,0] = np.nan ; halonan[:,-1] = np.nan
   DOMMSKT = halonan#xr.DataArray( halonan, dims=['y', 'x'] )
   DOMMSKU = halonan# xr.DataArray( halonan, dims=['y', 'x'] )
   DOMMSKV = halonan#xr.DataArray( halonan, dims=['y', 'x'] )

   dxT = np.sqrt(ncM.nod_area.values[0,south[0]])
   dyT = dxT

   ele1 = xc.shape[0]
   ele2 = xc.shape[1]

   ds = xr.Dataset(
      {
       "SO":        (["time", "z", "sxy"], SO),
       "THETAO":    (["time", "z", "sxy"], THETAO),
       "UX":        (["time", "z", "sxy"], UX),
       "VY":        (["time", "z", "sxy"], VY),
       "TAUX":      (["time", "sxy_e"], TAUX),
       "TAUY":      (["time", "sxy_e"], TAUY),
       "ZOS":       (["time", "sxy"], ZOS),
       "TOB":       (["time", "sxy"], TOB),
       "SOB":       (["time", "sxy"], SOB),
       "LIBMASSBFFL": (["time", "sxy"], FICESHELF),
       "FLANDICE":  (["time", "sxy"], FLANDICE ),
       "DYDRFLF":   (["time", "sxy"], DYDRFLF),
       "THDRFLF":   (["time", "sxy"], THDRFLF),
       "HADRFLF":   (["time", "sxy"], HADRFLF),
       "MSFTBAROT": (["time", "sxy"], MSFTBAROT),
       "HFS":      (["time", "sxy"], HFDS),
       "WFOAT":  (["time", "sxy"], WFOATRLI),
       "WFOCORR":  (["time", "sxy"], WFOCORR),
       "FSITHERM":  (["time", "sxy"], WFOSICOR),
       "SICONC":    (["time", "sxy"], SICONC),
       "SIVOL":     (["time", "sxy"], SIVOL),
       "SIUX":      (["time", "sxy"], SIUX),
       "SIVY":      (["time", "sxy"], SIVY),
       "LEVOFT":     (["z", "sxy"], LEVOFT),
       "LEVOFU":     (["z", "sxy"], LEVOFU),
       "LEVOFV":     (["z", "sxy"], LEVOFV),
       "SFTOF":     (["sxy"], SFTOF ),
       "SFTFLF":    (["sxy"], SFTFLF),
       "DEPFLF":    (["sxy"], DEPFLF),
       "DEPTHO":    (["sxy"], DEPTHO),
       "DOMMSKT":   (["sxy"], DOMMSKT),
       "DOMMSKU":   (["sxy"], DOMMSKU),
       "DOMMSKV":   (["sxy"], DOMMSKV),
       "lonT":      (["sxy"], lonT),
       "lonU":      (["sxy"], lonT),
       "lonV":      (["sxy_e"], xcm.values),
       "lonE":      (["sxy_e"], xcm.values),
       "latT":      (["sxy"], latT),
       "latU":      (["sxy"], latT),
       "latV":      (["sxy_e"], ycm.values),
       "latE":      (["sxy_e"], ycm.values),
       "dxT":       (["sxy"], dxT),
       "dyT":       (["sxy"], dyT),
       "thetaT":    (["sxy"], latT*0),#thetaT),
       "thetaU":    (["sxy"], latT*0),# thetaU),
       "thetaV":    (["sxy"], latT*0),# thetaV),
       "depTUV":    (['z'], depTUV.values),
       "xc":       (["ele1","ele2"], xc.values),
       "yc":       (["ele1","ele2"], yc.values)
      },
      coords={
      "time": time_val,
      "z": newdepth
      },
      attrs={
      "original_minlat": domain_minlat,
      "original_maxlat": domain_maxlat,
      "original_minlon": domain_minlon,
      "original_maxlon": domain_maxlon
      },
   )

   print('    Load duration: ',datetime.now() - startTime)

   return ds



def check_points_in_any_polygon(xx, yy, lon_pts, lat_pts):
    
    import numpy as np
    import shapely
    from shapely.ops import unary_union

    # 1. Create polygons from columns
    # We transpose so each row is a triangle's [x0, x1, x2] and [y0, y1, y2]
    coords = np.stack([xx, yy], axis=2).transpose(1, 0, 2)
    
    # Create the list of polygons
    polygons = [shapely.geometry.Polygon(p) for p in coords]
    
    # 2. To fix the "half-empty" issue, let's merge all polygons into 
    # one single "Ocean Mask" geometry. This fills any gaps between triangles.
    ocean_poly = unary_union(polygons)
    
    # 3. Vectorize points
    points = shapely.points(lon_pts, lat_pts)
    
    # 4. Use 'contains' which is faster on a single merged geometry
    # This returns a boolean array directly
    mask = shapely.contains(ocean_poly, points)
    
    return mask
