This commit is contained in:
GABRIEL Sebastian 2026-11-12 10:43:11 +01:00
commit 35a380b808
8 changed files with 954 additions and 46 deletions

View file

@ -0,0 +1,526 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.3.1"
+version = "0.3.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.3.1
+# Patient Monitor Simulation (PaMSim) — v0.3.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -20,14 +20,17 @@
## Windows
-**Admin:** Controls ECG rhythm and rate; mechanical capture; SpO₂; invasive
-arterial pressure, waveform shape and pulse-pressure variation; NIBP; and
-capnography. Numeric inputs have bidirectionally linked sliders and text fields.
+**Admin:** Controls patient name; ECG rhythm and rate; mechanical capture;
+SpO₂, signal quality and sensor connection; invasive arterial pressure,
+waveform shape and pulse-pressure variation; NIBP; and capnography. Numeric inputs have bidirectionally linked sliders and text fields.
Each of the five monitor parameters (ECG, SpO₂/pleth, ART, CO₂, NIBP) has its
own **Show on monitor** checkbox.
**Monitor:** Black background; ECG green, pleth yellow, ART red and capnogram
-light grey. Waveforms and vital signs disappear together when their respective
+light grey. The patient name entered in Admin replaces **PATIENT MONITOR** in
+the header immediately; leaving the name blank restores the generic title.
+Long names are automatically resized or clipped to fit the header.
+Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP can
@@ -36,6 +39,41 @@
The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
+
+## Patient name and pulse oximeter signal state (new in v0.3.2)
+
+The new **Patient name** text field at the top of Admin immediately replaces the
+monitor headline. It is optional; an empty or whitespace-only name displays
+**PATIENT MONITOR**. This is a local teaching label, not a patient record.
+
+Admin → **Pulse oximetry** has two additional controls:
+
+- **Sensor not attached** (checkbox): immediately removes the pleth waveform,
+ suppresses SpO₂ and pulse-rate readings, and displays **NO SENSOR** instead
+ of the numeric saturation. This takes precedence over signal quality.
+- **Signal quality** (dropdown), which changes the visible pleth waveform and
+ quality indicator, independently of the instructor-set SpO₂ percentage:
+
+| Setting | Pleth waveform | Monitor display |
+| --- | --- | --- |
+| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; 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 (★★★) |
+
+Default: sensor attached; signal quality **3 — Good**. At levels 1–3, the
+instructor-set SpO₂ number is shown only when mechanical pulses are detected.
+The signal quality does **not** randomly alter that number: it affects the
+pleth morphology and the quality indicator only. The simulated pulse rate
+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
+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
+can be taught.
## ECG and mechanical coupling
@@ -161,3 +199,17 @@
**Verification:** The archive is generated from these sources. Run `cargo test`
locally to verify the Rust/GTK build; Rust and GTK4 development components
were not available in the environment where this ZIP was prepared.
+
+## Changes in v0.3.2
+
+1. Added live patient-name header in Admin/Monitor with blank-name fallback.
+2. Added four levels of SpO₂ signal quality, quality stars and an irregular,
+ low-amplitude pleth waveform for Poor quality.
+3. Added **Sensor not attached** with `NO SENSOR` status and suppression of
+ saturation, pulse rate and pleth waveform.
+4. Added tests for signal-quality scaling, displayed readings and disconnected
+ sensor behavior.
+
+**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.
--- a/src/model.rs
+++ b/src/model.rs
@@ -58,12 +58,45 @@
Obstructive,
}
-#[derive(Clone, Copy, Debug)]
+/// Instructor-selected plethysmography signal quality; separate from the
+/// physiological oxygen-saturation setting and mechanical pulse capture.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Spo2Quality {
+ None,
+ Poor,
+ Adequate,
+ Good,
+}
+
+impl Spo2Quality {
+ pub fn stars(self) -> &'static str {
+ match self {
+ Self::None => "",
+ Self::Poor => "★",
+ Self::Adequate => "★★",
+ Self::Good => "★★★",
+ }
+ }
+
+ pub fn amplitude_scale(self) -> f64 {
+ match self {
+ Self::None => 0.0,
+ Self::Poor => 0.25,
+ Self::Adequate => 0.56,
+ Self::Good => 1.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
pub struct Parameters {
+ pub patient_name: String, // displayed in the monitor header, blank = generic title
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
- pub spo2: i32, // %
+ pub spo2: i32, // %; instructor-set nominal saturation
+ pub spo2_quality: Spo2Quality,
+ pub spo2_sensor_attached: bool,
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
pub art_diastolic: i32, // mmHg
pub arterial_shape: ArterialShape,
@@ -84,10 +117,13 @@
impl Default for Parameters {
fn default() -> Self {
Self {
+ patient_name: String::new(),
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
+ spo2_quality: Spo2Quality::Good,
+ spo2_sensor_attached: true,
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
@@ -120,6 +156,17 @@
}
#[test]
+ fn spo2_quality_stars_and_amplitude_progress_monotonically() {
+ assert_eq!(Spo2Quality::None.stars(), "");
+ assert_eq!(Spo2Quality::Poor.stars(), "★");
+ assert_eq!(Spo2Quality::Adequate.stars(), "★★");
+ assert_eq!(Spo2Quality::Good.stars(), "★★★");
+ assert_eq!(Spo2Quality::None.amplitude_scale(), 0.0);
+ assert!(Spo2Quality::Poor.amplitude_scale() < Spo2Quality::Adequate.amplitude_scale());
+ assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
+ }
+
+ #[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 3, 5, 7]);
--- 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, EcgRhythm, Parameters, PulseConduction};
+use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@@ -43,8 +43,18 @@
let trace_right = (split_x - pad).max(trace_left + 40.0);
let text_scale = (w.min(h * 1.7) / 850.0).clamp(0.65, 1.5);
- text(cr, "PATIENT MONITOR", pad + 5.0, header * 0.58, 18.0 * text_scale,
- LIGHT_GREY, true);
+ let patient_title = if p.patient_name.trim().is_empty() {
+ "PATIENT MONITOR"
+ } else {
+ p.patient_name.trim()
+ };
+ let title_max_width = if w >= 850.0 {
+ split_x - pad * 2.0 - 145.0 * text_scale
+ } else {
+ split_x - pad * 2.0
+ };
+ fitted_text(cr, patient_title, pad + 5.0, header * 0.58,
+ 18.0 * text_scale, title_max_width.max(25.0), LIGHT_GREY);
if w >= 850.0 {
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
@@ -84,6 +94,24 @@
}
}
+fn pleth_trace_enabled(p: &Parameters) -> bool {
+ p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
+}
+
+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());
+ }
+ 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 draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) {
let label_size = (row_h * 0.135).clamp(11.0, 19.0);
@@ -95,7 +123,7 @@
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let (label, value, info) = match ch {
Channel::Ecg => (
- "HR",
+ "HR".to_owned(),
if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() }
else { p.heart_rate.to_string() },
format!("bpm · {}", match p.ecg_rhythm {
@@ -106,13 +134,9 @@
EcgRhythm::Asystole => "Asystole",
}),
),
- Channel::Pleth => (
- "SpO₂",
- 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())),
- ),
+ Channel::Pleth => spo2_vitals(p, pulse_rate),
Channel::Art => (
- "ART",
+ "ART".to_owned(),
if pulse_rate.is_some() {
format!("{}/{}", p.art_systolic, p.art_diastolic)
} else { "--/--".to_owned() },
@@ -126,13 +150,20 @@
}
} else { "MAP -- mmHg".to_owned() },
),
- Channel::Capno => ("EtCO₂", p.etco2.to_string(),
+ Channel::Capno => ("EtCO₂".to_owned(), p.etco2.to_string(),
format!("mmHg RR {} /min", p.respiratory_rate)),
};
- text(cr, label, x, top + row_h * 0.24, label_size, color, false);
- // Reduce wide BP values so they fit within the sidebar.
- let value_size = if matches!(ch, Channel::Art) { number_size * 0.78 } else { number_size };
- text(cr, &value, x, top + row_h * 0.64, value_size, color, true);
+ text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
+ // Reduce wide readings so they fit within the sidebar.
+ let value_size = if value == "NO SENSOR" {
+ number_size.min(0.19 * width).min(26.0)
+ } else if matches!(ch, Channel::Art) {
+ number_size * 0.78
+ } else {
+ number_size
+ };
+ fitted_text(cr, &value, x, top + row_h * 0.64, value_size,
+ width.max(20.0), color);
text(cr, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false);
}
@@ -175,6 +206,13 @@
right, top + trace_height * 0.5, GRID, 0.7);
}
+ // Disconnected or absent pleth signal: no curve, including historical pulses.
+ if matches!(channel, Channel::Pleth) && !pleth_trace_enabled(p)
+ {
+ let _ = cr.restore();
+ return;
+ }
+
set_color(cr, color);
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
cr.set_line_cap(LineCap::Round);
@@ -194,11 +232,66 @@
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
- Channel::Pleth => (0.10 + s.pleth * 0.78).clamp(0.02, 0.98),
+ Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, p.spo2_quality) * 0.78)
+ .clamp(0.02, 0.98),
Channel::Art => (s.art / 200.0).clamp(0.0, 1.0),
Channel::Capno => (0.08 + (s.co2 / f64::from(p.etco2.max(1))) * 0.80)
.clamp(0.02, 0.98),
}
+}
+
+/// Signal degradation is presentation-only: no quality setting can invent
+/// pulses or change the ECG/ART generator. The noise is smoothly interpolated
+/// and reproducible, so redrawing a sample does not make it flicker.
+fn pleth_visual_amplitude(pleth: f64, time: f64, quality: Spo2Quality) -> f64 {
+ let scale = quality.amplitude_scale();
+ if scale == 0.0 || pleth <= 0.0 { return 0.0; }
+ let distortion = if quality == Spo2Quality::Poor {
+ (1.0 + 0.55 * smooth_noise(time * 7.0)
+ + 0.20 * smooth_noise(time * 23.0 + 4.0)).clamp(0.15, 1.75)
+ } else {
+ 1.0
+ };
+ (pleth * scale * distortion).clamp(0.0, 1.0)
+}
+
+fn smooth_noise(position: f64) -> f64 {
+ let index = position.floor() as i64;
+ let fraction = position - index as f64;
+ let smooth = fraction * fraction * (3.0 - 2.0 * fraction);
+ let a = noise_value(index);
+ let b = noise_value(index.wrapping_add(1));
+ a + (b - a) * smooth
+}
+
+fn noise_value(index: i64) -> f64 {
+ let mut x = (index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
+ x ^= x >> 30;
+ x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ x ^= x >> 27;
+ x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
+ x ^= x >> 31;
+ (x as f64 / u64::MAX as f64) * 2.0 - 1.0
+}
+
+/// Fit a name or numeric/status reading horizontally without changing the
+/// other monitor dimensions. For exceptionally long values, clip safely.
+fn fitted_text(cr: &Context, value: &str, x: f64, baseline: f64,
+ nominal_size: f64, available_width: f64, color: Color) {
+ cr.select_font_face("Sans", FontSlant::Normal, FontWeight::Bold);
+ cr.set_font_size(nominal_size);
+ let actual_width = cr.text_extents(value).map(|ext| ext.x_advance()).unwrap_or(0.0);
+ let fitted_size = if actual_width > available_width && actual_width > 0.0 {
+ (nominal_size * available_width / actual_width).max(8.0)
+ } else {
+ nominal_size
+ };
+ let _ = cr.save();
+ cr.rectangle(x, baseline - fitted_size * 1.25,
+ available_width.max(1.0), fitted_size * 1.55);
+ cr.clip();
+ text(cr, value, x, baseline, fitted_size, color, true);
+ let _ = cr.restore();
}
fn set_color(cr: &Context, c: Color) {
@@ -243,6 +336,53 @@
}
#[test]
+ fn pleth_degradation_preserves_capture_timing_and_suppresses_false_pulses() {
+ let pulse = 0.6;
+ let t = 1.234;
+ assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::None), 0.0);
+ assert_eq!(pleth_visual_amplitude(0.0, t, Spo2Quality::Poor), 0.0);
+ assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor)
+ < pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate));
+ assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate)
+ < pleth_visual_amplitude(pulse, t, Spo2Quality::Good));
+ assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Good), pulse);
+ assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
+ pleth_visual_amplitude(pulse, t, Spo2Quality::Poor));
+ assert_ne!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
+ pleth_visual_amplitude(pulse, t + 0.5, Spo2Quality::Poor));
+ }
+
+ #[test]
+ fn disconnected_or_no_quality_means_no_pleth_or_spo2_reading() {
+ let mut p = Parameters::default();
+ assert!(pleth_trace_enabled(&p));
+ p.spo2_sensor_attached = false;
+ assert!(!pleth_trace_enabled(&p));
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "NO SENSOR");
+ assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ 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!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ assert!(p.show_spo2); // no readings, but visible row and status
+ }
+
+ #[test]
+ fn poor_and_good_quality_keep_derived_pr_and_quality_indicators() {
+ let mut p = Parameters::default();
+ p.spo2_quality = Spo2Quality::Poor;
+ assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★");
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "98");
+ 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!(spo2_vitals(&p, None).2.contains("PR --"));
+ }
+
+ #[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, art: 100.0, co2: 0.0 };
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -8,7 +8,7 @@
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
+use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -41,7 +41,7 @@
let params = params.clone();
let simulator = simulator.clone();
move |_area, cr, width, height| {
- let config = *params.borrow();
+ let config = params.borrow();
render::draw(cr, width, height, &config, &simulator.borrow());
}
});
@@ -54,7 +54,7 @@
let now = Instant::now();
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();
previous.set(now);
- let config = *params.borrow();
+ let config = params.borrow();
simulator.borrow_mut().advance(elapsed, &config);
area.queue_draw();
glib::ControlFlow::Continue
@@ -104,6 +104,24 @@
scroller.set_vexpand(true);
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12);
+
+ let patient = group(&controls, "Patient");
+ let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
+ let patient_label = gtk::Label::new(Some("Patient name"));
+ patient_label.set_xalign(0.0);
+ patient_label.set_width_chars(17);
+ let name_entry = gtk::Entry::new();
+ name_entry.set_hexpand(true);
+ name_entry.set_max_length(80);
+ name_entry.set_placeholder_text(Some("Name displayed on monitor"));
+ name_entry.set_text(&params.borrow().patient_name);
+ name_entry.connect_changed({
+ let params = params.clone();
+ move |entry| params.borrow_mut().patient_name = entry.text().to_string()
+ });
+ patient_row.append(&patient_label);
+ patient_row.append(&name_entry);
+ patient.append(&patient_row);
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
@@ -126,6 +144,26 @@
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
+ let sensor = gtk::CheckButton::with_label("Sensor not attached");
+ sensor.set_active(!params.borrow().spo2_sensor_attached);
+ sensor.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().spo2_sensor_attached = !button.is_active()
+ });
+ spo2.append(&sensor);
+ add_dropdown_at(&spo2, "Signal quality", &[
+ "0 — None (no reading)",
+ "1 — Poor (*)",
+ "2 — Adequate (**)",
+ "3 — Good (***)",
+ ], params.borrow().spo2_quality as u32, params.clone(), |p, selected| {
+ p.spo2_quality = match selected {
+ 1 => Spo2Quality::Poor,
+ 2 => Spo2Quality::Adequate,
+ 3 => Spo2Quality::Good,
+ _ => Spo2Quality::None,
+ };
+ });
add_dropdown(&spo2, "Mechanical capture", &[
"1:1 (every QRS)",
"2:1 (one pulse in two)",
@@ -243,11 +281,18 @@
fn add_dropdown<F>(parent: &gtk::Box, label: &str, items: &[&str],
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
+ add_dropdown_at(parent, label, items, 0, params, setter);
+}
+
+fn add_dropdown_at<F>(parent: &gtk::Box, label: &str, items: &[&str],
+ initial: u32, params: SharedParams, setter: F)
+where F: Fn(&mut Parameters, u32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
caption.set_xalign(0.0);
caption.set_width_chars(17);
let combo = gtk::DropDown::from_strings(items);
+ combo.set_selected(initial);
combo.set_hexpand(true);
combo.connect_selected_notify(move |combo| {
setter(&mut params.borrow_mut(), combo.selected());

View file

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

View file

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

View file

@ -1,4 +1,4 @@
# Patient Monitor Simulation (PaMSim) — v0.3.0
# Patient Monitor Simulation (PaMSim) — v0.3.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@ -20,14 +20,17 @@ session (e.g., Fedora KDE/Wayland).
## Windows
**Admin:** Controls ECG rhythm and rate; mechanical capture; SpO₂; invasive
arterial pressure, waveform shape and pulse-pressure variation; NIBP; and
capnography. Numeric inputs have bidirectionally linked sliders and text fields.
**Admin:** Controls patient name; ECG rhythm and rate; mechanical capture;
SpO₂, signal quality and sensor connection; invasive arterial pressure,
waveform shape and pulse-pressure variation; NIBP; and capnography. Numeric inputs have bidirectionally linked sliders and text fields.
Each of the five monitor parameters (ECG, SpO₂/pleth, ART, CO₂, NIBP) has its
own **Show on monitor** checkbox.
**Monitor:** Black background; ECG green, pleth yellow, ART red and capnogram
light grey. Waveforms and vital signs disappear together when their respective
light grey. The patient name entered in Admin replaces **PATIENT MONITOR** in
the header immediately; leaving the name blank restores the generic title.
Long names are automatically resized or clipped to fit the header.
Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP can
@ -37,6 +40,41 @@ The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
## Patient name and pulse oximeter signal state (new in v0.3.2)
The new **Patient name** text field at the top of Admin immediately replaces the
monitor headline. It is optional; an empty or whitespace-only name displays
**PATIENT MONITOR**. This is a local teaching label, not a patient record.
Admin → **Pulse oximetry** has two additional controls:
- **Sensor not attached** (checkbox): immediately removes the pleth waveform,
suppresses SpO₂ and pulse-rate readings, and displays **NO SENSOR** instead
of the numeric saturation. This takes precedence over signal quality.
- **Signal quality** (dropdown), which changes the visible pleth waveform and
quality indicator, independently of the instructor-set SpO₂ percentage:
| Setting | Pleth waveform | Monitor display |
| --- | --- | --- |
| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; 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 (★★★) |
Default: sensor attached; signal quality **3 — Good**. At levels 1–3, the
instructor-set SpO₂ number is shown only when mechanical pulses are detected.
The signal quality does **not** randomly alter that number: it affects the
pleth morphology and the quality indicator only. The simulated pulse rate
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
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
can be taught.
## ECG and mechanical coupling
- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia,
@ -102,9 +140,31 @@ The five **Show on monitor** checkboxes affect the presentation only:
Remaining visible waveforms keep their relative order and receive an equal
share of the available area; zero waveform channels is supported.
## ECG morphology correction (v0.3.1)
At high heart rates, the previous ECG generator expressed QRS width as a fixed
fraction of the R–R interval and sampled at 100 Hz. Narrow R waves could fall
between samples, making successive QRS complexes appear to vary dramatically
in amplitude despite a regular sinus rhythm.
- Synthetic P/QRS/T components now have widths specified in milliseconds,
not fixed fractions of the cardiac cycle. P/T positioning and widths adapt
to the R–R interval, while the QRS width remains essentially constant.
- Sampling increased to **250 Hz** (4 ms intervals) to capture QRS peaks
more consistently, including at **189–240 bpm**.
- The ECG morphology remains independent of the respiratory arterial PPV
setting. The arterial and pleth delays and mechanical capture options are
unchanged.
- Regression tests compare peak heights at 60, 75, 120, 189 and 240 bpm,
and verify that changing PPV does not affect the ECG signal.
The ECG remains a schematic educational signal; no voltage calibration,
lead placement model, diagnostic criteria, or patient-specific physiology
are simulated.
## Signal implementation
- 100 Hz synthetic signal samples, 10 s retained history, 8 s scrolling trace.
- 250 Hz synthetic signal samples, 10 s retained history, 8 s scrolling trace.
- Cairo draws into the GTK4 `DrawingArea` and scales with the window.
- A conducted QRS records its own respiratory PPV multiplier at event time.
The arterial pulse thus retains the same amplitude throughout the beat.
@ -139,3 +199,17 @@ src/
**Verification:** The archive is generated from these sources. Run `cargo test`
locally to verify the Rust/GTK build; Rust and GTK4 development components
were not available in the environment where this ZIP was prepared.
## Changes in v0.3.2
1. Added live patient-name header in Admin/Monitor with blank-name fallback.
2. Added four levels of SpO₂ signal quality, quality stars and an irregular,
low-amplitude pleth waveform for Poor quality.
3. Added **Sensor not attached** with `NO SENSOR` status and suppression of
saturation, pulse rate and pleth waveform.
4. Added tests for signal-quality scaling, displayed readings and disconnected
sensor behavior.
**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.

View file

@ -58,12 +58,45 @@ pub enum CapnoShape {
Obstructive,
}
#[derive(Clone, Copy, Debug)]
/// Instructor-selected plethysmography signal quality; separate from the
/// physiological oxygen-saturation setting and mechanical pulse capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spo2Quality {
None,
Poor,
Adequate,
Good,
}
impl Spo2Quality {
pub fn stars(self) -> &'static str {
match self {
Self::None => "",
Self::Poor => "★",
Self::Adequate => "★★",
Self::Good => "★★★",
}
}
pub fn amplitude_scale(self) -> f64 {
match self {
Self::None => 0.0,
Self::Poor => 0.25,
Self::Adequate => 0.56,
Self::Good => 1.0,
}
}
}
#[derive(Clone, Debug)]
pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
pub spo2: i32, // %
pub spo2: i32, // %; instructor-set nominal saturation
pub spo2_quality: Spo2Quality,
pub spo2_sensor_attached: bool,
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
pub art_diastolic: i32, // mmHg
pub arterial_shape: ArterialShape,
@ -84,10 +117,13 @@ pub struct Parameters {
impl Default for Parameters {
fn default() -> Self {
Self {
patient_name: String::new(),
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
spo2_quality: Spo2Quality::Good,
spo2_sensor_attached: true,
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
@ -119,6 +155,17 @@ mod tests {
assert_eq!(mean_arterial_pressure(120, 75), 90);
}
#[test]
fn spo2_quality_stars_and_amplitude_progress_monotonically() {
assert_eq!(Spo2Quality::None.stars(), "");
assert_eq!(Spo2Quality::Poor.stars(), "★");
assert_eq!(Spo2Quality::Adequate.stars(), "★★");
assert_eq!(Spo2Quality::Good.stars(), "★★★");
assert_eq!(Spo2Quality::None.amplitude_scale(), 0.0);
assert!(Spo2Quality::Poor.amplitude_scale() < Spo2Quality::Adequate.amplitude_scale());
assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
}
#[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
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.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction};
use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@ -43,8 +43,18 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
let trace_right = (split_x - pad).max(trace_left + 40.0);
let text_scale = (w.min(h * 1.7) / 850.0).clamp(0.65, 1.5);
text(cr, "PATIENT MONITOR", pad + 5.0, header * 0.58, 18.0 * text_scale,
LIGHT_GREY, true);
let patient_title = if p.patient_name.trim().is_empty() {
"PATIENT MONITOR"
} else {
p.patient_name.trim()
};
let title_max_width = if w >= 850.0 {
split_x - pad * 2.0 - 145.0 * text_scale
} else {
split_x - pad * 2.0
};
fitted_text(cr, patient_title, pad + 5.0, header * 0.58,
18.0 * text_scale, title_max_width.max(25.0), LIGHT_GREY);
if w >= 850.0 {
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
@ -84,6 +94,24 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
}
}
fn pleth_trace_enabled(p: &Parameters) -> bool {
p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
}
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());
}
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 draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) {
let label_size = (row_h * 0.135).clamp(11.0, 19.0);
@ -95,7 +123,7 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let (label, value, info) = match ch {
Channel::Ecg => (
"HR",
"HR".to_owned(),
if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() }
else { p.heart_rate.to_string() },
format!("bpm · {}", match p.ecg_rhythm {
@ -106,13 +134,9 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
EcgRhythm::Asystole => "Asystole",
}),
),
Channel::Pleth => (
"SpO₂",
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())),
),
Channel::Pleth => spo2_vitals(p, pulse_rate),
Channel::Art => (
"ART",
"ART".to_owned(),
if pulse_rate.is_some() {
format!("{}/{}", p.art_systolic, p.art_diastolic)
} else { "--/--".to_owned() },
@ -126,13 +150,20 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
}
} else { "MAP -- mmHg".to_owned() },
),
Channel::Capno => ("EtCO₂", p.etco2.to_string(),
Channel::Capno => ("EtCO₂".to_owned(), p.etco2.to_string(),
format!("mmHg RR {} /min", p.respiratory_rate)),
};
text(cr, label, x, top + row_h * 0.24, label_size, color, false);
// Reduce wide BP values so they fit within the sidebar.
let value_size = if matches!(ch, Channel::Art) { number_size * 0.78 } else { number_size };
text(cr, &value, x, top + row_h * 0.64, value_size, color, true);
text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
// Reduce wide readings so they fit within the sidebar.
let value_size = if value == "NO SENSOR" {
number_size.min(0.19 * width).min(26.0)
} else if matches!(ch, Channel::Art) {
number_size * 0.78
} else {
number_size
};
fitted_text(cr, &value, x, top + row_h * 0.64, value_size,
width.max(20.0), color);
text(cr, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false);
}
@ -175,6 +206,13 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
right, top + trace_height * 0.5, GRID, 0.7);
}
// Disconnected or absent pleth signal: no curve, including historical pulses.
if matches!(channel, Channel::Pleth) && !pleth_trace_enabled(p)
{
let _ = cr.restore();
return;
}
set_color(cr, color);
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
cr.set_line_cap(LineCap::Round);
@ -194,13 +232,68 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
Channel::Pleth => (0.10 + s.pleth * 0.78).clamp(0.02, 0.98),
Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, p.spo2_quality) * 0.78)
.clamp(0.02, 0.98),
Channel::Art => (s.art / 200.0).clamp(0.0, 1.0),
Channel::Capno => (0.08 + (s.co2 / f64::from(p.etco2.max(1))) * 0.80)
.clamp(0.02, 0.98),
}
}
/// Signal degradation is presentation-only: no quality setting can invent
/// pulses or change the ECG/ART generator. The noise is smoothly interpolated
/// and reproducible, so redrawing a sample does not make it flicker.
fn pleth_visual_amplitude(pleth: f64, time: f64, quality: Spo2Quality) -> f64 {
let scale = quality.amplitude_scale();
if scale == 0.0 || pleth <= 0.0 { return 0.0; }
let distortion = if quality == Spo2Quality::Poor {
(1.0 + 0.55 * smooth_noise(time * 7.0)
+ 0.20 * smooth_noise(time * 23.0 + 4.0)).clamp(0.15, 1.75)
} else {
1.0
};
(pleth * scale * distortion).clamp(0.0, 1.0)
}
fn smooth_noise(position: f64) -> f64 {
let index = position.floor() as i64;
let fraction = position - index as f64;
let smooth = fraction * fraction * (3.0 - 2.0 * fraction);
let a = noise_value(index);
let b = noise_value(index.wrapping_add(1));
a + (b - a) * smooth
}
fn noise_value(index: i64) -> f64 {
let mut x = (index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 30;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 27;
x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
(x as f64 / u64::MAX as f64) * 2.0 - 1.0
}
/// Fit a name or numeric/status reading horizontally without changing the
/// other monitor dimensions. For exceptionally long values, clip safely.
fn fitted_text(cr: &Context, value: &str, x: f64, baseline: f64,
nominal_size: f64, available_width: f64, color: Color) {
cr.select_font_face("Sans", FontSlant::Normal, FontWeight::Bold);
cr.set_font_size(nominal_size);
let actual_width = cr.text_extents(value).map(|ext| ext.x_advance()).unwrap_or(0.0);
let fitted_size = if actual_width > available_width && actual_width > 0.0 {
(nominal_size * available_width / actual_width).max(8.0)
} else {
nominal_size
};
let _ = cr.save();
cr.rectangle(x, baseline - fitted_size * 1.25,
available_width.max(1.0), fitted_size * 1.55);
cr.clip();
text(cr, value, x, baseline, fitted_size, color, true);
let _ = cr.restore();
}
fn set_color(cr: &Context, c: Color) {
cr.set_source_rgb(c.0, c.1, c.2);
}
@ -242,6 +335,53 @@ mod tests {
assert!(visible_channels(&p).is_empty());
}
#[test]
fn pleth_degradation_preserves_capture_timing_and_suppresses_false_pulses() {
let pulse = 0.6;
let t = 1.234;
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::None), 0.0);
assert_eq!(pleth_visual_amplitude(0.0, t, Spo2Quality::Poor), 0.0);
assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor)
< pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate));
assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate)
< pleth_visual_amplitude(pulse, t, Spo2Quality::Good));
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Good), pulse);
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
pleth_visual_amplitude(pulse, t, Spo2Quality::Poor));
assert_ne!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
pleth_visual_amplitude(pulse, t + 0.5, Spo2Quality::Poor));
}
#[test]
fn disconnected_or_no_quality_means_no_pleth_or_spo2_reading() {
let mut p = Parameters::default();
assert!(pleth_trace_enabled(&p));
p.spo2_sensor_attached = false;
assert!(!pleth_trace_enabled(&p));
assert_eq!(spo2_vitals(&p, Some(75)).1, "NO SENSOR");
assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
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!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
assert!(p.show_spo2); // no readings, but visible row and status
}
#[test]
fn poor_and_good_quality_keep_derived_pr_and_quality_indicators() {
let mut p = Parameters::default();
p.spo2_quality = Spo2Quality::Poor;
assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★");
assert_eq!(spo2_vitals(&p, Some(75)).1, "98");
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!(spo2_vitals(&p, None).2.contains("PR --"));
}
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();

