## TO BE RUN IN THE multiCDM FOLDER
#setwd("s2dverification/multiCDM")

library(s2dverification)
source("../R/PlotTimeSeries.R")
sdates= paste0(1995:2005, '1101')

#data <- Load(var = "tas", exp = c('i00k'), obs = 'erainterim',
#             sdates = sdates, leadtimemax = 18, 
#             lonmin = -10, lonmax = 50, latmin = 20, latmax = 70,
#             output = 'areave', method = 'conservative')
data <- readRDS('tas_i00k_erainterim_europe.Rds')

enddates= paste0(1996:2006, '1101')

#Define the basic multiCDM class
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Create forecast and observation objects belonging to the multiCDM class
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ArrayToMultiCDM <- function(var) {
  x <- var
  class(x) <- "multiCDM"
  attr(x, "Dataset") <- list(Dataset = NULL, Realization = NULL, 
                             Variable = list(Variable = NULL, hasCfname = NULL, withUnits = NULL),
                             TemporalPeriod = list(hasStartyear = NULL,
                                                   hasEndyear = NULL,
                                                   hasMonth = NULL),
                             TemporalInstant = list(hasInitDate = NULL),
                             SpatialExtent = list(lon = NULL, lat = NULL))
  
  attr(x, "Step") <- list(class = NULL, type = NULL, attribute = NULL)
  attr(x, "dimensionNames") <- names(dim(x))
  attr(x, "Command") <- list(generatedbyCommand = NULL, fromPackage = NULL,
                             packageVersion = NULL, withForecast = NULL, 
                             withReference = NULL)
  attr(x, "hasNext") <- NULL
  invisible(x)
}

forecast <-ArrayToMultiCDM(data$mod)
attr(forecast, "Dataset") <- list(Dataset = attributes(data$Datasets$exp)$names, Realization = NULL, 
                                  Variable = list(Variable = attr(data$Variable, "longname"), hasCfname = data$Variable$varName, withUnits = attr(data$Variable, "units")),
                                  TemporalPeriod = list(hasStartyear = sdates,
                                                        hasMonth = substr(sdates[1], 5, 6)),
                                  TemporalInstant = list(hasInitDate = sdates[1]),
                                  SpatialExtent = list(lon = as.vector(data$lon), lat = as.vector(data$lat)))

reference <- ArrayToMultiCDM(data$obs)

attr(reference, "Dataset") <- list(Dataset = attributes(data$Datasets$obs)$names, Realization = NULL, 
                                   Variable = list(Variable = attr(data$Variable, "longname"), hasCfname = data$Variable$varName, withUnits = attr(data$Variable, "units")),
                                   TemporalPeriod = list(hasStartyear = sdates,
                                                         hasMonth = substr(sdates[1], 5, 6)),
                                   TemporalInstant = list(hasInitDate = sdates[1]),
                                   SpatialExtent = list(lon = as.vector(data$lon), lat = as.vector(data$lat)))


#Calculate the anomalies
#~~~~~~~~~~~~~~~~~

clim <- Clim(data$mod, data$obs)


ano_exp <- Ano(data$mod, clim$clim_exp) 
ano_obs <- Ano(data$obs, clim$clim_obs) 
runmean_months <- 6
dim_to_smooth <- 4
smooth_ano_exp <- Smoothing(ano_exp, runmean_months, dim_to_smooth) 
smooth_ano_obs <- Smoothing(ano_obs, runmean_months, dim_to_smooth) 

forecast_anomaly <- smooth_ano_exp
class(forecast_anomaly) <- "multiCDM"
attr(forecast_anomaly, "Step") <- list(class = "Transform", type = "Smoothed Anomaly", attribute = NULL)
attr(forecast_anomaly, "Dataset") <- attr(forecast, "Dataset")
attr(forecast_anomaly, "dimensionNames") <- c("dataset", "member", "sdate", "ftime")
attr(forecast_anomaly, "Command") <- list(generatedbyCommand = "Ano", fromPackage = "s2dverification",
                                          packageVersion = packageVersion("s2dverification"),
                                          withForecast = attr(forecast, "Dataset")$Dataset, 
                                          withReference = attr(reference, "Dataset")$Dataset
)
attr(forecast_anomaly, "Dataset")$Variable$hasVariable <- NULL


attr(forecast_anomaly, "hasNext")  <- "Correlation with reference"         

reference_anomaly <- smooth_ano_obs
class(reference_anomaly) <- "multiCDM"
attr(reference_anomaly, "Step") <- list(class = "Transform", type = "Anomaly", attribute = NULL)

attr(reference_anomaly, "dimensionNames") <- c("dataset", "member", "sdate", "ftime")
attr(reference_anomaly, "Dataset") <- attr(reference, "Dataset")
attr(reference_anomaly, "Command") <- list(generatedbyCommand = "Ano", fromPackage = "s2dverification",
                                           packageVersion = packageVersion("s2dverification"),
                                           withForecast = NA, 
                                           withReference = attr(reference, "Dataset")$Dataset 
)

attr(reference_anomaly, "hasNext")  <- "Correlation with forecast"                    

PlotTimeSeries(forecast_anomaly, curves_along = NA)

# Create an object containing the Verification measure "correlation"
# and plot it
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

verification_object <- Corr(Mean1Dim(forecast_anomaly, 2) , Mean1Dim(reference_anomaly, 2))
names(dim(verification_object)) <- c("model", "member", "values", "ftime")
class(verification_object) = "multiCDM"
attr(verification_object, "Dataset") <- attr(forecast, "Dataset")
attr(verification_object, "Command") = list(generatedbyCommand = "Corr", fromPackage = gsub("package:", "",find("Corr")),
                                   packageVersion = packageVersion(gsub("package:", "",find("Corr"))),
                                   withForecast = attr(forecast_anomaly, "Dataset")$Dataset, 
                                   withReference = attr(reference_anomaly, "Dataset")$Dataset)
attr(verification_object, "Step") <- list(class = "Verification", type = "Correlation", attribute = "Association")
attr(verification_object, "Dataset")$Variable = list(Variable = attr(forecast, "Dataset")$Variable$Variable, hasCfname = "tos", withUnits = NULL, hasVariable = NULL)

PlotTimeSeries(verification_object)
