# 1. ENFOQUE METODOLÓGICO
# ----------------------------
# Instalar las librerías necesarias si no están instaladas
# install.packages("readxl")
# install.packages("lmtest")
# install.packages("knitr")
# install.packages("ggplot2")

# Cargar las librerías necesarias
library(readxl)
## Warning: package 'readxl' was built under R version 4.4.3
library(lmtest)
## Warning: package 'lmtest' was built under R version 4.4.2
## Cargando paquete requerido: zoo
## Warning: package 'zoo' was built under R version 4.4.2
## 
## Adjuntando el paquete: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(knitr)
## Warning: package 'knitr' was built under R version 4.4.3
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.2
# ----------------------------
# 2. FUENTES DE DATOS
# ----------------------------
# Importar la base de datos
datos <- read_excel("C:/Users/DELL/Downloads/PROYECTO.xlsx", sheet = "ITUANGO")

# ----------------------------
# 3. VARIABLES DE ESTUDIO
# ----------------------------
# Renombrar las variables para facilitar el análisis
names(datos)[names(datos) == "Aportes Energía kWh"] <- "Aportes_energia_kWh"
names(datos)[names(datos) == "PROMEDIO DE PRECIPITACION"] <- "Precipitacion"
names(datos)[names(datos) == "TEMPERATURA A 2 METROS"] <- "Temperatura"

# Extraer las variables de interés
generacion <- datos$Aportes_energia_kWh
precipitacion <- datos$Precipitacion
temperatura <- datos$Temperatura

# ----------------------------
# 4. TÉCNICAS DE ANÁLISIS
# ----------------------------

## 4.1. Análisis Exploratorio de Datos (EDA)
# Verificar los primeros datos
head(datos)
## # A tibble: 6 × 16
##   AÑO       MES Precipitacion PROMEDIO DE LA SUMA DE PR…¹ HUMEDAD RELATIVA A 2…²
##   <chr>   <dbl>         <dbl>                       <dbl>                  <dbl>
## 1 ENERO    2015          2.32                        71.9                   86.4
## 2 FEBRERO  2015          3.58                       100.                    88.3
## 3 MARZO    2015          3.21                        99.5                   86.9
## 4 ABRIL    2015          4.87                       146.                    89.0
## 5 MAYO     2015          5.31                       165.                    89.2
## 6 JUNIO    2015          2.18                        65.5                   87.2
## # ℹ abbreviated names: ¹​`PROMEDIO DE LA SUMA DE PRECIPITACIONES`,
## #   ²​`HUMEDAD RELATIVA A 2 METROS`
## # ℹ 11 more variables: Temperatura <dbl>,
## #   `TEMPERATURA MAXIMA A 2 METROS` <dbl>,
## #   `TEMPERATURA MINIMA A 2 METROS` <dbl>, `Region Hidrologica` <chr>,
## #   `Nombre Río` <chr>, Aportes_energia_kWh <dbl>, `Aportes Caudal m3/s` <dbl>,
## #   `Aportes Media Histórica Energía kWh` <dbl>, …
# Resumen estadístico
summary(datos[, c("Aportes_energia_kWh", "Precipitacion","Temperatura")])
##  Aportes_energia_kWh Precipitacion     Temperatura   
##  Min.   : 14622300   Min.   : 0.500   Min.   :16.88  
##  1st Qu.: 55322775   1st Qu.: 2.987   1st Qu.:17.70  
##  Median : 83778750   Median : 4.770   Median :18.03  
##  Mean   :105508856   Mean   : 4.995   Mean   :18.09  
##  3rd Qu.:135072150   3rd Qu.: 6.890   3rd Qu.:18.44  
##  Max.   :462823100   Max.   :12.070   Max.   :19.51
## 4.2. Análisis de Correlación
# Matriz de correlación
cor(datos[, c("Aportes_energia_kWh", "Precipitacion", "Temperatura")], use = "complete.obs")
##                     Aportes_energia_kWh Precipitacion Temperatura
## Aportes_energia_kWh          1.00000000    0.07027517  -0.2633062
## Precipitacion                0.07027517    1.00000000  -0.3250073
## Temperatura                 -0.26330621   -0.32500734   1.0000000
## 4.3. Modelos Estadísticos

