library(factoextra)
library(dtwclust)
library(cluster)
library(ggplot2)
library(dplyr)
library(purrr)
library(readr)
library(readxl)
library(tibble)
library(writexl)
library(tidyverse)
library(tidyr)
library(readr)
library(readxl)

options(scipen = 999)

setwd("D:/gagarciav/Otros Requerimientos/DNP/Maestría Johanna/")

# Cargue de las series de tiempo mensuales completadas mediante imputación con IDW
rainfall_data <- read_csv("series_completas.csv", 
                          col_types = cols(...1 = col_skip()))
FECHALECTURA <- rainfall_data$FECHALECTURA

# Transposición de la matriz de datos
rainfall_data$FECHALECTURA <- NULL
rainfall_data <- as.data.frame(t(rainfall_data))

# Cargue de estaciones y conglomerados (clústeres)
stations <- read_xlsx("Coordenadas_1.xlsx")
clusters <- read_xlsx("Estaciones_Cluster_D_M.xlsx")
names(stations)[1] <- "station_id"
stations <- merge(stations, clusters, by = "station_id")

# Vínculo de datos de precipitación y conglomerados
rainfall_data <- rownames_to_column(rainfall_data, var = "station_id")
rainfall_data <- merge(rainfall_data, stations[,c(1,7)], by = "station_id")

# Separación de los datos por conglomerado
cluster1_data <- rainfall_data %>% 
  filter(CLR_D == 1) %>% 
  column_to_rownames(.,var = "station_id") %>% 
  select(-CLR_D)

cluster2_data <- rainfall_data %>% 
  filter(CLR_D == 2) %>% 
  column_to_rownames(.,var = "station_id") %>% 
  select(-CLR_D)

#---- 1. MEDOIDES (PAM) ----

# Paso 1: Cálculo de la matriz de distancias usando dtw
dtw_dist_cluster1 <- proxy::dist(cluster1_data, method = "DTW")
dtw_dist_cluster2 <- proxy::dist(cluster2_data, method = "DTW")

# Paso 2: Aplicar el algoritmo PAM para encontrar el medoide
pam_cluster1 <- pam(dtw_dist_cluster1, k = 1)
pam_cluster2 <- pam(dtw_dist_cluster2, k = 1)

# Paso 3: extraer la serie correspondiente al medoide
medoid_series_cluster1 <- as.data.frame(t(cluster1_data[pam_cluster1$medoids, ]))
medoid_series_cluster2 <- as.data.frame(t(cluster2_data[pam_cluster2$medoids, ]))

medoid_series_cluster1 <- cbind(FECHALECTURA, medoid_series_cluster1)
medoid_series_cluster2 <- cbind(FECHALECTURA, medoid_series_cluster2)

write_xlsx(medoid_series_cluster1, "cluster1_medoide.xlsx")
write_xlsx(medoid_series_cluster2, "cluster2_medoide.xlsx")

#---- 2. CLUSTER DBA ----

dba_cluster1 <- cbind(FECHALECTURA, as.data.frame(DBA(cluster1_data)))
names(dba_cluster1)[2] <- "Precipitacion"
dba_cluster2 <- cbind(FECHALECTURA, as.data.frame(DBA(cluster2_data)))
names(dba_cluster2)[2] <- "Precipitacion"

write_xlsx(dba_cluster1, "cluster1_DBA.xlsx")
write_xlsx(dba_cluster2, "cluster2_DBA.xlsx")


#---- 3. SERIE MÁS CERCANA A LA SERIE PROMEDIO ----

# Paso 1: calcular la serie promedio
mean_series_cluster1 <- colMeans(cluster1_data)
mean_series_cluster2 <- colMeans(cluster2_data)

# Paso 2: Calcular la distancia DTW entre la serie promedio y las series del clúster
dtw_to_mean_cluster1 <- sapply(1:nrow(cluster1_data), function(i) {
  dtw_basic(as.numeric(cluster1_data[i, ]), mean_series_cluster1)
})
dtw_to_mean_cluster2 <- sapply(1:nrow(cluster2_data), function(i) {
  dtw_basic(as.numeric(cluster2_data[i, ]), mean_series_cluster2)
})

# Paso 3: encontrar la serie más cercana a la serie promedio (distancia mínima)
closest_to_mean_cluster1 <- cluster1_data[which.min(dtw_to_mean_cluster1), ]
closest_to_mean_cluster2 <- cluster2_data[which.min(dtw_to_mean_cluster2), ]
