criterion/stats/univariate/
sample.rs1use std::{mem, ops};
2
3use cast;
4use rayon::prelude::*;
5use stats::float::Float;
6
7use stats::tuple::{Tuple, TupledDistributionsBuilder};
8use stats::univariate::Percentiles;
9use stats::univariate::Resamples;
10
11pub struct Sample<A>([A]);
18
19impl<A> Sample<A>
21where
22 A: Float,
23{
24 #[cfg_attr(feature = "cargo-clippy", allow(clippy::new_ret_no_self))]
30 pub fn new(slice: &[A]) -> &Sample<A> {
31 assert!(slice.len() > 1 && slice.iter().all(|x| !x.is_nan()));
32
33 unsafe { mem::transmute(slice) }
34 }
35
36 pub fn max(&self) -> A {
40 let mut elems = self.iter();
41
42 match elems.next() {
43 Some(&head) => elems.fold(head, |a, &b| a.max(b)),
44 None => unreachable!(),
46 }
47 }
48
49 pub fn mean(&self) -> A {
53 let n = self.len();
54
55 self.sum() / A::cast(n)
56 }
57
58 pub fn median_abs_dev(&self, median: Option<A>) -> A
65 where
66 usize: cast::From<A, Output = Result<usize, cast::Error>>,
67 {
68 let median = median.unwrap_or_else(|| self.percentiles().median());
69
70 let abs_devs = self.iter().map(|&x| (x - median).abs()).collect::<Vec<_>>();
73
74 let abs_devs: &Self = Self::new(&abs_devs);
75
76 abs_devs.percentiles().median() * A::cast(1.4826)
77 }
78
79 pub fn median_abs_dev_pct(&self) -> A
84 where
85 usize: cast::From<A, Output = Result<usize, cast::Error>>,
86 {
87 let _100 = A::cast(100);
88 let median = self.percentiles().median();
89 let mad = self.median_abs_dev(Some(median));
90
91 (mad / median) * _100
92 }
93
94 pub fn min(&self) -> A {
98 let mut elems = self.iter();
99
100 match elems.next() {
101 Some(&elem) => elems.fold(elem, |a, &b| a.min(b)),
102 None => unreachable!(),
104 }
105 }
106
107 pub fn percentiles(&self) -> Percentiles<A>
114 where
115 usize: cast::From<A, Output = Result<usize, cast::Error>>,
116 {
117 use std::cmp::Ordering;
118
119 fn cmp<T>(a: &T, b: &T) -> Ordering
121 where
122 T: PartialOrd,
123 {
124 if a < b {
125 Ordering::Less
126 } else if a == b {
127 Ordering::Equal
128 } else {
129 Ordering::Greater
130 }
131 }
132
133 let mut v = self.to_vec().into_boxed_slice();
134 v.par_sort_unstable_by(cmp);
135
136 unsafe { mem::transmute(v) }
138 }
139
140 pub fn std_dev(&self, mean: Option<A>) -> A {
146 self.var(mean).sqrt()
147 }
148
149 pub fn std_dev_pct(&self) -> A {
153 let _100 = A::cast(100);
154 let mean = self.mean();
155 let std_dev = self.std_dev(Some(mean));
156
157 (std_dev / mean) * _100
158 }
159
160 pub fn sum(&self) -> A {
164 ::stats::sum(self)
165 }
166
167 pub fn t(&self, other: &Sample<A>) -> A {
171 let (x_bar, y_bar) = (self.mean(), other.mean());
172 let (s2_x, s2_y) = (self.var(Some(x_bar)), other.var(Some(y_bar)));
173 let n_x = A::cast(self.len());
174 let n_y = A::cast(other.len());
175 let num = x_bar - y_bar;
176 let den = (s2_x / n_x + s2_y / n_y).sqrt();
177
178 num / den
179 }
180
181 pub fn var(&self, mean: Option<A>) -> A {
187 use std::ops::Add;
188
189 let mean = mean.unwrap_or_else(|| self.mean());
190 let slice = self;
191
192 let sum = slice
193 .iter()
194 .map(|&x| (x - mean).powi(2))
195 .fold(A::cast(0), Add::add);
196
197 sum / A::cast(slice.len() - 1)
198 }
199
200 pub fn bootstrap<T, S>(&self, nresamples: usize, statistic: S) -> T::Distributions
207 where
208 S: Fn(&Sample<A>) -> T,
209 S: Sync,
210 T: Tuple,
211 T: Send,
212 T::Distributions: Send,
213 T::Builder: Send,
214 {
215 (0..nresamples)
216 .into_par_iter()
217 .map_init(
218 || Resamples::new(self),
219 |resamples, _| statistic(resamples.next()),
220 )
221 .fold(
222 || T::Builder::new(0),
223 |mut sub_distributions, sample| {
224 sub_distributions.push(sample);
225 sub_distributions
226 },
227 )
228 .reduce(
229 || T::Builder::new(0),
230 |mut a, mut b| {
231 a.extend(&mut b);
232 a
233 },
234 )
235 .complete()
236 }
237
238 #[cfg(test)]
239 pub fn iqr(&self) -> A
240 where
241 usize: cast::From<A, Output = Result<usize, cast::Error>>,
242 {
243 self.percentiles().iqr()
244 }
245
246 #[cfg(test)]
247 pub fn median(&self) -> A
248 where
249 usize: cast::From<A, Output = Result<usize, cast::Error>>,
250 {
251 self.percentiles().median()
252 }
253}
254
255impl<A> ops::Deref for Sample<A> {
256 type Target = [A];
257
258 fn deref(&self) -> &[A] {
259 &self.0
260 }
261}