###Cargar paquetes

library(grateful) # Facilitate Citation of R Packages
## Warning: package 'grateful' was built under R version 4.4.3
library(readxl) # Read Excel Files
## Warning: package 'readxl' was built under R version 4.4.3
library(readr) 
## Warning: package 'readr' was built under R version 4.4.3
library(sf) # Simple Features for R
## Warning: package 'sf' was built under R version 4.4.3
## Linking to GEOS 3.13.0, GDAL 3.10.1, PROJ 9.5.1; sf_use_s2() is TRUE
library(mapview) # Interactive Viewing of Spatial Data in R
## Warning: package 'mapview' was built under R version 4.4.3
library(readr) # No used functions found
library(camtrapR) # Camera Trap Data Management and Preparation of Occupancy and Spatial Capture-Recapture Analyses 
## Warning: package 'camtrapR' was built under R version 4.4.3
library(unmarked) # hierarchical models of animal occurrence and abundance 
## Warning: package 'unmarked' was built under R version 4.4.3
library(DT) # datatable
## Warning: package 'DT' was built under R version 4.4.3
library(kableExtra) # Construct Complex Table with 'kable' and Pipe Syntax
## Warning: package 'kableExtra' was built under R version 4.4.3
library(tidyverse) # Easily Install and Load the 'Tidyverse'
## Warning: package 'tidyverse' was built under R version 4.4.3
## Warning: package 'ggplot2' was built under R version 4.4.3
## Warning: package 'tidyr' was built under R version 4.4.3
## Warning: package 'dplyr' was built under R version 4.4.3
## Warning: package 'lubridate' was built under R version 4.4.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.0     ✔ purrr     1.0.2
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   4.0.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter()     masks stats::filter()
## ✖ dplyr::group_rows() masks kableExtra::group_rows()
## ✖ dplyr::lag()        masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(glue)
library(terra)
## terra 1.7.83
## 
## Adjuntando el paquete: 'terra'
## 
## The following object is masked from 'package:glue':
## 
##     trim
## 
## The following object is masked from 'package:tidyr':
## 
##     extract
library(elevatr)
## Warning: package 'elevatr' was built under R version 4.4.3
## elevatr v0.99.0 NOTE: Version 0.99.0 of 'elevatr' uses 'sf' and 'terra'.  Use 
## of the 'sp', 'raster', and underlying 'rgdal' packages by 'elevatr' is being 
## deprecated; however, get_elev_raster continues to return a RasterLayer.  This 
## will be dropped in future versions, so please plan accordingly.

###Abrir los datos que obtuvimos de Wildlifeinsights

cameras<- read_csv("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/DatosRisaralda/data/cameras.csv")
## Rows: 131 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (4): camera_name, make, model, serial_number
## dbl (3): project_id, camera_id, year_purchased
## 
## ℹ 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.
images <- read_csv("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/DatosRisaralda/data/images_2000367.csv")
## Rows: 17390 Columns: 28
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (16): deployment_id, image_id, filename, location, identified_by, wi_ta...
## dbl   (4): project_id, is_blank, number_of_objects, cv_confidence
## lgl   (7): uncertainty, animal_recognizable, individual_id, individual_anima...
## dttm  (1): timestamp
## 
## ℹ 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.
deployments <- read_csv("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/DatosRisaralda/data/deployments.csv")
## Rows: 162 Columns: 29
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (15): deployment_id, placename, bait_type, feature_type, feature_type_m...
## dbl   (5): project_id, longitude, latitude, camera_id, quiet_period
## lgl   (7): bait_description, height_other, orientation_other, plot_treatment...
## dttm  (2): start_date, end_date
## 
## ℹ 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.
View(cameras)

#enlazar 3 tablas

data1 <-  cameras |> left_join(deployments) # join first two tables
## Joining with `by = join_by(project_id, camera_id, camera_name)`
by <- join_by("deployment_id") #  join by "Deployment ID"
# join by "Deployment ID" and # lets put together genus and species
data <- left_join(data1, images, by) |> 
  filter(subproject_name=="Ucumari") |> 
  mutate(binomial=paste(genus, species) )

