library(CSTools)
library(s2dverification)
library(zeallot)
# One start date to test:
#5
startdates <- sapply(2006:2018, function(x) {
               paste0(x, sprintf('%02d', 1), '01')})
path <- list(name = 'ERA5AI',
 path = '/esarchive/exp/tum/era5ai/$STORE_FREQ$_mean/$VAR_NAME$_f1h-r1.40625/$VAR_NAME$_$YEAR$$MONTH$01.nc')
#10
era5_LR_g500 <- CST_Load(var = 'g500', exp = NULL,
                 obs = list(path), leadtimemax = 31,
                 sdates =  startdates,
                 latmin = 25, latmax = 57, lonmin = -21, lonmax = 51,
#15
                 output = 'lonlat', storefreq = "daily",  nprocs = 1)
path <- list(name = 'ERA5HR',
 path = '/esarchive/recon/ecmwf/era5/$STORE_FREQ$_mean/$VAR_NAME$_f1h-r1440x721cds/$VAR_NAME$_$YEAR$$MONTH$.nc')
era5_HR_g500 <- CST_Load(var = 'g500', exp = NULL,
#20
                    obs = list(path), leadtimemax = 31,
                    sdates =  startdates,
                    latmin = 25, latmax = 57, lonmin = -21, lonmax = 51,
                    output = 'lonlat', storefreq = "daily",  nprocs = 1)
#25
era5_LR_g500_ts <- CST_MergeDims(data = era5_LR_g500, merge_dims = c('ftime', 'sdate'),
                                 rename_dim = 'time')
source("/esarchive/scratch/nperez/git/cstools/R/CST_Analogs.R")
library(multiApply)
#30 
down_data <- Analogs(expL = era5_LR_g500_ts$data[1, 1, i, , ], 
                     obsL = era5_LR_g500_ts$data[1, 1, 32:403, , ],
                     time_obsL = era5_LR_g500_ts$Dates[32:403], nAnalogs = 10)

#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)


