pacman::p_load(dplyr, sf, tmap, ggplot2, lubridate, spatstat, maptools)


getwd()
## [1] "C:/Users/the_m/OneDrive/Documentos"
dt <- st_read("C:/Users/the_m/OneDrive/Documentos/whale_shark_R_BCS.shp")
## Reading layer `whale_shark_R_BCS' from data source 
##   `C:\Users\the_m\OneDrive\Documentos\whale_shark_R_BCS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 89 features and 30 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -110.5975 ymin: 24.12661 xmax: -110.2704 ymax: 24.6064
## Geodetic CRS:  WGS 84
summary(as.POSIXct(dt$eventDt))
##                  Min.               1st Qu.                Median 
## "2006-07-06 00:00:00" "2016-12-17 00:00:00" "2018-01-04 00:00:00" 
##                  Mean               3rd Qu.                  Max. 
## "2017-12-08 06:33:42" "2019-11-02 00:00:00" "2022-04-02 00:00:00"
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(dt) +
  tm_dots(col = "year", style = "fisher", n = 10)
#Avistamientos por año

dt %>%
  st_set_geometry(NULL) %>%
  group_by(year) %>%
  count() %>%
  ggplot(aes(x = year, y = n)) +
  geom_col()  

#Avistamientos despues del 2000
dt %>%
  st_set_geometry(NULL) %>%
  filter(as.numeric(year) > 2000) %>%
  group_by(year) %>%
  count() %>%
  ggplot(aes(x = year, y = n)) +
  geom_col() 

#Avistamientos por mes
dt %>%
  st_set_geometry(NULL) %>%
  filter(as.numeric(year) > 2004) %>%
  group_by(month) %>%
  count() %>%
  ggplot(aes(x = factor(month), y = n)) +
  geom_col()  

#Avistamientos por semana
dt %>%
  st_set_geometry(NULL) %>%
  filter(as.numeric(year) > 2004) %>%
  mutate(fecha = ymd(paste(year, month, day, sep = "-")),
         semana = week(fecha)) %>%
  group_by(semana) %>%
  count() %>%
  ungroup() %>%
  right_join(data.frame(semana = c(1:54))) %>%
  mutate(n = ifelse(is.na(n), 0, n)) %>%
  ggplot(aes(x = factor(semana), y = n)) +
  geom_col() +
  geom_vline(xintercept = c(seq(from = 4, to = 52, by = 4)))
## Joining, by = "semana"

lp <- st_read("C:/Users/the_m/OneDrive/Documentos/whale_shark_R_BCS.shp")
## Reading layer `whale_shark_R_BCS' from data source 
##   `C:\Users\the_m\OneDrive\Documentos\whale_shark_R_BCS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 89 features and 30 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -110.5975 ymin: 24.12661 xmax: -110.2704 ymax: 24.6064
## Geodetic CRS:  WGS 84
ggplot() +
  geom_sf(data = lp, aes(color = factor(month), size = year), alpha = 0.5) +
  theme_minimal()

ggplot() +
  geom_sf(data = lp, aes(color = issues), alpha = 0.5) +
  theme_minimal()

#Por año
dt %>%
  st_set_geometry(NULL) %>%
  filter(as.numeric(year) > 2004) %>%
  group_by(year) %>%
  count() %>%
  ggplot(aes(x = factor(year), y = n)) +
  geom_col()  

lp %>%
  st_set_geometry(NULL) %>%
  filter(as.numeric(year) > 2004) %>%
  mutate(fecha = ymd(paste(year, month, day, sep = "-")),
         semana = week(fecha)) %>%
  group_by(semana) %>%
  count() %>%
  ungroup() %>%
  right_join(data.frame(semana = c(1:54))) %>%
  mutate(n = ifelse(is.na(n), 0, n)) %>%
  ggplot(aes(x = semana, y = n)) +
  geom_col() +
  geom_vline(xintercept = c(seq(from = 4, to = 52, by = 4)))
## Joining, by = "semana"

#Analisis de Patrones puntuales

lp_p <- lp %>%
  st_transform(32612) %>%
  st_coordinates()
plot(lp_p, asp = 1) # Coordenadas representadas 1:1 en el cociente de los ejes.

#Ventanas de observacion
lp_c <- lp %>%
  st_transform(32612) %>%
  st_union() %>%
  st_convex_hull() %>%
  st_cast("POLYGON") # Polígono convexo 
lp_1 <- lp %>%
  st_transform(32612) %>%
  st_bbox() %>%
  st_as_sfc() # Rectángulo envolvente
# Transformar en objetos owin
wbbox <- as.owin(lp_1) # Ventana de rectángulo envolvente
wch <- as.owin(lp_c)  # Ventana de polígono convexo
wr <- as.owin(ripras(lp_p)) # Ventana de Ripley-Rasson (Pológono convexo corregido)

tp_1 <- ppp(lp_p[,1], lp_p[,2], window = wbbox) # Patrón puntual con envolvente rectangular 
## Warning: data contain duplicated points
tp_1 <- unique(tp_1) # Eliminar duplicados
tp_2 <- ppp(lp_p[,1], lp_p[,2], window = wch) # Patrón puntual con polígono convexo 
## Warning: data contain duplicated points
tp_2 <- unique(tp_2) # Eliminar duplicados
tp_3 <- ppp(lp_p[,1], lp_p[,2], window = wr) # Patrón puntual con polígono convexo 
## Warning: data contain duplicated points
tp_3 <- unique(tp_3) # Eliminar duplicados

#REsumen de objetos
summary(tp_1)
## Planar point pattern:  87 points
## Average intensity 4.939097e-08 points per square unit
## 
## Coordinates are given to 2 decimal places
## i.e. rounded to the nearest multiple of 0.01 units
## 
## Window: polygonal boundary
## single connected closed polygon with 4 vertices
## enclosing rectangle: [540824.4, 574019.5] x [2668404.9, 2721468.6] units
##                      (33200 x 53060 units)
## Window area = 1761460000 square units
## Fraction of frame area: 1
summary(tp_2)
## Planar point pattern:  87 points
## Average intensity 7.845607e-08 points per square unit
## 
## Coordinates are given to 2 decimal places
## i.e. rounded to the nearest multiple of 0.01 units
## 
## Window: polygonal boundary
## single connected closed polygon with 11 vertices
## enclosing rectangle: [540824.4, 574019.5] x [2668404.9, 2721468.6] units
##                      (33200 x 53060 units)
## Window area = 1108900000 square units
## Fraction of frame area: 0.63
summary(tp_3)
## Planar point pattern:  87 points
## Average intensity 6.875925e-08 points per square unit
## 
## Coordinates are given to 2 decimal places
## i.e. rounded to the nearest multiple of 0.01 units
## 
## Window: polygonal boundary
## single connected closed polygon with 11 vertices
## enclosing rectangle: [539682.7, 575141.3] x [2666799.4, 2723481.4] units
##                      (35460 x 56680 units)
## Window area = 1265280000 square units
## Fraction of frame area: 0.63
#Mapa de Calor
par(mfrow = c(1,2))
d_gau <- density(tp_1,  sigma = 1500) # Kernel gaussiano (más suave)
d_epa <- density(tp_1,  sigma = 1500, kernel = "epanechnikov")
plot(d_gau)
plot(d_epa)