Skip to main content

qualia_vision/recipes/
respiration_monitor.rs

1//! Recipe: consent → motion RR ± rPPG-harmonic RR → ensemble respiration.
2//!
3//! Orchestration only. Fail closed without consent. No training.
4
5use crate::biosense::{
6    ensemble_respiration, pos_rppg_trace, respiration_from_rppg_harmonic,
7    respiration_rate_from_motion_trace, BiosenseConsent, RrEstimate, RR_MIN_SNR_DEFAULT,
8};
9use crate::cv::error::CvError;
10
11/// Default ensemble confidence floor (matches HR ensemble scale).
12const DEFAULT_MIN_CONF: f32 = 0.15;
13
14/// Respiratory rate from a vertical-motion trace and optional RGB-mean series.
15///
16/// * `vert_motion` — per-frame chest / torso vertical motion scalar (length `n_frames`).
17/// * `rgb_means` — optional interleaved `[r,g,b,…]` (length `3 * n_frames`) for the
18///   rPPG low-frequency harmonic path. When `None`, motion-only ensemble (scaled conf).
19/// * `min_confidence` — fused confidence gate; `0.0` → `DEFAULT_MIN_CONF`.
20/// * `min_snr` — spectral SNR gate for each branch; `None` → [`RR_MIN_SNR_DEFAULT`].
21pub fn respiration_monitor(
22    consent: BiosenseConsent,
23    vert_motion: &[f32],
24    rgb_means: Option<&[f32]>,
25    n_frames: usize,
26    fps: f32,
27    min_confidence: f32,
28    min_snr: Option<f32>,
29) -> Result<RrEstimate, CvError> {
30    if !consent.may_process() {
31        return Err(CvError::InvalidParameter);
32    }
33    if n_frames == 0 || vert_motion.len() < n_frames {
34        return Err(CvError::BufferTooSmall);
35    }
36    if fps <= 1.0 {
37        return Err(CvError::InvalidParameter);
38    }
39
40    let snr_gate = min_snr.unwrap_or(RR_MIN_SNR_DEFAULT);
41    let conf_gate = if min_confidence > 0.0 {
42        min_confidence
43    } else {
44        DEFAULT_MIN_CONF
45    };
46
47    let motion = respiration_rate_from_motion_trace(&vert_motion[..n_frames], fps, snr_gate).ok();
48
49    let harmonic = if let Some(means) = rgb_means {
50        if means.len() < n_frames * 3 {
51            return Err(CvError::BufferTooSmall);
52        }
53        let mut pulse = vec![0.0f32; n_frames];
54        pos_rppg_trace(means, n_frames, &mut pulse)?;
55        respiration_from_rppg_harmonic(&pulse, fps, Some(snr_gate)).ok()
56    } else {
57        None
58    };
59
60    ensemble_respiration(motion, harmonic, conf_gate)
61}
62
63/// Convenience: motion-only respiratory monitor (no rPPG branch).
64pub fn respiration_monitor_motion_only(
65    consent: BiosenseConsent,
66    vert_motion: &[f32],
67    fps: f32,
68) -> Result<RrEstimate, CvError> {
69    respiration_monitor(
70        consent,
71        vert_motion,
72        None,
73        vert_motion.len(),
74        fps,
75        DEFAULT_MIN_CONF,
76        None,
77    )
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::biosense::BiosensePurpose;
84
85    fn grant() -> BiosenseConsent {
86        BiosenseConsent::grant_process(BiosensePurpose::WellfairSelfMonitor, 3)
87    }
88
89    fn synth_motion(bpm: f32, fps: f32, n: usize) -> Vec<f32> {
90        let f = bpm / 60.0;
91        let mut t = vec![0.0f32; n];
92        for i in 0..n {
93            t[i] = (core::f32::consts::TAU * f * i as f32 / fps).sin();
94        }
95        t
96    }
97
98    fn synth_rgb_with_rr(hr_bpm: f32, rr_bpm: f32, fps: f32, n: usize) -> Vec<f32> {
99        let f_hr = hr_bpm / 60.0;
100        let f_rr = rr_bpm / 60.0;
101        let mut m = vec![0.0f32; n * 3];
102        for i in 0..n {
103            let ti = i as f32 / fps;
104            let pulse = (core::f32::consts::TAU * f_hr * ti).sin();
105            let breath = 0.8 * (core::f32::consts::TAU * f_rr * ti).sin();
106            let g = 120.0 + 20.0 * (pulse * (1.0 + 0.15 * breath) + breath);
107            let r = 110.0 + 5.0 * pulse;
108            let b = 90.0 - 4.0 * pulse;
109            m[i * 3] = r;
110            m[i * 3 + 1] = g;
111            m[i * 3 + 2] = b;
112        }
113        m
114    }
115
116    #[test]
117    fn no_consent_fails_closed() {
118        let m = synth_motion(15.0, 30.0, 450);
119        let r = respiration_monitor(
120            BiosenseConsent::denied(BiosensePurpose::WellfairSelfMonitor),
121            &m,
122            None,
123            m.len(),
124            30.0,
125            0.1,
126            Some(2.0),
127        );
128        assert!(r.is_err());
129    }
130
131    #[test]
132    fn motion_only_finds_fifteen_bpm() {
133        let fps = 30.0;
134        let m = synth_motion(15.0, fps, 450);
135        let e = respiration_monitor_motion_only(grant(), &m, fps).unwrap();
136        assert!(
137            (e.breaths_per_min - 15.0).abs() < 1.5,
138            "bpm={}",
139            e.breaths_per_min
140        );
141        assert!(e.confidence > 0.1);
142    }
143
144    #[test]
145    fn dual_source_ensemble() {
146        let fps = 30.0;
147        let n = 480;
148        let target = 16.0f32;
149        let motion = synth_motion(target, fps, n);
150        let rgb = synth_rgb_with_rr(72.0, target, fps, n);
151        let e = respiration_monitor(grant(), &motion, Some(&rgb), n, fps, 0.1, Some(2.0)).unwrap();
152        assert!(
153            (e.breaths_per_min - target).abs() < 2.5,
154            "bpm={}",
155            e.breaths_per_min
156        );
157        assert!(e.confidence > 0.1);
158    }
159
160    #[test]
161    fn flat_motion_fails_closed() {
162        let m = vec![0.0f32; 200];
163        let r = respiration_monitor(grant(), &m, None, m.len(), 30.0, 0.2, Some(8.0));
164        assert!(r.is_err());
165    }
166
167    #[test]
168    fn short_buffer_errors() {
169        let m = [0.1f32; 8];
170        assert!(respiration_monitor(grant(), &m, None, 8, 30.0, 0.1, None).is_err());
171    }
172}