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 fileTake it
Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
lines 1–3why, one step back1use std::ops::Add;2use std::ops::AddAssign;3use std::ops::Div;Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
line 4why, one step back4Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
lines 5–7why, one step back5use uom::num_traits;6use uom::si::f64::Ratio;7use uom::si::ratio::ratio;Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
line 8why, one step back8Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 9why, one step back9use super::{byte, second, Information, Time};Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 10–26why, one step back1011/// 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}26Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 27why, one step back27/// A mean function that assumes at least one elementMerge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 28–29why, one step back28pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q29whereMerge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 30why, one step back30 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 31–33why, one step back31 P: Into<Q>,32{33 let mut sum = Q::zero();Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 34why, one step back34 let mut count = 0;Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 35–53why, one step back35 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 );Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 54why, one step back54 values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 55–60why, one step back5556 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];Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 61why, one step back61 ((*a + *b) / Ratio::new::<ratio>(2.)).into()Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 62–93why, one step back62 } 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}93Support hardware counters (instructions, cache misses, ...) (#983)David Peterbefore adoptionbc3a3f0
lines 94–103why, one step back94impl 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}103Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
lines 104–105why, one step back104fn standard_deviation_f64(values: &[f64]) -> f64 {105 let mean_value = mean(values.iter().copied());Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
line 106why, one step back106Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
lines 107–115why, one step back107 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()Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 116–117why, one step back116}117Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
lines 118–123why, one step back118pub 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}123Merge pull request #883 from c-tonneslan/docs/modifized-typoDavid Peterbefore adoption87f3905
line 124why, one step back124/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined byMerge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 125–129why, one step back125/// `(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>Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
line 130why, one step back130pub fn modified_zscores_f64(xs: &[f64]) -> Vec<f64> {Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 131–146why, one step back131 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()Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
lines 147–148why, one step back147}148Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 149–231why, one step back149#[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 ];Merge pull request #976 from sharkdp/codex/remaining-statisticsDavid Peterbefore adoptionf48f44b
line 232why, one step back232 let result = standard_deviation(values);Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 233–235why, one step back233 assert_relative_eq!(result.get::<millisecond>(), 100.0);234 }235}