| Title: | End-to-End Passive Acoustic Monitoring Workflow |
|---|---|
| Description: | An end-to-end workflow for passive acoustic monitoring projects, from raw recordings to data ready for ecological analysis. Standardizes and checks field recordings, runs 'BirdNET' (Kahl et al. 2021 <doi:10.1016/j.ecoinf.2021.101236>) through its 'Python' package, cleans and validates detections, and computes soundscape indices. Builds detection histories, count histories and input for occupancy and abundance models, summarizes activity patterns and species richness, and writes 'HTML', 'PDF' and 'Excel' reports. Optional 'shiny' apps support standardization, validation and annotation, and the training of custom 'BirdNET' classifiers. |
| Authors: | Pradeeshwar Rajagopal James [aut, cre, cph] (ORCID: <https://orcid.org/0000-0003-1246-442X>) |
| Maintainer: | Pradeeshwar Rajagopal James <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.6.1 |
| Built: | 2026-11-26 12:19:49 UTC |
| Source: | https://github.com/cran/pamflow |
Counts the cleaned detections of each species in every hour of the day, day, week or month, and divides them by the time that was recorded in that period. Because the division uses recording effort, periods and sites that were recorded for different lengths of time can be compared. Use it for daily (diel) activity patterns and for seasonal patterns such as migration or breeding timing.
pam_activity( cfg, run_id = cfg$birdnet$run_id, by = c("hour", "day", "week", "month"), by_site = FALSE, species = NULL, thresholds = NULL, min_effort_hours = 0, write = FALSE )pam_activity( cfg, run_id = cfg$birdnet$run_id, by = c("hour", "day", "week", "month"), by_site = FALSE, species = NULL, thresholds = NULL, min_effort_hours = 0, write = FALSE )
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). |
by |
The period: |
by_site |
If |
species |
Optional species to keep: scientific names, common names or
species labels, in any capitalization. |
thresholds |
Optional per-species thresholds (a data frame, or the path
of a CSV file, with |
min_effort_hours |
Periods with less recorded time than this get no
rate ( |
write |
If |
detections_per_hour is the number of detected events (Stage 4 merges
overlapping BirdNET windows into events) per hour of recording. It is an
activity index: it depends on how often and how loudly animals call, not only
on how many are present, and on the confidence thresholds used. Compare it
between periods and sites for the same species, and avoid comparing raw
rates between species.
Hours are local clock hours of the project time zone. A recording is split over the hours it covers, so effort is exact for recordings that start part way through an hour or cross midnight.
A data.table with one row per period and species (and per site when
by_site = TRUE): period (hour 0-23, or the first day of the period),
species, scientific_name, n_detections, effort_hours,
detections_per_hour, relative_activity (the rate divided by the
species' highest rate, so 1 marks its peak), sufficient and, for pooled
tables, n_sites_surveyed and n_sites_detected. Periods with recordings
but no detection get 0. Periods with no recording have no row. The choices
are stored in the attributes by and by_site.
pam_plot_activity(), pam_detection_table()
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) act <- suppressMessages(pam_activity(ex$cfg, by = "hour")) as.data.frame(act)[, c("period", "species", "n_detections", "detections_per_hour")] # one row per site and day day <- suppressMessages(pam_activity(ex$cfg, by = "day", by_site = TRUE)) head(as.data.frame(day)[, c("site_id", "period", "species", "n_detections")], 4)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) act <- suppressMessages(pam_activity(ex$cfg, by = "hour")) as.data.frame(act)[, c("period", "species", "n_detections", "detections_per_hour")] # one row per site and day day <- suppressMessages(pam_activity(ex$cfg, by = "day", by_site = TRUE)) head(as.data.frame(day)[, c("site_id", "period", "species", "n_detections")], 4)
Add QC flags to a master audio table
pam_add_qc(master, cfg)pam_add_qc(master, cfg)
master |
data.table from |
cfg |
A |
Gaps are measured between the end of one file and the start of the
next within a grid. qc_pass requires a valid name, a readable and
untruncated file, and no duplicate; short files and gaps are reported but
do not fail QC. Truncation checks apply to PCM WAV files (where bit depth
is non-NA).
master with end_time, truncated, short, duplicate,
gap_s, gap_before, overlap_before and qc_pass. Sorted by grid and
start time.
ex <- pam_example_project() cfg <- ex$cfg master <- pam_parse_filenames(ex$files, cfg$filenames$pattern, cfg$filenames$timezone) master <- merge(master, pam_audio_info(ex$files), by = "file_path") master <- pam_add_qc(master, cfg) as.data.frame(master)[, c("file_name", "gap_s", "qc_pass")]ex <- pam_example_project() cfg <- ex$cfg master <- pam_parse_filenames(ex$files, cfg$filenames$pattern, cfg$filenames$timezone) master <- merge(master, pam_audio_info(ex$files), by = "file_path") master <- pam_add_qc(master, cfg) as.data.frame(master)[, c("file_name", "gap_s", "qc_pass")]
Attaches covariates, such as habitat or elevation, to histories that were built without them. Rows are matched to the sites by name, so the order of your table does not matter.
pam_add_site_covariates(x, covariates, replace = FALSE)pam_add_site_covariates(x, covariates, replace = FALSE)
x |
A |
covariates |
A data frame with a |
replace |
If |
x with the covariates added.
pam_as_count_history(), pam_model_input()
counts <- matrix(c(0, 2, 5, 1, 0, 3), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, species = "Example species") covs <- data.frame(site_id = c("site_c", "site_a", "site_b"), canopy = c(0.9, 0.2, 0.5)) pam_add_site_covariates(hist, covs)$site_covariatescounts <- matrix(c(0, 2, 5, 1, 0, 3), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, species = "Example species") covs <- data.frame(site_id = c("site_c", "site_a", "site_b"), canopy = c(0.9, 0.2, 0.5)) pam_add_site_covariates(hist, covs)$site_covariates
Shows random recording segments, one at a time, in shuffled order, with a
spectrogram and audio. The model's detections are never shown, so the
annotation is independent of the detector. Record every species you hear;
mark doubtful ones as "possibly present". Each save is written immediately to
recall_annotations.csv, so you can stop and resume.
pam_annotate(cfg, reviewer = pam_or(cfg$recall$reviewer, ""), lang = NULL)pam_annotate(cfg, reviewer = pam_or(cfg$recall$reviewer, ""), lang = NULL)
cfg |
A |
reviewer |
Annotator name pre-filled in the app. |
lang |
Interface language code (for example |
Nothing; runs until the app is closed.
if (interactive() && nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 5, run_id = NULL)) out <- suppressMessages(pam_recall_export(ex$cfg)) pam_annotate(ex$cfg) }if (interactive() && nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 5, run_id = NULL)) out <- suppressMessages(pam_recall_export(ex$cfg)) pam_annotate(ex$cfg) }
Wraps a matrix of counts (sites in rows, occasions in columns) so that it can
be prepared for modeling by pam_model_input(). pam_count_history() builds the same
object from the detections of a project; use this function when the counts
come from somewhere else.
pam_as_count_history( y, site_covariates = NULL, effort = NULL, day = NULL, occasions = NULL, species = NA_character_, count = "events" )pam_as_count_history( y, site_covariates = NULL, effort = NULL, day = NULL, occasions = NULL, species = NA_character_, count = "events" )
y |
A matrix of whole-number counts, sites in rows and occasions in
columns, with |
site_covariates |
Optional data frame of site covariates. With a
|
effort |
Optional matrix (same shape as |
day |
Optional matrix (same shape as |
occasions |
Optional data frame describing the occasions, one row per
column of |
species |
Name of the species, for labeling. |
count |
What the counts are: |
An object of class pam_count_history: a list with y, effort,
day, site_covariates, occasions, species and count.
pam_count_history(), pam_model_input()
counts <- matrix(c(0, 2, 5, 1, 0, 3, 4, 0, 2, 1, 1, 0), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, species = "Example species") hist$ycounts <- matrix(c(0, 2, 5, 1, 0, 3, 4, 0, 2, 1, 1, 0), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, species = "Example species") hist$y
Reads all batch files of a run, removes duplicates (from interrupted runs),
joins recording metadata from the Stage 1 master table, and writes
<detections>/<run_id>/detections.csv.
pam_assemble_detections(cfg, run_id = cfg$birdnet$run_id)pam_assemble_detections(cfg, run_id = cfg$birdnet$run_id)
cfg |
A |
run_id |
Name of the detection run (a sub-folder of paths$detections). Defaults to birdnet$run_id. |
A data.table with filename, species, scientific_name,
common_name, confidence, start_time and end_time (seconds into the
recording), site (= grid), grid, recorder, deployment_id,
in_deployment, recording_date, recording_start and
detection_datetime (local time), rel.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) det <- suppressMessages(pam_assemble_detections(ex$cfg)) nrow(det) # the batch file had one duplicate row, which is dropped as.data.frame(det)[, c("filename", "species", "confidence", "start_time", "end_time")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) det <- suppressMessages(pam_assemble_detections(ex$cfg)) nrow(det) # the batch file had one duplicate row, which is dropped as.data.frame(det)[, c("filename", "species", "confidence", "start_time", "end_time")]
Supported Audio File Extensions
pam_audio_exts()pam_audio_exts()
Character vector of supported audio extensions (lowercase).
pam_audio_exts()pam_audio_exts()
Collects, for every audio file, what each stage recorded about it: the standardization result (Stage 0), the scan and QC flags (Stage 1), filtering (Stage 2), detection (Stage 3), cleaning (Stage 4), validation (Stage 5), ground-truth annotation (Stage 5b) and whether it went into the occupancy histories (Stage 6). It reads the files the stages already write, so it works on existing projects and changes nothing unless you ask it to write.
pam_audio_history(cfg, file = NULL, run_id = NULL, wide = FALSE, write = FALSE)pam_audio_history(cfg, file = NULL, run_id = NULL, wide = FALSE, write = FALSE)
cfg |
A |
file |
Optional audio file to look up: a path relative to the
standardized audio folder (such as |
run_id |
Optional detection run (or runs). |
wide |
If |
write |
If |
Statuses: Stage 0 ok, warning or failed; Stage 1 pass or
fail; Stage 2 and 3 ok or failed; Stage 4 kept (some events
survived cleaning) or removed (none did); Stage 5 reviewed or
sampled; Stage 5b annotated, partly annotated or drawn; Stage 6
included or excluded. Stages whose outputs are missing are skipped.
Times are saved in UTC when write = TRUE. The history is built from the
current outputs, so a stage you delete or rerun is shown as it now is.
A data.table. The long table has one row per file and stage (and
run) with columns rel (path relative to the standardized audio folder,
NA for files Stage 0 set aside), file (file name), stage, run_id,
status, detail (what happened, in words), n (a count, such as the
number of detections) and time (when the stage recorded it, where the
stage keeps a time, otherwise the time its output file was written). The
attribute stages_found lists the stages whose outputs were found. With
wide = TRUE the table has rel plus one status column per stage.
ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) # one row per file and stage hist <- pam_audio_history(ex$cfg) as.data.frame(hist)[1:3, c("file", "stage", "status", "detail")] # one file, by name one <- pam_audio_history(ex$cfg, file = "G0059_20260405_183004.wav") as.data.frame(one)[, c("stage", "status", "detail")] # one row per file, one column per stage as.data.frame(pam_audio_history(ex$cfg, wide = TRUE))ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) # one row per file and stage hist <- pam_audio_history(ex$cfg) as.data.frame(hist)[1:3, c("file", "stage", "status", "detail")] # one file, by name one <- pam_audio_history(ex$cfg, file = "G0059_20260405_183004.wav") as.data.frame(one)[, c("stage", "status", "detail")] # one row per file, one column per stage as.data.frame(pam_audio_history(ex$cfg, wide = TRUE))
Reads header information (sample rate, duration, channels, bit depth)
for one or more WAV/FLAC files without loading sample data into memory.
Returns a data.table with readable status; errors for individual unreadable
files are caught gracefully and flagged with readable = FALSE.
pam_audio_info(paths) pam_audio_info_dt(paths)pam_audio_info(paths) pam_audio_info_dt(paths)
paths |
Character vector of file paths. |
A data.table with columns file_path, file_size_b,
sample_rate, channels, bits, duration_s,
readable.
ex <- pam_example_project() pam_audio_info(ex$files)ex <- pam_example_project() pam_audio_info(ex$files)
Regex Pattern Matching Supported Audio Files
pam_audio_pattern()pam_audio_pattern()
Character scalar regex pattern (case-insensitive).
grepl(pam_audio_pattern(), c("a.wav", "b.FLAC", "c.mp3"))grepl(pam_audio_pattern(), c("a.wav", "b.FLAC", "c.mp3"))
Summarize the audio master table
pam_audio_summary(master, dep = NULL)pam_audio_summary(master, dep = NULL)
master |
Output of |
dep |
Optional deployment table, to report grids/deployments with no match. |
A list: overall (one-row data.table), per_grid (data.table),
grids_without_deployment, deployments_without_audio.
ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) summ <- pam_audio_summary(res$master, res$deployments) summ$overall summ$per_gridex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) summ <- pam_audio_summary(res$master, res$deployments) summ$overall summ$per_grid
Runs pam_detect() on the same random sample of recordings once per worker
count and reports throughput, scaling efficiency, and an estimate for the
whole archive. Use it to choose birdnet$workers for your CPU, and as the
baseline to compare the new backend against.
pam_birdnet_benchmark( cfg, workers = c(1L, 2L, 4L, 8L), n_files = 8L, seed = 1L, keep_runs = FALSE )pam_birdnet_benchmark( cfg, workers = c(1L, 2L, 4L, 8L), n_files = 8L, seed = 1L, keep_runs = FALSE )
cfg |
A |
workers |
Integer vector of worker counts to test. Counts above the number of logical cores are dropped with a warning. |
n_files |
Files per run. Each file takes about a minute for a 60-minute recording, so keep this small (default 8). |
seed |
Seed for the file sample, identical for every run. |
keep_runs |
If FALSE (default) the temporary detection folders are deleted afterwards. |
The timing includes model loading in every worker, which is part of the real cost of starting a run. Real runs amortize it over many files, so the full-archive estimate is slightly pessimistic. Run on an otherwise idle machine.
A data.frame with one row per worker count: workers, n_done,
n_failed, elapsed_s, files_per_hour, speedup, efficiency and
est_hours_full. Also written to <logs>/birdnet_benchmark.csv.
## Not run: cfg <- pam_load_config("config.yml") pam_birdnet_benchmark(cfg, workers = c(1, 4, 8), n_files = 8) ## End(Not run)## Not run: cfg <- pam_load_config("config.yml") pam_birdnet_benchmark(cfg, workers = c(1, 4, 8), n_files = 8) ## End(Not run)
Interrupting a run (Esc) or a crash can leave the worker processes of the
Python birdnet package running in the background, holding memory (about
260 MB each). This finds those orphans and stops them. A worker counts as an
orphan only if the process that started it no longer exists, so workers of a
run that is still going are never touched.
pam_birdnet_cleanup(kill = TRUE, quiet = FALSE)pam_birdnet_cleanup(kill = TRUE, quiet = FALSE)
kill |
If FALSE, only report the orphans without stopping them. |
quiet |
If TRUE, print nothing. |
pam_detect() and the training functions call this automatically
(after an interrupt, and before a run starts), so you rarely need it.
Invisibly, a data.frame with pid, name, parent_pid and killed
(zero rows if there were no orphans).
## Not run: pam_birdnet_cleanup(kill = FALSE) # just look pam_birdnet_cleanup() # stop them ## End(Not run)## Not run: pam_birdnet_cleanup(kill = FALSE) # just look pam_birdnet_cleanup() # stop them ## End(Not run)
Inspects the R session, the machine (CPU cores, RAM, GPU) and the two pamflow BirdNET Python environments, and reports what is missing and what to do about it. Nothing is installed or changed. TensorFlow is probed in a separate process, so this never loads Python into your R session.
pam_birdnet_doctor( envs = list(inference = pam_birdnet_env_dir("inference"), training = pam_birdnet_env_dir("training")), quiet = FALSE )pam_birdnet_doctor( envs = list(inference = pam_birdnet_env_dir("inference"), training = pam_birdnet_env_dir("training")), quiet = FALSE )
envs |
Named list with the folders of the "inference" and "training" environments. Defaults to pamflow's private environments. |
quiet |
If TRUE, return the table without printing it. |
Assumptions: on native Windows, TensorFlow has no GPU support, so
pamflow runs BirdNET on CPU there; a detected NVIDIA GPU is reported as
information only. Run pam_birdnet_setup() to create missing
environments.
Invisibly, a data.frame with columns check, status
(ok/warn/fail/info) and detail. Class pam_birdnet_doctor.
## Not run: pam_birdnet_doctor() ## End(Not run)## Not run: pam_birdnet_doctor() ## End(Not run)
Builds a virtual environment (never touching the system Python) with a
pinned Python version. Uses uv when it is installed (it downloads the
requested Python itself); otherwise falls back to reticulate, which needs
a matching Python already installed.
pam_birdnet_setup( component = c("inference", "training"), python_version = "3.11", packages = NULL, envdir = pam_birdnet_env_dir(component), recreate = FALSE, dry_run = FALSE, uv = pam_find_uv() )pam_birdnet_setup( component = c("inference", "training"), python_version = "3.11", packages = NULL, envdir = pam_birdnet_env_dir(component), recreate = FALSE, dry_run = FALSE, uv = pam_find_uv() )
component |
"inference" (the |
python_version |
Python version for the environment. Default "3.11", chosen as widely supported by TensorFlow; change it if a package install reports an unsupported version. |
packages |
pip requirements. Defaults to
|
envdir |
Environment folder. Defaults to pamflow's private location. |
recreate |
If TRUE, delete and rebuild an existing environment. |
dry_run |
If TRUE, only return the plan without creating anything. |
uv |
Path to the uv executable. Found automatically when uv is on PATH or in a standard install location; set it if you installed uv elsewhere. |
Installing TensorFlow downloads roughly a gigabyte, so this can
take several minutes. In an interactive session you are asked to confirm
before anything is downloaded; use dry_run = TRUE to see the plan first.
Afterwards run pam_birdnet_doctor().
Invisibly, a list: envdir, python, python_version, packages.
## Not run: pam_birdnet_setup("inference", dry_run = TRUE) pam_birdnet_setup("inference") pam_birdnet_setup("training") ## End(Not run)## Not run: pam_birdnet_setup("inference", dry_run = TRUE) pam_birdnet_setup("inference") pam_birdnet_setup("training") ## End(Not run)
Runs BirdNET-Analyzer's own birdnet-train command inside pamflow's
training environment, so the trained model is the same kind of file the
Analyzer GUI produces. The training runs in a separate process: an error
or crash cannot take down your R session.
pam_birdnet_train( data_dir, output, params = list(), test_data = NULL, load_params = NULL, cache_mode = NULL, cache_file = NULL, envdir = pam_birdnet_env_dir("training"), live = FALSE, overwrite = FALSE, log_dir = NULL )pam_birdnet_train( data_dir, output, params = list(), test_data = NULL, load_params = NULL, cache_mode = NULL, cache_file = NULL, envdir = pam_birdnet_env_dir("training"), live = FALSE, overwrite = FALSE, log_dir = NULL )
data_dir |
Training folder with one sub-folder per class. Use
|
output |
Output path prefix, e.g. |
params |
Named list of training parameters. Names:
epochs, val_split, learning_rate, batch_size, threads, crop_mode,
overlap, fmin, fmax, audio_speed, hidden_units, dropout, focal_loss,
focal_loss_gamma, focal_loss_alpha, label_smoothing, mixup,
upsampling_ratio, upsampling_mode, model_save_mode, model_format
("tflite", "raven" or "both"), autotune, autotune_trials,
autotune_executions_per_trial. Yes/no options are on/off switches:
|
test_data |
Optional separate test folder; if NULL the Analyzer holds
out |
load_params |
Optional path to an earlier run's parameters file, passed
as |
cache_mode |
NULL (default), "save" or "load": passed as |
cache_file |
Cache file for |
envdir |
Training environment folder (from |
live |
If TRUE, also show the trainer's output on the console while it runs. The log file is written either way. |
overwrite |
If FALSE (default), refuse to overwrite an existing model. |
log_dir |
Optional folder for a log file ( |
This is a standalone tool: it is not a stage of the workflow and no workflow
function calls it. Use the trained model by pointing the birdnet: section of
the config at it.
This is a standalone tool, not a pipeline stage: it needs no config file
and nothing in the workflow calls it. Assumptions: BirdNET-Analyzer is installed in the training
environment and provides the birdnet-train command. Hyperparameter
autotuning needs the Analyzer's train extra
(pam_birdnet_setup("training", packages = "birdnet-analyzer[train]", recreate = TRUE)). Before running, pamflow checks that every option it
passes appears in the installed birdnet-train --help and stops with a
clear message if one does not.
Invisibly, a list: status ("ok" or "failed"), output, files
(named logical: which expected files exist), elapsed (difftime),
log, run_record, args, and metrics (from
pam_birdnet_train_metrics(), NULL if the log could not be read) and
evaluation (with a separate test_data folder: a list with overall,
classes and path read from <output>_evaluation.csv, one row per class
with precision, recall, F1, AUPRC and AUROC; otherwise NULL) and, when a cache
was used, cache (what the trainer reported: see pam_train_cache_notes()).
Kahl, S., Wood, C. M., Eibl, M. and Klinck, H. (2021). BirdNET: A deep learning solution for avian diversity monitoring. Ecological Informatics, 61, 101236. doi:10.1016/j.ecoinf.2021.101236
## Not run: prep <- pam_birdnet_train_prepare("E:/training_clips") res <- pam_birdnet_train("E:/training_clips", "E:/models/MyModel", params = list(epochs = 100, hidden_units = 512)) # reproduce an earlier run from its parameters file pam_birdnet_train("E:/training_clips", "E:/models/Rerun", load_params = "E:/models/BirdNet_v2_custom_Params.csv") ## End(Not run)## Not run: prep <- pam_birdnet_train_prepare("E:/training_clips") res <- pam_birdnet_train("E:/training_clips", "E:/models/MyModel", params = list(epochs = 100, hidden_units = 512)) # reproduce an earlier run from its parameters file pam_birdnet_train("E:/training_clips", "E:/models/Rerun", load_params = "E:/models/BirdNet_v2_custom_Params.csv") ## End(Not run)
birdnet-train logExtracts the per-epoch history and the final summary that the Analyzer prints, so runs can be compared (for example with the Analyzer GUI) without reading the log by hand.
pam_birdnet_train_metrics(log_file)pam_birdnet_train_metrics(log_file)
log_file |
Path to a training log ( |
The log format is the one printed by BirdNET-Analyzer 2.4.0. If the trainer prints something else, the fields come back empty or NA rather than guessed. Terminal progress bars and TensorFlow messages in the log are ignored.
A list: history (data.frame with epoch, auprc, auroc, loss,
val_auprc, val_auroc, val_loss, learning_rate), best (list with
auprc, auroc, loss, epoch, n_epochs; NA when not printed),
n_train, n_val, n_labels (NA if not found) and evaluated_on
("validation" or "test").
## Not run: m <- pam_birdnet_train_metrics("E:/models/MyModel_train.log") m$best$auprc ## End(Not run)## Not run: m <- pam_birdnet_train_metrics("E:/models/MyModel_train.log") m$best$auprc ## End(Not run)
Looks at the folder-per-class layout BirdNET-Analyzer expects and reports problems early: missing or empty classes, very small classes, files that are not audio, and a missing non-event class.
pam_birdnet_train_prepare(data_dir, min_clips = 20L, quiet = FALSE)pam_birdnet_train_prepare(data_dir, min_clips = 20L, quiet = FALSE)
data_dir |
Training folder with one sub-folder per class. |
min_clips |
Classes (other than noise classes) with fewer audio files are flagged. A rule of thumb for your own data, not an Analyzer limit. |
quiet |
If TRUE, do not print the report. |
Audio files are counted by extension (wav, flac, mp3, ogg, m4a); clip length is not inspected. The Analyzer's documentation recommends 3-second clips and a background class named noise, other, background or silence.
Invisibly, a list: classes (data.frame with class, n_audio,
n_other, n_subdirs, is_noise), issues (character) and ok
(TRUE if there are no issues).
## Not run: pam_birdnet_train_prepare("E:/training_clips") ## End(Not run)## Not run: pam_birdnet_train_prepare("E:/training_clips") ## End(Not run)
Each run uses a different random validation split and initialization, so a single score can be lucky or unlucky. Repeating the run shows how much the metrics vary, which is the yardstick for comparing settings, or pamflow against the Analyzer GUI, fairly.
pam_birdnet_train_repeat(data_dir, output, n = 5L, params = list(), ...)pam_birdnet_train_repeat(data_dir, output, n = 5L, params = list(), ...)
data_dir |
Training folder (see |
output |
Output path prefix; run |
n |
Number of runs. |
params |
Named list of training parameters (see |
... |
Further arguments passed to |
This is a standalone tool: it is not a stage of the workflow and no workflow
function calls it. Use the trained model by pointing the birdnet: section of
the config at it.
A failed run is recorded and does not stop the others. With a
fixed test_data folder every run is scored on the same clips, so the
spread then reflects training randomness only.
A list: runs (data.frame with run, status, auprc, auroc,
loss, best_epoch, elapsed_min, output) and summary (data.frame
with metric, n, mean, sd, min, max over the successful runs).
## Not run: rep5 <- pam_birdnet_train_repeat("E:/clips", "E:/models/Check", n = 5) rep5$summary ## End(Not run)## Not run: rep5 <- pam_birdnet_train_repeat("E:/clips", "E:/models/Check", n = 5) rep5$summary ## End(Not run)
Reads cleaned detections and the audio master, constructs per-species
detection history matrices (wide format), occasion covariates (effort
and Julian date), and site covariates. Writes everything to
data/occupancy/<run_id>/.
pam_build_occupancy(cfg, run_id = cfg$occupancy$run_id, force = FALSE)pam_build_occupancy(cfg, run_id = cfg$occupancy$run_id, force = FALSE)
cfg |
A list from |
run_id |
Character. The detection run to use. Defaults to
|
force |
Logical. Rebuild even if outputs exist? Default FALSE. |
An occasion is a block of occupancy$occasion_length_days calendar
days (default 1, midnight to midnight in the project timezone). Blocks
start on the first day with any recording in the project and are the same
for every site. Occasions with less than min_effort_hours of
recording in total are coded NA (not surveyed). A detection counts in the
occasion that contains its date. Outputs that already exist are kept unless
force = TRUE, so rebuild after changing the occasion length.
Grids with a single deployment use the grid name as the site ID.
Grids with multiple deployments get grid_deployment_id.
If processing.species_thresholds_file points to a CSV with
columns scientific_name and threshold, those per-species
values are used. Species not listed fall back to
processing.min_confidence.
Only species with at least occupancy.min_detections total
detections (after the confidence cut) get a history matrix.
Invisibly, a list with histories (named list of wide
matrices), effort, site_covariates, summary.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) # occupancy builds on cleaned detections occ <- suppressMessages(pam_build_occupancy(ex$cfg)) names(occ$histories) occ$summary # detection history of the first species: rows = sites, columns = days, NA = not surveyed occ$histories[[1]]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) # occupancy builds on cleaned detections occ <- suppressMessages(pam_build_occupancy(ex$cfg)) names(occ$histories) occ$summary # detection history of the first species: rows = sites, columns = days, NA = not surveyed occ$histories[[1]]
List problems in the deployment table
pam_check_deployments(dep)pam_check_deployments(dep)
dep |
Table from |
A data.table deployment_id, grid, issue (empty if none).
Issues: unparseable start, missing/unparseable recovery, recovery before
deployment, assumed recovery time, and overlap with another deployment of
the same grid.
ex <- pam_example_project() dep <- pam_read_deployments(ex$cfg) pam_check_deployments(dep) # no rows: the example deployments are consistentex <- pam_example_project() dep <- pam_read_deployments(ex$cfg) pam_check_deployments(dep) # no rows: the example deployments are consistent
Check that FFmpeg is installed and supports the filter chain
pam_check_ffmpeg(ffmpeg = "ffmpeg", filter = NULL)pam_check_ffmpeg(ffmpeg = "ffmpeg", filter = NULL)
ffmpeg |
Executable name or full path. |
filter |
Filter string to test on 0.1 s of silence. |
The first line of FFmpeg's version output. Aborts with install advice if FFmpeg is missing or too old for the filter.
if (nzchar(Sys.which("ffmpeg"))) { pam_check_ffmpeg("ffmpeg", filter = pam_highpass_filter_string(250, 8)) }if (nzchar(Sys.which("ffmpeg"))) { pam_check_ffmpeg("ffmpeg", filter = pam_highpass_filter_string(250, 8)) }
Runs a set of consistency checks on the output of pam_model_input():
dimensions, site and occasion matching, the values of the response and
missing values. Use it after editing the input by hand, or to confirm that
input is ready before it is passed to a modeling package.
pam_check_model_input(x, error = TRUE)pam_check_model_input(x, error = TRUE)
x |
A |
error |
If |
The checks are: the response is a numeric array; sites are unique and match the site covariates (count and names); observation covariates have the shape of the response; the response holds whole numbers of 0 or more (0 or 1 for detection / non-detection); every site was surveyed at least once; observation covariates are present wherever the response is; and, for seasons, the number of seasons and occasions match the response.
A data.table with one row per check: check, passed and detail
(invisibly when everything passed).
counts <- matrix(c(0, 2, 5, 1, 0, 3), nrow = 3, dimnames = list(c("a", "b", "c"), NULL)) x <- pam_model_input(pam_as_count_history(counts)) pam_check_model_input(x)counts <- matrix(c(0, 2, 5, 1, 0, 3), nrow = 3, dimnames = list(c("a", "b", "c"), NULL)) x <- pam_model_input(pam_as_count_history(counts)) pam_check_model_input(x)
Call this after the corresponding batch output has been written to disk, so an interruption never marks unwritten work as done.
pam_checkpoint_add(ids, path)pam_checkpoint_add(ids, path)
ids |
Character vector of IDs (e.g. file paths relative to the audio root). |
path |
Checkpoint file path. |
ids, invisibly.
ckpt <- tempfile(fileext = ".txt") pam_checkpoint_add("a.wav", ckpt) pam_checkpoint_add("b.wav", ckpt) pam_checkpoint_read(ckpt) unlink(ckpt)ckpt <- tempfile(fileext = ".txt") pam_checkpoint_add("a.wav", ckpt) pam_checkpoint_add("b.wav", ckpt) pam_checkpoint_read(ckpt) unlink(ckpt)
Read the set of already-processed item IDs
pam_checkpoint_read(path)pam_checkpoint_read(path)
path |
Path to a plain-text checkpoint file (one ID per line). |
Character vector of completed IDs (empty if the file doesn't exist).
ckpt <- tempfile(fileext = ".txt") pam_checkpoint_read(ckpt) # no file yet: nothing is done pam_checkpoint_add(c("a.wav", "b.wav"), ckpt) pam_checkpoint_read(ckpt) unlink(ckpt)ckpt <- tempfile(fileext = ".txt") pam_checkpoint_read(ckpt) # no file yet: nothing is done pam_checkpoint_add(c("a.wav", "b.wav"), ckpt) pam_checkpoint_read(ckpt) unlink(ckpt)
Pure function (no file access), so it can be tested directly. Rules run in a fixed order and each removed detection is kept with its reason.
pam_clean_detections(det, pc, thresholds = NULL, seasons = NULL)pam_clean_detections(det, pc, thresholds = NULL, seasons = NULL)
det |
A data.table of detections as returned by
|
pc |
The |
thresholds |
Optional data.table with |
seasons |
Optional data.table with |
A list: clean (one row per event, with confidence = maximum,
mean_confidence, n_windows), removed (rows with reason), steps
(rule, n_before, n_removed).
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) det <- suppressMessages(pam_assemble_detections(ex$cfg)) det$file_duration_s <- 2 # length of the example recordings, in seconds cleaned <- pam_clean_detections(det, ex$cfg$processing) cleaned$steps cleaned$removed$reason as.data.frame(cleaned$clean)[, c("species", "confidence", "n_windows", "start_time", "end_time")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) det <- suppressMessages(pam_assemble_detections(ex$cfg)) det$file_duration_s <- 2 # length of the example recordings, in seconds cleaned <- pam_clean_detections(det, ex$cfg$processing) cleaned$steps cleaned$removed$reason as.data.frame(cleaned$clean)[, c("species", "confidence", "n_windows", "start_time", "end_time")]
Read and validate a pamflow configuration file
pam_config_read(path)pam_config_read(path)
path |
Path to a YAML config file (required). There is no default: pamflow never looks for a configuration in the working directory. |
Missing keys fall back to the template defaults
(system.file("extdata", "config_template.yml", package = "pamflow")).
A relative paths$project_root is resolved against the folder that holds
the config file, not the working directory. The template uses "..", so a
config saved as <project>/config/config.yml points at <project>.
A named list of class pam_config, with all paths resolved
against paths$project_root.
ex <- pam_example_project() cfg <- pam_config_read(ex$config) cfg$birdnet$run_id cfg$paths$audio_standardizedex <- pam_example_project() cfg <- pam_config_read(ex$config) cfg$birdnet$run_id cfg$paths$audio_standardized
Validate a pamflow configuration
pam_config_validate(cfg)pam_config_validate(cfg)
cfg |
A config list. |
cfg, invisibly. Aborts with a clear message on invalid values.
ex <- pam_example_project() pam_config_validate(ex$cfg) # fine: returns the config invisibly bad <- ex$cfg bad$birdnet$min_confidence <- 2 # must be between 0 and 1 res <- try(pam_config_validate(bad), silent = TRUE) inherits(res, "try-error")ex <- pam_example_project() pam_config_validate(ex$cfg) # fine: returns the config invisibly bad <- ex$cfg bad$birdnet$min_confidence <- 2 # must be between 0 and 1 res <- try(pam_config_validate(bad), silent = TRUE) inherits(res, "try-error")
Builds a pam_count_history() for every species (or the species you name) in
one pass over the detections. All histories share the same sites, occasions,
effort and site covariates, which is what multi-species models need.
pam_count_histories( cfg, species = NULL, run_id = cfg$birdnet$run_id, bin_days = NULL, count = c("events", "files"), thresholds = NULL, min_effort_hours = NULL, site_covariates = NULL, min_total = 1 )pam_count_histories( cfg, species = NULL, run_id = cfg$birdnet$run_id, bin_days = NULL, count = c("events", "files"), thresholds = NULL, min_effort_hours = NULL, site_covariates = NULL, min_total = 1 )
cfg |
A |
species |
Optional species to include: scientific names, common names or
species labels (any capitalization). |
run_id |
Detection run (sub-folder of paths$detections). |
bin_days |
Length of an occasion in days. |
count |
What to count: |
thresholds |
Optional per-species thresholds (a data frame, or the path
of a CSV file, with |
min_effort_hours |
Minimum recorded hours for an occasion to count as
surveyed; others are |
site_covariates |
Optional data frame of site covariates with a
|
min_total |
Species with fewer than this many counts in total, over all sites and occasions, are left out (default 1, which drops species with no count after the thresholds). |
Pass the result to pam_model_input() to get a species by site by
occasion array for multi-species models, or take one species with
histories[["label"]].
An object of class pam_count_histories: a named list (one
pam_count_history() per species, named by species label).
pam_count_history(), pam_model_input()
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) hists <- suppressMessages(pam_count_histories(ex$cfg)) names(hists)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) hists <- suppressMessages(pam_count_histories(ex$cfg)) names(hists)
Counts the detections of one species in each site and occasion of a project
and returns them in the form that abundance models need: a matrix with
sites in rows and occasions in columns, NA where a site was not surveyed,
and matrices of recording effort and days. This is the abundance counterpart
of the detection histories of Stage 6.
pam_count_history( cfg, species, run_id = cfg$birdnet$run_id, bin_days = NULL, count = c("events", "files"), thresholds = NULL, min_effort_hours = NULL, site_covariates = NULL )pam_count_history( cfg, species, run_id = cfg$birdnet$run_id, bin_days = NULL, count = c("events", "files"), thresholds = NULL, min_effort_hours = NULL, site_covariates = NULL )
cfg |
A |
species |
The species, given as scientific name, common name or species label (any capitalization). It must identify exactly one species. |
run_id |
Detection run (sub-folder of paths$detections). |
bin_days |
Length of an occasion in days. |
count |
What to count: |
thresholds |
Optional per-species thresholds (a data frame, or the path
of a CSV file, with |
min_effort_hours |
Minimum recorded hours for an occasion to count as
surveyed; others are |
site_covariates |
Optional data frame of site covariates with a
|
Sites and occasions follow Stage 6: occasions are blocks of bin_days days
starting on the first recorded day, shared by all sites, and only occasions
with recordings at some site appear. The counts are numbers of detections,
not numbers of animals, so models fitted to them give a relative abundance
index. Use pam_model_input() to turn the history into input for
abundance or occupancy models.
An object of class pam_count_history: a list with
y: integer matrix of counts (sites x occasions, NA = not surveyed);
effort: matrix of recorded hours (NA where not surveyed);
day: matrix of days since the first occasion;
site_covariates: data frame with site_id and your covariates;
occasions: the start and end day of each occasion;
species, count: what was counted.
pam_as_count_history(), pam_model_input()
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) sp <- unique(proc$clean$scientific_name)[1] hist <- suppressMessages(pam_count_history(ex$cfg, species = sp)) hist$yex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) sp <- unique(proc$clean$scientific_name)[1] hist <- suppressMessages(pam_count_history(ex$cfg, species = sp)) hist$y
Extracts a sub-section of an audio file and writes it to disk, preserving the source file extension when possible.
pam_cut_audio(in_path, out_path, from, to)pam_cut_audio(in_path, out_path, from, to)
in_path |
Character. Source audio file path. |
out_path |
Character. Output file path. |
from |
Numeric. Start time in seconds. |
to |
Numeric. End time in seconds. |
Invisibly returns out_path.
ex <- pam_example_project() out <- tempfile(fileext = ".wav") pam_cut_audio(ex$files[1], out, from = 0.5, to = 1.5) pam_audio_info(out)$duration_s unlink(out)ex <- pam_example_project() out <- tempfile(fileext = ".wav") pam_cut_audio(ex$files[1], out, from = 0.5, to = 1.5) pam_audio_info(out)$duration_s unlink(out)
Builds a table of seasons (one per calendar year or month) that cover the
occasions of a history, for use as the seasons argument of
pam_model_input(). Years or months without any occasion between the first
and last are included, so the spacing of seasons is kept.
pam_define_seasons(history, by = c("year", "month"))pam_define_seasons(history, by = c("year", "month"))
history |
A |
by |
|
A data frame with season (label), start and end (Dates).
dates <- as.Date(c("2025-12-20", "2026-01-05", "2026-03-10")) counts <- matrix(c(1, 0, 2, 0, 1, 1), nrow = 2, dimnames = list(c("a", "b"), NULL)) hist <- pam_as_count_history( counts, occasions = data.frame(occasion = 1:3, bin_start = dates, bin_end = dates)) pam_define_seasons(hist, by = "month")dates <- as.Date(c("2025-12-20", "2026-01-05", "2026-03-10")) counts <- matrix(c(1, 0, 2, 0, 1, 1), nrow = 2, dimnames = list(c("a", "b"), NULL)) hist <- pam_as_count_history( counts, occasions = data.frame(occasion = 1:3, bin_start = dates, bin_end = dates)) pam_define_seasons(hist, by = "month")
Reads from the filtered folder (default) or the standardized folder
(birdnet$input), runs BirdNET in parallel worker processes, and writes
raw detections in batches to <detections>/<run_id>/batches/.
pam_detect(cfg, master = NULL, sample_n = NULL, seed = 1L, force = FALSE)pam_detect(cfg, master = NULL, sample_n = NULL, seed = 1L, force = FALSE)
cfg |
A |
master |
Optional Stage 1 master table; if NULL it is read from
|
sample_n |
If set, process a random sample of this many files (for
pilots). The same |
seed |
Seed for the pilot sample. |
force |
If TRUE, delete this run's earlier results and start over. |
BirdNET runs in pamflow's Python inference environment (see
pam_birdnet_setup()) using the birdnet Python package, which does its
own multiprocessing: birdnet$workers worker processes each load the
model (an unset value means half of the physical cores). top_k limits
the species kept per 3 s segment (NULL = all above min_confidence).
Resumable. A file is marked done (<run_dir>/done.txt) only after
its batch file is on disk, and files with no detections count as done.
If a crash happens between writing a batch and updating the checkpoint,
those files are re-run, and pam_assemble_detections() removes the
duplicates. Per-file outcomes (seconds, errors) go to file_results.csv;
settings and the birdnet package version go to run_settings_*.yml.
Run with pam_run_stage("03_detect", pam_detect, cfg).
Invisibly, a list: n_pending, n_done, n_failed,
n_detections, run_dir.
Kahl, S., Wood, C. M., Eibl, M. and Klinck, H. (2021). BirdNET: A deep learning solution for avian diversity monitoring. Ecological Informatics, 61, 101236. doi:10.1016/j.ecoinf.2021.101236
## Not run: # needs the BirdNET Python environment (pam_birdnet_setup("inference")) and your model cfg <- pam_config_read("config/config.yml") res <- pam_run_stage("03_detect", pam_detect, cfg) ## End(Not run)## Not run: # needs the BirdNET Python environment (pam_birdnet_setup("inference")) and your model cfg <- pam_config_read("config/config.yml") res <- pam_run_stage("03_detect", pam_detect, cfg) ## End(Not run)
The shared starting point for activity patterns, richness and abundance indices. It counts the cleaned detections (Stage 4) of every species in every site and time bin, and puts the recording effort next to the counts, so rates per recorded hour can be compared between sites that were recorded for different lengths of time.
pam_detection_table( cfg, run_id = cfg$birdnet$run_id, bin_days = NULL, thresholds = NULL, min_effort_hours = NULL, extra_by = character(), complete = TRUE, write = FALSE )pam_detection_table( cfg, run_id = cfg$birdnet$run_id, bin_days = NULL, thresholds = NULL, min_effort_hours = NULL, extra_by = character(), complete = TRUE, write = FALSE )
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). |
bin_days |
Length of a time bin in days. |
thresholds |
Optional per-species thresholds: a data frame, or the path
of a CSV file, with |
min_effort_hours |
Minimum recorded hours for a bin to count as
surveyed. |
extra_by |
Optional names of further detection columns to count by, for example a call type, if your detections have one. |
complete |
If |
write |
If |
Sites follow the occupancy stage: the grid name, or grid_deploymentId for
grids with several deployments. Effort counts recordings that passed QC and
lie inside a deployment window. Detections that fall in a site and bin with no
effort (for example, in a recording that failed QC) are dropped with a
warning.
All bins start on the first day with any recording in the project, so a bin covers the same dates at every site.
A data.table with one row per site, bin and species (and extra_by
column): site_id, bin_start, bin_end, species, scientific_name,
n_detections (events), n_files (recordings with a detection),
max_confidence, effort_hours, n_days, sufficient (the bin reached
the minimum effort) and detections_per_hour. Bins below the minimum
effort are kept and flagged, not dropped. The bin length and first bin day
are stored in the attributes bin_days and origin.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) tab <- suppressMessages(pam_detection_table(ex$cfg)) as.data.frame(tab)[, c("site_id", "bin_start", "species", "n_detections", "effort_hours")] # two-day bins instead of one-day bins tab2 <- suppressMessages(pam_detection_table(ex$cfg, bin_days = 2)) unique(tab2$bin_start)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) tab <- suppressMessages(pam_detection_table(ex$cfg)) as.data.frame(tab)[, c("site_id", "bin_start", "species", "n_detections", "effort_hours")] # two-day bins instead of one-day bins tab2 <- suppressMessages(pam_detection_table(ex$cfg, bin_days = 2)) unique(tab2$bin_start)
Builds a tiny, synthetic pamflow project in a temporary folder: six two-second WAV files (pure tones, 8 kHz, mono) from two recording grids with pamflow-style file names, a deployment sheet, a configuration file, and a BirdNET-style detections file for three species. It is meant for the examples in the help pages, for tests, and for getting to know the workflow without any field data. It needs only R packages that pamflow already depends on: no FFmpeg, Python or internet connection.
pam_example_project(dir = tempfile("pamflow_example_"))pam_example_project(dir = tempfile("pamflow_example_"))
dir |
Folder to create the project in. The default is a new folder inside
|
The project has this layout (the other folders are created when stages run):
<root>/
config/config.yml
metadata/deployments.csv
data/standardized/G0059/ (3 files)
data/standardized/G0110/ (3 files)
data/detections/run01/batches/batch_001.csv
Grid G0059 was recorded on 2026-04-05 at 18:30 and grid G0110 on
2026-04-06 at 06:00; every file lies inside its deployment window, so a scan
finds no problems.
The detections file looks like the batch files that pam_detect() writes
(three species, 3-second windows). It has a few things for the cleaning
stage to deal with: overlapping windows to merge, low-confidence rows, a
window past the end of its recording, and one duplicated row. The stages
after the scan need the master table, so run pam_scan_audio() on
ex$cfg first; the help-page examples show how.
The configuration only sets what differs from the defaults: occupancy needs no minimum recording effort and one detection per species, recall segments are 1 second long because the recordings are only 2 seconds long, and the filter stage uses a single worker.
A list with:
rootThe project folder.
configPath to config/config.yml.
cfgThe configuration, read with pam_config_read().
audio_dirFolder with the standardized audio.
filesPaths of the six WAV files.
deploymentsPath to the deployment sheet.
detectionsPath to the detections batch file.
ex <- pam_example_project() basename(ex$files) res <- suppressMessages(pam_scan_audio(ex$cfg)) res$summary$overallex <- pam_example_project() basename(ex$files) res <- suppressMessages(pam_scan_audio(ex$cfg)) res$summary$overall
Helper function to parse site/grid/recorder identifier from filename using pattern capture groups or leading token prior to first underscore.
pam_extract_grid(filename, pattern = NULL)pam_extract_grid(filename, pattern = NULL)
filename |
Character, filename or base name. |
pattern |
Optional regular expression pattern (e.g., cfg$filenames$pattern). |
Character string identifier or "unassigned".
pam_extract_grid("G0059_20260405_183000.wav") pam_extract_grid("recording.wav") # no recognisable identifierpam_extract_grid("G0059_20260405_183000.wav") pam_extract_grid("recording.wav") # no recognisable identifier
Applies a Butterworth high-pass (default 250 Hz, 48 dB/octave) with FFmpeg
and writes filtered copies (WAV or FLAC) to paths$filtered, mirroring the
folder structure and file names of paths$audio_standardized. Originals
are never modified.
pam_filter_audio(cfg, master = NULL, force = FALSE)pam_filter_audio(cfg, master = NULL, force = FALSE)
cfg |
A |
master |
Optional master table from |
force |
If TRUE, ignore the checkpoint and re-filter everything. |
Resumable: completed files are recorded in metadata/02_filter.done
only after the output has been written and verified (readable, same
duration, sample rate and channels). Per-file outcomes, including FFmpeg
error text, are appended to metadata/02_filter_results.csv. Only files
with qc_pass == TRUE are filtered. Format (WAV vs FLAC) is preserved from
source files. Run with pam_run_stage("02_filter", pam_filter_audio, cfg).
Invisibly, a list: n_pending, n_ok, n_failed, results_file.
if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) out <- suppressMessages(pam_filter_audio(ex$cfg)) out$n_ok basename(list.files(ex$cfg$paths$filtered, recursive = TRUE)) }if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) out <- suppressMessages(pam_filter_audio(ex$cfg)) out$n_ok basename(list.files(ex$cfg$paths$filtered, recursive = TRUE)) }
Base R only, so it can be shipped to parallel workers without the package
installed. Writes to <output>.part and renames on success, so an
interrupted run never leaves a half-written file that looks finished.
Preserves the file format (WAV or FLAC) based on output extension.
pam_filter_one(item, filter, ffmpeg = "ffmpeg")pam_filter_one(item, filter, ffmpeg = "ffmpeg")
item |
List with |
filter |
Filter string from |
ffmpeg |
Executable name or path. |
A list: ok (logical) and message (last FFmpeg error lines, or "").
if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() item <- list(input = ex$files[1], output = tempfile(fileext = ".wav"), bits = 16) res <- pam_filter_one(item, pam_highpass_filter_string(250, 8)) res$ok unlink(item$output) }if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() item <- list(input = ex$files[1], output = tempfile(fileext = ".wav"), bits = 16) res <- pam_filter_one(item, pam_highpass_filter_string(250, 8)) res$ok unlink(item$output) }
FFmpeg's highpass filter supports only 2 poles per instance, so higher
orders are built as a cascade of second-order sections, each with the Q
value that yields a true Butterworth response (maximally flat passband,
-3 dB at the cutoff). Four identical sections would NOT give this: the
cutoff would sit near -12 dB.
pam_highpass_filter_string(cutoff_hz = 250, order = 8L)pam_highpass_filter_string(cutoff_hz = 250, order = 8L)
cutoff_hz |
Cutoff frequency in Hz (-3 dB point). |
order |
Even filter order. 8 = 48 dB/octave. |
A single character string for ffmpeg -af.
pam_highpass_filter_string(250, 8)pam_highpass_filter_string(250, 8)
Recursively scans a raw data directory, classifies files (audio, short clips/memos, non-audio, corrupt), extracts audio properties, and parses recording datetimes.
pam_inspect_raw( raw_dir, recursive = TRUE, min_duration_s = 60, timezone = "Asia/Kolkata", pattern = NULL )pam_inspect_raw( raw_dir, recursive = TRUE, min_duration_s = 60, timezone = "Asia/Kolkata", pattern = NULL )
raw_dir |
Path to raw data folder. |
recursive |
Logical, scan subfolders recursively? |
min_duration_s |
Minimum duration in seconds for standard audio clips (default 60s). |
timezone |
Timezone string for timestamp parsing. |
pattern |
Optional filename regex pattern. |
data.table containing detailed file metadata and triage categorization.
ex <- pam_example_project() # the example audio stands in for a raw dump; recordings under 1 s would count as memos insp <- suppressMessages(pam_inspect_raw(ex$audio_dir, min_duration_s = 1)) as.data.frame(insp)[, c("filename", "duration_s", "grid", "category")]ex <- pam_example_project() # the example audio stands in for a raw dump; recordings under 1 s would count as memos insp <- suppressMessages(pam_inspect_raw(ex$audio_dir, min_duration_s = 1)) as.data.frame(insp)[, c("filename", "duration_s", "grid", "category")]
Check if a File is a FLAC File
pam_is_flac(path)pam_is_flac(path)
path |
Character. File path or vector of paths. |
Logical scalar or vector.
pam_is_flac(c("a.flac", "b.wav"))pam_is_flac(c("a.flac", "b.wav"))
List Audio Files in a Directory (WAV + FLAC)
pam_list_audio(dir, recursive = TRUE)pam_list_audio(dir, recursive = TRUE)
dir |
Character. Directory to scan. |
recursive |
Logical. Recurse into subdirectories. |
Character vector of file paths.
ex <- pam_example_project() basename(pam_list_audio(ex$audio_dir))ex <- pam_example_project() basename(pam_list_audio(ex$audio_dir))
Alias for pam_config_read
pam_load_config(path)pam_load_config(path)
path |
Path to config file (required). |
pam_config object.
ex <- pam_example_project() cfg <- pam_load_config(ex$config) cfg$filenames$timezoneex <- pam_example_project() cfg <- pam_load_config(ex$config) cfg$filenames$timezone
Write a timestamped log line to a per-stage log file
pam_log( level = c("INFO", "WARN", "ERROR"), msg, stage = "pamflow", log_dir = NULL, echo = TRUE )pam_log( level = c("INFO", "WARN", "ERROR"), msg, stage = "pamflow", log_dir = NULL, echo = TRUE )
level |
One of "INFO", "WARN", "ERROR". |
msg |
Character message. |
stage |
Stage name, used as the log file name ( |
log_dir |
Directory for log files (created if missing). If NULL, file logging is skipped. |
echo |
Also print to the console. |
The log line, invisibly.
log_dir <- tempfile("pamflow_logs_") pam_log("INFO", "scan started", stage = "01_scan", log_dir = log_dir) readLines(file.path(log_dir, "01_scan.log")) unlink(log_dir, recursive = TRUE)log_dir <- tempfile("pamflow_logs_") pam_log("INFO", "scan started", stage = "01_scan", log_dir = log_dir) readLines(file.path(log_dir, "01_scan.log")) unlink(log_dir, recursive = TRUE)
Attach recorder and coordinates by matching grid and time window
pam_match_deployments(master, dep)pam_match_deployments(master, dep)
master |
Master audio table with |
dep |
Table from |
master with deployment_id, recorder, latitude, longitude
and in_deployment. Recordings outside every deployment window of their
grid get NA and in_deployment = FALSE (not dropped).
ex <- pam_example_project() cfg <- ex$cfg master <- pam_parse_filenames(ex$files, cfg$filenames$pattern, cfg$filenames$timezone) master <- pam_match_deployments(master, pam_read_deployments(cfg)) as.data.frame(master)[, c("file_name", "deployment_id", "recorder", "in_deployment")]ex <- pam_example_project() cfg <- ex$cfg master <- pam_parse_filenames(ex$files, cfg$filenames$pattern, cfg$filenames$timezone) master <- pam_match_deployments(master, pam_read_deployments(cfg)) as.data.frame(master)[, c("file_name", "deployment_id", "recorder", "in_deployment")]
Turns a count history into the pieces that site-occupancy and abundance
models use: the response y (sites by occasions), the site covariates
siteCovs and the observation covariates obsCovs. It handles one species
or several, and one season or several. pamflow does not fit these models; use
the prepared input with the package you prefer, such as unmarked, ubms or
spOccupancy.
pam_model_input( history, binary = FALSE, standardize = FALSE, drop_unsurveyed = TRUE, seasons = NULL, season_covariates = NULL, dir = NULL )pam_model_input( history, binary = FALSE, standardize = FALSE, drop_unsurveyed = TRUE, seasons = NULL, season_covariates = NULL, dir = NULL )
history |
A |
binary |
If |
standardize |
If |
drop_unsurveyed |
If |
seasons |
Optional data frame with the columns |
season_covariates |
Optional data frame with a |
dir |
Optional folder. If given, the pieces are also written there as CSV files, for use outside R. Nothing is written by default. |
Both build their data frames from these pieces:
x <- pam_model_input(history)
umf <- unmarked::unmarkedFramePCount(y = x$y, siteCovs = x$siteCovs, obsCovs = x$obsCovs)
fit <- unmarked::pcount(~ effort ~ canopy, data = umf, K = 100)
x <- pam_model_input(history, binary = TRUE)
umf <- unmarked::unmarkedFrameOccu(y = x$y, siteCovs = x$siteCovs, obsCovs = x$obsCovs)
fit <- unmarked::occu(~ effort ~ canopy, data = umf)
# several seasons
x <- pam_model_input(history, binary = TRUE, seasons = pam_define_seasons(history))
umf <- unmarked::unmarkedMultFrame(y = x$y, siteCovs = x$siteCovs, obsCovs = x$obsCovs,
numPrimary = x$num_primary)
The detection formula (before the second ~) may use the observation
covariates effort and day and any site covariate; the other formula uses
site covariates. ubms takes the same unmarkedFrame* objects.
spOccupancy expects a list with the response, the occupancy covariates and
the detection covariates, which are the same pieces under other names (check
the argument names against its documentation):
x <- pam_model_input(history, binary = TRUE) # one species
data <- list(y = x$y, occ.covs = x$siteCovs, det.covs = x$obsCovs,
coords = coords) # coords: your site coordinates, same row order
x <- pam_model_input(histories, binary = TRUE) # several species
data <- list(y = x$y, occ.covs = x$siteCovs, det.covs = x$obsCovs, coords = coords)
For several species y has the species first (species x sites x occasions).
With seasons use y_array and obsCovs_array. x$site_ids gives the site
order.
Counts are numbers of detections, not numbers of animals. A model fitted to
them gives a relative abundance index, not a population size. N-mixture
models also slow down when counts are large (the upper bound K must exceed
the highest count), so count = "files" in pam_count_history() or shorter
occasions are often better than raw event counts.
Site covariates with missing values cannot be used by model functions; a warning names them.
An object of class pam_model_input. For one species and no seasons
it is a list with
y: integer matrix, sites in rows and occasions in columns, NA where a
site was not surveyed;
siteCovs: data frame of site covariates, one row per site (row names
are the site identifiers); NULL if there are none;
obsCovs: named list of matrices shaped like y: effort (recorded
hours, when the history has it) and day (days since the first
occasion);
site_ids, species, count, binary;
scaling: center and scale of every standardized covariate.
With several species, y is an array (species, sites, occasions) and
species lists the species. With seasons, the list also has
y_array: sites x seasons x occasions within season (with a leading
species dimension for several species); y is then the wide matrix
sites x (seasons * occasions) for one species, and NULL for several;
obsCovs (wide matrices) and obsCovs_array (arrays), shaped like y
and y_array;
num_primary (number of seasons), n_secondary (occasions per season,
including padding), seasons (with the number of occasions found) and
occasion_map (which original occasion went where);
with season_covariates: yearlySiteCovs (data frame, one row per site
and season, sites first) and yearlySiteCovs_matrices (sites x seasons).
The layout of y is stored in attr(x, "layout"); pam_check_model_input()
uses it.
pam_count_history(), pam_count_histories(), pam_define_seasons(),
pam_check_model_input()
counts <- matrix(c(0, 2, 5, 1, 0, 3, 4, 0, 2, 1, 1, 0), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, site_covariates = data.frame(canopy = c(0.2, 0.5, 0.9)), effort = matrix(24, 3, 4), species = "Example species") x <- pam_model_input(hist) x$y x$siteCovs names(x$obsCovs) # detection / non-detection instead of counts, covariates standardized pam_model_input(hist, binary = TRUE, standardize = TRUE)$ycounts <- matrix(c(0, 2, 5, 1, 0, 3, 4, 0, 2, 1, 1, 0), nrow = 3, dimnames = list(c("site_a", "site_b", "site_c"), NULL)) hist <- pam_as_count_history(counts, site_covariates = data.frame(canopy = c(0.2, 0.5, 0.9)), effort = matrix(24, 3, 4), species = "Example species") x <- pam_model_input(hist) x$y x$siteCovs names(x$obsCovs) # detection / non-detection instead of counts, covariates standardized pam_model_input(hist, binary = TRUE, standardize = TRUE)$y
Automatically detects and extracts recording timestamp from filename (ISO formats, 14-digit, 12-digit) or falls back to file modification time. Timestamps are returned as local time strings.
pam_parse_datetime(filename, file_path = NULL, timezone = "Asia/Kolkata")pam_parse_datetime(filename, file_path = NULL, timezone = "Asia/Kolkata")
filename |
Character, filename or base name. |
file_path |
Optional character path to file for metadata fallback. |
timezone |
Character string timezone (e.g. "Asia/Kolkata"). |
Character string timestamp in "YYYYMMDD_HHMMSS" format.
pam_parse_datetime("G0059_20260405_183000.wav") pam_parse_datetime("SM4_260405183000.wav") # 12-digit stamp: yymmddhhmmsspam_parse_datetime("G0059_20260405_183000.wav") pam_parse_datetime("SM4_260405183000.wav") # 12-digit stamp: yymmddhhmmss
Parse grid and start time from recording filenames
pam_parse_filenames(files, pattern, timezone)pam_parse_filenames(files, pattern, timezone)
files |
Character vector of file paths. |
pattern |
PCRE regex with named groups |
timezone |
Olson timezone of the filename timestamps (local time). |
A data.table with file_path, file_name, grid, start_time
(POSIXct) and valid_name. Files that don't match get NA and
valid_name = FALSE; they are never dropped.
ex <- pam_example_project() # the second name does not match the pattern, so it is flagged, not dropped pam_parse_filenames(c(ex$files[1], "not_a_recording.wav"), pattern = ex$cfg$filenames$pattern, timezone = "Asia/Kolkata")ex <- pam_example_project() # the second name does not match the pattern, so it is flagged, not dropped pam_parse_filenames(c(ex$files[1], "not_a_recording.wav"), pattern = ex$cfg$filenames$pattern, timezone = "Asia/Kolkata")
Split pending work into batches, skipping completed items
pam_pending_batches(all_ids, checkpoint_path, batch_size = 500L)pam_pending_batches(all_ids, checkpoint_path, batch_size = 500L)
all_ids |
Character vector of every ID to process. |
checkpoint_path |
Checkpoint file path. |
batch_size |
Number of IDs per batch. |
A list of character vectors (empty list if nothing is pending).
ckpt <- tempfile(fileext = ".txt") ids <- c("a.wav", "b.wav", "c.wav") pam_pending_batches(ids, ckpt, batch_size = 2) # all three are pending pam_checkpoint_add("a.wav", ckpt) pam_pending_batches(ids, ckpt, batch_size = 2) # only b and c are left unlink(ckpt)ckpt <- tempfile(fileext = ".txt") ids <- c("a.wav", "b.wav", "c.wav") pam_pending_batches(ids, ckpt, batch_size = 2) # all three are pending pam_checkpoint_add("a.wav", ckpt) pam_pending_batches(ids, ckpt, batch_size = 2) # only b and c are left unlink(ckpt)
Draws the result of pam_activity() with one panel per species: bars for the
hour of the day, a line for days, weeks and months.
pam_plot_activity(activity, species = NULL, relative = FALSE)pam_plot_activity(activity, species = NULL, relative = FALSE)
activity |
A pooled table from |
species |
Optional species (scientific or common name as in the table)
to plot; |
relative |
If |
A ggplot object.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) act <- suppressMessages(pam_activity(ex$cfg, by = "hour")) p <- pam_plot_activity(act) class(p)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) act <- suppressMessages(pam_activity(ex$cfg, by = "hour")) p <- pam_plot_activity(act) class(p)
Plot species richness
pam_plot_richness(x, type = c("accumulation", "sites"))pam_plot_richness(x, type = c("accumulation", "sites"))
x |
The result of |
type |
|
A ggplot object.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) rich <- suppressMessages(pam_richness(ex$cfg)) p <- pam_plot_richness(rich, "sites") class(p)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) rich <- suppressMessages(pam_richness(ex$cfg)) p <- pam_plot_richness(rich, "sites") class(p)
Assembles the run's detections, applies pam_clean_detections() using the
processing settings of the config, and writes the results to
<detections>/<run_id>/processed/.
pam_process_detections(cfg, run_id = cfg$birdnet$run_id)pam_process_detections(cfg, run_id = cfg$birdnet$run_id)
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). Defaults to birdnet$run_id. |
Writes detections_clean.csv, removed_detections.csv (with the
reason for each removal) and processing_steps.csv. Times are written as
local-time text. Run with
pam_run_stage("04_process", pam_process_detections, cfg, run_id = "...").
A list: clean, removed, steps (see pam_clean_detections()).
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) out <- suppressMessages(pam_process_detections(ex$cfg)) out$steps # the results are also written to the run folder list.files(file.path(ex$cfg$paths$detections, "run01", "processed"))ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) out <- suppressMessages(pam_process_detections(ex$cfg)) out$steps # the results are also written to the run folder list.files(file.path(ex$cfg$paths$detections, "run01", "processed"))
Decodes FLAC to a temporary WAV internally when needed. Returned object is
always a standard tuneR::Wave S4 object usable by seewave and
soundecology.
pam_read_audio(path, from = NULL, to = NULL)pam_read_audio(path, from = NULL, to = NULL)
path |
Character. Audio file path. |
from |
Numeric. Optional start time in seconds. |
to |
Numeric. Optional end time in seconds. |
A tuneR::Wave S4 object.
ex <- pam_example_project() w <- pam_read_audio(ex$files[1], from = 0.5, to = 1.5) length(w@left) / [email protected] # seconds readex <- pam_example_project() w <- pam_read_audio(ex$files[1], from = 0.5, to = 1.5) length(w@left) / w@samp.rate # seconds read
Read and clean the deployment sheet
pam_read_deployments(cfg)pam_read_deployments(cfg)
cfg |
A |
Columns are matched by position (deployments$columns); everything
is read as text so leading zeros survive. Repairs applied (and nothing
else): "/" and "." date separators become "-", "." in times becomes ":",
seconds are dropped, a blank recovery time becomes
deployments$default_recovery_time, and a recovery year before 2000
(e.g. 15-04-0206) is replaced by the deployment year. Rows that still
can't be parsed get NA and are listed by pam_check_deployments().
A data.table with the configured columns plus deploy_start,
retrieve_end (POSIXct, local time) and recovery_time_missing. grid
is converted to the filename format (0059 -> "G0059").
ex <- pam_example_project() dep <- pam_read_deployments(ex$cfg) as.data.frame(dep)[, c("deployment_id", "grid", "deploy_start", "retrieve_end")]ex <- pam_example_project() dep <- pam_read_deployments(ex$cfg) as.data.frame(dep)[, c("deployment_id", "grid", "deploy_start", "retrieve_end")]
Samples segments uniformly at random from the recordings, adds them to
<paths$validation>/ground_truth/recall_segments.csv, and never draws the
same segment twice. The ground truth belongs to the audio, not to a
detection run, so it can be reused to compare runs (for example filtered
against unfiltered audio).
pam_recall_draw(cfg, n = cfg$recall$n_segments, run_id = cfg$birdnet$run_id)pam_recall_draw(cfg, n = cfg$recall$n_segments, run_id = cfg$birdnet$run_id)
cfg |
A |
n |
Segments to draw in this round. |
run_id |
Detection run. Only recordings that run processed are sampled, because recall is measured against that run. NULL samples all recordings. |
Invisibly, the newly added rows.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) # run_id = NULL: sample all recordings (a real run would restrict to the files it processed) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 4, run_id = NULL)) as.data.frame(new)[, c("segment_id", "rel", "seg_start", "seg_end")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) # run_id = NULL: sample all recordings (a real run would restrict to the files it processed) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 4, run_id = NULL)) as.data.frame(new)[, c("segment_id", "rel", "seg_start", "seg_end")]
Cuts each segment from the audio chosen by recall$audio ("standardized"
by default, so the truth does not depend on the high-pass filter) and draws
a wide spectrogram. Existing files are kept.
pam_recall_export(cfg, force = FALSE)pam_recall_export(cfg, force = FALSE)
cfg |
A |
force |
Recreate all files. |
Invisibly, list(n_ok, n_failed, failed_ids).
if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 3, run_id = NULL)) out <- suppressMessages(pam_recall_export(ex$cfg)) out$n_ok }if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_recall_draw(ex$cfg, n = 3, run_id = NULL)) out <- suppressMessages(pam_recall_export(ex$cfg)) out$n_ok }
Cuts every QC-passed, in-deployment recording into consecutive,
non-overlapping segments of segment_s seconds (a final piece shorter than
a segment is dropped).
pam_recall_frame(master, segment_s = 60, hours = NULL)pam_recall_frame(master, segment_s = 60, hours = NULL)
master |
Table with |
segment_s |
Segment length in seconds. |
hours |
Optional c(from, to): keep only segments whose local start hour is >= from and < to (e.g. c(4, 18)). |
A data.table with one row per segment: rel, grid,
recording_start, seg_start, seg_end (seconds into the file),
slot_time, hour, seg_key.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) master <- res$master master$rel <- file.path(master$grid, master$file_name) # path relative to the audio folder master$recording_start <- master$start_time # the example recordings are 2 s long, so use 1 s segments (the default is 60 s) frame <- pam_recall_frame(master, segment_s = 1) nrow(frame) as.data.frame(frame)[1:3, c("rel", "seg_start", "seg_end")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) master <- res$master master$rel <- file.path(master$grid, master$file_name) # path relative to the audio folder master$recording_start <- master$start_time # the example recordings are 2 s long, so use 1 s segments (the default is 60 s) frame <- pam_recall_frame(master, segment_s = 1) nrow(frame) as.data.frame(frame)[1:3, c("rel", "seg_start", "seg_end")]
The unit is a segment x species: a species is "detected" in a segment if the detector has an event of that species overlapping the segment at or above the threshold, and "present" if the annotator marked it. Possibly-present pairs are left out of the counts.
pam_recall_metrics( truth, segments, events, classes = NULL, thresholds = c(0.3, 0.4, 0.5, 0.7) )pam_recall_metrics( truth, segments, events, classes = NULL, thresholds = c(0.3, 0.4, 0.5, 0.7) )
truth |
Annotation table ( |
segments |
Segment table ( |
events |
Detector events from |
classes |
Scientific names of the classifier's classes. |
thresholds |
Confidence thresholds to evaluate. |
With simple random sampling of segments the estimates apply to the
sampled recordings and hours. A species that is rarely present in random
segments has few n_present and an uncertain recall.
A data.table with one row per species (and "ALL", summed over
species) and threshold: tp, fn, fp, tn, n_present, recall,
recall_low, recall_high, precision, precision_low,
precision_high, f1.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) segments <- suppressMessages(pam_recall_draw(ex$cfg, n = 12, run_id = NULL)) events <- suppressMessages(pam_validation_pool(ex$cfg)) # normally the annotation app records what an expert hears; here we pretend the # parakeet is present in every segment truth <- data.table::data.table(segment_id = segments$segment_id, present = "Psittacula longicauda_Long-tailed Parakeet", possible = NA_character_) m <- pam_recall_metrics(truth, segments, events, thresholds = c(0.3, 0.5)) m <- as.data.frame(m) m[m$scientific_name == "ALL", c("threshold", "n_present", "tp", "fn", "fp", "recall", "precision")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) segments <- suppressMessages(pam_recall_draw(ex$cfg, n = 12, run_id = NULL)) events <- suppressMessages(pam_validation_pool(ex$cfg)) # normally the annotation app records what an expert hears; here we pretend the # parakeet is present in every segment truth <- data.table::data.table(segment_id = segments$segment_id, present = "Psittacula longicauda_Long-tailed Parakeet", possible = NA_character_) m <- pam_recall_metrics(truth, segments, events, thresholds = c(0.3, 0.5)) m <- as.data.frame(m) m[m$scientific_name == "ALL", c("threshold", "n_present", "tp", "fn", "fp", "recall", "precision")]
Compares a run's detections with the ground-truth annotations and writes
recall_by_species_threshold.csv to <detections>/<run_id>/validation/.
Only annotated segments from recordings the run processed are used.
pam_recall_report( cfg, run_id = cfg$birdnet$run_id, thresholds = NULL, pool = NULL )pam_recall_report( cfg, run_id = cfg$birdnet$run_id, thresholds = NULL, pool = NULL )
cfg |
A |
run_id |
Detection run. |
thresholds |
Confidence thresholds. Default: the band edges of
|
pool |
Optional pool from |
A list: metrics (see pam_recall_metrics()), n_segments,
n_no_species, n_other_only.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) segments <- suppressMessages(pam_recall_draw(ex$cfg, n = 12, run_id = NULL)) gt_dir <- file.path(ex$cfg$paths$validation, "ground_truth") # normally the annotation app writes this file; here the parakeet is "heard" everywhere truth <- data.frame(segment_id = segments$segment_id, present = "Psittacula longicauda_Long-tailed Parakeet", possible = "", other = "", none_audible = FALSE, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(truth, file.path(gt_dir, "recall_annotations.csv"), row.names = FALSE) rep <- suppressMessages(pam_recall_report(ex$cfg)) rep$n_segmentsex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) segments <- suppressMessages(pam_recall_draw(ex$cfg, n = 12, run_id = NULL)) gt_dir <- file.path(ex$cfg$paths$validation, "ground_truth") # normally the annotation app writes this file; here the parakeet is "heard" everywhere truth <- data.frame(segment_id = segments$segment_id, present = "Psittacula longicauda_Long-tailed Parakeet", possible = "", other = "", none_audible = FALSE, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(truth, file.path(gt_dir, "recall_annotations.csv"), row.names = FALSE) rep <- suppressMessages(pam_recall_report(ex$cfg)) rep$n_segments
Simple random sample of segments
pam_recall_sample(frame, n, seed = 1L, exclude_keys = character())pam_recall_sample(frame, n, seed = 1L, exclude_keys = character())
frame |
Segments from |
n |
Number of segments. |
seed |
Random seed. |
exclude_keys |
|
A data.table of min(n, available) segments.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) master <- res$master master$rel <- file.path(master$grid, master$file_name) # path relative to the audio folder master$recording_start <- master$start_time frame <- pam_recall_frame(master, segment_s = 1) pick <- pam_recall_sample(frame, n = 3, seed = 1) as.data.frame(pick)[, c("rel", "seg_start", "seg_end")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) master <- res$master master$rel <- file.path(master$grid, master$file_name) # path relative to the audio folder master$recording_start <- master$start_time frame <- pam_recall_frame(master, segment_s = 1) pick <- pam_recall_sample(frame, n = 3, seed = 1) as.data.frame(pick)[, c("rel", "seg_start", "seg_end")]
Gathers outputs from all completed stages and renders summary reports in HTML, PDF and/or Excel format.
pam_report( cfg, run_id = cfg$birdnet$run_id, formats = cfg$report$formats, output_dir = cfg$paths$reports, force = FALSE )pam_report( cfg, run_id = cfg$birdnet$run_id, formats = cfg$report$formats, output_dir = cfg$paths$reports, force = FALSE )
cfg |
A list from |
run_id |
Character. The detection run to report on. Defaults to
|
formats |
Character vector. One or more of |
output_dir |
Character. Directory for the output files.
Defaults to |
force |
Logical. Overwrite existing reports? Default FALSE. |
HTML and PDF are rendered from an R Markdown template using
rmarkdown::render. PDF requires a LaTeX installation
(e.g. tinytex::install_tinytex()). If PDF rendering fails,
a warning is issued and the other formats are still produced.
Excel output is a multi-sheet workbook with one sheet per report
section, created with openxlsx.
Besides recording effort, detections, validation and occupancy, the report
includes species richness and diversity per site (with the species
accumulation curve and the Chao2 estimate), activity patterns (detections
per recorded hour by hour of the day and by week) and the per-species
thresholds saved by pam_species_thresholds(). A section is left out
when its inputs are not available.
Invisibly, a character vector of generated file paths.
if (requireNamespace("rmarkdown", quietly = TRUE) && rmarkdown::pandoc_available()) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) occ <- suppressMessages(pam_build_occupancy(ex$cfg)) files <- suppressMessages(pam_report(ex$cfg, formats = "html")) basename(files) }if (requireNamespace("rmarkdown", quietly = TRUE) && rmarkdown::pandoc_available()) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) occ <- suppressMessages(pam_build_occupancy(ex$cfg)) files <- suppressMessages(pam_report(ex$cfg, formats = "html")) basename(files) }
Turns the cleaned detections into species richness and diversity: for every
site and time bin, for every site over the whole survey, and across sites
(species accumulation and an estimate of how many species were missed). The
site table can be joined to habitat covariates by site_id to study how
richness varies with the environment.
pam_richness( cfg, run_id = cfg$birdnet$run_id, bin_days = NULL, min_events = 1, abundance = c("counts", "presence"), q = c(1, 2), thresholds = NULL, species = NULL, min_effort_hours = NULL, write = FALSE )pam_richness( cfg, run_id = cfg$birdnet$run_id, bin_days = NULL, min_events = 1, abundance = c("counts", "presence"), q = c(1, 2), thresholds = NULL, species = NULL, min_effort_hours = NULL, write = FALSE )
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). |
bin_days |
Length of a time bin in days. |
min_events |
A species counts as present in a site and bin only when it has at least this many events there (a whole number, default 1). A higher number removes species known only from a lone, possibly false, detection, at the cost of missing rare species. |
abundance |
How species are weighted in the Hill numbers: |
q |
Orders of the Hill numbers to compute besides richness (default 1 and 2). Richness is the Hill number of order 0 and is always returned. |
thresholds |
Optional per-species thresholds (a data frame, or the path
of a CSV file, with |
species |
Optional species to keep (scientific names, common names or
species labels). |
min_effort_hours |
Minimum recorded hours for a bin to count as
surveyed. |
write |
If |
Hill numbers describe diversity as an effective number of species. Order 1
is the number of equally common species that gives the same Shannon
diversity, and order 2 the same for the Simpson index; larger orders give
more weight to the dominant species. With abundance = "counts" a loud, vocal
species weighs more than a quiet one, so the numbers describe the acoustic
community; use "presence" when only occurrence matters. A bin with no
species has richness 0 and NA for the other orders.
Sites are the sampling units. accumulation is the exact expected number of
species found in n randomly chosen surveyed sites (sample-based
rarefaction), so curves from different projects can be compared at the same
number of sites. The Chao2 estimate uses how many species were found in only
one or two sites to estimate how many remain undetected; treat it as a lower
bound. A species with a false-positive detection counts as present, so
validated thresholds and min_events matter for all of these numbers.
A list of class pam_richness:
occasions: one row per site and bin: richness, hill_q<q> columns,
n_events (events of the species counted as present), effort_hours,
n_days, sufficient. Bins below the minimum effort are kept and
flagged.
sites: one row per site, using only surveyed bins: richness,
hill_q<q>, n_events, n_occasions_surveyed, effort_hours.
accumulation: the expected number of species (richness) for
n_sites = 1 to the number of surveyed sites.
estimates: one row with the observed richness, the Chao2 estimate of
the total and completeness (observed divided by estimated).
settings: the choices that were used.
pam_plot_richness(), pam_detection_table()
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) rich <- suppressMessages(pam_richness(ex$cfg)) as.data.frame(rich$sites)[, c("site_id", "richness", "hill_q1", "hill_q2")] rich$estimates # count a species only when it has at least two events in a bin strict <- suppressMessages(pam_richness(ex$cfg, min_events = 2)) strict$sites$richnessex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) rich <- suppressMessages(pam_richness(ex$cfg)) as.data.frame(rich$sites)[, c("site_id", "richness", "hill_q1", "hill_q2")] rich$estimates # count a species only when it has at least two events in a bin strict <- suppressMessages(pam_richness(ex$cfg, min_events = 2)) strict$sites$richness
Logs start time, end time, duration and every warning, and converts errors into a logged failure instead of terminating the whole workflow.
pam_run_stage(stage, fn, cfg, ...)pam_run_stage(stage, fn, cfg, ...)
stage |
Stage name (e.g. "03_detect"). |
fn |
Function taking |
cfg |
A |
... |
Passed on to |
A list: status ("ok" or "failed"), result, duration (difftime),
warnings (character).
ex <- pam_example_project() res <- suppressMessages(pam_run_stage("demo", function(cfg, x) x * 2, ex$cfg, x = 21)) res$status res$result # an error is logged and returned as a failed status; it does not stop your script bad <- suppressMessages(pam_run_stage("demo_fail", function(cfg) stop("boom"), ex$cfg)) bad$statusex <- pam_example_project() res <- suppressMessages(pam_run_stage("demo", function(cfg, x) x * 2, ex$cfg, x = 21)) res$status res$result # an error is logged and returned as a failed status; it does not stop your script bad <- suppressMessages(pam_run_stage("demo_fail", function(cfg) stop("boom"), ex$cfg)) bad$status
Lists WAV/FLAC files, parses filenames, reads headers (cached, so re-runs only read new files and an interrupted run resumes), joins deployments, adds QC flags, and writes the master table and summaries.
pam_scan_audio(cfg, force = FALSE)pam_scan_audio(cfg, force = FALSE)
cfg |
A |
force |
If TRUE, discard the header cache and re-read every file. |
Writes metadata/audio_headers.csv (cache), metadata/audio_master.csv,
outputs/audio_summary_per_grid.csv and outputs/deployment_issues.csv.
Times in CSV files are written as UTC (ISO 8601) by data.table::fwrite.
Run with pam_run_stage("01_scan", pam_scan_audio, cfg) for logging.
Audio discovery uses pam_list_audio() (WAV + FLAC). Header reading uses
pam_audio_info().
A list: master, deployments, summary.
ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) res$summary$overall # the master table and summaries are also written to the project list.files(ex$cfg$paths$metadata)ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) res$summary$overall # the master table and summaries are also written to the project list.files(ex$cfg$paths$metadata)
Batch Process Audio Files for Soundscape Indices
pam_soundscape_batch(file_list, cfg, test_n = NULL)pam_soundscape_batch(file_list, cfg, test_n = NULL)
file_list |
Character vector. File paths to audio files (WAV or FLAC). |
cfg |
List. Parsed configuration structure. |
test_n |
Integer. Optional. Process only this many files (for tests). |
A data.table containing raw soundscape index values.
Reads WAV or FLAC via pam_read_audio, optionally downsamples
to 24 kHz, applies a high-pass filter at sub-window level, and computes
configured acoustic indices (ACI, ADI, AEve, Bio, H, M, NDSI).
pam_soundscape_one( audio_path, low_stop_hz = NULL, cfg = NULL, window_sec = NULL )pam_soundscape_one( audio_path, low_stop_hz = NULL, cfg = NULL, window_sec = NULL )
audio_path |
Character. Path to input audio file ( |
low_stop_hz |
Numeric. Highpass low-stop frequency in Hz (default 500). |
cfg |
List. Parsed configuration structure from |
window_sec |
Numeric. Optional window duration in seconds. |
A data.table with file/window metadata and index values.
if (requireNamespace("soundecology", quietly = TRUE)) { ex <- pam_example_project() # the example tones are only 2 s long and 8 kHz, so some indices come out as NA pam_soundscape_one(ex$files[1], cfg = ex$cfg) }if (requireNamespace("soundecology", quietly = TRUE)) { ex <- pam_example_project() # the example tones are only 2 s long and 8 kHz, so some indices come out as NA pam_soundscape_one(ex$files[1], cfg = ex$cfg) }
Generates line plots showing index values across 0-23 hours grouped by grid site.
pam_soundscape_plot_diel(hourly_dt, indices = NULL, out_dir = NULL, cfg = NULL)pam_soundscape_plot_diel(hourly_dt, indices = NULL, out_dir = NULL, cfg = NULL)
hourly_dt |
|
indices |
Character vector. Acoustic indices to plot (e.g. |
out_dir |
Character. Optional output directory to save plot images. |
cfg |
List. Optional configuration structure. |
A list of ggplot objects.
Generates bar plots comparing mean values between Day and Night phases per grid site.
pam_soundscape_plot_phase(diel_dt, indices = NULL, out_dir = NULL, cfg = NULL)pam_soundscape_plot_phase(diel_dt, indices = NULL, out_dir = NULL, cfg = NULL)
diel_dt |
|
indices |
Character vector. Acoustic indices to plot. If NULL, auto-detects. |
out_dir |
Character. Optional output directory to save plot images. |
cfg |
List. Optional configuration structure. |
A list of ggplot objects.
Compiles an HTML diagnostic report summarizing soundscape indices, site covariates,
and diel visualizations using the template at inst/rmd/soundscape_report.Rmd.
pam_soundscape_report(cfg, sc_results = NULL, vis_results = NULL)pam_soundscape_report(cfg, sc_results = NULL, vis_results = NULL)
cfg |
List. Parsed configuration structure from |
sc_results |
List. Optional return object from |
vis_results |
List. Return object from |
Character. Path to the generated HTML report file.
Discovers WAV/FLAC files via pam_list_audio, computes indices
with pam_soundscape_batch, and writes hourly/diel/site summaries.
pam_soundscape_run(cfg, test_n = NULL)pam_soundscape_run(cfg, test_n = NULL)
cfg |
List. Parsed configuration structure from |
test_n |
Integer. Optional. Process only this many files (for tests). |
A named list containing raw, hourly, diel, and site_covariates.
Takes parsed config and optional previous Stage 2b results, loads soundscape summary tables, exports diagnostic diel plots, and generates an HTML report.
pam_soundscape_run_vis(cfg, sc_results = NULL, generate_report = TRUE)pam_soundscape_run_vis(cfg, sc_results = NULL, generate_report = TRUE)
cfg |
List. Parsed configuration structure from |
sc_results |
List. Optional return object from |
generate_report |
Logical. If TRUE, compiles an HTML diagnostic report. |
A named list of generated ggplot objects.
Summarize Soundscape Indices into Hourly, Diel, and Site Covariate Metrics
pam_soundscape_summarise(raw_dt, master_dt, cfg = NULL)pam_soundscape_summarise(raw_dt, master_dt, cfg = NULL)
raw_dt |
|
master_dt |
|
cfg |
List. Parsed configuration structure. |
A named list containing hourly, diel, and site_covariates.
Species differ a lot in how reliable BirdNET is, so one confidence cut-off for all species is rarely right. This function reads the reviewed verdicts of Stage 5 and gives every species its own threshold, without asking you for a precision target.
pam_species_thresholds( cfg, run_id = cfg$birdnet$run_id, tolerance = 0.05, min_judged = 10, min_coverage = 0.5, manual = NULL, write = FALSE )pam_species_thresholds( cfg, run_id = cfg$birdnet$run_id, tolerance = 0.05, min_judged = 10, min_coverage = 0.5, manual = NULL, write = FALSE )
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). |
tolerance |
How far below its own best estimated precision a species may fall (a number between 0 and 1, default 0.05). |
min_judged |
Minimum number of judged samples (correct or incorrect) a species needs; species with fewer get the default threshold. |
min_coverage |
A confidence level only counts when at least this share of the species' events at or above it lies in bands that were reviewed (default 0.5). |
manual |
Optional data frame, or path to a CSV file, with the columns
|
write |
If |
For each species, the estimated precision of all events at or above each
confidence band edge comes from pam_validation_metrics(). The species'
best estimated precision is found, and the lowest confidence whose
precision is within tolerance of that best value is chosen. Going higher
than that would discard detections without making them noticeably more
reliable. A species with a flat precision curve therefore keeps a low
threshold, and one that needs a high threshold gets one.
A species with too few judged samples, or no confidence level with enough
reviewed events, gets processing$min_confidence and method = "default";
the reason column says why. Manual values always win (method = "manual").
Save it with write = TRUE and set processing$species_thresholds_file in
the config to that file. Stage 4 and Stage 6 read it; the columns they do
not need are ignored.
A data.table with one row per species: scientific_name,
threshold, method, precision_est (estimated precision of the events
kept), coverage, n_judged, n_events_kept and reason.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) thr <- suppressMessages(pam_species_thresholds(ex$cfg, min_judged = 1)) as.data.frame(thr)[, c("scientific_name", "threshold", "method")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) thr <- suppressMessages(pam_species_thresholds(ex$cfg, min_judged = 1)) as.data.frame(thr)[, c("scientific_name", "threshold", "method")]
Interactive GUI for inspecting raw acoustic data, parsing timestamps, previewing conversions, isolating non-audio/memo files, and performing standardized audio transcoding.
pam_standardization_app(cfg = NULL, raw_dir = NULL, lang = NULL)pam_standardization_app(cfg = NULL, raw_dir = NULL, lang = NULL)
cfg |
Optional configuration object from |
raw_dir |
Optional path override for raw audio directory. |
lang |
Interface language code (for example |
Runs Shiny application.
if (interactive()) { ex <- pam_example_project() pam_standardization_app(ex$cfg, raw_dir = ex$audio_dir) }if (interactive()) { ex <- pam_example_project() pam_standardization_app(ex$cfg, raw_dir = ex$audio_dir) }
Standardizes raw audio datasets by organizing folders, parsing timestamps, converting formats (WAV/FLAC), resampling, mixing channels to mono, isolating non-audio/memos, and logging results.
pam_standardize( cfg = NULL, raw_dir = NULL, standardized_dir = NULL, isolated_dir = NULL, dry_run = NULL, prefix = NULL, target_format = NULL, target_hz = NULL, channels = NULL, min_duration_s = NULL, organize_folders = NULL, rename_strategy = NULL, isolate_non_audio = NULL, isolate_short = NULL, timezone = NULL )pam_standardize( cfg = NULL, raw_dir = NULL, standardized_dir = NULL, isolated_dir = NULL, dry_run = NULL, prefix = NULL, target_format = NULL, target_hz = NULL, channels = NULL, min_duration_s = NULL, organize_folders = NULL, rename_strategy = NULL, isolate_non_audio = NULL, isolate_short = NULL, timezone = NULL )
cfg |
Optional configuration object from |
raw_dir |
Directory containing raw audio files. |
standardized_dir |
Directory to save standardized audio. Required (here
or in |
isolated_dir |
Directory to save isolated non-audio and memo files.
Required (here or in |
dry_run |
Logical, if TRUE simulates actions without modifying disk. |
prefix |
Prefix string prepended to standardized filenames. |
target_format |
Output format: "flac" or "wav". |
target_hz |
Target sample rate (Hz). If NULL or higher than input, original rate is kept. |
channels |
Target audio channels (1 = mono, 2 = stereo). |
min_duration_s |
Minimum duration threshold for valid recordings (default 60s). |
organize_folders |
Subfolder structure: "grid" (G0059/), "date" (YYYY/MM/DD), "grid_date" (G0059/YYYY/MM/DD), "preserve", or "flat". |
rename_strategy |
Naming strategy: "auto" (uses extracted datetime) or "keep". |
isolate_non_audio |
Logical, isolate non-audio files? |
isolate_short |
Logical, isolate short audio clips? |
timezone |
Timezone string (default "Asia/Kolkata"). |
data.table containing audit log of standardization operations.
ex <- pam_example_project() demo <- tempfile("pamflow_std_") # dry_run = TRUE only plans what would happen; nothing is written plan <- suppressMessages(pam_standardize( ex$cfg, raw_dir = ex$audio_dir, standardized_dir = file.path(demo, "standardized"), isolated_dir = file.path(demo, "isolated"), dry_run = TRUE, target_format = "wav", min_duration_s = 1)) table(plan$action) if (requireNamespace("av", quietly = TRUE)) { # convert for real: the example WAV files become FLAC done <- suppressMessages(pam_standardize( ex$cfg, raw_dir = ex$audio_dir, standardized_dir = file.path(demo, "standardized"), isolated_dir = file.path(demo, "isolated"), target_format = "flac", min_duration_s = 1)) table(done$action) } unlink(demo, recursive = TRUE)ex <- pam_example_project() demo <- tempfile("pamflow_std_") # dry_run = TRUE only plans what would happen; nothing is written plan <- suppressMessages(pam_standardize( ex$cfg, raw_dir = ex$audio_dir, standardized_dir = file.path(demo, "standardized"), isolated_dir = file.path(demo, "isolated"), dry_run = TRUE, target_format = "wav", min_duration_s = 1)) table(plan$action) if (requireNamespace("av", quietly = TRUE)) { # convert for real: the example WAV files become FLAC done <- suppressMessages(pam_standardize( ex$cfg, raw_dir = ex$audio_dir, standardized_dir = file.path(demo, "standardized"), isolated_dir = file.path(demo, "isolated"), target_format = "flac", min_duration_s = 1)) table(done$action) } unlink(demo, recursive = TRUE)
A standalone tool, not a workflow stage: a point-and-click interface for
training a custom BirdNET classifier, laid out
like the training tab of the BirdNET-Analyzer GUI: training data, cache,
frequency and speed, cropping, autotune, training settings and the model save
mode. It shows the progress and the learning curves while training runs, can
repeat a training several times to show how much the scores vary, keeps a
history of earlier runs, and gives the birdnet: config lines that use the
trained model.
pam_train_app( cfg = NULL, data_dir = NULL, output_dir = NULL, lang = NULL, envdir = pam_birdnet_env_dir("training") )pam_train_app( cfg = NULL, data_dir = NULL, output_dir = NULL, lang = NULL, envdir = pam_birdnet_env_dir("training") )
cfg |
Optional configuration from |
data_dir |
Optional training folder to start with (one sub-folder per class). |
output_dir |
Optional output folder to start with. |
lang |
Interface language code (for example |
envdir |
Folder of the training Python environment (see
|
This is a standalone tool: it is not a stage of the workflow and no workflow
function calls it. Use the trained model by pointing the birdnet: section of
the config at it.
Training runs in a separate process, so the app stays responsive and
Stop ends the training and everything it started. Closing the app also stops
a running training. The settings shown are the BirdNET-Analyzer 2.4.0
defaults; each value you see is the value used, and it is recorded in the
run's _run.yml. The first training downloads the base BirdNET model
(about 224 MB) once.
The scores shown come from clips held out of the training folder and are therefore optimistic; give a separate test folder for a more honest estimate.
A Shiny app object. Printing it at the console starts it, or pass it
to shiny::runApp().
if (interactive()) { pam_train_app() } ## Not run: pam_train_app(data_dir = "E:/clips", output_dir = "E:/models", lang = "en") ## End(Not run)if (interactive()) { pam_train_app() } ## Not run: pam_train_app(data_dir = "E:/clips", output_dir = "E:/models", lang = "en") ## End(Not run)
Shows the exported spectrogram and audio of each sampled event in random
order and records "correct", "incorrect" (plus the true species) or
"unsure". Every save is written immediately to validation_results.csv, so
you can stop at any time and continue later.
pam_validate( cfg, run_id = cfg$birdnet$run_id, reviewer = pam_or(cfg$validation$reviewer, ""), show_confidence = isTRUE(cfg$validation$show_confidence), lang = NULL )pam_validate( cfg, run_id = cfg$birdnet$run_id, reviewer = pam_or(cfg$validation$reviewer, ""), show_confidence = isTRUE(cfg$validation$show_confidence), lang = NULL )
cfg |
A |
run_id |
Detection run. |
reviewer |
Name pre-filled in the app. |
show_confidence |
Show the model's confidence while reviewing. Hidden
by default ( |
lang |
Interface language code (for example |
Nothing; runs until the app is closed.
if (interactive() && nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 5)) out <- suppressMessages(pam_validation_export(ex$cfg)) # clips and spectrograms to review pam_validate(ex$cfg) }if (interactive() && nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 5)) out <- suppressMessages(pam_validation_export(ex$cfg)) # clips and spectrograms to review pam_validate(ex$cfg) }
Each call adds a new round to <detections>/<run_id>/validation/ validation_samples.csv. Events drawn in earlier rounds are never drawn
again, so you can start small and add more later.
pam_validation_draw( cfg, run_id = cfg$birdnet$run_id, strategy = c("stratified", "random", "rare"), n = 100L, species = NULL, n_per_cell = cfg$validation$n_per_cell, pool = NULL )pam_validation_draw( cfg, run_id = cfg$birdnet$run_id, strategy = c("stratified", "random", "rare"), n = 100L, species = NULL, n_per_cell = cfg$validation$n_per_cell, pool = NULL )
cfg |
A |
run_id |
Detection run. |
strategy |
"stratified", "random" or "rare" (see |
n |
Events for the "random" strategy. |
species |
Optional species restriction. |
n_per_cell |
Events per species x band for "stratified". Defaults to
|
pool |
Optional pool from |
Invisibly, the newly added rows.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 5)) as.data.frame(new)[, c("sample_id", "species", "confidence", "clip_file")] # the sample file is written to the run folder file.exists(file.path(ex$cfg$paths$detections, "run01", "validation", "validation_samples.csv"))ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 5)) as.data.frame(new)[, c("sample_id", "species", "confidence", "clip_file")] # the sample file is written to the run folder file.exists(file.path(ex$cfg$paths$detections, "run01", "validation", "validation_samples.csv"))
For every row of validation_samples.csv whose files are missing, cuts a
clip (event plus validation$clip_pad_s seconds of context on each side)
from the audio the run read, and draws a spectrogram PNG with FFmpeg.
Dynamically uses -c:a flac or -c:a pcm_s16le based on the target clip file
extension. Existing files are kept, so it can be rerun after each new round.
pam_validation_export(cfg, run_id = cfg$birdnet$run_id, force = FALSE)pam_validation_export(cfg, run_id = cfg$birdnet$run_id, force = FALSE)
cfg |
A |
run_id |
Detection run. |
force |
Recreate all files. |
Invisibly, list(n_ok, n_failed, failed_ids).
if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 3)) out <- suppressMessages(pam_validation_export(ex$cfg)) out$n_ok }if (nzchar(Sys.which("ffmpeg"))) { ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 3)) out <- suppressMessages(pam_validation_export(ex$cfg)) out$n_ok }
Join the reviewed verdicts to the sample table
pam_validation_import(cfg, run_id = cfg$birdnet$run_id)pam_validation_import(cfg, run_id = cfg$birdnet$run_id)
cfg |
A |
run_id |
Detection run. |
A data.table: one row per reviewed sample, with verdict
("correct", "incorrect", "unsure"), true_species, note, reviewer,
reviewed_at added to the sample columns.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) val <- pam_validation_import(ex$cfg) as.data.frame(val)[, c("sample_id", "species", "confidence", "verdict")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) val <- pam_validation_import(ex$cfg) as.data.frame(val)[, c("sample_id", "species", "confidence", "verdict")]
Precision by species and confidence band, and by confidence threshold
pam_validation_metrics(val, pool, bands)pam_validation_metrics(val, pool, bands)
val |
Reviewed samples from |
pool |
Pool of all events from |
bands |
Confidence band edges used when sampling. |
Recall, false negatives and F1 cannot be estimated from reviewing detections alone: they need a set of recordings in which every call has been annotated independently of the detector.
A list:
cells: per species x band: n_pool, n_reviewed, n_correct,
n_incorrect, n_unsure, n_judged, precision and its 95% Wilson
interval (unsure verdicts are excluded from precision).
thresholds: for each species (and "ALL") and each band edge, the
estimated precision of all events at or above that confidence, weighted
by band size, plus coverage (share of those events that sit in bands
with at least one judged sample).
confusion: counts of predicted species vs the true species entered for
incorrect verdicts.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) val <- pam_validation_import(ex$cfg) pool <- suppressMessages(pam_validation_pool(ex$cfg)) metrics <- pam_validation_metrics(val, pool, bands = unlist(ex$cfg$validation$bands)) as.data.frame(metrics$cells)[, c("scientific_name", "band", "n_pool", "n_reviewed", "precision")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) val <- pam_validation_import(ex$cfg) pool <- suppressMessages(pam_validation_pool(ex$cfg)) metrics <- pam_validation_metrics(val, pool, bands = unlist(ex$cfg$validation$bands)) as.data.frame(metrics$cells)[, c("scientific_name", "band", "n_pool", "n_reviewed", "precision")]
Takes the run's assembled detections through the Stage 4 rules (deployment window, species lists, merging of windows into events) but with the confidence cutoff set to the lowest stored confidence and no species thresholds or seasons, so that events below your intended cutoff can also be reviewed.
pam_validation_pool(cfg, run_id = cfg$birdnet$run_id)pam_validation_pool(cfg, run_id = cfg$birdnet$run_id)
cfg |
A |
run_id |
Detection run (sub-folder of paths$detections). |
A data.table of events with event_id (rel|species|start).
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) pool <- suppressMessages(pam_validation_pool(ex$cfg)) as.data.frame(pool)[, c("species", "confidence", "n_windows", "start_time")]ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) pool <- suppressMessages(pam_validation_pool(ex$cfg)) as.data.frame(pool)[, c("species", "confidence", "n_windows", "start_time")]
Imports the reviewed verdicts, computes pam_validation_metrics() and
writes precision_by_cell.csv, precision_by_threshold.csv and
confusion_incorrect.csv to <detections>/<run_id>/validation/.
pam_validation_report(cfg, run_id = cfg$birdnet$run_id, pool = NULL)pam_validation_report(cfg, run_id = cfg$birdnet$run_id, pool = NULL)
cfg |
A |
run_id |
Detection run. |
pool |
Optional pool from |
The metrics list (see pam_validation_metrics()).
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) metrics <- suppressMessages(pam_validation_report(ex$cfg)) list.files(val_dir, pattern = "^precision")ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) proc <- suppressMessages(pam_process_detections(ex$cfg)) new <- suppressMessages(pam_validation_draw(ex$cfg, strategy = "random", n = 8)) val_dir <- file.path(ex$cfg$paths$detections, "run01", "validation") # normally the review app writes this file; here the verdicts are made up results <- data.frame(sample_id = new$sample_id, verdict = rep_len(c("correct", "correct", "incorrect"), nrow(new)), true_species = NA_character_, note = "", reviewer = "example", reviewed_at = format(Sys.time()), stringsAsFactors = FALSE) utils::write.csv(results, file.path(val_dir, "validation_results.csv"), row.names = FALSE) metrics <- suppressMessages(pam_validation_report(ex$cfg)) list.files(val_dir, pattern = "^precision")
Pure function (no file access). Strategies:
"stratified": up to n_per_cell events per species x confidence band;
restrict to some species with species.
"random": n events drawn at random from the whole pool (or from
species).
"rare": species with at most rare_max_events events in the pool;
up to rare_n events of each.
pam_validation_sample( pool, strategy = c("stratified", "random", "rare"), bands, n_per_cell = 25L, n = 100L, species = NULL, rare_max_events = 30L, rare_n = 50L, seed = 1L, exclude_ids = character() )pam_validation_sample( pool, strategy = c("stratified", "random", "rare"), bands, n_per_cell = 25L, n = 100L, species = NULL, rare_max_events = 30L, rare_n = 50L, seed = 1L, exclude_ids = character() )
pool |
Events from |
strategy |
One of "stratified", "random", "rare". |
bands |
Increasing confidence band edges. |
n_per_cell, n, rare_max_events, rare_n
|
See above. |
species |
Optional names (scientific, common or "Scientific_Common"). |
seed |
Random seed. |
exclude_ids |
|
A data.table: the sampled rows with band_idx and band.
ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) pool <- suppressMessages(pam_validation_pool(ex$cfg)) bands <- unlist(ex$cfg$validation$bands) # at most one event per species and confidence band smp <- pam_validation_sample(pool, "stratified", bands = bands, n_per_cell = 1) as.data.frame(smp)[, c("species", "confidence", "band")] # five events at random from the whole pool rnd <- pam_validation_sample(pool, "random", bands = bands, n = 5, seed = 42) nrow(rnd)ex <- pam_example_project() # the later stages read the master table that the scan builds res <- suppressMessages(pam_scan_audio(ex$cfg)) pool <- suppressMessages(pam_validation_pool(ex$cfg)) bands <- unlist(ex$cfg$validation$bands) # at most one event per species and confidence band smp <- pam_validation_sample(pool, "stratified", bands = bands, n_per_cell = 1) as.data.frame(smp)[, c("species", "confidence", "band")] # five events at random from the whole pool rnd <- pam_validation_sample(pool, "random", bands = bands, n = 5, seed = 42) nrow(rnd)
Wilson score confidence interval for a proportion
pam_wilson_ci(x, n, conf = 0.95)pam_wilson_ci(x, n, conf = 0.95)
x |
Number of successes (vector). |
n |
Number of trials (vector, same length). |
conf |
Confidence level. |
A data.table with low and high (NA where n is 0).
pam_wilson_ci(c(18, 5), c(25, 5))pam_wilson_ci(c(18, 5), c(25, 5))
Implementation of ecoacoustic soundscape indices following Bradfer-Lawrence
et al. (2019) guidelines. Computes core acoustic indices with 1-minute
sub-windowing, checkpointing, multi-core parallel processing, and
timezone-aware hourly/diel summarization. Supports WAV and FLAC via
pam_read_audio / pam_list_audio.
Generates 24-hour diel profiles, day/night comparison plots, and summary visualizations for ecoacoustic soundscape indices.
Safely Extract a Single Numeric Value from Soundecology/Seewave Returns
to_scalar_num(x)to_scalar_num(x)
x |
An object returned by a soundecology/seewave function. |
A length-1 numeric, or NA_real_.
Centralized helpers for cross-format audio reading, metadata inspection, and lossless clip extraction. All downstream pamflow stages route through this module so WAV and FLAC are handled uniformly.