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
#[cfg(test)]
extern crate matplotrust;

extern crate rand;

use rand::prelude::*;
use rand::distributions::Normal as N;
use std::f64::consts::PI;

mod utils;
mod timeseries;

macro_rules! assert_delta {
    ($x:expr, $y:expr, $d:expr) => {
        if !(($x - $y).abs() < $d || ($y - $x).abs() < $d) { panic!(); }
    }
}

fn mean(numbers: &Vec<f64>) -> f64 {
    numbers.iter().sum::<f64>() as f64 / numbers.len() as f64
}

pub struct Normal {
    mean : f64,
    std : f64
}

impl Normal {
    pub fn new(mean: f64, std: f64) -> Normal {
        return Normal {
            mean : mean,
            std: std,
        }
    }

    pub fn sample(&mut self) -> f64 {
        let normal = N::new(self.mean, self.std);
        let v = normal.sample(&mut rand::thread_rng());
        return v;
    }

    pub fn logpdf(&mut self, x: f64) -> f64 {
        return -0.5 * (2.0 * PI).ln() - self.std.ln() - (x - self.mean).powi(2) / (2.0 * self.std * self.std)
    }

    pub fn pdf(&mut self, x: f64) -> f64 {
        return self.logpdf(x).exp();
    }
}

pub struct MonotonicCubicSpline {
    m_x: Vec<f64>,
    m_y: Vec<f64>,
    m_m: Vec<f64>
}

impl MonotonicCubicSpline {

    pub fn new(x : &Vec<f64>, y : &Vec<f64>) -> MonotonicCubicSpline {

        assert!(x.len() == y.len() && x.len() >= 2 && y.len() >= 2, "Must have at least 2 control points.");

        let n = x.len();

        let mut secants = vec![0.0 ; n - 1];
        let mut slopes  = vec![0.0 ; n];

        for i in 0..(n-1) {
            let h = *x.get(i + 1).unwrap() - *x.get(i).unwrap();
            assert!(h > 0.0, "Control points must be monotonically increasing.");
            secants[i] = (*y.get(i + 1).unwrap() - *y.get(i).unwrap()) / h;

        }

        slopes[0] = secants[0];
        for i in 1..(n-1) {
            slopes[i] = (secants[i - 1] + secants[i]) * 0.5;
        }
        slopes[n - 1] = secants[n - 2];

        for i in 0..(n-1) {
            if secants[i] == 0.0 {
                slopes[i] = 0.0;
                slopes[i + 1] = 0.0;
            } else {
                let alpha = slopes[i] / secants[i];
                let beta = slopes[i + 1] / secants[i];
                let h = alpha.hypot(beta);
                if h > 9.0 {
                    let t = 3.0 / h;
                    slopes[i] = t * alpha * secants[i];
                    slopes[i + 1] = t * beta * secants[i];
                }
            }
        }

        let spline = MonotonicCubicSpline {
            m_x: x.clone(),
            m_y: y.clone(),
            m_m: slopes
        };
        return spline;
    }

    pub fn hermite(point: f64, x : (f64, f64), y: (f64, f64), m: (f64, f64)) -> f64 {

        let h: f64 = x.1 - x.0;
        let t = (point - x.0) / h;
        return (y.0 * (1.0 + 2.0 * t) + h * m.0 * t) * (1.0 - t) * (1.0 - t)
            + (y.1 * (3.0 - 2.0 * t) + h * m.1 * (t - 1.0)) * t * t;
    }

    pub fn interpolate(&mut self, point : f64) -> f64 {
        let n = self.m_x.len();

        if point <= *self.m_x.get(0).unwrap() {
            return *self.m_y.get(0).unwrap();
        }
        if point >= *self.m_x.get(n - 1).unwrap() {
            return *self.m_y.get(n - 1).unwrap();
        }

        let mut i = 0;
        while point >= *self.m_x.get(i + 1).unwrap() {
            i += 1;
            if point == *self.m_x.get(i).unwrap() {
                return *self.m_y.get(i).unwrap();
            }
        }
        return MonotonicCubicSpline::hermite(point,
                                             (*self.m_x.get(i).unwrap(), *self.m_x.get(i+1).unwrap()),
                                             (*self.m_y.get(i).unwrap(), *self.m_y.get(i+1).unwrap()),
                                             (*self.m_m.get(i).unwrap(), *self.m_m.get(i+1).unwrap()));
    }

    fn partial(x: Vec<f64>, y: Vec<f64>) -> impl Fn(f64) -> f64 {
        move |p| {
            let mut spline = MonotonicCubicSpline::new(&x, &y);
            spline.interpolate(p)
        }
    }

}

#[cfg(test)]
mod test_normal {

    use super::*;

    #[test]
    fn sample_mean_std() {
        let n = 0..1000000;
        let mut normal = Normal::new(0.0, 1.0);
        let samples = n.map(|_i| normal.sample()).collect::<Vec<f64>>();
        let mu = mean(&samples);
        assert_delta!(0.0, mu, 1e-3);
    }

    #[test]
    fn logpdf() {
        let mut normal = Normal::new(0.0, 1.0);
        let _logpdf = normal.logpdf(0.0);
        print!("{:?}", _logpdf);
        assert_delta!(-0.9189385, _logpdf, 1e-5);
    }

    fn pdf() {
        let mut normal = Normal::new(0.0, 1.0);
        let _pdf = normal.pdf(0.0);
        print!("{:?}", _pdf);
        assert_delta!(0.3989423, _pdf, 1e-5);
    }


    #[test]
    fn interpolation() {
        use matplotrust::*;

        let x = vec![0.0, 2.0, 3.0, 10.0];
        let y = vec![1.0, 4.0, 8.0, 10.5];

        let smooth = MonotonicCubicSpline::partial(x.clone(), y.clone());

        let mut x_interp = Vec::new();
        let mut y_interp = Vec::new();
        for i in 0..100 {
            let p = i as f64 / 10.0;
            x_interp.push(p);
            y_interp.push(smooth(p));
        }
        let mut figure = Figure::new();
        let points = scatter_plot::<f64, f64>(x, y, None);
        let interpolation = line_plot::<f64, f64>(x_interp, y_interp, None);
        figure.add_plot(points);
        figure.add_plot(interpolation);
        figure.save("./docs/figures/monotonic_cubic_spline.png", None);

    }

}