library(startR)

path <- '/esarchive/recon/ecmwf/era5/1hourly/$var$/$var$_$sdate$.nc'

sdate <- sapply(1990:2019, function(x) paste0(x, sprintf('%02d', 1:12)))
dim(sdate) <- c(month = 12, year = 30)

data <- Start(dat = path,
              var = 'tasmax',
              sdate = sdate,
              time = 'all',
              latitude = indices(1:4),
              longitude = indices(1:3),
              #latitude = 'all',
              #longitude = 'all', # when using this option, run Compute in Nord3.
              split_multiselected_dims = TRUE,
              synonims = list(longitude = c('lon', 'longitude'),
                             latitude = c('lat', 'latitude')),
              return_vars = list(latitude = 'dat',
                                 longitude = 'dat',
                                 time = 'sdate'),
              retrieve = FALSE)

Mean <- function(x) {
  mean(x, na.rm = TRUE)
}

step <- Step(fun = Mean,
             target_dims = c('time'),
             output_dims = NULL)

wf <- AddStep(data, step)
  
## locally
start.time <- Sys.time()
res1 <- Compute(wf,
                chunks = list(year = 30))
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

climatology <- s2dv::MeanDims(result, 'year') 

plot(1:(12*30), s2dv::MeanDims(result, c('latitude', 'longitude')),
     type = 'b',  ylab = "tasmax (Celsius)", xlab = "Time (months)",
     xaxt = 'n', bty = 'n')
lines(1:(12*30), rep(s2dv::MeanDims(climatology, c('latitude', 'longitude')), 30),
      col = 'purple')
axis(1, seq(6, 360, 12), 1990:2019)

## efficiency tests can be done comparing against and submitting to Nord3:
start.time <- Sys.time()
res1 <- Compute(wf,
                chunks = list(year = 30, month = 12))
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

