# =============================
# 1. CARGAR LIBRERÍAS
# =============================
library(readr)
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(caret)
## Cargando paquete requerido: ggplot2
## Cargando paquete requerido: lattice
library(plotly)
## 
## Adjuntando el paquete: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(car)
## Cargando paquete requerido: carData
## 
## Adjuntando el paquete: 'car'
## The following object is masked from 'package:dplyr':
## 
##     recode
# =============================
# 2. CARGAR DATOS
# =============================
ruta_archivo <- "C:/Users/y-oss/OneDrive/Escritorio/brasil rstudios/brasil depurada 12.csv"
Datos_raw <- read_delim(ruta_archivo, delim = ";")
## Rows: 29575 Columns: 59
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ";"
## chr (52): POCO, CADASTRO, OPERADOR, POCO_OPERADOR, ESTADO, BACIA, BLOCO, SIG...
## num  (7): LONGITUDE_BASE_DD, PROFUNDIDADE_VERTICAL_M, PROFUNDIDADE_SONDADOR_...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# =============================
# 3. LIMPIAR Y TRANSFORMAR
# =============================
Datos_limpios <- Datos_raw %>%
  filter(!is.na(PROFUNDIDADE_VERTICAL_M)) %>%
  mutate(log_PROFUNDIDADE_VERTICAL_M = ifelse(PROFUNDIDADE_VERTICAL_M > 0,
                                              log(PROFUNDIDADE_VERTICAL_M),
                                              NA)) %>%
  filter(!is.na(log_PROFUNDIDADE_VERTICAL_M))
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `log_PROFUNDIDADE_VERTICAL_M = ifelse(...)`.
## Caused by warning in `log()`:
## ! Se han producido NaNs
# =============================
# 4. SELECCIONAR VARIABLES
# =============================
datos <- Datos_limpios %>%
  select(PROFUNDIDADE_VERTICAL_M,
         LAMINA_D_AGUA_M,
         COTA_ALTIMETRICA_M,
         PROFUNDIDADE_MEDIDA_M,
         PROFUNDIDADE_SONDADOR_M,
         LATITUDE_BASE_DD,
         LONGITUDE_BASE_DD,
         TERRA_MAR,
         GEOLOGIA_GRUPO_FINAL,
         BACIA) %>%
  na.omit()


# =============================
# 6. FILTRAR VALORES EXTREMOS
# =============================
# Eliminar registros con profundidad mayor a 10,000 m (ajustable)
datos_filtrados <- datos %>%
  filter(PROFUNDIDADE_VERTICAL_M < 10000)

# =============================
# 7. MODELO SIMPLE CON 2 VARIABLES
# =============================
modelo_simple <- lm(PROFUNDIDADE_VERTICAL_M ~ LAMINA_D_AGUA_M + COTA_ALTIMETRICA_M, 
                    data = datos_filtrados)


# =============================
# 8. GENERAR GRID DE PREDICCIÓN
# =============================
x <- datos_filtrados$LAMINA_D_AGUA_M
y <- datos_filtrados$COTA_ALTIMETRICA_M
z <- datos_filtrados$PROFUNDIDADE_VERTICAL_M

grid_lines <- 30
x_seq <- seq(min(x), max(x), length.out = grid_lines)
y_seq <- seq(min(y), max(y), length.out = grid_lines)
grid <- expand.grid(LAMINA_D_AGUA_M = x_seq,
                    COTA_ALTIMETRICA_M = y_seq)

z_pred <- matrix(predict(modelo_simple, newdata = grid), 
                 nrow = grid_lines, ncol = grid_lines)

# =============================
# 9. GRÁFICO 3D CORREGIDO
# =============================
fig <- plot_ly() %>%
  add_markers(x = x, y = y, z = z,
              marker = list(color = 'blue', size = 3),
              name = "Datos Reales") %>%
  add_surface(x = x_seq, y = y_seq, z = z_pred,
              opacity = 0.5,
              showscale = FALSE,
              name = "Plano de Regresión") %>%
  layout(scene = list(
    xaxis = list(title = "Lámina de Agua (m)"),
    yaxis = list(title = "Cota Altimétrica (m)"),
    zaxis = list(title = "Profundidad Vertical (m)")
  ),
  title = "Gráfico 3D sin valores extremos")

fig
# =============================
# 10. EVALUACIÓN DEL MODELO
# =============================

# Predicciones del modelo sobre los datos usados
predicciones <- predict(modelo_simple, newdata = datos_filtrados)

# R² (R-squared)
r2 <- summary(modelo_simple)$r.squared

# MSE (Mean Squared Error)
mse <- mean((datos_filtrados$PROFUNDIDADE_VERTICAL_M - predicciones)^2)

# Mostrar resultados
cat("✅ MÉTRICAS DEL MODELO:\n")
## ✅ MÉTRICAS DEL MODELO:
cat("R² =", round(r2, 4), "\n")
## R² = 0.0398
cat("MSE =", round(mse, 4), "\n")
## MSE = 4356768
# Conclusion

conclusion <-"El modelo de regresión con lámina de agua y cota altimétrica explica solo el 3.98% de la variación en la profundidad vertical (R² = 0.0398), lo que indica un bajo poder predictivo. el MSE alto (4,356,768) muestra que las predicciones son poco precisas. "