Skip to content
Myr

statistics.rs

This file

Path

src/quantity/statistics.rs

235 lines · 6.7 KiB · Rust

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take it

1use std::ops::Add;2use std::ops::AddAssign;3use std::ops::Div;45use uom::num_traits;6use uom::si::f64::Ratio;7use uom::si::ratio::ratio;89use 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    values14        .into_iter()15        .min_by(|a, b| a.partial_cmp(b).expect("No NaN values"))16        .expect("'min' requires at least one element")17}1819/// A max function that assumes no NaNs and at least one element20pub fn max<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {21    values22        .into_iter()23        .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))24        .expect("'max' requires at least one element")25}2627/// A mean function that assumes at least one element28pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q29where30    Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,31    P: Into<Q>,32{33    let mut sum = Q::zero();34    let mut count = 0;35    for value in values {36        sum += value;37        count += 1;38    }3940    let count = Ratio::new::<ratio>(count as f64);41    (sum / count).into()42}4344pub 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<_>>();50    assert!(51        !values.is_empty(),52        "median requires at least one measurement"53    );54    values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));5556    let len = values.len();57    if len % 2 == 0 {58        let mid = len / 2;59        let a = &values[mid - 1];60        let b = &values[mid];61        ((*a + *b) / Ratio::new::<ratio>(2.)).into()62    } else {63        values[len / 2]64    }65}6667/// This is just sad, but after several hours trying to figure out how to write68/// a generic `standard_deviation` function using `uom` quantities, I gave up.69pub trait UnsafeRawValue {70    fn unsafe_raw_value(&self) -> f64;71    fn unsafe_from_raw_value(value: f64) -> Self;72}7374impl UnsafeRawValue for Time {75    fn unsafe_raw_value(&self) -> f64 {76        self.get::<second>()77    }7879    fn unsafe_from_raw_value(value: f64) -> Self {80        Time::new::<second>(value)81    }82}8384impl UnsafeRawValue for Information {85    fn unsafe_raw_value(&self) -> f64 {86        self.get::<byte>()87    }8889    fn unsafe_from_raw_value(value: f64) -> Self {90        Information::new::<byte>(value)91    }92}9394impl UnsafeRawValue for Ratio {95    fn unsafe_raw_value(&self) -> f64 {96        self.get::<ratio>()97    }9899    fn unsafe_from_raw_value(value: f64) -> Self {100        Ratio::new::<ratio>(value)101    }102}103104fn standard_deviation_f64(values: &[f64]) -> f64 {105    let mean_value = mean(values.iter().copied());106107    let mut squared_deviations = 0.;108    let mut n = 0;109    for value in values {110        let deviation = value - mean_value;111        squared_deviations += deviation * deviation;112        n += 1;113    }114115    (1. / ((n - 1) as f64) * squared_deviations).sqrt()116}117118pub fn standard_deviation<Q: UnsafeRawValue>(values: impl IntoIterator<Item = Q> + Clone) -> Q {119    let values: Vec<_> = values.into_iter().map(|q| q.unsafe_raw_value()).collect();120    let result = standard_deviation_f64(&values);121    Q::unsafe_from_raw_value(result)122}123124/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined by125/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`126/// where MAD is the median absolute deviation.127///128/// References:129/// - <https://en.wikipedia.org/wiki/Median_absolute_deviation>130pub fn modified_zscores_f64(xs: &[f64]) -> Vec<f64> {131    assert!(!xs.is_empty());132133    // Compute sample median:134    let x_median = median(xs.iter().copied());135136    // Compute the absolute deviations from the median:137    let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();138139    // Compute median absolute deviation:140    let mad = median(deviations.iter().copied());141142    // Handle MAD == 0 case143    let mad = if mad > 0.0 { mad } else { f64::EPSILON };144145    // Compute modified Z-scores (x_i - x_median) / MAD146    xs.iter().map(|&x| (x - x_median) / mad).collect()147}148149#[cfg(test)]150mod tests {151    use super::*;152    use approx::assert_relative_eq;153    use uom::si::information::kibibyte;154    use uom::si::time::{microsecond, millisecond};155156    #[test]157    fn test_min() {158        assert_eq!(1.0, min([1.0]));159        assert_eq!(-1.0, min([-1.0]));160        assert_eq!(-2.0, min([-2.0, -1.0]));161        assert_eq!(-1.0, min([-1.0, 1.0]));162        assert_eq!(-1.0, min([1.0, -1.0, 0.0]));163164        let values = vec![165            Information::new::<kibibyte>(1.0),166            Information::new::<byte>(2.0),167            Information::new::<byte>(3.0),168        ];169        assert_eq!(min(&values).get::<byte>(), 2.0);170    }171172    #[test]173    fn test_max() {174        assert_eq!(1.0, max([1.0]));175        assert_eq!(-1.0, max([-1.0]));176        assert_eq!(-1.0, max([-2.0, -1.0]));177        assert_eq!(1.0, max([-1.0, 1.0]));178        assert_eq!(1.0, max([-1.0, 1.0, 0.0]));179180        let values = vec![181            Information::new::<byte>(1.0),182            Information::new::<kibibyte>(2.0),183            Information::new::<byte>(3.0),184        ];185        assert_eq!(max(&values).get::<kibibyte>(), 2.0);186    }187188    #[test]189    fn test_mean() {190        assert_eq!(1.0, mean([1.0]));191        assert_relative_eq!(2.0, mean([1.0, 3.0]));192193        let values = [194            Time::new::<millisecond>(100.0),195            Time::new::<millisecond>(200.0),196            Time::new::<microsecond>(600_000.0),197        ];198        let result = mean(values);199        assert_relative_eq!(result.get::<millisecond>(), 300.0);200    }201202    #[test]203    fn test_median() {204        assert_eq!(1.0, median([1.0]));205        assert_relative_eq!(2.0, median([1.0, 3.0]));206207        let values = [208            Time::new::<millisecond>(100.0),209            Time::new::<millisecond>(200.0),210            Time::new::<microsecond>(600_000.0),211        ];212        let result = median(values);213        assert_relative_eq!(result.get::<millisecond>(), 200.0);214215        let values = [216            Time::new::<millisecond>(100.0),217            Time::new::<millisecond>(200.0),218            Time::new::<microsecond>(300_000.0),219            Time::new::<microsecond>(600_000.0),220        ];221        let result = median(values);222        assert_relative_eq!(result.get::<millisecond>(), 250.0);223    }224225    #[test]226    fn test_standard_deviation() {227        let values = [228            Time::new::<millisecond>(100.0),229            Time::new::<millisecond>(200.0),230            Time::new::<microsecond>(300_000.0),231        ];232        let result = standard_deviation(values);233        assert_relative_eq!(result.get::<millisecond>(), 100.0);234    }235}