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

rm(list = ls())
gc()
options(scipen = 999)

# Cargue de las series de tiempo mensuales completadas mediante imputación con IDW
rainfall_data <- read_csv("D:/guvelez/Personales/Otros/Scripts/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 <- t(rainfall_data)

stations <- read_xlsx("D:/guvelez/Personales/Otros/Scripts/Coordenadas_1.xlsx")
clusters <- read_xlsx("D:/guvelez/Personales/Otros/Scripts/Estaciones_Cluster_D_M.xlsx")
names(stations)[1] <- "station_id"
stations <- merge(stations, clusters, by = "station_id")

# Dataframe con los datos de precipitación
time_series_df <- data.frame(
  Month = rep(1:132, times = 56),              # Repite los meses por cada estación
  Rainfall = as.vector(rainfall_data),         # "Aplana" la matriz de datos 
  Station = factor(rep(stations$station_id, each = 132)),      # IDs de las estaciones
  Cluster = factor(rep(stations$CLR_D, each = 132))  # Asignación de cluster
)


# Cálculo de la serie de tiempo promedio para cada cluster
avg_time_series <- aggregate(Rainfall ~ Month + Cluster, data = time_series_df, FUN = mean)

# Gráfica de la serie de tiempo promedio para cada cluster
ggplot(avg_time_series, aes(x = Month, y = Rainfall, color = Cluster, group = Cluster)) +
  geom_line(linewidth = 1.2) +
  labs(title = "Average Time Series of Rainfall by Cluster", x = "Month", y = "Average Rainfall (mm)") +
  theme_minimal()

# Exportar las series de tiempo promedio para cada cluster
avg_rainfall_series_wide <- avg_time_series %>%
  pivot_wider(names_from = Cluster, values_from = Rainfall)

avg_rainfall_series_wide$FECHALECTURA <- FECHALECTURA
avg_rainfall_series_wide$Month <- NULL
names(avg_rainfall_series_wide) <- c("PRECIPITACION_CL1", "PRECIPITACION_CL2", "FECHALECTURA")

avg_rainfall_series_wide <- avg_rainfall_series_wide %>%
  select(FECHALECTURA, everything())

for(i in 1:2){
  serie <- avg_rainfall_series_wide[,c(1,i+1)]
  ruta <- paste0("D:/guvelez/Personales/Otros/Scripts/DATOS_PROMEDIO_MENSUALES_CLUSTERS/CLUSTER_", i, ".xlsx")
  write_xlsx(serie, ruta)
}
