From 483a3c3d61e902d94cb1a9f805ab42d6a81c5ed6 Mon Sep 17 00:00:00 2001 From: GABRIEL Sebastian Date: Thu, 12 Nov 2026 15:11:04 +0100 Subject: [PATCH] v0.5.4: Chest compressions --- ...-monitor-simulation-v0.5.3-to-v0.5.4.patch | 764 ++++++++++++++++++ patient-monitor-simulation/Cargo.lock | 2 +- patient-monitor-simulation/Cargo.toml | 2 +- patient-monitor-simulation/README.de.md | 47 ++ patient-monitor-simulation/README.de.md.orig | 35 +- patient-monitor-simulation/README.de.md.rej | 22 +- patient-monitor-simulation/README.md | 43 +- patient-monitor-simulation/src/alarm.rs | 5 +- patient-monitor-simulation/src/model.rs | 38 + patient-monitor-simulation/src/render.rs | 25 +- patient-monitor-simulation/src/simulation.rs | 295 ++++++- patient-monitor-simulation/src/ui.rs | 57 +- 12 files changed, 1288 insertions(+), 47 deletions(-) create mode 100644 patient-monitor-simulation-v0.5.3-to-v0.5.4.patch diff --git a/patient-monitor-simulation-v0.5.3-to-v0.5.4.patch b/patient-monitor-simulation-v0.5.3-to-v0.5.4.patch new file mode 100644 index 0000000..cfca810 --- /dev/null +++ b/patient-monitor-simulation-v0.5.3-to-v0.5.4.patch @@ -0,0 +1,764 @@ +diff --git a/Cargo.toml b/Cargo.toml +index debf638..d2a7098 100644 +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "patient-monitor-simulation" +-version = "0.5.3" ++version = "0.5.4" + edition = "2021" + license = "MIT" + description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" +diff --git a/README.de.md b/README.de.md +index 374281f..f7c5ba2 100644 +--- a/README.de.md ++++ b/README.de.md +@@ -1,4 +1,4 @@ +-# Patient Monitor Simulation (PaMSim) — v0.5.3 ++# Patient Monitor Simulation (PaMSim) — v0.5.4 + + Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux. + +@@ -6,6 +6,53 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst + > EKG, invasive arterielle Druckkurve, Plethysmogramm und Kapnogramm sind schematische mathematische Annäherungen. + > Die Simulation wurde nicht klinisch validiert und ist kein Medizinprodukt. + ++## Thoraxkompressionen (v0.5.4) ++ ++Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche ++**Start Chest Compressions** die Simulation. Während aktiver Kompressionen ++wechselt sie zu **Stop Chest Compressions** mit rotem Hintergrund. ++Die **Compression quality** kann jederzeit auf **Good**, **Adequate** ++(Standard), **Poor** oder **Bad** gestellt werden. ++ ++- Die Kompressionsfrequenz schwankt zufällig im Bereich **90–110/min**; ++ für jeden Druckstoß werden Frequenz und Druckhöhe neu festgelegt. ++ Der eingestellte EKG-Rhythmus und die elektrische Herzfrequenz bleiben ++ unverändert. ++- Das EKG wird durch kompressionssynchrone Bewegungsartefakte überlagert. ++ Besteht ein **eigener arterieller Kreislauf**, bleibt die ursprüngliche ++ Druckkurve bestehen, wird jedoch durch Kompressionen verzerrt. ++- **Ohne eigenständige arterielle Pulsation** (beispielsweise bei KF, PVT, ++ Asystolie oder PEA) erzeugen wirksame Kompressionen breite, stumpfe ++ arterielle Druckwellen: ++ ++ | Kompressionsqualität | Systolischer ART-Spitzendruck | ++ | --- | --- | ++ | Good | 90 mmHg ±10 % (81–99 mmHg) | ++ | Adequate (Standard) | 70 mmHg ±10 % (63–77 mmHg) | ++ | Poor | 50 mmHg, +10 % / −50 % (25–55 mmHg) | ++ | Bad | Kein durch Kompressionen erzeugter Druck; Grundschwankung von 0–5 mmHg | ++ ++ Bei fehlender Eigenpulsation zeigt **ART SYS** den Spitzendruck der ++ aktuellen Kompression; **DIA/MAP** bleiben `--`, da sie aus der synthetischen ++ Kurve nicht verlässlich bestimmt werden. ++- Ein SpO₂-Messwert und ein Plethysmogramm werden während laufender ++ Kompressionen **nur bei Qualität Good** angezeigt, vorausgesetzt, der Sensor ++ ist angeschlossen und nicht durch eine NIBP-Manschette okkludiert. ++ Die angezeigte Signalqualität beträgt unabhängig von der Grundeinstellung ++ **Poor (★)**. Die angezeigte **PR folgt der Kompressionsfrequenz (90–110/min)**, ++ nicht der EKG-Frequenz. Bei Adequate, Poor oder Bad erscheint **NO READING**, ++ bei abgezogenem Sensor **NO SENSOR**. Die durch Kompressionen erzwungene ++ Signalqualität Poor führt nicht zu den sonst üblichen periodischen ++ Aussetzern; bei regulärer Grundeinstellung Poor gelten diese nach Ende ++ der Kompressionen wieder. ++- Die bestehenden Rhythmus- und Grenzwertalarme bleiben aktiv. ART-SYS-Grenzen ++ beziehen sich dabei auf die Kompressionsspitzen. Die NIBP-Messintervalle bleiben unverändert; die Dauer eines Messzyklus ++ richtet sich weiterhin nach der wirksamen SpO₂-Signalqualität beim Start. ++ ++**Hinweis:** Druckwerte und Signalformen sind didaktisch gewählt und nicht ++klinisch validiert. Aus dieser Simulation darf keine reale Wirksamkeit von ++Reanimationsmaßnahmen abgeleitet werden. ++ + ## Installation, Kompilierung und Start unter Fedora + + ```bash +diff --git a/README.md b/README.md +index 20d5943..30ec481 100644 +--- a/README.md ++++ b/README.md +@@ -1,4 +1,4 @@ +-# Patient Monitor Simulation (PaMSim) — v0.5.3 ++# Patient Monitor Simulation (PaMSim) — v0.5.4 + + A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. + +@@ -6,6 +6,47 @@ A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. + > plethysmography and capnography are schematic mathematical approximations. The + > simulation has no clinical validation and is not a medical device. + ++## Chest compressions (v0.5.4) ++ ++The **Chest compressions** Admin group provides a large **Start Chest Compressions** ++button (green background). While active it changes to **Stop Chest Compressions** ++(red background). **Compression quality** can be changed at any time: ++**Good**, **Adequate** (default), **Poor**, or **Bad**. ++ ++- Compressions are generated independently of the ECG at **90–110/min**, with ++ a new reproducible pseudo-random compression rate and pressure each stroke. ++ **The ECG rhythm and electrical HR setting are not changed.** ++- Every compression adds movement artifact to the ECG. In a patient with ++ **existing intrinsic arterial perfusion**, the native arterial waveform is ++ preserved but distorted by compression-synchronous pressure artifact. ++- With **no intrinsic arterial pulse** (e.g., VF, PVT, asystole or PEA), ++ each effective compression generates a broad, blunt arterial pressure wave: ++ ++ | Compression quality | Compression-generated ART systolic peak | ++ | --- | --- | ++ | Good | 90 mmHg ±10% (81–99 mmHg) | ++ | Adequate (default) | 70 mmHg ±10% (63–77 mmHg) | ++ | Poor | 50 mmHg, +10% / −50% (25–55 mmHg) | ++ | Bad | No compression-generated arterial pressure; 0–5 mmHg baseline drift | ++ ++ During pulseless CPR, **ART SYS** shows the current compression peak, ++ while **DIA/MAP** remain `--` (not estimable from this synthetic pressure). ++- SpO₂ numeric saturation and the pleth waveform remain visible **only when ++ compression quality is Good**, provided the sensor is connected and not ++ occluded by an NIBP cuff. Their effective signal quality is forced to ++ **Poor (★)**, irrespective of the normal Admin quality setting. The displayed ++ pleth-derived **PR follows the compression rate (90–110/min)**, not the ECG. ++ Adequate, Poor and Bad CPR display **NO READING**; detached sensors display ++ **NO SENSOR**. Compression-induced Poor quality does not schedule the usual ++ intermittent dropout; that resumes when ordinary Poor signal mode returns. ++- Existing numerical alarms and rhythm alarms remain active. ART SYS limits ++ apply to compression-generated systolic peaks; NIBP scheduling remains unchanged; its cycle duration still depends on ++ effective SpO₂ quality at the start of a measurement. ++ ++These pressure targets are **didactic assumptions**, not validated CPR ++hemodynamic criteria. The exercise must not be used to judge real compression ++quality or clinical perfusion. ++ + ## Build and run on Fedora + + ```bash +diff --git a/src/alarm.rs b/src/alarm.rs +index d368f20..116b7f4 100644 +--- a/src/alarm.rs ++++ b/src/alarm.rs +@@ -35,7 +35,6 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel { + let captured = p.ecg_rhythm.can_generate_pulse() + && p.heart_rate > 0 + && p.pulse_conduction != PulseConduction::None; +- let pr = if captured { sim.pulse_rate() } else { None }; + + if p.show_ecg { + if p.ecg_rhythm.rhythm_alarm().is_some() { +@@ -47,10 +46,10 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel { + } + + if p.show_spo2 { +- let status = p.spo2_status_at_quality(pr, sim.poor_signal_lost(), sim.spo2_quality(p)); ++ let status = sim.spo2_status(p); + if status != Spo2Status::Available + || outside(p.alarms.spo2, Some(p.spo2)) +- || outside(p.alarms.pr, pr) ++ || outside(p.alarms.pr, sim.spo2_pulse_rate(p)) + { + result = AlarmLevel::Standard; + } +diff --git a/src/model.rs b/src/model.rs +index 996d6ba..009b231 100644 +--- a/src/model.rs ++++ b/src/model.rs +@@ -83,6 +83,29 @@ pub enum CapnoShape { + 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)] +@@ -202,6 +225,8 @@ 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 heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate + pub pulse_conduction: PulseConduction, +@@ -277,6 +302,8 @@ impl Default for Parameters { + patient_name: String::new(), + alarms: AlarmSettings::default(), + audible_alarms: true, ++ chest_compressions_active: false, ++ chest_compression_quality: ChestCompressionQuality::Adequate, + ecg_rhythm: EcgRhythm::Sinus, + heart_rate: 75, + pulse_conduction: PulseConduction::OneToOne, +@@ -313,6 +340,17 @@ pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 { + 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 mean_pressure_uses_one_third_pulse_pressure() { + assert_eq!(mean_arterial_pressure(120, 75), 90); +diff --git a/src/render.rs b/src/render.rs +index 8cce43d..4053fe1 100644 +--- a/src/render.rs ++++ b/src/render.rs +@@ -150,6 +150,7 @@ fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64, + ], right, top, height * 0.65, width * 0.72); + } + ++#[cfg(test)] + fn pleth_trace_enabled(p: &Parameters) -> bool { + p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None + } +@@ -160,9 +161,16 @@ fn spo2_vitals(p: &Parameters, pulse_rate: Option, signal_lost: bool) + spo2_vitals_at_quality(p, pulse_rate, signal_lost, p.spo2_quality) + } + ++#[cfg(test)] + fn spo2_vitals_at_quality(p: &Parameters, pulse_rate: Option, signal_lost: bool, + quality: Spo2Quality) -> (String, String, String) { +- match p.spo2_status_at_quality(pulse_rate, signal_lost, quality) { ++ spo2_vitals_for_status(p, pulse_rate, quality, ++ p.spo2_status_at_quality(pulse_rate, signal_lost, quality)) ++} ++ ++fn spo2_vitals_for_status(p: &Parameters, pulse_rate: Option, quality: Spo2Quality, ++ status: Spo2Status) -> (String, String, String) { ++ match status { + Spo2Status::NoSensor => ( + "SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()), + Spo2Status::NoReading => ( +@@ -196,10 +204,11 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, + && p.heart_rate > 0 + && p.pulse_conduction != PulseConduction::None; + let pulse_rate = if has_capture { sim.pulse_rate() } else { None }; ++ let spo2_rate = sim.spo2_pulse_rate(p); + let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 { + Some(p.heart_rate) + } else { None }; +- let spo2_status = p.spo2_status_at_quality(pulse_rate, sim.poor_signal_lost(), sim.spo2_quality(p)); ++ let spo2_status = sim.spo2_status(p); + let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None }; + + let limits: Vec<(&str, AlarmLimits)> = match ch { +@@ -228,8 +237,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, + } + } + Channel::Pleth => { +- let (label, value, info) = spo2_vitals_at_quality(p, pulse_rate, +- sim.poor_signal_lost(), sim.spo2_quality(p)); ++ let (label, value, info) = spo2_vitals_for_status(p, spo2_rate, ++ sim.spo2_quality(p), spo2_status); + text(cr, &label, x, top + row_h * 0.24, label_size, color, false); + let technical_alarm = spo2_status != Spo2Status::Available; + let value_size = if technical_alarm { +@@ -239,8 +248,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, + width, color, technical_alarm || alarmed(p.alarms.spo2, oxygen), flash); + if oxygen.is_some() { + draw_alarm_inline(cr, x, info_y, sub_size, width, color, +- "% PR ", &pulse_rate.unwrap_or_default().to_string(), " bpm", +- alarmed(p.alarms.pr, pulse_rate), flash); ++ "% PR ", &spo2_rate.unwrap_or_default().to_string(), " bpm", ++ alarmed(p.alarms.pr, spo2_rate), flash); + } else { + text(cr, &info, x, info_y, sub_size, color, false); + } +@@ -427,9 +436,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color, + + // Disconnected or absent pleth signal: no curve, including historical pulses. + if matches!(channel, Channel::Pleth) +- && (!pleth_trace_enabled(p) +- || p.spo2_status_at_quality(sim.pulse_rate(), sim.poor_signal_lost(), +- sim.spo2_quality(p)) != Spo2Status::Available) ++ && sim.spo2_status(p) != Spo2Status::Available + { + let _ = cr.restore(); + return; +diff --git a/src/simulation.rs b/src/simulation.rs +index c148a30..06fd000 100644 +--- a/src/simulation.rs ++++ b/src/simulation.rs +@@ -2,7 +2,8 @@ + //! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse. + use std::collections::VecDeque; + +-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; ++use crate::model::{ArterialShape, CapnoShape, ChestCompressionQuality, EcgRhythm, ++ Parameters, PulseConduction, Spo2Quality, Spo2Status}; + use crate::nibp::{CuffZone, NibpMachine, NibpReading}; + + const SAMPLE_STEP: f64 = 0.004; // 250 Hz; adequately samples the QRS upstroke +@@ -87,6 +88,91 @@ impl PoorSignalOutages { + } + } + ++/// CPR is a separate mechanical clock, independent of intrinsic cardiac rate. ++/// Randomness is sampled once per compression, so peaks and intervals remain ++/// stable during drawing and are reproducible in tests. ++#[derive(Debug)] ++struct ChestCompressions { ++ active: bool, ++ phase: f64, ++ rate_bpm: f64, ++ peak_pressure: f64, ++ quality: ChestCompressionQuality, ++ rng: u64, ++} ++ ++impl ChestCompressions { ++ fn new() -> Self { ++ Self { active: false, phase: 0.0, rate_bpm: 100.0, ++ peak_pressure: 0.0, quality: ChestCompressionQuality::Adequate, ++ rng: 0xC0FF_EE12_3456_789A } ++ } ++ ++ 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 choose_peak(&mut self) { ++ self.peak_pressure = match self.quality.peak_range() { ++ Some((low, high)) => low + (high - low) * self.random_unit(), ++ None => 0.0, ++ }; ++ } ++ ++ fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) { ++ if !enabled { ++ self.active = false; ++ self.phase = 0.0; ++ self.peak_pressure = 0.0; ++ return; ++ } ++ if !self.active { ++ self.active = true; ++ self.phase = 0.0; ++ self.rate_bpm = 90.0 + self.random_unit() * 20.0; ++ self.quality = quality; ++ self.choose_peak(); ++ } else if self.quality != quality { ++ self.quality = quality; ++ self.choose_peak(); ++ } ++ self.phase += SAMPLE_STEP * self.rate_bpm / 60.0; ++ if self.phase >= 1.0 { ++ self.phase = self.phase.fract(); ++ self.rate_bpm = 90.0 + self.random_unit() * 20.0; ++ self.choose_peak(); ++ } ++ } ++ ++ fn pressure_wave(&self) -> f64 { ++ // Rounded, broad compression crest (no narrow physiological upstroke). ++ let rise = smooth_step(self.phase / 0.22); ++ let fall = 1.0 - smooth_step((self.phase - 0.36) / 0.43); ++ (rise * fall).clamp(0.0, 1.0) ++ } ++ ++ fn pleth_wave(&self) -> f64 { ++ // A delayed, deliberately weak mechanical pleth pulse. ++ let phase = (self.phase - 0.26).rem_euclid(1.0); ++ smooth_step(phase / 0.27) * (1.0 - smooth_step((phase - 0.27) / 0.62)) ++ } ++ ++ fn ecg_artifact(&self, time: f64) -> f64 { ++ // Compression-synchronous baseline motion and jagged contact artifact. ++ let wave = self.pressure_wave(); ++ 0.56 * (wave - 0.30) ++ + 0.12 * (time * 71.0).sin() * wave ++ + 0.08 * (time * 113.0).sin() * wave ++ } ++} ++ ++fn smooth_step(value: f64) -> f64 { ++ let t = value.clamp(0.0, 1.0); ++ t * t * (3.0 - 2.0 * t) ++} ++ + pub struct Simulator { + samples: VecDeque, + time: f64, +@@ -100,6 +186,7 @@ pub struct Simulator { + previous_conduction: PulseConduction, + previous_heart_rate: i32, + poor_signal_outages: PoorSignalOutages, ++ compressions: ChestCompressions, + nibp: NibpMachine, + art_hold_pressure: Option, + pending_time: f64, +@@ -120,6 +207,7 @@ impl Simulator { + previous_conduction: params.pulse_conduction, + previous_heart_rate: params.heart_rate, + poor_signal_outages: PoorSignalOutages::new(), ++ compressions: ChestCompressions::new(), + nibp: NibpMachine::new(), + art_hold_pressure: None, + pending_time: 0.0, +@@ -149,7 +237,43 @@ impl Simulator { + pub fn time(&self) -> f64 { self.time } + + pub fn spo2_quality(&self, p: &Parameters) -> Spo2Quality { +- self.nibp.effective_spo2_quality(self.time, p) ++ if !p.chest_compressions_active { ++ return self.nibp.effective_spo2_quality(self.time, p); ++ } ++ if p.chest_compression_quality != ChestCompressionQuality::Good { ++ return Spo2Quality::None; ++ } ++ // During effective CPR the pleth signal is Poor regardless of Admin's ++ // baseline quality; an occlusive NIBP cuff can still suppress it. ++ if p.nibp_cuff_on_spo2 { ++ match self.nibp.cuff_zone(self.time, p) { ++ CuffZone::Occluded => return Spo2Quality::None, ++ CuffZone::Partial | CuffZone::Free => {} ++ } ++ } ++ Spo2Quality::Poor ++ } ++ ++ /// Display-only pulse rate: under effective CPR the peripheral signal ++ /// follows compressions rather than non-perfusing electrical QRS events. ++ pub fn spo2_pulse_rate(&self, p: &Parameters) -> Option { ++ if p.chest_compressions_active { ++ (p.chest_compression_quality == ChestCompressionQuality::Good) ++ .then_some(self.compressions.rate_bpm.round() as i32) ++ } else { ++ self.pulse_rate() ++ } ++ } ++ ++ pub fn spo2_status(&self, p: &Parameters) -> Spo2Status { ++ if !p.spo2_sensor_attached { return Spo2Status::NoSensor; } ++ if p.chest_compressions_active { ++ return if p.chest_compression_quality == ChestCompressionQuality::Good ++ && self.spo2_quality(p) != Spo2Quality::None ++ { Spo2Status::Available } else { Spo2Status::NoReading }; ++ } ++ p.spo2_status_at_quality(self.pulse_rate(), self.poor_signal_lost(), ++ self.spo2_quality(p)) + } + + pub fn start_nibp_now(&mut self, p: &Parameters) { +@@ -161,7 +285,7 @@ impl Simulator { + if !p.spo2_sensor_attached || self.poor_signal_outages.active { + Spo2Quality::None + } else { +- p.spo2_quality ++ self.spo2_quality(p) + } + } + +@@ -169,6 +293,11 @@ impl Simulator { + pub fn displayed_art_pressures(&self, p: &Parameters, has_capture: bool) + -> (Option, Option, Option) { + if !has_capture { ++ // During pulseless CPR the upper ART number reflects the peak ++ // compression pressure; DIA/MAP remain intentionally unassessed. ++ if self.compressions.active && p.chest_compression_quality != ChestCompressionQuality::Bad { ++ return (Some(self.compressions.peak_pressure.round() as i32), None, None); ++ } + return (self.measured_art_pressure(), None, None); + } + if p.nibp_cuff_on_art { +@@ -219,8 +348,11 @@ impl Simulator { + + fn step(&mut self, params: &Parameters) { + self.time += SAMPLE_STEP; ++ self.compressions.update(params.chest_compressions_active, ++ params.chest_compression_quality); + self.poor_signal_outages.update(self.time, +- params.spo2_quality == Spo2Quality::Poor && params.spo2_sensor_attached); ++ !params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor ++ && params.spo2_sensor_attached); + // Snapshot the unoccluded sensor quality at the start of a cuff cycle. + // Cuff-induced signal loss during that cycle must not change its duration. + let start_quality = self.nibp_start_quality(params); +@@ -289,8 +421,25 @@ impl Simulator { + self.rate_qrs.pop_front(); + } + +- let ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate); +- let (normal_art, pleth_target) = self.mechanical_signals(params); ++ let mut ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate); ++ let (mut normal_art, mut pleth_target) = self.mechanical_signals(params); ++ if self.compressions.active { ++ ecg += self.compressions.ecg_artifact(self.time); ++ let perfusing = params.ecg_rhythm.can_generate_pulse() ++ && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0; ++ let wave = self.compressions.pressure_wave(); ++ if perfusing { ++ // Preserve the patient's intrinsic pressure, with superimposed ++ // compression-synchronous artifact even during bad CPR. ++ normal_art = (normal_art + 22.0 * (wave - 0.32)).clamp(0.0, 250.0); ++ } else if self.compressions.peak_pressure > 0.0 { ++ let baseline = pulseless_arterial_drift(self.time); ++ normal_art = baseline + (self.compressions.peak_pressure - baseline) * wave; ++ } ++ pleth_target = if params.chest_compression_quality == ChestCompressionQuality::Good { ++ 0.85 * self.compressions.pleth_wave() ++ } else { 0.0 }; ++ } + let art = self.art_with_cuff(normal_art, params); + let smoothing = 1.0 - (-SAMPLE_STEP / PLETH_FILTER_TAU).exp(); + self.filtered_pleth += smoothing * (pleth_target - self.filtered_pleth); +@@ -301,9 +450,7 @@ impl Simulator { + }; + + let pleth_quality = self.spo2_quality(params); +- let pleth_valid = params.spo2_sensor_attached +- && pleth_quality != Spo2Quality::None +- && !self.poor_signal_outages.active; ++ let pleth_valid = self.spo2_status(params) == Spo2Status::Available; + self.samples.push_back(Sample { + time: self.time, ecg, pleth, pleth_valid, pleth_quality, art, co2, + }); +@@ -313,9 +460,10 @@ impl Simulator { + } + + fn art_with_cuff(&mut self, normal_art: f64, params: &Parameters) -> f64 { +- if !params.nibp_cuff_on_art || !params.ecg_rhythm.can_generate_pulse() +- || params.pulse_conduction == PulseConduction::None || params.heart_rate <= 0 +- { ++ let native_pulse = params.ecg_rhythm.can_generate_pulse() ++ && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0; ++ let compression_pulse = self.compressions.active && self.compressions.peak_pressure > 0.0; ++ if !params.nibp_cuff_on_art || !(native_pulse || compression_pulse) { + self.art_hold_pressure = None; + return normal_art; + } +@@ -545,6 +693,129 @@ mod tests { + sim + } + ++ #[test] ++ fn compression_rate_varies_only_between_90_and_110_bpm() { ++ let mut cpr = ChestCompressions::new(); ++ let mut observed = Vec::new(); ++ for _ in 0..(25.0 / SAMPLE_STEP) as usize { ++ let previous = cpr.phase; ++ cpr.update(true, ChestCompressionQuality::Good); ++ assert!((90.0..=110.0).contains(&cpr.rate_bpm)); ++ if cpr.phase < previous { observed.push(cpr.rate_bpm); } ++ } ++ assert!(observed.len() >= 30); ++ assert!(observed.iter().any(|rate| (rate - observed[0]).abs() > 1.0)); ++ cpr.update(false, ChestCompressionQuality::Good); ++ assert!(!cpr.active); ++ assert_eq!(cpr.peak_pressure, 0.0); ++ } ++ ++ #[test] ++ fn compressions_generate_requested_pulseless_arterial_pressure_by_quality() { ++ for (quality, limits) in [ ++ (ChestCompressionQuality::Good, Some((81.0, 99.0))), ++ (ChestCompressionQuality::Adequate, Some((63.0, 77.0))), ++ (ChestCompressionQuality::Poor, Some((25.0, 55.0))), ++ (ChestCompressionQuality::Bad, None), ++ ] { ++ let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation, ++ chest_compressions_active: true, chest_compression_quality: quality, ++ ..Parameters::default() }; ++ let mut sim = Simulator::new(&p); ++ for _ in 0..(2.0 / SAMPLE_STEP) as usize { sim.step(&p); } ++ assert_eq!(sim.pulse_rate(), None, "no intrinsic QRS pulse in VF"); ++ let recent: Vec<_> = sim.samples.iter().rev().take(500).collect(); ++ let peak = recent.iter().map(|s| s.art).fold(f64::NEG_INFINITY, f64::max); ++ let (sys, dia, map) = sim.displayed_art_pressures(&p, false); ++ assert_eq!((dia, map), (None, None)); ++ if let Some((low, high)) = limits { ++ assert!(peak >= low - 1.0 && peak <= high + 1.0, ++ "{quality:?}: waveform peak {peak}"); ++ assert!(sys.is_some_and(|v| (low - 1.0..=high + 1.0).contains(&f64::from(v)))); ++ } else { ++ assert!(peak <= 5.0, "bad CPR must not create a pulse"); ++ assert!(sys.is_some_and(|v| (0..=5).contains(&v))); ++ } ++ } ++ } ++ ++ #[test] ++ fn good_cpr_can_create_poor_pleth_in_vf_despite_admin_no_quality() { ++ let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation, ++ spo2_quality: Spo2Quality::None, ++ chest_compressions_active: true, ++ chest_compression_quality: ChestCompressionQuality::Good, ++ ..Parameters::default() }; ++ let mut sim = Simulator::new(&p); ++ for _ in 0..400 { sim.step(&p); } ++ assert_eq!(sim.spo2_quality(&p), Spo2Quality::Poor); ++ assert_eq!(sim.spo2_status(&p), Spo2Status::Available); ++ assert!(sim.spo2_pulse_rate(&p).is_some_and(|v| (90..=110).contains(&v))); ++ assert!(sim.samples.iter().rev().take(400).any(|s| s.pleth > 0.05 && s.pleth_valid)); ++ assert!(sim.samples.iter().rev().take(400).all(|s| s.pleth_quality == Spo2Quality::Poor)); ++ } ++ ++ #[test] ++ fn only_good_cpr_shows_pleth_and_sensor_disconnect_takes_precedence() { ++ for quality in [ChestCompressionQuality::Adequate, ++ ChestCompressionQuality::Poor, ChestCompressionQuality::Bad] { ++ let p = Parameters { chest_compressions_active: true, ++ chest_compression_quality: quality, ..Parameters::default() }; ++ let mut sim = Simulator::new(&p); ++ sim.step(&p); ++ assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading); ++ assert_eq!(sim.spo2_pulse_rate(&p), None); ++ assert!(!sim.samples.back().unwrap().pleth_valid); ++ } ++ let mut p = Parameters { chest_compressions_active: true, ++ chest_compression_quality: ChestCompressionQuality::Good, ..Parameters::default() }; ++ let mut sim = Simulator::new(&p); ++ p.spo2_sensor_attached = false; ++ sim.step(&p); ++ assert_eq!(sim.spo2_status(&p), Spo2Status::NoSensor); ++ assert!(!sim.samples.back().unwrap().pleth_valid); ++ } ++ ++ #[test] ++ fn compressions_distort_ecg_and_preserve_intrinsic_pulses_in_sinus() { ++ let normal = Parameters::default(); ++ let with_cpr = Parameters { chest_compressions_active: true, ++ chest_compression_quality: ChestCompressionQuality::Adequate, ++ ..Parameters::default() }; ++ let mut base = Simulator::new(&normal); ++ let mut cpr = Simulator::new(&with_cpr); ++ let mut ecg_distortion = false; ++ let mut art_distortion = false; ++ for _ in 0..500 { ++ base.step(&normal); ++ cpr.step(&with_cpr); ++ let native = base.samples.back().unwrap(); ++ let compressed = cpr.samples.back().unwrap(); ++ ecg_distortion |= (compressed.ecg - native.ecg).abs() > 0.1; ++ art_distortion |= (compressed.art - native.art).abs() > 5.0; ++ } ++ assert!(ecg_distortion); ++ assert!(art_distortion); ++ assert!(cpr.samples.iter().rev().take(500).any(|s| s.art > 60.0)); ++ assert_eq!(cpr.pulse_rate(), Some(75), "CPR must not change underlying HR/PR capture"); ++ } ++ ++ #[test] ++ fn stopping_compressions_restores_pulseless_drift_and_normal_pleth_rules() { ++ let mut p = Parameters { ecg_rhythm: EcgRhythm::Asystole, ++ chest_compressions_active: true, ++ chest_compression_quality: ChestCompressionQuality::Good, ++ ..Parameters::default() }; ++ let mut sim = Simulator::new(&p); ++ assert_eq!(sim.spo2_status(&p), Spo2Status::Available); ++ p.chest_compressions_active = false; ++ sim.step(&p); ++ assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art)); ++ assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading); ++ assert!(!sim.samples.back().unwrap().pleth_valid); ++ assert_eq!(sim.spo2_pulse_rate(&p), None); ++ } ++ + #[test] + fn signals_remain_in_expected_ranges() { + let p = Parameters::default(); +diff --git a/src/ui.rs b/src/ui.rs +index 7e6fd0a..ffb8579 100644 +--- a/src/ui.rs ++++ b/src/ui.rs +@@ -9,7 +9,8 @@ use gtk::prelude::*; + use gtk::{Application, ApplicationWindow, Orientation}; + + use crate::alarm::{self, AlarmAudio}; +-use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; ++use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, ++ ChestCompressionQuality, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; + use crate::render; + use crate::simulation::Simulator; + +@@ -186,6 +187,60 @@ fn create_admin(app: &Application, params: SharedParams, + patient_row.append(&name_entry); + patient.append(&patient_row); + ++ // Resuscitation controls are deliberately near the top of the Admin panel. ++ // CSS sets the *button background*, not just its text color. ++ if let Some(display) = gdk::Display::default() { ++ let provider = gtk::CssProvider::new(); ++ provider.load_from_data( ++ "button.cpr-start { background-image: none; background-color: #158742; color: #ffffff; font-weight: bold; } ++ button.cpr-stop { background-image: none; background-color: #c53035; color: #ffffff; font-weight: bold; }" ++ ); ++ gtk::style_context_add_provider_for_display( ++ &display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION); ++ } ++ let cpr = group(&controls, "Chest compressions", None); ++ let compression_button = gtk::Button::with_label("Start Chest Compressions"); ++ compression_button.set_hexpand(true); ++ compression_button.add_css_class("cpr-start"); ++ compression_button.connect_clicked({ ++ let params = params.clone(); ++ move |button| { ++ let mut p = params.borrow_mut(); ++ p.chest_compressions_active = !p.chest_compressions_active; ++ if p.chest_compressions_active { ++ button.set_label("Stop Chest Compressions"); ++ button.remove_css_class("cpr-start"); ++ button.add_css_class("cpr-stop"); ++ } else { ++ button.set_label("Start Chest Compressions"); ++ button.remove_css_class("cpr-stop"); ++ button.add_css_class("cpr-start"); ++ } ++ } ++ }); ++ cpr.append(&compression_button); ++ let _quality = add_dropdown_at(&cpr, "Compression quality", ++ &["Good", "Adequate", "Poor", "Bad"], 1, params.clone(), |p, selected| { ++ p.chest_compression_quality = match selected { ++ 0 => ChestCompressionQuality::Good, ++ 2 => ChestCompressionQuality::Poor, ++ 3 => ChestCompressionQuality::Bad, ++ _ => ChestCompressionQuality::Adequate, ++ }; ++ }); ++ let cpr_hint = gtk::Label::new(Some( ++ "CPR: 90–110 compressions/min. ECG is distorted; ART receives compression waves. " ++ )); ++ cpr_hint.set_xalign(0.0); ++ cpr_hint.set_wrap(true); ++ cpr.append(&cpr_hint); ++ let cpr_hint2 = gtk::Label::new(Some( ++ "Only Good compressions generate a Poor-quality SpO₂/pleth signal (if the sensor is attached)." ++ )); ++ cpr_hint2.set_xalign(0.0); ++ cpr_hint2.set_wrap(true); ++ cpr.append(&cpr_hint2); ++ + let ecg = group(&controls, "ECG", Some(ECG_GREEN)); + add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show); + let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[ diff --git a/patient-monitor-simulation/Cargo.lock b/patient-monitor-simulation/Cargo.lock index 0bed9fc..a7b458d 100644 --- a/patient-monitor-simulation/Cargo.lock +++ b/patient-monitor-simulation/Cargo.lock @@ -438,7 +438,7 @@ dependencies = [ [[package]] name = "patient-monitor-simulation" -version = "0.5.3" +version = "0.5.4" dependencies = [ "gtk4", ] diff --git a/patient-monitor-simulation/Cargo.toml b/patient-monitor-simulation/Cargo.toml index debf638..d2a7098 100644 --- a/patient-monitor-simulation/Cargo.toml +++ b/patient-monitor-simulation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "patient-monitor-simulation" -version = "0.5.3" +version = "0.5.4" edition = "2021" license = "MIT" description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" diff --git a/patient-monitor-simulation/README.de.md b/patient-monitor-simulation/README.de.md index cf61f7d..306d7a8 100644 --- a/patient-monitor-simulation/README.de.md +++ b/patient-monitor-simulation/README.de.md @@ -6,6 +6,53 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst > EKG, invasive arterielle Druckkurve, Plethysmogramm und Kapnogramm sind schematische mathematische Annäherungen. > Die Simulation wurde nicht klinisch validiert und ist kein Medizinprodukt. +## Thoraxkompressionen (v0.5.4) + +Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche +**Start Chest Compressions** die Simulation. Während aktiver Kompressionen +wechselt sie zu **Stop Chest Compressions** mit rotem Hintergrund. +Die **Compression quality** kann jederzeit auf **Good**, **Adequate** +(Standard), **Poor** oder **Bad** gestellt werden. + +- Die Kompressionsfrequenz schwankt zufällig im Bereich **90–110/min**; + für jeden Druckstoß werden Frequenz und Druckhöhe neu festgelegt. + Der eingestellte EKG-Rhythmus und die elektrische Herzfrequenz bleiben + unverändert. +- Das EKG wird durch kompressionssynchrone Bewegungsartefakte überlagert. + Besteht ein **eigener arterieller Kreislauf**, bleibt die ursprüngliche + Druckkurve bestehen, wird jedoch durch Kompressionen verzerrt. +- **Ohne eigenständige arterielle Pulsation** (beispielsweise bei KF, PVT, + Asystolie oder PEA) erzeugen wirksame Kompressionen breite, stumpfe + arterielle Druckwellen: + + | Kompressionsqualität | Systolischer ART-Spitzendruck | + | --- | --- | + | Good | 90 mmHg ±10 % (81–99 mmHg) | + | Adequate (Standard) | 70 mmHg ±10 % (63–77 mmHg) | + | Poor | 50 mmHg, +10 % / −50 % (25–55 mmHg) | + | Bad | Kein durch Kompressionen erzeugter Druck; Grundschwankung von 0–5 mmHg | + + Bei fehlender Eigenpulsation zeigt **ART SYS** den Spitzendruck der + aktuellen Kompression; **DIA/MAP** bleiben `--`, da sie aus der synthetischen + Kurve nicht verlässlich bestimmt werden. +- Ein SpO₂-Messwert und ein Plethysmogramm werden während laufender + Kompressionen **nur bei Qualität Good** angezeigt, vorausgesetzt, der Sensor + ist angeschlossen und nicht durch eine NIBP-Manschette okkludiert. + Die angezeigte Signalqualität beträgt unabhängig von der Grundeinstellung + **Poor (★)**. Die angezeigte **PR folgt der Kompressionsfrequenz (90–110/min)**, + nicht der EKG-Frequenz. Bei Adequate, Poor oder Bad erscheint **NO READING**, + bei abgezogenem Sensor **NO SENSOR**. Die durch Kompressionen erzwungene + Signalqualität Poor führt nicht zu den sonst üblichen periodischen + Aussetzern; bei regulärer Grundeinstellung Poor gelten diese nach Ende + der Kompressionen wieder. +- Die bestehenden Rhythmus- und Grenzwertalarme bleiben aktiv. ART-SYS-Grenzen + beziehen sich dabei auf die Kompressionsspitzen. Die NIBP-Messintervalle bleiben unverändert; die Dauer eines Messzyklus + richtet sich weiterhin nach der wirksamen SpO₂-Signalqualität beim Start. + +**Hinweis:** Druckwerte und Signalformen sind didaktisch gewählt und nicht +klinisch validiert. Aus dieser Simulation darf keine reale Wirksamkeit von +Reanimationsmaßnahmen abgeleitet werden. + ## Installation, Kompilierung und Start unter Fedora ```bash diff --git a/patient-monitor-simulation/README.de.md.orig b/patient-monitor-simulation/README.de.md.orig index 7565e9f..cf61f7d 100644 --- a/patient-monitor-simulation/README.de.md.orig +++ b/patient-monitor-simulation/README.de.md.orig @@ -9,7 +9,7 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst ## Installation, Kompilierung und Start unter Fedora ```bash -sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel +sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pipewire-utils cargo test cargo run --release ``` @@ -43,6 +43,39 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden. Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben. +## Akustische Alarme (v0.5.3) + +Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im +Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten. +Mit **Test tone** kann die Tonausgabe unabhängig von der Stummschaltung geprüft +werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin. + +- **Kritische Rhythmusalarme:** VT, PVT, Kammerflimmern und Asystolie lösen + einen Doppelton aus (zweimal kurz 880 Hz), der ungefähr alle 1,5 Sekunden + wiederholt wird. +- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie + **NO SENSOR** und **NO READING** lösen einen kurzen Ton mit 700 Hz aus, + der ungefähr alle 2,5 Sekunden wiederholt wird. +- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven + Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder + Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche + lösen keine akustischen Alarme aus. +- Nicht verfügbare Messwerte, etwa NIBP vor der ersten abgeschlossenen Messung, + lösen keinen numerischen Grenzwertalarm aus. Eine laufende NIBP-Messung + selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung + der Kurven verarbeitet. + +Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet, +alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch +mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne +zur Laufzeit. Falls kein Wiedergabeprogramm verfügbar ist, erscheint im +Admin-Fenster ein entsprechender Hinweis; der Monitor bleibt funktionstüchtig. +Wiedergabegerät und Lautstärke werden über die Systemeinstellungen verwaltet. + +**Wichtig:** Diese didaktischen Tonsignale entsprechen nicht den Anforderungen +an Medizinproduktealarme (insbesondere IEC 60601-1-8) und dürfen nicht zur +klinischen Überwachung verwendet werden. + ## Numerische Alarmgrenzen (seit v0.4.0; Anordnung und Voreinstellungen seit v0.4.1) Für jeden angezeigten numerischen Messwert können im zugehörigen Admin-Bereich **unabhängige optionale untere (↓) und obere (↑) Alarmgrenzen** festgelegt werden. diff --git a/patient-monitor-simulation/README.de.md.rej b/patient-monitor-simulation/README.de.md.rej index 4dbb0db..623dd0a 100644 --- a/patient-monitor-simulation/README.de.md.rej +++ b/patient-monitor-simulation/README.de.md.rej @@ -1,22 +1,8 @@ ---- README.de.md 2026-11-12 13:10:05.131166243 +0000 -+++ README.de.md 2026-11-12 13:28:21.812109359 +0000 +--- README.de.md ++++ README.de.md @@ -1,4 +1,4 @@ --# Patient Monitor Simulation (PaMSim) — v0.5.2 -+# Patient Monitor Simulation (PaMSim) — v0.5.3 +-# Patient Monitor Simulation (PaMSim) — v0.5.3 ++# Patient Monitor Simulation (PaMSim) — v0.5.4 Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux. -@@ -412,3 +445,13 @@ - die anderen Wertefelder vertikal zusammenzudrängen. Beim Ausblenden einzelner - Monitorbereiche werden beide Spalten gemeinsam neu aufgeteilt. - Das Messverhalten und die Alarmfunktionen bleiben unverändert. -+ -+## v0.5.3 — Akustische Alarmierung -+ -+- Alarmausgabe mit `pw-play` (PipeWire) bzw. `paplay` (Fallback), ohne neue -+ Rust-Bibliotheken. -+- Admin-Bedienelemente zum Stummschalten und für einen Testton. -+- Unterschiedliche Töne für kritische Rhythmusalarme und Standard- bzw. -+ technische Alarme; kritische Alarme haben Vorrang. -+- Die Audioausgabe ist von der Kurvendarstellung entkoppelt. -+- Bisherige optische Alarme und Simulationsfunktionen bleiben unverändert. diff --git a/patient-monitor-simulation/README.md b/patient-monitor-simulation/README.md index 20d5943..30ec481 100644 --- a/patient-monitor-simulation/README.md +++ b/patient-monitor-simulation/README.md @@ -1,4 +1,4 @@ -# Patient Monitor Simulation (PaMSim) — v0.5.3 +# Patient Monitor Simulation (PaMSim) — v0.5.4 A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. @@ -6,6 +6,47 @@ A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. > plethysmography and capnography are schematic mathematical approximations. The > simulation has no clinical validation and is not a medical device. +## Chest compressions (v0.5.4) + +The **Chest compressions** Admin group provides a large **Start Chest Compressions** +button (green background). While active it changes to **Stop Chest Compressions** +(red background). **Compression quality** can be changed at any time: +**Good**, **Adequate** (default), **Poor**, or **Bad**. + +- Compressions are generated independently of the ECG at **90–110/min**, with + a new reproducible pseudo-random compression rate and pressure each stroke. + **The ECG rhythm and electrical HR setting are not changed.** +- Every compression adds movement artifact to the ECG. In a patient with + **existing intrinsic arterial perfusion**, the native arterial waveform is + preserved but distorted by compression-synchronous pressure artifact. +- With **no intrinsic arterial pulse** (e.g., VF, PVT, asystole or PEA), + each effective compression generates a broad, blunt arterial pressure wave: + + | Compression quality | Compression-generated ART systolic peak | + | --- | --- | + | Good | 90 mmHg ±10% (81–99 mmHg) | + | Adequate (default) | 70 mmHg ±10% (63–77 mmHg) | + | Poor | 50 mmHg, +10% / −50% (25–55 mmHg) | + | Bad | No compression-generated arterial pressure; 0–5 mmHg baseline drift | + + During pulseless CPR, **ART SYS** shows the current compression peak, + while **DIA/MAP** remain `--` (not estimable from this synthetic pressure). +- SpO₂ numeric saturation and the pleth waveform remain visible **only when + compression quality is Good**, provided the sensor is connected and not + occluded by an NIBP cuff. Their effective signal quality is forced to + **Poor (★)**, irrespective of the normal Admin quality setting. The displayed + pleth-derived **PR follows the compression rate (90–110/min)**, not the ECG. + Adequate, Poor and Bad CPR display **NO READING**; detached sensors display + **NO SENSOR**. Compression-induced Poor quality does not schedule the usual + intermittent dropout; that resumes when ordinary Poor signal mode returns. +- Existing numerical alarms and rhythm alarms remain active. ART SYS limits + apply to compression-generated systolic peaks; NIBP scheduling remains unchanged; its cycle duration still depends on + effective SpO₂ quality at the start of a measurement. + +These pressure targets are **didactic assumptions**, not validated CPR +hemodynamic criteria. The exercise must not be used to judge real compression +quality or clinical perfusion. + ## Build and run on Fedora ```bash diff --git a/patient-monitor-simulation/src/alarm.rs b/patient-monitor-simulation/src/alarm.rs index d368f20..116b7f4 100644 --- a/patient-monitor-simulation/src/alarm.rs +++ b/patient-monitor-simulation/src/alarm.rs @@ -35,7 +35,6 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel { let captured = p.ecg_rhythm.can_generate_pulse() && p.heart_rate > 0 && p.pulse_conduction != PulseConduction::None; - let pr = if captured { sim.pulse_rate() } else { None }; if p.show_ecg { if p.ecg_rhythm.rhythm_alarm().is_some() { @@ -47,10 +46,10 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel { } if p.show_spo2 { - let status = p.spo2_status_at_quality(pr, sim.poor_signal_lost(), sim.spo2_quality(p)); + let status = sim.spo2_status(p); if status != Spo2Status::Available || outside(p.alarms.spo2, Some(p.spo2)) - || outside(p.alarms.pr, pr) + || outside(p.alarms.pr, sim.spo2_pulse_rate(p)) { result = AlarmLevel::Standard; } diff --git a/patient-monitor-simulation/src/model.rs b/patient-monitor-simulation/src/model.rs index 996d6ba..009b231 100644 --- a/patient-monitor-simulation/src/model.rs +++ b/patient-monitor-simulation/src/model.rs @@ -83,6 +83,29 @@ pub enum CapnoShape { 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)] @@ -202,6 +225,8 @@ 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 heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate pub pulse_conduction: PulseConduction, @@ -277,6 +302,8 @@ impl Default for Parameters { patient_name: String::new(), alarms: AlarmSettings::default(), audible_alarms: true, + chest_compressions_active: false, + chest_compression_quality: ChestCompressionQuality::Adequate, ecg_rhythm: EcgRhythm::Sinus, heart_rate: 75, pulse_conduction: PulseConduction::OneToOne, @@ -313,6 +340,17 @@ pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 { 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 mean_pressure_uses_one_third_pulse_pressure() { assert_eq!(mean_arterial_pressure(120, 75), 90); diff --git a/patient-monitor-simulation/src/render.rs b/patient-monitor-simulation/src/render.rs index 8cce43d..4053fe1 100644 --- a/patient-monitor-simulation/src/render.rs +++ b/patient-monitor-simulation/src/render.rs @@ -150,6 +150,7 @@ fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64, ], right, top, height * 0.65, width * 0.72); } +#[cfg(test)] fn pleth_trace_enabled(p: &Parameters) -> bool { p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None } @@ -160,9 +161,16 @@ fn spo2_vitals(p: &Parameters, pulse_rate: Option, signal_lost: bool) spo2_vitals_at_quality(p, pulse_rate, signal_lost, p.spo2_quality) } +#[cfg(test)] fn spo2_vitals_at_quality(p: &Parameters, pulse_rate: Option, signal_lost: bool, quality: Spo2Quality) -> (String, String, String) { - match p.spo2_status_at_quality(pulse_rate, signal_lost, quality) { + spo2_vitals_for_status(p, pulse_rate, quality, + p.spo2_status_at_quality(pulse_rate, signal_lost, quality)) +} + +fn spo2_vitals_for_status(p: &Parameters, pulse_rate: Option, quality: Spo2Quality, + status: Spo2Status) -> (String, String, String) { + match status { Spo2Status::NoSensor => ( "SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()), Spo2Status::NoReading => ( @@ -196,10 +204,11 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, && p.heart_rate > 0 && p.pulse_conduction != PulseConduction::None; let pulse_rate = if has_capture { sim.pulse_rate() } else { None }; + let spo2_rate = sim.spo2_pulse_rate(p); let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 { Some(p.heart_rate) } else { None }; - let spo2_status = p.spo2_status_at_quality(pulse_rate, sim.poor_signal_lost(), sim.spo2_quality(p)); + let spo2_status = sim.spo2_status(p); let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None }; let limits: Vec<(&str, AlarmLimits)> = match ch { @@ -228,8 +237,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, } } Channel::Pleth => { - let (label, value, info) = spo2_vitals_at_quality(p, pulse_rate, - sim.poor_signal_lost(), sim.spo2_quality(p)); + let (label, value, info) = spo2_vitals_for_status(p, spo2_rate, + sim.spo2_quality(p), spo2_status); text(cr, &label, x, top + row_h * 0.24, label_size, color, false); let technical_alarm = spo2_status != Spo2Status::Available; let value_size = if technical_alarm { @@ -239,8 +248,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, width, color, technical_alarm || alarmed(p.alarms.spo2, oxygen), flash); if oxygen.is_some() { draw_alarm_inline(cr, x, info_y, sub_size, width, color, - "% PR ", &pulse_rate.unwrap_or_default().to_string(), " bpm", - alarmed(p.alarms.pr, pulse_rate), flash); + "% PR ", &spo2_rate.unwrap_or_default().to_string(), " bpm", + alarmed(p.alarms.pr, spo2_rate), flash); } else { text(cr, &info, x, info_y, sub_size, color, false); } @@ -427,9 +436,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color, // Disconnected or absent pleth signal: no curve, including historical pulses. if matches!(channel, Channel::Pleth) - && (!pleth_trace_enabled(p) - || p.spo2_status_at_quality(sim.pulse_rate(), sim.poor_signal_lost(), - sim.spo2_quality(p)) != Spo2Status::Available) + && sim.spo2_status(p) != Spo2Status::Available { let _ = cr.restore(); return; diff --git a/patient-monitor-simulation/src/simulation.rs b/patient-monitor-simulation/src/simulation.rs index c148a30..06fd000 100644 --- a/patient-monitor-simulation/src/simulation.rs +++ b/patient-monitor-simulation/src/simulation.rs @@ -2,7 +2,8 @@ //! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse. use std::collections::VecDeque; -use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; +use crate::model::{ArterialShape, CapnoShape, ChestCompressionQuality, EcgRhythm, + Parameters, PulseConduction, Spo2Quality, Spo2Status}; use crate::nibp::{CuffZone, NibpMachine, NibpReading}; const SAMPLE_STEP: f64 = 0.004; // 250 Hz; adequately samples the QRS upstroke @@ -87,6 +88,91 @@ impl PoorSignalOutages { } } +/// CPR is a separate mechanical clock, independent of intrinsic cardiac rate. +/// Randomness is sampled once per compression, so peaks and intervals remain +/// stable during drawing and are reproducible in tests. +#[derive(Debug)] +struct ChestCompressions { + active: bool, + phase: f64, + rate_bpm: f64, + peak_pressure: f64, + quality: ChestCompressionQuality, + rng: u64, +} + +impl ChestCompressions { + fn new() -> Self { + Self { active: false, phase: 0.0, rate_bpm: 100.0, + peak_pressure: 0.0, quality: ChestCompressionQuality::Adequate, + rng: 0xC0FF_EE12_3456_789A } + } + + 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 choose_peak(&mut self) { + self.peak_pressure = match self.quality.peak_range() { + Some((low, high)) => low + (high - low) * self.random_unit(), + None => 0.0, + }; + } + + fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) { + if !enabled { + self.active = false; + self.phase = 0.0; + self.peak_pressure = 0.0; + return; + } + if !self.active { + self.active = true; + self.phase = 0.0; + self.rate_bpm = 90.0 + self.random_unit() * 20.0; + self.quality = quality; + self.choose_peak(); + } else if self.quality != quality { + self.quality = quality; + self.choose_peak(); + } + self.phase += SAMPLE_STEP * self.rate_bpm / 60.0; + if self.phase >= 1.0 { + self.phase = self.phase.fract(); + self.rate_bpm = 90.0 + self.random_unit() * 20.0; + self.choose_peak(); + } + } + + fn pressure_wave(&self) -> f64 { + // Rounded, broad compression crest (no narrow physiological upstroke). + let rise = smooth_step(self.phase / 0.22); + let fall = 1.0 - smooth_step((self.phase - 0.36) / 0.43); + (rise * fall).clamp(0.0, 1.0) + } + + fn pleth_wave(&self) -> f64 { + // A delayed, deliberately weak mechanical pleth pulse. + let phase = (self.phase - 0.26).rem_euclid(1.0); + smooth_step(phase / 0.27) * (1.0 - smooth_step((phase - 0.27) / 0.62)) + } + + fn ecg_artifact(&self, time: f64) -> f64 { + // Compression-synchronous baseline motion and jagged contact artifact. + let wave = self.pressure_wave(); + 0.56 * (wave - 0.30) + + 0.12 * (time * 71.0).sin() * wave + + 0.08 * (time * 113.0).sin() * wave + } +} + +fn smooth_step(value: f64) -> f64 { + let t = value.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + pub struct Simulator { samples: VecDeque, time: f64, @@ -100,6 +186,7 @@ pub struct Simulator { previous_conduction: PulseConduction, previous_heart_rate: i32, poor_signal_outages: PoorSignalOutages, + compressions: ChestCompressions, nibp: NibpMachine, art_hold_pressure: Option, pending_time: f64, @@ -120,6 +207,7 @@ impl Simulator { previous_conduction: params.pulse_conduction, previous_heart_rate: params.heart_rate, poor_signal_outages: PoorSignalOutages::new(), + compressions: ChestCompressions::new(), nibp: NibpMachine::new(), art_hold_pressure: None, pending_time: 0.0, @@ -149,7 +237,43 @@ impl Simulator { pub fn time(&self) -> f64 { self.time } pub fn spo2_quality(&self, p: &Parameters) -> Spo2Quality { - self.nibp.effective_spo2_quality(self.time, p) + if !p.chest_compressions_active { + return self.nibp.effective_spo2_quality(self.time, p); + } + if p.chest_compression_quality != ChestCompressionQuality::Good { + return Spo2Quality::None; + } + // During effective CPR the pleth signal is Poor regardless of Admin's + // baseline quality; an occlusive NIBP cuff can still suppress it. + if p.nibp_cuff_on_spo2 { + match self.nibp.cuff_zone(self.time, p) { + CuffZone::Occluded => return Spo2Quality::None, + CuffZone::Partial | CuffZone::Free => {} + } + } + Spo2Quality::Poor + } + + /// Display-only pulse rate: under effective CPR the peripheral signal + /// follows compressions rather than non-perfusing electrical QRS events. + pub fn spo2_pulse_rate(&self, p: &Parameters) -> Option { + if p.chest_compressions_active { + (p.chest_compression_quality == ChestCompressionQuality::Good) + .then_some(self.compressions.rate_bpm.round() as i32) + } else { + self.pulse_rate() + } + } + + pub fn spo2_status(&self, p: &Parameters) -> Spo2Status { + if !p.spo2_sensor_attached { return Spo2Status::NoSensor; } + if p.chest_compressions_active { + return if p.chest_compression_quality == ChestCompressionQuality::Good + && self.spo2_quality(p) != Spo2Quality::None + { Spo2Status::Available } else { Spo2Status::NoReading }; + } + p.spo2_status_at_quality(self.pulse_rate(), self.poor_signal_lost(), + self.spo2_quality(p)) } pub fn start_nibp_now(&mut self, p: &Parameters) { @@ -161,7 +285,7 @@ impl Simulator { if !p.spo2_sensor_attached || self.poor_signal_outages.active { Spo2Quality::None } else { - p.spo2_quality + self.spo2_quality(p) } } @@ -169,6 +293,11 @@ impl Simulator { pub fn displayed_art_pressures(&self, p: &Parameters, has_capture: bool) -> (Option, Option, Option) { if !has_capture { + // During pulseless CPR the upper ART number reflects the peak + // compression pressure; DIA/MAP remain intentionally unassessed. + if self.compressions.active && p.chest_compression_quality != ChestCompressionQuality::Bad { + return (Some(self.compressions.peak_pressure.round() as i32), None, None); + } return (self.measured_art_pressure(), None, None); } if p.nibp_cuff_on_art { @@ -219,8 +348,11 @@ impl Simulator { fn step(&mut self, params: &Parameters) { self.time += SAMPLE_STEP; + self.compressions.update(params.chest_compressions_active, + params.chest_compression_quality); self.poor_signal_outages.update(self.time, - params.spo2_quality == Spo2Quality::Poor && params.spo2_sensor_attached); + !params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor + && params.spo2_sensor_attached); // Snapshot the unoccluded sensor quality at the start of a cuff cycle. // Cuff-induced signal loss during that cycle must not change its duration. let start_quality = self.nibp_start_quality(params); @@ -289,8 +421,25 @@ impl Simulator { self.rate_qrs.pop_front(); } - let ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate); - let (normal_art, pleth_target) = self.mechanical_signals(params); + let mut ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate); + let (mut normal_art, mut pleth_target) = self.mechanical_signals(params); + if self.compressions.active { + ecg += self.compressions.ecg_artifact(self.time); + let perfusing = params.ecg_rhythm.can_generate_pulse() + && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0; + let wave = self.compressions.pressure_wave(); + if perfusing { + // Preserve the patient's intrinsic pressure, with superimposed + // compression-synchronous artifact even during bad CPR. + normal_art = (normal_art + 22.0 * (wave - 0.32)).clamp(0.0, 250.0); + } else if self.compressions.peak_pressure > 0.0 { + let baseline = pulseless_arterial_drift(self.time); + normal_art = baseline + (self.compressions.peak_pressure - baseline) * wave; + } + pleth_target = if params.chest_compression_quality == ChestCompressionQuality::Good { + 0.85 * self.compressions.pleth_wave() + } else { 0.0 }; + } let art = self.art_with_cuff(normal_art, params); let smoothing = 1.0 - (-SAMPLE_STEP / PLETH_FILTER_TAU).exp(); self.filtered_pleth += smoothing * (pleth_target - self.filtered_pleth); @@ -301,9 +450,7 @@ impl Simulator { }; let pleth_quality = self.spo2_quality(params); - let pleth_valid = params.spo2_sensor_attached - && pleth_quality != Spo2Quality::None - && !self.poor_signal_outages.active; + let pleth_valid = self.spo2_status(params) == Spo2Status::Available; self.samples.push_back(Sample { time: self.time, ecg, pleth, pleth_valid, pleth_quality, art, co2, }); @@ -313,9 +460,10 @@ impl Simulator { } fn art_with_cuff(&mut self, normal_art: f64, params: &Parameters) -> f64 { - if !params.nibp_cuff_on_art || !params.ecg_rhythm.can_generate_pulse() - || params.pulse_conduction == PulseConduction::None || params.heart_rate <= 0 - { + let native_pulse = params.ecg_rhythm.can_generate_pulse() + && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0; + let compression_pulse = self.compressions.active && self.compressions.peak_pressure > 0.0; + if !params.nibp_cuff_on_art || !(native_pulse || compression_pulse) { self.art_hold_pressure = None; return normal_art; } @@ -545,6 +693,129 @@ mod tests { sim } + #[test] + fn compression_rate_varies_only_between_90_and_110_bpm() { + let mut cpr = ChestCompressions::new(); + let mut observed = Vec::new(); + for _ in 0..(25.0 / SAMPLE_STEP) as usize { + let previous = cpr.phase; + cpr.update(true, ChestCompressionQuality::Good); + assert!((90.0..=110.0).contains(&cpr.rate_bpm)); + if cpr.phase < previous { observed.push(cpr.rate_bpm); } + } + assert!(observed.len() >= 30); + assert!(observed.iter().any(|rate| (rate - observed[0]).abs() > 1.0)); + cpr.update(false, ChestCompressionQuality::Good); + assert!(!cpr.active); + assert_eq!(cpr.peak_pressure, 0.0); + } + + #[test] + fn compressions_generate_requested_pulseless_arterial_pressure_by_quality() { + for (quality, limits) in [ + (ChestCompressionQuality::Good, Some((81.0, 99.0))), + (ChestCompressionQuality::Adequate, Some((63.0, 77.0))), + (ChestCompressionQuality::Poor, Some((25.0, 55.0))), + (ChestCompressionQuality::Bad, None), + ] { + let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation, + chest_compressions_active: true, chest_compression_quality: quality, + ..Parameters::default() }; + let mut sim = Simulator::new(&p); + for _ in 0..(2.0 / SAMPLE_STEP) as usize { sim.step(&p); } + assert_eq!(sim.pulse_rate(), None, "no intrinsic QRS pulse in VF"); + let recent: Vec<_> = sim.samples.iter().rev().take(500).collect(); + let peak = recent.iter().map(|s| s.art).fold(f64::NEG_INFINITY, f64::max); + let (sys, dia, map) = sim.displayed_art_pressures(&p, false); + assert_eq!((dia, map), (None, None)); + if let Some((low, high)) = limits { + assert!(peak >= low - 1.0 && peak <= high + 1.0, + "{quality:?}: waveform peak {peak}"); + assert!(sys.is_some_and(|v| (low - 1.0..=high + 1.0).contains(&f64::from(v)))); + } else { + assert!(peak <= 5.0, "bad CPR must not create a pulse"); + assert!(sys.is_some_and(|v| (0..=5).contains(&v))); + } + } + } + + #[test] + fn good_cpr_can_create_poor_pleth_in_vf_despite_admin_no_quality() { + let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation, + spo2_quality: Spo2Quality::None, + chest_compressions_active: true, + chest_compression_quality: ChestCompressionQuality::Good, + ..Parameters::default() }; + let mut sim = Simulator::new(&p); + for _ in 0..400 { sim.step(&p); } + assert_eq!(sim.spo2_quality(&p), Spo2Quality::Poor); + assert_eq!(sim.spo2_status(&p), Spo2Status::Available); + assert!(sim.spo2_pulse_rate(&p).is_some_and(|v| (90..=110).contains(&v))); + assert!(sim.samples.iter().rev().take(400).any(|s| s.pleth > 0.05 && s.pleth_valid)); + assert!(sim.samples.iter().rev().take(400).all(|s| s.pleth_quality == Spo2Quality::Poor)); + } + + #[test] + fn only_good_cpr_shows_pleth_and_sensor_disconnect_takes_precedence() { + for quality in [ChestCompressionQuality::Adequate, + ChestCompressionQuality::Poor, ChestCompressionQuality::Bad] { + let p = Parameters { chest_compressions_active: true, + chest_compression_quality: quality, ..Parameters::default() }; + let mut sim = Simulator::new(&p); + sim.step(&p); + assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading); + assert_eq!(sim.spo2_pulse_rate(&p), None); + assert!(!sim.samples.back().unwrap().pleth_valid); + } + let mut p = Parameters { chest_compressions_active: true, + chest_compression_quality: ChestCompressionQuality::Good, ..Parameters::default() }; + let mut sim = Simulator::new(&p); + p.spo2_sensor_attached = false; + sim.step(&p); + assert_eq!(sim.spo2_status(&p), Spo2Status::NoSensor); + assert!(!sim.samples.back().unwrap().pleth_valid); + } + + #[test] + fn compressions_distort_ecg_and_preserve_intrinsic_pulses_in_sinus() { + let normal = Parameters::default(); + let with_cpr = Parameters { chest_compressions_active: true, + chest_compression_quality: ChestCompressionQuality::Adequate, + ..Parameters::default() }; + let mut base = Simulator::new(&normal); + let mut cpr = Simulator::new(&with_cpr); + let mut ecg_distortion = false; + let mut art_distortion = false; + for _ in 0..500 { + base.step(&normal); + cpr.step(&with_cpr); + let native = base.samples.back().unwrap(); + let compressed = cpr.samples.back().unwrap(); + ecg_distortion |= (compressed.ecg - native.ecg).abs() > 0.1; + art_distortion |= (compressed.art - native.art).abs() > 5.0; + } + assert!(ecg_distortion); + assert!(art_distortion); + assert!(cpr.samples.iter().rev().take(500).any(|s| s.art > 60.0)); + assert_eq!(cpr.pulse_rate(), Some(75), "CPR must not change underlying HR/PR capture"); + } + + #[test] + fn stopping_compressions_restores_pulseless_drift_and_normal_pleth_rules() { + let mut p = Parameters { ecg_rhythm: EcgRhythm::Asystole, + chest_compressions_active: true, + chest_compression_quality: ChestCompressionQuality::Good, + ..Parameters::default() }; + let mut sim = Simulator::new(&p); + assert_eq!(sim.spo2_status(&p), Spo2Status::Available); + p.chest_compressions_active = false; + sim.step(&p); + assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art)); + assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading); + assert!(!sim.samples.back().unwrap().pleth_valid); + assert_eq!(sim.spo2_pulse_rate(&p), None); + } + #[test] fn signals_remain_in_expected_ranges() { let p = Parameters::default(); diff --git a/patient-monitor-simulation/src/ui.rs b/patient-monitor-simulation/src/ui.rs index 7e6fd0a..ffb8579 100644 --- a/patient-monitor-simulation/src/ui.rs +++ b/patient-monitor-simulation/src/ui.rs @@ -9,7 +9,8 @@ use gtk::prelude::*; use gtk::{Application, ApplicationWindow, Orientation}; use crate::alarm::{self, AlarmAudio}; -use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; +use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, + ChestCompressionQuality, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; use crate::render; use crate::simulation::Simulator; @@ -186,6 +187,60 @@ fn create_admin(app: &Application, params: SharedParams, patient_row.append(&name_entry); patient.append(&patient_row); + // Resuscitation controls are deliberately near the top of the Admin panel. + // CSS sets the *button background*, not just its text color. + if let Some(display) = gdk::Display::default() { + let provider = gtk::CssProvider::new(); + provider.load_from_data( + "button.cpr-start { background-image: none; background-color: #158742; color: #ffffff; font-weight: bold; } + button.cpr-stop { background-image: none; background-color: #c53035; color: #ffffff; font-weight: bold; }" + ); + gtk::style_context_add_provider_for_display( + &display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION); + } + let cpr = group(&controls, "Chest compressions", None); + let compression_button = gtk::Button::with_label("Start Chest Compressions"); + compression_button.set_hexpand(true); + compression_button.add_css_class("cpr-start"); + compression_button.connect_clicked({ + let params = params.clone(); + move |button| { + let mut p = params.borrow_mut(); + p.chest_compressions_active = !p.chest_compressions_active; + if p.chest_compressions_active { + button.set_label("Stop Chest Compressions"); + button.remove_css_class("cpr-start"); + button.add_css_class("cpr-stop"); + } else { + button.set_label("Start Chest Compressions"); + button.remove_css_class("cpr-stop"); + button.add_css_class("cpr-start"); + } + } + }); + cpr.append(&compression_button); + let _quality = add_dropdown_at(&cpr, "Compression quality", + &["Good", "Adequate", "Poor", "Bad"], 1, params.clone(), |p, selected| { + p.chest_compression_quality = match selected { + 0 => ChestCompressionQuality::Good, + 2 => ChestCompressionQuality::Poor, + 3 => ChestCompressionQuality::Bad, + _ => ChestCompressionQuality::Adequate, + }; + }); + let cpr_hint = gtk::Label::new(Some( + "CPR: 90–110 compressions/min. ECG is distorted; ART receives compression waves. " + )); + cpr_hint.set_xalign(0.0); + cpr_hint.set_wrap(true); + cpr.append(&cpr_hint); + let cpr_hint2 = gtk::Label::new(Some( + "Only Good compressions generate a Poor-quality SpO₂/pleth signal (if the sensor is attached)." + )); + cpr_hint2.set_xalign(0.0); + cpr_hint2.set_wrap(true); + cpr.append(&cpr_hint2); + let ecg = group(&controls, "ECG", Some(ECG_GREEN)); add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show); let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[