Initial commit
This commit is contained in:
commit
788c68a1d8
10 changed files with 2020 additions and 0 deletions
14
patient-monitor-simulation/src/main.rs
Normal file
14
patient-monitor-simulation/src/main.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
mod model;
|
||||
mod render;
|
||||
mod simulation;
|
||||
mod ui;
|
||||
|
||||
use gtk::prelude::*;
|
||||
|
||||
fn main() -> gtk::glib::ExitCode {
|
||||
let application = gtk::Application::builder()
|
||||
.application_id("org.example.PatientMonitorSimulation")
|
||||
.build();
|
||||
application.connect_activate(ui::create_windows);
|
||||
application.run()
|
||||
}
|
||||
131
patient-monitor-simulation/src/model.rs
Normal file
131
patient-monitor-simulation/src/model.rs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
//! Shared configuration of the synthetic monitor signals.
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EcgRhythm {
|
||||
Sinus,
|
||||
AtrialFibrillation,
|
||||
VentricularTachycardia,
|
||||
VentricularFibrillation,
|
||||
Asystole,
|
||||
}
|
||||
|
||||
impl EcgRhythm {
|
||||
/// VF and asystole have no organized QRS to trigger a mechanical pulse.
|
||||
pub fn has_qrs(self) -> bool {
|
||||
!matches!(self, Self::VentricularFibrillation | Self::Asystole)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PulseConduction {
|
||||
OneToOne,
|
||||
TwoToOne,
|
||||
ThreeToOne,
|
||||
None,
|
||||
Random,
|
||||
}
|
||||
|
||||
impl PulseConduction {
|
||||
pub fn conducts(self, beat: u64) -> bool {
|
||||
match self {
|
||||
Self::OneToOne => true,
|
||||
// One mechanical pulse for every two QRS complexes.
|
||||
Self::TwoToOne => (beat - 1) % 2 == 0,
|
||||
Self::ThreeToOne => (beat - 1) % 3 == 0,
|
||||
Self::None => false,
|
||||
Self::Random => {
|
||||
// Deterministic pseudo-random 65% mechanical capture for reproducible lessons.
|
||||
let mut x = beat.wrapping_mul(0x9E37_79B9_7F4A_7C15);
|
||||
x ^= x >> 30;
|
||||
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
x ^= x >> 27;
|
||||
(x % 100) < 65
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArterialShape {
|
||||
Normal,
|
||||
Damped,
|
||||
Hyperdynamic,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CapnoShape {
|
||||
Normal,
|
||||
Obstructive,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Parameters {
|
||||
pub ecg_rhythm: EcgRhythm,
|
||||
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
|
||||
pub pulse_conduction: PulseConduction,
|
||||
pub spo2: i32, // %
|
||||
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
|
||||
pub art_diastolic: i32, // mmHg
|
||||
pub arterial_shape: ArterialShape,
|
||||
pub pulse_pressure_variation: i32, // PPV %, 0 disables respiratory variation
|
||||
pub nibp_systolic: i32, // mmHg, historical/static simulated cuff value
|
||||
pub nibp_diastolic: i32, // mmHg
|
||||
pub etco2: i32, // mmHg
|
||||
pub respiratory_rate: i32, // breaths/min
|
||||
pub capno_shape: CapnoShape,
|
||||
// These affect display only; the underlying physiological signals continue.
|
||||
pub show_ecg: bool,
|
||||
pub show_spo2: bool,
|
||||
pub show_art: bool,
|
||||
pub show_capno: bool,
|
||||
pub show_nibp: bool,
|
||||
}
|
||||
|
||||
impl Default for Parameters {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
ecg_rhythm: EcgRhythm::Sinus,
|
||||
heart_rate: 75,
|
||||
pulse_conduction: PulseConduction::OneToOne,
|
||||
spo2: 98,
|
||||
art_systolic: 120,
|
||||
art_diastolic: 75,
|
||||
arterial_shape: ArterialShape::Normal,
|
||||
pulse_pressure_variation: 0,
|
||||
nibp_systolic: 118,
|
||||
nibp_diastolic: 74,
|
||||
etco2: 38,
|
||||
respiratory_rate: 14,
|
||||
capno_shape: CapnoShape::Normal,
|
||||
show_ecg: true,
|
||||
show_spo2: true,
|
||||
show_art: true,
|
||||
show_capno: true,
|
||||
show_nibp: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 {
|
||||
((systolic as f64 + 2.0 * diastolic as f64) / 3.0).round() as i32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mean_pressure_uses_one_third_pulse_pressure() {
|
||||
assert_eq!(mean_arterial_pressure(120, 75), 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_mechanical_capture_follows_requested_patterns() {
|
||||
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
|
||||
vec![1, 3, 5, 7]);
|
||||
assert_eq!((1..=9).filter(|&b| PulseConduction::ThreeToOne.conducts(b)).collect::<Vec<_>>(),
|
||||
vec![1, 4, 7]);
|
||||
assert!((1..=20).all(|b| PulseConduction::OneToOne.conducts(b)));
|
||||
assert!((1..=20).all(|b| !PulseConduction::None.conducts(b)));
|
||||
}
|
||||
}
|
||||
255
patient-monitor-simulation/src/render.rs
Normal file
255
patient-monitor-simulation/src/render.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
//! 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::simulation::{Sample, Simulator};
|
||||
|
||||
type Color = (f64, f64, f64);
|
||||
const BG: Color = (0.0, 0.0, 0.0);
|
||||
const GREEN: Color = (0.26, 1.0, 0.39);
|
||||
const YELLOW: Color = (1.0, 0.85, 0.17);
|
||||
const RED: Color = (1.0, 0.30, 0.31);
|
||||
const LIGHT_GREY: Color = (0.80, 0.84, 0.87);
|
||||
const MUTED: Color = (0.42, 0.46, 0.49);
|
||||
const GRID: Color = (0.10, 0.14, 0.13);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Channel { Ecg, Pleth, Art, Capno }
|
||||
|
||||
fn visible_channels(p: &Parameters) -> Vec<(Channel, &'static str, Color)> {
|
||||
let mut channels = Vec::with_capacity(4);
|
||||
if p.show_ecg { channels.push((Channel::Ecg, "II / ECG", GREEN)); }
|
||||
if p.show_spo2 { channels.push((Channel::Pleth, "SpO₂ / PLETH", YELLOW)); }
|
||||
if p.show_art { channels.push((Channel::Art, "ART", RED)); }
|
||||
if p.show_capno { channels.push((Channel::Capno, "CO₂", LIGHT_GREY)); }
|
||||
channels
|
||||
}
|
||||
|
||||
pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulator) {
|
||||
let w = f64::from(width.max(1));
|
||||
let h = f64::from(height.max(1));
|
||||
set_color(cr, BG);
|
||||
let _ = cr.paint();
|
||||
|
||||
let pad = (w.min(h) * 0.018).clamp(6.0, 20.0);
|
||||
let header = (h * 0.083).clamp(32.0, 68.0);
|
||||
let footer = if p.show_nibp { (h * 0.13).clamp(52.0, 102.0) } else { 0.0 };
|
||||
let channels = visible_channels(p);
|
||||
let row_height = ((h - header - footer - pad).max(20.0))
|
||||
/ (channels.len().max(1) as f64);
|
||||
let sidebar = (w * 0.235).clamp(125.0, 370.0).min(w * 0.44);
|
||||
let split_x = w - sidebar - pad;
|
||||
let trace_left = pad + 6.0;
|
||||
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);
|
||||
if w >= 850.0 {
|
||||
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
|
||||
11.0 * text_scale, MUTED, false);
|
||||
}
|
||||
stroke_line(cr, pad, header, w - pad, header, MUTED, 0.8);
|
||||
stroke_line(cr, split_x, header, split_x, h - footer, MUTED, 0.9);
|
||||
|
||||
for (index, (channel, title, color)) in channels.iter().copied().enumerate() {
|
||||
let top = header + index as f64 * row_height;
|
||||
let bottom = top + row_height;
|
||||
stroke_line(cr, pad, bottom, w - pad, bottom, MUTED, 0.65);
|
||||
text(cr, title, trace_left + 4.0, top + row_height * 0.17,
|
||||
(row_height * 0.11).clamp(10.0, 17.0), color, false);
|
||||
draw_trace(cr, channel, color, trace_left, trace_right,
|
||||
top + row_height * 0.25, bottom - row_height * 0.06, p, sim);
|
||||
draw_vitals(cr, channel, color, split_x + pad,
|
||||
top, row_height, sidebar - 2.0 * pad, p, sim);
|
||||
}
|
||||
|
||||
if p.show_nibp {
|
||||
let footer_top = h - footer;
|
||||
text(cr, "NIBP", pad + 6.0, footer_top + footer * 0.32,
|
||||
(footer * 0.21).clamp(12.0, 20.0), LIGHT_GREY, false);
|
||||
text(cr, &format!("{} / {}", p.nibp_systolic, p.nibp_diastolic),
|
||||
pad + 6.0, footer_top + footer * 0.77,
|
||||
(footer * 0.42).clamp(20.0, 44.0), LIGHT_GREY, true);
|
||||
if w >= 510.0 {
|
||||
text(cr, &format!("({}) mmHg", mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic)),
|
||||
pad + (w * 0.28).min(260.0), footer_top + footer * 0.73,
|
||||
(footer * 0.24).clamp(12.0, 23.0), LIGHT_GREY, false);
|
||||
}
|
||||
if w >= 1020.0 {
|
||||
text(cr, "SYNTHETIC SIGNALS · NOT FOR CLINICAL USE",
|
||||
w * 0.56, footer_top + footer * 0.68,
|
||||
10.0 * text_scale, MUTED, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
let has_capture = p.ecg_rhythm.has_qrs()
|
||||
&& p.heart_rate > 0
|
||||
&& p.pulse_conduction != PulseConduction::None;
|
||||
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
|
||||
let (label, value, info) = match ch {
|
||||
Channel::Ecg => (
|
||||
"HR",
|
||||
if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() }
|
||||
else { p.heart_rate.to_string() },
|
||||
format!("bpm · {}", match p.ecg_rhythm {
|
||||
EcgRhythm::Sinus => "Sinus",
|
||||
EcgRhythm::AtrialFibrillation => "AF",
|
||||
EcgRhythm::VentricularTachycardia => "VT",
|
||||
EcgRhythm::VentricularFibrillation => "VF",
|
||||
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::Art => (
|
||||
"ART",
|
||||
if pulse_rate.is_some() {
|
||||
format!("{}/{}", p.art_systolic, p.art_diastolic)
|
||||
} else { "--/--".to_owned() },
|
||||
if pulse_rate.is_some() {
|
||||
if p.pulse_pressure_variation > 0 {
|
||||
format!("MAP {} · PPV {}%",
|
||||
mean_arterial_pressure(p.art_systolic, p.art_diastolic),
|
||||
p.pulse_pressure_variation)
|
||||
} else {
|
||||
format!("MAP {} mmHg", mean_arterial_pressure(p.art_systolic, p.art_diastolic))
|
||||
}
|
||||
} else { "MAP -- mmHg".to_owned() },
|
||||
),
|
||||
Channel::Capno => ("EtCO₂", 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, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_trace(cr: &Context, channel: Channel, color: Color,
|
||||
left: f64, right: f64, top: f64, bottom: f64,
|
||||
p: &Parameters, sim: &Simulator) {
|
||||
// ART is shown on an absolute fixed-pressure axis (0..200 mmHg),
|
||||
// unlike the automatically normalized ECG, pleth and CO2 traces.
|
||||
let axis_width = if matches!(channel, Channel::Art) { 36.0 } else { 0.0 };
|
||||
let plot_left = left + axis_width;
|
||||
let trace_width = (right - plot_left).max(1.0);
|
||||
let trace_height = (bottom - top).max(1.0);
|
||||
const VISIBLE_SECONDS: f64 = 8.0;
|
||||
let last_t = sim.samples().back().map(|s| s.time).unwrap_or(0.0);
|
||||
let start_t = last_t - VISIBLE_SECONDS;
|
||||
|
||||
let _ = cr.save();
|
||||
cr.rectangle(left, top, right - left, trace_height);
|
||||
cr.clip();
|
||||
|
||||
// A subtle grid, one vertical division per second.
|
||||
for second in (start_t.ceil() as i64)..=(last_t.floor() as i64) {
|
||||
let x = right - (last_t - second as f64) / VISIBLE_SECONDS * trace_width;
|
||||
stroke_line(cr, x, top, x, bottom, GRID, 0.75);
|
||||
}
|
||||
if matches!(channel, Channel::Art) {
|
||||
for pressure in (0..=200).step_by(50) {
|
||||
let y = bottom - pressure as f64 / 200.0 * trace_height;
|
||||
stroke_line(cr, plot_left, y, right, y, GRID, 0.8);
|
||||
// Right-align tick labels against the axis.
|
||||
let label = pressure.to_string();
|
||||
let label_offset = if pressure >= 100 { 23.0 } else if pressure >= 10 { 17.0 } else { 10.0 };
|
||||
text(cr, &label, plot_left - label_offset, (y + 3.0).max(top + 9.0).min(bottom),
|
||||
9.5, MUTED, false);
|
||||
}
|
||||
stroke_line(cr, plot_left, top, plot_left, bottom, MUTED, 0.75);
|
||||
} else {
|
||||
stroke_line(cr, left, top + trace_height * 0.5,
|
||||
right, top + trace_height * 0.5, GRID, 0.7);
|
||||
}
|
||||
|
||||
set_color(cr, color);
|
||||
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
|
||||
cr.set_line_cap(LineCap::Round);
|
||||
cr.set_line_join(LineJoin::Round);
|
||||
let mut started = false;
|
||||
for s in sim.samples().iter().filter(|s| s.time >= start_t) {
|
||||
let x = right - (last_t - s.time) / VISIBLE_SECONDS * trace_width;
|
||||
let amplitude = normalized(channel, s, p);
|
||||
let y = bottom - amplitude * trace_height;
|
||||
if started { cr.line_to(x, y); }
|
||||
else { cr.move_to(x, y); started = true; }
|
||||
}
|
||||
if started { let _ = cr.stroke(); }
|
||||
let _ = cr.restore();
|
||||
}
|
||||
|
||||
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::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),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_color(cr: &Context, c: Color) {
|
||||
cr.set_source_rgb(c.0, c.1, c.2);
|
||||
}
|
||||
|
||||
fn stroke_line(cr: &Context, x1: f64, y1: f64, x2: f64, y2: f64,
|
||||
color: Color, width: f64) {
|
||||
set_color(cr, color);
|
||||
cr.set_line_width(width);
|
||||
cr.move_to(x1, y1);
|
||||
cr.line_to(x2, y2);
|
||||
let _ = cr.stroke();
|
||||
}
|
||||
|
||||
fn text(cr: &Context, value: &str, x: f64, baseline: f64,
|
||||
size: f64, color: Color, bold: bool) {
|
||||
set_color(cr, color);
|
||||
cr.select_font_face("Sans", FontSlant::Normal,
|
||||
if bold { FontWeight::Bold } else { FontWeight::Normal });
|
||||
cr.set_font_size(size);
|
||||
cr.move_to(x, baseline);
|
||||
let _ = cr.show_text(value);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn toggled_channels_disappear_and_remaining_rows_reflow() {
|
||||
let mut p = Parameters::default();
|
||||
assert_eq!(visible_channels(&p).len(), 4);
|
||||
p.show_ecg = false;
|
||||
p.show_art = false;
|
||||
assert_eq!(visible_channels(&p).len(), 2);
|
||||
assert!(matches!(visible_channels(&p)[0].0, Channel::Pleth));
|
||||
assert!(matches!(visible_channels(&p)[1].0, Channel::Capno));
|
||||
p.show_spo2 = false;
|
||||
p.show_capno = false;
|
||||
assert!(visible_channels(&p).is_empty());
|
||||
}
|
||||
|
||||
#[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 };
|
||||
assert_eq!(normalized(Channel::Art, &s, &p), 0.5);
|
||||
s.art = 200.0;
|
||||
assert_eq!(normalized(Channel::Art, &s, &p), 1.0);
|
||||
s.art = 0.0;
|
||||
assert_eq!(normalized(Channel::Art, &s, &p), 0.0);
|
||||
}
|
||||
}
|
||||
479
patient-monitor-simulation/src/simulation.rs
Normal file
479
patient-monitor-simulation/src/simulation.rs
Normal file
|
|
@ -0,0 +1,479 @@
|
|||
//! Event-driven synthetic QRS, mechanical pulse and respiratory generation.
|
||||
//! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse.
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
|
||||
|
||||
const SAMPLE_STEP: f64 = 0.01; // 100 Hz
|
||||
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
|
||||
const PLETH_FILTER_TAU: f64 = 0.16; // seconds: deliberately strong damping
|
||||
const QRS_PHASE: f64 = 0.335;
|
||||
|
||||
/// One mechanically conducted QRS. Respiratory modulation is sampled on the
|
||||
/// beat, so pressure varies from beat to beat rather than within a single beat.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ConductedBeat {
|
||||
qrs_time: f64,
|
||||
pulse_pressure_scale: f64,
|
||||
}
|
||||
|
||||
/// PPV = 100 * (PPmax - PPmin) / ((PPmax + PPmin) / 2).
|
||||
/// For a requested PPV of 20%, pulse pressure oscillates between 90% and 110%
|
||||
/// of its nominal value over one respiratory cycle.
|
||||
fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
|
||||
1.0 + (ppv_percent.clamp(0, 60) as f64 / 200.0)
|
||||
* (std::f64::consts::TAU * respiratory_phase).sin()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Sample {
|
||||
pub time: f64,
|
||||
pub ecg: f64, // arbitrary amplitude
|
||||
pub pleth: f64, // attenuated, low-pass-filtered amplitude 0..1
|
||||
pub art: f64, // absolute pressure in mmHg; display clips above 200
|
||||
pub co2: f64, // mmHg
|
||||
}
|
||||
|
||||
pub struct Simulator {
|
||||
samples: VecDeque<Sample>,
|
||||
time: f64,
|
||||
ecg_phase: f64,
|
||||
respiratory_phase: f64,
|
||||
ecg_beat_number: u64,
|
||||
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
|
||||
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
|
||||
filtered_pleth: f64,
|
||||
previous_rhythm: EcgRhythm,
|
||||
previous_conduction: PulseConduction,
|
||||
previous_heart_rate: i32,
|
||||
pending_time: f64,
|
||||
}
|
||||
|
||||
impl Simulator {
|
||||
pub fn new(params: &Parameters) -> Self {
|
||||
let mut sim = Self {
|
||||
samples: VecDeque::with_capacity(1_100),
|
||||
time: -8.0,
|
||||
ecg_phase: 0.0,
|
||||
respiratory_phase: 0.0,
|
||||
ecg_beat_number: 0,
|
||||
conducted_qrs: VecDeque::new(),
|
||||
rate_qrs: VecDeque::new(),
|
||||
filtered_pleth: 0.0,
|
||||
previous_rhythm: params.ecg_rhythm,
|
||||
previous_conduction: params.pulse_conduction,
|
||||
previous_heart_rate: params.heart_rate,
|
||||
pending_time: 0.0,
|
||||
};
|
||||
// Prepopulate the trace and pulse history, including the initial pulse rate.
|
||||
for _ in 0..800 {
|
||||
sim.step(params);
|
||||
}
|
||||
sim
|
||||
}
|
||||
|
||||
pub fn advance(&mut self, elapsed_seconds: f64, params: &Parameters) {
|
||||
// Cap huge steps after a suspended/minimized window.
|
||||
self.pending_time += elapsed_seconds.clamp(0.0, 0.1);
|
||||
while self.pending_time >= SAMPLE_STEP {
|
||||
self.step(params);
|
||||
self.pending_time -= SAMPLE_STEP;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn samples(&self) -> &VecDeque<Sample> {
|
||||
&self.samples
|
||||
}
|
||||
|
||||
/// Average of recent *mechanically captured* beat intervals, not an independent setting.
|
||||
pub fn pulse_rate(&self) -> Option<i32> {
|
||||
if self.rate_qrs.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let end = self.rate_qrs.len() - 1;
|
||||
// Use the last three intervals, so PR settles rapidly after a rate change.
|
||||
let start = end.saturating_sub(3);
|
||||
let first = self.rate_qrs[start];
|
||||
let last = self.rate_qrs[end];
|
||||
// Suppress stale pulse values after a prolonged period without capture.
|
||||
if self.time - last > 12.0 || last <= first {
|
||||
return None;
|
||||
}
|
||||
Some((((end - start) as f64 * 60.0) / (last - first)).round() as i32)
|
||||
}
|
||||
|
||||
fn step(&mut self, params: &Parameters) {
|
||||
self.time += SAMPLE_STEP;
|
||||
|
||||
if params.ecg_rhythm != self.previous_rhythm
|
||||
|| params.pulse_conduction != self.previous_conduction
|
||||
|| !params.ecg_rhythm.has_qrs()
|
||||
|| params.pulse_conduction == PulseConduction::None
|
||||
|| params.heart_rate <= 0
|
||||
{
|
||||
// A rhythm/capture change terminates previously queued mechanical events.
|
||||
self.conducted_qrs.clear();
|
||||
self.rate_qrs.clear();
|
||||
self.filtered_pleth = 0.0;
|
||||
self.previous_rhythm = params.ecg_rhythm;
|
||||
self.previous_conduction = params.pulse_conduction;
|
||||
}
|
||||
if params.heart_rate != self.previous_heart_rate {
|
||||
// Old captured events remain in the *waveforms* until they pass.
|
||||
// They must not bias the pulse rate after an HR slider change.
|
||||
self.rate_qrs.clear();
|
||||
self.previous_heart_rate = params.heart_rate;
|
||||
}
|
||||
|
||||
// Respiratory phase drives both the capnogram and arterial PPV.
|
||||
let respiratory_rate = params.respiratory_rate.max(0) as f64 / 60.0;
|
||||
self.respiratory_phase = (self.respiratory_phase + SAMPLE_STEP * respiratory_rate).fract();
|
||||
|
||||
if params.ecg_rhythm.has_qrs() && params.heart_rate > 0 {
|
||||
let irregularity = if params.ecg_rhythm == EcgRhythm::AtrialFibrillation {
|
||||
// Reproducible irregular R-R durations.
|
||||
let x = (self.ecg_beat_number.wrapping_mul(1_103_515_245)
|
||||
.wrapping_add(12_345) % 997) as f64 / 997.0;
|
||||
0.65 + x * 0.70
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
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.
|
||||
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) {
|
||||
let pulse_pressure_scale = if params.respiratory_rate > 0 {
|
||||
ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase)
|
||||
} else {
|
||||
1.0 // no respiratory swing during apnea
|
||||
};
|
||||
self.conducted_qrs.push_back(ConductedBeat { qrs_time, pulse_pressure_scale });
|
||||
self.rate_qrs.push_back(qrs_time);
|
||||
}
|
||||
}
|
||||
self.ecg_phase = next_phase.fract();
|
||||
} else {
|
||||
self.ecg_phase = 0.0;
|
||||
}
|
||||
|
||||
// Preserve up to 30s of delivered events for stable derived PR calculations.
|
||||
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
|
||||
self.conducted_qrs.pop_front();
|
||||
}
|
||||
while self.rate_qrs.front().is_some_and(|&qrs| qrs < self.time - 30.0) {
|
||||
self.rate_qrs.pop_front();
|
||||
}
|
||||
|
||||
let ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate);
|
||||
let (art, pleth_target) = self.mechanical_signals(params);
|
||||
let smoothing = 1.0 - (-SAMPLE_STEP / PLETH_FILTER_TAU).exp();
|
||||
self.filtered_pleth += smoothing * (pleth_target - self.filtered_pleth);
|
||||
let pleth = self.filtered_pleth.clamp(0.0, 1.0);
|
||||
let co2 = params.etco2.max(0) as f64
|
||||
* if params.respiratory_rate <= 0 { 0.0 } else {
|
||||
capno_amplitude(self.respiratory_phase, params.capno_shape)
|
||||
};
|
||||
|
||||
self.samples.push_back(Sample { time: self.time, ecg, pleth, art, co2 });
|
||||
while self.samples.front().is_some_and(|first| first.time < self.time - HISTORY_SECONDS) {
|
||||
self.samples.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
fn mechanical_signals(&self, params: &Parameters) -> (f64, f64) {
|
||||
let systolic = params.art_systolic.clamp(0, 200) as f64;
|
||||
let diastolic = params.art_diastolic.clamp(0, 200).min(params.art_systolic.clamp(0, 200)) as f64;
|
||||
let pulse_pressure = (systolic - diastolic).max(0.0);
|
||||
|
||||
let mut latest_art_age: Option<f64> = None;
|
||||
let mut art_peak: f64 = 0.0;
|
||||
let mut pleth_peak: f64 = 0.0;
|
||||
for beat in &self.conducted_qrs {
|
||||
let art_age = self.time - beat.qrs_time - ART_DELAY;
|
||||
if art_age >= 0.0 {
|
||||
latest_art_age = Some(art_age);
|
||||
art_peak = art_peak.max(
|
||||
arterial_amplitude(art_age, params.arterial_shape)
|
||||
* beat.pulse_pressure_scale,
|
||||
);
|
||||
}
|
||||
let pleth_age = self.time - beat.qrs_time - PLETH_DELAY;
|
||||
if pleth_age >= 0.0 {
|
||||
pleth_peak = pleth_peak.max(pleth_amplitude(pleth_age));
|
||||
}
|
||||
}
|
||||
|
||||
let art = 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();
|
||||
(baseline + pulse_pressure * art_peak).clamp(0.0, 250.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
(art, pleth_peak)
|
||||
}
|
||||
}
|
||||
|
||||
fn gaussian(x: f64, center: f64, width: f64) -> f64 {
|
||||
let d = (x - center) / width;
|
||||
(-0.5 * d * d).exp()
|
||||
}
|
||||
|
||||
fn phase_gaussian(phase: f64, center: f64, width: f64) -> f64 {
|
||||
let distance = (phase - center + 0.5).rem_euclid(1.0) - 0.5;
|
||||
gaussian(distance, 0.0, width)
|
||||
}
|
||||
|
||||
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.
|
||||
return 0.29 * (time * 42.1 + 0.40 * (time * 3.1).sin()).sin()
|
||||
+ 0.22 * (time * 57.2 + 0.57 * (time * 5.7).sin()).sin()
|
||||
+ 0.14 * (time * 31.4).sin();
|
||||
}
|
||||
if heart_rate <= 0 || rhythm == EcgRhythm::Asystole {
|
||||
return 0.006 * (time * 9.3).sin();
|
||||
}
|
||||
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)
|
||||
}
|
||||
EcgRhythm::AtrialFibrillation => {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
EcgRhythm::VentricularFibrillation | EcgRhythm::Asystole => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn arterial_amplitude(age: f64, shape: ArterialShape) -> f64 {
|
||||
if age < 0.0 { return 0.0; }
|
||||
let value = match shape {
|
||||
ArterialShape::Normal => {
|
||||
let envelope = if age < 0.13 { (age / 0.13).powf(1.8) }
|
||||
else { (-(age - 0.13) / 0.25).exp() };
|
||||
envelope - 0.12 * gaussian(age, 0.35, 0.023)
|
||||
+ 0.055 * gaussian(age, 0.43, 0.045)
|
||||
}
|
||||
ArterialShape::Damped => {
|
||||
let envelope = if age < 0.22 { (age / 0.22).powf(1.3) }
|
||||
else { (-(age - 0.22) / 0.39).exp() };
|
||||
envelope * 0.82
|
||||
}
|
||||
ArterialShape::Hyperdynamic => {
|
||||
let envelope = if age < 0.085 { (age / 0.085).powf(1.9) }
|
||||
else { (-(age - 0.085) / 0.18).exp() };
|
||||
envelope - 0.16 * gaussian(age, 0.27, 0.022)
|
||||
+ 0.095 * gaussian(age, 0.36, 0.034)
|
||||
}
|
||||
};
|
||||
value.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
fn pleth_amplitude(age: f64) -> f64 {
|
||||
if age < 0.0 { return 0.0; }
|
||||
// Heavily attenuated, broad pulse, without a prominent dicrotic notch.
|
||||
0.75 * (1.0 - (-age / 0.13).exp()) * (-age / 0.48).exp()
|
||||
}
|
||||
|
||||
fn capno_amplitude(phase: f64, shape: CapnoShape) -> f64 {
|
||||
match shape {
|
||||
CapnoShape::Normal => {
|
||||
if phase < 0.30 { 0.0 }
|
||||
else if phase < 0.38 { (phase - 0.30) / 0.08 * 0.92 }
|
||||
else if phase < 0.76 { 0.92 + 0.08 * ((phase - 0.38) / 0.38) }
|
||||
else if phase < 0.82 { 1.0 - (phase - 0.76) / 0.06 }
|
||||
else { 0.0 }
|
||||
}
|
||||
CapnoShape::Obstructive => {
|
||||
if phase < 0.28 { 0.0 }
|
||||
else if phase < 0.76 { ((phase - 0.28) / 0.48).powf(0.68) }
|
||||
else if phase < 0.83 { 1.0 - (phase - 0.76) / 0.07 }
|
||||
else { 0.0 }
|
||||
}
|
||||
}.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn blank(p: &Parameters) -> Simulator {
|
||||
let mut sim = Simulator::new(p);
|
||||
sim.samples.clear();
|
||||
sim.conducted_qrs.clear();
|
||||
sim.rate_qrs.clear();
|
||||
sim.time = 0.0;
|
||||
sim.ecg_phase = 0.0;
|
||||
sim.ecg_beat_number = 0;
|
||||
sim.filtered_pleth = 0.0;
|
||||
sim
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signals_remain_in_expected_ranges() {
|
||||
let p = Parameters::default();
|
||||
let mut sim = Simulator::new(&p);
|
||||
sim.advance(0.1, &p);
|
||||
assert!(sim.samples().len() >= 800);
|
||||
for s in sim.samples() {
|
||||
assert!((0.0..=1.0).contains(&s.pleth));
|
||||
assert!((0.0..=250.0).contains(&s.art));
|
||||
assert!((0.0..=f64::from(p.etco2)).contains(&s.co2));
|
||||
assert!(s.ecg.is_finite());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qrs_triggers_delayed_art_and_later_pleth() {
|
||||
let p = Parameters::default();
|
||||
let mut sim = blank(&p);
|
||||
while sim.conducted_qrs.is_empty() { sim.step(&p); }
|
||||
let qrs = sim.conducted_qrs.back().unwrap().qrs_time;
|
||||
let art_before = sim.samples.back().unwrap().art;
|
||||
assert_eq!(art_before, 0.0);
|
||||
while sim.time < qrs + ART_DELAY + 0.13 { sim.step(&p); }
|
||||
assert!(sim.samples.back().unwrap().art > p.art_diastolic as f64);
|
||||
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
|
||||
while sim.time < qrs + PLETH_DELAY + 0.20 { sim.step(&p); }
|
||||
assert!(sim.samples.back().unwrap().pleth > 0.03);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asystole_and_vf_and_pea_produce_no_mechanical_pulses() {
|
||||
for (rhythm, capture) in [
|
||||
(EcgRhythm::Asystole, PulseConduction::OneToOne),
|
||||
(EcgRhythm::VentricularFibrillation, 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));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_to_pea_cancels_existing_pulses_immediately() {
|
||||
let mut p = Parameters::default();
|
||||
let mut sim = Simulator::new(&p);
|
||||
assert!(sim.pulse_rate().is_some());
|
||||
p.pulse_conduction = PulseConduction::None;
|
||||
sim.step(&p);
|
||||
assert!(sim.pulse_rate().is_none());
|
||||
assert_eq!(sim.samples.back().unwrap().art, 0.0);
|
||||
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pulse_rate_follows_two_to_one_capture() {
|
||||
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };
|
||||
let mut sim = blank(&p);
|
||||
for _ in 0..1_400 { sim.step(&p); }
|
||||
// 75 QRS/min, with every second QRS producing a pulse = 37.5/min.
|
||||
assert_eq!(sim.pulse_rate(), Some(38));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pulse_rate_follows_three_to_one_capture() {
|
||||
let p = Parameters { pulse_conduction: PulseConduction::ThreeToOne, ..Parameters::default() };
|
||||
let mut sim = blank(&p);
|
||||
for _ in 0..1_400 { sim.step(&p); }
|
||||
assert_eq!(sim.pulse_rate(), Some(25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pulse_rate_updates_when_heart_rate_slider_changes() {
|
||||
let mut p = Parameters::default();
|
||||
let mut sim = Simulator::new(&p);
|
||||
assert_eq!(sim.pulse_rate(), Some(75));
|
||||
p.heart_rate = 189;
|
||||
sim.step(&p);
|
||||
// No old 75 bpm PR is displayed while the new beat interval is measured.
|
||||
assert_eq!(sim.pulse_rate(), None);
|
||||
for _ in 0..200 { sim.step(&p); }
|
||||
assert_eq!(sim.pulse_rate(), Some(189));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rate_respects_two_to_one_mechanical_capture() {
|
||||
let mut p = Parameters::default();
|
||||
let mut sim = Simulator::new(&p);
|
||||
p.heart_rate = 180;
|
||||
p.pulse_conduction = PulseConduction::TwoToOne;
|
||||
for _ in 0..400 { sim.step(&p); }
|
||||
assert_eq!(sim.pulse_rate(), Some(90));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asystole_is_flat_and_vf_has_waveform_without_qrs() {
|
||||
assert!(ecg_amplitude(0.335, 2.0, EcgRhythm::Asystole, 75).abs() < 0.01);
|
||||
assert!(ecg_amplitude(0.335, 2.0, EcgRhythm::VentricularFibrillation, 75).abs() > 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ppv_produces_requested_peak_to_trough_pulse_pressure_change() {
|
||||
let max_scale = ppv_multiplier(20, 0.25);
|
||||
let min_scale = ppv_multiplier(20, 0.75);
|
||||
assert!((max_scale - 1.10).abs() < 1e-12);
|
||||
assert!((min_scale - 0.90).abs() < 1e-12);
|
||||
let calculated_ppv = 100.0 * (max_scale - min_scale) / ((max_scale + min_scale) / 2.0);
|
||||
assert!((calculated_ppv - 20.0).abs() < 1e-10);
|
||||
assert_eq!(ppv_multiplier(0, 0.25), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn respiratory_phase_modulates_arterial_pulses_not_pleth() {
|
||||
let p = Parameters::default();
|
||||
let mut sim = blank(&p);
|
||||
sim.time = ART_DELAY + 0.13;
|
||||
sim.conducted_qrs.push_back(ConductedBeat {
|
||||
qrs_time: 0.0, pulse_pressure_scale: 1.2,
|
||||
});
|
||||
let (art_high, pleth_high) = sim.mechanical_signals(&p);
|
||||
sim.conducted_qrs.front_mut().unwrap().pulse_pressure_scale = 0.8;
|
||||
let (art_low, pleth_low) = sim.mechanical_signals(&p);
|
||||
assert!(art_high > art_low);
|
||||
assert_eq!(pleth_high, pleth_low);
|
||||
assert!(art_low > f64::from(p.art_diastolic));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apnea_suppresses_ppv_and_hidden_ecg_does_not_suppress_pulses() {
|
||||
let p = Parameters {
|
||||
pulse_pressure_variation: 40,
|
||||
respiratory_rate: 0,
|
||||
show_ecg: false,
|
||||
..Parameters::default()
|
||||
};
|
||||
let sim = Simulator::new(&p);
|
||||
assert!(sim.conducted_qrs.iter().all(|b| b.pulse_pressure_scale == 1.0));
|
||||
assert!(sim.pulse_rate().is_some());
|
||||
assert!(sim.samples().iter().any(|s| s.art > 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capnogram_reaches_etco2_plateau() {
|
||||
assert!((capno_amplitude(0.76, CapnoShape::Normal) - 1.0).abs() < 1e-8);
|
||||
}
|
||||
}
|
||||
326
patient-monitor-simulation/src/ui.rs
Normal file
326
patient-monitor-simulation/src/ui.rs
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
//! GTK4 Admin and Monitor windows; all callbacks run on the GTK main thread.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Instant;
|
||||
|
||||
use gtk::gdk;
|
||||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{Application, ApplicationWindow, Orientation};
|
||||
|
||||
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
|
||||
use crate::render;
|
||||
use crate::simulation::Simulator;
|
||||
|
||||
type SharedParams = Rc<RefCell<Parameters>>;
|
||||
|
||||
pub fn create_windows(app: &Application) {
|
||||
let parameters = Rc::new(RefCell::new(Parameters::default()));
|
||||
let simulator = Rc::new(RefCell::new(Simulator::new(¶meters.borrow())));
|
||||
let monitor = create_monitor(app, parameters.clone(), simulator);
|
||||
let admin = create_admin(app, parameters, &monitor);
|
||||
|
||||
// Present monitor first, then leave controls in the foreground.
|
||||
monitor.present();
|
||||
admin.present();
|
||||
}
|
||||
|
||||
fn create_monitor(app: &Application, params: SharedParams,
|
||||
simulator: Rc<RefCell<Simulator>>) -> ApplicationWindow {
|
||||
let window = ApplicationWindow::builder()
|
||||
.application(app)
|
||||
.title(concat!("Patient Monitor — Simulation v", env!("CARGO_PKG_VERSION")))
|
||||
.default_width(1200)
|
||||
.default_height(760)
|
||||
.build();
|
||||
|
||||
let canvas = gtk::DrawingArea::new();
|
||||
canvas.set_hexpand(true);
|
||||
canvas.set_vexpand(true);
|
||||
canvas.set_draw_func({
|
||||
let params = params.clone();
|
||||
let simulator = simulator.clone();
|
||||
move |_area, cr, width, height| {
|
||||
let config = *params.borrow();
|
||||
render::draw(cr, width, height, &config, &simulator.borrow());
|
||||
}
|
||||
});
|
||||
|
||||
// Synchronize simulation time with frame updates; synthesize at 100 Hz.
|
||||
let previous = Rc::new(Cell::new(Instant::now()));
|
||||
canvas.add_tick_callback({
|
||||
let params = params.clone();
|
||||
move |area, _frame_clock| {
|
||||
let now = Instant::now();
|
||||
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();
|
||||
previous.set(now);
|
||||
let config = *params.borrow();
|
||||
simulator.borrow_mut().advance(elapsed, &config);
|
||||
area.queue_draw();
|
||||
glib::ControlFlow::Continue
|
||||
}
|
||||
});
|
||||
|
||||
let keys = gtk::EventControllerKey::new();
|
||||
let for_keys = window.clone();
|
||||
keys.connect_key_pressed(move |_, key, _, _| {
|
||||
if key == gdk::Key::F11 {
|
||||
if for_keys.is_fullscreen() { for_keys.unfullscreen(); }
|
||||
else { for_keys.fullscreen(); }
|
||||
glib::Propagation::Stop
|
||||
} else if key == gdk::Key::Escape && for_keys.is_fullscreen() {
|
||||
for_keys.unfullscreen();
|
||||
glib::Propagation::Stop
|
||||
} else {
|
||||
glib::Propagation::Proceed
|
||||
}
|
||||
});
|
||||
window.add_controller(keys);
|
||||
window.set_child(Some(&canvas));
|
||||
window
|
||||
}
|
||||
|
||||
fn create_admin(app: &Application, params: SharedParams,
|
||||
monitor: &ApplicationWindow) -> ApplicationWindow {
|
||||
let window = ApplicationWindow::builder()
|
||||
.application(app)
|
||||
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
|
||||
.default_width(600)
|
||||
.default_height(790)
|
||||
.build();
|
||||
|
||||
let main_box = gtk::Box::new(Orientation::Vertical, 10);
|
||||
main_box.set_margin_top(12);
|
||||
main_box.set_margin_bottom(12);
|
||||
main_box.set_margin_start(12);
|
||||
main_box.set_margin_end(12);
|
||||
|
||||
let header = gtk::Label::new(Some("Patient Monitor Simulation — Teaching Controls"));
|
||||
header.set_xalign(0.0);
|
||||
main_box.append(&header);
|
||||
|
||||
let scroller = gtk::ScrolledWindow::new();
|
||||
scroller.set_hexpand(true);
|
||||
scroller.set_vexpand(true);
|
||||
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
|
||||
let controls = gtk::Box::new(Orientation::Vertical, 12);
|
||||
|
||||
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",
|
||||
], params.clone(), |p, selected| {
|
||||
p.ecg_rhythm = match selected {
|
||||
1 => EcgRhythm::AtrialFibrillation,
|
||||
2 => EcgRhythm::VentricularTachycardia,
|
||||
3 => EcgRhythm::VentricularFibrillation,
|
||||
4 => EcgRhythm::Asystole,
|
||||
_ => EcgRhythm::Sinus,
|
||||
};
|
||||
});
|
||||
add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
|
||||
params.clone(), |p, v| p.heart_rate = v);
|
||||
|
||||
let spo2 = group(&controls, "Pulse oximetry");
|
||||
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);
|
||||
add_dropdown(&spo2, "Mechanical capture", &[
|
||||
"1:1 (every QRS)",
|
||||
"2:1 (one pulse in two)",
|
||||
"3:1 (one pulse in three)",
|
||||
"None (PEA)",
|
||||
"Random (65% capture)",
|
||||
], params.clone(), |p, selected| {
|
||||
p.pulse_conduction = match selected {
|
||||
1 => PulseConduction::TwoToOne,
|
||||
2 => PulseConduction::ThreeToOne,
|
||||
3 => PulseConduction::None,
|
||||
4 => PulseConduction::Random,
|
||||
_ => PulseConduction::OneToOne,
|
||||
};
|
||||
});
|
||||
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."
|
||||
));
|
||||
conduction_hint.set_xalign(0.0);
|
||||
conduction_hint.set_wrap(true);
|
||||
spo2.append(&conduction_hint);
|
||||
|
||||
let art = group(&controls, "Invasive arterial blood pressure");
|
||||
add_visibility(&art, params.borrow().show_art, params.clone(), |p, show| p.show_art = show);
|
||||
add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
|
||||
params.clone(), |p, v| p.art_systolic = v);
|
||||
add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
|
||||
params.clone(), |p, v| p.art_diastolic = v);
|
||||
add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
|
||||
params.borrow().pulse_pressure_variation, params.clone(),
|
||||
|p, v| p.pulse_pressure_variation = v);
|
||||
let ppv_hint = gtk::Label::new(Some(
|
||||
"Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0."
|
||||
));
|
||||
ppv_hint.set_xalign(0.0);
|
||||
ppv_hint.set_wrap(true);
|
||||
art.append(&ppv_hint);
|
||||
add_dropdown(&art, "Arterial waveform", &[
|
||||
"Normal", "Damped", "Hyperdynamic",
|
||||
], params.clone(), |p, selected| {
|
||||
p.arterial_shape = match selected {
|
||||
1 => ArterialShape::Damped,
|
||||
2 => ArterialShape::Hyperdynamic,
|
||||
_ => ArterialShape::Normal,
|
||||
};
|
||||
});
|
||||
|
||||
let nibp = group(&controls, "Non-invasive blood pressure (NIBP)");
|
||||
add_visibility(&nibp, params.borrow().show_nibp, params.clone(), |p, show| p.show_nibp = show);
|
||||
add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
|
||||
params.clone(), |p, v| p.nibp_systolic = v);
|
||||
add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
|
||||
params.clone(), |p, v| p.nibp_diastolic = v);
|
||||
|
||||
let capno = group(&controls, "Capnography");
|
||||
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
|
||||
add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
|
||||
params.clone(), |p, selected| {
|
||||
p.capno_shape = if selected == 1 { CapnoShape::Obstructive }
|
||||
else { CapnoShape::Normal };
|
||||
});
|
||||
add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
|
||||
params.clone(), |p, v| p.etco2 = v);
|
||||
add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
|
||||
params.clone(), |p, v| p.respiratory_rate = v);
|
||||
|
||||
scroller.set_child(Some(&controls));
|
||||
main_box.append(&scroller);
|
||||
|
||||
let fullscreen = gtk::CheckButton::with_label("Monitor fullscreen (F11 / Esc)");
|
||||
fullscreen.connect_toggled({
|
||||
let monitor = monitor.clone();
|
||||
move |toggle| {
|
||||
if toggle.is_active() && !monitor.is_fullscreen() { monitor.fullscreen(); }
|
||||
else if !toggle.is_active() && monitor.is_fullscreen() { monitor.unfullscreen(); }
|
||||
}
|
||||
});
|
||||
monitor.connect_fullscreened_notify({
|
||||
let fullscreen = fullscreen.clone();
|
||||
move |monitor| fullscreen.set_active(monitor.is_fullscreen())
|
||||
});
|
||||
main_box.append(&fullscreen);
|
||||
|
||||
let hint = gtk::Label::new(Some("Move the monitor to your presentation screen before entering fullscreen.\nSynthetic teaching signals only — not for clinical use."));
|
||||
hint.set_xalign(0.0);
|
||||
hint.set_wrap(true);
|
||||
main_box.append(&hint);
|
||||
|
||||
window.set_child(Some(&main_box));
|
||||
window
|
||||
}
|
||||
|
||||
fn group(parent: >k::Box, title: &str) -> gtk::Box {
|
||||
let frame = gtk::Frame::new(Some(title));
|
||||
let content = gtk::Box::new(Orientation::Vertical, 8);
|
||||
content.set_margin_top(10);
|
||||
content.set_margin_bottom(10);
|
||||
content.set_margin_start(10);
|
||||
content.set_margin_end(10);
|
||||
frame.set_child(Some(&content));
|
||||
parent.append(&frame);
|
||||
content
|
||||
}
|
||||
|
||||
/// Display toggles never change signal generation or ECG-to-pulse coupling.
|
||||
fn add_visibility<F>(parent: >k::Box, initial: bool, params: SharedParams, setter: F)
|
||||
where F: Fn(&mut Parameters, bool) + 'static {
|
||||
let toggle = gtk::CheckButton::with_label("Show on monitor");
|
||||
toggle.set_active(initial);
|
||||
toggle.connect_toggled(move |button| setter(&mut params.borrow_mut(), button.is_active()));
|
||||
parent.append(&toggle);
|
||||
}
|
||||
|
||||
fn add_dropdown<F>(parent: >k::Box, label: &str, items: &[&str],
|
||||
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_hexpand(true);
|
||||
combo.connect_selected_notify(move |combo| {
|
||||
setter(&mut params.borrow_mut(), combo.selected());
|
||||
});
|
||||
row.append(&caption);
|
||||
row.append(&combo);
|
||||
parent.append(&row);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn add_numeric<F>(parent: >k::Box, label: &str, unit: &str,
|
||||
min: i32, max: i32, initial: i32,
|
||||
params: SharedParams, setter: F)
|
||||
where F: Fn(&mut Parameters, i32) + '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 slider = gtk::Scale::with_range(Orientation::Horizontal,
|
||||
f64::from(min), f64::from(max), 1.0);
|
||||
slider.set_draw_value(false);
|
||||
slider.set_digits(0);
|
||||
slider.set_hexpand(true);
|
||||
slider.set_value(f64::from(initial));
|
||||
|
||||
let entry = gtk::Entry::new();
|
||||
entry.set_width_chars(5);
|
||||
entry.set_max_width_chars(5);
|
||||
entry.set_text(&initial.to_string());
|
||||
entry.set_input_purpose(gtk::InputPurpose::Digits);
|
||||
|
||||
slider.connect_value_changed({
|
||||
let entry = entry.clone();
|
||||
move |slider| {
|
||||
let v = slider.value().round() as i32;
|
||||
setter(&mut params.borrow_mut(), v);
|
||||
// Do not overwrite a partially typed number while the entry has focus.
|
||||
if !entry.has_focus() { entry.set_text(&v.to_string()); }
|
||||
}
|
||||
});
|
||||
entry.connect_changed({
|
||||
let slider = slider.clone();
|
||||
move |entry| {
|
||||
if let Ok(v) = entry.text().parse::<i32>() {
|
||||
if (min..=max).contains(&v) { slider.set_value(f64::from(v)); }
|
||||
}
|
||||
}
|
||||
});
|
||||
entry.connect_activate({
|
||||
let slider = slider.clone();
|
||||
move |entry| normalize_entry(entry, &slider, min, max)
|
||||
});
|
||||
entry.connect_has_focus_notify({
|
||||
let slider = slider.clone();
|
||||
move |entry| {
|
||||
if !entry.has_focus() { normalize_entry(entry, &slider, min, max); }
|
||||
}
|
||||
});
|
||||
|
||||
let suffix = gtk::Label::new(Some(unit));
|
||||
suffix.set_width_chars(5);
|
||||
suffix.set_xalign(0.0);
|
||||
row.append(&caption);
|
||||
row.append(&slider);
|
||||
row.append(&entry);
|
||||
row.append(&suffix);
|
||||
parent.append(&row);
|
||||
}
|
||||
|
||||
fn normalize_entry(entry: >k::Entry, slider: >k::Scale, min: i32, max: i32) {
|
||||
let parsed = entry.text().parse::<i32>().ok();
|
||||
let value = parsed.map(|v| v.clamp(min, max))
|
||||
.unwrap_or_else(|| slider.value().round() as i32);
|
||||
slider.set_value(f64::from(value));
|
||||
entry.set_text(&value.to_string());
|
||||
}
|
||||
Loading…
Reference in a new issue