# ----------------------------
# 1. CARGA DE PAQUETES
# ----------------------------







if (!require(readxl)) install.packages("readxl")
## Cargando paquete requerido: readxl
if (!require(dplyr)) install.packages("dplyr")
## Cargando paquete requerido: dplyr
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
if (!require(ggplot2)) install.packages("ggplot2")
## Cargando paquete requerido: ggplot2
if (!require(psych)) install.packages("psych")
## Cargando paquete requerido: psych
## 
## Adjuntando el paquete: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
if (!require(summarytools)) install.packages("summarytools")
## Cargando paquete requerido: summarytools
if (!require(lubridate)) install.packages("lubridate")
## Cargando paquete requerido: lubridate
## 
## Adjuntando el paquete: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
if (!require(lmtest)) install.packages("lmtest")
## Cargando paquete requerido: lmtest
## Cargando paquete requerido: zoo
## 
## Adjuntando el paquete: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
if (!require(knitr)) install.packages("knitr")
## Cargando paquete requerido: knitr
if (!require(car)) install.packages("car")
## Cargando paquete requerido: car
## Cargando paquete requerido: carData
## 
## Adjuntando el paquete: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
## The following object is masked from 'package:dplyr':
## 
##     recode
library(readxl)
library(dplyr)
library(ggplot2)
library(psych)
library(summarytools)
library(lubridate)
library(lmtest)
library(knitr)
library(car)

# ----------------------------
# 2. CARGA Y LIMPIEZA DE DATOS
# ----------------------------

# Leer archivo Excel
ruta <- "Copia de ITUANGO Y RIOS(1).xlsx"
datos <- read_excel(ruta, sheet = "ITUANGO")

# Renombrar columnas según necesidad (ajusta si tus nombres difieren)
names(datos)[names(datos) == "PROMEDIO DE PRECIPITACION"] <- "Precipitacion"
names(datos)[names(datos) == "Aportes Energía kWh"] <- "Aportes_energia_kWh"
names(datos)[names(datos) == "TEMPERATURA A 2 METROS"] <- "Temperatura"
names(datos)[names(datos) == "Aportes Caudal m3/s"] <- "Caudal"

datos$Precipitacion <- as.numeric(datos$Precipitacion)
datos$Temperatura <- as.numeric(datos$Temperatura)
datos$Aportes_energia_kWh <- as.numeric(datos$Aportes_energia_kWh)

# Convertir columnas a formato adecuado
datos <- datos %>%
  mutate(
    AÑO = as.numeric(AÑO),
    MES = as.numeric(MES),
    MES = sprintf("%02d", MES),
    Fecha = as.Date(paste(AÑO, MES, "01", sep = "-"), format = "%Y-%m-%d")
  )

# Filtrar años de interés
datos <- datos %>%
  filter(year(Fecha) >= 2015 & year(Fecha) <= 2023)

# Convertir Mes a factor ordenado
datos$Mes_nombre <- month.name[as.numeric(datos$MES)]
datos$Mes_nombre <- factor(datos$Mes_nombre, levels = month.name)

# ----------------------------
# 3. ANÁLISIS DESCRIPTIVO
# ----------------------------
# Estadísticas descriptivas
descriptivas <- describe(datos[, c("Precipitacion", "Temperatura", 
                                   "Aportes_energia_kWh")], skew = FALSE, ranges = FALSE)
print(descriptivas)
##                     vars   n         mean          sd         se
## Precipitacion          1 108         4.99        2.62       0.25
## Temperatura            2 108        18.09        0.53       0.05
## Aportes_energia_kWh    3 108 105508855.56 79264085.46 7627190.18
# Resumen más detallado
dfSummary(datos[, c("Precipitacion", "Temperatura", "Aportes_energia_kWh")])
## Data Frame Summary  
## datos  
## Dimensions: 108 x 3  
## Duplicates: 0  
## 
## ------------------------------------------------------------------------------------------------------------------------------
## No   Variable              Stats / Values                     Freqs (% of Valid)    Graph                 Valid      Missing  
## ---- --------------------- ---------------------------------- --------------------- --------------------- ---------- ---------
## 1    Precipitacion         Mean (sd) : 5 (2.6)                99 distinct values      : :                 108        0        
##      [numeric]             min < med < max:                                           : : .               (100.0%)   (0.0%)   
##                            0.5 < 4.8 < 12.1                                         . : : :                                   
##                            IQR (CV) : 3.9 (0.5)                                     : : : : :                                 
##                                                                                     : : : : : .                               
## 
## 2    Temperatura           Mean (sd) : 18.1 (0.5)             87 distinct values        . :               108        0        
##      [numeric]             min < med < max:                                             : :               (100.0%)   (0.0%)   
##                            16.9 < 18 < 19.5                                           . : : .                                 
##                            IQR (CV) : 0.7 (0)                                         : : : :                                 
##                                                                                       : : : : .                               
## 
## 3    Aportes_energia_kWh   Mean (sd) : 105508856 (79264086)   108 distinct values   : .                   108        0        
##      [numeric]             min < med < max:                                         : :                   (100.0%)   (0.0%)   
##                            14622300 < 83778750 < 462823100                          : : . .                                   
##                            IQR (CV) : 79749375 (0.8)                                : : : :                                   
##                                                                                     : : : : .         .                       
## ------------------------------------------------------------------------------------------------------------------------------
# Histograma de precipitación
ggplot(datos, aes(x = Precipitacion)) +
  geom_histogram(bins = 20, fill = "skyblue", color = "black") +
  labs(title = "Distribución del Promedio de Precipitación",
       x = "Precipitación (mm)", y = "Frecuencia") +
  theme_minimal()

