library(CSTools)
library(lubridate)
library(startR)
library(s2dv)
#source('/esarchive/scratch/jramon/GitLab_jramon/downscaling/csdownscale/R/Interpolation.R')
source("/home/Earth/aho/aho-testtest/csdownscale_interpolation.R")

#plotpath <- '/esarchive/scratch/jramon/downscaling/plots/ip'
target_grid <- '/esarchive/recon/ecmwf/era5/monthly_mean/tas_f1h/tas_200002.nc'
#sdates <- c('20000201','20010201','20020201','20030201','20040201','20050201','20060201','20070201')
sdates <- '20000201'

latmin <- 10
latmax <- 20
#============================
# Case [0, 360]
#============================
# 1-1) One integrate region
lonmin <- 10
lonmax <- 20
# 1-2) Two split regions (across border)
lonmin <- 350
lonmax <- 5
# 1-3) One integrate region at left border
lonmin <- 0
lonmax <- 10
# 1-4) One integrate region at right border
lonmin <- 350
lonmax <- 360

exp1 <- Start(dat = '/esarchive/exp/ecmwf/system4_m1/monthly_mean/$var$_f6h/$var$_$sdate$.nc',
              var = 'tas', time = indices(1), member = indices(1), 
              sdate = sdates,
              lat = values(list(latmin, latmax)), 
              lat_reorder = Sort(decreasing = FALSE),
              lon = values(list(lonmin, lonmax)), 
              lon_reorder = CircularSort(0, 360),
              synonims = list(lon = c('lon', 'longitude'),
                              lat = c('lat', 'latitude'), 
                              member = c('member','ensemble')),
              return_vars = list(lat = 'dat', lon = 'dat'),
              num_procs = 1, 
              retrieve = TRUE)

as.vector(attr(exp1, 'Variables')$dat1$lon)
# 1-1) One integrate region
 [1] 10.54688 11.25000 11.95312 12.65625 13.35938 14.06250 14.76562 15.46875
 [9] 16.17188 16.87500 17.57812 18.28125 18.98438 19.68750
# 1-2) Two split regions (across border)
 [1]   0.000000   0.703125   1.406250   2.109375   2.812500   3.515625
 [7]   4.218750   4.921875 350.156250 350.859375 351.562500 352.265625
[13] 352.968750 353.671875 354.375000 355.078125 355.781250 356.484375
[19] 357.187500 357.890625 358.593750 359.296875
# 1-3) One integrate region at left border
 [1] 0.000000 0.703125 1.406250 2.109375 2.812500 3.515625 4.218750 4.921875
 [9] 5.625000 6.328125 7.031250 7.734375 8.437500 9.140625 9.843750
# 1-4) One integrate region at right border
 [1]   0.0000 350.1562 350.8594 351.5625 352.2656 352.9688 353.6719 354.3750
 [9] 355.0781 355.7812 356.4844 357.1875 357.8906 358.5938 359.2969
#360 changes to 0!!!!!!!!!!!!!!!!!!!!



#==========================================================================

exp2 <- s2dv_cube(exp1, lat = attr(exp1, "Variables")$dat1$lat, lon = attr(exp1, "Variables")$dat1$lon,
                 source_files = attr(exp1, "Files")[1,1,])
attr(exp2$lon,"first_lon") <- exp2$lon[1]
attr(exp2$lon,"last_lon") <- exp2$lon[length(exp2$lon)]
attr(exp2$lat,"first_lat") <- exp2$lat[1]
attr(exp2$lat,"last_lat") <- exp2$lat[length(exp2$lat)]

#--------------------------------
# Downscaling with Interpolation
#--------------------------------
lat1 <- attr(exp1, "Variables")$dat1$lat
lon1 <- attr(exp1, "Variables")$dat1$lon
exp1_1 <- Interpolation(exp = exp1, lats = lat1, lons = lon1, 
                        target_grid = target_grid, method_remap = 'con')
#exp1_1 has mismatch dim
exp1_2 <- Interpolation(exp = exp1, lats = lat1, lons = lon1,
                        target_grid = target_grid, method_remap = 'con',
                        remap_region = c(lonmin, lonmax, latmin, latmax))
exp1_3 <- s2dv::CDORemap(exp1, lons = lon1, lats =lat1, grid = target_grid,
                         method = 'con', crop = c(lonmin, lonmax, latmin, latmax))
all.equal(exp1_3$data_array, exp1_2$data)
[1] TRUE
all.equal(exp1_3$lon, exp1_2$lon)
[1] TRUE
all.equal(exp1_3$lat, exp1_2$lat)
[1] TRUE
as.vector(exp1_2$lon)


#==========================================================================

#--------------------------------
# Downscaling with CST_Interpolation
#--------------------------------
exp2_con <- CST_Interpolation(exp = exp2, target_grid = target_grid, method_remap = 'con')
exp2_bil <- CST_Interpolation(exp = exp2, target_grid = target_grid, method_remap = 'bil')
exp2_bic <- CST_Interpolation(exp = exp2, target_grid = target_grid, method_remap = 'bic')
exp2_nn <- CST_Interpolation(exp = exp2, target_grid = target_grid, method_remap = 'nn')
exp2_con2 <- CST_Interpolation(exp = exp2, target_grid = target_grid, method_remap = 'con2')

#--------------------------------
# Downscaling to point locations
#--------------------------------
points <- list(lat = c(36.1, 38.7), lon = c(-1.9, 0.8))
down_points_sbc <- CST_Interpolation(exp = exp, points = points, method_point_interp = 'bilinear',
                                     target_grid = target_grid, int_method = 'con', bc_method = 'simple_bias',
                                     ncores = 4)

#s2dv::PlotEquiMap(var = obs$data[1,1,1,,,1], lat = obs$lat, lon = obs$lon, filled.continents = FALSE, toptitle = 'Observations', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_obs.png"))
#s2dv::PlotEquiMap(var = exp$data[1,1,1,1,1,,], lat = exp$lat, lon = exp$lon, filled.continents = FALSE, toptitle = 'Predictions', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_fcst.png"))
#s2dv::PlotEquiMap(var = exp1_con$data[1,1,1,1,1,,], lat = exp_con$lat, lon = exp_con$lon, filled.continents = FALSE, toptitle = 'Conservative', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_con.png"))
#s2dv::PlotEquiMap(var = exp1_bil$data[1,1,1,1,1,,], lat = exp_bil$lat, lon = exp_bil$lon, filled.continents = FALSE, toptitle = 'Bilinear', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_bil.png"))
#s2dv::PlotEquiMap(var = exp1_bic$data[1,1,1,1,1,,], lat = exp_bic$lat, lon = exp_bic$lon, filled.continents = FALSE, toptitle = 'Bicubic', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_bic.png"))
#s2dv::PlotEquiMap(var = exp1_nn$data[1,1,1,1,1,,], lat = exp_nn$lat, lon = exp_nn$lon, filled.continents = FALSE, toptitle = 'Nearest neighbour', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_nn.png"))
#s2dv::PlotEquiMap(var = exp1_con2$data[1,1,1,1,1,,], lat = exp_con2$lat, lon = exp_con2$lon, filled.continents = FALSE, toptitle = '2nd order conservative', brks = seq(275,288,1), height = 8, width = 10, fileout = file.path(plotpath, "ip_con2.png"))