##hacer mapa, con internet me puedo acercar y ver bien los datos

datos_distinct <- data |> distinct(longitude, latitude, deployment_id, camera_name) |> as.data.frame()


projlatlon <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

datos_sf <-  st_as_sf(x = datos_distinct,
                         coords = c("longitude", 
                                    "latitude"),
                         crs = projlatlon)

mapview(datos_sf)

##Extraer covariables de sitio con una imagen de satelite

# let make a 3K buffer around the points
datos_sf_buff  <- st_buffer(datos_sf, 3000)
# get elevation raster from AWS using the 3K buffer
elevation_detailed <- rast(get_elev_raster(datos_sf_buff, z = 9, clip="bbox", neg_to_na=TRUE))
## Mosaicing & Projecting
## Clipping DEM to bbox
## Note: Elevation units are in meters.
slope_map<-terrain(elevation_detailed, v="slope", unit='degrees', neighbors=8)
aspect_map<-terrain(elevation_detailed, v="aspect", unit='degrees', neighbors=8)
roughness_map <- terrain(elevation_detailed, v = c("roughness"))


# Load forest map... it is huge!
# forest_type <- rast("C:/CodigoR/CameraTrapCesar/posts/2026-01-01-wildlifeinsights-to-detections/raster/2017_coverage_lclu.tif") 

# cut the huge forest map to 3K buffer
# forest_type_cropped <- crop(forest_type, elevation_detailed)

# lets remove the huge map from memory to save RAM
# rm(forest_type)


per_tree_cov <- rast("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/MOD44B_Perc_TreeCov_2017_065.tif")

# cut the huge tree cover map to 3K buffer
per_tree_cov_cropped <- crop(per_tree_cov, elevation_detailed)

# lets remove the huge map from memory to save RAM
rm(per_tree_cov)

# Forest Integrity Index
FLII2017 <- rast("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/FLII_2017.tif")
# cut the huge FLII map to 3K buffer
FLII2017_cropped <- crop(FLII2017, elevation_detailed)

# lets remove the huge map from memory to save RAM
rm(FLII2017)


# extract covs using points (datos_sf) and add to sites
# covs <- cbind(sites, terra::extract(SiteCovsRast, sites))

elev <- terra::extract(elevation_detailed, datos_sf)
# forest_typ <- terra::extract(forest_type_cropped, datos_sf)
tree_cov <- terra::extract(per_tree_cov_cropped, datos_sf)
slope <- terra::extract(slope_map, datos_sf)
aspect <- terra::extract(aspect_map, datos_sf)
roughness <- terra::extract(roughness_map, datos_sf)
flii <- terra::extract(FLII2017_cropped, datos_sf)

#### make a table of cameras dropping geometry
sites <- datos_sf %>%
  mutate(
    lat = st_coordinates(.)[, 1],
    lon = st_coordinates(.)[, 2]
  ) %>%
  st_drop_geometry() |>
  as.data.frame()

### Add the covariates to the table
# remove decimals convert to factor
# sites$forest_typ <- factor(forest_typ[,2])
sites$elev <-  elev[,2]
sites$tree_cov <-  tree_cov[,2]
sites$slope <-  slope[,2]
sites$aspect <-  aspect[,2]
sites$roughness <-  roughness[,2]
sites$flii <-  flii[,2]

mapview(per_tree_cov_cropped)+ mapview(elevation_detailed) + mapview(datos_sf)

###Estas Covariables hacen un buffer alrededor de los puntos, necesita concexión a internet

# filter first year and make uniques to get a table of cameras and operation dates

CToperation <- data |> 
  # filter(samp_year == 2021) |> # multi-season data
  group_by(deployment_id) |>
  mutate(minStart = min(start_date), maxEnd = max(end_date)) |>
  distinct(longitude, latitude, minStart, maxEnd) |> #, samp_year) |>
  ungroup() |>
  as.data.frame()