# Serie temporal de precipitación
ggplot(datos, aes(x = Fecha, y = Precipitacion)) +
  geom_line(color = "blue") +
  labs(title = "Serie Temporal de Precipitación (2015–2023)",
       x = "Fecha", y = "Precipitación (mm)") +
  theme_minimal()

# Serie temporal de generación de energía
ggplot(datos, aes(x = Fecha, y = Aportes_energia_kWh)) +
  geom_line(color = "darkgreen") +
  labs(title = "Serie Temporal de Generación de Energía (2015–2023)",
       x = "Fecha", y = "Generación (kWh)") +
  theme_minimal()

#serie temporal del caudal 
ggplot(datos, aes(x = Fecha, y = Caudal)) +
  geom_line(color = "purple") +
  labs(title = "Serie Temporal del Caudal (2015–2023)",
       x = "Fecha", y = "Caudal (m³/s)") +
  theme_minimal()

# ----------------------------
# 4. ANÁLISIS CORRELACIONAL
# ----------------------------

# Matriz de correlación de variables principales
matriz_cor <- cor(datos[, c("Precipitacion", "Temperatura", "Aportes_energia_kWh")], 
                  use = "complete.obs")
print(matriz_cor)
##                     Precipitacion Temperatura Aportes_energia_kWh
## Precipitacion          1.00000000  -0.3250073          0.07027517
## Temperatura           -0.32500734   1.0000000         -0.26330621
## Aportes_energia_kWh    0.07027517  -0.2633062          1.00000000
# ----------------------------
# 5. MODELADO ESTADÍSTICO
# ----------------------------

# Modelos de regresión simple
modelo_precip <- lm(Aportes_energia_kWh ~ Precipitacion, data = datos)
modelo_temp   <- lm(Aportes_energia_kWh ~ Temperatura, data = datos)

# Modelo de regresión múltiple
modelo_multiple <- lm(Aportes_energia_kWh ~ Precipitacion + Temperatura, data = datos)

# Resúmenes
summary(modelo_precip)
## 
## Call:
## lm(formula = Aportes_energia_kWh ~ Precipitacion, data = datos)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -89366399 -50100606 -21099286  30469251 348859151 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   94885487   16521239   5.743 8.96e-08 ***
## Precipitacion  2126919    2932385   0.725     0.47    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 79440000 on 106 degrees of freedom
## Multiple R-squared:  0.004939,   Adjusted R-squared:  -0.004449 
## F-statistic: 0.5261 on 1 and 106 DF,  p-value: 0.4699
summary(modelo_temp)
## 
## Call:
## lm(formula = Aportes_energia_kWh ~ Temperatura, data = datos)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -96032543 -49167931 -14667746  24776417 341419745 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)   
## (Intercept) 823849765  255738387   3.221  0.00169 **
## Temperatura -39708672   14130878  -2.810  0.00590 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 76830000 on 106 degrees of freedom
## Multiple R-squared:  0.06933,    Adjusted R-squared:  0.06055 
## F-statistic: 7.896 on 1 and 106 DF,  p-value: 0.0059
summary(modelo_multiple)
## 
## Call:
## lm(formula = Aportes_energia_kWh ~ Precipitacion + Temperatura, 
##     data = datos)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -95248072 -49516459 -14111217  25817298 343142480 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   841605585  276907877   3.039  0.00299 **
## Precipitacion   -517797    3012538  -0.172  0.86386   
## Temperatura   -40547220   15010933  -2.701  0.00806 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 77180000 on 105 degrees of freedom
## Multiple R-squared:  0.06959,    Adjusted R-squared:  0.05187 
## F-statistic: 3.927 on 2 and 105 DF,  p-value: 0.02267
# ----------------------------
# 6. GRÁFICOS DE REGRESIÓN
# ----------------------------

