library(s2dverification)

data <- array(runif(5 * 25 * 30 * 31 * 89 * 180, 5, 10), 
      dim = c(dat = 5, var = 1, sdate = 30, ensemble = 25, ftime = 31,
              latitude = 89, longitude = 180))


map_anom <- array(numeric(), dim = c(latitude = 89, longitude = 180))

map_agree <- array(numeric(), dim = c(latitude = 89, longitude = 180))			


for (y in 1:89) {
    for (x in 1:180) {
        sub_dat <- Subset(Subset(data,  along = 'latitude', indices = y),
                          along = 'longitude', indices = x)
        clim <- s2dv::MeanDims(sub_dat, dims = c('sdate', 'ensemble'))
        anom <- sub_dat - s2dv::InsertDim(s2dv::InsertDim(clim, posdim = 3, 
                               lendim = 25, name = 'ensemble'), posdim = 3,
                               lendim = 30, name = 'sdate')
        ano_mean <- s2dv::MeanDims(anom, c('ensemble', 'ftime', 'sdate'))	
        MM_mean <- s2dv::MeanDims(ano_mean, c('dat'))
           if (!is.na(MM_mean)) {
               if (MM_mean > 0) {
                   ano_agree <- 100 * sum(ano_mean[!is.na(ano_mean)] > 0) / 
                                        length(ano_mean[!is.na(ano_mean)]) 
              } else if (MM_mean < 0) {
                    ano_agree <- 100 * sum(ano_mean[!is.na(ano_mean)] < 0)  / 
                                        length(ano_mean[!is.na(ano_mean)]) 
              } else if (MMc_mean == 0) {warning("Anomaly mean is equal to 0.")}
          } else {
             ano_agree <- NA
          }
    map_anom[y,x] <- MM_mean
    map_agree[y,x] <- ano_agree
    }
}


# ----------------- function
data <- array(rlnorm(5*30*25*31), dim = c(dat=5, sdate = 30, ensemble = 25, ftime = 31)) 

Agreement <- function(data) {
    clim <- s2dv::MeanDims(data, dims = c('sdate', 'ensemble'))
 
    anom <- Apply(data, c('dat', 'ftime'), function(x){x -clim})$output1 
     ano_mean <- s2dv::MeanDims(anom, c('sdate', 'ftime','ensemble'))
      MM_mean <- s2dv::MeanDims(ano_mean, c('dat'))
               if (MM_mean > 0) {
                   ano_agree <- 100 * sum(ano_mean[!is.na(ano_mean)] > 0) /
                                        length(ano_mean[!is.na(ano_mean)])
              } else if (MM_mean < 0) {
                    ano_agree <- 100 * sum(ano_mean[!is.na(ano_mean)] < 0)  /
                                        length(ano_mean[!is.na(ano_mean)])
              } else if (MM_mean == 0) {warning("Anomaly mean is equal to 0.")}
    return(list(MMM = MM_mean, agree = ano_agree))
}

data <- array(runif(5 * 25 * 30 * 31 * 89 * 2, 5, 10),
      dim = c(dat = 5, var = 1, sdate = 30, ensemble = 25, ftime = 31,
              latitude = 89, longitude = 2))
result <- Apply(data, c('dat', 'sdate', 'ftime', 'ensemble'), Agreement)

