





# Issue https://earth.bsc.es/gitlab/es/s2dverification/issues/227



library(s2dverification)


#t <- array(rnorm(76),c(1,3,4,3,2,2)) # define array as clim expects: nexp,nmemb,nsdates,nltime,nlon,nlat                                                                                   
t <- array(1:(9*4*4), c(1,3,4,3,2,2)) #In fact it expects: nlat,nlon                                                                                   
c3 <- Clim(t,t,memb=TRUE)$clim_exp # Clim for each member                                     
dim(c3)
dim(Clim(t,t,memb=FALSE)$clim_exp) # dimensions if memb=FALSE                              
c1 <- InsertDim(c3[,1,,,],1,1) # clim as if memb=FALSE but identical to member 1              
dim(c1)
identical(c1[,,,],c3[,1,,,]) # results in TRUE
a3 <- Ano(t,c3)  # ano for each member individually                                           
a1 <- Ano(t,c1)  # ano for first member                                                       
identical(a1[,1,,,,],a3[,1,,,,])  ## RESULTS IN FALSE

#T <- array(rnorm(240),c(1,3,4,5,2,2)) # define array as clim expects: nexp,nmemb,nsdates,nltime,nlon,nlat                                                                                  
T <- array(1 : (15 * 16), c(1,3,4,5,2,2)) # Order lat, lon                                                                                 
C3 <- Clim(T,T,memb=TRUE)$clim_exp # Clim for each member                                     
dim(C3)
dim(Clim(T,T,memb=FALSE)$clim_exp) # dimensions if memb=FALSE                              
C1 <- InsertDim(C3[,1,,,],1,1) # clim as if memb=FALSE but identical to member 1              
dim(C1)
identical(C1[,,,],C3[,1,,,]) # results in TRUE
A3 <- Ano(T,C3)  # ano for each member individually                                           
A1 <- Ano(T,C1)  # ano for first member                                                       
identical(A1[,1,,,,],A3[,1,,,,]) ## RESULTS IN TRUE


var <- T
clim <- C3
dim(clim)
names(dim(clim)) <- c('exp', 'memb', '')
Ano <- function(var, clim) {
  #
  #  Duplicate clim dimensions to heve same dimensions as var
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #
  dimvar <- dim(var)
  
  if (length(dim(clim)) <= 2) {
    clim <- InsertDim(clim, 2, dimvar[2])
  }
  if ((length(dimvar) > length(dim(clim))) & (names(dim(clim)[2]) != names(dimvar[2]))) {
    clim <- InsertDim(clim, 2, dimvar[2])
  }
  if ((length(dimvar) > length(dim(clim))) & (names(dim(clim)[3]) != names(dimvar[3]))) {
    clim <- InsertDim(clim, 3, dimvar[3])
  }
  if ((length(dimvar) > length(dim(clim))) & (names(dim(clim)[4]) != names(dimvar[4]))) {
    clim <- InsertDim(clim, 4, dimvar[4])
  }
  
  #
  #  Raw anomalies
  # ~~~~~~~~~~~~~~~
  #
  ano <- var - clim
  
  #
  #  Outputs
  # ~~~~~~~~~
  #
  ano
}