### Modelo 1: Generación de Energía vs Precipitación
# Cálculo manual de coeficientes
media_precip <- mean(precipitacion, na.rm = TRUE)
media_generacion <- mean(generacion, na.rm = TRUE)
numerador <- sum((precipitacion - media_precip) * (generacion - media_generacion), na.rm = TRUE)
denominador <- sum((precipitacion - media_precip)^2, na.rm = TRUE)
beta_1_precip <- numerador / denominador
beta_0_precip <- media_generacion - beta_1_precip * media_precip

# Modelo ajustado
modelo_precip <- lm(generacion ~ precipitacion, data = datos)
summary(modelo_precip)
## 
## Call:
## lm(formula = generacion ~ 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
### Modelo 2: Generación de Energía vs Temperatura
# Cálculo manual de coeficientes
media_temp <- mean(temperatura, na.rm = TRUE)
numerador_temp <- sum((temperatura - media_temp) * (generacion - media_generacion), na.rm = TRUE)
denominador_temp <- sum((temperatura - media_temp)^2, na.rm = TRUE)
beta_1_temp <- numerador_temp / denominador_temp
beta_0_temp <- media_generacion - beta_1_temp * media_temp

# Modelo ajustado
modelo_temp <- lm(generacion ~ temperatura, data = datos)
summary(modelo_temp)
## 
## Call:
## lm(formula = generacion ~ 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
### Modelo de Regresión Lineal Múltiple
modelo_multiple <- lm(generacion ~ precipitacion + temperatura, data = datos)
summary(modelo_multiple)
## 
## Call:
## lm(formula = generacion ~ 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
### Modelo de Regresión Logística
# Crear variable binaria
umbral <- median(datos$Aportes_energia_kWh, na.rm = TRUE)
datos$Generacion_alta <- ifelse(datos$Aportes_energia_kWh >= umbral, 1, 0)

str(datos)
## tibble [108 × 17] (S3: tbl_df/tbl/data.frame)
##  $ AÑO                                   : chr [1:108] "ENERO" "FEBRERO" "MARZO" "ABRIL" ...
##  $ MES                                   : num [1:108] 2015 2015 2015 2015 2015 ...
##  $ Precipitacion                         : num [1:108] 2.32 3.58 3.21 4.87 5.31 2.18 5.38 4.97 4.28 6.04 ...
##  $ PROMEDIO DE LA SUMA DE PRECIPITACIONES: num [1:108] 71.9 100.3 99.5 146 164.7 ...
##  $ HUMEDAD RELATIVA A 2 METROS           : num [1:108] 86.4 88.3 86.9 89 89.2 ...
##  $ Temperatura                           : num [1:108] 17.5 18 18.3 18.4 18.4 ...
##  $ TEMPERATURA MAXIMA A 2 METROS         : num [1:108] 23.9 24.5 25.6 25.2 25.2 ...
##  $ TEMPERATURA MINIMA A 2 METROS         : num [1:108] 12.1 13.4 13.2 13.9 14.5 ...
##  $ Region Hidrologica                    : chr [1:108] "VALLE" "VALLE" "VALLE" "VALLE" ...
##  $ Nombre Río                            : chr [1:108] "CAUCA SALVAJINA" "CAUCA SALVAJINA" "CAUCA SALVAJINA" "CAUCA SALVAJINA" ...
##  $ Aportes_energia_kWh                   : num [1:108] 55303200 59314900 77937900 84408900 53220700 ...
##  $ Aportes Caudal m3/s                   : num [1:108] 75.3 89.4 106.1 118.2 72 ...
##  $ Aportes Media Histórica Energía kWh   : num [1:108] 1.22e+08 9.66e+07 1.02e+08 1.10e+08 1.13e+08 ...
##  $ Aportes Media Histórica Caudal m3/s   : num [1:108] 165 145 139 153 153 ...
##  $ Aportes 95 PSS Energía kWh            : num [1:108] 55180000 39480000 41850000 58800000 68510000 ...
##  $ Aportes 95 PSS Caudal m3/s            : num [1:108] 75 59.5 57.1 82.3 92.8 ...
##  $ Generacion_alta                       : num [1:108] 0 0 0 1 0 0 0 0 0 0 ...
# Ajustar modelo
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
# Evaluación del modelo
probabilidades <- predict(modelo_logistico, type = "response")
predicciones <- ifelse(probabilidades > 0.5, 1, 0)
table(Predicho = predicciones, Real = datos$Generacion_alta)
##         Real
## Predicho  0  1
##        0 33 19
##        1 21 35
## 4.4. Análisis de Eficiencia
# Tabla ANOVA para el modelo múltiple
anova(modelo_multiple)
## Analysis of Variance Table
## 
## Response: generacion
##                Df     Sum Sq    Mean Sq F value   Pr(>F)   
## precipitacion   1 3.3200e+15 3.3200e+15  0.5573 0.457003   
## temperatura     1 4.3464e+16 4.3464e+16  7.2964 0.008057 **
## Residuals     105 6.2548e+17 5.9569e+15                    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# ----------------------------
# 5. HERRAMIENTAS UTILIZADAS
# ----------------------------
# Gráficos de Regresión

