
library(s2dv)
library(easyVerification)

# exp <- array(rnorm(1000), dim = c(lon = 3, lat = 2, sdate = 60, member = 10))
# ref <- array(rnorm(1000), dim = c(lon = 3, lat = 2, sdate = 60, member = 10))
# obs <- array(rnorm(1000), dim = c(lon = 3, lat = 2, sdate = 60))
# ROCSS(exp, obs)
# ROCSS(exp, obs, ref)

ROCSS <- function(exp, obs, ref = NULL, prob_thresholds = c(1/3,2/3), time_dim = 'sdate', member_dim = 'member', na.rm = FALSE, ncores = NULL){
  
  n_cats <- 1 + length(prob_thresholds)
  
  ## Reordering dimensions (for EnsRoca)
  exp <- Reorder(data = exp, order = c(names(dim(exp))[-(which(names(dim(exp)) %in% c(time_dim,member_dim)))], time_dim, member_dim))
  obs <- Reorder(data = obs, order = c(names(dim(exp))[-(which(names(dim(exp)) %in% c(time_dim,member_dim)))], time_dim))
  if (!is.null(ref)){
    ref <- Reorder(data = ref, order = c(names(dim(ref))[-(which(names(dim(ref)) %in% c(time_dim,member_dim)))], time_dim, member_dim))
  }
  
  ## ROCS for the forecast
  rocs_exp <- easyVerification::veriApply(verifun = 'EnsRoca', fcst = exp, obs = obs, 
                                          tdim = which(names(dim(exp))==time_dim), 
                                          ensdim = which(names(dim(exp))==member_dim), 
                                          prob = prob_thresholds, 
                                          na.rm = na.rm, ncpus = ncores)
  ## ROCSS
  rocss <- list()
  if (is.null(ref)){ ## Random forecast as reference forecast
    for (cat in paste0('cat',1:n_cats)){
      rocss[[cat]] <- 2 * rocs_exp[[cat]] - 1
    }
  } else {
    ## ROCS for the reference forecast
    rocs_ref <- easyVerification::veriApply(verifun = 'EnsRoca', fcst = ref, obs = obs, 
                                            tdim = which(names(dim(ref))==time_dim), 
                                            ensdim = which(names(dim(ref))==member_dim), 
                                            prob = prob_thresholds, 
                                            na.rm = na.rm, ncpus = ncores)
    for (cat in paste0('cat',1:n_cats)){
      rocss[[cat]] <- (rocs_exp[[cat]] - rocs_ref[[cat]]) / (1 - rocs_ref[[cat]])
    }
  }
  
  return(rocss)
}
