library(CSTools)
startDates <- c('20001101', '20011101', '20021101',
                '20031101', '20041101', '20051101')

regrid_exp <- CST_Load(var = 'psl',
                         exp = 'system5c3s',
                         nmember = 1, sdates = '20191101', leadtimemax = 1,
                         latmin = 27, latmax = 48, lonmin = -12, lonmax = 40,
                         output = 'lonlat', storefreq = "daily",  nprocs = 1,
                         grid = 'r1280x640',
                         configfile = "/esarchive/scratch/nperez/BSC.conf")
obs <- CST_Load(var = 'psl', obs = 'era5',
                sdate = c('20011101', '20021101'),
                leadtimemax = 5, 
                latmin = 27, latmax = 48, lonmin = -12, lonmax = 40,
                output = 'lonlat', storefreq = "daily",  nprocs = 1,
                grid = 'r1280x640',
                configfile = "/esarchive/scratch/nperez/BSC.conf")
regrid_data <- list(exp = regrid_exp, obs = obs)
save('regrid_data', list = 'regrid_data', file = 'RegridDataforAnalogs.RData')
load('RegridDataforAnalogs.RData')
res <- CST_Analogs(regrid_data$exp, regrid_data$obs)

object.size(regrid_exp)/1000/1000
object.size(obs)/1000/1000

res <- Analogs(regrid_exp$data, obs$data, time_obsL = obs$Dates)
 
prec_data <-  CST_Load(var = 'psl',
                       exp = 'system5c3s',#, obs = 'era5',
                       nmember = 15,sdates = startDates, leadtimemax = 3,
                       latmin = 27, latmax = 48, lonmin = -12, lonmax = 40,
                       output = 'lonlat', storefreq = "daily",  nprocs = 1,
                       configfile = "/esarchive/scratch/nperez/BSC.conf")

# Output verification:
> dim(lonlat_data$exp$data)
dataset  member   sdate   ftime     lat     lon 
      1      15       6       3      75     185 
> dim(lonlat_data$obs$data)
dataset  member   sdate   ftime     lat     lon 
      1       1       6       3      75     185 
> dim(prec_data$obs$data)
dataset  member   sdate   ftime     lat     lon 
      1       1       6       3      22      53 
> dim(prec_data$exp$data)
dataset  member   sdate   ftime     lat     lon 
      1      15       6       3      22      53 
lonlat_data$exp$lat
[....]
attr(,"cdo_grid_name")
[1] "r1280x640"
prec_data$exp$lat
attr(,"cdo_grid_name")
[1] "r360x181"

> summary(prec_data$exp$data)*3600*24*1000
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
 -1.72022   0.00000   0.00763   1.43251   0.95386 103.93920 
> summary(prec_data$obs$data)*3600*24*1000
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
 0.00000  0.00000  0.02455  1.57334  0.86210 87.78240 
> summary(lonlat_data$exp$data)*3600*24*1000
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
 -1.72022   0.00000   0.02543   1.42992   1.00310 103.93920 
> summary(lonlat_data$obs$data)*3600*24*1000
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
  0.00000   0.00000   0.00651   1.58976   0.73051 108.51840 




