#----------------------------------------------------------------------------
# Author: An-Chi Ho
# Date: 18th Jun 2021 
#
# This script shows how to use Start() to load irregular grid data , then regrid it
# by s2dv::CDORemap. 
#----------------------------------------------------------------------------

library(startR)
library(s2dv)

# Case 1:
path1 <- '/esarchive/exp/ecearth/a1ua/cmorfiles/DCPP/EC-Earth-Consortium/EC-Earth3/dcppA-hindcast/r1i1p1f1/Omon/$var$/gn/v20190713/$var$_*_s$sdate$-$member$_gn_$aux$.nc'

data1 <- Start(dataset = path1,
               var = 'tos',
               sdate = paste0(1960),
               aux = indices(1),
               aux_depends = 'sdate',
               j = 'all', 
               i = 'all',
               time = indices(1),
               member = 'r1i1p1f1',
               return_vars = list(j = NULL, i = NULL, 
                                  latitude = NULL, longitude = NULL),
               retrieve = T)
lons1 <- attributes(data1)$Variables$common$longitude
lats1 <- attributes(data1)$Variables$common$latitude
dim(lons1)
#  i   j 
#362 292
dim(lats1)
#  i   j 
#362 292 
dim(data1) 
#dataset     var   sdate     aux       j       i    time  member 
#      1       1       1       1     292     362       1       1 

res1 <- CDORemap(drop(data1), lons1, lats1, grid = 'r100x50', method = 'bil', crop = FALSE)
dim(res1$data_array)
#lon lat 
#100  50 
PlotEquiMap(t(res1$data_array), lon = res1$lons, lat = res1$lats, fileout = '~/irre_grid_res1.png')

#---------------------------------------------------------

# Case 2: 
path2 <- paste0('/esarchive/exp/CMIP6/dcppA-hindcast/cmcc-cm2-sr5/cmip6-dcppA-hindcast_i1p1/',
               'DCPP/CMCC/CMCC-CM2-SR5/dcppA-hindcast/$member$/Omon/$var$/gn/v20210312/',
               '$var$_*_s$sdate$-$member$_gn_$aux$.nc')

data2 <- Start(dataset = path2,
              var = 'tos',
              sdate = '1960',
              aux = 'all',
              aux_depends = 'sdate',
              j = indices(2:361), # remove two indices to avoid white strips 
              i = indices(2:291), # remove two indices to avoid white strips 
              time = indices(1),
              member = 'r1i1p1f1',
              return_vars = list(j = NULL, i = NULL,
                                 latitude = NULL, longitude = NULL),
              retrieve = T)

lons2 <- attributes(data2)$Variables$common$longitude
lats2 <- attributes(data2)$Variables$common$latitude
dim(lons2)
#  j   i 
#360 290 
dim(lats2)
#  j   i 
#360 290
dim(data2) 
#dataset     var   sdate     aux       j       i    time  member 
#      1       1       1       1     360     290       1       1 

data2 <- ClimProjDiags::Subset(data2, c(1,2,3,7,8), list(1,1,1,1,1), drop = 'selected')
res2 <- CDORemap(drop(data2), lons2, lats2, grid = 'r100x50', method = 'bil', crop = FALSE)
dim(res2$data_array)
#lon lat 
#100  50 
PlotEquiMap(res2$data_array, lon = res2$lons, lat = res2$lats, fileout = '~/irre_grid_res2.png')

