Naturalist Remarks

A script in R for calculation ADI over 20 kHz

In this script I calculated the Acoustic Diversity Index values for acoustic signals of bats over 20 kHz. Here, I filtered frequencies using the bwfilter() function. It is necessary to set n = 8. In this case, acoustic signals from 20 to 15 kHz will still be present but more muted. You have to set bandpass = TRUE and from = 20000 (Hz), in this case signals below 20 kHz will be removed. Below 15 kHz sounds will be practically removed.

library(tuneR)
library(seewave)
library(soundecology)

# 1. DEFINÍCIA ÚLOH
tasks <- list(
  list(
    input = "address of the directory with recordings ",
    output = "address of the output file *.csv"
  ),
  list(
    input = "address of the second directory with recordings",
    output = "address of the output file *.csv"
  )
)

# 2. CYKLUS CEZ ÚLOHY
for (task in tasks) {
  input_dir <- task$input
  output_file <- task$output

  file_list <- list.files(input_dir, pattern = "\\.WAV$", ignore.case = TRUE, full.names = TRUE)

  if (length(file_list) == 0) {
    message(paste("Skipping empty directory:", input_dir))
    next
  }

  message(paste(">>> I am starting to process the directory:", input_dir))
  results <- data.frame(FileName = character(), ADI = numeric(), stringsAsFactors = FALSE)

  # 3. VNÚTORNÝ CYKLUS CEZ SÚBORY
  for (i in 1:length(file_list)) {
    f <- file_list[i]
    try({
      wave_file <- readWave(f)
      wave_file <- rmoffset(wave_file, output = "Wave")
      fs <- wave_file@samp.rate

      filtered_wave <- bwfilter(wave_file, f = fs, n = 8, from = 20000,
                                bandpass = TRUE, output = "Wave")
      rm(wave_file)

      adi_val <- acoustic_diversity(filtered_wave, max_freq = (fs/2), freq_step = 15000)

      results <- rbind(results, data.frame(FileName = basename(f), ADI = adi_val$adi_left))

      rm(filtered_wave)
      gc()

      if (i %% 5 == 0) {
        message(paste(" Actual status processing files:", i, "/", length(file_list)))
      }
    })
  }
    write.csv(results, output_file, row.names = FALSE)
  message(paste("<<< Done. Results saved to:", output_file))
}

message("=== All planned directories were processed. ===")