library(urbanR)
######################
## SERIAL VERSION
n_receptors <- 100
results <- data.frame(rec_id=1:n_receptors,NO2=1/(1:n_receptors))
corrected1 <- data.frame(rec_id = numeric(), NO2 = numeric())
for (index in 1:n_receptors) {
  model_day     <- results[results$rec_id==index,]
  model_day$NO2 = model_day$NO2 + 1
  corrected1[index,] =  list( index, model_day$NO2 )
}

library(multiApply)

## Version 1:
# convert input to array
datos <- array(results$NO2, c(rec_id = length(results$NO2)))

res <- Apply(list(datos), target_dims = NULL, #margins = 'rec_id',
             fun = function(x) {x + 1})$output1
# res is an array
all(res == corrected1[,2])


datos <- array(rep(results$NO2, 4), c(rec_id = length(results$NO2), hora = 4))
correccio <- array(rnorm(100), c(rec_id = 100))
res <- Apply(list(datos, correccio), margins = 'rec_id', fun = function(x, y) {
               print(x); print(y)
               x + y})$output1
res2 <- Apply(list(datos, correccio), target_dims = list('hora', NULL), fun = function(x, y) {
               print(x); print(y)
               x + y})$output1

# tranform res to data.frame:
corrected_Apply <- data.frame(rec_id = 1:n_receptors, model_day = res) 
str(corrected_Apply)

## Version 2:
# create a index to loop
index_vector <-   1:n_receptors
dim(index_vector) <- c(receptors=n_receptors)
res <- Apply(list(index_vector), margins = 'receptors',
             fun = function (x, inputdata) {
                return(inputdata[inputdata$rec_id==x, 2] + 1)}, 
             inputdata = results)$output1
all(res == corrected1[,2])
# tranform res to data.frame:
corrected_Apply <- data.frame(rec_id = 1:n_receptors, model_day = res)
str(corrected_Apply)

# Version 4
test_f <- function(idx, results) {
  print(idx)
  model_day     <- results[results$rec_id==idx,]
  #model_day$NO2 = model_day$NO2 + 1
  #corrected2[idx,] =  list( idx, model_day$NO2 )
  return(model_day$NO2 + 1)
}
corrected2 <- data.frame(rec_id = numeric(), NO2 = numeric())
n_receptors <- 100
results <- data.frame(rec_id=1:n_receptors,NO2=1/(1:n_receptors))
index_vector <-   1:n_receptors
dim(index_vector) <- c(receptors=n_receptors)
parallel_corrected2 <- multiApply::Apply(list(index_vector),
                  margins='receptors',
                  fun = test_f, results = results,
                  ncores = 2)$output1

 # data should be a list
 # results should be an input to the function
