v0.4.2: add PVT

This commit is contained in:
GABRIEL Sebastian 2026-11-12 12:08:46 +01:00
commit 5e397019fc
8 changed files with 727 additions and 51 deletions

View file

@ -0,0 +1,509 @@
diff --git a/Cargo.toml b/Cargo.toml
index 4c97d45..02a5d17 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.4.1"
+version = "0.4.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index 4c5b8f0..c693e16 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.4.1
+# Patient Monitor Simulation (PaMSim) — v0.4.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -130,7 +130,7 @@ Admin → **Pulse oximetry** has two additional controls:
| Setting | Pleth waveform | Monitor display |
| --- | --- | --- |
-| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; no stars |
+| **0 — None** | No waveform | Flashing **NO READING**, PR `--`; no stars |
| **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) |
| **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) |
| **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) |
@@ -143,7 +143,7 @@ remains derived from mechanically captured QRS complexes.
The degraded waveform uses deterministic, smoothly interpolated pseudo-noise
that scales only existing pleth pulses: it cannot manufacture pulses during
-PEA, ventricular fibrillation or asystole. Unplugging a sensor or selecting
+PEA, PVT, ventricular fibrillation or asystole. Unplugging a sensor or selecting
quality 0 hides even previously buffered pleth samples immediately. ECG and
ART continue unaffected. The **Show on monitor** checkbox still hides the
entire SpO₂ row; sensor/quality controls leave the row visible so the status
@@ -151,15 +151,18 @@ can be taught.
## ECG and mechanical coupling
-- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia,
+- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia
+ (potentially perfusing), pulseless ventricular tachycardia (PVT),
ventricular fibrillation and asystole.
- Mechanical capture: **1:1**, **2:1**, **3:1**, **None (PEA)**, or deterministic
pseudo-random capture (~65%). PR is derived from conducted QRS events, never
controlled by a pulse-rate slider.
- A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a
peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered.
-- VF, asystole and PEA suppress mechanical pulses; old samples scroll out of
- view. NIBP is a static, separately entered cuff reading.
+- PVT, VF, asystole and PEA suppress mechanical pulses; the ART trace then
+ drifts smoothly at 0–5 mmHg rather than representing a pulsatile pressure.
+ Previous pressure samples scroll out of view. NIBP is a static,
+ separately entered cuff reading.
## Invasive arterial pressure and PPV (new in v0.3)
@@ -205,7 +208,7 @@ The five **Show on monitor** checkboxes affect the presentation only:
| Checkbox | Hidden monitor content |
| --- | --- |
-| ECG | ECG waveform, HR and rhythm label |
+| ECG | ECG waveform, HR and rhythm alarm (when present) |
| Pulse oximetry | Pleth waveform, SpO₂ and PR |
| Invasive arterial blood pressure | ART waveform, pressure values, MAP and PPV label |
| Capnography | CO₂ waveform, EtCO₂ and RR |
@@ -287,3 +290,13 @@ were not available in the environment where this ZIP was prepared.
**Build verification:** ZIP integrity and patch application were checked.
The GTK4 application and Rust tests were not compiled in the packaging
environment; run `cargo test` and `cargo run --release` on Fedora.
+
+
+## v0.4.2 — Rhythm, sensor and missing-reading alarms
+
+- **VT** remains potentially perfusing. The new **PVT** (pulseless ventricular tachycardia) rhythm retains organized broad QRS complexes but produces no arterial/pleth pulses. VF and asystole are also pulseless regardless of capture selection.
+- **ECG**: a flashing **ARRHYTHMIA** message for VT, PVT and VF; a flashing **ASYSTOLE** message for asystole. These event alarms do not depend on numerical HR limits.
+- **SpO₂**: when the probe is disconnected, a flashing **NO SENSOR** replaces the saturation reading. Quality 0, loss of mechanical capture or a pulseless rhythm results in flashing **NO READING** (no numerical SpO₂/PR). Sensor disconnection takes precedence. No pleth waveform is displayed in these conditions.
+- **ART**: without mechanical pulses (including PVT/VF/asystole/PEA), the simulated invasive pressure line has slow non-pulsatile drift between **0 and 5 mmHg**. The numerical blood-pressure reading remains unavailable (`--/--`), rather than misrepresenting this baseline as true systolic and diastolic pressures.
+- **ECG rhythm name** has been removed from the monitor; only HR and the associated alarm message, when present, are visible. The instructor continues to select the rhythm in Admin.
+- Numerical alarm thresholds and the Adult preset from v0.4.1 are unchanged. Synthetic demonstration behavior only; not suitable for clinical decisions.
diff --git a/src/model.rs b/src/model.rs
index 2ce532c..6b1f6d1 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -5,15 +5,40 @@ pub enum EcgRhythm {
Sinus,
AtrialFibrillation,
VentricularTachycardia,
+ PulselessVentricularTachycardia,
VentricularFibrillation,
Asystole,
}
impl EcgRhythm {
- /// VF and asystole have no organized QRS to trigger a mechanical pulse.
+ /// 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,
+ }
+ }
+}
+
+/// 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)]
@@ -195,6 +220,24 @@ pub struct Parameters {
pub show_nibp: bool,
}
+impl Parameters {
+ /// No saturation without an attached sensor, usable signal quality and
+ /// two observed mechanical pulse events. Thresholds do not control this alarm.
+ pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
+ if !self.spo2_sensor_attached {
+ Spo2Status::NoSensor
+ } else if self.spo2_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
+ }
+ }
+}
+
impl Default for Parameters {
fn default() -> Self {
Self {
@@ -308,6 +351,41 @@ mod tests {
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 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<_>>(),
diff --git a/src/render.rs b/src/render.rs
index 8391fe8..c0f8474 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -1,7 +1,7 @@
//! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
-use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Quality, Spo2Status};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@@ -106,17 +106,17 @@ fn pleth_trace_enabled(p: &Parameters) -> bool {
}
fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) {
- if !p.spo2_sensor_attached {
- return ("SpO₂".to_owned(), "NO SENSOR".to_owned(), "SpO₂ -- PR -- bpm".to_owned());
+ match p.spo2_status(pulse_rate) {
+ Spo2Status::NoSensor => (
+ "SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()),
+ Spo2Status::NoReading => (
+ "SpO₂".to_owned(), "NO READING".to_owned(), "PR -- bpm".to_owned()),
+ Spo2Status::Available => (
+ format!("SpO₂ {}", p.spo2_quality.stars()),
+ p.spo2.to_string(),
+ format!("% PR {} bpm", pulse_rate.unwrap_or_default()),
+ ),
}
- if p.spo2_quality == Spo2Quality::None {
- return ("SpO₂".to_owned(), "--".to_owned(), "NO SIGNAL PR -- bpm".to_owned());
- }
- (
- format!("SpO₂ {}", p.spo2_quality.stars()),
- if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
- format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
- )
}
fn alarmed(limits: AlarmLimits, value: Option<i32>) -> bool {
@@ -136,16 +136,15 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0);
let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85;
let flash = alarm_flash_on(sim);
- let has_capture = p.ecg_rhythm.has_qrs()
+ let has_capture = p.ecg_rhythm.can_generate_pulse()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Some(p.heart_rate)
} else { None };
- let oxygen = if pleth_trace_enabled(p) && pulse_rate.is_some() {
- Some(p.spo2)
- } else { None };
+ let spo2_status = p.spo2_status(pulse_rate);
+ let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
let limits: Vec<(&str, AlarmLimits)> = match ch {
@@ -165,23 +164,23 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
draw_alarm_number(cr, &ecg_hr.map_or("--".to_owned(), |v| v.to_string()),
x, value_y, number_size, width, color,
alarmed(p.alarms.hr, ecg_hr), flash);
- let rhythm = match p.ecg_rhythm {
- EcgRhythm::Sinus => "Sinus",
- EcgRhythm::AtrialFibrillation => "AF",
- EcgRhythm::VentricularTachycardia => "VT",
- EcgRhythm::VentricularFibrillation => "VF",
- EcgRhythm::Asystole => "Asystole",
- };
- text(cr, &format!("bpm · {}", rhythm), x, info_y, sub_size, color, false);
+ // Show only the clinical alarm message, never the selected ECG rhythm.
+ if let Some(message) = p.ecg_rhythm.rhythm_alarm() {
+ draw_alarm_number(cr, message, x, info_y, sub_size * 1.1,
+ width, color, true, flash);
+ } else {
+ text(cr, "bpm", x, info_y, sub_size, color, false);
+ }
}
Channel::Pleth => {
let (label, value, info) = spo2_vitals(p, pulse_rate);
text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
- let value_size = if value == "NO SENSOR" {
- number_size.min(0.19 * width).min(26.0)
+ let technical_alarm = spo2_status != Spo2Status::Available;
+ let value_size = if technical_alarm {
+ number_size.min(0.17 * width).min(26.0)
} else { number_size };
draw_alarm_number(cr, &value, x, value_y, value_size,
- width, color, alarmed(p.alarms.spo2, oxygen), flash);
+ 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",
@@ -377,7 +376,9 @@ 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)
+ if matches!(channel, Channel::Pleth)
+ && (!pleth_trace_enabled(p)
+ || p.spo2_status(sim.pulse_rate()) != Spo2Status::Available)
{
let _ = cr.restore();
return;
@@ -544,8 +545,7 @@ mod tests {
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::None;
assert!(!pleth_trace_enabled(&p));
- assert_eq!(spo2_vitals(&p, Some(75)).1, "--");
- assert!(spo2_vitals(&p, Some(75)).2.contains("NO SIGNAL"));
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "NO READING");
assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
assert!(p.show_spo2); // no readings, but visible row and status
}
@@ -559,10 +559,20 @@ mod tests {
assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm"));
p.spo2_quality = Spo2Quality::Good;
assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★");
- assert_eq!(spo2_vitals(&p, None).1, "--");
+ assert_eq!(spo2_vitals(&p, None).1, "NO READING");
assert!(spo2_vitals(&p, None).2.contains("PR --"));
}
+ #[test]
+ fn no_sensor_precedes_no_reading_and_both_are_spo2_alarms() {
+ let mut p = Parameters::default();
+ assert_eq!(spo2_vitals(&p, None).1, "NO READING");
+ p.ecg_rhythm = crate::model::EcgRhythm::PulselessVentricularTachycardia;
+ assert_eq!(spo2_vitals(&p, Some(100)).1, "NO READING");
+ p.spo2_sensor_attached = false;
+ assert_eq!(spo2_vitals(&p, Some(100)).1, "NO SENSOR");
+ }
+
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
diff --git a/src/simulation.rs b/src/simulation.rs
index f3d7b01..a9f5c7b 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -109,7 +109,7 @@ impl Simulator {
if params.ecg_rhythm != self.previous_rhythm
|| params.pulse_conduction != self.previous_conduction
- || !params.ecg_rhythm.has_qrs()
+ || !params.ecg_rhythm.can_generate_pulse()
|| params.pulse_conduction == PulseConduction::None
|| params.heart_rate <= 0
{
@@ -146,7 +146,8 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
- if params.pulse_conduction.conducts(self.ecg_beat_number) {
+ if params.ecg_rhythm.can_generate_pulse()
+ && params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase)
} else {
@@ -208,7 +209,14 @@ impl Simulator {
}
}
- let art = if let Some(age) = latest_art_age {
+ let art = if !params.ecg_rhythm.can_generate_pulse()
+ || params.pulse_conduction == PulseConduction::None
+ || params.heart_rate <= 0
+ {
+ // Low-frequency baseline drift around zero, without pulsations.
+ // The smooth, deterministic noise stays within 0..5 mmHg.
+ pulseless_arterial_drift(self.time)
+ } else if let Some(age) = latest_art_age {
// Pressure decays after an unperfused interval instead of showing a
// non-existent 75 mmHg baseline during prolonged missed captures.
let baseline = diastolic * (-(age - 0.60).max(0.0) / 1.40).exp();
@@ -220,6 +228,28 @@ impl Simulator {
}
}
+/// Deterministic smooth value noise with a slow, non-cardiac frequency.
+fn smooth_random_unit(time: f64, seconds_per_step: f64, seed: i64) -> f64 {
+ fn hash(index: i64) -> f64 {
+ let mut x = (index as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
+ x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ x ^= x >> 31;
+ (x as f64) / (u64::MAX as f64)
+ }
+ let position = time / seconds_per_step;
+ let index = position.floor() as i64;
+ let delta = position - index as f64;
+ let fade = delta * delta * (3.0 - 2.0 * delta);
+ hash(index.wrapping_add(seed)) * (1.0 - fade)
+ + hash(index.wrapping_add(seed).wrapping_add(1)) * fade
+}
+
+fn pulseless_arterial_drift(time: f64) -> f64 {
+ (0.4 + 3.6 * smooth_random_unit(time, 2.4, 12)
+ + 0.65 * smooth_random_unit(time, 0.95, 41)).clamp(0.0, 5.0)
+}
+
fn gaussian(x: f64, center: f64, width: f64) -> f64 {
let d = (x - center) / width;
(-0.5 * d * d).exp()
@@ -281,7 +311,7 @@ fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f
- 0.32 * lobe(0.028, 0.012)
+ 0.28 * lobe(t_after_qrs, t_width)
}
- EcgRhythm::VentricularTachycardia => {
+ EcgRhythm::VentricularTachycardia | EcgRhythm::PulselessVentricularTachycardia => {
// Broad monomorphic ventricular complexes, also in milliseconds.
1.06 * lobe(0.0, 0.045)
- 0.49 * lobe(0.068, 0.030)
@@ -389,13 +419,14 @@ mod tests {
for (rhythm, capture) in [
(EcgRhythm::Asystole, PulseConduction::OneToOne),
(EcgRhythm::VentricularFibrillation, PulseConduction::OneToOne),
+ (EcgRhythm::PulselessVentricularTachycardia, PulseConduction::OneToOne),
(EcgRhythm::Sinus, PulseConduction::None),
] {
let p = Parameters { ecg_rhythm: rhythm, pulse_conduction: capture, ..Parameters::default() };
let mut sim = Simulator::new(&p);
for _ in 0..250 { sim.step(&p); }
assert!(sim.pulse_rate().is_none());
- assert!(sim.samples.iter().all(|s| s.art == 0.0 && s.pleth == 0.0));
+ assert!(sim.samples.iter().all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
}
}
@@ -407,10 +438,44 @@ mod tests {
p.pulse_conduction = PulseConduction::None;
sim.step(&p);
assert!(sim.pulse_rate().is_none());
- assert_eq!(sim.samples.back().unwrap().art, 0.0);
+ assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art));
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
}
+ #[test]
+ fn vt_remains_perfusing_and_pvt_has_qrs_but_no_pulse() {
+ let mut p = Parameters {
+ ecg_rhythm: EcgRhythm::VentricularTachycardia,
+ heart_rate: 160,
+ ..Parameters::default()
+ };
+ let mut sim = Simulator::new(&p);
+ assert_eq!(sim.pulse_rate(), Some(160));
+ assert!(sim.samples().iter().any(|s| s.art > 70.0 && s.pleth > 0.0));
+ p.ecg_rhythm = EcgRhythm::PulselessVentricularTachycardia;
+ sim.step(&p);
+ assert_eq!(sim.pulse_rate(), None);
+ assert!((0.0..=5.0).contains(&sim.samples().back().unwrap().art));
+ assert_eq!(sim.samples().back().unwrap().pleth, 0.0);
+ for _ in 0..500 { sim.step(&p); }
+ assert!(sim.samples().iter().rev().take(500)
+ .all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
+ assert!(sim.samples().iter().rev().take(500)
+ .any(|s| s.ecg.abs() > 0.3));
+ }
+
+ #[test]
+ fn low_pressure_drift_is_smooth_and_never_pulsatile() {
+ let values: Vec<f64> = (0..5000)
+ .map(|n| pulseless_arterial_drift(n as f64 * SAMPLE_STEP))
+ .collect();
+ assert!(values.iter().all(|v| (0.0..=5.0).contains(v)));
+ assert!(values.windows(2).all(|w| (w[1] - w[0]).abs() < 0.10));
+ let spread = values.iter().copied().fold(f64::NEG_INFINITY, f64::max)
+ - values.iter().copied().fold(f64::INFINITY, f64::min);
+ assert!(spread > 0.25);
+ }
+
#[test]
fn pulse_rate_follows_two_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };
diff --git a/src/ui.rs b/src/ui.rs
index a36fec3..669c227 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -146,14 +146,15 @@ fn create_admin(app: &Application, params: SharedParams,
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
add_dropdown(&ecg, "ECG rhythm", &[
- "Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia",
- "Ventricular fibrillation", "Asystole",
+ "Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
+ "Pulseless ventricular tachycardia (PVT)", "Ventricular fibrillation", "Asystole",
], params.clone(), |p, selected| {
p.ecg_rhythm = match selected {
1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia,
- 3 => EcgRhythm::VentricularFibrillation,
- 4 => EcgRhythm::Asystole,
+ 3 => EcgRhythm::PulselessVentricularTachycardia,
+ 4 => EcgRhythm::VentricularFibrillation,
+ 5 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus,
};
});
@@ -210,7 +211,7 @@ fn create_admin(app: &Application, params: SharedParams,
});
let conduction_hint = gtk::Label::new(Some(
"Pulse rate is derived from captured QRS events.
-ART and pleth are delayed; VF and asystole always have no pulse."
+ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulseless."
));
conduction_hint.set_xalign(0.0);
conduction_hint.set_wrap(true);

View file

@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.4.1" version = "0.4.2"
dependencies = [ dependencies = [
"gtk4", "gtk4",
] ]

View file

@ -1,6 +1,6 @@
[package] [package]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.4.1" version = "0.4.2"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"

View file

@ -1,4 +1,4 @@
# Patient Monitor Simulation (PaMSim) — v0.4.1 # Patient Monitor Simulation (PaMSim) — v0.4.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@ -130,7 +130,7 @@ Admin → **Pulse oximetry** has two additional controls:
| Setting | Pleth waveform | Monitor display | | Setting | Pleth waveform | Monitor display |
| --- | --- | --- | | --- | --- | --- |
| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; no stars | | **0 — None** | No waveform | Flashing **NO READING**, PR `--`; no stars |
| **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) | | **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) |
| **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) | | **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) |
| **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) | | **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) |
@ -143,7 +143,7 @@ remains derived from mechanically captured QRS complexes.
The degraded waveform uses deterministic, smoothly interpolated pseudo-noise The degraded waveform uses deterministic, smoothly interpolated pseudo-noise
that scales only existing pleth pulses: it cannot manufacture pulses during that scales only existing pleth pulses: it cannot manufacture pulses during
PEA, ventricular fibrillation or asystole. Unplugging a sensor or selecting PEA, PVT, ventricular fibrillation or asystole. Unplugging a sensor or selecting
quality 0 hides even previously buffered pleth samples immediately. ECG and quality 0 hides even previously buffered pleth samples immediately. ECG and
ART continue unaffected. The **Show on monitor** checkbox still hides the ART continue unaffected. The **Show on monitor** checkbox still hides the
entire SpO₂ row; sensor/quality controls leave the row visible so the status entire SpO₂ row; sensor/quality controls leave the row visible so the status
@ -151,15 +151,18 @@ can be taught.
## ECG and mechanical coupling ## ECG and mechanical coupling
- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia, - ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia
(potentially perfusing), pulseless ventricular tachycardia (PVT),
ventricular fibrillation and asystole. ventricular fibrillation and asystole.
- Mechanical capture: **1:1**, **2:1**, **3:1**, **None (PEA)**, or deterministic - Mechanical capture: **1:1**, **2:1**, **3:1**, **None (PEA)**, or deterministic
pseudo-random capture (~65%). PR is derived from conducted QRS events, never pseudo-random capture (~65%). PR is derived from conducted QRS events, never
controlled by a pulse-rate slider. controlled by a pulse-rate slider.
- A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a - A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a
peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered. peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered.
- VF, asystole and PEA suppress mechanical pulses; old samples scroll out of - PVT, VF, asystole and PEA suppress mechanical pulses; the ART trace then
view. NIBP is a static, separately entered cuff reading. drifts smoothly at 0–5 mmHg rather than representing a pulsatile pressure.
Previous pressure samples scroll out of view. NIBP is a static,
separately entered cuff reading.
## Invasive arterial pressure and PPV (new in v0.3) ## Invasive arterial pressure and PPV (new in v0.3)
@ -205,7 +208,7 @@ The five **Show on monitor** checkboxes affect the presentation only:
| Checkbox | Hidden monitor content | | Checkbox | Hidden monitor content |
| --- | --- | | --- | --- |
| ECG | ECG waveform, HR and rhythm label | | ECG | ECG waveform, HR and rhythm alarm (when present) |
| Pulse oximetry | Pleth waveform, SpO₂ and PR | | Pulse oximetry | Pleth waveform, SpO₂ and PR |
| Invasive arterial blood pressure | ART waveform, pressure values, MAP and PPV label | | Invasive arterial blood pressure | ART waveform, pressure values, MAP and PPV label |
| Capnography | CO₂ waveform, EtCO₂ and RR | | Capnography | CO₂ waveform, EtCO₂ and RR |
@ -287,3 +290,13 @@ were not available in the environment where this ZIP was prepared.
**Build verification:** ZIP integrity and patch application were checked. **Build verification:** ZIP integrity and patch application were checked.
The GTK4 application and Rust tests were not compiled in the packaging The GTK4 application and Rust tests were not compiled in the packaging
environment; run `cargo test` and `cargo run --release` on Fedora. environment; run `cargo test` and `cargo run --release` on Fedora.
## v0.4.2 — Rhythm, sensor and missing-reading alarms
- **VT** remains potentially perfusing. The new **PVT** (pulseless ventricular tachycardia) rhythm retains organized broad QRS complexes but produces no arterial/pleth pulses. VF and asystole are also pulseless regardless of capture selection.
- **ECG**: a flashing **ARRHYTHMIA** message for VT, PVT and VF; a flashing **ASYSTOLE** message for asystole. These event alarms do not depend on numerical HR limits.
- **SpO₂**: when the probe is disconnected, a flashing **NO SENSOR** replaces the saturation reading. Quality 0, loss of mechanical capture or a pulseless rhythm results in flashing **NO READING** (no numerical SpO₂/PR). Sensor disconnection takes precedence. No pleth waveform is displayed in these conditions.
- **ART**: without mechanical pulses (including PVT/VF/asystole/PEA), the simulated invasive pressure line has slow non-pulsatile drift between **0 and 5 mmHg**. The numerical blood-pressure reading remains unavailable (`--/--`), rather than misrepresenting this baseline as true systolic and diastolic pressures.
- **ECG rhythm name** has been removed from the monitor; only HR and the associated alarm message, when present, are visible. The instructor continues to select the rhythm in Admin.
- Numerical alarm thresholds and the Adult preset from v0.4.1 are unchanged. Synthetic demonstration behavior only; not suitable for clinical decisions.

View file

@ -5,15 +5,40 @@ pub enum EcgRhythm {
Sinus, Sinus,
AtrialFibrillation, AtrialFibrillation,
VentricularTachycardia, VentricularTachycardia,
PulselessVentricularTachycardia,
VentricularFibrillation, VentricularFibrillation,
Asystole, Asystole,
} }
impl EcgRhythm { impl EcgRhythm {
/// VF and asystole have no organized QRS to trigger a mechanical pulse. /// Organized electrical QRS complexes. PVT still has electrical QRS complexes.
pub fn has_qrs(self) -> bool { pub fn has_qrs(self) -> bool {
!matches!(self, Self::VentricularFibrillation | Self::Asystole) !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,
}
}
}
/// 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)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@ -195,6 +220,24 @@ pub struct Parameters {
pub show_nibp: bool, pub show_nibp: bool,
} }
impl Parameters {
/// No saturation without an attached sensor, usable signal quality and
/// two observed mechanical pulse events. Thresholds do not control this alarm.
pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
if !self.spo2_sensor_attached {
Spo2Status::NoSensor
} else if self.spo2_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
}
}
}
impl Default for Parameters { impl Default for Parameters {
fn default() -> Self { fn default() -> Self {
Self { Self {
@ -308,6 +351,41 @@ mod tests {
assert!(!p.alarms.pr.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 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] #[test]
fn grouped_mechanical_capture_follows_requested_patterns() { fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(), assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),

View file

@ -1,7 +1,7 @@
//! Size-independent Cairo drawing of the synthetic bedside monitor. //! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin}; use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Quality, Spo2Status};
use crate::simulation::{Sample, Simulator}; use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64); type Color = (f64, f64, f64);
@ -106,17 +106,17 @@ fn pleth_trace_enabled(p: &Parameters) -> bool {
} }
fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) { fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) {
if !p.spo2_sensor_attached { match p.spo2_status(pulse_rate) {
return ("SpO₂".to_owned(), "NO SENSOR".to_owned(), "SpO₂ -- PR -- bpm".to_owned()); Spo2Status::NoSensor => (
"SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::NoReading => (
"SpO₂".to_owned(), "NO READING".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::Available => (
format!("SpO₂ {}", p.spo2_quality.stars()),
p.spo2.to_string(),
format!("% PR {} bpm", pulse_rate.unwrap_or_default()),
),
} }
if p.spo2_quality == Spo2Quality::None {
return ("SpO₂".to_owned(), "--".to_owned(), "NO SIGNAL PR -- bpm".to_owned());
}
(
format!("SpO₂ {}", p.spo2_quality.stars()),
if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
)
} }
fn alarmed(limits: AlarmLimits, value: Option<i32>) -> bool { fn alarmed(limits: AlarmLimits, value: Option<i32>) -> bool {
@ -136,16 +136,15 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0); let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0);
let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85; let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85;
let flash = alarm_flash_on(sim); let flash = alarm_flash_on(sim);
let has_capture = p.ecg_rhythm.has_qrs() let has_capture = p.ecg_rhythm.can_generate_pulse()
&& p.heart_rate > 0 && p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None; && p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None }; let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 { let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Some(p.heart_rate) Some(p.heart_rate)
} else { None }; } else { None };
let oxygen = if pleth_trace_enabled(p) && pulse_rate.is_some() { let spo2_status = p.spo2_status(pulse_rate);
Some(p.spo2) let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
} else { None };
let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic); let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
let limits: Vec<(&str, AlarmLimits)> = match ch { let limits: Vec<(&str, AlarmLimits)> = match ch {
@ -165,23 +164,23 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
draw_alarm_number(cr, &ecg_hr.map_or("--".to_owned(), |v| v.to_string()), draw_alarm_number(cr, &ecg_hr.map_or("--".to_owned(), |v| v.to_string()),
x, value_y, number_size, width, color, x, value_y, number_size, width, color,
alarmed(p.alarms.hr, ecg_hr), flash); alarmed(p.alarms.hr, ecg_hr), flash);
let rhythm = match p.ecg_rhythm { // Show only the clinical alarm message, never the selected ECG rhythm.
EcgRhythm::Sinus => "Sinus", if let Some(message) = p.ecg_rhythm.rhythm_alarm() {
EcgRhythm::AtrialFibrillation => "AF", draw_alarm_number(cr, message, x, info_y, sub_size * 1.1,
EcgRhythm::VentricularTachycardia => "VT", width, color, true, flash);
EcgRhythm::VentricularFibrillation => "VF", } else {
EcgRhythm::Asystole => "Asystole", text(cr, "bpm", x, info_y, sub_size, color, false);
}; }
text(cr, &format!("bpm · {}", rhythm), x, info_y, sub_size, color, false);
} }
Channel::Pleth => { Channel::Pleth => {
let (label, value, info) = spo2_vitals(p, pulse_rate); let (label, value, info) = spo2_vitals(p, pulse_rate);
text(cr, &label, x, top + row_h * 0.24, label_size, color, false); text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
let value_size = if value == "NO SENSOR" { let technical_alarm = spo2_status != Spo2Status::Available;
number_size.min(0.19 * width).min(26.0) let value_size = if technical_alarm {
number_size.min(0.17 * width).min(26.0)
} else { number_size }; } else { number_size };
draw_alarm_number(cr, &value, x, value_y, value_size, draw_alarm_number(cr, &value, x, value_y, value_size,
width, color, alarmed(p.alarms.spo2, oxygen), flash); width, color, technical_alarm || alarmed(p.alarms.spo2, oxygen), flash);
if oxygen.is_some() { if oxygen.is_some() {
draw_alarm_inline(cr, x, info_y, sub_size, width, color, draw_alarm_inline(cr, x, info_y, sub_size, width, color,
"% PR ", &pulse_rate.unwrap_or_default().to_string(), " bpm", "% PR ", &pulse_rate.unwrap_or_default().to_string(), " bpm",
@ -377,7 +376,9 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
} }
// Disconnected or absent pleth signal: no curve, including historical pulses. // Disconnected or absent pleth signal: no curve, including historical pulses.
if matches!(channel, Channel::Pleth) && !pleth_trace_enabled(p) if matches!(channel, Channel::Pleth)
&& (!pleth_trace_enabled(p)
|| p.spo2_status(sim.pulse_rate()) != Spo2Status::Available)
{ {
let _ = cr.restore(); let _ = cr.restore();
return; return;
@ -544,8 +545,7 @@ mod tests {
p.spo2_sensor_attached = true; p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::None; p.spo2_quality = Spo2Quality::None;
assert!(!pleth_trace_enabled(&p)); assert!(!pleth_trace_enabled(&p));
assert_eq!(spo2_vitals(&p, Some(75)).1, "--"); assert_eq!(spo2_vitals(&p, Some(75)).1, "NO READING");
assert!(spo2_vitals(&p, Some(75)).2.contains("NO SIGNAL"));
assert!(spo2_vitals(&p, Some(75)).2.contains("PR --")); assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
assert!(p.show_spo2); // no readings, but visible row and status assert!(p.show_spo2); // no readings, but visible row and status
} }
@ -559,10 +559,20 @@ mod tests {
assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm")); assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm"));
p.spo2_quality = Spo2Quality::Good; p.spo2_quality = Spo2Quality::Good;
assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★"); assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★");
assert_eq!(spo2_vitals(&p, None).1, "--"); assert_eq!(spo2_vitals(&p, None).1, "NO READING");
assert!(spo2_vitals(&p, None).2.contains("PR --")); assert!(spo2_vitals(&p, None).2.contains("PR --"));
} }
#[test]
fn no_sensor_precedes_no_reading_and_both_are_spo2_alarms() {
let mut p = Parameters::default();
assert_eq!(spo2_vitals(&p, None).1, "NO READING");
p.ecg_rhythm = crate::model::EcgRhythm::PulselessVentricularTachycardia;
assert_eq!(spo2_vitals(&p, Some(100)).1, "NO READING");
p.spo2_sensor_attached = false;
assert_eq!(spo2_vitals(&p, Some(100)).1, "NO SENSOR");
}
#[test] #[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() { fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default(); let p = Parameters::default();

View file

@ -109,7 +109,7 @@ impl Simulator {
if params.ecg_rhythm != self.previous_rhythm if params.ecg_rhythm != self.previous_rhythm
|| params.pulse_conduction != self.previous_conduction || params.pulse_conduction != self.previous_conduction
|| !params.ecg_rhythm.has_qrs() || !params.ecg_rhythm.can_generate_pulse()
|| params.pulse_conduction == PulseConduction::None || params.pulse_conduction == PulseConduction::None
|| params.heart_rate <= 0 || params.heart_rate <= 0
{ {
@ -146,7 +146,8 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned. // Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment; let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1; self.ecg_beat_number += 1;
if params.pulse_conduction.conducts(self.ecg_beat_number) { if params.ecg_rhythm.can_generate_pulse()
&& params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 { let pulse_pressure_scale = if params.respiratory_rate > 0 {
ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase) ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase)
} else { } else {
@ -208,7 +209,14 @@ impl Simulator {
} }
} }
let art = if let Some(age) = latest_art_age { let art = if !params.ecg_rhythm.can_generate_pulse()
|| params.pulse_conduction == PulseConduction::None
|| params.heart_rate <= 0
{
// Low-frequency baseline drift around zero, without pulsations.
// The smooth, deterministic noise stays within 0..5 mmHg.
pulseless_arterial_drift(self.time)
} else if let Some(age) = latest_art_age {
// Pressure decays after an unperfused interval instead of showing a // Pressure decays after an unperfused interval instead of showing a
// non-existent 75 mmHg baseline during prolonged missed captures. // non-existent 75 mmHg baseline during prolonged missed captures.
let baseline = diastolic * (-(age - 0.60).max(0.0) / 1.40).exp(); let baseline = diastolic * (-(age - 0.60).max(0.0) / 1.40).exp();
@ -220,6 +228,28 @@ impl Simulator {
} }
} }
/// Deterministic smooth value noise with a slow, non-cardiac frequency.
fn smooth_random_unit(time: f64, seconds_per_step: f64, seed: i64) -> f64 {
fn hash(index: i64) -> f64 {
let mut x = (index as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
(x as f64) / (u64::MAX as f64)
}
let position = time / seconds_per_step;
let index = position.floor() as i64;
let delta = position - index as f64;
let fade = delta * delta * (3.0 - 2.0 * delta);
hash(index.wrapping_add(seed)) * (1.0 - fade)
+ hash(index.wrapping_add(seed).wrapping_add(1)) * fade
}
fn pulseless_arterial_drift(time: f64) -> f64 {
(0.4 + 3.6 * smooth_random_unit(time, 2.4, 12)
+ 0.65 * smooth_random_unit(time, 0.95, 41)).clamp(0.0, 5.0)
}
fn gaussian(x: f64, center: f64, width: f64) -> f64 { fn gaussian(x: f64, center: f64, width: f64) -> f64 {
let d = (x - center) / width; let d = (x - center) / width;
(-0.5 * d * d).exp() (-0.5 * d * d).exp()
@ -281,7 +311,7 @@ fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f
- 0.32 * lobe(0.028, 0.012) - 0.32 * lobe(0.028, 0.012)
+ 0.28 * lobe(t_after_qrs, t_width) + 0.28 * lobe(t_after_qrs, t_width)
} }
EcgRhythm::VentricularTachycardia => { EcgRhythm::VentricularTachycardia | EcgRhythm::PulselessVentricularTachycardia => {
// Broad monomorphic ventricular complexes, also in milliseconds. // Broad monomorphic ventricular complexes, also in milliseconds.
1.06 * lobe(0.0, 0.045) 1.06 * lobe(0.0, 0.045)
- 0.49 * lobe(0.068, 0.030) - 0.49 * lobe(0.068, 0.030)
@ -389,13 +419,14 @@ mod tests {
for (rhythm, capture) in [ for (rhythm, capture) in [
(EcgRhythm::Asystole, PulseConduction::OneToOne), (EcgRhythm::Asystole, PulseConduction::OneToOne),
(EcgRhythm::VentricularFibrillation, PulseConduction::OneToOne), (EcgRhythm::VentricularFibrillation, PulseConduction::OneToOne),
(EcgRhythm::PulselessVentricularTachycardia, PulseConduction::OneToOne),
(EcgRhythm::Sinus, PulseConduction::None), (EcgRhythm::Sinus, PulseConduction::None),
] { ] {
let p = Parameters { ecg_rhythm: rhythm, pulse_conduction: capture, ..Parameters::default() }; let p = Parameters { ecg_rhythm: rhythm, pulse_conduction: capture, ..Parameters::default() };
let mut sim = Simulator::new(&p); let mut sim = Simulator::new(&p);
for _ in 0..250 { sim.step(&p); } for _ in 0..250 { sim.step(&p); }
assert!(sim.pulse_rate().is_none()); assert!(sim.pulse_rate().is_none());
assert!(sim.samples.iter().all(|s| s.art == 0.0 && s.pleth == 0.0)); assert!(sim.samples.iter().all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
} }
} }
@ -407,10 +438,44 @@ mod tests {
p.pulse_conduction = PulseConduction::None; p.pulse_conduction = PulseConduction::None;
sim.step(&p); sim.step(&p);
assert!(sim.pulse_rate().is_none()); assert!(sim.pulse_rate().is_none());
assert_eq!(sim.samples.back().unwrap().art, 0.0); assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art));
assert_eq!(sim.samples.back().unwrap().pleth, 0.0); assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
} }
#[test]
fn vt_remains_perfusing_and_pvt_has_qrs_but_no_pulse() {
let mut p = Parameters {
ecg_rhythm: EcgRhythm::VentricularTachycardia,
heart_rate: 160,
..Parameters::default()
};
let mut sim = Simulator::new(&p);
assert_eq!(sim.pulse_rate(), Some(160));
assert!(sim.samples().iter().any(|s| s.art > 70.0 && s.pleth > 0.0));
p.ecg_rhythm = EcgRhythm::PulselessVentricularTachycardia;
sim.step(&p);
assert_eq!(sim.pulse_rate(), None);
assert!((0.0..=5.0).contains(&sim.samples().back().unwrap().art));
assert_eq!(sim.samples().back().unwrap().pleth, 0.0);
for _ in 0..500 { sim.step(&p); }
assert!(sim.samples().iter().rev().take(500)
.all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
assert!(sim.samples().iter().rev().take(500)
.any(|s| s.ecg.abs() > 0.3));
}
#[test]
fn low_pressure_drift_is_smooth_and_never_pulsatile() {
let values: Vec<f64> = (0..5000)
.map(|n| pulseless_arterial_drift(n as f64 * SAMPLE_STEP))
.collect();
assert!(values.iter().all(|v| (0.0..=5.0).contains(v)));
assert!(values.windows(2).all(|w| (w[1] - w[0]).abs() < 0.10));
let spread = values.iter().copied().fold(f64::NEG_INFINITY, f64::max)
- values.iter().copied().fold(f64::INFINITY, f64::min);
assert!(spread > 0.25);
}
#[test] #[test]
fn pulse_rate_follows_two_to_one_capture() { fn pulse_rate_follows_two_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() }; let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };

View file

@ -146,14 +146,15 @@ fn create_admin(app: &Application, params: SharedParams,
let ecg = group(&controls, "ECG"); let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show); add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
add_dropdown(&ecg, "ECG rhythm", &[ add_dropdown(&ecg, "ECG rhythm", &[
"Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia", "Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
"Ventricular fibrillation", "Asystole", "Pulseless ventricular tachycardia (PVT)", "Ventricular fibrillation", "Asystole",
], params.clone(), |p, selected| { ], params.clone(), |p, selected| {
p.ecg_rhythm = match selected { p.ecg_rhythm = match selected {
1 => EcgRhythm::AtrialFibrillation, 1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia, 2 => EcgRhythm::VentricularTachycardia,
3 => EcgRhythm::VentricularFibrillation, 3 => EcgRhythm::PulselessVentricularTachycardia,
4 => EcgRhythm::Asystole, 4 => EcgRhythm::VentricularFibrillation,
5 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus, _ => EcgRhythm::Sinus,
}; };
}); });
@ -210,7 +211,7 @@ fn create_admin(app: &Application, params: SharedParams,
}); });
let conduction_hint = gtk::Label::new(Some( let conduction_hint = gtk::Label::new(Some(
"Pulse rate is derived from captured QRS events. "Pulse rate is derived from captured QRS events.
ART and pleth are delayed; VF and asystole always have no pulse." ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulseless."
)); ));
conduction_hint.set_xalign(0.0); conduction_hint.set_xalign(0.0);
conduction_hint.set_wrap(true); conduction_hint.set_wrap(true);