---
title: "Verifying the installation"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Verifying the installation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(R2camtrapdp)
```

# Overview

This vignette shows how to check that `R2camtrapdp` works on your machine. It
converts the example data shipped with the package into every supported
Camtrap DP release and variant, and validates each result:

| Variant | Camtrap DP release | Example data |
|---|---|---|
| camera trap | 1.0, 1.0.1, 1.0.2 | `Idep`, `Iobs` |
| bioacoustics | 1.0.2 | `Adep`, `Aobs` |

Each package is checked twice: in R (schema constraints, primary and foreign
keys, required metadata) and with the Python Frictionless validator, the
reference validator for Camtrap DP. Every check should report no issues.

The same steps are run by the package's automated tests
(`tests/testthat/test-verify-versions.R`), so you can also run them with
`devtools::test()` from a copy of the source repository.

**Requirements.** Steps 2 to 4 download the official schemas, so they need
internet access. Step 4 also needs Python with the `frictionless` package
(`pip install frictionless`). Step 1 runs offline. The chunks that need internet
access or Python are not evaluated when this vignette is built.

# 1. Build the tables offline

The table constructors run without internet access. This confirms that the
package and its dependencies are installed correctly.

```{r}
deployments <- create_deployments(
  deploymentID         = Idep$deploymentID,
  longitude            = Idep$longitude,
  latitude             = Idep$latitude,
  deploymentStart_date = Idep$startDate,
  deploymentStart_time = Idep$startTime,
  deploymentEnd_date   = Idep$endDate,
  deploymentEnd_time   = Idep$endTime)
nrow(deployments) == nrow(Idep)
```

# 2. Define the conversions

The two functions below build a complete data package from the example data.
`build_camera_package()` takes the Camtrap DP release as its argument;
`build_acoustic_package()` targets the bioacoustics variant of release 1.0.2.

The `taxonomic` metadata is filled directly with the observed scientific names.
In real use, `set_taxon()` looks up the `taxonID` of each name with `taxadb`, but
that requires a one-time download of the taxonomic database, which is not needed
to verify the installation.

```{r, eval = FALSE}
add_example_metadata <- function(dp, observations, captureMethod, observationLevel,
                                 samplingDesign) {
  dp$add_contributors(data.frame(title = "Example contributor", role = "contact"))
  dp$set_project(title = "Installation check", samplingDesign = samplingDesign,
                 captureMethod = captureMethod, individualAnimals = FALSE,
                 observationLevel = observationLevel)
  dp$set_st()
  dp$taxonomic <- lapply(sort(unique(stats::na.omit(observations$scientificName))),
                         function(x) list(scientificName = x))
  dp$update_created()
  invisible(dp)
}

build_camera_package <- function(version) {
  deployments <- create_deployments(
    deploymentID         = Idep$deploymentID,
    longitude            = Idep$longitude,
    latitude             = Idep$latitude,
    locationID           = Idep$locationID,
    deploymentStart_date = Idep$startDate,
    deploymentStart_time = Idep$startTime,
    deploymentEnd_date   = Idep$endDate,
    deploymentEnd_time   = Idep$endTime,
    cameraID             = Idep$cameraID,
    cameraModel          = Idep$cameraModel,
    cameraDelay          = Idep$Delay,
    cameraHeight         = Idep$Height,
    baitUse              = Idep$bait,
    setupBy              = Idep$setupBy)

  mediaID <- paste(Iobs$institutionCode, Iobs$collectionCode, Iobs$locationID,
                   as.numeric(factor(Iobs$filename)), sep = "_")
  media <- create_media(
    mediaID        = mediaID,
    deploymentID   = Iobs$deploymentID,
    timestamp_date = Iobs$date,
    timestamp_time = Iobs$time,
    filePath       = "Image",
    filePublic     = TRUE,
    fileMediatype  = paste0("image/", tolower(tools::file_ext(Iobs$filename))),
    captureMethod  = "activityDetection",
    fileName       = Iobs$filename)

  observations <- create_observations(
    observationID             = paste(mediaID, Iobs$obsID, sep = "_"),
    deploymentID              = Iobs$deploymentID,
    eventID                   = Iobs$eventID,
    eventStart                = Iobs$eventStart,
    eventEnd                  = Iobs$eventEnd,
    observationLevel          = "event",
    observationType           = ifelse(Iobs$object == "hito", "human",
                                ifelse(Iobs$object == "none", "blank",
                                ifelse(Iobs$object == "unidentifiable", "unknown", "animal"))),
    scientificName            = ifelse(is.na(Iobs$genus), Iobs$class,
                                       paste(Iobs$genus, Iobs$species)),
    count                     = Iobs$individualCount,
    classificationMethod      = "human",
    classificationProbability = 1)

  dp <- R6_CamtrapDP$new(version = version)
  dp$set_deployments(deployments, validate = FALSE)
  dp$set_media(media, validate = FALSE)
  dp$set_observations(observations, validate = FALSE)
  add_example_metadata(dp, observations, captureMethod = "activityDetection",
                       observationLevel = "event", samplingDesign = "simpleRandom")
}

acoustic_base <- "https://raw.githubusercontent.com/camera-traps/bioacoustics/main/camtrap-dp/1.0.2/%s"