# camera operation matrix for
# multi-season data. Season1
camop <- cameraOperation(
  CTtable = CToperation, # Tabla de operación
  stationCol = "deployment_id", # Columna que define la estación
  setupCol = "minStart", # Columna fecha de colocación
  retrievalCol = "maxEnd", # Columna fecha de retiro
  # sessionCol = "samp_year", # multi-season column
  # hasProblems= T, # Hubo fallos de cámaras
  dateFormat = "%Y-%m-%d"
 ) # , #, # Formato de las fechas
## Warning: There are spaces in CTtable[, setupCol], but not in dateFormat
## Warning: There are spaces in CTtable[, retrievalCol], but not in dateFormat
# cameraCol="CT")
# sessionCol= "samp_year")

# Plot camera operation as image
image(t(camop))

#que veo ahi la diferencia en los tiempos de muestreo etre las camaras desde que las coloque, las rayas que estan en blanco y se extienden es porque no tomaron datos, entonces hay que

# Generar las historias de detección ---------------------------------------
## remove plroblem species
# ind <- which(datos_PCF$Species=="Marmosa sp.")
# datos_PCF <- datos_PCF[-ind,]


DetHist_list_UCU <- lapply(unique(data$binomial), FUN = function(x) {
  detectionHistory(
    recordTable = data, # Tabla de registros
    camOp = camop, # Matriz de operación de cámaras
    stationCol = "deployment_id",
    speciesCol = "binomial",
    recordDateTimeCol = "timestamp",
    recordDateTimeFormat = "%Y-%m-%d %H:%M:%S",
    species = x, # la función reemplaza x por cada una de las especies
    occasionLength = 1, # Colapso de las historias a días
    day1 = "survey",#  "station", # inicie en la fecha de cada survey
    datesAsOccasionNames = FALSE, # pone fecha en columna
    includeEffort = TRUE,
    scaleEffort = FALSE,
    unmarkedMultFrameInput = TRUE,
    timeZone = "America/Bogota"
  )
})
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 6 stations there were records after camera operation date range:  CT-UC-02-08, CT-UC-01-26, CT-UC-01-17, CT-UC-01-15, CT-UC-01-08, CT-UC-01-07
## Warning: 
## 
## 17 records (out of 610) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-08: 2017-03-18 06:58:29
## CT-UC-02-08: 2017-03-18 07:44:32
## CT-UC-02-08: 2017-03-18 13:53:44
## CT-UC-01-26: 2017-01-27 03:13:18
## CT-UC-01-26: 2017-01-27 03:13:27
## CT-UC-01-26: 2017-01-27 03:13:34
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records before camera operation date range:  CT-UC-01-03
## Warning: 
## At 6 stations there were records after camera operation date range:  CT-UC-02-15, CT-UC-01-26, CT-UC-01-25, CT-UC-01-16, CT-UC-01-11, CT-UC-01-07
## Warning: 91 records (out of 6562) were removed because they were taken before day1 (if a date was specified),  within the buffer period, or before occasionStartTime on the 1st day, e.g.:
## CT-UC-01-03: 2017-01-03 18:36:58
## CT-UC-01-03: 2017-01-03 18:37:01
## CT-UC-01-03: 2017-01-03 18:37:00
## CT-UC-01-03: 2017-01-03 18:37:01
## CT-UC-01-03: 2017-01-03 18:37:03
## CT-UC-01-03: 2017-01-03 18:37:03
## Warning: 
## 
## 116 records (out of 6562) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-15: 2017-03-20 01:45:54
## CT-UC-02-15: 2017-03-20 01:45:56
## CT-UC-02-15: 2017-03-20 01:46:00
## CT-UC-02-15: 2017-03-20 01:48:20
## CT-UC-02-15: 2017-03-20 01:46:02
## CT-UC-01-26: 2017-01-27 04:57:05
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 3 stations there were records after camera operation date range:  CT-UC-02-21, CT-UC-01-26, CT-UC-01-07
## Warning: 
## 
## 28 records (out of 292) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-21: 2017-03-19 21:20:13
## CT-UC-02-21: 2017-03-19 21:20:28
## CT-UC-02-21: 2017-03-19 21:20:37
## CT-UC-02-21: 2017-03-19 21:20:43
## CT-UC-02-21: 2017-03-19 21:21:13
## CT-UC-02-21: 2017-03-19 21:39:23
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-02-18
## Warning: 
## 
## 3 records (out of 75) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-18: 2017-03-18 23:51:28
## CT-UC-02-18: 2017-03-18 23:55:42
## CT-UC-02-18: 2017-03-18 23:55:43
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-01-08
## Warning: 
## 
## 1 records (out of 255) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-01-08: 2017-01-27 11:41:08
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-01-13
## Warning: 
## 
## 1 records (out of 217) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-01-13: 2017-01-27 11:58:13
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-02-08
## Warning: 
## 
## 4 records (out of 65) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-08: 2017-03-18 06:41:00
## CT-UC-02-08: 2017-03-18 06:58:37
## CT-UC-02-08: 2017-03-18 06:58:39
## CT-UC-02-08: 2017-03-18 06:58:44
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 5 stations there were records after camera operation date range:  CT-UC-02-13, CT-UC-01-31, CT-UC-01-13, CT-UC-01-12, CT-UC-01-10
## Warning: 
## 
## 21 records (out of 34) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-13: 2017-03-18 10:25:14
## CT-UC-01-31: 2017-01-27 09:48:47
## CT-UC-01-31: 2017-01-27 09:48:49
## CT-UC-01-31: 2017-01-27 09:48:52
## CT-UC-01-13: 2017-01-27 07:53:15
## CT-UC-01-13: 2017-01-27 07:53:23
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-02-10
## Warning: 
## 
## 4 records (out of 78) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-02-10: 2017-03-18 08:35:37
## CT-UC-02-10: 2017-03-18 13:14:59
## CT-UC-02-10: 2017-03-18 13:15:02
## CT-UC-02-10: 2017-03-18 13:15:08
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 
## At 1 stations there were records after camera operation date range:  CT-UC-01-07
## Warning: 
## 
## 1 records (out of 3) were removed because they were taken after the end of the last occasion, e.g.:
## CT-UC-01-07: 2017-01-29 01:31:09
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
## Warning: 'unmarkedMultFrameInput' is defined, but I cannot find session IDs in
## the rownames of camOp. Check the row names format and maybe run
## camtrapR:::deparseCamOpRownames(camOp) to see if it can be interpreted
# names
names(DetHist_list_UCU) <- unique(data$binomial)

