Skip to contents

Writes, in one folder, everything an occupancy model with false positives needs from a passive acoustic survey: the occasions, the classifier scores, the reviewed clips with their sampling design and, optionally, covariates of the occasions and posterior draws of a Bayesian calibration. The folder follows the sheepdog-occupancy schema (version 1.5), described in vignette("crywolf-integration"); the crywolf package reads it, but any software can, since every table is a plain CSV file (the calibration draws are a Parquet file).

Usage

export_occupancy_data(
  output_dir,
  detections,
  recordings = NULL,
  validation = NULL,
  fit = NULL,
  sites = NULL,
  occasion_covariates = NULL,
  calibration_keys = NULL,
  occasion_unit = c("file", "minute"),
  recording_duration = NULL,
  min_confidence = 0.1,
  dawn_hour = 12,
  species = NULL,
  n_draws = 100,
  grid_step = 0.01,
  seed = 2026,
  n_versions = NULL,
  rule = c("sample", "threshold"),
  p_min = 0.95,
  covariate_scaling = NULL,
  audio_pattern = "\\.(wav|flac|mp3)$",
  remap_from = NULL,
  remap_to = NULL,
  min_verified = 10,
  candidates = NULL,
  window_step = 3,
  classifier = NULL,
  overwrite = FALSE
)

Arguments

output_dir

Character scalar, path to the folder to write. Created if needed.

detections

A data frame of predictions, one row per BirdNET prediction, as returned by read_selection_tables() (columns site, species_code, confidence, begin_path and file_offset).

recordings

NULL, a data frame (one row per recording) or a character scalar, path to a CSV file: the list of all recordings, with the columns site and source_audio, as in select_clips(). NULL lists the audio files in the folders of the recordings that have predictions, which then must be reachable (see remap_from).

validation

NULL, a character vector of paths or a data frame (one row per reviewed clip): reviewed clips, without those with an inherited verdict (see select_clips()): paths to validation_by_clip.csv files (output of post_validation()) or a data frame with their columns, e.g. from read_validation_tables() or consensus_verdicts(). NULL writes no validation tables.

fit

NULL or a brmsfit from fit_calibration() with engine = "brms", for calibration_draws.parquet.

sites

NULL or a data frame of site covariates, one row per site, with a site column.

occasion_covariates

NULL or a data frame of covariates of the occasions (e.g. temperature or the month), with site and either occasion_id or source_audio (plus start, in s, for minute occasions). One row per occasion; occasions without a row get NA. Columns named like those of occasions.csv are refused.

calibration_keys

NULL or character vector, grouping variables of the calibration model, besides site and species, that vary between occasions (see Calibration keys). Only used with fit.

occasion_unit

Character scalar, the occasion of the occupancy model: "file" (a recording) or "minute". Use the value of the clip extraction, so that the occasion_id of the reviewed clips match.

recording_duration

NULL or numeric scalar, length of the recordings (s). Needed for minute occasions unless the 'av' package can read the files.

min_confidence

Numeric scalar in [0, 1]. Predictions below this confidence are not written; it is also the lower end of the grid of the calibration draws. Use the min_confidence of the BirdNET run or higher.

dawn_hour

Numeric scalar in [0, 24]. Recordings that start before this hour belong to the night before.

species

NULL or character vector. Restrict to these short species codes (the last part of species_code, e.g. "boa-ran"). NULL keeps all.

n_draws

Integer scalar >= 1, number of posterior draws of the calibration.

grid_step

Numeric scalar > 0, step of the grid of scores of the calibration draws.

seed

Integer scalar, seed of the choice of draws and, with n_versions, of the versions of the detections (rule = "sample"). The global random number generator is left as it was.

n_versions

NULL or integer scalar >= 1, number of versions of the detections to write to occasion_draws.parquet, from the first calibration draws. Without continuous covariates, occasion_draws() is called on the folder. With them, the versions are always written, and NULL means one per calibration draw (n_draws).

rule, p_min

Character scalar ("sample" or "threshold") and numeric scalar in [0, 1]: rule of the versions, as in occasion_draws().

covariate_scaling

NULL or a list named by covariate, each element a numeric vector with center and scale, recording how each continuous covariate of the calibration was standardised before the model was fitted, e.g. list(temp = c(center = 22.4, scale = 3.1)) for (temp_raw - 22.4) / 3.1. It is written to schema.json so that a reader can map the covariate back; the values of occasion_covariates must already be on the scale of the model.

audio_pattern

Character scalar, regular expression for the audio files listed when recordings is NULL.

remap_from, remap_to

NULL or character scalars. Replace the prefix remap_from of the begin_path paths by remap_to, e.g. "N:/" and "/Volumes/Arara/". Backslashes are turned into forward slashes first.

min_verified

Integer scalar. Species with predictions but fewer than this number of reviewed detection clips (positive or negative), or without any positive or any negative clip, are named in a warning: their false-positive rate will rest on the other species (a community model) or on the prior. The default is a floor, not a sample size calculation. Only used with validation.

candidates

NULL, a character scalar (path) or a data frame: the candidates.csv of the first round of a "random_detections" design. It gives the stratum of each occasion and, in schema.json, the threshold and the strata of the draw. NULL looks for it in the folders of validation; without it, stratum is empty unless validation has that column, as after combine_rounds(). Only used with validation.

window_step

Numeric scalar > 0, time between the starts of consecutive windows of the classifier (s), for n_windows: 3 for BirdNET without overlap.

classifier

NULL or character scalar, label of the classifier, recorded in schema.json.

overwrite

Logical scalar. If TRUE, replace an existing export in output_dir.

Value

Invisibly, a list with the tables written (tibbles) and the schema (a list).