build_acoustic_package <- function() {
  dp <- R6_CamtrapDP$new(version = "1.0.2")
  dp$set_properties(
    version     = "1.0.2",
    profile     = sprintf(acoustic_base, "camtrap-dp-profile-acoustic.json"),
    schema_urls = list(
      deployments  = sprintf(acoustic_base, "deployments-table-schema-acoustic.json"),
      media        = sprintf(acoustic_base, "media-table-schema-acoustic.json"),
      observations = sprintf(acoustic_base, "observations-table-schema-acoustic.json")))

  deployments <- data.frame(
    deploymentID    = Adep$deploymentID,
    latitude        = Adep$latitude,
    longitude       = Adep$longitude,
    locationID      = Adep$locationID,
    deploymentStart = as.POSIXct(paste(Adep$startDate, Adep$startTime), tz = "Asia/Tokyo"),
    deploymentEnd   = as.POSIXct(paste(Adep$endDate, Adep$endTime), tz = "Asia/Tokyo"),
    deviceID        = Adep$deviceID,
    deviceModel     = Adep$deviceModel,
    setupBy         = Adep$setupBy)

  files <- Aobs[!duplicated(Aobs$filename), ]
  media <- data.frame(
    mediaID       = files$filename,
    deploymentID  = files$deploymentID,
    timestamp     = as.POSIXct(paste(files$date, files$time), tz = "Asia/Tokyo"),
    filePath      = file.path("audio", files$filename),
    filePublic    = TRUE,
    fileMediatype = paste0("audio/", tolower(tools::file_ext(files$filename))),
    duration      = files$duration)
  media <- merge(media, Adep[, c("deploymentID", "samplingFrequency", "bitDepth", "channels")],
                 by = "deploymentID", all.x = TRUE)

  observations <- data.frame(
    observationID    = paste(Aobs$deploymentID, Aobs$eventID, Aobs$obsID, sep = "_"),
    deploymentID     = Aobs$deploymentID,
    mediaID          = Aobs$filename,
    eventStart       = as.POSIXct(Aobs$eventStart, tz = "Asia/Tokyo"),
    eventEnd         = as.POSIXct(Aobs$eventEnd, tz = "Asia/Tokyo"),
    observationLevel = "media",
    observationType  = ifelse(Aobs$object == "none", "blank",
                       ifelse(Aobs$object == "hito", "human", "animal")),
    scientificName   = ifelse(is.na(Aobs$genus), Aobs$class, paste(Aobs$genus, Aobs$species)),
    count            = Aobs$individualCount,
    frequencyLow     = Aobs$frequencyLow,
    frequencyHigh    = Aobs$frequencyHigh)

  dp$set_deployments(deployments, validate = FALSE)
  dp$set_media(media, validate = FALSE)
  dp$set_observations(observations, validate = FALSE)
  add_example_metadata(dp, observations, captureMethod = "recordingSchedule",
                       observationLevel = "media", samplingDesign = "systematicRandom")
}
```

# 3. Check every release and variant in R

```{r, eval = FALSE}
packages <- list(
  "camera trap 1.0"    = build_camera_package("1.0"),
  "camera trap 1.0.1"  = build_camera_package("1.0.1"),
  "camera trap 1.0.2"  = build_camera_package("1.0.2"),
  "bioacoustics 1.0.2" = build_acoustic_package())

sapply(packages, function(dp) {
  ctdp_is_valid(dp$validate(relations = TRUE, metadata = TRUE, summarize = FALSE))
})
#>    camera trap 1.0  camera trap 1.0.1  camera trap 1.0.2 bioacoustics 1.0.2
#>               TRUE               TRUE               TRUE               TRUE
```

Release 1.0 emits a warning that its official profile contains a malformed
internal `$ref`. This is an upstream issue; `validate_frictionless()` works
around it automatically, and 1.0.1 or later is recommended for new data.

# 4. Validate every package with Frictionless

`validate_frictionless()` writes each package to a temporary directory and runs
the Python Frictionless validator on it. Set `python` to the interpreter that
has `frictionless` installed.

```{r, eval = FALSE}
python <- "python"

sapply(names(packages), function(nm) {
  path <- file.path(tempdir(), gsub(" ", "-", nm))
  issues <- packages[[nm]]$validate_frictionless(directory = path, python = python,
                                                 summarize = FALSE)
  ctdp_is_valid(issues)
})
#>    camera trap 1.0  camera trap 1.0.1  camera trap 1.0.2 bioacoustics 1.0.2
#>               TRUE               TRUE               TRUE               TRUE
```

If a result is `FALSE`, print the issue table (for example
`packages[["camera trap 1.0.2"]]$validate_frictionless(directory = path, python = python)`)
to see the file, field, row, violated rule and offending value of each problem.
The most common causes are a missing Python `frictionless` package and blocked
access to `raw.githubusercontent.com`, from where the schemas are downloaded.

# Running the automated tests

From a copy of the source repository, the same checks run with:

```{r, eval = FALSE}
Sys.setenv(R2CAMTRAPDP_PYTHON = "python")  # interpreter with 'frictionless'
devtools::test()
```

The tests that need internet access are skipped on CRAN and when offline, and
the Frictionless tests are skipped when no Python interpreter with
`frictionless` is found.
