context("Compute: Transform and chunk along lat/lon")

test_that("transform lat/lon and chunk over them", {

lons.min <- 10
lons.max <- 20
lats.min <- 20
lats.max <- 40

suppressWarnings(
exp <- Start(dat = '/esarchive/exp/ecmwf/system5_m1/monthly_mean/$var$_f6h/$var$_$sdate$.nc',
             var = 'tas',
             sdate = '20000101', #paste0(2000:2001, '0101'),
             ensemble = indices(1), #'all',
             time = indices(1),
             latitude = values(list(lats.min, lats.max)),
             latitude_reorder = Sort(),
             longitude = values(list(lons.min, lons.max)),
             longitude_reorder = CircularSort(0, 360),
             transform = CDORemapper,
             transform_params = list(grid = 'r100x50', 
                                     method = 'con',
                                     crop = c(lons.min, lons.max, lats.min, lats.max)),
             transform_vars = c('latitude', 'longitude'),
             transform_extra_cells = 8,
             synonims = list(latitude = c('lat', 'latitude'),
                             longitude = c('longitude', 'lon')),
             return_vars = list(latitude = NULL, #'dat',
                                longitude = NULL, #'dat',
                                time = 'sdate'),
             retrieve= F)
)
func <- function(exp) {
  return(exp)
}
step <- Step(func,
             target_dims = 'sdate', output_dims = 'sdate')
wf <- AddStep(exp, step)
suppressWarnings(
res <- Compute(wf,
               chunks = list(latitude = 2, longitude = 2))$output1
)

expect_equal(
dim(res),
c(sdate = 1, dat = 1, var = 1, ensemble = 1, time = 1, latitude = 5, longitude = 3)
)
expect_equal(
drop(res)[, 1],
c(284.9907, 282.9883, 281.2574, 284.1387, 285.6547),
tolerance = 0.0001
)
expect_equal(
drop(res)[, 2],
c(285.4820, 282.9362, 282.6088, 287.3716, 285.0194),
tolerance = 0.0001
)
expect_equal(
drop(res)[, 3],
c(286.1208, 284.3523, 285.9198, 287.7389, 286.1099),
tolerance = 0.0001
)

suppressWarnings(
res1 <- Compute(wf,
               chunks = list(latitude = 3))$output1
)
expect_equal(
dim(res),
dim(res1)
)
expect_equal(
drop(res),
drop(res1)
)

})