# Finalmente creamos una lista nueva donde estén solo las historias de detección
ylist_UCU <- lapply(DetHist_list_UCU, FUN = function(x) x$detection_history)
# y el esfuerzo de muestreo
effortlist_UCU <- lapply(DetHist_list_UCU, FUN = function(x) x$effort)

### Danta, venado
# which(names(ylist_UCU) == "Tapirus pinchaque")
#> integer(0)
# which(names(ylist_UCU) == "Mazama rufina")
#> [1] 5

###Se obtiene la historia de detección, saca para todas las especies como fueron los registros, si se detecto o no ### Listado de especies extraer

names(DetHist_list_UCU) # name of each list entry
##  [1] "Bos taurus"               "NA NA"                   
##  [3] "Aburria aburri"           "Didelphis marsupialis"   
##  [5] "Tapirus pinchaque"        "Sciurus NA"              
##  [7] "Grallaria NA"             "Eira barbara"            
##  [9] "Mazama rufina"            "Puma concolor"           
## [11] "Leopardus pardalis"       "Dasypus novemcinctus"    
## [13] "Leopardus wiedii"         "Cuniculus taczanowskii"  
## [15] "Nasuella olivacea"        "Penelope perspicax"      
## [17] "Momotus aequatorialis"    "Mustela felipei"         
## [19] "Dasyprocta leporina"      "Nothoprocta pentlandii"  
## [21] "Herpailurus yagouaroundi" "Leptotila NA"            
## [23] "Formicarius analis"       "Formicarius NA"          
## [25] "Canis familiaris"         "Sciurus granatensis"     
## [27] "Columba NA"               "Penelope montagnii"      
## [29] "Nasua nasua"              "Odontophorus columbianus"
## [31] "Turdus NA"                "Leptotila verreauxi"     
## [33] "Odontophorus gujanensis"  "Aramides cajaneus"       
## [35] "Tamandua mexicana"        "Neogale frenata"         
## [37] "Dasyprocta fuliginosa"    "Odontophorus NA"         
## [39] "Tinamus major"            "Bassaricyon neblina"     
## [41] "Odontophorus hyperythrus" "Dasyprocta punctata"     
## [43] "Tinamus NA"               "Momotus momota"          
## [45] "Cyanocorax NA"            "Alouatta seniculus"      
## [47] "Pyroderus scutatus"       "Didelphis virginiana"    
## [49] "Leopardus NA"             "Tremarctos ornatus"      
## [51] "Leopardus tigrinus"       "Didelphis albiventris"   
## [53] "Didelphis NA"
#>  [1] "Bos taurus"               "NA NA"                   
#>  [3] "Aburria aburri"           "Didelphis marsupialis"   
#>  [5] "Tapirus pinchaque"        "Sciurus NA"              
#>  [7] "Grallaria NA"             "Eira barbara"            
#>  [9] "Mazama rufina"            "Puma concolor"           
#> [11] "Leopardus pardalis"       "Dasypus novemcinctus"    
#> [13] "Leopardus wiedii"         "Cuniculus taczanowskii"  
#> [15] "Nasuella olivacea"        "Penelope perspicax"      
#> [17] "Momotus aequatorialis"    "Mustela felipei"         
#> [19] "Dasyprocta leporina"      "Nothoprocta pentlandii"  
#> [21] "Herpailurus yagouaroundi" "Leptotila NA"            
#> [23] "Formicarius analis"       "Formicarius NA"          
#> [25] "Canis familiaris"         "Sciurus granatensis"     
#> [27] "Columba NA"               "Penelope montagnii"      
#> [29] "Nasua nasua"              "Odontophorus columbianus"
#> [31] "Turdus NA"                "Leptotila verreauxi"     
#> [33] "Odontophorus gujanensis"  "Aramides cajaneus"       
#> [35] "Tamandua mexicana"        "Neogale frenata"         
#> [37] "Dasyprocta fuliginosa"    "Odontophorus NA"         
#> [39] "Tinamus major"            "Bassaricyon neblina"     
#> [41] "Odontophorus hyperythrus" "Dasyprocta punctata"     
#> [43] "Tinamus NA"               "Momotus momota"          
#> [45] "Cyanocorax NA"            "Alouatta seniculus"      
#> [47] "Pyroderus scutatus"       "Didelphis virginiana"    
#> [49] "Leopardus NA"             "Tremarctos ornatus"      
#> [51] "Leopardus tigrinus"       "Didelphis albiventris"   
#> [53] "Didelphis NA"

