# ============================================
# ==== 
# ==== Compute cluster of modes
# ====
# ============================================
# ==== Libraries
library(ncdf4)
library(s2dverification)
library(reshape2)
library(ggplot2)
library(NbClust)
# ==== Sources
source("R/SelBox.R")
source("R/WeatherRegime.R")
source("R/Cluster.R")
source("R/Trend.R")

# ==== Data
args     <- commandArgs(trailingOnly = TRUE)
filepath <- args[1]
seas     <- args[2]
exps     <- args[3]

file <- nc_open(filepath)
sic  <- ncvar_get(file, paste0("siconc_",exps))
lon  <- ncvar_get(file, "lon")
lat  <- ncvar_get(file, "lat")
time <- ncvar_get(file, "time_counter")

# ==== Get data array into s2dverification format
sic  <- InsertDim(sic[,,1:36], 1, 1)

# ==== For weather regimes function, the array has to have dimensions: names(dim(sic)) <- c("sdate", "ftime", "lat", "lon")
sic  <- aperm(sic, c(1, 4, 3, 2))
names(dim(sic)) <- c("sdate", "ftime", "lat", "lon")

# ==== Select Arctic region
fake_lon <- 1 : 360

arctic   <- SelBox(sic, region = c(1, 360, 40, 90), lon = fake_lon, lat = lat, londim = 4, latdim = 3)  # (lon_min, lon_max, lat_min, lat_max) 

# ==== Calculate anomalies
arctic_ano  <- arctic$data - InsertDim(Mean1Dim(arctic$data, posdim = 2), 2, 36)

# ==== Modes <- WeatherRegime(sic_djf_detrend, lon = lon, lat = arctic$lat, ncenter = 3)
nlon = 360
nlat = 50
anom = array(dim=c(nlon,nlat,36))

modes <- WeatherRegime(arctic_ano, lon = lon, lat = arctic$lat, ncenter = 3)

dist1 = array(dim=c(nlon,nlat,36))
dist2 = array(dim=c(nlon,nlat,36))
dist3 = array(dim=c(nlon,nlat,36))
rmse  = array(dim=c(3,36))

for (h in 1:36){
     dist1[,,h] = sqrt(modes$field$composite[,,1] - arctic_ano[,h,,])*(modes$field$composite[,,1] - arctic_ano[,h,,])
     dist2[,,h] = sqrt(modes$field$composite[,,2] - arctic_ano[,h,,])*(modes$field$composite[,,2] - arctic_ano[,h,,]) 
     dist3[,,h] = sqrt(modes$field$composite[,,3] - arctic_ano[,h,,])*(modes$field$composite[,,3] - arctic_ano[,h,,])
}

rmse[1,] = Mean1Dim(Mean1Dim(dist1,1,),1)
rmse[2,] = Mean1Dim(Mean1Dim(dist2,1,),1)
rmse[3,] = Mean1Dim(Mean1Dim(dist3,1,),1)


# ==== Sort modes by frequency in descending order
ordering = seq(1,3,1)
ordering[1] = modes$frequency[[1]]
ordering[2] = modes$frequency[[2]]
ordering[3] = modes$frequency[[3]]

# ==== Save: Clusters' maps
xvals <- seq( 0, 359, 1)
yvals <- seq(41,  90, 1)
tvals <- seq(1, 3, 1)
nx    <- length(xvals)
ny    <- length(yvals)
nt    <- length(tvals)
lon1  <- ncdim_def("longitude", "degrees_east",  xvals)
lat2  <- ncdim_def("latitude",  "degrees_north", yvals)
time  <- ncdim_def("dummy_time","modes", tvals, unlim=TRUE) # Save modes on the time axis
mv    <- -999 # missing value to use

omodes    <- modes$field$composite[, , order(ordering,decreasing=TRUE)]
data      <- aperm(omodes, c(2,1,3))

filename   <- paste0("sic-cluster-maps-",exps,".",seas,".nc")
varname    <- "sicluster" 
var_modes  <- ncvar_def(varname, "Non-dimensional", list(lon1, lat2, time), longname="Clustes", mv) 
ncnew      <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, data, start=c(1,1,1), count=c(nx,ny,nt))
nc_close(ncnew)

# ==== Save: Clusters' p values
opval    <- modes$field$pvalue[, , order(ordering,decreasing=TRUE)]
pval     <- aperm(opval, c(2,1,3))

filename <- paste0("sic-cluster-pvalue-",exps,".",seas,".nc")
varname  <- "pval"
var_modes <- ncvar_def(varname, "Non-dimensional", list(lon1, lat2, time), longname="Cluster Pvalues", mv)
ncnew     <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, pval, start=c(1,1,1), count=c(nx,ny,nt))
nc_close(ncnew)

# ==== Save: Clusters' frequency
freqordered = ordering[order(ordering,decreasing=TRUE)]

filename   <- paste0("sic-cluster-freqs-",exps,".",seas,".nc")
varname    <- "frequency"
var_modes  <- ncvar_def(varname, "Variance explained", list(time), longname="Clusters frequency", mv)
ncnew      <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, freqordered, start=c(1), count=c(nt))
nc_close(ncnew)

# ==== Save: Clusters' persistence
persisordered = modes$persistence[order(ordering,decreasing=TRUE)]

filename   <- paste0("sic-cluster-persi-",exps,".",seas,".nc")
varname    <- "persistence"
var_modes  <- ncvar_def(varname, "Years", list(time), longname="Clusters persistence", mv)
ncnew      <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, persisordered, start=c(1), count=c(nt))
nc_close(ncnew)

# ==== Save: Clusters' weights
occurrece = match(modes$cluster,order(ordering,decreasing=TRUE))

tvals2 <- seq(1979,2014,1)
nt2    <- length(tvals2)
time2  <- ncdim_def("time","years", tvals2, unlim=TRUE) # Saving on a time axis

filename   <- paste0("sic-cluster-occur-",exps,".",seas,".nc")
varname    <- "occurrence"
var_modes  <- ncvar_def(varname, "occurrence", list(time2), longname="Clusters occurrence", mv)
ncnew      <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, occurrece, start=c(1), count=c(nt2))
nc_close(ncnew)

# ==== Save: Clusters' RMSE
matches     <- match(modes$cluster, order(ordering, decreasing = TRUE))
rmseordered <- sapply(1:length(modes$cluster), function (x) rmse[matches[x], x])

filename   <- paste0("sic-cluster-rmse-",exps,".",seas,".nc")
varname    <- "rmse"
var_modes  <- ncvar_def(varname, "rmse", list(time2), longname="Most relevant cluster RMSE", mv)
ncnew      <- nc_create(filename, list(var_modes))
ncvar_put(ncnew, var_modes, rmseordered, start=c(1), count=c(nt2))
nc_close(ncnew)

# ==== Save: Arctic SIC anomalies
filename2 <- paste0("anom-sic-arctic-",exps,".",seas,".nc")
varname2  <- "sic"

var_modes2 <- ncvar_def(varname2, "percentage of area", list(lon1, lat2, time2), longname="sic anomalies", mv)
ncnew2     <- nc_create(filename2, list(var_modes2))
data2      <- aperm(drop(arctic_ano), c(3,2,1))

ncvar_put(ncnew2, var_modes2, data2, start=c(1,1,1), count=c(nx,ny,nt2))
nc_close(ncnew2)
