#======REGRESION LINEAL SIMPLE: PROYECCION VS ENERGIA======
library(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
library(ggplot2)
library(knitr)

#--- PASO 0: CARGA Y CONFIGURACI??N ---
# Establecemos el directorio y cargamos el archivo original
setwd("C:/Users/HP/Documents/PROYECTO ESTADISTICA/RStudio")
datos <- read.csv("tablap.csv", header = TRUE, dec = ".", sep = ";")

#--- PASO 1 y 2: DEFINICI??N DE VARIABLES Y CREACI??N DE TPV ---
# Usamos los nombres de tus columnas originales de Gas
x_var <- "Projection.of.gas.production"
y_var <- "Energy.of.gas"

# Limpieza: Convertimos a num??rico y eliminamos NAs
x_raw <- as.numeric(gsub(",", ".", as.character(datos[[x_var]])))
y_raw <- as.numeric(gsub(",", ".", as.character(datos[[y_var]])))

# Creamos el data frame TPV (Tabla de Puntos V??lidos) 
TPV <- data.frame(x = x_raw, y = y_raw)
TPV <- na.omit(TPV)

# Filtro de los "Top 300" para optimizar el ajuste (pozos de alto rendimiento)
TPV <- TPV %>%
  filter(x > 0, y > 0) %>%
  arrange(desc(y)) %>%
  slice(1:300)

x <- TPV$x
y <- TPV$y

#--- PASO 3: GRAFICA 1 (DISPERSI??N) ---
plot(x, y, 
     main = "Grafica Nro. 1: Diagrama de dispersi??n (Gas)",
     xlab = "Proyecci??n de Gas", 
     ylab = "Energ??a del Gas", 
     pch = 16, col = "gray70")

#--- PASO 4: CONJETURA ---
# En base a la tendencia de los puntos, conjeturamos una funci??n de tipo LINEAL.

#--- PASO 5 y 6: REGRESI??N LINEAL Y PAR??METROS ---
regresion_lineal <- lm(y ~ x)
a_pendiente <- coef(regresion_lineal)[2]
b_intercepto <- coef(regresion_lineal)[1]

#--- PASO 7: DIBUJO CON RECTA (MODELO) ---
plot(x, y, col = "lightblue", pch = 16,
     main = "Modelo de Regresi??n Lineal: Proyecci??n vs Energ??a",
     xlab = "Proyecci??n de Producci??n", 
     ylab = "Energ??a")
abline(regresion_lineal, col = "red", lwd = 2)

#--- PASO 8: TEST DE PEARSON ---
r <- cor(x, y)
cat("\n--- RESULTADOS DEL MODELO LINEAL ---\n")
## 
## --- RESULTADOS DEL MODELO LINEAL ---
cat("Coeficiente de correlaci??n (r):", round(r, 4), "\n")
## Coeficiente de correlaci??n (r): 0.9931
#--- PASO 9: COEFICIENTE DE DETERMINACI??N ---
r2 <- r^2 * 100
cat("Coeficiente de determinaci??n (r2):", round(r2, 2), "%\n")
## Coeficiente de determinaci??n (r2): 98.62 %
#--- PASO 10: CALCULO DE ESTIMACIONES ---
valor_x_prueba <- 1.2e+10  # Valor de proyecci??n de ejemplo
Energia_esp <- (valor_x_prueba * a_pendiente) + b_intercepto
cat("Estimaci??n: Para una Proyecci??n de", valor_x_prueba, "la Energ??a esperada es:", round(Energia_esp, 2), "\n")
## Estimaci??n: Para una Proyecci??n de 1.2e+10 la Energ??a esperada es: 11761091562
#--- PASO 11: AN??LISIS DE RESTRICCIONES ---
dom_x_min <- min(x); dom_x_max <- max(x)
dom_y_min <- min(y); dom_y_max <- max(y)
y_pred_min <- (dom_x_min * a_pendiente) + b_intercepto
existe_restriccion <- ifelse(y_pred_min < 0, "SI", "NO")

cat("\n--- ANALISIS DE DOMINIOS Y RESTRICCIONES ---\n")
## 
## --- ANALISIS DE DOMINIOS Y RESTRICCIONES ---
cat("Dominio observado x: [", round(dom_x_min, 2), ",", round(dom_x_max, 2), "]\n")
## Dominio observado x: [ 8775974102 , 75927969228 ]
cat("??Existe restricci??n f??sica en el modelo?:", existe_restriccion, "\n")
## ??Existe restricci??n f??sica en el modelo?: NO
#--- TABLA FINAL DE RESULTADOS ---
tabla_final_regresion <- data.frame(
  Indicador = c("Coeficiente de Correlaci??n (r)", "Coeficiente de Determinaci??n (R2)", 
                "Pendiente (a)", "Intercepto (b)", "Restricci??n de Modelo"),
  Valor = c(round(r, 4), paste0(round(r2, 2), "%"), round(a_pendiente, 8), 
            round(b_intercepto, 2), existe_restriccion)
)

cat("\n--- TABLA Nro. 30: RESUMEN DE PAR??METROS Y PRUEBAS DE REGRESI??N ---\n")
## 
## --- TABLA Nro. 30: RESUMEN DE PAR??METROS Y PRUEBAS DE REGRESI??N ---
print(kable(tabla_final_regresion, format = "markdown", align = "lc"))
## 
## 
## |Indicador                          |    Valor     |
## |:----------------------------------|:------------:|
## |Coeficiente de Correlaci??n (r)    |    0.9931    |
## |Coeficiente de Determinaci??n (R2) |    98.62%    |
## |Pendiente (a)                      |  0.98724157  |
## |Intercepto (b)                     | -85807312.09 |
## |Restricci??n de Modelo             |      NO      |
#--- GR??FICO AVANZADO GGPLOT2 ---

ggplot(TPV, aes(x = x, y = y)) +
  geom_point(color = "blue", alpha = 0.4, size = 1.5) +
  geom_smooth(method = "lm", se = TRUE, color = "red", linewidth = 1) +
  labs(title = "Regresi??n Lineal: Proyecci??n de Gas vs Energ??a",
       x = "Proyecci??n de Producci??n", y = "Energ??a del Gas") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'