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

561 lines
21 KiB
Rust

//! Shared configuration of the synthetic monitor signals.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EcgRhythm {
Sinus,
AtrialFibrillation,
VentricularTachycardia,
PulselessVentricularTachycardia,
VentricularFibrillation,
Asystole,
}
impl EcgRhythm {
/// Organized electrical QRS complexes. PVT still has electrical QRS complexes.
pub fn has_qrs(self) -> bool {
!matches!(self, Self::VentricularFibrillation | Self::Asystole)
}
/// Whether a QRS can trigger a mechanical pulse, depending on capture.
/// Perfusing VT is distinct from PVT. VF and asystole have no QRS.
pub fn can_generate_pulse(self) -> bool {
self.has_qrs() && self != Self::PulselessVentricularTachycardia
}
/// Rhythm alarms are independent of instructor-defined HR thresholds.
pub fn rhythm_alarm(self) -> Option<&'static str> {
match self {
Self::VentricularTachycardia | Self::PulselessVentricularTachycardia
| Self::VentricularFibrillation => Some("ARRHYTHMIA"),
Self::Asystole => Some("ASYSTOLE"),
_ => None,
}
}
}
/// Displayed single-channel ECG lead. Synthetic morphology is lead-II-like;
/// projection below provides illustrative polarity/gain, not a 12-lead model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EcgLead {
I, II, III, AVR, AVL, AVF, V1, V2, V3, V4, V5, V6,
}
impl EcgLead {
pub const LABELS: &'static [&'static str] = &[
"I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6",
];
pub fn from_index(index: u32) -> Self {
match index {
0 => Self::I, 2 => Self::III, 3 => Self::AVR, 4 => Self::AVL,
5 => Self::AVF, 6 => Self::V1, 7 => Self::V2, 8 => Self::V3,
9 => Self::V4, 10 => Self::V5, 11 => Self::V6, _ => Self::II,
}
}
pub fn index(self) -> u32 {
match self {
Self::I => 0, Self::II => 1, Self::III => 2, Self::AVR => 3,
Self::AVL => 4, Self::AVF => 5, Self::V1 => 6, Self::V2 => 7,
Self::V3 => 8, Self::V4 => 9, Self::V5 => 10, Self::V6 => 11,
}
}
pub fn label(self) -> &'static str { Self::LABELS[self.index() as usize] }
/// Illustrative polarity and voltage gain relative to lead II. This changes
/// only the trace, never ECG event timing or mechanical capture.
pub fn display_gain(self) -> f64 {
match self {
Self::I => 0.82, Self::II => 1.0, Self::III => 0.67,
Self::AVR => -0.85, Self::AVL => 0.52, Self::AVF => 0.75,
Self::V1 => -0.75, Self::V2 => -0.38, Self::V3 => 0.52,
Self::V4 => 1.08, Self::V5 => 1.0, Self::V6 => 0.83,
}
}
}
/// Pulse-oximeter availability and technical alarms. Sensor loss takes precedence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spo2Status {
Available,
NoSensor,
NoReading,
}
#[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,
}
/// Instructor-selected efficacy of manual chest compressions.
/// This affects synthetic pressure and pleth signals, not ECG rhythm or HR.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChestCompressionQuality {
Good,
Adequate,
Poor,
Bad,
}
impl ChestCompressionQuality {
/// Approximate compression-generated systolic peak pressure (mmHg).
/// None means that compressions generate no measurable arterial pressure.
pub fn peak_range(self) -> Option<(f64, f64)> {
match self {
Self::Good => Some((81.0, 99.0)), // 90 +/- 10%
Self::Adequate => Some((63.0, 77.0)), // 70 +/- 10%
Self::Poor => Some((25.0, 55.0)), // 50 -50% / +10%
Self::Bad => None,
}
}
}
/// 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 min(self, other: Self) -> Self {
if (self as u8) <= (other as u8) { self } else { other }
}
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,
}
}
}
/// 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())
}
format!("{} ↓{} ↑{}", name, bound(self.lower), bound(self.upper))
}
}
/// Separate limits for every numeric readout, including derived MAP and PR.
/// Defaults to all disabled, so adding alarms does not alter old scenarios.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
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,
}
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()
}
}
}
#[derive(Clone, Debug)]
pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms
pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
pub ecg_lead: EcgLead, // ECG trace label and illustrative lead projection
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
pub spo2: i32, // %; instructor-set nominal saturation
pub spo2_quality: Spo2Quality,
pub spo2_sensor_attached: bool,
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, initial measured NIBP result
pub nibp_diastolic: i32, // mmHg, initial measured NIBP result
pub nibp_interval_minutes: i32, // 1 / 3 / 5 / 10 / 20 / 30 / 60
pub nibp_no_reading: bool, // force unsuccessful cuff measurement
pub nibp_cuff_on_spo2: bool, // simulated probe on cuff extremity
pub nibp_cuff_on_art: bool, // simulated arterial catheter on cuff extremity
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 Parameters {
/// Selecting a ventricular tachycardia starts at the teaching default of
/// 160 bpm. The instructor can subsequently adjust the heart rate.
pub fn select_ecg_rhythm(&mut self, rhythm: EcgRhythm) {
self.ecg_rhythm = rhythm;
if matches!(rhythm, EcgRhythm::VentricularTachycardia
| EcgRhythm::PulselessVentricularTachycardia) {
self.heart_rate = 160;
}
}
/// Test-only convenience wrapper for saturation availability without dropout.
#[cfg(test)]
pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
self.spo2_status_during(pulse_rate, false)
}
/// Effective quality can be temporarily reduced by an NIBP cuff on the
/// same extremity. A detached probe still has highest priority.
pub fn spo2_status_at_quality(&self, pulse_rate: Option<i32>, signal_lost: bool,
effective_quality: Spo2Quality) -> Spo2Status {
if !self.spo2_sensor_attached {
Spo2Status::NoSensor
} else if (signal_lost && self.spo2_quality == Spo2Quality::Poor)
|| effective_quality == Spo2Quality::None || pulse_rate.is_none()
|| !self.ecg_rhythm.can_generate_pulse()
|| self.pulse_conduction == PulseConduction::None
|| self.heart_rate <= 0
{
Spo2Status::NoReading
} else {
Spo2Status::Available
}
}
/// Quality without cuff interference; retained for regression tests.
#[cfg(test)]
pub fn spo2_status_during(&self, pulse_rate: Option<i32>, signal_lost: bool) -> Spo2Status {
self.spo2_status_at_quality(pulse_rate, signal_lost, self.spo2_quality)
}
}
impl Default for Parameters {
fn default() -> Self {
Self {
patient_name: String::new(),
alarms: AlarmSettings::default(),
audible_alarms: true,
chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,
ecg_lead: EcgLead::II,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
spo2_quality: Spo2Quality::Good,
spo2_sensor_attached: true,
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
pulse_pressure_variation: 0,
nibp_systolic: 118,
nibp_diastolic: 74,
nibp_interval_minutes: 5,
nibp_no_reading: false,
nibp_cuff_on_spo2: false,
nibp_cuff_on_art: false,
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 compression_quality_defaults_to_adequate_and_has_requested_pressure_ranges() {
let p = Parameters::default();
assert!(!p.chest_compressions_active);
assert_eq!(p.chest_compression_quality, ChestCompressionQuality::Adequate);
assert_eq!(ChestCompressionQuality::Good.peak_range(), Some((81.0, 99.0)));
assert_eq!(ChestCompressionQuality::Adequate.peak_range(), Some((63.0, 77.0)));
assert_eq!(ChestCompressionQuality::Poor.peak_range(), Some((25.0, 55.0)));
assert_eq!(ChestCompressionQuality::Bad.peak_range(), None);
}
#[test]
fn ecg_lead_defaults_to_ii_and_selection_is_bijective() {
let p = Parameters::default();
assert_eq!(p.ecg_lead, EcgLead::II);
assert_eq!(p.ecg_lead.label(), "II");
for index in 0..EcgLead::LABELS.len() as u32 {
let lead = EcgLead::from_index(index);
assert_eq!(lead.index(), index);
assert_eq!(lead.label(), EcgLead::LABELS[index as usize]);
}
assert_eq!(EcgLead::from_index(999), EcgLead::II);
assert!(EcgLead::AVR.display_gain() < 0.0);
assert_eq!(EcgLead::II.display_gain(), 1.0);
}
#[test]
fn mean_pressure_uses_one_third_pulse_pressure() {
assert_eq!(mean_arterial_pressure(120, 75), 90);
}
#[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());
}
#[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);
assert_eq!(low_only.display("MAP"), "MAP ↓60 ↑---");
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);
assert_eq!(both.display("SYS"), "SYS ↓80 ↑180");
assert!(!AlarmLimits { lower: Some(181), upper: Some(80) }.valid());
}
#[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);
}
#[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());
}
#[test]
fn vt_stays_perfusing_and_pvt_is_electrically_organized_but_pulseless() {
use EcgRhythm::*;
assert!(VentricularTachycardia.has_qrs());
assert!(VentricularTachycardia.can_generate_pulse());
assert!(PulselessVentricularTachycardia.has_qrs());
assert!(!PulselessVentricularTachycardia.can_generate_pulse());
assert!(!VentricularFibrillation.can_generate_pulse());
assert!(!Asystole.can_generate_pulse());
for rhythm in [VentricularTachycardia, PulselessVentricularTachycardia, VentricularFibrillation] {
assert_eq!(rhythm.rhythm_alarm(), Some("ARRHYTHMIA"));
}
assert_eq!(Asystole.rhythm_alarm(), Some("ASYSTOLE"));
assert_eq!(Sinus.rhythm_alarm(), None);
assert_eq!(AtrialFibrillation.rhythm_alarm(), None);
}
#[test]
fn tachycardia_selection_sets_160_bpm_but_other_rhythms_do_not() {
let mut p = Parameters::default();
p.select_ecg_rhythm(EcgRhythm::VentricularTachycardia);
assert_eq!(p.heart_rate, 160);
p.heart_rate = 185; // a subsequent instructor override remains possible
p.select_ecg_rhythm(EcgRhythm::Sinus);
assert_eq!(p.heart_rate, 185);
p.select_ecg_rhythm(EcgRhythm::PulselessVentricularTachycardia);
assert_eq!(p.heart_rate, 160);
assert!(!p.ecg_rhythm.can_generate_pulse());
}
#[test]
fn transient_poor_signal_loss_preserves_sensor_precedence() {
let mut p = Parameters::default();
p.spo2_quality = Spo2Quality::Poor;
assert_eq!(p.spo2_status_during(Some(80), false), Spo2Status::Available);
assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::NoReading);
p.spo2_sensor_attached = false;
assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::NoSensor);
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::Good;
assert_eq!(p.spo2_status_during(Some(80), false), Spo2Status::Available);
assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::Available);
}
#[test]
fn sensor_and_no_reading_alarms_override_spo2_thresholds() {
let mut p = Parameters::default();
assert_eq!(p.spo2_status(Some(80)), Spo2Status::Available);
assert_eq!(p.spo2_status(None), Spo2Status::NoReading);
p.spo2_quality = Spo2Quality::None;
assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
p.spo2_sensor_attached = false;
assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoSensor);
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::Good;
p.ecg_rhythm = EcgRhythm::PulselessVentricularTachycardia;
assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
p.ecg_rhythm = EcgRhythm::Sinus;
p.pulse_conduction = PulseConduction::None;
assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
}
#[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)));
}
}