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
use crate::time_series::{TimeSeries, Style};
use crate::plotable::Plotable;
use plotlib::view::{View, ContinuousView};
use plotlib::repr::Plot;
#[derive(Clone)]
pub struct ExpSmoothing {
series: TimeSeries,
alpha: Option<f64>,
cur: usize,
smooth: Vec<(f64, f64)>
}
impl ExpSmoothing {
pub fn new(series: &TimeSeries) -> Self {
let mut result = Self {
series: series.clone(),
alpha: None,
cur: 0,
smooth: Vec::new(),
};
result
}
pub fn with_alpha(mut self, alpha: f64) -> Self {
self.cur = 0;
self.smooth = Vec::new();
self.alpha = Some(alpha);
self.smooth = self.exp_smooth(alpha);
self
}
fn exp_smooth(&mut self, alpha: f64) -> Vec<(f64, f64)> {
let mut smooth = Vec::new();
if self.cur == 0 {
let new_cur = self.series.len();
let data = self.series.get_data();
let mut last_fore = data[0].1;
for i in self.cur + 1..new_cur {
smooth.push(
((i + 1) as f64, Self::calculate_smooth(alpha, data[i - 1].1, last_fore))
);
last_fore = smooth.last().expect("No last forecasted value").1;
}
self.cur = new_cur;
}
smooth
}
pub fn get_data(&self) -> Vec<(f64, f64)> {
if self.alpha.is_none() {
panic!("Can't get data of ExpSmoothing with no alpha");
}
self.smooth.clone()
}
pub fn style(&self) -> Style {
self.series.style()
}
pub fn as_time_series(&self) -> TimeSeries {
TimeSeries::from_pairs_vec(self.get_data())
}
fn calculate_smooth(alpha: f64, last: f64, last_fore: f64) -> f64 {
if alpha > 1.0 || alpha < 0.0 {
panic!("bad alpha argument for ExpSmooth");
}
alpha * last + (1.0 - alpha) * last_fore
}
pub fn alpha(&self) -> f64 {
self.alpha.expect("Couldn't get alpha from expsmooth: None")
}
}
impl Plotable for ExpSmoothing {
fn plot(&self) -> Box<dyn View> {
let plot = self.as_plot();
Box::new(ContinuousView::new().add(plot))
}
fn as_plot(&self) -> Plot {
let mut plot = Plot::new(self.get_data());
plot
.point_style(self.style().point)
.line_style(self.style().line)
}
}