SimPaM/patient-monitor-simulation/src/model.rs

320 lines
11 KiB
Rust
Raw Normal View History

2026-11-12 09:36:13 +01:00
//! Shared configuration of the synthetic monitor signals.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EcgRhythm {
Sinus,
AtrialFibrillation,
VentricularTachycardia,
VentricularFibrillation,
Asystole,
}
impl EcgRhythm {
/// VF and asystole have no organized QRS to trigger a mechanical pulse.
pub fn has_qrs(self) -> bool {
!matches!(self, Self::VentricularFibrillation | Self::Asystole)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PulseConduction {
OneToOne,
TwoToOne,
ThreeToOne,
None,
Random,
}
impl PulseConduction {
pub fn conducts(self, beat: u64) -> bool {
match self {
Self::OneToOne => true,
// One mechanical pulse for every two QRS complexes.
Self::TwoToOne => (beat - 1) % 2 == 0,
Self::ThreeToOne => (beat - 1) % 3 == 0,
Self::None => false,
Self::Random => {
// Deterministic pseudo-random 65% mechanical capture for reproducible lessons.
let mut x = beat.wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 30;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 27;
(x % 100) < 65
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArterialShape {
Normal,
Damped,
Hyperdynamic,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CapnoShape {
Normal,
Obstructive,
}
2026-11-12 10:43:11 +01:00
/// Instructor-selected plethysmography signal quality; separate from the
/// physiological oxygen-saturation setting and mechanical pulse capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spo2Quality {
None,
Poor,
Adequate,
Good,
}
impl Spo2Quality {
pub fn stars(self) -> &'static str {
match self {
Self::None => "",
Self::Poor => "★",
Self::Adequate => "★★",
Self::Good => "★★★",
}
}
pub fn amplitude_scale(self) -> f64 {
match self {
Self::None => 0.0,
Self::Poor => 0.25,
Self::Adequate => 0.56,
Self::Good => 1.0,
}
}
}
2026-11-12 11:30:50 +01:00
/// Optional lower and upper bounds for one displayed numeric measurement.
/// Equal-to-limit values are inside the permitted range.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AlarmLimits {
pub lower: Option<i32>,
pub upper: Option<i32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AlarmState {
Normal,
Low,
High,
}
impl AlarmLimits {
pub fn enabled(self) -> bool {
self.lower.is_some() || self.upper.is_some()
}
pub fn valid(self) -> bool {
match (self.lower, self.upper) {
(Some(lo), Some(hi)) => lo <= hi,
_ => true,
}
}
/// Missing measurements cannot cause threshold-based alarms.
pub fn evaluate(self, value: Option<i32>) -> AlarmState {
let Some(value) = value else { return AlarmState::Normal; };
if self.lower.is_some_and(|lo| value < lo) { return AlarmState::Low; }
if self.upper.is_some_and(|hi| value > hi) { return AlarmState::High; }
AlarmState::Normal
}
pub fn display(self, name: &str) -> String {
fn bound(value: Option<i32>) -> String {
value.map_or_else(|| "---".to_owned(), |v| v.to_string())
}
2026-11-12 11:47:38 +01:00
format!("{} ↓{} ↑{}", name, bound(self.lower), bound(self.upper))
2026-11-12 11:30:50 +01:00
}
}
/// Separate limits for every numeric readout, including derived MAP and PR.
/// Defaults to all disabled, so adding alarms does not alter old scenarios.
2026-11-12 11:47:38 +01:00
#[derive(Clone, Debug, Default, PartialEq, Eq)]
2026-11-12 11:30:50 +01:00
pub struct AlarmSettings {
pub hr: AlarmLimits,
pub spo2: AlarmLimits,
pub pr: AlarmLimits,
pub art_sys: AlarmLimits,
pub art_map: AlarmLimits,
pub art_dia: AlarmLimits,
pub ppv: AlarmLimits,
pub nibp_sys: AlarmLimits,
pub nibp_map: AlarmLimits,
pub nibp_dia: AlarmLimits,
pub etco2: AlarmLimits,
pub rr: AlarmLimits,
}
2026-11-12 11:47:38 +01:00
impl AlarmSettings {
/// Instructor convenience preset; does not change physiological settings.
/// Unspecified alarm boundaries remain disabled.
pub fn adult() -> Self {
Self {
hr: AlarmLimits { lower: Some(60), upper: Some(100) },
spo2: AlarmLimits { lower: Some(90), upper: None },
art_sys: AlarmLimits { lower: Some(80), upper: Some(180) },
art_map: AlarmLimits { lower: Some(60), upper: Some(100) },
ppv: AlarmLimits { lower: None, upper: Some(10) },
nibp_sys: AlarmLimits { lower: Some(80), upper: Some(180) },
nibp_map: AlarmLimits { lower: Some(60), upper: Some(100) },
etco2: AlarmLimits { lower: Some(30), upper: Some(50) },
rr: AlarmLimits { lower: Some(10), upper: Some(20) },
..Self::default()
}
}
}
2026-11-12 10:43:11 +01:00
#[derive(Clone, Debug)]
2026-11-12 09:36:13 +01:00
pub struct Parameters {
2026-11-12 10:43:11 +01:00
pub patient_name: String, // displayed in the monitor header, blank = generic title
2026-11-12 11:30:50 +01:00
pub alarms: AlarmSettings,
2026-11-12 09:36:13 +01:00
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
2026-11-12 10:43:11 +01:00
pub spo2: i32, // %; instructor-set nominal saturation
pub spo2_quality: Spo2Quality,
pub spo2_sensor_attached: bool,
2026-11-12 09:36:13 +01:00
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
pub art_diastolic: i32, // mmHg
pub arterial_shape: ArterialShape,
pub pulse_pressure_variation: i32, // PPV %, 0 disables respiratory variation
pub nibp_systolic: i32, // mmHg, historical/static simulated cuff value
pub nibp_diastolic: i32, // mmHg
pub etco2: i32, // mmHg
pub respiratory_rate: i32, // breaths/min
pub capno_shape: CapnoShape,
// These affect display only; the underlying physiological signals continue.
pub show_ecg: bool,
pub show_spo2: bool,
pub show_art: bool,
pub show_capno: bool,
pub show_nibp: bool,
}
impl Default for Parameters {
fn default() -> Self {
Self {
2026-11-12 10:43:11 +01:00
patient_name: String::new(),
2026-11-12 11:30:50 +01:00
alarms: AlarmSettings::default(),
2026-11-12 09:36:13 +01:00
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
2026-11-12 10:43:11 +01:00
spo2_quality: Spo2Quality::Good,
spo2_sensor_attached: true,
2026-11-12 09:36:13 +01:00
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
pulse_pressure_variation: 0,
nibp_systolic: 118,
nibp_diastolic: 74,
etco2: 38,
respiratory_rate: 14,
capno_shape: CapnoShape::Normal,
show_ecg: true,
show_spo2: true,
show_art: true,
show_capno: true,
show_nibp: true,
}
}
}
pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 {
((systolic as f64 + 2.0 * diastolic as f64) / 3.0).round() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mean_pressure_uses_one_third_pulse_pressure() {
assert_eq!(mean_arterial_pressure(120, 75), 90);
}
2026-11-12 10:43:11 +01:00
#[test]
fn spo2_quality_stars_and_amplitude_progress_monotonically() {
assert_eq!(Spo2Quality::None.stars(), "");
assert_eq!(Spo2Quality::Poor.stars(), "★");
assert_eq!(Spo2Quality::Adequate.stars(), "★★");
assert_eq!(Spo2Quality::Good.stars(), "★★★");
assert_eq!(Spo2Quality::None.amplitude_scale(), 0.0);
assert!(Spo2Quality::Poor.amplitude_scale() < Spo2Quality::Adequate.amplitude_scale());
assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
}
2026-11-12 11:30:50 +01:00
#[test]
fn independent_optional_alarm_limits_and_inclusive_boundaries() {
let off = AlarmLimits::default();
assert!(!off.enabled());
assert_eq!(off.evaluate(Some(20)), AlarmState::Normal);
let low_only = AlarmLimits { lower: Some(60), upper: None };
assert!(low_only.enabled());
assert_eq!(low_only.evaluate(Some(59)), AlarmState::Low);
assert_eq!(low_only.evaluate(Some(60)), AlarmState::Normal);
assert_eq!(low_only.evaluate(None), AlarmState::Normal);
2026-11-12 11:47:38 +01:00
assert_eq!(low_only.display("MAP"), "MAP ↓60 ↑---");
2026-11-12 11:30:50 +01:00
let high_only = AlarmLimits { lower: None, upper: Some(180) };
assert_eq!(high_only.evaluate(Some(181)), AlarmState::High);
assert_eq!(high_only.evaluate(Some(180)), AlarmState::Normal);
let both = AlarmLimits { lower: Some(80), upper: Some(180) };
assert!(both.valid());
assert_eq!(both.evaluate(Some(79)), AlarmState::Low);
assert_eq!(both.evaluate(Some(181)), AlarmState::High);
assert_eq!(both.evaluate(Some(120)), AlarmState::Normal);
2026-11-12 11:47:38 +01:00
assert_eq!(both.display("SYS"), "SYS ↓80 ↑180");
2026-11-12 11:30:50 +01:00
assert!(!AlarmLimits { lower: Some(181), upper: Some(80) }.valid());
}
2026-11-12 11:47:38 +01:00
#[test]
fn adult_preset_sets_exact_requested_limits_and_leaves_others_off() {
let preset = AlarmSettings::adult();
let pair = |lo, hi| AlarmLimits { lower: lo, upper: hi };
assert_eq!(preset.hr, pair(Some(60), Some(100)));
assert_eq!(preset.spo2, pair(Some(90), None));
assert_eq!(preset.pr, pair(None, None));
assert_eq!(preset.art_sys, pair(Some(80), Some(180)));
assert_eq!(preset.art_map, pair(Some(60), Some(100)));
assert_eq!(preset.art_dia, pair(None, None));
assert_eq!(preset.ppv, pair(None, Some(10)));
assert_eq!(preset.nibp_sys, preset.art_sys);
assert_eq!(preset.nibp_map, preset.art_map);
assert_eq!(preset.nibp_dia, preset.art_dia);
assert_eq!(preset.etco2, pair(Some(30), Some(50)));
assert_eq!(preset.rr, pair(Some(10), Some(20)));
assert!([
preset.hr, preset.spo2, preset.art_sys, preset.art_map,
preset.ppv, preset.nibp_sys, preset.nibp_map,
preset.etco2, preset.rr,
].iter().all(|bounds| bounds.valid()));
assert_eq!(AlarmSettings::default(), Parameters::default().alarms);
}
2026-11-12 11:30:50 +01:00
#[test]
fn all_limits_disabled_by_default() {
let p = Parameters::default();
assert!(!p.alarms.hr.enabled());
assert!(!p.alarms.art_sys.enabled());
assert!(!p.alarms.art_map.enabled());
assert!(!p.alarms.art_dia.enabled());
assert!(!p.alarms.ppv.enabled());
assert!(!p.alarms.nibp_sys.enabled());
assert!(!p.alarms.spo2.enabled());
assert!(!p.alarms.pr.enabled());
}
2026-11-12 09:36:13 +01:00
#[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 3, 5, 7]);
assert_eq!((1..=9).filter(|&b| PulseConduction::ThreeToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 4, 7]);
assert!((1..=20).all(|b| PulseConduction::OneToOne.conducts(b)));
assert!((1..=20).all(|b| !PulseConduction::None.conducts(b)));
}
}