#Ahora tomaremos un dato especiefico para un modelo de danta

y_sp <- ylist_UCU$"Tapirus pinchaque"
head(y_sp)
##             o1 o2 o3 o4 o5 o6 o7 o8 o9 o10 o11 o12 o13 o14 o15 o16 o17 o18 o19
## CT-UC-02-24 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-23 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-22 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-21 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-18 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-17 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
##             o20 o21 o22 o23 o24 o25 o26 o27 o28 o29 o30 o31 o32 o33 o34 o35 o36
## CT-UC-02-24  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-23  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-22  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-21  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-18  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
## CT-UC-02-17  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
##             o37 o38 o39 o40 o41 o42 o43 o44 o45 o46 o47 o48 o49 o50 o51 o52 o53
## CT-UC-02-24  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
## CT-UC-02-23  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
## CT-UC-02-22  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
## CT-UC-02-21  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
## CT-UC-02-18  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
## CT-UC-02-17  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
##             o54 o55 o56 o57 o58 o59 o60 o61 o62 o63 o64 o65 o66 o67 o68 o69 o70
## CT-UC-02-24   0   0   0   0   0   0   0   0   0   0   0   1   0   1   0   0   0
## CT-UC-02-23   0   0   0   1   0   0   0   0   0   0   0   0   0   1   0   0   0
## CT-UC-02-22   1   0   0   0   1   0   0   0   0   0   1   0   0   0   0   0   0
## CT-UC-02-21   0   0   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0
## CT-UC-02-18   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-17   1   0   0   0   1   0   0   0   0   0   0   1   0   0   0   1   0
##             o71 o72 o73 o74 o75 o76 o77 o78 o79 o80 o81 o82 o83 o84 o85 o86 o87
## CT-UC-02-24   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-23   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-22   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-21   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-18   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
## CT-UC-02-17   1   0   0   0   1   0   0   0   1   0   0   0   0   0   0   0   0
##             o88 o89 o90 o91 o92 o93 o94 o95 o96 o97 o98 o99 o100 o101
## CT-UC-02-24   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
## CT-UC-02-23   0   0   0   0   0   0   0   1   0  NA  NA  NA   NA   NA
## CT-UC-02-22   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
## CT-UC-02-21   0   0   1   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
## CT-UC-02-18   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
## CT-UC-02-17   0   0   0   1   0   0  NA  NA  NA  NA  NA  NA   NA   NA
#>             o1 o2 o3 o4 o5 o6 o7 o8 o9 o10 o11 o12 o13 o14 o15 o16 o17 o18 o19
#> CT-UC-02-24 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-23 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-22 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-21 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-18 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-17 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#>             o20 o21 o22 o23 o24 o25 o26 o27 o28 o29 o30 o31 o32 o33 o34 o35 o36
#> CT-UC-02-24  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-23  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-22  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-21  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-18  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#> CT-UC-02-17  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
#>             o37 o38 o39 o40 o41 o42 o43 o44 o45 o46 o47 o48 o49 o50 o51 o52 o53
#> CT-UC-02-24  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#> CT-UC-02-23  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#> CT-UC-02-22  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#> CT-UC-02-21  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#> CT-UC-02-18  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#> CT-UC-02-17  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA   0   0   0   0   0   0
#>             o54 o55 o56 o57 o58 o59 o60 o61 o62 o63 o64 o65 o66 o67 o68 o69 o70
#> CT-UC-02-24   0   0   0   0   0   0   0   0   0   0   0   1   0   1   0   0   0
#> CT-UC-02-23   0   0   0   1   0   0   0   0   0   0   0   0   0   1   0   0   0
#> CT-UC-02-22   1   0   0   0   1   0   0   0   0   0   1   0   0   0   0   0   0
#> CT-UC-02-21   0   0   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0
#> CT-UC-02-18   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-17   1   0   0   0   1   0   0   0   0   0   0   1   0   0   0   1   0
#>             o71 o72 o73 o74 o75 o76 o77 o78 o79 o80 o81 o82 o83 o84 o85 o86 o87
#> CT-UC-02-24   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-23   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-22   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-21   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-18   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
#> CT-UC-02-17   1   0   0   0   1   0   0   0   1   0   0   0   0   0   0   0   0
#>             o88 o89 o90 o91 o92 o93 o94 o95 o96 o97 o98 o99 o100 o101
#> CT-UC-02-24   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
#> CT-UC-02-23   0   0   0   0   0   0   0   1   0  NA  NA  NA   NA   NA
#> CT-UC-02-22   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
#> CT-UC-02-21   0   0   1   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
#> CT-UC-02-18   0   0   0   0   0   0  NA  NA  NA  NA  NA  NA   NA   NA
#> CT-UC-02-17   0   0   0   1   0   0  NA  NA  NA  NA  NA  NA   NA   NA