Tables

  • occasions.csv: one row per occasion (a recording, or a minute of a recording), with or without predictions, with its number of windows of the classifier (n_windows, NA when the length of the occasion is unknown), followed by the columns of occasion_covariates and of the calibration keys.

  • detections.csv: one row per prediction with confidence >= min_confidence.

  • scores.csv: one row per occasion x species with at least one prediction: the highest score and the number of predictions. Occasion x species pairs absent from this table had no prediction >= min_confidence (a censored score).

  • validation.csv: the reviewed clips of the "top", "random_detections", "directed_pps" (from select_directed()) and "score_bands" designs, with their verdict, inclusion probability, round and stratum, what a negative verdict covers (review_scope) and, for negative or uncertain clips, the identity given by the reviewer (identity, identity_certainty; see join_identities()) (only when validation is given).

  • recordings_verified.csv: the occasions annotated by ear in the "random_recordings" design, with the state of each occasion (only when validation holds such clips).

  • sites.csv: one row per site, with the covariates of sites.

  • calibration_draws.parquet: posterior draws of P(TP) on a grid of scores for each site x species with predictions, and for each level of the calibration_keys found among the occasions of the site (only when fit is given; needs the 'arrow' package).

  • occasion_draws.parquet: versions of the detections over the calibration draws, as written by occasion_draws() (only with n_versions, or with a calibration on continuous covariates).

  • schema.json: name and version of the schema, the settings of the export, the lists of sites and species and the number of rows of each table.

Calibration keys. A calibration may depend on a property of the occasion besides site and species, such as the month of the recording (tp ~ logit_conf + (1 | month)). Name such grouping variables in calibration_keys: each becomes a text column of occasions.csv and of calibration_draws.parquet, so that a reader matches each prediction to the draws of its occasion. A key must be a column of occasion_covariates, except "month", which is derived from the recording date (YYYYMM) when not given. Levels absent from the calibration data are drawn as new levels of the group (brms sample_new_levels = "uncertainty"); occasions without a value of a key are reported, since their predictions cannot be scored.

Continuous covariates (schema 1.3). A calibration may also depend on a continuous covariate of the occasion, such as the temperature of the night or an acoustic index (tp ~ logit_conf + temp). Numeric variables of the model besides logit_conf are taken as such covariates; each must be a column of occasion_covariates, on the scale used in the model. A grid of scores would then need one point per value of the covariate, so P(TP) is computed for each prediction instead, and the versions of the detections are drawn here, by the rules of occasion_draws(), and written to occasion_draws.parquet; calibration_draws.parquet is not written. schema.json records the covariates (calibration$covariates), their range in the calibration data, the scaling given in covariate_scaling, the rule, the seed and the number of versions. Occasions with predictions but without a value of a covariate are not scored (NA), and values outside the range of the calibration data are reported. To change the rule or the number of versions, export again; occasion_draws() refuses such a folder.

Two checks guard against inputs that would inflate the detections: predictions repeating the site, recording, offset and species of another (e.g. a selection table read twice) are dropped with a warning, and a warning is given when most occasion x species with several predictions have the same score in all of them, a sign that one score per occasion was copied to several rows.

A clip verdict and the state of an occasion are kept apart on purpose: a positive clip proves that the species called in its occasion, but a negative clip only says that this prediction was a false positive (the species may still have called, with a lower score). A recording annotated by ear gives the state of the whole occasion.

See also

vignette("crywolf-integration") for the columns of each table.

Examples

ex <- system.file("extdata", "example", package = "sheepdog")
det <- read_selection_tables(file.path(ex, "birdnet"))
#> 4 combined table(s) and 0 per-audio table(s) found in 4 folder(s):
#>   - /home/runner/work/_temp/Library/sheepdog/extdata/example/birdnet/ARA: BirdNET_SelectionTable.txt
#>   - /home/runner/work/_temp/Library/sheepdog/extdata/example/birdnet/BAI: BirdNET_SelectionTable.txt
#>   - /home/runner/work/_temp/Library/sheepdog/extdata/example/birdnet/NHE: BirdNET_SelectionTable.txt
#>   - /home/runner/work/_temp/Library/sheepdog/extdata/example/birdnet/XAR: BirdNET_SelectionTable.txt
#> 7553 predictions read from 4 site(s).
out_dir <- file.path(tempdir(), "occupancy")
out <- export_occupancy_data(
  out_dir, det,
  recordings = file.path(ex, "recordings.csv"),
  validation = list.files(file.path(ex, "validation"), full.names = TRUE),
  classifier = "BirdNET", overwrite = TRUE
)
#> Export written to /tmp/RtmpnYqzB0/occupancy: occasions, detections, scores, validation, sites.
vapply(out$tables, nrow, integer(1))
#>  occasions detections     scores validation      sites 
#>        354       7553       2298       2467          4 
list.files(out_dir)
#> [1] "detections.csv" "occasions.csv"  "schema.json"    "scores.csv"    
#> [5] "sites.csv"      "validation.csv"
if (FALSE) { # interactive() && requireNamespace("brms", quietly = TRUE)
# With a Bayesian calibration, the export also holds its posterior
# draws. Fitting compiles a Stan model, which takes minutes, so this
# part runs only in interactive sessions.
val <- read_validations(list.files(file.path(ex, "validation"),
                                   full.names = TRUE))
f <- tp ~ logit_conf + (1 | species)
fit <- fit_calibration(val, f, engine = "brms",
                       prior = calibration_prior(f, val),
                       chains = 4, iter = 2000, seed = 1, refresh = 0)
export_occupancy_data(
  out_dir, det,
  recordings = file.path(ex, "recordings.csv"),
  validation = list.files(file.path(ex, "validation"), full.names = TRUE),
  fit = fit, n_draws = 100, overwrite = TRUE
)
}