Skip to content
Myr

Split out statistics module

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 9c2ee56 · Browse files · 3 files+130 added−334 removed
This commit

State

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

Diff stats

3 files+130 added−334 removed

  • other:+130 added−334 removed

3 files+130 added−334 removed

modified:src/benchmark/measurement.rs+2 added-4 removed
1use std::process::ExitStatus;23use serde::Serialize;45use crate::quantity::{6 max, mean, median, min, modified_zscores, serialize_information, serialize_time,7 standard_deviation, Information, Time,8};5use crate::quantity::statistics::{max, mean, median, min, modified_zscores, standard_deviation};6use crate::quantity::{serialize_information, serialize_time, Information, Time};7use crate::util::exit_code::extract_exit_code;89fn serialize_exit_status<S>(exit_status: &ExitStatus, serializer: S) -> Result<S::Ok, S::Error>10where
112 unmodified lines
modified:src/quantity/mod.rs+42 added-169 removed
1use core::f64;2use std::marker::PhantomData;3use std::ops::Add;4use std::ops::AddAssign;5use std::ops::Div;34use serde::ser::SerializeStruct;5use serde::Serializer;610use uom::num_traits;7use uom::si;89pub use si::f64::{Information, Ratio, Time};10pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};
2 unmodified lines
13pub use uom::num_traits::Zero;1415pub use units::{InformationUnit, IsUnit, TimeUnit};1617pub mod statistics;18mod units;1920pub trait FormatQuantity {21 type Unit;
57 unmodified lines
7980 fn suitable_unit(&self) -> InformationUnit {81 if *self < Information::new::<kibibyte>(1.0) {82 InformationUnit::Byte86 } else {83 } else if *self < Information::new::<mebibyte>(1.0) {84 InformationUnit::KibiByte85 } else if *self < Information::new::<gibibyte>(1.0) {86 InformationUnit::MebiByte87 } else {88 InformationUnit::GibiByte89 }90 }9192 /// Format the information in the given unit with the given precision.
39 unmodified lines
132 state.serialize_field("unit", "byte")?;133 state.end()134}135135pub trait UnsafeRawValue {136 fn unsafe_raw_value(&self) -> f64;137 fn unsafe_from_raw_value(value: f64) -> Self;138}139140impl UnsafeRawValue for Time {141 fn unsafe_raw_value(&self) -> f64 {142 self.get::<second>()143 }144145 fn unsafe_from_raw_value(value: f64) -> Self {146 Time::new::<second>(value)147 }148}149150impl UnsafeRawValue for Information {151 fn unsafe_raw_value(&self) -> f64 {152 self.get::<byte>()153 }154155 fn unsafe_from_raw_value(value: f64) -> Self {156 Information::new::<byte>(value)157 }158}159160macro_rules! quantity_fn {161 ($name:ident, $unwrapped_values:ident, $body:expr) => {162 pub fn $name<Q: UnsafeRawValue>(values: &[Q]) -> Q {163 let $unwrapped_values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();164 let result_value = $body;165166 Q::unsafe_from_raw_value(result_value)167 }168 };169}170171/// A max function that assumes no NaNs and at least one element172pub fn max<V: PartialOrd>(values: impl IntoIterator<Item = V>) -> V {173 values174 .into_iter()175 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))176 .expect("'max' requires at least one element")177}178179/// A min function that assumes no NaNs and at least one element180pub fn min<V: PartialOrd>(values: impl IntoIterator<Item = V>) -> V {181 values182 .into_iter()183 .min_by(|a, b| a.partial_cmp(b).expect("No NaN values"))184 .expect("'min' requires at least one element")185}186187/// A mean function that assumes at least one element188pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q189where190 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,191 P: Into<Q>,192{193 let mut sum = Q::zero();194 let mut count = 0;195 for value in values {196 sum += value;197 count += 1;198 }199200 let count = Ratio::new::<ratio>(count as f64);201 (sum / count).into()202}203204pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q205where206 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,207 P: Into<Q>,208{209 let mut values = values.into_iter().collect::<Vec<_>>();210 values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));211212 let len = values.len();213 if len % 2 == 0 {214 let mid = len / 2;215 let a = &values[mid - 1];216 let b = &values[mid];217 ((*a + *b) / Ratio::new::<ratio>(2.)).into()218 } else {219 values[len / 2]220 }221}222223quantity_fn!(standard_deviation, values, {224 let mean_value = statistical::mean(&values);225 statistical::standard_deviation(&values, Some(mean_value))226});227228pub fn modified_zscores<Q: UnsafeRawValue>(values: &[Q]) -> Vec<f64> {229 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();230 crate::outlier_detection::modified_zscores(&values)231}232136#[test]234fn test_max() {235 assert_eq!(1.0, max([1.0]));236 assert_eq!(-1.0, max([-1.0]));237 assert_eq!(-1.0, max([-2.0, -1.0]));238 assert_eq!(1.0, max([-1.0, 1.0]));239 assert_eq!(1.0, max([-1.0, 1.0, 0.0]));240}241242#[test]137fn test_time() {138 let time = Time::new::<millisecond>(123.4);139 assert_eq!(time.get::<millisecond>(), 123.4);140
18 unmodified lines
159 assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);160}161162#[test]269fn test_format() {270 let time = Time::new::<millisecond>(123.4);271 assert_eq!(time.format(TimeUnit::Second), "0.123 s");272 assert_eq!(time.format(TimeUnit::MilliSecond), "123.4 ms");273 assert_eq!(time.format(TimeUnit::MicroSecond), "123400.0 µs");274275 let peak_memory_usage = Information::new::<kibibyte>(8.);276 assert_eq!(peak_memory_usage.format(InformationUnit::Byte), "8192 B");277 assert_eq!(278 peak_memory_usage.format(InformationUnit::KibiByte),279 "8.0 KiB"280 );281}282283#[test]284fn test_mean() {285 let values = vec![286 Time::new::<millisecond>(123.4),287 Time::new::<millisecond>(234.5),288 ];289 let result = mean(values.into_iter());290 assert_eq!(result.format(TimeUnit::MilliSecond), "178.9 ms");291}292293#[test]294fn test_suiteable_unit() {163fn test_suiteable_unit_time() {164 assert_eq!(Time::new::<second>(1.3).suitable_unit(), TimeUnit::Second);165 assert_eq!(Time::new::<second>(1.0).suitable_unit(), TimeUnit::Second);166 assert_eq!(167 Time::new::<second>(0.999).suitable_unit(),
13 unmodified lines
181 );182}183184#[test]185fn test_suitable_unit_information() {186 assert_eq!(187 Information::new::<byte>(512.0).suitable_unit(),188 InformationUnit::Byte189 );190 assert_eq!(191 Information::new::<byte>(2048.0).suitable_unit(),192 InformationUnit::KibiByte193 );194 assert_eq!(195 Information::new::<byte>(2_097_152.0).suitable_unit(),196 InformationUnit::MebiByte197 );198 assert_eq!(199 Information::new::<byte>(2_147_483_648.0).suitable_unit(),200 InformationUnit::GibiByte201 );202}203204#[test]205fn test_format() {206 let time = Time::new::<millisecond>(123.4);207 assert_eq!(time.format(TimeUnit::Second), "0.123 s");208 assert_eq!(time.format(TimeUnit::MilliSecond), "123.4 ms");209 assert_eq!(time.format(TimeUnit::MicroSecond), "123400.0 µs");210211 let peak_memory_usage = Information::new::<kibibyte>(8.);212 assert_eq!(peak_memory_usage.format(InformationUnit::Byte), "8192 B");213 assert_eq!(214 peak_memory_usage.format(InformationUnit::KibiByte),215 "8.0 KiB"216 );217}218219#[test]220fn test_format_duration_unit_with_unit() {221 let out = Time::new::<second>(1.3).format(TimeUnit::Second);222 assert_eq!("1.300 s", out);223
2 unmodified lines
226227 let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);228 assert_eq!("1300000.0 µs", out);229}326327#[test]328fn statistics() {329 let values = vec![330 Time::new::<second>(1.0),331 Time::new::<second>(2.0),332 Time::new::<second>(3.0),333 ];334335 assert_eq!(336 mean(values.iter().copied()).format(TimeUnit::Second),337 "2.000 s"338 );339 assert_eq!(340 median(values.iter().copied()).format(TimeUnit::Second),341 "2.000 s"342 );343 assert_eq!(min(&values).format(TimeUnit::Second), "1.000 s");344 assert_eq!(max(&values).format(TimeUnit::Second), "3.000 s");345 assert_eq!(346 standard_deviation(&values).format(TimeUnit::Second),347 "1.000 s"348 );349350 let values = vec![351 Information::new::<byte>(1.0),352 Information::new::<byte>(2.0),353 Information::new::<byte>(3.0),354 ];355 mean(values.iter().copied()).format(InformationUnit::Byte);356}
modified:src/quantity/statistics.rs+86 added-161 removed
6 unmodified lines
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")11pub trait UnsafeRawValue {12 fn unsafe_raw_value(&self) -> f64;13 fn unsafe_from_raw_value(value: f64) -> Self;14}1516impl UnsafeRawValue for Time {17 fn unsafe_raw_value(&self) -> f64 {18 self.get::<second>()19 }2021 fn unsafe_from_raw_value(value: f64) -> Self {22 Time::new::<second>(value)23 }24}2526impl UnsafeRawValue for Information {27 fn unsafe_raw_value(&self) -> f64 {28 self.get::<byte>()29 }3031 fn unsafe_from_raw_value(value: f64) -> Self {32 Information::new::<byte>(value)33 }34}3536/// A max function that assumes no NaNs and at least one element37pub fn max<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {38 values39 .into_iter()40 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))41 .expect("'max' requires at least one element")42}4344/// A min function that assumes no NaNs and at least one element45pub fn min<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {46 values47 .into_iter()48 .min_by(|a, b| a.partial_cmp(b).expect("No NaN values"))49 .expect("'min' requires at least one element")50}5152/// A mean function that assumes at least one element53pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q54where55 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,
15 unmodified lines
71 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,72 P: Into<Q>,73{74 let mut values = values.into_iter().collect::<Vec<_>>();50 assert!(51 !values.is_empty(),52 "median requires at least one measurement"53 );75 values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));7677 let len = values.len();78 if len % 2 == 0 {
5 unmodified lines
84 values[len / 2]85 }86}8767/// 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;88pub fn standard_deviation<Q: UnsafeRawValue>(values: &[Q]) -> Q {89 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();90 let result_value = {91 let mean_value = statistical::mean(&values);92 statistical::standard_deviation(&values, Some(mean_value))93 };94 Q::unsafe_from_raw_value(result_value)95}9674impl 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 }97pub fn modified_zscores<Q: UnsafeRawValue>(values: &[Q]) -> Vec<f64> {98 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();99 crate::outlier_detection::modified_zscores(&values)100}10184impl 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 }102#[test]103fn test_max() {104 assert_eq!(1.0, max([1.0]));105 assert_eq!(-1.0, max([-1.0]));106 assert_eq!(-1.0, max([-2.0, -1.0]));107 assert_eq!(1.0, max([-1.0, 1.0]));108 assert_eq!(1.0, max([-1.0, 1.0, 0.0]));109}11094fn standard_deviation_f64(values: &[f64]) -> f64 {95 let mean_value = mean(values.iter().copied());111#[test]112fn test_mean() {113 use crate::quantity::{FormatQuantity, TimeUnit};114 use uom::si::time::millisecond;11597 let mut squared_deviations = 0.;98 let mut n = 0;99 for value in values {100 let deviation = value - mean_value;101 squared_deviations += deviation * deviation;102 n += 1;103 }104105 (1. / ((n - 1) as f64) * squared_deviations).sqrt()116 let values = vec![117 Time::new::<millisecond>(123.4),118 Time::new::<millisecond>(234.5),119 ];120 let result = mean(values.into_iter());121 assert_eq!(result.format(TimeUnit::MilliSecond), "178.9 ms");122}123108pub fn standard_deviation<Q: UnsafeRawValue>(values: impl IntoIterator<Item = Q> + Clone) -> Q {109 let values: Vec<_> = values.into_iter().map(|q| q.unsafe_raw_value()).collect();110 let result = standard_deviation_f64(&values);111 Q::unsafe_from_raw_value(result)112}124#[test]125fn statistics() {126 use crate::quantity::{FormatQuantity, InformationUnit, TimeUnit};127114/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined by115/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`116/// where MAD is the median absolute deviation.117///118/// References:119/// - <https://en.wikipedia.org/wiki/Median_absolute_deviation>120pub fn modified_zscores_f64(xs: &[f64]) -> Vec<f64> {121 assert!(!xs.is_empty());128 let values = vec![129 Time::new::<second>(1.0),130 Time::new::<second>(2.0),131 Time::new::<second>(3.0),132 ];133123 // Compute sample median:124 let x_median = median(xs.iter().copied());134 assert_eq!(135 mean(values.iter().copied()).format(TimeUnit::Second),136 "2.000 s"137 );138 assert_eq!(139 median(values.iter().copied()).format(TimeUnit::Second),140 "2.000 s"141 );142 assert_eq!(min(&values).format(TimeUnit::Second), "1.000 s");143 assert_eq!(max(&values).format(TimeUnit::Second), "3.000 s");144 assert_eq!(145 standard_deviation(&values).format(TimeUnit::Second),146 "1.000 s"147 );148126 // Compute the absolute deviations from the median:127 let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();128129 // Compute median absolute deviation:130 let mad = median(deviations.iter().copied());131132 // Handle MAD == 0 case133 let mad = if mad > 0.0 { mad } else { f64::EPSILON };134135 // Compute modified Z-scores (x_i - x_median) / MAD136 xs.iter().map(|&x| (x - x_median) / mad).collect()149 let values = vec![150 Information::new::<byte>(1.0),151 Information::new::<byte>(2.0),152 Information::new::<byte>(3.0),153 ];154 mean(values.iter().copied()).format(InformationUnit::Byte);155}138139pub fn modified_zscores<Q: UnsafeRawValue>(values: &[Q]) -> Vec<f64> {140 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();141 modified_zscores_f64(&values)142}143144#[cfg(test)]145mod tests {146 use super::*;147 use approx::assert_relative_eq;148 use uom::si::information::kibibyte;149 use uom::si::time::{microsecond, millisecond};150151 #[test]152 fn test_min() {153 assert_eq!(1.0, min([1.0]));154 assert_eq!(-1.0, min([-1.0]));155 assert_eq!(-2.0, min([-2.0, -1.0]));156 assert_eq!(-1.0, min([-1.0, 1.0]));157 assert_eq!(-1.0, min([1.0, -1.0, 0.0]));158159 let values = vec![160 Information::new::<kibibyte>(1.0),161 Information::new::<byte>(2.0),162 Information::new::<byte>(3.0),163 ];164 assert_eq!(min(&values).get::<byte>(), 2.0);165 }166167 #[test]168 fn test_max() {169 assert_eq!(1.0, max([1.0]));170 assert_eq!(-1.0, max([-1.0]));171 assert_eq!(-1.0, max([-2.0, -1.0]));172 assert_eq!(1.0, max([-1.0, 1.0]));173 assert_eq!(1.0, max([-1.0, 1.0, 0.0]));174175 let values = vec![176 Information::new::<byte>(1.0),177 Information::new::<kibibyte>(2.0),178 Information::new::<byte>(3.0),179 ];180 assert_eq!(max(&values).get::<kibibyte>(), 2.0);181 }182183 #[test]184 fn test_mean() {185 assert_eq!(1.0, mean([1.0]));186 assert_relative_eq!(2.0, mean([1.0, 3.0]));187188 let values = [189 Time::new::<millisecond>(100.0),190 Time::new::<millisecond>(200.0),191 Time::new::<microsecond>(600_000.0),192 ];193 let result = mean(values);194 assert_relative_eq!(result.get::<millisecond>(), 300.0);195 }196197 #[test]198 fn test_median() {199 assert_eq!(1.0, median([1.0]));200 assert_relative_eq!(2.0, median([1.0, 3.0]));201202 let values = [203 Time::new::<millisecond>(100.0),204 Time::new::<millisecond>(200.0),205 Time::new::<microsecond>(600_000.0),206 ];207 let result = median(values);208 assert_relative_eq!(result.get::<millisecond>(), 200.0);209210 let values = [211 Time::new::<millisecond>(100.0),212 Time::new::<millisecond>(200.0),213 Time::new::<microsecond>(300_000.0),214 Time::new::<microsecond>(600_000.0),215 ];216 let result = median(values);217 assert_relative_eq!(result.get::<millisecond>(), 250.0);218 }219220 #[test]221 fn test_standard_deviation() {222 let values = [223 Time::new::<millisecond>(100.0),224 Time::new::<millisecond>(200.0),225 Time::new::<microsecond>(300_000.0),226 ];227 let result = standard_deviation(values);228 assert_relative_eq!(result.get::<millisecond>(), 100.0);229 }230}