Skip to main content

qualia_audio/features/envelope/
centroid_time.rs

1//! Time-domain temporal centroid (energy-weighted mean time of a signal).
2
3use crate::types::AudioError;
4
5/// Temporal centroid of `signal` in **seconds**: the energy-weighted mean time
6/// `sum(t_i * x_i^2) / sum(x_i^2)` where `t_i = i / sample_rate`. This is the
7/// time-domain analogue of the spectral centroid — the "balance point" of the
8/// signal's energy along the time axis.
9///
10/// # Errors
11/// - [`AudioError::InvalidParameter`] if `sample_rate <= 0`, the signal is
12///   empty, or it carries no energy.
13pub fn centroid_time(signal: &[f32], sample_rate: f32) -> Result<f32, AudioError> {
14    if sample_rate <= 0.0 || !sample_rate.is_finite() || signal.is_empty() {
15        return Err(AudioError::InvalidParameter);
16    }
17    let mut weighted = 0.0f64;
18    let mut energy = 0.0f64;
19    for (i, &x) in signal.iter().enumerate() {
20        let e = (x as f64) * (x as f64);
21        weighted += i as f64 * e;
22        energy += e;
23    }
24    if energy == 0.0 {
25        return Err(AudioError::InvalidParameter);
26    }
27    let centroid_samples = weighted / energy;
28    Ok((centroid_samples / sample_rate as f64) as f32)
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn rejects_degenerate() {
37        assert_eq!(
38            centroid_time(&[], 8000.0),
39            Err(AudioError::InvalidParameter)
40        );
41        assert_eq!(
42            centroid_time(&[1.0, 1.0], 0.0),
43            Err(AudioError::InvalidParameter)
44        );
45        assert_eq!(
46            centroid_time(&[0.0, 0.0, 0.0], 8000.0),
47            Err(AudioError::InvalidParameter)
48        );
49    }
50
51    /// Golden: all energy at one sample -> centroid equals that sample's time.
52    #[test]
53    fn single_impulse_centroid() {
54        let sr = 1000.0f32;
55        let mut sig = vec![0.0f32; 100];
56        sig[40] = 1.0; // t = 40/1000 = 0.04 s
57        let c = centroid_time(&sig, sr).expect("c");
58        assert!((c - 0.04).abs() < 1e-6, "centroid={c}");
59    }
60
61    /// A symmetric energy distribution centres on the middle time.
62    #[test]
63    fn symmetric_energy_is_centred() {
64        let sr = 1000.0f32;
65        let n = 101usize; // symmetric around index 50 -> 0.05 s
66        let mut sig = vec![0.0f32; n];
67        for i in 0..n {
68            // Symmetric triangular magnitude about the centre.
69            sig[i] = 1.0 - (i as f32 - 50.0).abs() / 50.0;
70        }
71        let c = centroid_time(&sig, sr).expect("c");
72        assert!((c - 0.05).abs() < 1e-3, "centroid={c}");
73    }
74}