View file

@ -4,7 +4,7 @@ use std::collections::VecDeque;
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
const SAMPLE_STEP: f64 = 0.01; // 100 Hz
const SAMPLE_STEP: f64 = 0.004; // 250 Hz; adequately samples the QRS upstroke
const HISTORY_SECONDS: f64 = 10.0;
const ART_DELAY: f64 = 0.12; // QRS -> arterial upstroke, seconds (schematic)
const PLETH_DELAY: f64 = 0.30; // QRS -> peripheral pleth onset, seconds
@ -54,7 +54,7 @@ pub struct Simulator {
impl Simulator {
pub fn new(params: &Parameters) -> Self {
let mut sim = Self {
samples: VecDeque::with_capacity(1_100),
samples: VecDeque::with_capacity((HISTORY_SECONDS / SAMPLE_STEP) as usize + 16),
time: -8.0,
ecg_phase: 0.0,
respiratory_phase: 0.0,
@ -68,7 +68,7 @@ impl Simulator {
pending_time: 0.0,
};
// Prepopulate the trace and pulse history, including the initial pulse rate.
for _ in 0..800 {
for _ in 0..(8.0 / SAMPLE_STEP) as usize {
sim.step(params);
}
sim
@ -143,7 +143,7 @@ impl Simulator {
let increment = SAMPLE_STEP * params.heart_rate as f64 / 60.0 / irregularity;
let next_phase = self.ecg_phase + increment;
if self.ecg_phase < QRS_PHASE && next_phase >= QRS_PHASE {
// Interpolate within the 10ms 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;
self.ecg_beat_number += 1;
if params.pulse_conduction.conducts(self.ecg_beat_number) {
@ -230,6 +230,17 @@ fn phase_gaussian(phase: f64, center: f64, width: f64) -> f64 {
gaussian(distance, 0.0, width)
}
/// Periodic ECG component with a location and width expressed in seconds,
/// not as fractions of the R-R interval. This keeps QRS morphology from
/// artificially narrowing when the instructor increases the heart rate.
fn ecg_lobe(phase: f64, rr_seconds: f64, offset_seconds: f64, width_seconds: f64) -> f64 {
phase_gaussian(
phase,
QRS_PHASE + offset_seconds / rr_seconds,
width_seconds / rr_seconds,
)
}
fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f64 {
if rhythm == EcgRhythm::VentricularFibrillation {
// Non-periodic-looking composite oscillation with no organized QRS.
@ -240,26 +251,41 @@ fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f
if heart_rate <= 0 || rhythm == EcgRhythm::Asystole {
return 0.006 * (time * 9.3).sin();
}
// ECG wave durations are measured in *seconds*. Only the P/T placement
// and their widths shorten with R-R interval; Q/R/S widths stay fixed.
// These synthetic lead-II-like morphologies are illustrative, not
// calibrated or validated diagnostic ECGs.
let rr_seconds = 60.0 / f64::from(heart_rate);
let p_before_qrs = (rr_seconds * 0.26).clamp(0.08, 0.18);
let t_after_qrs = (rr_seconds * 0.30).clamp(0.10, 0.29);
let p_width = (rr_seconds * 0.045).clamp(0.014, 0.035);
let t_width = (rr_seconds * 0.09).clamp(0.022, 0.065);
let lobe = |offset, width| ecg_lobe(phase, rr_seconds, offset, width);
match rhythm {
EcgRhythm::Sinus => {
0.16 * phase_gaussian(phase, 0.16, 0.030)
- 0.19 * phase_gaussian(phase, 0.300, 0.011)
+ 1.26 * phase_gaussian(phase, QRS_PHASE, 0.008)
- 0.32 * phase_gaussian(phase, 0.363, 0.014)
+ 0.32 * phase_gaussian(phase, 0.61, 0.070)
// Small P wave, narrow negative Q, prominent R, negative S and T.
0.16 * lobe(-p_before_qrs, p_width)
- 0.22 * lobe(-0.026, 0.009)
+ 1.26 * lobe(0.0, 0.012)
- 0.32 * lobe(0.028, 0.012)
+ 0.32 * lobe(t_after_qrs, t_width)
}
EcgRhythm::AtrialFibrillation => {
// No organized P waves; preserve the QRS shape under changing HR.
0.023 * (time * 39.0).sin()
+ 0.014 * (time * 57.0).sin()
- 0.19 * phase_gaussian(phase, 0.300, 0.011)
+ 1.26 * phase_gaussian(phase, QRS_PHASE, 0.008)
- 0.32 * phase_gaussian(phase, 0.363, 0.014)
+ 0.28 * phase_gaussian(phase, 0.61, 0.072)
- 0.22 * lobe(-0.026, 0.009)
+ 1.26 * lobe(0.0, 0.012)
- 0.32 * lobe(0.028, 0.012)
+ 0.28 * lobe(t_after_qrs, t_width)
}
EcgRhythm::VentricularTachycardia => {
1.06 * phase_gaussian(phase, 0.31, 0.086)
- 0.49 * phase_gaussian(phase, 0.46, 0.067)
- 0.16 * phase_gaussian(phase, 0.72, 0.10)
// Broad monomorphic ventricular complexes, also in milliseconds.
1.06 * lobe(0.0, 0.045)
- 0.49 * lobe(0.068, 0.030)
- 0.16 * lobe(0.13, 0.045)
}
EcgRhythm::VentricularFibrillation | EcgRhythm::Asystole => unreachable!(),
}
@ -472,6 +498,56 @@ mod tests {
assert!(sim.samples().iter().any(|s| s.art > 0.0));
}
#[test]
fn sinus_qrs_peak_height_is_stable_even_at_high_heart_rates() {
// The previous phase-based 100 Hz version varied strongly at 189 bpm:
// the narrow R peaks frequently fell between sample timestamps.
for heart_rate in [60, 75, 120, 189, 240] {
let p = Parameters { heart_rate, ..Parameters::default() };
let mut sim = blank(&p);
let rr = 60.0 / f64::from(heart_rate);
let duration = 9.0;
while sim.time < duration {
sim.step(&p);
}
// Compare maxima in +/-30 ms windows around the exact QRS times.
let peaks: Vec<f64> = (1..18)
.filter_map(|beat| {
let qrs_time = (f64::from(beat) + QRS_PHASE) * rr;
if qrs_time > duration - 0.05 { return None; }
sim.samples.iter()
.filter(|s| (s.time - qrs_time).abs() <= 0.03)
.map(|s| s.ecg)
.reduce(f64::max)
})
.collect();
assert!(peaks.len() >= 5, "too few captured QRS at {heart_rate} bpm");
let minimum = peaks.iter().copied().fold(f64::INFINITY, f64::min);
let maximum = peaks.iter().copied().fold(f64::NEG_INFINITY, f64::max);
assert!(minimum > 1.1, "QRS peak too small at {heart_rate} bpm: {minimum}");
assert!(maximum - minimum < 0.04,
"QRS peak varies excessively at {heart_rate} bpm: {minimum}..{maximum}");
}
}
#[test]
fn pulse_pressure_variation_does_not_change_ecg_amplitude() {
let baseline = Parameters::default();
let with_ppv = Parameters {
pulse_pressure_variation: 60,
..Parameters::default()
};
let mut sim_baseline = blank(&baseline);
let mut sim_ppv = blank(&with_ppv);
for _ in 0..1_000 {
sim_baseline.step(&baseline);
sim_ppv.step(&with_ppv);
assert_eq!(sim_baseline.samples.back().unwrap().ecg,
sim_ppv.samples.back().unwrap().ecg);
}
}
#[test]
fn capnogram_reaches_etco2_plateau() {
assert!((capno_amplitude(0.76, CapnoShape::Normal) - 1.0).abs() < 1e-8);

View file

@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@ -41,12 +41,12 @@ fn create_monitor(app: &Application, params: SharedParams,
let params = params.clone();
let simulator = simulator.clone();
move |_area, cr, width, height| {
let config = *params.borrow();
let config = params.borrow();
render::draw(cr, width, height, &config, &simulator.borrow());
}
});
// Synchronize simulation time with frame updates; synthesize at 100 Hz.
// Synchronize simulation time with frame updates; synthesize at 250 Hz.
let previous = Rc::new(Cell::new(Instant::now()));
canvas.add_tick_callback({
let params = params.clone();
@ -54,7 +54,7 @@ fn create_monitor(app: &Application, params: SharedParams,
let now = Instant::now();
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();
previous.set(now);
let config = *params.borrow();
let config = params.borrow();
simulator.borrow_mut().advance(elapsed, &config);
area.queue_draw();
glib::ControlFlow::Continue
@ -105,6 +105,24 @@ fn create_admin(app: &Application, params: SharedParams,
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12);
let patient = group(&controls, "Patient");
let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
let patient_label = gtk::Label::new(Some("Patient name"));
patient_label.set_xalign(0.0);
patient_label.set_width_chars(17);
let name_entry = gtk::Entry::new();
name_entry.set_hexpand(true);
name_entry.set_max_length(80);
name_entry.set_placeholder_text(Some("Name displayed on monitor"));
name_entry.set_text(&params.borrow().patient_name);
name_entry.connect_changed({
let params = params.clone();
move |entry| params.borrow_mut().patient_name = entry.text().to_string()
});
patient_row.append(&patient_label);
patient_row.append(&name_entry);
patient.append(&patient_row);
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", &[
@ -126,6 +144,26 @@ fn create_admin(app: &Application, params: SharedParams,
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
let sensor = gtk::CheckButton::with_label("Sensor not attached");
sensor.set_active(!params.borrow().spo2_sensor_attached);
sensor.connect_toggled({
let params = params.clone();
move |button| params.borrow_mut().spo2_sensor_attached = !button.is_active()
});
spo2.append(&sensor);
add_dropdown_at(&spo2, "Signal quality", &[
"0 — None (no reading)",
"1 — Poor (*)",
"2 — Adequate (**)",
"3 — Good (***)",
], params.borrow().spo2_quality as u32, params.clone(), |p, selected| {
p.spo2_quality = match selected {
1 => Spo2Quality::Poor,
2 => Spo2Quality::Adequate,
3 => Spo2Quality::Good,
_ => Spo2Quality::None,
};
});
add_dropdown(&spo2, "Mechanical capture", &[
"1:1 (every QRS)",
"2:1 (one pulse in two)",
@ -242,12 +280,19 @@ where F: Fn(&mut Parameters, bool) + 'static {
fn add_dropdown<F>(parent: &gtk::Box, label: &str, items: &[&str],
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
add_dropdown_at(parent, label, items, 0, params, setter);
}
fn add_dropdown_at<F>(parent: &gtk::Box, label: &str, items: &[&str],
initial: u32, params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
caption.set_xalign(0.0);
caption.set_width_chars(17);
let combo = gtk::DropDown::from_strings(items);
combo.set_selected(initial);
combo.set_hexpand(true);
combo.connect_selected_notify(move |combo| {
setter(&mut params.borrow_mut(), combo.selected());