Skip to content

Commit 050c2d7

Browse files
committed
Switch to a slower but more extensible binning strategy
1 parent 4094e4a commit 050c2d7

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

src/histogram.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ TODO:
2121
*/
2222

2323
use axis;
24+
use utils::PairWise;
2425

2526
#[derive(Debug)]
2627
pub struct Histogram {
@@ -51,11 +52,15 @@ impl Histogram {
5152
let bounds = bounds;
5253

5354
for &val in v.iter() {
55+
/*
5456
let mut bin = ((val - min) / bin_width) as usize;
5557
if bin == num_bins && val == max {
5658
//We are right on the top-most bound
5759
bin = num_bins - 1;
5860
}
61+
*/
62+
63+
let bin = bounds.pairwise().enumerate().skip_while(|&(_, (&l, &u))| !(val >= l && val <= u)).map(|(i, (_,_))| i).next().unwrap();
5964
bins[bin] += 1;
6065
}
6166
let density_per_bin = bins.iter().map(|&x| x as f64 / bin_width).collect();

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ Data structures and helpers for managing plotting data
66

77
pub mod histogram;
88
pub mod axis;
9+
pub mod utils;

src/utils.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use std::iter::{Zip, Skip};
2+
use std::slice::Iter;
3+
4+
pub trait PairWise<T> {
5+
fn pairwise(&self) -> Zip<Iter<T>, Skip<Iter<T>>>;
6+
}
7+
8+
impl<T> PairWise<T> for [T] {
9+
fn pairwise(&self) -> Zip<Iter<T>, Skip<Iter<T>>> {
10+
self.iter().zip(self.iter().skip(1))
11+
}
12+
}
13+
14+
#[cfg(test)]
15+
mod tests {
16+
use super::*;
17+
18+
#[test]
19+
fn test_pairwise() {
20+
let a = [1, 2, 3, 4, 5];
21+
assert_eq!(a.pairwise().nth(0).unwrap(), (&1, &2));
22+
assert_eq!(a.pairwise().last().unwrap(), (&4, &5));
23+
assert_eq!(a.pairwise().len(), a.len() - 1);
24+
25+
let a = [1, 2];
26+
assert_eq!(a.pairwise().nth(0).unwrap(), (&1, &2));
27+
assert_eq!(a.pairwise().last().unwrap(), (&1, &2));
28+
assert_eq!(a.pairwise().len(), a.len() - 1);
29+
30+
let a = [1];
31+
assert!(a.pairwise().nth(0).is_none());
32+
33+
let b: Vec<f64> = vec![0.0, 0.1, 0.2];
34+
assert_eq!(b.pairwise().nth(0).unwrap(), (&0.0, &0.1));
35+
}
36+
}

0 commit comments

Comments
 (0)