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
use crate::{Echo, View, WelfordOnlineSliding};
#[derive(Clone)]
pub struct VSCT {
view: Box<dyn View>,
welford_online: Box<WelfordOnlineSliding>,
last: f64,
}
impl VSCT {
pub fn new(view: Box<dyn View>, window_len: usize) -> Box<Self> {
Box::new(VSCT {
view,
welford_online: WelfordOnlineSliding::new_final(window_len),
last: 0.0,
})
}
pub fn new_final(window_len: usize) -> Box<Self> {
Self::new(Echo::new(), window_len)
}
}
impl View for VSCT {
fn update(&mut self, val: f64) {
self.view.update(val);
let val = self.view.last();
self.welford_online.update(val);
self.last = val;
}
fn last(&self) -> f64 {
let std_dev = self.welford_online.last();
if std_dev == 0.0 {
return 0.0;
}
let mean = self.welford_online.mean();
(self.last - mean) / std_dev
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plot::plot_values;
use crate::test_data::TEST_DATA;
#[test]
fn vsct_plot() {
let mut vsct = VSCT::new_final(16);
let mut out: Vec<f64> = Vec::with_capacity(TEST_DATA.len());
for v in &TEST_DATA {
vsct.update(*v);
out.push(vsct.last());
}
let filename = "img/vsct.png";
plot_values(out, filename).unwrap();
}
}