Export the data of an occupancy model with false positives
Source:R/export_occupancy.R
export_occupancy_data.RdWrites, 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()(columnssite,species_code,confidence,begin_pathandfile_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 columnssiteandsource_audio, as inselect_clips().NULLlists the audio files in the folders of the recordings that have predictions, which then must be reachable (seeremap_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 (seeselect_clips()): paths tovalidation_by_clip.csvfiles (output ofpost_validation()) or a data frame with their columns, e.g. fromread_validation_tables()orconsensus_verdicts().NULLwrites no validation tables.- fit
NULLor abrmsfitfromfit_calibration()withengine = "brms", forcalibration_draws.parquet.- sites
NULLor a data frame of site covariates, one row per site, with asitecolumn.- occasion_covariates
NULLor a data frame of covariates of the occasions (e.g. temperature or the month), withsiteand eitheroccasion_idorsource_audio(plusstart, in s, for minute occasions). One row per occasion; occasions without a row getNA. Columns named like those ofoccasions.csvare refused.- calibration_keys
NULLor character vector, grouping variables of the calibration model, besidessiteandspecies, that vary between occasions (see Calibration keys). Only used withfit.- occasion_unit
Character scalar, the occasion of the occupancy model:
"file"(a recording) or"minute". Use the value of the clip extraction, so that theoccasion_idof the reviewed clips match.- recording_duration
NULLor 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_confidenceof the BirdNET run or higher.- dawn_hour
Numeric scalar in [0, 24]. Recordings that start before this hour belong to the night before.
- species
NULLor character vector. Restrict to these short species codes (the last part ofspecies_code, e.g."boa-ran").NULLkeeps 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
NULLor integer scalar >= 1, number of versions of the detections to write tooccasion_draws.parquet, from the first calibration draws. Without continuous covariates,occasion_draws()is called on the folder. With them, the versions are always written, andNULLmeans 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 inoccasion_draws().- covariate_scaling
NULLor a list named by covariate, each element a numeric vector withcenterandscale, 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 toschema.jsonso that a reader can map the covariate back; the values ofoccasion_covariatesmust already be on the scale of the model.- audio_pattern
Character scalar, regular expression for the audio files listed when
recordingsisNULL.- remap_from, remap_to
NULLor character scalars. Replace the prefixremap_fromof thebegin_pathpaths byremap_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: thecandidates.csvof the first round of a"random_detections"design. It gives the stratum of each occasion and, inschema.json, the threshold and the strata of the draw.NULLlooks for it in the folders ofvalidation; without it,stratumis empty unlessvalidationhas that column, as aftercombine_rounds(). Only used withvalidation.- 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
NULLor character scalar, label of the classifier, recorded inschema.json.- overwrite
Logical scalar. If
TRUE, replace an existing export inoutput_dir.
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,NAwhen the length of the occasion is unknown), followed by the columns ofoccasion_covariatesand 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"(fromselect_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; seejoin_identities()) (only whenvalidationis given).recordings_verified.csv: the occasions annotated by ear in the"random_recordings"design, with the state of each occasion (only whenvalidationholds such clips).sites.csv: one row per site, with the covariates ofsites.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 thecalibration_keysfound among the occasions of the site (only whenfitis given; needs the 'arrow' package).occasion_draws.parquet: versions of the detections over the calibration draws, as written byoccasion_draws()(only withn_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
)
}