#leer datos de precipitación

# read de precipitation data
rainfall_total <-  read_csv("C:/Users/valen/OneDrive/Escritorio/Curso fototrampeo/descargaDhime.csv")
## Rows: 757 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): NombreEstacion, Variable, Parametro, Unidad, NivelAprobacion
## dbl  (2): CodigoEstacion, Valor
## dttm (1): Fecha
## 
## ℹ 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.
sampling_start <- min(CToperation$minStart)
Sampling_end <- max(CToperation$maxEnd)

# extracts dates of start and end to match the precipitation dates
rainfall_selected <- rainfall_total |> filter(Fecha >= sampling_start, Fecha<=Sampling_end) 

# put selected precipitation values on columns an repeated 49 times in rows
rainfall_mat <- matrix(rainfall_selected$Valor,
                       nrow=49, ncol=101, byrow=TRUE)

#show table
datatable(head(y_sp))

###leer datos de precipitación con los datos de ocurrencia

library(unmarked)
umf <- unmarkedFrameOccu(y= y_sp, 
                         siteCovs=data.frame(tree_cov=sites$tree_cov, 
                                             elev=sites$elev,
                                             slope=sites$slope,
                                             aspect=sites$aspect,
                                             roughness=sites$roughness,
                                             flii=sites$flii),
                         obsCovs=list(rain=rainfall_mat)
                        )

