├── .gitignore ├── src ├── spline │ ├── mod.rs │ └── greedy.rs ├── regression │ ├── mod.rs │ ├── greedy.rs │ └── optimal.rs ├── test_util.rs ├── util.rs └── lib.rs ├── .github └── workflows │ └── rust.yml ├── benches ├── spline_bench.rs └── plr_bench.rs ├── README.md ├── Cargo.toml ├── COPYING └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | *~ 4 | Cargo.lock 5 | .ipynb_checkpoints 6 | -------------------------------------------------------------------------------- /src/spline/mod.rs: -------------------------------------------------------------------------------- 1 | mod greedy; 2 | 3 | pub use greedy::greedy_spline; 4 | pub use greedy::GreedySpline; 5 | -------------------------------------------------------------------------------- /src/regression/mod.rs: -------------------------------------------------------------------------------- 1 | mod greedy; 2 | mod optimal; 3 | 4 | pub use greedy::GreedyPLR; 5 | pub use optimal::OptimalPLR; 6 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /benches/spline_bench.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use plr::spline::greedy_spline; 3 | 4 | pub fn criterion_benchmark(c: &mut Criterion) { 5 | let mut data = Vec::new(); 6 | 7 | for idx in 0..2000 { 8 | let x = idx as f64 / 2000.0; 9 | let y = f64::sin(x); 10 | 11 | data.push((x, y)); 12 | } 13 | 14 | c.bench_function("spline greedy 2000", |b| { 15 | b.iter(|| { 16 | let _res = greedy_spline(&data, 0.0005); 17 | }) 18 | }); 19 | } 20 | 21 | criterion_group!(benches, criterion_benchmark); 22 | criterion_main!(benches); 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PLR (piecewise linear regression) 2 | 3 | [![Rust](https://github.com/RyanMarcus/plr/actions/workflows/rust.yml/badge.svg)](https://github.com/RyanMarcus/plr/actions/workflows/rust.yml) [![crates.io](https://img.shields.io/crates/v/plr.svg)](https://crates.io/crates/plr) 4 | 5 | Rust implementation of the greedy and optimal error-bounded PLR algorithms described in: 6 | 7 | > Qing Xie, Chaoyi Pang, Xiaofang Zhou, Xiangliang Zhang, and Ke Deng. 2014. Maximum error-bounded Piecewise Linear Representation for online stream approximation. The VLDB Journal 23, 6 (December 2014), 915–937. DOI: https://doi.org/10.1007/s00778-014-0355-0 8 | 9 | Error-bounded piecewise linear regression is the task of taking a set of datapoints and finding a piecewise linear function that approximates each datapoint within a fixed bound. See the [crate documentation](https://docs.rs/plr/) for more information. 10 | 11 | ![PLR at various error levels](https://rmarcus.info/images/plr.png) 12 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "plr" 3 | description = "Performs greedy or optimal error-bounded piecewise linear regression (PLR) and spline regression" 4 | repository = "https://github.com/RyanMarcus/plr" 5 | keywords = ["plr", "piecewise", "regression"] 6 | license = "GPL-3.0-or-later" 7 | version = "0.3.2" 8 | authors = ["Ryan Marcus "] 9 | edition = "2018" 10 | readme = "README.md" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | approx = "0.3" 16 | rug = "1.28" 17 | serde = { version = "1.0", features = ["derive"] } 18 | 19 | [dev-dependencies] 20 | criterion = "0.3" 21 | superslice = "1.0.0" 22 | 23 | #[profile.release] 24 | #debug = true 25 | 26 | [badges] 27 | travis-ci = { repository = "RyanMarcus/plr", branch = "master" } 28 | 29 | #[[bin]] 30 | #name = "plr" 31 | #path = "src/bin.rs" 32 | 33 | [[bench]] 34 | name = "plr_bench" 35 | harness = false 36 | 37 | [[bench]] 38 | name = "spline_bench" 39 | harness = false 40 | -------------------------------------------------------------------------------- /benches/plr_bench.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use plr::regression::{GreedyPLR, OptimalPLR}; 3 | 4 | pub fn criterion_benchmark(c: &mut Criterion) { 5 | let mut data = Vec::new(); 6 | 7 | for idx in 0..2000 { 8 | let x = idx as f64 / 2000.0; 9 | let y = f64::sin(x); 10 | 11 | data.push((x, y)); 12 | } 13 | 14 | c.bench_function("optimal 2000", |b| { 15 | b.iter(|| { 16 | let mut plr = OptimalPLR::new(0.0005); 17 | 18 | for &(x, y) in data.iter() { 19 | plr.process(x, y); 20 | } 21 | 22 | plr.finish(); 23 | }) 24 | }); 25 | 26 | c.bench_function("greedy 2000", |b| { 27 | b.iter(|| { 28 | let mut plr = GreedyPLR::new(0.0005); 29 | 30 | for &(x, y) in data.iter() { 31 | plr.process(x, y); 32 | } 33 | 34 | plr.finish(); 35 | }) 36 | }); 37 | } 38 | 39 | criterion_group!(benches, criterion_benchmark); 40 | criterion_main!(benches); 41 | -------------------------------------------------------------------------------- /src/test_util.rs: -------------------------------------------------------------------------------- 1 | // < begin copyright > 2 | // Copyright Ryan Marcus 2019 3 | // 4 | // This file is part of plr. 5 | // 6 | // plr is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // plr is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with plr. If not, see . 18 | // 19 | // < end copyright > 20 | use crate::data::*; 21 | use crate::util::*; 22 | use std::collections::VecDeque; 23 | use superslice::*; 24 | 25 | pub fn sin_data() -> Vec<(f64, f64)> { 26 | let mut data = Vec::new(); 27 | 28 | for i in 0..1000 { 29 | let x = (i as f64) / 1000.0 * 7.0; 30 | let y = f64::sin(x); 31 | data.push((x, y)); 32 | } 33 | 34 | return data; 35 | } 36 | 37 | pub fn linear_data(slope: f64, intercept: f64) -> Vec<(f64, f64)> { 38 | let mut data = Vec::new(); 39 | 40 | for i in 0..10 { 41 | let x = (i as f64) / 1000.0; 42 | let y = x * slope + intercept; 43 | data.push((x, y)); 44 | } 45 | 46 | return data; 47 | } 48 | 49 | pub fn precision_data() -> Vec<(f64, f64)> { 50 | let mut data = Vec::new(); 51 | 52 | for i in 0..1000 { 53 | let x = ((i as f64) / 1000.0) * f64::powi(2.0, 60); 54 | 55 | let y = i as f64; 56 | 57 | data.push((x, y)); 58 | } 59 | 60 | return data; 61 | } 62 | 63 | pub fn osm_data() -> Vec<(f64, f64)> { 64 | return OSM_DATA 65 | .iter() 66 | .map(|&(x, y)| (x as f64, y as f64)) 67 | .collect(); 68 | } 69 | 70 | pub fn fb_data() -> Vec<(f64, f64)> { 71 | return FB_DATA.iter().map(|&(x, y)| (x as f64, y as f64)).collect(); 72 | } 73 | 74 | pub fn verify_gamma(gamma: f64, data: &[(f64, f64)], segments: &[Segment]) { 75 | let mut seg_q = VecDeque::new(); 76 | 77 | for segment in segments { 78 | seg_q.push_back(segment); 79 | } 80 | 81 | for &(x, y) in data { 82 | while seg_q.front().unwrap().stop <= x { 83 | seg_q.pop_front(); 84 | } 85 | 86 | let seg = seg_q.front().unwrap(); 87 | 88 | assert!(seg.start <= x); 89 | assert!(seg.stop >= x); 90 | 91 | let line = Line::new(seg.slope, seg.intercept); 92 | let pred = line.at(x).y; 93 | 94 | assert!( 95 | f64::abs(pred - y) <= gamma, 96 | "Prediction of {} was not within gamma ({}) of true value {}", 97 | pred, 98 | gamma, 99 | y 100 | ); 101 | } 102 | } 103 | 104 | fn spline_interpolate(pt: f64, knots: &[(f64, f64)]) -> (f64, f64) { 105 | let upper_idx = usize::min( 106 | knots.len() - 1, 107 | knots.upper_bound_by(|x| x.0.partial_cmp(&pt).unwrap()), 108 | ); 109 | let lower_idx = upper_idx - 1; 110 | 111 | return Point::from_tuple(knots[lower_idx]) 112 | .line_to(&Point::from_tuple(knots[upper_idx])) 113 | .at(pt) 114 | .as_tuple(); 115 | } 116 | 117 | pub fn verify_gamma_splines(gamma: f64, data: &[(f64, f64)], pts: &[(f64, f64)]) { 118 | println!("{:?}", pts); 119 | for &(x, y) in data { 120 | let pred = spline_interpolate(x, pts); 121 | assert!( 122 | f64::abs(pred.1 - y) <= gamma, 123 | "Prediction of {} was not within gamma ({}) of true value {}", 124 | pred.1, 125 | gamma, 126 | y 127 | ); 128 | } 129 | } 130 | 131 | pub fn verify_gamma_splines_cast(gamma: f64, data: &[(f64, f64)], pts: &[(f64, f64)]) { 132 | println!("{:?}", pts); 133 | for &(x, y) in data { 134 | let x = (x as u64) as f64; 135 | let pred = spline_interpolate(x, pts); 136 | let pred = pred.1 as u64; 137 | assert!( 138 | f64::abs(pred as f64 - y) <= gamma, 139 | "Prediction of {} was not within gamma ({}) of true value {}", 140 | pred, 141 | gamma, 142 | y 143 | ); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/spline/greedy.rs: -------------------------------------------------------------------------------- 1 | use crate::util::Point; 2 | 3 | /// A greedy spline regressor using the greedy spline corridor algorithm. 4 | /// Each call to `process` will return a new spline point if one is needed 5 | /// to maintain the error bound, or `None` if the passed point works with 6 | /// the current spline. 7 | /// 8 | /// Note that the first point (passed to `new`) won't be returned by 9 | /// `process`, but still needs to be included in the spline knots. 10 | /// 11 | /// Call `finish` to get the final point of the spline. 12 | #[derive(Clone)] 13 | pub struct GreedySpline { 14 | error: f64, 15 | pt1: Point, 16 | pt2: Option, 17 | slope_ub: f64, 18 | slope_lb: f64, 19 | } 20 | 21 | impl GreedySpline { 22 | /// Constructs a new online greedy spline regression. The first point, 23 | /// passed to this function, must be used as the first spline point. 24 | pub fn new(x: f64, y: f64, err: f64) -> GreedySpline { 25 | let pt1 = Point::new(x, y); 26 | GreedySpline { 27 | error: err, 28 | pt1, 29 | pt2: None, 30 | slope_lb: std::f64::NEG_INFINITY, 31 | slope_ub: std::f64::INFINITY, 32 | } 33 | } 34 | 35 | /// Add another point the spline regression, potentially returning a new knot. 36 | pub fn process(&mut self, x: f64, y: f64) -> Option<(f64, f64)> { 37 | let pt = Point::new(x, y); 38 | match self.pt2 { 39 | None => { 40 | self.pt2 = Some(pt); 41 | self.slope_ub = self.pt1.line_to(&pt.upper_bound(self.error)).slope(); 42 | self.slope_lb = self.pt1.line_to(&pt.lower_bound(self.error)).slope(); 43 | return None; 44 | } 45 | 46 | Some(pt2) => { 47 | assert!( 48 | x > pt2.x, 49 | "x values not in order, saw new point ({},{}) with old point ({},{})", 50 | x, 51 | y, 52 | pt2.x, 53 | pt.y 54 | ); 55 | 56 | let potential_upper = self.pt1.line_to(&pt.upper_bound(self.error)).slope(); 57 | let potential_my = self.pt1.line_to(&pt).slope(); 58 | let potential_lower = self.pt1.line_to(&pt.lower_bound(self.error)).slope(); 59 | 60 | if potential_my >= self.slope_ub || potential_my <= self.slope_lb { 61 | // this point is outside our bound, have to create a new spline point 62 | self.pt1 = pt2; 63 | self.slope_lb = std::f64::NEG_INFINITY; 64 | self.slope_ub = std::f64::INFINITY; 65 | self.pt2 = None; 66 | return Some(pt2.as_tuple()); 67 | } 68 | 69 | // otherwise, we have a new pt2 and need to update the slope bounds 70 | debug_assert!(f64::abs(self.pt1.line_to(&pt).at(pt2.x).y - pt2.y) <= self.error); 71 | 72 | self.pt2 = Some(pt); 73 | self.slope_lb = f64::max(self.slope_lb, potential_lower); 74 | self.slope_ub = f64::min(self.slope_ub, potential_upper); 75 | 76 | return None; 77 | } 78 | }; 79 | } 80 | 81 | /// Finish the spline regression, returning the final knot. 82 | pub fn finish(self) -> (f64, f64) { 83 | match self.pt2 { 84 | Some(pt) => (pt.x, pt.y), 85 | None => (self.pt1.x, self.pt1.y), 86 | } 87 | } 88 | } 89 | 90 | /// Learns a spline regression over `data` with an error bound of `err`. 91 | /// Each spline point is returned in (x, y) coordinates. 92 | pub fn greedy_spline(data: &[(f64, f64)], err: f64) -> Vec<(f64, f64)> { 93 | assert!(data.len() >= 2); 94 | if data.len() == 2 { 95 | return vec![data[0], data[1]]; 96 | } 97 | 98 | let mut pts = vec![data[0]]; 99 | let mut gs = GreedySpline::new(data[0].0, data[0].1, err); 100 | 101 | for pt in &data[1..] { 102 | if let Some(knot) = gs.process(pt.0, pt.1) { 103 | pts.push(knot); 104 | } 105 | } 106 | pts.push(gs.finish()); 107 | return pts; 108 | } 109 | 110 | #[cfg(test)] 111 | mod test { 112 | use super::*; 113 | use crate::test_util::*; 114 | 115 | #[test] 116 | fn test_sin() { 117 | let data = sin_data(); 118 | let pts = greedy_spline(&data, 0.0005); 119 | assert!(pts.len() < 500); 120 | verify_gamma_splines(0.0005, &data, &pts); 121 | } 122 | 123 | #[test] 124 | fn test_linear() { 125 | let data = linear_data(10.0, 25.0); 126 | let pts = greedy_spline(&data, 0.0005); 127 | assert_eq!(pts.len(), 2); 128 | verify_gamma_splines(0.0005, &data, &pts); 129 | } 130 | 131 | #[test] 132 | fn test_precision() { 133 | let data = precision_data(); 134 | let pts = greedy_spline(&data, 0.0005); 135 | assert_eq!(pts.len(), 2); 136 | verify_gamma_splines(0.0005, &data, &pts); 137 | } 138 | 139 | #[test] 140 | fn test_osm() { 141 | let data = osm_data(); 142 | let pts = greedy_spline(&data, 64.0); 143 | verify_gamma_splines(64.0, &data, &pts); 144 | } 145 | 146 | #[test] 147 | fn test_osm_int_keys() { 148 | let data = osm_data(); 149 | let pts = greedy_spline(&data, 64.0); 150 | verify_gamma_splines_cast(64.0, &data, &pts); 151 | } 152 | 153 | #[test] 154 | fn test_fb() { 155 | let data = fb_data(); 156 | let pts = greedy_spline(&data, 64.0); 157 | verify_gamma_splines(64.0, &data, &pts); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | // < begin copyright > 2 | // Copyright Ryan Marcus 2019 3 | // 4 | // This file is part of plr. 5 | // 6 | // plr is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // plr is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with plr. If not, see . 18 | // 19 | // < end copyright > 20 | 21 | use approx::*; 22 | use rug::Float; 23 | use serde::{Deserialize, Serialize}; 24 | 25 | #[derive(Debug, Clone, Copy, Serialize, Deserialize)] 26 | pub struct Point { 27 | pub x: f64, 28 | pub y: f64, 29 | } 30 | 31 | #[derive(Debug)] 32 | pub struct Line { 33 | a: f64, 34 | b: f64, 35 | } 36 | 37 | /// A single segment of a PLR. The `start` field is inclusive, the `stop` field is exclusive. 38 | /// The `slope` and `intercept` field can be used in a linear model: in other words, for some 39 | /// `x` such that `start <= x < stop`, the prediction is `slope * x + intercept`. 40 | #[derive(Debug, Serialize, Deserialize)] 41 | pub struct Segment { 42 | pub start: f64, 43 | pub stop: f64, 44 | pub slope: f64, 45 | pub intercept: f64, 46 | } 47 | 48 | impl Line { 49 | #[cfg(test)] 50 | pub fn new(slope: f64, intercept: f64) -> Line { 51 | return Line { 52 | a: slope, 53 | b: intercept, 54 | }; 55 | } 56 | 57 | fn as_tuple(&self) -> (f64, f64) { 58 | return (self.a, self.b); 59 | } 60 | 61 | pub fn intersection(l1: &Line, l2: &Line) -> Point { 62 | let (a, c) = l1.as_tuple(); 63 | let (b, d) = l2.as_tuple(); 64 | 65 | // handle floating point precision issues when both slopes are very 66 | // small numbers 67 | if relative_eq!(a, b) { 68 | let a_f = Float::with_val(128, a); 69 | let b_f = Float::with_val(128, b); 70 | let c_f = Float::with_val(128, c); 71 | let d_f = Float::with_val(128, d); 72 | 73 | let denom_f: Float = Float::with_val(128, &a_f - &b_f); 74 | 75 | let x_val = 76 | Float::with_val(128, (d_f.clone() - c_f.clone()) / denom_f.clone()).to_f64(); 77 | let y_val = ((a_f * d_f - b_f * c_f) / denom_f).to_f64(); 78 | 79 | return Point::new(x_val, y_val); 80 | } 81 | 82 | let denom = a - b; 83 | let x_val = (d - c) / denom; 84 | let y_val = (a * d - b * c) / denom; 85 | 86 | return Point::new(x_val, y_val); 87 | } 88 | 89 | pub fn average_slope(l1: &Line, l2: &Line) -> f64 { 90 | if relative_eq!(l1.a, l2.a) { 91 | // use higher precision 92 | let a1 = Float::with_val(128, l1.a); 93 | let a2 = Float::with_val(128, l2.a); 94 | let avg = ((a1 + a2) / Float::with_val(128, 2.0)).to_f64(); 95 | return avg; 96 | } 97 | 98 | // min + max to avoid precision loss 99 | return (f64::min(l1.a, l2.a) + f64::max(l1.a, l2.a)) / 2.0; 100 | } 101 | 102 | pub fn slope(&self) -> f64 { 103 | return self.a; 104 | } 105 | 106 | pub fn at(&self, x: f64) -> Point { 107 | return Point::new(x, self.a * x + self.b); 108 | } 109 | } 110 | 111 | impl Point { 112 | pub fn new(x: f64, y: f64) -> Point { 113 | return Point { x, y }; 114 | } 115 | 116 | #[cfg(test)] 117 | pub fn from_tuple(pt: (f64, f64)) -> Point { 118 | return Point::new(pt.0, pt.1); 119 | } 120 | 121 | pub fn as_tuple(&self) -> (f64, f64) { 122 | return (self.x, self.y); 123 | } 124 | 125 | pub fn slope_to(&self, other: &Point) -> f64 { 126 | // handle floating point precision issues when both x coords are very 127 | // large (or very small, although this is uncommon) numbers 128 | if relative_eq!(self.x, other.x) { 129 | let x1_f = Float::with_val(128, self.x); 130 | let y1_f = Float::with_val(128, self.y); 131 | let x2_f = Float::with_val(128, other.x); 132 | let y2_f = Float::with_val(128, other.y); 133 | 134 | let res = ((y1_f - y2_f) / (x1_f - x2_f)).to_f64(); 135 | return res; 136 | } 137 | 138 | return (self.y - other.y) / (self.x - other.x); 139 | } 140 | 141 | pub fn line_to(&self, other: &Point) -> Line { 142 | let a = self.slope_to(other); 143 | 144 | debug_assert!( 145 | !f64::is_nan(a), 146 | "slope from {:?} to {:?} was NaN", 147 | self, 148 | other 149 | ); 150 | 151 | let b = -a * self.x + self.y; 152 | return Line { a, b }; 153 | } 154 | 155 | pub fn above(&self, line: &Line) -> bool { 156 | return self.y > line.at(self.x).y; 157 | } 158 | 159 | pub fn below(&self, line: &Line) -> bool { 160 | return self.y < line.at(self.x).y; 161 | } 162 | 163 | pub fn upper_bound(&self, gamma: f64) -> Point { 164 | // check float precision 165 | debug_assert!( 166 | !relative_eq!(self.y, self.y + gamma), 167 | "Gamma value of {} and encountered Y value of {} won't work in 64-bit!", 168 | gamma, 169 | self.y 170 | ); 171 | return Point { 172 | x: self.x, 173 | y: self.y + gamma, 174 | }; 175 | } 176 | 177 | pub fn lower_bound(&self, gamma: f64) -> Point { 178 | // check float precision 179 | debug_assert!( 180 | !relative_eq!(self.y, self.y - gamma), 181 | "Gamma value of {} and encountered Y value of {} won't work in 64-bit!", 182 | gamma, 183 | self.y 184 | ); 185 | return Point { 186 | x: self.x, 187 | y: self.y - gamma, 188 | }; 189 | } 190 | } 191 | 192 | #[cfg(test)] 193 | mod test { 194 | use super::*; 195 | use approx::*; 196 | 197 | #[test] 198 | fn test_slope() { 199 | let p1 = Point::new(1.0, 3.0); 200 | let p2 = Point::new(5.0, 6.0); 201 | 202 | assert_relative_eq!(p1.slope_to(&p2), p2.slope_to(&p1)); 203 | assert_relative_eq!(p1.slope_to(&p2), 0.75); 204 | } 205 | 206 | #[test] 207 | fn test_line() { 208 | let p1 = Point::new(1.0, 3.0); 209 | let p2 = Point::new(2.0, 6.0); 210 | 211 | let line1 = p1.line_to(&p2); 212 | let line2 = p2.line_to(&p1); 213 | 214 | assert_relative_eq!(line1.a, line2.a); 215 | assert_relative_eq!(line1.b, line2.b); 216 | 217 | assert_relative_eq!(line1.a, 3.0); 218 | assert_relative_eq!(line1.b, 0.0); 219 | } 220 | 221 | #[cfg(debug)] 222 | #[test] 223 | #[should_panic] 224 | fn test_line_ident() { 225 | let p1 = Point::new(1.0, 3.0); 226 | let p2 = Point::new(1.0, 6.0); 227 | 228 | p1.line_to(&p2); 229 | } 230 | 231 | #[test] 232 | fn test_intersection() { 233 | let p1 = Point::new(1.0, 3.0); 234 | let p2 = Point::new(2.0, 6.0); 235 | let line1 = p1.line_to(&p2); 236 | 237 | let p3 = Point::new(8.0, -100.0); 238 | let line2 = p1.line_to(&p3); 239 | 240 | let intersection = Line::intersection(&line1, &line2); 241 | 242 | assert_relative_eq!(intersection.x, p1.x); 243 | assert_relative_eq!(intersection.y, p1.y); 244 | } 245 | 246 | #[test] 247 | fn test_above_below() { 248 | let p1 = Point::new(1.0, 3.0); 249 | let p2 = Point::new(2.0, 6.0); 250 | let line1 = p1.line_to(&p2); 251 | 252 | let above = Point::new(1.5, 10.0); 253 | let below = Point::new(1.5, -10.0); 254 | 255 | assert!(above.above(&line1)); 256 | assert!(below.below(&line1)); 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/regression/greedy.rs: -------------------------------------------------------------------------------- 1 | // < begin copyright > 2 | // Copyright Ryan Marcus 2019 3 | // 4 | // This file is part of plr. 5 | // 6 | // plr is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // plr is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with plr. If not, see . 18 | // 19 | // < end copyright > 20 | use crate::util::{Line, Point, Segment}; 21 | 22 | #[derive(PartialEq)] 23 | enum GreedyState { 24 | Need2, 25 | Need1, 26 | Ready, 27 | } 28 | 29 | /// Performs a greedy piecewise linear regression (PLR) in an online fashion. This approach uses constant 30 | /// time for each call to [`process`](#method.process) as well as constant space. Note that, due to the 31 | /// greedy nature of the algorithm, more regression segments may be created than strictly needed. For 32 | /// PLR with a minimal number of segments, please see [`OptimalPLR`](struct.OptimalPLR.html). 33 | /// 34 | /// Each call to [`process`](#method.process) consumes a single point. Each time it is called, 35 | /// [`process`](#method.process) returns either a [`Segment`](../struct.Segment.html) representing 36 | /// a piece of the final regression, or `None`. If your stream of points terminates, you can call 37 | /// [`finish`](#method.finish) to flush the buffer and return the final segment. 38 | /// 39 | /// # Example 40 | /// ``` 41 | /// use plr::regression::GreedyPLR; 42 | /// // first, generate some data points... 43 | /// let mut data = Vec::new(); 44 | /// 45 | /// for i in 0..1000 { 46 | /// let x = (i as f64) / 1000.0 * 7.0; 47 | /// let y = f64::sin(x); 48 | /// data.push((x, y)); 49 | /// } 50 | /// 51 | /// let mut plr = GreedyPLR::new(0.0005); // gamma = 0.0005, the maximum regression error 52 | /// 53 | /// let mut segments = Vec::new(); 54 | /// 55 | /// for (x, y) in data { 56 | /// // when `process` returns a segment, we should add it to our list 57 | /// if let Some(segment) = plr.process(x, y) { 58 | /// segments.push(segment); 59 | /// } 60 | /// } 61 | /// 62 | /// // because we have a finite amount of data, we flush the buffer and get the potential 63 | /// // last segment. 64 | /// if let Some(segment) = plr.finish() { 65 | /// segments.push(segment); 66 | /// } 67 | /// 68 | /// // the `segments` vector now contains all segments for this regression. 69 | /// ``` 70 | pub struct GreedyPLR { 71 | state: GreedyState, 72 | gamma: f64, 73 | s0: Option, 74 | s1: Option, 75 | sint: Option, 76 | s_last: Option, 77 | rho_lower: Option, 78 | rho_upper: Option, 79 | } 80 | 81 | impl GreedyPLR { 82 | /// Enables performing PLR using a greedy algorithm with a fixed gamma (maximum error). 83 | /// 84 | /// # Examples 85 | /// 86 | /// To perform a greedy PLR with a maximum error of `0.05`: 87 | /// ``` 88 | /// use plr::regression::GreedyPLR; 89 | /// let plr = GreedyPLR::new(0.05); 90 | /// ``` 91 | pub fn new(gamma: f64) -> GreedyPLR { 92 | return GreedyPLR { 93 | state: GreedyState::Need2, 94 | gamma, 95 | s0: None, 96 | s1: None, 97 | sint: None, 98 | s_last: None, 99 | rho_lower: None, 100 | rho_upper: None, 101 | }; 102 | } 103 | 104 | fn setup(&mut self) { 105 | // we have two points, initialize rho lower and rho upper. 106 | let gamma = self.gamma; 107 | let s0 = self.s0.as_ref().unwrap(); 108 | let s1 = self.s1.as_ref().unwrap(); 109 | 110 | self.rho_lower = Some(s0.upper_bound(gamma).line_to(&s1.lower_bound(gamma))); 111 | self.rho_upper = Some(s0.lower_bound(gamma).line_to(&s1.upper_bound(gamma))); 112 | 113 | self.sint = Some(Line::intersection( 114 | self.rho_lower.as_ref().unwrap(), 115 | self.rho_upper.as_ref().unwrap(), 116 | )); 117 | 118 | assert!(self.sint.is_some()); 119 | } 120 | 121 | fn current_segment(&self, end: f64) -> Segment { 122 | assert!(self.state == GreedyState::Ready); 123 | 124 | let segment_start = self.s0.as_ref().unwrap().as_tuple().0; 125 | let segment_stop = end; 126 | 127 | let avg_slope = Line::average_slope( 128 | self.rho_lower.as_ref().unwrap(), 129 | self.rho_upper.as_ref().unwrap(), 130 | ); 131 | 132 | let (sint_x, sint_y) = self.sint.as_ref().unwrap().as_tuple(); 133 | let intercept = -avg_slope * sint_x + sint_y; 134 | return Segment { 135 | start: segment_start, 136 | stop: segment_stop, 137 | slope: avg_slope, 138 | intercept, 139 | }; 140 | } 141 | 142 | fn process_pt(&mut self, pt: Point) -> Option { 143 | assert!(self.state == GreedyState::Ready); 144 | 145 | if !(pt.above(self.rho_lower.as_ref().unwrap()) 146 | && pt.below(self.rho_upper.as_ref().unwrap())) 147 | { 148 | // we cannot adjust either extreme slope to fit this point, we have to 149 | // start a new segment. 150 | let current_segment = self.current_segment(pt.as_tuple().0); 151 | 152 | self.s0 = Some(pt); 153 | self.state = GreedyState::Need1; 154 | return Some(current_segment); 155 | } 156 | 157 | // otherwise, we can adjust the extreme slopes to fit the point. 158 | let s_upper = pt.upper_bound(self.gamma); 159 | let s_lower = pt.lower_bound(self.gamma); 160 | if s_upper.below(self.rho_upper.as_ref().unwrap()) { 161 | self.rho_upper = Some(self.sint.as_ref().unwrap().line_to(&s_upper)); 162 | } 163 | 164 | if s_lower.above(self.rho_lower.as_ref().unwrap()) { 165 | self.rho_lower = Some(self.sint.as_ref().unwrap().line_to(&s_lower)); 166 | } 167 | 168 | return None; 169 | } 170 | 171 | /// Processes a single point using the greedy PLR algorithm. This function returns 172 | /// a new [`Segment`](../struct.Segment.html) when the current segment cannot accommodate 173 | /// the passed point, and returns None if the current segment could be (greedily) adjusted to 174 | /// fit the point. 175 | pub fn process(&mut self, x: f64, y: f64) -> Option { 176 | let pt = Point::new(x, y); 177 | self.s_last = Some(pt); 178 | 179 | let mut returned_segment: Option = None; 180 | 181 | let new_state = match self.state { 182 | GreedyState::Need2 => { 183 | self.s0 = Some(pt); 184 | GreedyState::Need1 185 | } 186 | GreedyState::Need1 => { 187 | self.s1 = Some(pt); 188 | self.setup(); 189 | GreedyState::Ready 190 | } 191 | GreedyState::Ready => { 192 | returned_segment = self.process_pt(pt); 193 | 194 | if returned_segment.is_some() { 195 | GreedyState::Need1 196 | } else { 197 | GreedyState::Ready 198 | } 199 | } 200 | }; 201 | 202 | self.state = new_state; 203 | return returned_segment; 204 | } 205 | 206 | /// Terminates the PLR process, returning a final segment if required. 207 | pub fn finish(self) -> Option { 208 | return match self.state { 209 | GreedyState::Need2 => None, 210 | GreedyState::Need1 => { 211 | let s0 = self.s0.unwrap().as_tuple(); 212 | Some(Segment { 213 | start: s0.0, 214 | stop: std::f64::MAX, 215 | slope: 0.0, 216 | intercept: s0.1, 217 | }) 218 | } 219 | GreedyState::Ready => Some(self.current_segment(std::f64::MAX)), 220 | }; 221 | } 222 | } 223 | 224 | #[cfg(test)] 225 | mod test { 226 | use super::*; 227 | use crate::test_util::*; 228 | 229 | #[test] 230 | fn test_sin() { 231 | let mut plr = GreedyPLR::new(0.0005); 232 | let data = sin_data(); 233 | 234 | let mut segments = Vec::new(); 235 | 236 | for &(x, y) in data.iter() { 237 | if let Some(segment) = plr.process(x, y) { 238 | segments.push(segment); 239 | } 240 | } 241 | 242 | if let Some(segment) = plr.finish() { 243 | segments.push(segment); 244 | } 245 | 246 | assert_eq!(segments.len(), 77); 247 | verify_gamma(0.0005, &data, &segments); 248 | } 249 | 250 | #[test] 251 | fn test_linear() { 252 | let mut plr = GreedyPLR::new(0.00005); 253 | let data = linear_data(10.0, 25.0); 254 | 255 | let mut segments = Vec::new(); 256 | 257 | for &(x, y) in data.iter() { 258 | if let Some(segment) = plr.process(x, y) { 259 | segments.push(segment); 260 | } 261 | } 262 | 263 | if let Some(segment) = plr.finish() { 264 | segments.push(segment); 265 | } 266 | 267 | assert_eq!(segments.len(), 1); 268 | verify_gamma(0.00005, &data, &segments); 269 | } 270 | 271 | #[test] 272 | fn test_precision() { 273 | let mut plr = GreedyPLR::new(0.00005); 274 | let data = precision_data(); 275 | 276 | let mut segments = Vec::new(); 277 | 278 | for &(x, y) in data.iter() { 279 | if let Some(segment) = plr.process(x, y) { 280 | segments.push(segment); 281 | } 282 | } 283 | 284 | if let Some(segment) = plr.finish() { 285 | segments.push(segment); 286 | } 287 | 288 | assert_eq!(segments.len(), 1); 289 | verify_gamma(0.00005, &data, &segments); 290 | } 291 | 292 | #[test] 293 | fn test_osm() { 294 | let mut plr = GreedyPLR::new(64.0); 295 | let data = osm_data(); 296 | 297 | let mut segments = Vec::new(); 298 | 299 | for &(x, y) in data.iter() { 300 | if let Some(segment) = plr.process(x, y) { 301 | segments.push(segment); 302 | } 303 | } 304 | 305 | if let Some(segment) = plr.finish() { 306 | segments.push(segment); 307 | } 308 | 309 | verify_gamma(64.0, &data, &segments); 310 | } 311 | 312 | #[test] 313 | fn test_fb() { 314 | let mut plr = GreedyPLR::new(64.0); 315 | let data = fb_data(); 316 | 317 | let mut segments = Vec::new(); 318 | 319 | for &(x, y) in data.iter() { 320 | if let Some(segment) = plr.process(x, y) { 321 | segments.push(segment); 322 | } 323 | } 324 | 325 | if let Some(segment) = plr.finish() { 326 | segments.push(segment); 327 | } 328 | 329 | verify_gamma(64.0, &data, &segments); 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /src/regression/optimal.rs: -------------------------------------------------------------------------------- 1 | // < begin copyright > 2 | // Copyright Ryan Marcus 2019 3 | // 4 | // This file is part of plr. 5 | // 6 | // plr is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // plr is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with plr. If not, see . 18 | // 19 | // < end copyright > 20 | use crate::util::{Line, Point, Segment}; 21 | use std::collections::VecDeque; 22 | 23 | struct Hull { 24 | upper: bool, 25 | data: VecDeque, 26 | } 27 | 28 | impl Hull { 29 | fn new_upper() -> Hull { 30 | return Hull { 31 | upper: true, 32 | data: VecDeque::new(), 33 | }; 34 | } 35 | 36 | fn new_lower() -> Hull { 37 | return Hull { 38 | upper: false, 39 | data: VecDeque::new(), 40 | }; 41 | } 42 | 43 | fn remove_front(&mut self, count: usize) { 44 | for _ in 0..count { 45 | let res = self.data.pop_front(); 46 | debug_assert!(res.is_some()); 47 | } 48 | } 49 | 50 | fn push(&mut self, pt: Point) { 51 | self.data.push_back(pt); 52 | 53 | while self.data.len() > 2 { 54 | let pt1 = &self.data[self.data.len() - 1]; 55 | let pt2 = &self.data[self.data.len() - 2]; 56 | let pt3 = &self.data[self.data.len() - 3]; 57 | 58 | let line = pt1.line_to(pt3); 59 | 60 | if (self.upper && pt2.above(&line)) || (!self.upper && pt2.below(&line)) { 61 | // remove p2 62 | let res = self.data.remove(self.data.len() - 2); 63 | debug_assert!(res.is_some()); 64 | } else { 65 | break; 66 | } 67 | } 68 | } 69 | 70 | fn items(&self) -> &VecDeque { 71 | return &self.data; 72 | } 73 | } 74 | 75 | #[derive(PartialEq)] 76 | enum OptimalState { 77 | Need2, 78 | Need1, 79 | Ready, 80 | } 81 | 82 | /// Performs an optimal piecewise linear regression (PLR) in an online fashion. This approach uses linear 83 | /// time for each call to [`process`](#method.process) and potentially linear space. In practice, 84 | /// the space used is generally a small fraction of the data. If constant space is required for your 85 | /// applications, please see [`GreedyPLR`](struct.GreedyPLR.html). 86 | /// 87 | /// Each call to [`process`](#method.process) consumes a single point. Each time it is called, 88 | /// [`process`](#method.process) returns either a [`Segment`](../struct.Segment.html) representing 89 | /// a piece of the final regression, or `None`. If your stream of points terminates, you can call 90 | /// [`finish`](#method.finish) to flush the buffer and return the final segment. 91 | /// 92 | /// # Example 93 | /// ``` 94 | /// use plr::regression::OptimalPLR; 95 | /// // first, generate some data points... 96 | /// let mut data = Vec::new(); 97 | /// 98 | /// for i in 0..1000 { 99 | /// let x = (i as f64) / 1000.0 * 7.0; 100 | /// let y = f64::sin(x); 101 | /// data.push((x, y)); 102 | /// } 103 | /// 104 | /// let mut plr = OptimalPLR::new(0.0005); // gamma = 0.0005, the maximum regression error 105 | /// 106 | /// let mut segments = Vec::new(); 107 | /// 108 | /// for (x, y) in data { 109 | /// // when `process` returns a segment, we should add it to our list 110 | /// if let Some(segment) = plr.process(x, y) { 111 | /// segments.push(segment); 112 | /// } 113 | /// } 114 | /// 115 | /// // because we have a finite amount of data, we flush the buffer and get the potential 116 | /// // last segment. 117 | /// if let Some(segment) = plr.finish() { 118 | /// segments.push(segment); 119 | /// } 120 | /// 121 | /// // the `segments` vector now contains all segments for this regression. 122 | /// ``` 123 | pub struct OptimalPLR { 124 | state: OptimalState, 125 | gamma: f64, 126 | s0: Option, 127 | s1: Option, 128 | s_last: Option, 129 | rho_lower: Option, 130 | rho_upper: Option, 131 | upper_hull: Option, 132 | lower_hull: Option, 133 | } 134 | 135 | impl OptimalPLR { 136 | /// Enables performing PLR using an optimal algorithm with a fixed gamma (maximum error). 137 | /// 138 | /// # Examples 139 | /// 140 | /// To perform an optimal PLR with a maximum error of `0.05`: 141 | /// ``` 142 | /// use plr::regression::OptimalPLR; 143 | /// let plr = OptimalPLR::new(0.05); 144 | /// ``` 145 | pub fn new(gamma: f64) -> OptimalPLR { 146 | return OptimalPLR { 147 | state: OptimalState::Need2, 148 | gamma, 149 | s0: None, 150 | s1: None, 151 | s_last: None, 152 | rho_lower: None, 153 | rho_upper: None, 154 | upper_hull: None, 155 | lower_hull: None, 156 | }; 157 | } 158 | 159 | fn setup(&mut self) { 160 | // we have two points, initialize rho lower and rho upper. 161 | let gamma = self.gamma; 162 | let s0 = self.s0.as_ref().unwrap(); 163 | let s1 = self.s1.as_ref().unwrap(); 164 | 165 | self.rho_lower = Some(s0.upper_bound(gamma).line_to(&s1.lower_bound(gamma))); 166 | self.rho_upper = Some(s0.lower_bound(gamma).line_to(&s1.upper_bound(gamma))); 167 | 168 | let mut upper_hull = Hull::new_upper(); 169 | let mut lower_hull = Hull::new_lower(); 170 | 171 | upper_hull.push(s0.upper_bound(gamma)); 172 | upper_hull.push(s1.upper_bound(gamma)); 173 | lower_hull.push(s0.lower_bound(gamma)); 174 | lower_hull.push(s1.lower_bound(gamma)); 175 | 176 | self.upper_hull = Some(upper_hull); 177 | self.lower_hull = Some(lower_hull); 178 | } 179 | 180 | fn current_segment(&self, end: f64) -> Segment { 181 | assert!(self.state == OptimalState::Ready); 182 | let sint = Line::intersection( 183 | self.rho_lower.as_ref().unwrap(), 184 | self.rho_upper.as_ref().unwrap(), 185 | ); 186 | let segment_start = self.s0.as_ref().unwrap().as_tuple().0; 187 | let segment_stop = end; 188 | 189 | let avg_slope = Line::average_slope( 190 | self.rho_lower.as_ref().unwrap(), 191 | self.rho_upper.as_ref().unwrap(), 192 | ); 193 | 194 | let (sint_x, sint_y) = sint.as_tuple(); 195 | let intercept = -avg_slope * sint_x + sint_y; 196 | return Segment { 197 | start: segment_start, 198 | stop: segment_stop, 199 | slope: avg_slope, 200 | intercept, 201 | }; 202 | } 203 | 204 | fn process_pt(&mut self, pt: Point) -> Option { 205 | assert!(self.state == OptimalState::Ready); 206 | if !(pt.above(self.rho_lower.as_ref().unwrap()) 207 | && pt.below(self.rho_upper.as_ref().unwrap())) 208 | { 209 | // we cannot adjust either extreme slope to fit this point, we have to 210 | // start a new segment. 211 | let current_segment = self.current_segment(pt.as_tuple().0); 212 | 213 | self.s0 = Some(pt); 214 | self.state = OptimalState::Need1; 215 | return Some(current_segment); 216 | } 217 | 218 | // otherwise, we can adjust the extreme slopes to fit the point. 219 | let s_upper = pt.upper_bound(self.gamma); 220 | let s_lower = pt.lower_bound(self.gamma); 221 | if s_upper.below(self.rho_upper.as_ref().unwrap()) { 222 | let lower_hull: &mut Hull = self.lower_hull.as_mut().unwrap(); 223 | 224 | // find the point in the lower hull that would minimize the slope 225 | // between that point and s_upper 226 | let it = lower_hull 227 | .items() 228 | .iter() 229 | .enumerate() 230 | .map(|(idx, pt)| (idx, pt.line_to(&s_upper))); 231 | 232 | // get the min, because we can't use .min() on f64 233 | let mut curr_best_val = std::f64::INFINITY; 234 | let mut curr_best_idx = 0; 235 | for (idx, line) in it { 236 | if line.slope() < curr_best_val { 237 | curr_best_idx = idx; 238 | curr_best_val = line.slope(); 239 | } 240 | } 241 | 242 | self.rho_upper = Some(s_upper.line_to(&lower_hull.items()[curr_best_idx])); 243 | 244 | lower_hull.remove_front(curr_best_idx); 245 | lower_hull.push(s_lower); 246 | } 247 | 248 | if s_lower.above(self.rho_lower.as_ref().unwrap()) { 249 | let upper_hull: &mut Hull = self.upper_hull.as_mut().unwrap(); 250 | 251 | // find the point in the upper hull that would maximize the slope 252 | // between that point and s_upper 253 | let it = upper_hull 254 | .items() 255 | .iter() 256 | .enumerate() 257 | .map(|(idx, pt)| (idx, pt.line_to(&s_lower))); 258 | 259 | // get the max, because we can't use .max() on f64 260 | let mut curr_best_val = -std::f64::INFINITY; 261 | let mut curr_best_idx = 0; 262 | for (idx, line) in it { 263 | if line.slope() > curr_best_val { 264 | curr_best_idx = idx; 265 | curr_best_val = line.slope(); 266 | } 267 | } 268 | 269 | self.rho_lower = Some(s_lower.line_to(&upper_hull.items()[curr_best_idx])); 270 | 271 | upper_hull.remove_front(curr_best_idx); 272 | upper_hull.push(s_upper); 273 | } 274 | 275 | return None; 276 | } 277 | 278 | /// Processes a single point using the optimal PLR algorithm. This function returns 279 | /// a new [`Segment`](../struct.Segment.html) when the current segment cannot accommodate 280 | /// the passed point, and returns None if the current segment could be (greedily) adjusted to 281 | /// fit the point. 282 | pub fn process(&mut self, x: f64, y: f64) -> Option { 283 | let pt = Point::new(x, y); 284 | self.s_last = Some(pt); 285 | 286 | let mut returned_segment: Option = None; 287 | 288 | let new_state = match self.state { 289 | OptimalState::Need2 => { 290 | self.s0 = Some(pt); 291 | OptimalState::Need1 292 | } 293 | OptimalState::Need1 => { 294 | self.s1 = Some(pt); 295 | self.setup(); 296 | OptimalState::Ready 297 | } 298 | OptimalState::Ready => { 299 | returned_segment = self.process_pt(pt); 300 | 301 | if returned_segment.is_some() { 302 | OptimalState::Need1 303 | } else { 304 | OptimalState::Ready 305 | } 306 | } 307 | }; 308 | 309 | self.state = new_state; 310 | return returned_segment; 311 | } 312 | 313 | /// Terminates the PLR process, returning a final segment if required. 314 | pub fn finish(self) -> Option { 315 | return match self.state { 316 | OptimalState::Need2 => None, 317 | OptimalState::Need1 => { 318 | let s0 = self.s0.unwrap().as_tuple(); 319 | Some(Segment { 320 | start: s0.0, 321 | stop: std::f64::MAX, 322 | slope: 0.0, 323 | intercept: s0.1, 324 | }) 325 | } 326 | OptimalState::Ready => Some(self.current_segment(std::f64::MAX)), 327 | }; 328 | } 329 | } 330 | 331 | #[cfg(test)] 332 | mod test { 333 | use super::*; 334 | use crate::test_util::*; 335 | use approx::*; 336 | 337 | #[test] 338 | fn test_upper_hull() { 339 | let mut hull = Hull::new_upper(); 340 | 341 | hull.push(Point::new(1.0, 1.0)); 342 | hull.push(Point::new(2.0, 1.0)); 343 | hull.push(Point::new(3.0, 3.0)); 344 | hull.push(Point::new(4.0, 3.0)); 345 | 346 | assert_eq!(hull.items().len(), 3); 347 | 348 | let items = hull.items(); 349 | 350 | // (1.0, 1.0) 351 | assert_relative_eq!(items[0].as_tuple().0, 1.0); 352 | assert_relative_eq!(items[0].as_tuple().1, 1.0); 353 | 354 | // (2.0, 1.0) 355 | assert_relative_eq!(items[1].as_tuple().0, 2.0); 356 | assert_relative_eq!(items[1].as_tuple().1, 1.0); 357 | 358 | // (4.0, 3.0) 359 | assert_relative_eq!(items[2].as_tuple().0, 4.0); 360 | assert_relative_eq!(items[2].as_tuple().1, 3.0); 361 | } 362 | 363 | #[test] 364 | fn test_lower_hull() { 365 | let mut hull = Hull::new_lower(); 366 | 367 | hull.push(Point::new(1.0, 1.0)); 368 | hull.push(Point::new(2.0, 1.0)); 369 | hull.push(Point::new(3.0, 3.0)); 370 | hull.push(Point::new(4.0, 3.0)); 371 | 372 | assert_eq!(hull.items().len(), 3); 373 | 374 | let items = hull.items(); 375 | 376 | // (1.0, 1.0) 377 | assert_relative_eq!(items[0].as_tuple().0, 1.0); 378 | assert_relative_eq!(items[0].as_tuple().1, 1.0); 379 | 380 | // (3.0, 3.0) 381 | assert_relative_eq!(items[1].as_tuple().0, 3.0); 382 | assert_relative_eq!(items[1].as_tuple().1, 3.0); 383 | 384 | // (4.0, 3.0) 385 | assert_relative_eq!(items[2].as_tuple().0, 4.0); 386 | assert_relative_eq!(items[2].as_tuple().1, 3.0); 387 | } 388 | 389 | #[test] 390 | fn test_sin() { 391 | let mut plr = OptimalPLR::new(0.0005); 392 | let data = sin_data(); 393 | 394 | let mut segments = Vec::new(); 395 | 396 | for &(x, y) in data.iter() { 397 | if let Some(segment) = plr.process(x, y) { 398 | segments.push(segment); 399 | } 400 | } 401 | 402 | if let Some(segment) = plr.finish() { 403 | segments.push(segment); 404 | } 405 | 406 | assert_eq!(segments.len(), 66); 407 | verify_gamma(0.0005, &data, &segments); 408 | } 409 | 410 | #[test] 411 | fn test_linear() { 412 | let mut plr = OptimalPLR::new(0.0005); 413 | let data = linear_data(10.0, 25.0); 414 | 415 | let mut segments = Vec::new(); 416 | 417 | for &(x, y) in data.iter() { 418 | if let Some(segment) = plr.process(x, y) { 419 | segments.push(segment); 420 | } 421 | } 422 | 423 | if let Some(segment) = plr.finish() { 424 | segments.push(segment); 425 | } 426 | 427 | assert_eq!(segments.len(), 1); 428 | verify_gamma(0.0005, &data, &segments); 429 | } 430 | 431 | #[test] 432 | fn test_precision() { 433 | let mut plr = OptimalPLR::new(0.00005); 434 | let data = precision_data(); 435 | 436 | let mut segments = Vec::new(); 437 | 438 | for &(x, y) in data.iter() { 439 | if let Some(segment) = plr.process(x, y) { 440 | segments.push(segment); 441 | } 442 | } 443 | 444 | if let Some(segment) = plr.finish() { 445 | segments.push(segment); 446 | } 447 | 448 | assert_eq!(segments.len(), 1); 449 | verify_gamma(0.00005, &data, &segments); 450 | } 451 | } 452 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // < begin copyright > 2 | // Copyright Ryan Marcus 2019 3 | // 4 | // This file is part of plr. 5 | // 6 | // plr is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // plr is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with plr. If not, see . 18 | // 19 | // < end copyright > 20 | #![allow(clippy::needless_return)] 21 | 22 | //! This crate provides code for performing error-bounded piecewise linear 23 | //! regression (PLR) in an online fashion using either a 24 | //! [greedy](regression/struct.GreedyPLR.html) (constant time per point, 25 | //! constant space) or [optimal](regression/struct.OptimalPLR.html) (linear 26 | //! time per point, linear space) algorithm. Both algorithms were 27 | //! implemented as described in: 28 | //! 29 | //! > Qing Xie, Chaoyi Pang, Xiaofang Zhou, Xiangliang Zhang, and Ke Deng. 30 | //! > 2014. Maximum error-bounded Piecewise Linear Representation for 31 | //! > online stream approximation. The VLDB Journal 23, 6 (December 2014), 32 | //! > 915–937. DOI: 33 | //! 34 | //! Error-bounded piecewise linear regression is the task of taking a set 35 | //! of datapoints and finding a piecewise linear function that approximates 36 | //! each datapoint within a fixed bound. In other words, given a dataset 37 | //! `(x, y) ∈ D`, we seek a piecewise linear function `f` such that `∀(x, 38 | //! y)∈D(|f(x) - y| < δ)`, for some given δ. This can also be thought of as 39 | //! minimizing the "L-infinity" loss. Since `f` could be trivially realized 40 | //! by a piecewise linear function with `|D|` pieces, we also seek the `f` 41 | //! with a minimal number of pieces. 42 | //! 43 | //!
44 | //! 740 | //!
741 | //! 742 | //! In the example above, we show the original 1000 data points (left), a 743 | //! PLR with a maximum error of 0.05 (center), and a PLR with a maximum 744 | //! error of 0.005. All of the displayed PLRs are optimal, meaning that 745 | //! they contain the fewest number segments possible to achieve their error 746 | //! bound. 747 | //! 748 | //! This package can perform PLR using one of two online algorithms: 749 | //! * [Greedy PLR](regression/struct.GreedyPLR.html), which uses a constant 750 | //! time per point and a constant amount of space. Greedy PLR always 751 | //! finds a PLR with the specified error bound (e.g., none of the 752 | //! original points will be more than δ from their predictions), but the 753 | //! greedy approach may not find the PLR with the minimal number of 754 | //! segments. 755 | //! * [Optimal PLR](regression/struct.OptimalPLR.html), which uses a linear 756 | //! time per point and potentially linear space. In practice, the amount 757 | //! of space used by the optimal algorithm should be small, but in the 758 | //! worst case linear space may be required (see [the 759 | //! paper](https://dl.acm.org/citation.cfm?id=2691542) for more details). 760 | //! The optimal algorithm will find the solution with a minimal number of 761 | //! segments. 762 | //! 763 | //! This package can also perform spline regression instead of piecewise 764 | //! linear regression. See [greedy_splines](spline/fn.greedy_spline.html), 765 | //! or the online version [GreedySpline](spline/struct.GreedySpline.html). 766 | //! 767 | //! 768 | //! Written by [Ryan Marcus](https://rmarcus.info), licensed under the GPL 769 | //! v3. 770 | 771 | pub mod regression; 772 | pub mod spline; 773 | mod util; 774 | 775 | #[cfg(test)] 776 | mod test_util; 777 | 778 | #[cfg(test)] 779 | mod data; 780 | 781 | //pub use regression::GreedyPLR; 782 | //pub use regression::OptimalPLR; 783 | 784 | pub use util::Segment; 785 | --------------------------------------------------------------------------------