library(CSTools)
library(s2dverification)
setwd("/esarchive/scratch/nperez/git/Flor/DL_DoswcalingPoster/")
#exp <- lonlat_prec




CDORemap(data_array = NULL, lons, lats, grid, method,

# January:
#startdates <- sapply(1979:2018, function(x) {
#               paste0(x, sprintf('%02d', 1), '01')})
# February: 
startdates <- sapply(1979:2018, function(x) {
               paste0(x, sprintf('%02d', 2), '01')})
path <- list(name = 'ERA5AI',
 path = '/esarchive/exp/tum/era5ai/$STORE_FREQ$_mean/$VAR_NAME$_f1h-r1.40625/$VAR_NAME$_$YEAR$$MONTH$01.nc')
exp <- CST_Load(var = 'prlr', exp = NULL,
                obs = list(path), leadtimemax = 29,
                sdates =  startdates,
                latmin = 20, latmax = 80, lonmin = -20, lonmax = 40,
                output = 'lonlat', storefreq = "daily",  nprocs = 1)

PlotEquiMap(exp$data[1,1,1,1,,], lon = exp$lon, lat = exp$lat,
            filled.continents = FALSE)


lons <- c(exp$lon[30:43]-360, exp$lon[1:29])
climWeights <- CST_RFWeights('wc2.0_30s_prec_eu.nc',  nf = 1,
                             lon = lons, lat = exp$lat)
climw <- CDORemap(data_array = climWeights, lons, lats, grid, method,
expReordered <- exp$data[,,,,,c(30:43, 1:29)]
exp$data <- expReordered
exp$lon <- lons 
exp_down_weights <- CST_RainFARM(exp, nf = 20, kmin = 1, nens = 1, 
                                 weights = climWeights, 
                                 time_dim = c("member", "ftime"), nprocs = 4)

save(exp_down_weights, file = "/esarchive/scratch/nperez/git/Flor/DL_DoswcalingPoster/DownData_RainFARMFebruary.RData")

cols <- rev(terrain.colors(20))
cols <- topo.colors(20)
brks <- round(seq(0, 200, length.out = length(cols) + 1), 2)

options(bitmapType = "cairo")
PlotEquiMap(exp_down_weights$data[1,1,,,1] * 86400 * 1000,
            lat = exp_down_weights$lat, lon = exp_down_weights$lon,
            filled.continents = FALSE, cols = cols, brks = brks,
 fileout = "/esarchive/scratch/nperez/git/Flor/DL_DoswcalingPoster/Plot_sdate1979_ftimeFEB1.png")



