Skip to main content

qualia_vision/biosense/respiration/
ensemble_respiration.rs

1//! Ensemble respiratory rate from motion ± rPPG-harmonic estimates.
2//!
3//! Honest confidence: agreement-weighted blend; large disagreement or dual
4//! abstain → fail closed. No training.
5
6use super::rr_estimate::RrEstimate;
7use crate::cv::error::CvError;
8
9/// Max |Δ bpm| for full agreement weight; beyond this, confidence collapses.
10const AGREE_BPM_FULL: f32 = 2.0;
11/// Beyond this absolute disagreement, ensemble abstains even if both confident.
12const AGREE_BPM_MAX: f32 = 6.0;
13
14/// Combine optional motion and rPPG-harmonic RR estimates.
15///
16/// * At least one `Some` required; both preferred.
17/// * `min_confidence` — fail closed if fused confidence is below this (e.g. 0.15).
18pub fn ensemble_respiration(
19    motion: Option<RrEstimate>,
20    rppg_harmonic: Option<RrEstimate>,
21    min_confidence: f32,
22) -> Result<RrEstimate, CvError> {
23    match (motion, rppg_harmonic) {
24        (None, None) => Err(CvError::InvalidParameter),
25        (Some(m), None) => gate_single(m, min_confidence, 0.85),
26        (None, Some(h)) => gate_single(h, min_confidence, 0.80),
27        (Some(m), Some(h)) => fuse_pair(m, h, min_confidence),
28    }
29}
30
31fn gate_single(e: RrEstimate, min_confidence: f32, scale: f32) -> Result<RrEstimate, CvError> {
32    let conf = (e.confidence * scale).clamp(0.0, 1.0);
33    if conf < min_confidence {
34        return Err(CvError::InvalidParameter);
35    }
36    Ok(RrEstimate {
37        breaths_per_min: e.breaths_per_min,
38        snr: e.snr,
39        confidence: conf,
40    })
41}
42
43fn fuse_pair(m: RrEstimate, h: RrEstimate, min_confidence: f32) -> Result<RrEstimate, CvError> {
44    let delta = (m.breaths_per_min - h.breaths_per_min).abs();
45    if delta > AGREE_BPM_MAX {
46        return Err(CvError::InvalidParameter);
47    }
48    let wm = m.confidence.max(1e-3);
49    let wh = h.confidence.max(1e-3);
50    let bpm = (m.breaths_per_min * wm + h.breaths_per_min * wh) / (wm + wh);
51    let snr = (m.snr * wm + h.snr * wh) / (wm + wh);
52    // Agreement factor: 1 at ≤AGREE_BPM_FULL, linear down to 0 at AGREE_BPM_MAX.
53    let agree = if delta <= AGREE_BPM_FULL {
54        1.0
55    } else {
56        1.0 - (delta - AGREE_BPM_FULL) / (AGREE_BPM_MAX - AGREE_BPM_FULL)
57    };
58    let base = ((wm + wh) * 0.5).clamp(0.0, 1.0);
59    // Dual source bonus when they agree.
60    let conf = (base * agree * 1.05).clamp(0.0, 1.0);
61    if conf < min_confidence {
62        return Err(CvError::InvalidParameter);
63    }
64    Ok(RrEstimate {
65        breaths_per_min: bpm,
66        snr,
67        confidence: conf,
68    })
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    fn est(bpm: f32, snr: f32, conf: f32) -> RrEstimate {
76        RrEstimate {
77            breaths_per_min: bpm,
78            snr,
79            confidence: conf,
80        }
81    }
82
83    #[test]
84    fn fuses_agreeing_estimates() {
85        let e = ensemble_respiration(Some(est(15.0, 12.0, 0.7)), Some(est(15.5, 10.0, 0.6)), 0.15)
86            .unwrap();
87        assert!(
88            (e.breaths_per_min - 15.25).abs() < 0.5,
89            "bpm={}",
90            e.breaths_per_min
91        );
92        assert!(e.confidence >= 0.15);
93    }
94
95    #[test]
96    fn abstains_on_large_disagreement() {
97        let r = ensemble_respiration(Some(est(12.0, 10.0, 0.8)), Some(est(24.0, 10.0, 0.8)), 0.1);
98        assert!(r.is_err());
99    }
100
101    #[test]
102    fn single_source_scaled() {
103        let e = ensemble_respiration(Some(est(14.0, 8.0, 0.5)), None, 0.2).unwrap();
104        assert!((e.breaths_per_min - 14.0).abs() < 0.01);
105        assert!(e.confidence < 0.5); // scaled down vs dual
106    }
107
108    #[test]
109    fn both_none_fails() {
110        assert!(ensemble_respiration(None, None, 0.1).is_err());
111    }
112
113    #[test]
114    fn low_confidence_fails_closed() {
115        let r = ensemble_respiration(Some(est(14.0, 2.0, 0.05)), None, 0.2);
116        assert!(r.is_err());
117    }
118}