Skip to content
Myr

Adopt the remaining statistics changes from #790

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Peter · committed by David Peter · parent efd57b3 · Browse files · 2 files+35 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+35 added−33 removed

  • other:+35 added−33 removed

2 files+35 added−33 removed

modified:src/benchmark/measurement.rs+5 added-4 removed
52 unmodified lines
53 pub fn time_wall_clock_mean(&self) -> Time {54 mean(self.wall_clock_times())55 }5657 /// The standard deviation of wall clock times, if at least two runs were measured.57 /// The standard deviation of all wall clock times. Not available if only one run has been performed58 pub fn stddev(&self) -> Option<Time> {59 let times: Vec<_> = self.wall_clock_times().collect(); // TODO: Avoid collecting6059 if self.len() < 2 {61 if times.len() < 2 {62 None63 } else {62 let times: Vec<_> = self.wall_clock_times().collect();63 Some(standard_deviation(&times, self.time_wall_clock_mean()))64 Some(standard_deviation(times))65 }66 }6768 /// The median wall clock time.
33 unmodified lines
modified:src/quantity/statistics.rs+30 added-29 removed
1//! Statistics for non-empty samples of finite measurements.1use std::ops::Add;2use std::ops::AddAssign;3use std::ops::Div;43use std::ops::{Add, AddAssign, Div};5use uom::num_traits;6use uom::si::f64::Ratio;7use uom::si::ratio::ratio;85use crate::quantity::{byte, ratio, second, Information, Ratio, Time, Zero};9use super::{byte, second, Information, Time};1011/// A min function that assumes no NaNs and at least one element12pub fn min<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {13 values
9 unmodified lines
23 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))24 .expect("'max' requires at least one element")25}2623/// Arithmetic mean, summing measurements in their original order.27/// A mean function that assumes at least one element28pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q29where26 Q: AddAssign + Zero + Div<Ratio, Output = P>,30 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,31 P: Into<Q>,32{33 let mut sum = Q::zero();30 let mut count = 0usize;34 let mut count = 0;35 for value in values {36 sum += value;37 count += 1;38 }
1 unmodified line
40 let count = Ratio::new::<ratio>(count as f64);41 (sum / count).into()42}4340/// Median without modifying the input sample.44pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q45where46 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,47 P: Into<Q>,48{49 let mut values = values.into_iter().collect::<Vec<_>>();47 assert!(48 !values.is_empty(),49 "median requires at least one measurement"50 );51 values.sort_unstable_by(|a, b| a.partial_cmp(b).expect("No NaN measurements"));50 values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));5152 let len = values.len();53 if len % 2 == 0 {54 let mid = len / 2;55 let a = &values[mid - 1];56 let b = &values[mid];58 ((*b + *a) / Ratio::new::<ratio>(2.)).into()57 ((*a + *b) / Ratio::new::<ratio>(2.)).into()58 } else {59 values[len / 2]60 }61}
24 unmodified lines
86 Information::new::<byte>(value)87 }88}8991/// Sample standard deviation, using an already computed mean.92pub fn standard_deviation<Q: UnsafeRawValue>(values: &[Q], mean: Q) -> Q {93 let mean = mean.unsafe_raw_value();94 assert!(95 values.len() > 1,96 "standard deviation requires at least two measurements"97 );98 let sum = values99 .iter()100 .map(|value| (value.unsafe_raw_value() - mean) * (value.unsafe_raw_value() - mean))101 .fold(0.0, |sum, deviation| sum + deviation);102 assert!(sum >= 0.0, "invalid sum of squared deviations");90fn standard_deviation_f64(values: &[f64]) -> f64 {91 let mean_value = mean(values.iter().copied());92104 // Preserve the operation order of statistical 1.0: dividing by n - 1105 // before taking the square root also preserves exported floating-point values.106 Q::unsafe_from_raw_value((sum / (values.len() as f64 - 1.0)).sqrt())93 let mut squared_deviations = 0.;94 let mut n = 0;95 for value in values {96 let deviation = value - mean_value;97 squared_deviations += deviation * deviation;98 n += 1;99 }100101 (1. / ((n - 1) as f64) * squared_deviations).sqrt()102}103104pub fn standard_deviation<Q: UnsafeRawValue>(values: impl IntoIterator<Item = Q> + Clone) -> Q {105 let values: Vec<_> = values.into_iter().map(|q| q.unsafe_raw_value()).collect();106 let result = standard_deviation_f64(&values);107 Q::unsafe_from_raw_value(result)108}109110/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined by111/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`112/// where MAD is the median absolute deviation.113///
105 unmodified lines
219 Time::new::<millisecond>(100.0),220 Time::new::<millisecond>(200.0),221 Time::new::<microsecond>(300_000.0),222 ];222 let result = standard_deviation(&values, mean(values));223 let result = standard_deviation(values);224 assert_relative_eq!(result.get::<millisecond>(), 100.0);225 }226}