Skip to content
Myr

statistics.rs

This file

Path

src/quantity/statistics.rs

225 lines · 6.9 KiB · Rust

Last changed by

Merge pull request #883 from c-tonneslan/docs/modifized-typoDavid Peterbefore adoption87f3905

History of this file

Take it

Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24

lines 1–108why, one step back
1//! Statistics for non-empty samples of finite measurements.
23use std::ops::{Add, AddAssign, Div};45use crate::quantity::{byte, ratio, second, Information, Ratio, Time, Zero};67/// A min function that assumes no NaNs and at least one element8pub fn min<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {9 values10 .into_iter()11 .min_by(|a, b| a.partial_cmp(b).expect("No NaN values"))12 .expect("'min' requires at least one element")13}1415/// A max function that assumes no NaNs and at least one element16pub fn max<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {17 values18 .into_iter()19 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))20 .expect("'max' requires at least one element")21}2223/// Arithmetic mean, summing measurements in their original order.24pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q25where26 Q: AddAssign + Zero + Div<Ratio, Output = P>,27 P: Into<Q>,28{29 let mut sum = Q::zero();30 let mut count = 0usize;31 for value in values {32 sum += value;33 count += 1;34 }3536 let count = Ratio::new::<ratio>(count as f64);37 (sum / count).into()38}3940/// Median without modifying the input sample.41pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q42where43 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,44 P: Into<Q>,45{46 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"));5253 let len = values.len();54 if len % 2 == 0 {55 let mid = len / 2;56 let a = &values[mid - 1];57 let b = &values[mid];58 ((*b + *a) / Ratio::new::<ratio>(2.)).into()59 } else {60 values[len / 2]61 }62}6364/// This is just sad, but after several hours trying to figure out how to write65/// a generic `standard_deviation` function using `uom` quantities, I gave up.66pub trait UnsafeRawValue {67 fn unsafe_raw_value(&self) -> f64;68 fn unsafe_from_raw_value(value: f64) -> Self;69}7071impl UnsafeRawValue for Time {72 fn unsafe_raw_value(&self) -> f64 {73 self.get::<second>()74 }7576 fn unsafe_from_raw_value(value: f64) -> Self {77 Time::new::<second>(value)78 }79}8081impl UnsafeRawValue for Information {82 fn unsafe_raw_value(&self) -> f64 {83 self.get::<byte>()84 }8586 fn unsafe_from_raw_value(value: f64) -> Self {87 Information::new::<byte>(value)88 }89}9091/// 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");103104 // 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())107}108

Merge pull request #883 from c-tonneslan/docs/modifized-typoDavid Peterbefore adoption87f3905

line 109why, one step back
109/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined by

Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24

lines 110–114why, one step back
110/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`
111/// where MAD is the median absolute deviation.112///113/// References:114/// - <https://en.wikipedia.org/wiki/Median_absolute_deviation>

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

line 115why, one step back
115pub fn modified_zscores_f64(xs: &[f64]) -> Vec<f64> {

Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24

lines 116–131why, one step back
116 assert!(!xs.is_empty());
117118 // Compute sample median:119 let x_median = median(xs.iter().copied());120121 // Compute the absolute deviations from the median:122 let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();123124 // Compute median absolute deviation:125 let mad = median(deviations.iter().copied());126127 // Handle MAD == 0 case128 let mad = if mad > 0.0 { mad } else { f64::EPSILON };129130 // Compute modified Z-scores (x_i - x_median) / MAD131 xs.iter().map(|&x| (x - x_median) / mad).collect()

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

lines 132–136why, one step back
132}
133134pub fn modified_zscores<Q: UnsafeRawValue>(values: &[Q]) -> Vec<f64> {135 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();136 modified_zscores_f64(&values)

Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24

lines 137–225why, one step back
137}
138139#[cfg(test)]140mod tests {141 use super::*;142 use approx::assert_relative_eq;143 use uom::si::information::kibibyte;144 use uom::si::time::{microsecond, millisecond};145146 #[test]147 fn test_min() {148 assert_eq!(1.0, min([1.0]));149 assert_eq!(-1.0, min([-1.0]));150 assert_eq!(-2.0, min([-2.0, -1.0]));151 assert_eq!(-1.0, min([-1.0, 1.0]));152 assert_eq!(-1.0, min([1.0, -1.0, 0.0]));153154 let values = vec![155 Information::new::<kibibyte>(1.0),156 Information::new::<byte>(2.0),157 Information::new::<byte>(3.0),158 ];159 assert_eq!(min(&values).get::<byte>(), 2.0);160 }161162 #[test]163 fn test_max() {164 assert_eq!(1.0, max([1.0]));165 assert_eq!(-1.0, max([-1.0]));166 assert_eq!(-1.0, max([-2.0, -1.0]));167 assert_eq!(1.0, max([-1.0, 1.0]));168 assert_eq!(1.0, max([-1.0, 1.0, 0.0]));169170 let values = vec![171 Information::new::<byte>(1.0),172 Information::new::<kibibyte>(2.0),173 Information::new::<byte>(3.0),174 ];175 assert_eq!(max(&values).get::<kibibyte>(), 2.0);176 }177178 #[test]179 fn test_mean() {180 assert_eq!(1.0, mean([1.0]));181 assert_relative_eq!(2.0, mean([1.0, 3.0]));182183 let values = [184 Time::new::<millisecond>(100.0),185 Time::new::<millisecond>(200.0),186 Time::new::<microsecond>(600_000.0),187 ];188 let result = mean(values);189 assert_relative_eq!(result.get::<millisecond>(), 300.0);190 }191192 #[test]193 fn test_median() {194 assert_eq!(1.0, median([1.0]));195 assert_relative_eq!(2.0, median([1.0, 3.0]));196197 let values = [198 Time::new::<millisecond>(100.0),199 Time::new::<millisecond>(200.0),200 Time::new::<microsecond>(600_000.0),201 ];202 let result = median(values);203 assert_relative_eq!(result.get::<millisecond>(), 200.0);204205 let values = [206 Time::new::<millisecond>(100.0),207 Time::new::<millisecond>(200.0),208 Time::new::<microsecond>(300_000.0),209 Time::new::<microsecond>(600_000.0),210 ];211 let result = median(values);212 assert_relative_eq!(result.get::<millisecond>(), 250.0);213 }214215 #[test]216 fn test_standard_deviation() {217 let values = [218 Time::new::<millisecond>(100.0),219 Time::new::<millisecond>(200.0),220 Time::new::<microsecond>(300_000.0),221 ];222 let result = standard_deviation(&values, mean(values));223 assert_relative_eq!(result.get::<millisecond>(), 100.0);224 }225}