-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathvital_trend.rs
More file actions
347 lines (308 loc) · 10.8 KB
/
vital_trend.rs
File metadata and controls
347 lines (308 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! Vital sign trend analysis — ADR-041 Phase 1 module.
//!
//! Monitors breathing rate and heart rate over time windows (1-min, 5-min, 15-min)
//! and detects clinically significant trends:
//! - Bradypnea (breathing < 12 BPM sustained)
//! - Tachypnea (breathing > 25 BPM sustained)
//! - Bradycardia (HR < 50 BPM sustained)
//! - Tachycardia (HR > 120 BPM sustained)
//! - Apnea (no breathing detected for > 20 seconds)
//! - Trend reversal (sudden direction change in vital trajectory)
// No libm imports needed — pure arithmetic.
/// Window sizes in samples (at 1 Hz timer rate).
const WINDOW_1M: usize = 60;
const WINDOW_5M: usize = 300;
/// Maximum history depth.
const MAX_HISTORY: usize = 300; // 5 minutes at 1 Hz.
/// Clinical thresholds (BPM).
const BRADYPNEA_THRESH: f32 = 12.0;
const TACHYPNEA_THRESH: f32 = 25.0;
const BRADYCARDIA_THRESH: f32 = 50.0;
const TACHYCARDIA_THRESH: f32 = 120.0;
const APNEA_SECONDS: u32 = 20;
/// Minimum consecutive alerts before emitting (debounce).
const ALERT_DEBOUNCE: u8 = 5;
/// Event types (100-series: Medical).
pub const EVENT_VITAL_TREND: i32 = 100;
pub const EVENT_BRADYPNEA: i32 = 101;
pub const EVENT_TACHYPNEA: i32 = 102;
pub const EVENT_BRADYCARDIA: i32 = 103;
pub const EVENT_TACHYCARDIA: i32 = 104;
pub const EVENT_APNEA: i32 = 105;
pub const EVENT_BREATHING_AVG: i32 = 110;
pub const EVENT_HEARTRATE_AVG: i32 = 111;
/// Ring buffer for vital sign history.
struct VitalHistory {
values: [f32; MAX_HISTORY],
len: usize,
idx: usize,
}
impl VitalHistory {
const fn new() -> Self {
Self {
values: [0.0; MAX_HISTORY],
len: 0,
idx: 0,
}
}
fn push(&mut self, val: f32) {
self.values[self.idx] = val;
self.idx = (self.idx + 1) % MAX_HISTORY;
if self.len < MAX_HISTORY {
self.len += 1;
}
}
/// Compute mean of the last N samples.
fn mean_last(&self, n: usize) -> f32 {
let count = n.min(self.len);
if count == 0 {
return 0.0;
}
let mut sum = 0.0f32;
for i in 0..count {
let ri = (self.idx + MAX_HISTORY - count + i) % MAX_HISTORY;
sum += self.values[ri];
}
sum / count as f32
}
/// Check if all of the last N samples are below threshold.
#[allow(dead_code)]
fn all_below(&self, n: usize, threshold: f32) -> bool {
let count = n.min(self.len);
if count < n {
return false;
}
for i in 0..count {
let ri = (self.idx + MAX_HISTORY - count + i) % MAX_HISTORY;
if self.values[ri] >= threshold {
return false;
}
}
true
}
/// Check if all of the last N samples are above threshold.
#[allow(dead_code)]
fn all_above(&self, n: usize, threshold: f32) -> bool {
let count = n.min(self.len);
if count < n {
return false;
}
for i in 0..count {
let ri = (self.idx + MAX_HISTORY - count + i) % MAX_HISTORY;
if self.values[ri] <= threshold {
return false;
}
}
true
}
/// Compute simple linear trend (positive = increasing).
fn trend(&self, n: usize) -> f32 {
let count = n.min(self.len);
if count < 4 {
return 0.0;
}
// Simple: (last_quarter_mean - first_quarter_mean) / window.
let quarter = count / 4;
let mut first_sum = 0.0f32;
let mut last_sum = 0.0f32;
for i in 0..quarter {
let ri = (self.idx + MAX_HISTORY - count + i) % MAX_HISTORY;
first_sum += self.values[ri];
}
for i in (count - quarter)..count {
let ri = (self.idx + MAX_HISTORY - count + i) % MAX_HISTORY;
last_sum += self.values[ri];
}
let first_mean = first_sum / quarter as f32;
let last_mean = last_sum / quarter as f32;
(last_mean - first_mean) / count as f32
}
}
/// Vital trend analyzer.
pub struct VitalTrendAnalyzer {
breathing: VitalHistory,
heartrate: VitalHistory,
/// Debounce counters for each alert type.
bradypnea_count: u8,
tachypnea_count: u8,
bradycardia_count: u8,
tachycardia_count: u8,
/// Consecutive samples with near-zero breathing.
apnea_counter: u32,
/// Timer call count.
timer_count: u32,
}
impl VitalTrendAnalyzer {
pub const fn new() -> Self {
Self {
breathing: VitalHistory::new(),
heartrate: VitalHistory::new(),
bradypnea_count: 0,
tachypnea_count: 0,
bradycardia_count: 0,
tachycardia_count: 0,
apnea_counter: 0,
timer_count: 0,
}
}
/// Called at ~1 Hz with current vital signs.
///
/// Returns events as (event_type, value) pairs.
pub fn on_timer(&mut self, breathing_bpm: f32, heartrate_bpm: f32) -> &[(i32, f32)] {
self.timer_count += 1;
self.breathing.push(breathing_bpm);
self.heartrate.push(heartrate_bpm);
static mut EVENTS: [(i32, f32); 8] = [(0, 0.0); 8];
let mut n = 0usize;
// ── Apnea detection (highest priority) ──────────────────────────
if breathing_bpm < 1.0 {
self.apnea_counter += 1;
if self.apnea_counter >= APNEA_SECONDS {
unsafe {
EVENTS[n] = (EVENT_APNEA, self.apnea_counter as f32);
}
n += 1;
}
} else {
self.apnea_counter = 0;
}
// ── Bradypnea (sustained low breathing) ────────────────────────
if breathing_bpm > 0.0 && breathing_bpm < BRADYPNEA_THRESH {
self.bradypnea_count = self.bradypnea_count.saturating_add(1);
if self.bradypnea_count >= ALERT_DEBOUNCE && n < 7 {
unsafe {
EVENTS[n] = (EVENT_BRADYPNEA, breathing_bpm);
}
n += 1;
}
} else {
self.bradypnea_count = 0;
}
// ── Tachypnea (sustained high breathing) ───────────────────────
if breathing_bpm > TACHYPNEA_THRESH {
self.tachypnea_count = self.tachypnea_count.saturating_add(1);
if self.tachypnea_count >= ALERT_DEBOUNCE && n < 7 {
unsafe {
EVENTS[n] = (EVENT_TACHYPNEA, breathing_bpm);
}
n += 1;
}
} else {
self.tachypnea_count = 0;
}
// ── Bradycardia ────────────────────────────────────────────────
if heartrate_bpm > 0.0 && heartrate_bpm < BRADYCARDIA_THRESH {
self.bradycardia_count = self.bradycardia_count.saturating_add(1);
if self.bradycardia_count >= ALERT_DEBOUNCE && n < 7 {
unsafe {
EVENTS[n] = (EVENT_BRADYCARDIA, heartrate_bpm);
}
n += 1;
}
} else {
self.bradycardia_count = 0;
}
// ── Tachycardia ────────────────────────────────────────────────
if heartrate_bpm > TACHYCARDIA_THRESH {
self.tachycardia_count = self.tachycardia_count.saturating_add(1);
if self.tachycardia_count >= ALERT_DEBOUNCE && n < 7 {
unsafe {
EVENTS[n] = (EVENT_TACHYCARDIA, heartrate_bpm);
}
n += 1;
}
} else {
self.tachycardia_count = 0;
}
// ── Periodic averages (every 60 seconds) ───────────────────────
if self.timer_count % 60 == 0 && self.breathing.len >= WINDOW_1M {
let br_avg = self.breathing.mean_last(WINDOW_1M);
let hr_avg = self.heartrate.mean_last(WINDOW_1M);
if n < 7 {
unsafe {
EVENTS[n] = (EVENT_BREATHING_AVG, br_avg);
}
n += 1;
}
if n < 8 {
unsafe {
EVENTS[n] = (EVENT_HEARTRATE_AVG, hr_avg);
}
n += 1;
}
}
unsafe { &EVENTS[..n] }
}
/// Get the 1-minute breathing average.
pub fn breathing_avg_1m(&self) -> f32 {
self.breathing.mean_last(WINDOW_1M)
}
/// Get the breathing trend (positive = increasing).
pub fn breathing_trend_5m(&self) -> f32 {
self.breathing.trend(WINDOW_5M)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vital_trend_init() {
let vt = VitalTrendAnalyzer::new();
assert_eq!(vt.timer_count, 0);
assert_eq!(vt.apnea_counter, 0);
}
#[test]
fn test_normal_vitals_no_alerts() {
let mut vt = VitalTrendAnalyzer::new();
// Normal breathing (16 BPM) and heart rate (72 BPM).
for _ in 0..60 {
let events = vt.on_timer(16.0, 72.0);
// Should not generate clinical alerts.
for &(et, _) in events {
assert!(
et != EVENT_BRADYPNEA && et != EVENT_TACHYPNEA
&& et != EVENT_BRADYCARDIA && et != EVENT_TACHYCARDIA
&& et != EVENT_APNEA,
"unexpected clinical alert with normal vitals"
);
}
}
}
#[test]
fn test_apnea_detection() {
let mut vt = VitalTrendAnalyzer::new();
let mut apnea_detected = false;
for _ in 0..30 {
let events = vt.on_timer(0.0, 72.0);
for &(et, _) in events {
if et == EVENT_APNEA {
apnea_detected = true;
}
}
}
assert!(apnea_detected, "apnea should be detected after 20+ seconds of zero breathing");
}
#[test]
fn test_tachycardia_detection() {
let mut vt = VitalTrendAnalyzer::new();
let mut tachy_detected = false;
for _ in 0..20 {
let events = vt.on_timer(16.0, 130.0);
for &(et, _) in events {
if et == EVENT_TACHYCARDIA {
tachy_detected = true;
}
}
}
assert!(tachy_detected, "tachycardia should be detected with sustained HR > 120");
}
#[test]
fn test_breathing_average() {
let mut vt = VitalTrendAnalyzer::new();
for _ in 0..60 {
vt.on_timer(16.0, 72.0);
}
let avg = vt.breathing_avg_1m();
assert!((avg - 16.0).abs() < 0.1, "1-min breathing average should be ~16.0");
}
}