1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//! Bootstrap resampling functions
use rand::{Rng, seq::*};
use average::Variance;


/// returns reduced value + estimated error (as sqrt of variance).
/// Note, that you can use [bootstrap_copyable](crate::bootstrap_copyable) 
/// if your `N1` implements Copy
pub fn bootstrap<F, R, N1>(mut rng: R, samples: usize, data: &[N1], reduction: F) -> (f64, f64)
where F: Fn (&[&N1]) -> f64,
    R: Rng,
{
    let mut bootstrap_sample = Vec::with_capacity(data.len());
    let variance: Variance =
    (0..samples).map(|_|
        {
            bootstrap_sample.clear();
            bootstrap_sample.extend(
                (0..data.len())
                    .map(|_| 
                        {
                            data.choose(&mut rng).unwrap()
                        }
                    )
            );
            reduction(&bootstrap_sample)
        }
    ).collect();
    
    let mean = variance.mean();
    let variance = variance.population_variance();
    (mean, variance)
}

/// Similar to [bootstrap](crate::bootstrap::bootstrap) but for stuff that implements `Copy`. Likely more effient in these cases
/// returns reduced value + estimated error (as sqrt of variance)
pub fn bootstrap_copyable<F, R, N1>(mut rng: R, samples: usize, data: &[N1], reduction: F) -> (f64, f64)
where F: Fn (&mut [N1]) -> f64,
    R: Rng,
    N1: Copy
{
    let mut bootstrap_sample = Vec::with_capacity(data.len());
    let variance: Variance =
    (0..samples).map(|_|
        {
            bootstrap_sample.clear();
            bootstrap_sample.extend(
                (0..data.len())
                    .map(|_| 
                        {
                            data.choose(&mut rng).unwrap()
                        }
                    )
            );
            reduction(&mut bootstrap_sample)
        }
    ).collect();
    
    let mean = variance.mean();
    let variance = variance.population_variance();
    (mean, variance)
}