# Energía vs Precipitación
ggplot(datos, aes(x = Precipitacion, y = Aportes_energia_kWh)) +
  geom_point(color = "blue") +
  geom_smooth(method = "lm", color = "red") +
  labs(title = "Generación de Energía vs Precipitación",
       x = "Precipitación (mm)", y = "Generación de Energía (kWh)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# Energía vs Temperatura
ggplot(datos, aes(x = Temperatura, y = Aportes_energia_kWh)) +
  geom_point(color = "green") +
  geom_smooth(method = "lm", color = "orange") +
  labs(title = "Generación de Energía vs Temperatura",
       x = "Temperatura (°C)", y = "Generación de Energía (kWh)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# ----------------------------
# 7. VALIDACIÓN DE SUPUESTOS DEL MODELO
# ----------------------------

par(mfrow = c(1, 2))
plot(modelo_multiple$fitted.values, modelo_multiple$residuals,
     main = "Residuos vs Valores Ajustados",
     xlab = "Valores Ajustados", ylab = "Residuos", pch = 19, col = "purple")
abline(h = 0, col = "black", lty = 2)

qqnorm(modelo_multiple$residuals)
qqline(modelo_multiple$residuals, col = "blue")

# Normalidad de residuos para modelo múltiple
shapiro.test(modelo_multiple$residuals)
## 
##  Shapiro-Wilk normality test
## 
## data:  modelo_multiple$residuals
## W = 0.82265, p-value = 4.607e-10
# Verificar multicolinealidad
car::vif(modelo_multiple)
## Precipitacion   Temperatura 
##      1.118105      1.118105
# ----------------------------
# 8. MODELO LOGÍSTICO (opcional)
# ----------------------------

# Crear variable binaria: generación alta (mayor que la mediana)
umbral <- median(datos$Aportes_energia_kWh, na.rm = TRUE)
datos$Generacion_alta <- ifelse(datos$Aportes_energia_kWh >= umbral, 1, 0)

modelo_logistico <- glm(Generacion_alta ~ Precipitacion + Temperatura, 
                        data = datos, family = "binomial")
summary(modelo_logistico)
## 
## Call:
## glm(formula = Generacion_alta ~ Precipitacion + Temperatura, 
##     family = "binomial", data = datos)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)  
## (Intercept)   14.15879    7.62540   1.857   0.0633 .
## Precipitacion  0.08679    0.08079   1.074   0.2827  
## Temperatura   -0.80683    0.41470  -1.946   0.0517 .
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 149.72  on 107  degrees of freedom
## Residual deviance: 142.48  on 105  degrees of freedom
## AIC: 148.48
## 
## Number of Fisher Scoring iterations: 4
# ----------------------------
# 9. EXPORTAR RESULTADOS (opcional)
# ----------------------------
write.csv(summary(modelo_multiple)$coefficients, "resultados_modelo_multiple.csv")

# ----------------------------
# 10. LIMITACIONES Y REVISIÓN DE DATOS
# ----------------------------
# Valores faltantes
cat("Total de valores faltantes en la base:", sum(is.na(datos)), "\n")
## Total de valores faltantes en la base: 0
##############################################################

# 1. Carga de paquetes
if (!require(readxl)) install.packages("readxl")
if (!require(dplyr)) install.packages("dplyr")
if (!require(ggplot2)) install.packages("ggplot2")
if (!require(effects)) install.packages("effects")
## Cargando paquete requerido: effects
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
library(readxl)
library(dplyr)
library(ggplot2)
library(effects)

# 2. Cargar la base y revisar nombres
datos <- read_excel("Copia de ITUANGO Y RIOS(1).xlsx")
cat("Nombres originales:\n")
## Nombres originales:
print(names(datos))
##  [1] "MES"                                   
##  [2] "AÑO"                                   
##  [3] "PROMEDIO DE PRECIPITACION"             
##  [4] "PROMEDIO DE LA SUMA DE PRECIPITACIONES"
##  [5] "HUMEDAD RELATIVA A 2 METROS"           
##  [6] "TEMPERATURA A 2 METROS"                
##  [7] "TEMPERATURA MAXIMA A 2 METROS"         
##  [8] "TEMPERATURA MINIMA A 2 METROS"         
##  [9] "Region Hidrologica"                    
## [10] "Nombre Río"                            
## [11] "Aportes Energía kWh"                   
## [12] "Aportes Caudal m3/s"                   
## [13] "Aportes Media Histórica Energía kWh"   
## [14] "Aportes Media Histórica Caudal m3/s"   
## [15] "Aportes 95 PSS Energía kWh"            
## [16] "Aportes 95 PSS Caudal m3/s"
# 3. Renombrar columnas claves (ajustar si los nombres cambian)
names(datos)[names(datos) == "Aportes Caudal m3/s"] <- "Caudal"
names(datos)[names(datos) == "PROMEDIO DE PRECIPITACION"] <- "Precipitacion"
names(datos)[names(datos) == "TEMPERATURA A 2 METROS"] <- "Temperatura"
names(datos)[names(datos) == "Aportes Energía kWh"] <- "Aportes_Energia_kWh"

# 4. Convertir a formato válido en R y asegurarse que sean numéricas
names(datos) <- make.names(names(datos))
datos$Caudal <- as.numeric(datos$Caudal)
datos$Precipitacion <- as.numeric(datos$Precipitacion)
datos$Temperatura <- as.numeric(datos$Temperatura)
datos$Aportes_Energia_kWh <- as.numeric(datos$Aportes_Energia_kWh)

# 5. Confirmar cambios de nombres
cat("\nNombres después de make.names:\n")
## 
## Nombres después de make.names:
print(names(datos))
##  [1] "MES"                                   
##  [2] "AÑO"                                   
##  [3] "Precipitacion"                         
##  [4] "PROMEDIO.DE.LA.SUMA.DE.PRECIPITACIONES"
##  [5] "HUMEDAD.RELATIVA.A.2.METROS"           
##  [6] "Temperatura"                           
##  [7] "TEMPERATURA.MAXIMA.A.2.METROS"         
##  [8] "TEMPERATURA.MINIMA.A.2.METROS"         
##  [9] "Region.Hidrologica"                    
## [10] "Nombre.Río"                            
## [11] "Aportes_Energia_kWh"                   
## [12] "Caudal"                                
## [13] "Aportes.Media.Histórica.Energía.kWh"   
## [14] "Aportes.Media.Histórica.Caudal.m3.s"   
## [15] "Aportes.95.PSS.Energía.kWh"            
## [16] "Aportes.95.PSS.Caudal.m3.s"
# 6. Revisar coincidencias para caudal
cat("\nCoincidencias para 'caudal':\n")
## 
## Coincidencias para 'caudal':
print(grep("caudal", names(datos), ignore.case = TRUE, value = TRUE))
## [1] "Caudal"                              "Aportes.Media.Histórica.Caudal.m3.s"
## [3] "Aportes.95.PSS.Caudal.m3.s"
# 7. Modelo Caudal ~ Precipitación + Temperatura
modelo_caudal <- lm(Caudal ~ Precipitacion + Temperatura, data = datos)
summary(modelo_caudal)
## 
## Call:
## lm(formula = Caudal ~ Precipitacion + Temperatura, data = datos)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -112.99  -50.00   -6.53   47.91  169.43 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   1012.8021   233.5718   4.336 3.34e-05 ***
## Precipitacion    0.7967     2.5411   0.314 0.754503    
## Temperatura    -49.0629    12.6617  -3.875 0.000186 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 65.1 on 105 degrees of freedom
## Multiple R-squared:  0.1448, Adjusted R-squared:  0.1285 
## F-statistic: 8.891 on 2 and 105 DF,  p-value: 0.000271
# Gráfico de efectos
plot(allEffects(modelo_caudal))

# 8. Modelo extendido que incluye generación de energía
modelo_completo <- lm(Caudal ~ Precipitacion + Temperatura + Aportes_Energia_kWh, data = datos)
summary(modelo_completo)
## 
## Call:
## lm(formula = Caudal ~ Precipitacion + Temperatura + Aportes_Energia_kWh, 
##     data = datos)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -117.115  -35.408   -3.867   30.990  124.298 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          5.555e+02  1.872e+02   2.967  0.00373 ** 
## Precipitacion        1.078e+00  1.953e+00   0.552  0.58217    
## Temperatura         -2.703e+01  1.006e+01  -2.686  0.00842 ** 
## Aportes_Energia_kWh  5.434e-07  6.326e-08   8.589 9.35e-14 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 50.03 on 104 degrees of freedom
## Multiple R-squared:  0.4997, Adjusted R-squared:  0.4853 
## F-statistic: 34.63 on 3 and 104 DF,  p-value: 1.339e-15
# 9. Comparación de modelos (¿aporta algo la energía generada?)
anova(modelo_caudal, modelo_completo)
## Analysis of Variance Table
## 
## Model 1: Caudal ~ Precipitacion + Temperatura
## Model 2: Caudal ~ Precipitacion + Temperatura + Aportes_Energia_kWh
##   Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
## 1    105 445021                                  
## 2    104 260346  1    184675 73.772 9.346e-14 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# 10. Clasificación de régimen hídrico
datos$Regimen_hidrico <- dplyr::case_when(
  datos$Precipitacion > quantile(datos$Precipitacion, 0.75, na.rm = TRUE) ~ "Húmedo",
  datos$Precipitacion < quantile(datos$Precipitacion, 0.25, na.rm = TRUE) ~ "Seco",
  TRUE ~ "Normal"
)

# 11. Gráfico resumen por régimen hídrico
datos %>%
  group_by(Regimen_hidrico) %>%
  summarise(
    Caudal_medio = mean(Caudal, na.rm = TRUE),
    Generacion_media = mean(Aportes_Energia_kWh, na.rm = TRUE),
    Frecuencia = n()
  ) %>%
  ggplot(aes(x = Regimen_hidrico, y = Generacion_media, size = Caudal_medio, color = Regimen_hidrico)) +
  geom_point() +
  scale_color_manual(values = c("Húmedo" = "blue", "Seco" = "red", "Normal" = "green")) +
  labs(title = "Generación Energética por Régimen Hídrico",
       x = "Régimen Hídrico",
       y = "Generación Media (kWh)",
       size = "Caudal Medio (m3/s)") +
  theme_minimal()

# 12. (Opcional) Guardar tabla resumen
tabla_resumen <- datos %>%
  group_by(Regimen_hidrico) %>%
  summarise(
    Caudal_medio = mean(Caudal, na.rm = TRUE),
    Generacion_media = mean(Aportes_Energia_kWh, na.rm = TRUE),
    Frecuencia = n()
  )
write.csv(tabla_resumen, "resumen_regimen_hidrico.csv", row.names = FALSE)

# 13. (Opcional) Explora la relación caudal-generación según régimen
ggplot(datos, aes(x = Caudal, y = Aportes_Energia_kWh, color = Regimen_hidrico)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Generación vs Caudal por Régimen Hídrico",
       x = "Caudal (m3/s)", y = "Generación (kWh)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# --- Fin del bloque principal ---

#############################################################################
library(readxl)
library(ggplot2)
library(scales)
## 
## Adjuntando el paquete: 'scales'
## The following objects are masked from 'package:psych':
## 
##     alpha, rescale
library(dplyr)
library(tidyr)

# Leer los datos
datos_hidrologicos <- read_excel("Copia de ITUANGO Y RIOS(1).xlsx")

datos_hidrologicos <- datos_hidrologicos %>%
  rename(
    Mes = MES,
    Caudal_actual = `Aportes Caudal m3/s`,
    Media_historica = `Aportes Media Histórica Caudal m3/s`,
    PSS_95 = `Aportes 95 PSS Caudal m3/s`,
    Aporte_energia = `Aportes Energía kWh`,
    Precipitacion = `PROMEDIO DE PRECIPITACION`,
    Temperatura = `TEMPERATURA A 2 METROS`
  )


# Estadísticas descriptivas para todas las variables clave
library(psych)
describe(datos_hidrologicos[, c("Caudal_actual", "Media_historica", "PSS_95",
                                "Aporte_energia", "Precipitacion", "Temperatura")])
##                 vars   n         mean          sd      median     trimmed
## Caudal_actual      1 108       129.22       69.74      113.57      124.50
## Media_historica    2 108       135.10       43.47      141.11      134.93
## PSS_95             3 108        69.80       21.50       67.12       70.04
## Aporte_energia     4 108 105508855.56 79264085.46 83778750.00 93685575.00
## Precipitacion      5 108         4.99        2.62        4.77        4.83
## Temperatura        6 108        18.09        0.53       18.03       18.07
##                         mad         min          max        range  skew
## Caudal_actual         71.44       20.45       307.82       287.38  0.58
## Media_historica       43.60       59.33       215.26       155.93 -0.05
## PSS_95                24.49       31.62       113.34        81.72  0.04
## Aporte_energia  54683402.97 14622300.00 462823100.00 448200800.00  2.24
## Precipitacion          3.01        0.50        12.07        11.57  0.47
## Temperatura            0.53       16.88        19.51         2.63  0.27
##                 kurtosis         se
## Caudal_actual      -0.62       6.71
## Media_historica    -0.74       4.18
## PSS_95             -1.06       2.07
## Aporte_energia      6.47 7627190.18
## Precipitacion      -0.51       0.25
## Temperatura        -0.35       0.05
# Matriz de correlación
correlaciones <- cor(datos_hidrologicos[, c("Caudal_actual", "Media_historica", "PSS_95",
                                            "Aporte_energia", "Precipitacion", "Temperatura")],
                     use = "complete.obs")
print(round(correlaciones, 2))
##                 Caudal_actual Media_historica PSS_95 Aporte_energia
## Caudal_actual            1.00            0.54   0.48           0.67
## Media_historica          0.54            1.00   0.87           0.42
## PSS_95                   0.48            0.87   1.00           0.36
## Aporte_energia           0.67            0.42   0.36           1.00
## Precipitacion            0.15           -0.20  -0.04           0.07
## Temperatura             -0.38           -0.19  -0.07          -0.26
##                 Precipitacion Temperatura
## Caudal_actual            0.15       -0.38
## Media_historica         -0.20       -0.19
## PSS_95                  -0.04       -0.07
## Aporte_energia           0.07       -0.26
## Precipitacion            1.00       -0.33
## Temperatura             -0.33        1.00
# Gráfico combinado de caudales
library(ggplot2)
library(tidyr)
datos_largos <- datos_hidrologicos %>%
  select(Mes, Caudal_actual, Media_historica, PSS_95) %>%
  pivot_longer(-Mes, names_to = "Tipo_Caudal", values_to = "Valor")
ggplot(datos_largos, aes(x = Mes, y = Valor, fill = Tipo_Caudal)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Comparativo de Caudales por Mes", y = "Caudal (m³/s)") +
  theme_minimal()

# Caudal vs Precipitación
ggplot(datos_hidrologicos, aes(x = Precipitacion, y = Caudal_actual)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relación Precipitación vs Caudal Actual", x = "Precipitación (mm)", y = "Caudal (m³/s)")
## `geom_smooth()` using formula = 'y ~ x'

# Caudal vs Generación de Energía
ggplot(datos_hidrologicos, aes(x = Caudal_actual, y = Aporte_energia)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Generación de Energía vs Caudal", x = "Caudal (m³/s)", y = "Energía (kWh)")
## `geom_smooth()` using formula = 'y ~ x'

#correlacion de pearson con todas las variables 
matriz_cor <- cor(datos[, c("Caudal", "Precipitacion", "Temperatura", "Aportes_Energia_kWh")],
                  use = "complete.obs")
print(round(matriz_cor, 2))
##                     Caudal Precipitacion Temperatura Aportes_Energia_kWh
## Caudal                1.00          0.15       -0.38                0.67
## Precipitacion         0.15          1.00       -0.33                0.07
## Temperatura          -0.38         -0.33        1.00               -0.26
## Aportes_Energia_kWh   0.67          0.07       -0.26                1.00
 print(names(datos))
##  [1] "MES"                                   
##  [2] "AÑO"                                   
##  [3] "Precipitacion"                         
##  [4] "PROMEDIO.DE.LA.SUMA.DE.PRECIPITACIONES"
##  [5] "HUMEDAD.RELATIVA.A.2.METROS"           
##  [6] "Temperatura"                           
##  [7] "TEMPERATURA.MAXIMA.A.2.METROS"         
##  [8] "TEMPERATURA.MINIMA.A.2.METROS"         
##  [9] "Region.Hidrologica"                    
## [10] "Nombre.Río"                            
## [11] "Aportes_Energia_kWh"                   
## [12] "Caudal"                                
## [13] "Aportes.Media.Histórica.Energía.kWh"   
## [14] "Aportes.Media.Histórica.Caudal.m3.s"   
## [15] "Aportes.95.PSS.Energía.kWh"            
## [16] "Aportes.95.PSS.Caudal.m3.s"            
## [17] "Regimen_hidrico"
#############################################
# Correlación Pearson
correlacion <- cor(datos %>% select(Temperatura, Precipitacion, Caudal, Aportes_Energia_kWh), use = "complete.obs")
print(round(correlacion, 2))
##                     Temperatura Precipitacion Caudal Aportes_Energia_kWh
## Temperatura                1.00         -0.33  -0.38               -0.26
## Precipitacion             -0.33          1.00   0.15                0.07
## Caudal                    -0.38          0.15   1.00                0.67
## Aportes_Energia_kWh       -0.26          0.07   0.67                1.00
# Matriz de correlación visual
pairs.panels(datos %>% select(Temperatura, Precipitacion, Caudal, Aportes_Energia_kWh))

#########
##
set.seed(42)
n_meses <- 120  # Para 20 años; usa 360 para 30 años

media_precip <- mean(datos$Precipitacion, na.rm = TRUE)
sd_precip <- sd(datos$Precipitacion, na.rm = TRUE)
media_temp <- mean(datos$Temperatura, na.rm = TRUE)
sd_temp <- sd(datos$Temperatura, na.rm = TRUE)

precip_sim <- rnorm(n_meses, mean = media_precip, sd = sd_precip)
temp_sim <- rnorm(n_meses, mean = media_temp, sd = sd_temp)
##
nueva_simulacion <- data.frame(
  Precipitacion = precip_sim,
  Temperatura = temp_sim
)
nueva_simulacion$Aportes_energia_kWh <- predict(modelo_multiple, newdata = nueva_simulacion)
##
nueva_simulacion$Fecha <- seq.Date(
  from = as.Date("2024-01-01"),
  by = "month",
  length.out = n_meses
)
##
head(nueva_simulacion)
##   Precipitacion Temperatura Aportes_energia_kWh      Fecha
## 1      8.585196    17.30523           135481055 2024-01-01
## 2      3.515805    17.31742           137611772 2024-02-01
## 3      5.945738    18.15582           102358832 2024-03-01
## 4      6.652159    17.56645           125890478 2024-04-01
## 5      6.053481    18.08932           104999476 2024-05-01
## 6      4.716787    17.86519           114779593 2024-06-01
write.csv(nueva_simulacion, "simulacion_energia_20anios.csv", row.names = FALSE)
#####
#genera una serie de eventos del fenomeno el niño, neutral, la niña
set.seed(123)
n_meses <- 120 # 10 años
eventos_ENSO <- sample(c("Nino", "Nina", "Neutral"), n_meses, replace = TRUE, prob = c(0.25, 0.25, 0.5))
##
#ajusta la precipitacion y temperatura segun el evento 
media_precip <- mean(datos$Precipitacion, na.rm = TRUE)
sd_precip <- sd(datos$Precipitacion, na.rm = TRUE)
media_temp <- mean(datos$Temperatura, na.rm = TRUE)
sd_temp <- sd(datos$Temperatura, na.rm = TRUE)

precip_sim <- rnorm(n_meses, mean = media_precip, sd = sd_precip)
temp_sim <- rnorm(n_meses, mean = media_temp, sd = sd_temp)

# Ajuste por ENSO
for(i in 1:n_meses){
  if(eventos_ENSO[i] == "Nino"){
    precip_sim[i] <- precip_sim[i] * 0.7
    temp_sim[i] <- temp_sim[i] + 1
  } else if(eventos_ENSO[i] == "Nina"){
    precip_sim[i] <- precip_sim[i] * 1.25
    temp_sim[i] <- temp_sim[i] - 0.5
  }
}
##
nueva_simulacion <- data.frame(
  Precipitacion = precip_sim,
  Temperatura = temp_sim
)
nueva_simulacion$Aportes_energia_kWh <- predict(modelo_multiple, newdata = nueva_simulacion)
nueva_simulacion$ENSO <- eventos_ENSO
nueva_simulacion$Fecha <- seq.Date(from = as.Date("2024-01-01"), by = "month", length.out = n_meses)
##
library(dplyr)
nueva_simulacion %>%
  group_by(ENSO) %>%
  summarise(
    Energia_promedio = mean(Aportes_energia_kWh, na.rm = TRUE),
    Precip_promedio = mean(Precipitacion, na.rm = TRUE),
    Temp_promedio = mean(Temperatura, na.rm = TRUE)
  )
## # A tibble: 3 × 4
##   ENSO    Energia_promedio Precip_promedio Temp_promedio
##   <chr>              <dbl>           <dbl>         <dbl>
## 1 Neutral       103202497.            4.29          18.2
## 2 Nina          122763230.            6.88          17.6
## 3 Nino           65994945.            3.99          19.1
###
# ----------------------------
# 1. Carga de paquetes
# ----------------------------
if (!require(dplyr)) install.packages("dplyr")
if (!require(ggplot2)) install.packages("ggplot2")
if (!require(psych)) install.packages("psych")

library(dplyr)
library(ggplot2)
library(psych)

# ----------------------------
# 2. Datos históricos resumen (ajusta con tus datos reales)
# ----------------------------
# Reemplaza estos valores con las medias y desviaciones reales de tu dataset
media_precip <- 150   # media histórica de precipitación (mm)
sd_precip <- 50       # desviación estándar
media_temp <- 22      # media histórica de temperatura (°C)
sd_temp <- 2          # desviación estándar

# Modelo de regresión múltiple ajustado (ejemplo coeficientes)
intercepto <- 50
coef_precip <- 2
coef_temp <- 3

# ----------------------------
# 3. Simulación ENSO para 30 años (360 meses)
# ----------------------------
set.seed(123)
n_meses <- 120

# Generar eventos ENSO aleatorios con probabilidades
eventos_ENSO <- sample(c("Nino", "Nina", "Neutral"), n_meses, replace = TRUE, prob = c(0.25, 0.25, 0.5))

# Simular precipitación y temperatura base
precip_sim <- rnorm(n_meses, mean = media_precip, sd = sd_precip)
temp_sim <- rnorm(n_meses, mean = media_temp, sd = sd_temp)

# Ajustar según ENSO
for(i in 1:n_meses){
  if(eventos_ENSO[i] == "Nino"){
    precip_sim[i] <- precip_sim[i] * 0.7    # -30% precipitación
    temp_sim[i] <- temp_sim[i] + 1          # +1°C temperatura
  } else if(eventos_ENSO[i] == "Nina"){
    precip_sim[i] <- precip_sim[i] * 1.25   # +25% precipitación
    temp_sim[i] <- temp_sim[i] - 0.5        # -0.5°C temperatura
  }
}

# ----------------------------
# 4. Crear dataframe simulación
# ----------------------------
simulacion <- data.frame(
  Fecha = seq.Date(from = as.Date("2024-01-01"), by = "month", length.out = n_meses),
  ENSO = eventos_ENSO,
  Precipitacion = precip_sim,
  Temperatura = temp_sim
)

# ----------------------------
# 5. Predecir generación de energía con modelo múltiple
# ----------------------------
simulacion <- simulacion %>%
  mutate(
    Aportes_energia_kWh = intercepto + coef_precip * Precipitacion + coef_temp * Temperatura
  )

# ----------------------------
# 6. Análisis de correlación de Pearson
# ----------------------------
correlacion <- cor(simulacion %>% select(Precipitacion, Temperatura, Aportes_energia_kWh))
print(round(correlacion, 3))
##                     Precipitacion Temperatura Aportes_energia_kWh
## Precipitacion               1.000      -0.226               0.998
## Temperatura                -0.226       1.000              -0.172
## Aportes_energia_kWh         0.998      -0.172               1.000
# ----------------------------
# 7. Visualizaciones
# ----------------------------

# Serie temporal de Precipitación
ggplot(simulacion, aes(x = Fecha, y = Precipitacion, color = ENSO)) +
  geom_line() +
  labs(title = "Serie Temporal Simulada de Precipitación con ENSO",
       y = "Precipitación (mm)", x = "Fecha") +
  theme_minimal()

# Serie temporal de Temperatura
ggplot(simulacion, aes(x = Fecha, y = Temperatura, color = ENSO)) +
  geom_line() +
  labs(title = "Serie Temporal Simulada de Temperatura con ENSO",
       y = "Temperatura (°C)", x = "Fecha") +
  theme_minimal()

# Serie temporal de Generación de Energía
ggplot(simulacion, aes(x = Fecha, y = Aportes_energia_kWh, color = ENSO)) +
  geom_line() +
  labs(title = "Serie Temporal Simulada de Generación de Energía",
       y = "Generación (kWh)", x = "Fecha") +
  theme_minimal()

# Scatter plot: Generación vs Precipitación
ggplot(simulacion, aes(x = Precipitacion, y = Aportes_energia_kWh, color = ENSO)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = FALSE, color = "black") +
  labs(title = "Generación de Energía vs Precipitación",
       x = "Precipitación (mm)", y = "Generación (kWh)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# Scatter plot: Generación vs Temperatura
ggplot(simulacion, aes(x = Temperatura, y = Aportes_energia_kWh, color = ENSO)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = FALSE, color = "black") +
  labs(title = "Generación de Energía vs Temperatura",
       x = "Temperatura (°C)", y = "Generación (kWh)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# ----------------------------
# 8. Resumen por evento ENSO
# ----------------------------
resumen_ENSO <- simulacion %>%
  group_by(ENSO) %>%
  summarise(
    Media_Precipitacion = mean(Precipitacion),
    Media_Temperatura = mean(Temperatura),
    Media_Generacion = mean(Aportes_energia_kWh)
  )
print(resumen_ENSO)
## # A tibble: 3 × 4
##   ENSO    Media_Precipitacion Media_Temperatura Media_Generacion
##   <chr>                 <dbl>             <dbl>            <dbl>
## 1 Neutral                137.              22.3             390.
## 2 Nina                   200.              21.7             514.
## 3 Nino                   114.              23.0             348.
# ----------------------------
# FIN
# ----------------------------