library(startR)
data_seas5_retrieved <- Start(dat = "/esarchive/exp/ecmwf/system5_m3/monthly_mean/$var$_f6h/$var$_$sdate$.nc",
                              var = 'tos',
                              ensemble = indices(1:2),
                              sdate = c('19900501', '19910501',
                                        '19920501', '19930501'),
                              time = indices(1:4), 
                              lat = 'all', 
                              lat_reorder = Sort(decreasing = FALSE),
                              lon = 'all',
                              lon_reorder = CircularSort(-180, 180),
                              synonims = list(lon = c('lon', 'longitude'),
                                              lat = c('lat', 'latitude')),
                              return_vars = list(lat = 'dat', lon = 'dat',
                                                 time = 'sdate'),
                              retrieve = FALSE)
lat_seas5 = as.vector(attr(data_seas5_retrieved, 'Variables')$dat1$lat)
lon_seas5 = as.vector(attr(data_seas5_retrieved, 'Variables')$dat1$lon)

nc <- ncdf4::nc_open(as.vector(attributes(data_seas5_retrieved)$ExpectedFiles)[1])
var_attributes <- ncatt_get( nc, 'tos')
ncdf4::nc_close(nc)

fun_spatial_mean <- function(x, lons_data, lats_data, lon_min, lon_max, 
                             lat_min, lat_max) {
  library(ClimProjDiags)
  data_smean <- WeightedMean(data = x, lon = lons_data, lat = lats_data,
                             region = c(lon_min, lon_max, lat_min, lat_max),
                             mask = NULL,
                             londim = which(names(dim(x)) == 'lon'),
                             latdim = which(names(dim(x)) == 'lat'))
  return(data_smean)
}


step <- Step(fun = fun_spatial_mean,
             use_libraries = c('startR','ClimProjDiags'),
             target_dims = c('time', 'lat', 'lon'),
             output_dims = 'time')
wf_seas <- AddStep(inputs = data_seas5_retrieved,
                   step_fun = step,
                   lons_data = lon_seas5,
                   lats_data = lat_seas5,
                   lon_min = -150,
                   lon_max = -90,
                   lat_min = -5,
                   lat_max = 5)

res <- Compute(workflow = wf_seas,
               chunks = list(ensemble = 2, sdate = 4),
               threads_load = 1,
               threads_compute = 4,
               cluster = list(queue_host = 'nord3',
                              queue_type = 'lsf',
                         temp_dir = '/gpfs/scratch/bsc32/bsc32339/startR_hpc/',
                         job_wallclock = '01:00',
                         max_jobs = 8,
                         extra_queue_params = list('#BSUB -q bsc_es'),
                         bidirectional = FALSE,
                         polling_period = 10),
                 ecflow_suite_dir = '/home/Earth/nperez/startR_local/',
                 wait = TRUE)$output1

