Skip to main content

qualia_audio/features/spectral/
energy_band_ratio.rs

1//! Ratio of energy between two frequency bands.
2
3use crate::features::spectral::energy_band::energy_band;
4use crate::types::AudioError;
5
6/// Ratio of the spectral energy in band 1 to that in band 2.
7///
8/// Both bands are evaluated over the one-sided magnitude spectrum `mag` with
9/// [`crate::features::spectral::energy_band()`]: the numerator is the
10/// energy in \[f_lo1, f_hi1\] Hz and the denominator the energy in
11/// \[f_lo2, f_hi2\] Hz. The result is `E1 / E2`, a scale-invariant balance
12/// measure (e.g. high-band vs low-band brightness).
13///
14/// Zero-heap: two passes, scalar result.
15///
16/// # Errors
17/// - Any error from [`energy_band`] for either band (bad `sample_rate`, too few
18///   bins, or malformed frequency bounds).
19/// - [`AudioError::InvalidParameter`] if the denominator band has zero energy
20///   (the ratio would be undefined).
21#[allow(clippy::too_many_arguments)]
22pub fn energy_band_ratio(
23    mag: &[f32],
24    sample_rate: f32,
25    f_lo1: f32,
26    f_hi1: f32,
27    f_lo2: f32,
28    f_hi2: f32,
29) -> Result<f32, AudioError> {
30    let e1 = energy_band(mag, sample_rate, f_lo1, f_hi1)?;
31    let e2 = energy_band(mag, sample_rate, f_lo2, f_hi2)?;
32    if e2 == 0.0 {
33        return Err(AudioError::InvalidParameter);
34    }
35    Ok(e1 / e2)
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn known_ratio() {
44        let sr = 8000.0f32; // 9 bins, bin_hz = 500
45        let mut mag = [0.0f32; 9];
46        mag[1] = 2.0; // 500 Hz  (low band)  -> E = 4
47        mag[6] = 4.0; // 3000 Hz (high band) -> E = 16
48                      // high/low = 16/4 = 4.0
49        let r = energy_band_ratio(&mag, sr, 2500.0, 3500.0, 250.0, 750.0).expect("ratio");
50        assert!((r - 4.0).abs() < 1e-4, "ratio={r}");
51    }
52
53    #[test]
54    fn unity_when_bands_match() {
55        let sr = 8000.0f32;
56        let mut mag = [0.0f32; 9];
57        mag[2] = 3.0; // 1000 Hz
58        mag[6] = 3.0; // 3000 Hz
59        let r = energy_band_ratio(&mag, sr, 900.0, 1100.0, 2900.0, 3100.0).expect("ratio");
60        assert!((r - 1.0).abs() < 1e-4, "ratio={r}");
61    }
62
63    #[test]
64    fn rejects_zero_denominator() {
65        let sr = 8000.0f32;
66        let mut mag = [0.0f32; 9];
67        mag[1] = 2.0; // only low band has energy
68        assert_eq!(
69            energy_band_ratio(&mag, sr, 250.0, 750.0, 2500.0, 3500.0),
70            Err(AudioError::InvalidParameter)
71        );
72    }
73
74    #[test]
75    fn propagates_band_error() {
76        let mag = [1.0f32; 9];
77        assert_eq!(
78            energy_band_ratio(&mag, 0.0, 0.0, 100.0, 200.0, 300.0),
79            Err(AudioError::InvalidParameter)
80        );
81    }
82}