diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-18 02:49:50 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-18 02:49:50 +0000 |
commit | 9835e2ae736235810b4ea1c162ca5e65c547e770 (patch) | |
tree | 3fcebf40ed70e581d776a8a4c65923e8ec20e026 /vendor/plotters/src/data | |
parent | Releasing progress-linux version 1.70.0+dfsg2-1~progress7.99u1. (diff) | |
download | rustc-9835e2ae736235810b4ea1c162ca5e65c547e770.tar.xz rustc-9835e2ae736235810b4ea1c162ca5e65c547e770.zip |
Merging upstream version 1.71.1+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/plotters/src/data')
-rw-r--r-- | vendor/plotters/src/data/data_range.rs | 42 | ||||
-rw-r--r-- | vendor/plotters/src/data/float.rs | 145 | ||||
-rw-r--r-- | vendor/plotters/src/data/mod.rs | 13 | ||||
-rw-r--r-- | vendor/plotters/src/data/quartiles.rs | 127 |
4 files changed, 327 insertions, 0 deletions
diff --git a/vendor/plotters/src/data/data_range.rs b/vendor/plotters/src/data/data_range.rs new file mode 100644 index 000000000..445260b97 --- /dev/null +++ b/vendor/plotters/src/data/data_range.rs @@ -0,0 +1,42 @@ +use std::cmp::{Ordering, PartialOrd}; +use std::iter::IntoIterator; +use std::ops::Range; + +use num_traits::{One, Zero}; + +/// Build a range that fits the data +/// +/// - `iter`: the iterator over the data +/// - **returns** The resulting range +/// +/// ```rust +/// use plotters::data::fitting_range; +/// +/// let data = [4, 14, -2, 2, 5]; +/// let range = fitting_range(&data); +/// assert_eq!(range, std::ops::Range { start: -2, end: 14 }); +/// ``` +pub fn fitting_range<'a, T: 'a, I: IntoIterator<Item = &'a T>>(iter: I) -> Range<T> +where + T: Zero + One + PartialOrd + Clone, +{ + let (mut lb, mut ub) = (None, None); + + for value in iter.into_iter() { + if let Some(Ordering::Greater) = lb + .as_ref() + .map_or(Some(Ordering::Greater), |lbv: &T| lbv.partial_cmp(value)) + { + lb = Some(value.clone()); + } + + if let Some(Ordering::Less) = ub + .as_ref() + .map_or(Some(Ordering::Less), |ubv: &T| ubv.partial_cmp(value)) + { + ub = Some(value.clone()); + } + } + + lb.unwrap_or_else(Zero::zero)..ub.unwrap_or_else(One::one) +} diff --git a/vendor/plotters/src/data/float.rs b/vendor/plotters/src/data/float.rs new file mode 100644 index 000000000..febd330ea --- /dev/null +++ b/vendor/plotters/src/data/float.rs @@ -0,0 +1,145 @@ +// The code that is related to float number handling +fn find_minimal_repr(n: f64, eps: f64) -> (f64, usize) { + if eps >= 1.0 { + return (n, 0); + } + if n - n.floor() < eps { + (n.floor(), 0) + } else if n.ceil() - n < eps { + (n.ceil(), 0) + } else { + let (rem, pre) = find_minimal_repr((n - n.floor()) * 10.0, eps * 10.0); + (n.floor() + rem / 10.0, pre + 1) + } +} + +#[allow(clippy::never_loop)] +fn float_to_string(n: f64, max_precision: usize, min_decimal: usize) -> String { + let (mut result, mut count) = loop { + let (sign, n) = if n < 0.0 { ("-", -n) } else { ("", n) }; + let int_part = n.floor(); + + let dec_part = + ((n.abs() - int_part.abs()) * (10.0f64).powi(max_precision as i32)).round() as u64; + + if dec_part == 0 || max_precision == 0 { + break (format!("{}{:.0}", sign, int_part), 0); + } + + let mut leading = "".to_string(); + let mut dec_result = format!("{}", dec_part); + + for _ in 0..(max_precision - dec_result.len()) { + leading.push('0'); + } + + while let Some(c) = dec_result.pop() { + if c != '0' { + dec_result.push(c); + break; + } + } + + break ( + format!("{}{:.0}.{}{}", sign, int_part, leading, dec_result), + leading.len() + dec_result.len(), + ); + }; + + if count == 0 && min_decimal > 0 { + result.push('.'); + } + + while count < min_decimal { + result.push('0'); + count += 1; + } + result +} + +/// Handles printing of floating point numbers +pub struct FloatPrettyPrinter { + /// Whether scientific notation is allowed + pub allow_scientific: bool, + /// Minimum allowed number of decimal digits + pub min_decimal: i32, + /// Maximum allowed number of decimal digits + pub max_decimal: i32, +} + +impl FloatPrettyPrinter { + /// Handles printing of floating point numbers + pub fn print(&self, n: f64) -> String { + let (tn, p) = find_minimal_repr(n, (10f64).powi(-self.max_decimal)); + let d_repr = float_to_string(tn, p, self.min_decimal as usize); + if !self.allow_scientific { + d_repr + } else { + if n == 0.0 { + return "0".to_string(); + } + + let mut idx = n.abs().log10().floor(); + let mut exp = (10.0f64).powf(idx); + + if n.abs() / exp + 1e-5 >= 10.0 { + idx += 1.0; + exp *= 10.0; + } + + if idx.abs() < 3.0 { + return d_repr; + } + + let (sn, sp) = find_minimal_repr(n / exp, 1e-5); + let s_repr = format!( + "{}e{}", + float_to_string(sn, sp, self.min_decimal as usize), + float_to_string(idx, 0, 0) + ); + if s_repr.len() + 1 < d_repr.len() || (tn == 0.0 && n != 0.0) { + s_repr + } else { + d_repr + } + } + } +} + +/// The function that pretty prints the floating number +/// Since rust doesn't have anything that can format a float with out appearance, so we just +/// implement a float pretty printing function, which finds the shortest representation of a +/// floating point number within the allowed error range. +/// +/// - `n`: The float number to pretty-print +/// - `allow_sn`: Should we use scientific notation when possible +/// - **returns**: The pretty printed string +pub fn pretty_print_float(n: f64, allow_sn: bool) -> String { + (FloatPrettyPrinter { + allow_scientific: allow_sn, + min_decimal: 0, + max_decimal: 10, + }) + .print(n) +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn test_pretty_printing() { + assert_eq!(pretty_print_float(0.99999999999999999999, false), "1"); + assert_eq!(pretty_print_float(0.9999, false), "0.9999"); + assert_eq!( + pretty_print_float(-1e-5 - 0.00000000000000001, true), + "-1e-5" + ); + assert_eq!( + pretty_print_float(-1e-5 - 0.00000000000000001, false), + "-0.00001" + ); + assert_eq!(pretty_print_float(1e100, true), "1e100"); + assert_eq!(pretty_print_float(1234567890f64, true), "1234567890"); + assert_eq!(pretty_print_float(1000000001f64, true), "1e9"); + } +} diff --git a/vendor/plotters/src/data/mod.rs b/vendor/plotters/src/data/mod.rs new file mode 100644 index 000000000..a6b903894 --- /dev/null +++ b/vendor/plotters/src/data/mod.rs @@ -0,0 +1,13 @@ +/*! +The data processing module, which implements algorithms related to visualization of data. +Such as, down-sampling, etc. +*/ + +mod data_range; +pub use data_range::fitting_range; + +mod quartiles; +pub use quartiles::Quartiles; + +/// Handles the printing of floating-point numbers. +pub mod float; diff --git a/vendor/plotters/src/data/quartiles.rs b/vendor/plotters/src/data/quartiles.rs new file mode 100644 index 000000000..054f51d1a --- /dev/null +++ b/vendor/plotters/src/data/quartiles.rs @@ -0,0 +1,127 @@ +/// The quartiles +#[derive(Clone, Debug)] +pub struct Quartiles { + lower_fence: f64, + lower: f64, + median: f64, + upper: f64, + upper_fence: f64, +} + +impl Quartiles { + // Extract a value representing the `pct` percentile of a + // sorted `s`, using linear interpolation. + fn percentile_of_sorted<T: Into<f64> + Copy>(s: &[T], pct: f64) -> f64 { + assert!(!s.is_empty()); + if s.len() == 1 { + return s[0].into(); + } + assert!(0_f64 <= pct); + let hundred = 100_f64; + assert!(pct <= hundred); + if (pct - hundred).abs() < std::f64::EPSILON { + return s[s.len() - 1].into(); + } + let length = (s.len() - 1) as f64; + let rank = (pct / hundred) * length; + let lower_rank = rank.floor(); + let d = rank - lower_rank; + let n = lower_rank as usize; + let lo = s[n].into(); + let hi = s[n + 1].into(); + lo + (hi - lo) * d + } + + /// Create a new quartiles struct with the values calculated from the argument. + /// + /// - `s`: The array of the original values + /// - **returns** The newly created quartiles + /// + /// ```rust + /// use plotters::prelude::*; + /// + /// let quartiles = Quartiles::new(&[7, 15, 36, 39, 40, 41]); + /// assert_eq!(quartiles.median(), 37.5); + /// ``` + pub fn new<T: Into<f64> + Copy + PartialOrd>(s: &[T]) -> Self { + let mut s = s.to_owned(); + s.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); + + let lower = Quartiles::percentile_of_sorted(&s, 25_f64); + let median = Quartiles::percentile_of_sorted(&s, 50_f64); + let upper = Quartiles::percentile_of_sorted(&s, 75_f64); + let iqr = upper - lower; + let lower_fence = lower - 1.5 * iqr; + let upper_fence = upper + 1.5 * iqr; + Self { + lower_fence, + lower, + median, + upper, + upper_fence, + } + } + + /// Get the quartiles values. + /// + /// - **returns** The array [lower fence, lower quartile, median, upper quartile, upper fence] + /// + /// ```rust + /// use plotters::prelude::*; + /// + /// let quartiles = Quartiles::new(&[7, 15, 36, 39, 40, 41]); + /// let values = quartiles.values(); + /// assert_eq!(values, [-9.0, 20.25, 37.5, 39.75, 69.0]); + /// ``` + pub fn values(&self) -> [f32; 5] { + [ + self.lower_fence as f32, + self.lower as f32, + self.median as f32, + self.upper as f32, + self.upper_fence as f32, + ] + } + + /// Get the quartiles median. + /// + /// - **returns** The median + /// + /// ```rust + /// use plotters::prelude::*; + /// + /// let quartiles = Quartiles::new(&[7, 15, 36, 39, 40, 41]); + /// assert_eq!(quartiles.median(), 37.5); + /// ``` + pub fn median(&self) -> f64 { + self.median + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + #[should_panic] + fn test_empty_input() { + let empty_array: [i32; 0] = []; + Quartiles::new(&empty_array); + } + + #[test] + fn test_low_inputs() { + assert_eq!( + Quartiles::new(&[15.0]).values(), + [15.0, 15.0, 15.0, 15.0, 15.0] + ); + assert_eq!( + Quartiles::new(&[10, 20]).values(), + [5.0, 12.5, 15.0, 17.5, 25.0] + ); + assert_eq!( + Quartiles::new(&[10, 20, 30]).values(), + [0.0, 15.0, 20.0, 25.0, 40.0] + ); + } +} |