library(CSTools)
library(s2dverification)
library(zeallot)
# One start date to test:
startdates <- sapply(1999, function(x) {
               paste0(x, sprintf('%02d', 6), '01')})
c(exp, obs) %<-% CST_Load(var = 'psl', exp = 'system5c3s',
                 obs = 'era5', leadtimemax = 92,
                 sdates =  startdates,
                 #latmin = 30, latmax = 70, lonmin = -60, lonmax = 40,
                 latmin = 25, latmax = 57, lonmin = -21, lonmax = 51,
                 output = 'lonlat', storefreq = "daily",  nprocs = 1,
                 configfile = "/esarchive/scratch/nperez/BSC.conf")
era5 <- CST_Load(var = 'psl',
                 obs = 'era5', leadtimemax = 92,
                 sdates =  startdates,
                 #latmin = 30, latmax = 70, lonmin = -60, lonmax = 40,
                 latmin = 25, latmax = 57, lonmin = -21, lonmax = 51,
                 output = 'lonlat', storefreq = "daily",  nprocs = 1,
                 configfile = "/esarchive/scratch/nperez/BSC.conf")

source("/esarchive/scratch/nperez/git/cstools/R/CST_MergeDims.R")
library(abind)
obs <- CST_MergeDims(data = obs, merge_dims = c('ftime', 'sdate'),
                         rename_dim = 'time')
era5 <- CST_MergeDims(data = era5, merge_dims = c('ftime', 'sdate'),
                         rename_dim = 'time')
dim(obs$data)
dim(exp$data)
#source("/esarchive/scratch/nperez/git/cstools/R/CST_AnalogsStatistics.R")
#statistics <- AnalogsStatistics(expL = exp$data, obsL = obs$data, ncores = detectCores() - 1)

source("/esarchive/scratch/nperez/git/cstools/R/CST_Analogs.R")
library(multiApply)
library(parallel)
  result <- Select(expL = exp$data, obsL = obs$data,
                 ncores = detectCores() - 1)
  best <- Apply(list(result$position), target_dims = c('time', 'pos'),
              fun = BestAnalog, criteria = 'LargeDist',
              return_list = FALSE, nAnalogs = 1, ncores = detectCores() - 1)$output1
  Analogs_dates <- obs$Dates[best]
  dim(Analogs_dates) <- dim(best)
  Analogs_metric <- Subset(result$metric, along = 'time', indices = 1 : nAnalogs)
  Analogs_field <- Subset(obs$data, along = 'time', indices = best)
  dim(Analogs_field) <- dim(exp$data)
  PlotEquiMap(Analogs_field[1,1,1,1,,], lon = exp$lon, lat = exp$lat, filled.con = FALSE)
  dev.new()
  PlotEquiMap(exp$data[1,1,1,1,,], lon = exp$lon, lat = exp$lat, filled.con = FALSE)




result <- Analogs(expL = exp$data, obsL = obs$data, time_obsL = obs$Dates[[1]], 
                  obsVar = obs$data, criteria = 'Large_dist',
                  ncores = detectCores() - 1)
PlotEquiMap(result$AnalogsFields[1,1,1,1,,], lon = obs$lon, lat = obs$lat, filled.c = F)

result <- Analogs(expL = exp$data, obsL = obs$data, time_obsL = obs$Dates[[1]],
                  obsVar = era5$data, criteria = 'Large_dist',
                  ncores = detectCores() - 1)
PlotEquiMap(result$AnalogsFields[1,1,1,9,,], lon = era5$lon, lat = era5$lat, filled.c = F,
            toptitle = c('Downscaled for System5c3s psl 1999-06-09', 'ERA5 psl 1999-06-11'),
            title_scale = 0.7, fileout = '/esarchive/scratch/nperez/Day1ERA511.png')
)            
PlotEquiMap(era5$data[1,1,9,,], lon = era5$lon, lat = era5$lat, filled.c = F,
            toptitle = c('ERA5 psl 1999-06-09'),
            fileout = '/esarchive/scratch/nperez/Day1ERA59.png')

result$AnalogsMetrics[1,1,1,1,9, 1,1,1]

dim(result$AnalogsDates)
PlotEquiMap(exp$data[1,1,1,9,,], lon = exp$lon, lat = exp$lat, filled.con = FALSE,
            toptitle = 'System5c3s psl 1999-06-09', fileout = '/esarchive/scratch/nperez/Day1.png')

 result <- Select(expL = exp$data, obsL = obs$data,
                 ncores = detectCores() - 1)
  best <- Apply(list(result$position), target_dims = c('time', 'pos'),
              fun = BestAnalog, criteria = 'LargeDist',
              return_list = FALSE, nAnalogs = 1, ncores = detectCores() - 1)$output1
  Analogs_dates <- obs$Dates[best]
  dim(Analogs_dates) <- dim(best)
  Analogs_metric <- Subset(result$metric, along = 'time', indices = 1 : nAnalogs)
  Analogs_field <- Subset(era5$data, along = 'time', indices = best)


