#  check kmeans
library(abind)
x <-  1:50
y <- 10 * x^2 - x 
z <- exp(x)
a <-  c(1: (50 * 10), 2999:2500, y, y + 50, y + 10, y - 10, 
        y - 20, y * 2, y / 2, y * 7, y / 7, y + 1, z, z + 1,
        z + 5, z - 5, z * 2, z * 7, z / 7, z + 50, z - 10, z * 2)     

dim(a) <- c(d1 = 40, d2 = 50)
run1  <- kmeans(a, centers = 4)  
run2  <- kmeans(a, centers = 4)
run3  <- kmeans(a, centers = 4)
run <- abind(run1$centers, run2$centers, run3$centers, along = 3)

matplot( 1:50, run[1,,], type ="l")

# ----  Edu code:/esarchive/scratch/emchamarro/appl/sit-cat/clusters/scripts/clusters-all-seasons-undetrend-sims.R
setwd("/esarchive/scratch/emchamarro/appl/sit-cat/clusters/scripts/")
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
sic <- 
# ==== 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)





