rm(list = ls())
library(plyr)
library(multiApply)
source('/esarchive/scratch/jramon/GitLab_jramon/downscaling/csdownscale/R/Interpolation.R')
output.dir.resolution <- '/esarchive/scratch/cchou/FOCUS/resolution/output/'
interpolation.methods.point <- c('nearest', 'bilinear', '9point', 'invdist4nn',
                                 "NE", "NW", "SE", "SW")
systems <- c('seas5')

system <- 'seas5'
var <- 'tas'
load('/esarchive/scratch/cchou/FOCUS/resolution/output//data/Interpolation_seas5_tas_r3600x1801_point.RData') # sample data
hcst <- drop(data$hcst$data)[24, 1, , , 1] - 273.15 # the year 2016
obs <- drop(data$obs$data)[24, 1, , ] - 273.15 # the year 2016
hcst.lon <- data$hcst$lon
hcst.lat <- data$hcst$lat
obs.lon <- data$obs$lon
obs.lat <- data$obs$lat

obs.median <- median(obs, na.rm = TRUE)
obs.median
yy.obs <- obs.lat[which(obs == obs.median, arr.ind = TRUE)[1, 1]]
xx.obs <- obs.lon[which(obs == obs.median, arr.ind = TRUE)[1, 2]]
obs[which(obs == obs.median, arr.ind = TRUE)[1, 1], which(obs == obs.median, arr.ind = TRUE)[1, 2]]

era5land.coordinate <- list(latitude = yy.obs, longitude = xx.obs)
interpolation.method.point = 'bilinear' # debug

print(paste0("Method '", interpolation.method.point, "' | point at lat ", yy.obs, ' and lon ', xx.obs))
res <- Interpolation(exp = hcst, lats = hcst.lat, lons = hcst.lon,
                     method_remap = interpolation.method.point,
                     points = era5land.coordinate,
                     target_grid = NULL,
                     method_point_interp = interpolation.method.point,
                     source_file = '/esarchive/exp/ecmwf/system5c3s/monthly_mean/tas_f6h/tas_20160101.nc',
                     lat_dim = 'latitude', lon_dim = 'longitude')


