rm(list=ls())
source("modules/Loading/Loading.R")
source("modules/Units/Units.R")
source("modules/Anomalies/Anomalies.R")

recipe_file <- "recipe_bias.yml"
recipe <- prepare_outputs(recipe_file)

regions  <- list(NH = c(lon.min = 0,  lon.max = 360, lat.min = 30, lat.max = 90),
                 Tr = c(lon.min = 0,  lon.max = 360, lat.min = -30, lat.max = 30),
                 SH = c(lon.min = 0,  lon.max = 360, lat.min = -90, lat.max = -30))
biases <- list()
pvals <- list()

source("WeightedCells.R")

for (i in 1:12) {
  recipe$Analysis$Time$sdate <- paste0(sprintf("%02d", i), '01')
  data <- Loading(recipe)
  data <- Units(recipe = recipe, data = data)
  
  bias <- Bias(data$hcst$data, data$obs$data, time_dim = 'syear', memb_dim = 'ensemble')
  EM <- MeanDims(data$hcst$data, 'ensemble')

  em_w <- WeightedCells(data = EM, 
                        lat = as.vector(data$hcst$coords$lat), 
                        lon = as.vector(data$hcst$coords$lon),
                        lat_dim = 'latitude', lon_dim = 'longitude',
                        method = 'other')
  weights <- em_w$weights
  em_w <- em_w$data
  obs_w <- WeightedCells(data = data$obs$data,
                        lat = as.vector(data$obs$coords$lat),
                        lon = as.vector(data$hcst$coords$lon), 
                        lat_dim = 'latitude', lon_dim = 'longitude',
                        method = 'other')$data

  bias_w <- Bias(drop(em_w), drop(obs_w), time_dim = 'syear', memb_dim = NULL)


  for (reg in 1:3) {
    # case 1:
    bias_1 <- WeightedMean(bias,
                           lat = as.vector(data$hcst$coords$lat), 
                           lon = as.vector(data$hcst$coords$lon),
                           londim = 'longitude', latdim = 'latitude',
                           region = regions[[reg]])
    # case 2
    wt <- SelBox(weights, lat = as.vector(data$hcst$coords$lat),
                         lon = as.vector(data$hcst$coords$lon),
                         londim = 'longitude', latdim = 'latitude',
                         region = regions[[reg]])$data
    select <- SelBox(bias_w, lat = as.vector(data$hcst$coords$lat),         
                         lon = as.vector(data$hcst$coords$lon),
                         londim = 'longitude', latdim = 'latitude',
                         region = regions[[reg]])$data

    bias_2 <- Apply(list(select),  target_dims = c('latitude', 'longitude'),
                       function(x, y) {sum(as.vector(x))/sum(as.vector(y))}, y = wt)$output1

    obs_reg <- SelBox(obs_w, 
                      lat = as.vector(data$obs$coords$lat), 
                      lon = as.vector(data$obs$coords$lon),
                      londim = 'longitude', latdim = 'latitude',
                      region = regions[[reg]])
    em_reg <-  SelBox(em_w,
                      lat = as.vector(data$hcst$coords$lat), 
                      lon = as.vector(data$hcst$coords$lon),
                      londim = 'longitude', latdim = 'latitude',
                      region = regions[[reg]])
    test <- Apply(list(obs_reg$data, em_reg$data),
                  target_dims = c('syear', 'latitude', 'longitude'),
                  function(x,y) {res <- t.test(x, y)
                                return(list(welch.t = res$p.value, means = res$estimate))})

    # case 3
    obs_reg_w <- WeightedMean(data$obs$data,
                      lat = as.vector(data$obs$coords$lat),
                      lon = as.vector(data$obs$coords$lon),
                      londim = 'longitude', latdim = 'latitude',
                      region = regions[[reg]])
    em_reg_w <- WeightedMean(EM,
                      lat = as.vector(data$hcst$coords$lat),
                      lon = as.vector(data$hcst$coords$lon),
                      londim = 'longitude', latdim = 'latitude',
                      region = regions[[reg]])
    test3 <- Apply(list(obs_reg_w, em_reg_w), target_dims = 'syear',
                 function(x,y) {res <- t.test(x, y)
                                return(list(welch.t = res$p.value, means = res$estimate))})
    bias_3 <- apply(test3$means, 6, function(x){x[2]-x[1]})
    bias_list <- list(list(bias_1 = as.vector(bias_1),
                           bias_2 = as.vector(bias_2),
                           bias_3 = as.vector(bias_3)))
    names(bias_list) <- paste0(names(regions)[reg], i)
    biases <- append(biases, bias_list)
    pval_list <- list(list(method1 = as.vector(test$welch.t),
                           method2 = as.vector(test3$welch.t)))
    names(pval_list) <- paste0(names(regions)[reg], i)
    pvals <- append(pvals, pval_list)
  } # end reg

} # end sdate


saveRDS(list(biases = biases, pvals = pvals), file = 'bias_results.RDS')


