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
Provenance
- Commit
e9892ea- Tree
bc9c60f- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <mail@david-peter.de>- Parent
9c2ee56
3 files changed+130 added−334 removed
modified:src/benchmark/measurement.rs+2 added-4 removed
1 use std::process::ExitStatus;2 3 use serde::Serialize;4 5-use crate::quantity::{6- max, mean, median, min, modified_zscores, serialize_information, serialize_time,7- standard_deviation, Information, Time,8-};5+use crate::quantity::statistics::{max, mean, median, min, modified_zscores, standard_deviation};6+use crate::quantity::{serialize_information, serialize_time, Information, Time};7 use crate::util::exit_code::extract_exit_code;8 9 fn serialize_exit_status<S>(exit_status: &ExitStatus, serializer: S) -> Result<S::Ok, S::Error>10 where112 unmodified linesmodified:src/quantity/mod.rs+42 added-169 removed
1 use core::f64;2 use std::marker::PhantomData;3-use std::ops::Add;4-use std::ops::AddAssign;5-use std::ops::Div;3 4 use serde::ser::SerializeStruct;5 use serde::Serializer;6 10-use uom::num_traits;7 use uom::si;8 9 pub use si::f64::{Information, Ratio, Time};10 pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};2 unmodified lines13 pub use uom::num_traits::Zero;14 15 pub use units::{InformationUnit, IsUnit, TimeUnit};16 17+pub mod statistics;18 mod units;19 20 pub trait FormatQuantity {21 type Unit;57 unmodified lines79 80 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 }91 92 /// Format the information in the given unit with the given precision.39 unmodified lines132 state.serialize_field("unit", "byte")?;133 state.end()134 }135 135-pub trait UnsafeRawValue {136- fn unsafe_raw_value(&self) -> f64;137- fn unsafe_from_raw_value(value: f64) -> Self;138-}139-140-impl UnsafeRawValue for Time {141- fn unsafe_raw_value(&self) -> f64 {142- self.get::<second>()143- }144-145- fn unsafe_from_raw_value(value: f64) -> Self {146- Time::new::<second>(value)147- }148-}149-150-impl UnsafeRawValue for Information {151- fn unsafe_raw_value(&self) -> f64 {152- self.get::<byte>()153- }154-155- fn unsafe_from_raw_value(value: f64) -> Self {156- Information::new::<byte>(value)157- }158-}159-160-macro_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;165-166- Q::unsafe_from_raw_value(result_value)167- }168- };169-}170-171-/// A max function that assumes no NaNs and at least one element172-pub 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-}178-179-/// A min function that assumes no NaNs and at least one element180-pub 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-}186-187-/// A mean function that assumes at least one element188-pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q189-where190- 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- }199-200- let count = Ratio::new::<ratio>(count as f64);201- (sum / count).into()202-}203-204-pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q205-where206- 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"));211-212- 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-}222-223-quantity_fn!(standard_deviation, values, {224- let mean_value = statistical::mean(&values);225- statistical::standard_deviation(&values, Some(mean_value))226-});227-228-pub 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-}232-136 #[test]234-fn 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-}241-242-#[test]137 fn test_time() {138 let time = Time::new::<millisecond>(123.4);139 assert_eq!(time.get::<millisecond>(), 123.4);140 18 unmodified lines159 assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);160 }161 162 #[test]269-fn 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");274-275- 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-}282-283-#[test]284-fn 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-}292-293-#[test]294-fn test_suiteable_unit() {163+fn 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 lines181 );182 }183 184 #[test]185+fn 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+}203+204+#[test]205+fn 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");210+211+ 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+}218+219+#[test]220 fn 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 lines226 227 let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);228 assert_eq!("1300000.0 µs", out);229 }326-327-#[test]328-fn statistics() {329- let values = vec![330- Time::new::<second>(1.0),331- Time::new::<second>(2.0),332- Time::new::<second>(3.0),333- ];334-335- 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- );349-350- 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 lines7 use uom::si::ratio::ratio;8 9 use super::{byte, second, Information, Time};10 11-/// A min function that assumes no NaNs and at least one element12-pub 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")11+pub trait UnsafeRawValue {12+ fn unsafe_raw_value(&self) -> f64;13+ fn unsafe_from_raw_value(value: f64) -> Self;14 }15 16+impl UnsafeRawValue for Time {17+ fn unsafe_raw_value(&self) -> f64 {18+ self.get::<second>()19+ }20+21+ fn unsafe_from_raw_value(value: f64) -> Self {22+ Time::new::<second>(value)23+ }24+}25+26+impl UnsafeRawValue for Information {27+ fn unsafe_raw_value(&self) -> f64 {28+ self.get::<byte>()29+ }30+31+ fn unsafe_from_raw_value(value: f64) -> Self {32+ Information::new::<byte>(value)33+ }34+}35+36 /// A max function that assumes no NaNs and at least one element37 pub 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 }43 44+/// A min function that assumes no NaNs and at least one element45+pub 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+}51+52 /// A mean function that assumes at least one element53 pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q54 where55 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,15 unmodified lines71 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"));76 77 let len = values.len();78 if len % 2 == 0 {5 unmodified lines84 values[len / 2]85 }86 }87 67-/// 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.69-pub trait UnsafeRawValue {70- fn unsafe_raw_value(&self) -> f64;71- fn unsafe_from_raw_value(value: f64) -> Self;88+pub 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 }96 74-impl UnsafeRawValue for Time {75- fn unsafe_raw_value(&self) -> f64 {76- self.get::<second>()77- }78-79- fn unsafe_from_raw_value(value: f64) -> Self {80- Time::new::<second>(value)81- }97+pub 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 }101 84-impl UnsafeRawValue for Information {85- fn unsafe_raw_value(&self) -> f64 {86- self.get::<byte>()87- }88-89- fn unsafe_from_raw_value(value: f64) -> Self {90- Information::new::<byte>(value)91- }102+#[test]103+fn 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 }110 94-fn standard_deviation_f64(values: &[f64]) -> f64 {95- let mean_value = mean(values.iter().copied());111+#[test]112+fn test_mean() {113+ use crate::quantity::{FormatQuantity, TimeUnit};114+ use uom::si::time::millisecond;115 97- 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- }104-105- (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 }123 108-pub 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]125+fn statistics() {126+ use crate::quantity::{FormatQuantity, InformationUnit, TimeUnit};127 114-/// 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>120-pub 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+ ];133 123- // 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+ );148 126- // Compute the absolute deviations from the median:127- let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();128-129- // Compute median absolute deviation:130- let mad = median(deviations.iter().copied());131-132- // Handle MAD == 0 case133- let mad = if mad > 0.0 { mad } else { f64::EPSILON };134-135- // 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 }138-139-pub 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-}143-144-#[cfg(test)]145-mod tests {146- use super::*;147- use approx::assert_relative_eq;148- use uom::si::information::kibibyte;149- use uom::si::time::{microsecond, millisecond};150-151- #[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]));158-159- 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- }166-167- #[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]));174-175- 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- }182-183- #[test]184- fn test_mean() {185- assert_eq!(1.0, mean([1.0]));186- assert_relative_eq!(2.0, mean([1.0, 3.0]));187-188- 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- }196-197- #[test]198- fn test_median() {199- assert_eq!(1.0, median([1.0]));200- assert_relative_eq!(2.0, median([1.0, 3.0]));201-202- 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);209-210- 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- }219-220- #[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-}