summary(umf)
## unmarkedFrame Object
## 
## 49 sites
## Maximum number of observations per site: 101 
## Mean number of observations per site: 44.63 
## Sites with at least one detection: 45 
## 
## Tabulation of y observations:
##    0    1 <NA> 
## 1965  222 2762 
## 
## Site-level covariates:
##     tree_cov          elev          slope            aspect        
##  Min.   : 2.00   Min.   :1820   Min.   : 3.792   Min.   :  0.4294  
##  1st Qu.:11.00   1st Qu.:1998   1st Qu.: 7.663   1st Qu.:164.5982  
##  Median :20.00   Median :2127   Median :12.657   Median :199.8469  
##  Mean   :23.71   Mean   :2140   Mean   :13.926   Mean   :206.3143  
##  3rd Qu.:34.00   3rd Qu.:2254   3rd Qu.:17.225   3rd Qu.:255.9186  
##  Max.   :54.00   Max.   :2724   Max.   :32.342   Max.   :359.4761  
##    roughness          flii      
##  Min.   : 40.0   Min.   :6.153  
##  1st Qu.: 75.0   1st Qu.:8.834  
##  Median :111.0   Median :9.364  
##  Mean   :117.4   Mean   :9.029  
##  3rd Qu.:150.0   3rd Qu.:9.626  
##  Max.   :235.0   Max.   :9.865  
## 
## Observation-level covariates:
##       rain       
##  Min.   : 0.000  
##  1st Qu.: 0.000  
##  Median : 3.300  
##  Mean   : 8.904  
##  3rd Qu.:11.200  
##  Max.   :95.200
#> unmarkedFrame Object
#> 
#> 49 sites
#> Maximum number of observations per site: 101 
#> Mean number of observations per site: 44.63 
#> Sites with at least one detection: 45 
#> 
#> Tabulation of y observations:
#>    0    1 <NA> 
#> 1965  222 2762 
#> 
#> Site-level covariates:
#>     tree_cov          elev          slope            aspect        
#>  Min.   : 2.00   Min.   :1820   Min.   : 3.792   Min.   :  0.4294  
#>  1st Qu.:11.00   1st Qu.:1998   1st Qu.: 7.663   1st Qu.:164.5982  
#>  Median :20.00   Median :2127   Median :12.657   Median :199.8469  
#>  Mean   :23.71   Mean   :2140   Mean   :13.926   Mean   :206.3143  
#>  3rd Qu.:34.00   3rd Qu.:2254   3rd Qu.:17.225   3rd Qu.:255.9186  
#>  Max.   :54.00   Max.   :2724   Max.   :32.342   Max.   :359.4761  
#>    roughness          flii      
#>  Min.   : 40.0   Min.   :6.153  
#>  1st Qu.: 75.0   1st Qu.:8.834  
#>  Median :111.0   Median :9.364  
#>  Mean   :117.4   Mean   :9.029  
#>  3rd Qu.:150.0   3rd Qu.:9.626  
#>  Max.   :235.0   Max.   :9.865  
#> 
#> Observation-level covariates:
#>       rain       
#>  Min.   : 0.000  
#>  1st Qu.: 0.000  
#>  Median : 3.300  
#>  Mean   : 8.904  
#>  3rd Qu.:11.200  
#>  Max.   :95.200

###lo que se ve en el plot es donde aparecio la foto de la danta en los dias