library(startR)

  repos <- "/esarchive/exp/ecmwf/system5_m1/monthly_mean/$var$_f6h/$var$_$sdate$.nc"
  var <- 'tas'
  sdate <- c('20170101', '20170201')
  lon.min <- 0
  lon.max <- 359.9
  lat.min <- -90
  lat.max <- 90

  data <- Start(dat = repos,
                var = var,
                sdate = sdate,
                ensemble = 'all',   
                time = 'all',
                latitude = values(list(lat.min, lat.max)),
                latitude_reorder = Sort(),
                longitude = values(list(lon.min, lon.max)),
                longitude_reorder = CircularSort(0, 360),
                synonims = list(latitude = c('lat', 'latitude'),
                                longitude = c('lon', 'longitude')),
                return_vars = list(time = 'sdate', 
                                   longitude = NULL, latitude = NULL),
                retrieve = FALSE
               )
  
  func <- function(x, conf, pval) {
    # x: [ensemble, time]
    # ensemble mean
    ens_mean <- apply(x, 2, mean)
    # temporal trend
    trend <- s2dv::Trend(ens_mean, conf = conf, pval = pval)$trend

    return(trend)
  }

  step <- Step(func, target_dims = c('ensemble', 'time'),
               output_dims = list(trend = 'stats'),
               use_libraries = c('s2dv'))

  wf <- AddStep(data, step, conf = FALSE, pval = FALSE)

#-------------------user-defined---------------------
  queue_host <- 'nord4' # short name in .ssh/config
  temp_dir <- '/gpfs/scratch/bsc32/bsc32734/startR_hpc/'
  ecflow_suite_dir <- '/home/Earth/aho/startR_local/'
#----------------------------------------------------

  # Nord3-v2
  res <- Compute(wf,
                 chunks = list(latitude = 2,
                               longitude = 2),
                 threads_load = 2,
                 threads_compute = 4,
                 cluster = list(
                   queue_host = 'nord4',
                   queue_type = 'slurm',
                   temp_dir = temp_dir,
                   cores_per_job = 16,
                   job_wallclock = '01:00:00',
                   max_jobs = 4,
#                   extra_queue_params = list('#SBATCH --constraint=medmem'),
                   bidirectional = FALSE,
                   polling_period = 10
                 ),
                 ecflow_suite_dir = ecflow_suite_dir,
                 wait = TRUE
                 )  

# Save the result if needed
saveRDS(res, file = '~/nord3_demo_result.Rds')

# Check the result
str(res)
dim(res$trend)

