Skip to content

bioamla.detect

bioamla.detect

Advanced acoustic detection algorithms.

Energy, RIBBIT (periodic call), CWT peak-sequence, and accelerating-pattern detectors. Detectors run on the slim core (librosa + scipy) — no optional extras required. Functions and detector methods return plain data and raise :class:bioamla.exceptions.BioamlaError subclasses on failure.

Example

from bioamla.detect import BandLimitedEnergyDetector detector = BandLimitedEnergyDetector(low_freq=500, high_freq=3000) detections = detector.detect_from_file("recording.wav")

AcceleratingPatternDetector

Detector for accelerating call patterns.

Many species produce vocalizations with increasing or decreasing pulse rates (e.g., tree frog advertisement calls that speed up). This detector identifies such patterns by analyzing inter-pulse intervals.

Parameters:

Name Type Description Default
min_pulses int

Minimum number of pulses to detect pattern.

5
acceleration_threshold float

Minimum acceleration ratio (final_rate/initial_rate).

1.5
low_freq float

Lower frequency bound in Hz.

500.0
high_freq float

Upper frequency bound in Hz.

5000.0
min_pulse_rate float

Minimum expected pulse rate in Hz.

2.0
max_pulse_rate float

Maximum expected pulse rate in Hz.

50.0
window_duration float

Analysis window duration in seconds.

3.0

Raises:

Type Description
InvalidDetectionParams

If high_freq <= low_freq or a frequency bound is negative.

Example

Detect calls that accelerate from 5 to 15+ pulses/sec