# Generación de Energía vs Precipitación
ggplot(datos, aes(x = precipitacion, y = generacion)) +
  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'

# Generación de Energía vs Temperatura
ggplot(datos, aes(x = temperatura, y = generacion)) +
  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'

# ----------------------------
# 6. VALIDACIÓN DE RESULTADOS
# ----------------------------
# Validación de supuestos para los modelos

## Linealidad y Homocedasticidad
par(mfrow = c(1, 2))
plot(modelo_precip$fitted.values, modelo_precip$residuals,
     main = "Residuos vs Valores Ajustados (Precipitación)",
     xlab = "Valores Ajustados", ylab = "Residuos", pch = 19, col = "blue")
abline(h = 0, col = "red", lty = 2)

plot(modelo_temp$fitted.values, modelo_temp$residuals,
     main = "Residuos vs Valores Ajustados (Temperatura)",
     xlab = "Valores Ajustados", ylab = "Residuos", pch = 19, col = "green")
abline(h = 0, col = "orange", lty = 2)

## Normalidad de los Residuos
par(mfrow = c(1, 2))
qqnorm(modelo_precip$residuals)
qqline(modelo_precip$residuals, col = "red")

qqnorm(modelo_temp$residuals)
qqline(modelo_temp$residuals, col = "orange")

# Para el modelo múltiple
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")

# ----------------------------
# 7. LIMITACIONES
# ----------------------------
# Nota: Esta sección sería de análisis cualitativo basado en los resultados
# Se podría añadir código para identificar problemas específicos como:
# - Valores faltantes
sum(is.na(datos))
## [1] 0
# - Multicolinealidad
car::vif(modelo_multiple)
## precipitacion   temperatura 
##      1.118105      1.118105
# ----------------------------
# 8. RESULTADOS ESPERADOS
# ----------------------------
# Resumen de coeficientes significativos
coeficientes_significativos <- summary(modelo_multiple)$coefficients
coeficientes_significativos
##                  Estimate Std. Error    t value    Pr(>|t|)
## (Intercept)   841605584.9  276907877  3.0392981 0.002993202
## precipitacion   -517797.1    3012537 -0.1718807 0.863862156
## temperatura   -40547220.2   15010933 -2.7011792 0.008057265
# Gráfico final comparativo
# (Podrías añadir aquí visualizaciones que resuman tus hallazgos principales)