//! Synthetic oscillometric NIBP cuff cycle; no physiological or diagnostic validity. //! All time is measured in simulation seconds so the behavior is independent of FPS. use crate::model::{Parameters, Spo2Quality}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NibpReading { pub systolic: i32, pub diastolic: i32, } impl NibpReading { pub fn mean(self) -> i32 { crate::model::mean_arterial_pressure(self.systolic, self.diastolic) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CuffZone { Free, Partial, Occluded, } #[derive(Clone, Copy, Debug)] struct Cycle { start: f64, duration: f64, quality_at_start: Spo2Quality, first: bool, first_reading: NibpReading, } #[derive(Debug)] pub struct NibpMachine { cycle: Option, ever_started: bool, ever_successful: bool, last_completed: Option, last_reading: Option, last_success_at: Option, rng: u64, } impl NibpMachine { pub fn new() -> Self { Self { cycle: None, ever_started: false, ever_successful: false, last_completed: None, last_reading: None, last_success_at: None, rng: 0xC4E3_1A86_957B_1D29, } } fn random_unit(&mut self) -> f64 { self.rng = self.rng.wrapping_mul(6_364_136_223_846_793_005) .wrapping_add(1_442_695_040_888_963_407); (self.rng >> 11) as f64 / (1_u64 << 53) as f64 } fn random_between(&mut self, low: f64, high: f64) -> f64 { low + self.random_unit() * (high - low) } pub fn measuring(&self) -> bool { self.cycle.is_some() } pub fn reading(&self) -> Option { self.last_reading } /// Time since the last completed measurement as a fraction of the interval. /// While measuring, the waiting progress resets to zero. pub fn interval_progress(&self, now: f64, minutes: i32) -> f64 { if self.cycle.is_some() { return 0.0; } let Some(last) = self.last_completed else { return 0.0; }; ((now - last) / (f64::from(minutes.max(1)) * 60.0)).clamp(0.0, 1.0) } /// Five appearances/disappearances over five seconds (no color inversion). pub fn show_new_value(&self, now: f64) -> bool { let Some(last) = self.last_success_at else { return true; }; let elapsed = now - last; !(0.0..5.0).contains(&elapsed) || (elapsed * 2.0).floor() as i32 % 2 == 0 } pub fn cuff_pressure(&self, now: f64) -> f64 { let Some(cycle) = self.cycle else { return 0.0; }; let t = ((now - cycle.start) / cycle.duration).clamp(0.0, 1.0); let poor = matches!(cycle.quality_at_start, Spo2Quality::Poor | Spo2Quality::None); (if !poor { if t < 0.13 { 200.0 * t / 0.13 } else { 200.0 * (1.0 - t) / 0.87 } } else if t < 0.13 { 200.0 * t / 0.13 } else if t < 0.54 { // First deflation stops at one third of the maximum pressure. 200.0 - (200.0 - 200.0 / 3.0) * (t - 0.13) / 0.41 } else if t < 0.71 { // Reinflation to two thirds of maximum pressure. 200.0 / 3.0 + (200.0 / 3.0) * (t - 0.54) / 0.17 } else { (400.0 / 3.0) * (1.0 - t) / 0.29 }).clamp(0.0, 200.0) } pub fn cuff_zone(&self, now: f64, params: &Parameters) -> CuffZone { if !self.measuring() { return CuffZone::Free; } let pressure = self.cuff_pressure(now); if pressure > f64::from(params.art_systolic) { CuffZone::Occluded } else if pressure > f64::from(params.art_diastolic) { CuffZone::Partial } else { CuffZone::Free } } pub fn effective_spo2_quality(&self, now: f64, p: &Parameters) -> Spo2Quality { if !p.nibp_cuff_on_spo2 { return p.spo2_quality; } match self.cuff_zone(now, p) { CuffZone::Occluded => Spo2Quality::None, CuffZone::Partial => p.spo2_quality.min(Spo2Quality::Poor), CuffZone::Free => p.spo2_quality, } } fn start(&mut self, now: f64, p: &Parameters, quality: Spo2Quality) { let quality = if p.nibp_no_reading { Spo2Quality::None } else { quality }; let duration = match quality { Spo2Quality::Good => 20.0, Spo2Quality::Adequate => 40.0, Spo2Quality::Poor => self.random_between(60.0, 120.0), Spo2Quality::None => 120.0, }; self.cycle = Some(Cycle { start: now, duration, quality_at_start: quality, first: !self.ever_successful, first_reading: NibpReading { systolic: p.nibp_systolic, diastolic: p.nibp_diastolic, }, }); self.ever_started = true; } /// The initial cycle starts at simulation time zero. Afterwards, the /// interval is counted from the last completed measurement, not cycle start. pub fn update(&mut self, now: f64, p: &Parameters, quality_at_start: Spo2Quality) { if now < 0.0 { return; } if let Some(cycle) = self.cycle { if now - cycle.start >= cycle.duration { self.complete(now, p, cycle); } } else if !self.ever_started || self.last_completed.is_some_and(|last| { now - last >= f64::from(p.nibp_interval_minutes.max(1)) * 60.0 }) { self.start(now, p, quality_at_start); } } /// Instructor-triggered measurement; ignored if a cuff cycle is in progress. pub fn measure_now(&mut self, now: f64, p: &Parameters, quality: Spo2Quality) { if !self.measuring() { self.start(now.max(0.0), p, quality); } } fn complete(&mut self, now: f64, p: &Parameters, cycle: Cycle) { let successful = match cycle.quality_at_start { Spo2Quality::None => false, Spo2Quality::Poor => self.random_unit() < 0.65, Spo2Quality::Adequate | Spo2Quality::Good => true, }; self.last_reading = if successful { let reading = if cycle.first { cycle.first_reading } else { let (low, high) = match cycle.quality_at_start { Spo2Quality::Good => (-0.05, 0.05), Spo2Quality::Adequate => (-0.10, 0.05), Spo2Quality::Poor => (-0.15, -0.05), Spo2Quality::None => (0.0, 0.0), }; // Independent random deviation for SYS and DIA; preserve SYS >= DIA. let sys = (f64::from(p.art_systolic) * (1.0 + self.random_between(low, high))) .round().clamp(0.0, 260.0) as i32; let dia = (f64::from(p.art_diastolic) * (1.0 + self.random_between(low, high))) .round().clamp(0.0, f64::from(sys)) as i32; NibpReading { systolic: sys, diastolic: dia } }; self.last_success_at = Some(now); self.ever_successful = true; Some(reading) } else { self.last_success_at = None; None }; self.cycle = None; self.last_completed = Some(now); } } #[cfg(test)] mod tests { use super::*; #[test] fn intervals_and_first_values() { let mut m = NibpMachine::new(); let p = Parameters::default(); m.update(0.0, &p, Spo2Quality::Good); assert!(m.measuring()); assert_eq!(m.reading(), None); assert!((m.cuff_pressure(2.6) - 200.0).abs() < 0.1); m.update(20.0, &p, Spo2Quality::Good); assert_eq!(m.reading(), Some(NibpReading { systolic: 118, diastolic: 74 })); assert!(!m.measuring()); assert!(m.show_new_value(20.1)); assert!(!m.show_new_value(20.6)); assert!(m.show_new_value(25.1)); assert!((m.interval_progress(170.0, 5) - 0.5).abs() < 1e-6); m.update(319.9, &p, Spo2Quality::Good); assert!(!m.measuring()); m.update(320.0, &p, Spo2Quality::Good); assert!(m.measuring()); m.update(340.0, &p, Spo2Quality::Good); assert!(m.reading().is_some()); let result = m.reading().unwrap(); assert!((result.systolic - p.art_systolic).abs() <= 6); assert!((result.diastolic - p.art_diastolic).abs() <= 4); } #[test] fn failed_measurement_and_retry_cycle() { let p = Parameters { nibp_no_reading: true, ..Parameters::default() }; let mut m = NibpMachine::new(); m.update(0.0, &p, Spo2Quality::Good); assert!(m.measuring()); assert!((m.cuff_pressure(15.6) - 200.0).abs() < 0.1); assert!((m.cuff_pressure(64.8) - 200.0/3.0).abs() < 0.1); assert!((m.cuff_pressure(85.2) - 400.0/3.0).abs() < 0.1); m.update(120.0, &p, Spo2Quality::Good); assert!(m.reading().is_none()); } #[test] fn cuff_interference_never_improves_quality() { let p = Parameters { nibp_cuff_on_spo2: true, ..Parameters::default() }; let mut m = NibpMachine::new(); m.update(0.0, &p, Spo2Quality::Good); assert_eq!(m.effective_spo2_quality(2.6, &p), Spo2Quality::None); assert_eq!(m.effective_spo2_quality(10.0, &p), Spo2Quality::Poor); assert_eq!(m.effective_spo2_quality(19.0, &p), Spo2Quality::Good); let p = Parameters { spo2_quality: Spo2Quality::Poor, ..p }; assert_eq!(m.effective_spo2_quality(10.0, &p), Spo2Quality::Poor); } } #[cfg(test)] mod more_tests { use super::*; #[test] fn quality_determines_cycle_duration() { for (quality, seconds) in [ (Spo2Quality::Good, 20.0), (Spo2Quality::Adequate, 40.0), (Spo2Quality::None, 120.0), ] { let mut machine = NibpMachine::new(); let p = Parameters::default(); machine.update(0.0, &p, quality); machine.update(seconds - 0.01, &p, quality); assert!(machine.measuring()); machine.update(seconds, &p, quality); assert!(!machine.measuring()); assert_eq!(machine.reading().is_some(), quality != Spo2Quality::None); } let mut machine = NibpMachine::new(); let p = Parameters::default(); machine.update(0.0, &p, Spo2Quality::Poor); assert!((60.0..=120.0).contains(&machine.cycle.unwrap().duration)); } #[test] fn first_successful_reading_uses_admin_even_after_failed_cycle() { let mut p = Parameters { nibp_no_reading: true, ..Parameters::default() }; let mut machine = NibpMachine::new(); machine.update(0.0, &p, Spo2Quality::None); machine.update(120.0, &p, Spo2Quality::None); assert!(machine.reading().is_none()); p.nibp_no_reading = false; machine.measure_now(121.0, &p, Spo2Quality::Good); machine.update(141.0, &p, Spo2Quality::Good); assert_eq!(machine.reading(), Some(NibpReading { systolic: 118, diastolic: 74 })); } #[test] fn partial_pressure_uses_diastic_and_systolic_boundaries() { let p = Parameters { nibp_cuff_on_art: true, ..Parameters::default() }; let mut machine = NibpMachine::new(); machine.update(0.0, &p, Spo2Quality::Good); assert_eq!(machine.cuff_zone(2.6, &p), CuffZone::Occluded); assert_eq!(machine.cuff_zone(10.0, &p), CuffZone::Partial); assert_eq!(machine.cuff_zone(19.0, &p), CuffZone::Free); } }