detector = AcceleratingPatternDetector( ... min_pulses=5, ... acceleration_threshold=2.0, # 2x speedup ... low_freq=1000, ... high_freq=4000, ... ) detections = detector.detect(audio, sample_rate)

analyze_intervals

analyze_intervals(peak_times: ndarray) -> dict[str, Any]

Analyze inter-peak intervals for acceleration pattern.

Parameters:

Name Type Description Default
peak_times ndarray

Array of peak times in seconds.

required

Returns:

Type Description
dict[str, Any]

Dictionary with interval analysis results.

detect

detect(audio: ndarray, sample_rate: int) -> list[Detection]

Detect accelerating/decelerating call patterns.

Parameters:

Name Type Description Default
audio ndarray

Audio signal as numpy array.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
list[Detection]

List of Detection objects.

Raises:

Type Description
DetectionError

If detection fails.

detect_from_file

detect_from_file(filepath: str | Path) -> list[Detection]

Detect accelerating patterns from an audio file.

Raises:

Type Description
AudioLoadError

If the audio file cannot be loaded.

DetectionError

If detection fails.

BandLimitedEnergyDetector

Band-limited energy detector for frequency-specific sound detection.

This detector filters audio to a specific frequency band and detects regions where the energy exceeds a threshold. Useful for detecting vocalizations that occur in a known frequency range.

Parameters:

Name Type Description Default
low_freq float

Lower frequency bound in Hz.

500.0
high_freq float

Upper frequency bound in Hz.

5000.0
threshold_db float

Detection threshold in dB relative to max energy.

-20.0
min_duration float

Minimum detection duration in seconds.

0.05
merge_threshold float

Merge detections within this many seconds.

0.1
smoothing_window float

Energy smoothing window in seconds.

0.02

Raises:

Type Description
InvalidDetectionParams

If high_freq <= low_freq or a frequency bound is negative.

Example

detector = BandLimitedEnergyDetector(low_freq=1000, high_freq=4000) detections = detector.detect(audio, sample_rate) for d in detections: ... print(f"{d.start_time:.2f}s - {d.end_time:.2f}s: {d.confidence:.2f}")

compute_energy

compute_energy(
    audio: ndarray, sample_rate: int, hop_length: int = 256
) -> tuple[np.ndarray, np.ndarray]

Compute band-limited energy envelope.

Parameters:

Name Type Description Default
audio ndarray

Audio signal.

required
sample_rate int

Sample rate in Hz.

required
hop_length int

Hop length for energy computation.

256

Returns:

Type Description
tuple[ndarray, ndarray]

Tuple of (energy envelope, time axis).

detect

detect(
    audio: ndarray, sample_rate: int, hop_length: int = 256
) -> list[Detection]

Detect sounds in the specified frequency band.

Parameters:

Name Type Description Default
audio ndarray

Audio signal as numpy array.

required
sample_rate int

Sample rate in Hz.

required
hop_length int

Hop length for analysis.

256

Returns:

Type Description
list[Detection]

List of Detection objects.

Raises:

Type Description
DetectionError

If detection fails.

detect_from_file

detect_from_file(
    filepath: str | Path, **kwargs: Any
) -> list[Detection]

Detect sounds from an audio file.

Parameters:

Name Type Description Default
filepath str | Path

Path to audio file.

required
**kwargs Any

Additional arguments for detect().

{}

Returns:

Type Description
list[Detection]

List of Detection objects.

Raises:

Type Description
AudioLoadError

If the audio file cannot be loaded.

DetectionError

If detection fails.

CWTPeakDetector

Peak sequence detector using Continuous Wavelet Transform (CWT).

Uses CWT to identify peaks in the audio energy envelope at multiple scales, providing robust peak detection that's less sensitive to noise and baseline drift.

Parameters:

Name Type Description Default
min_scale int

Minimum wavelet scale.

1
max_scale int

Maximum wavelet scale.

50
n_scales int

Number of scales to analyze.

20
snr_threshold float

Signal-to-noise ratio threshold for peaks.

2.0
min_peak_distance float

Minimum distance between peaks in seconds.

0.01
low_freq float | None

Optional frequency band lower bound.

None
high_freq float | None

Optional frequency band upper bound.

None

Raises:

Type Description
InvalidDetectionParams

If both frequency bounds are given and high_freq <= low_freq.

Example

detector = CWTPeakDetector(snr_threshold=3.0) peaks = detector.detect(audio, sample_rate) for p in peaks: ... print(f"Peak at {p.time:.3f}s, amplitude: {p.amplitude:.2f}")

compute_cwt

compute_cwt(
    signal: ndarray, sample_rate: int
) -> tuple[np.ndarray, np.ndarray]

Compute Continuous Wavelet Transform using convolution.

Parameters:

Name Type Description Default
signal ndarray

Input signal.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
tuple[ndarray, ndarray]

Tuple of (CWT coefficients, scales).

find_ridge_peaks

find_ridge_peaks(
    cwt_matrix: ndarray, sample_rate: int
) -> list[PeakDetection]

Find peaks along ridges in CWT matrix.

Parameters:

Name Type Description Default
cwt_matrix ndarray

CWT coefficient matrix.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
list[PeakDetection]

List of PeakDetection objects.

detect

detect(
    audio: ndarray, sample_rate: int, hop_length: int = 256
) -> list[PeakDetection]

Detect peaks using CWT analysis.

Parameters:

Name Type Description Default
audio ndarray

Audio signal as numpy array.

required
sample_rate int

Sample rate in Hz.

required
hop_length int

Hop length for envelope computation.

256

Returns:

Type Description
list[PeakDetection]

List of PeakDetection objects.

Raises:

Type Description
DetectionError

If detection fails.

detect_sequences

detect_sequences(
    audio: ndarray,
    sample_rate: int,
    min_peaks: int = 3,
    max_gap: float = 1.0,
) -> list[Detection]

Detect sequences of peaks as detections.

Parameters:

Name Type Description Default
audio ndarray

Audio signal.

required
sample_rate int

Sample rate in Hz.

required
min_peaks int

Minimum peaks to form a sequence.

3
max_gap float

Maximum gap between peaks in a sequence.

1.0

Returns:

Type Description
list[Detection]

List of Detection objects.

Raises:

Type Description
DetectionError

If detection fails.

detect_from_file

detect_from_file(
    filepath: str | Path, **kwargs
) -> list[PeakDetection]

Detect peaks from an audio file.

Raises:

Type Description
AudioLoadError

If the audio file cannot be loaded.

DetectionError

If detection fails.

Detection dataclass

Represents a detected acoustic event.

Attributes:

Name Type Description
start_time float

Start time in seconds.

end_time float

End time in seconds.

confidence float

Detection confidence/score (0-1).

frequency_low float | None

Lower frequency bound in Hz.

frequency_high float | None

Upper frequency bound in Hz.

label str

Optional detection label.

metadata dict[str, Any]

Additional metadata.

duration property

duration: float

Duration of detection in seconds.

center_time property

center_time: float

Center time of detection in seconds.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

PeakDetection dataclass

Represents a detected peak in a signal.

Attributes:

Name Type Description
time float

Time of peak in seconds.

amplitude float

Peak amplitude/intensity.

width float

Peak width in seconds.

prominence float

Peak prominence.

frequency float | None

Associated frequency in Hz (if applicable).

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

RibbitDetector

RIBBIT (Repeat-Interval-Based Bioacoustic Identification Tool) detector.

Detects periodic vocalizations by analyzing the autocorrelation of the spectrogram at different pulse rates. Particularly effective for detecting frog calls, insect sounds, and other repetitive vocalizations.

Based on the opensoundscape RIBBIT algorithm.

Parameters:

Name Type Description Default
pulse_rate_hz float

Expected pulse rate in Hz (pulses per second).

10.0
pulse_rate_tolerance float

Tolerance around expected rate (fraction).

0.2
low_freq float

Lower frequency bound in Hz.

500.0
high_freq float

Upper frequency bound in Hz.

5000.0
window_duration float

Analysis window duration in seconds.

2.0
hop_duration float

Hop between analysis windows in seconds.

0.5
min_score float

Minimum detection score threshold.

0.3
n_fft int

FFT size for spectrogram.

1024

Raises:

Type Description
InvalidDetectionParams

If high_freq <= low_freq or a frequency bound is negative.

Example

Detect frog calls with ~10 pulses per second

detector = RibbitDetector( ... pulse_rate_hz=10.0, ... low_freq=500, ... high_freq=3000, ... ) detections = detector.detect(audio, sample_rate)

compute_pulse_score

compute_pulse_score(
    audio: ndarray, sample_rate: int
) -> float

Compute RIBBIT pulse score for an audio segment.

The score measures how well the audio matches the expected periodic pulse rate by analyzing spectrogram autocorrelation.

Parameters:

Name Type Description Default
audio ndarray

Audio segment.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
float

Pulse score (0-1).

detect

detect(audio: ndarray, sample_rate: int) -> list[Detection]

Detect periodic calls using RIBBIT algorithm.

Parameters:

Name Type Description Default
audio ndarray

Audio signal as numpy array.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
list[Detection]

List of Detection objects.

Raises:

Type Description
DetectionError

If detection fails.

compute_temporal_scores

compute_temporal_scores(
    audio: ndarray, sample_rate: int
) -> tuple[np.ndarray, np.ndarray]

Compute RIBBIT scores over time.

Parameters:

Name Type Description Default
audio ndarray

Audio signal.

required
sample_rate int

Sample rate in Hz.

required

Returns:

Type Description
tuple[ndarray, ndarray]

Tuple of (scores array, time axis).

detect_from_file

detect_from_file(filepath: str | Path) -> list[Detection]

Detect periodic calls from an audio file.

Raises:

Type Description
AudioLoadError

If the audio file cannot be loaded.

DetectionError

If detection fails.

AudioLoadError

Bases: BioamlaError

Failed to load or decode an audio file.

DependencyError

Bases: BioamlaError

A required dependency is unavailable at runtime.

All Python dependencies ship in the base install, so this is reserved for genuine environment problems (e.g. a missing system library or a broken install).

DetectionError

Bases: BioamlaError

An acoustic detection (energy, RIBBIT, CWT peaks, patterns) failure.

InvalidDetectionParams

Bases: InvalidInputError

Caller passed invalid parameters to a detector (e.g. high_freq <= low_freq).

batch_detect_dir

batch_detect_dir(
    input_dir: str | Path,
    output_dir: str | Path,
    method: str = "energy",
    *,
    recursive: bool = True,
    continue_on_error: bool = True,
    max_workers: int = 1,
    **params: Any,
) -> BatchResult

Run a detector over every audio file in input_dir.

Discovers audio files, runs the selected detector on each (recording per-file success/failure via :func:bioamla.batch.run_batch), and writes an aggregated detections_<method>.json under output_dir mapping each file to its list of detection dicts.

Parameters:

Name Type Description Default
input_dir str | Path

Directory containing audio files.

required
output_dir str | Path

Directory where the aggregated JSON is written.

required
method str

Detector to run ("energy", "ribbit", "peaks", "accelerating").

'energy'
recursive bool

Whether to recurse into subdirectories.

True
continue_on_error bool

Keep going when an individual file fails.

True
max_workers int

Number of worker processes (1 = sequential).

1
**params Any

Detector-specific parameters (e.g. low_freq, high_freq).

{}

Returns:

Name Type Description
A BatchResult

class:bioamla.batch.BatchResult; its metadata holds the output

BatchResult

file path and total detection count on success.

Raises:

Type Description
InvalidDetectionParams

If method is unknown.

batch_detect

batch_detect(
    filepaths: list[str | Path],
    detector: BandLimitedEnergyDetector
    | RibbitDetector
    | CWTPeakDetector
    | AcceleratingPatternDetector,
    verbose: bool = True,
) -> dict[str, list[Detection]]

Run detection on multiple files.

Per-file failures are logged and recorded as an empty detection list so a single bad file does not abort the whole run.

Parameters:

Name Type Description Default
filepaths list[str | Path]

List of audio file paths.

required
detector BandLimitedEnergyDetector | RibbitDetector | CWTPeakDetector | AcceleratingPatternDetector

Detector instance to use.

required
verbose bool

Print progress.

True

Returns:

Type Description
dict[str, list[Detection]]

Dictionary mapping filepath to list of detections.

detect_all

detect_all(
    audio: ndarray,
    sample_rate: int,
    detectors: list[
        BandLimitedEnergyDetector
        | RibbitDetector
        | CWTPeakDetector
        | AcceleratingPatternDetector
    ],
) -> list[Detection]

Run multiple detectors and combine results.

Parameters:

Name Type Description Default
audio ndarray

Audio signal.

required
sample_rate int

Sample rate in Hz.

required
detectors list[BandLimitedEnergyDetector | RibbitDetector | CWTPeakDetector | AcceleratingPatternDetector]

List of detector instances.

required

Returns:

Type Description
list[Detection]

Combined list of detections.

Raises:

Type Description
DetectionError

If any detector fails.

export_detections

export_detections(
    detections: list[Detection],
    output_path: str | Path,
    format: str = "csv",
) -> Path

Export detections to file.

Parameters:

Name Type Description Default
detections list[Detection]

List of Detection objects.

required
output_path str | Path

Output file path.

required
format str

Output format ('csv' or 'json').

'csv'

Returns:

Type Description
Path

Path to output file.

Raises:

Type Description
DetectionError

If writing the output file fails.