# ==========================================================
# 1. CARGA DE LIBRERÍAS Y DATOS 
# ==========================================================
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(knitr)
library(gt)

# Configuración de directorio y carga de archivo
setwd("C:/Users/HP/Documents/PROYECTO ESTADISTICA/RStudio")
datos <- read.csv("tablap.csv", header = TRUE, sep = ";", dec = ",")

# ==========================================================
# 2. TABLA PARES DE VALORES
# ==========================================================
# Extraer variables
area_pozo  <- as.numeric(datos$Area.of.well.pads)
produccion <- as.numeric(datos$Total.gas.production.by.2023)

# Crear TPV inicial y limpiar (NA, 0 y negativos)
TPV <- data.frame(area_pozo = area_pozo, produccion = produccion)
TPV <- na.omit(TPV)
TPV <- TPV[TPV$area_pozo > 0 & TPV$produccion > 0, ]

# --- ELIMINACIÓN DE OUTLIERS (SEGÚN GUÍA) ---
Q1_x <- quantile(TPV$area_pozo, 0.25); Q3_x <- quantile(TPV$area_pozo, 0.75)
IQR_x <- Q3_x - Q1_x
lim_inf_x <- Q1_x - 1.5 * IQR_x; lim_sup_x <- Q3_x + 1.5 * IQR_x

Q1_y <- quantile(TPV$produccion, 0.25); Q3_y <- quantile(TPV$produccion, 0.75)
IQR_y <- Q3_y - Q1_y
lim_inf_y <- Q1_y - 1.5 * IQR_y; lim_sup_y <- Q3_y + 1.5 * IQR_y

TPV_limpio <- TPV[
  TPV$area_pozo >= lim_inf_x & TPV$area_pozo <= lim_sup_x &
    TPV$produccion >= lim_inf_y & TPV$produccion <= lim_sup_y, 
]

# Ordenar la tabla
TPV_limpio <- TPV_limpio[order(TPV_limpio$area_pozo), ]

# --- RESETEAR NUMERACIÓN DE FILAS ---
row.names(TPV_limpio) <- NULL

# --- MOSTRAR TABLA (Primeros 20 registros) ---
cat("TABLA DE PARES DE VALORES (Vista previa limpia):\n")
## TABLA DE PARES DE VALORES (Vista previa limpia):
print(head(TPV_limpio, 20))
##    area_pozo produccion
## 1       2804      59263
## 2       2807      58319
## 3       2821      58334
## 4       2822     108411
## 5       2823      80571
## 6       2824      57084
## 7       2827      58521
## 8       2839      74661
## 9       2850      68191
## 10      2868      77172
## 11      2870      50308
## 12      2871      69337
## 13      2875      72314
## 14      2879      51300
## 15      2880      86043
## 16      2880      93692
## 17      2886      68459
## 18      2891      42390
## 19      2898      50339
## 20      2898      68475
# Definición de variables finales para el modelo (100% de datos limpios)
x <- TPV_limpio$area_pozo
y <- TPV_limpio$produccion

# Selección aleatoria del 50% solo para representación visual
set.seed(123)
indice_visual <- sample(1:nrow(TPV_limpio), nrow(TPV_limpio) / 20)

# ==========================================================
# 3. DIAGRAMA DE DISPERSIÓN (VISTA 50%)
# ==========================================================
plot(x[indice_visual], y[indice_visual], 
     pch = 16, col = "blue",
     main = "Gráfica N°1: Diagrama de dispersión \n Área de pozo vs Producción de Gas",
     xlab = "Área de plataformas de pozo", 
     ylab = "Producción total de gas (2023)")

# ==========================================================
# 4. CONJETURA DEL MODELO (EXPONENCIAL)
# ==========================================================
# Transformación logarítmica de la variable dependiente Y
y1 <- log(y)

# Cálculo de parámetros (Usa 100% de los datos limpios)
regresion_exponencial <- lm(y1 ~ x)
beta0 <- coef(regresion_exponencial)[1]
beta1 <- coef(regresion_exponencial)[2]

a <- exp(beta0) # Intercepto transformado
b <- beta1      # Tasa de crecimiento

# Graficar comparación realidad vs modelo (Puntos al 50%)
plot(x[indice_visual], y[indice_visual], 
     pch = 16, col = "blue",
     main = "Gráfica N°2: Comparación de la realidad con el modelo exponencial",
     xlab = "Área de plataformas de pozo", 
     ylab = "Producción de gas")

# Añadir curva exponencial
curve(a * exp(b * x), from = min(x), to = max(x), add = TRUE, col = "red", lwd = 2)

# Mostrar Ecuación
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
eq <- paste0("Ecuación exponencial\n Y = ae^(bx)\n Y = ", 
             round(a, 2), "e^(", round(b, 3), "x)")
text(1, 1, labels = eq, cex = 1.7, col = "blue", font = 2)

# ==========================================================
# 5. TEST DE APROBACIÓN Y RESTRICCIONES
# ==========================================================
r <- cor(x, y1)
cat("\nTest de Pearson (r*100):", round(r * 100, 2), "%\n")
## 
## Test de Pearson (r*100): 96.25 %
cat("\nRESTRICCIONES:\n")
## 
## RESTRICCIONES:
cat("El modelo exponencial no permite valores de Y iguales o menores a cero. 
La confiabilidad se limita al rango de datos observados.")
## El modelo exponencial no permite valores de Y iguales o menores a cero. 
## La confiabilidad se limita al rango de datos observados.
# ==========================================================
# 6. CÁLCULO DE PRONÓSTICOS
# ==========================================================
area_test <- 10 # Valor de ejemplo
T_Esp <- a * exp(b * area_test)

plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
text(x = 1, y = 1,
     labels = paste0("¿Cuál sería la producción si se tiene \n un área de pozo de ", area_test, "?\n\n R = ", round(T_Esp, 2)),
     cex = 1.5, col = "blue", font = 2)

# ==========================================================
# 7. CONCLUSIÓN
# ==========================================================
cat("\n--- CONCLUSIÓN ---\n")
## 
## --- CONCLUSIÓN ---
cat(paste0("Entre el área de pozo y la producción de gas existe una relación exponencial "))
## Entre el área de pozo y la producción de gas existe una relación exponencial
cat(paste0("representada por el modelo f(x) = ", round(a, 2), "e^(", round(b, 3), "x). "))
## representada por el modelo f(x) = 13588.53e^(0.001x).
cat(paste0("Ejemplo: Con un área de ", area_test, ", el modelo predice una producción de ", round(T_Esp, 2), "."))
## Ejemplo: Con un área de 10, el modelo predice una producción de 13668.72.