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

479 lines
19 KiB
Rust
Raw Normal View History

2026-11-12 09:36:13 +01:00
//! 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);
}
}