| 1 | use std::collections::BTreeMap; |
| 2 | |
| 3 | use crate::{Bucket, Error}; |
| 4 | |
| 5 | /// A validated quantile value in the inclusive range `0.0..=1.0`. |
| 6 | /// |
| 7 | /// This newtype ensures that only valid quantile values (finite, non-NaN, |
| 8 | /// within `[0.0, 1.0]`) are used as keys in [`QuantilesResult`]. Because |
| 9 | /// NaN and infinity are excluded by construction, `Quantile` safely |
| 10 | /// implements [`Eq`] and [`Ord`]. |
| 11 | /// |
| 12 | /// # Examples |
| 13 | /// |
| 14 | /// ``` |
| 15 | /// use histogram::Quantile; |
| 16 | /// |
| 17 | /// let q = Quantile::new(0.99).unwrap(); |
| 18 | /// assert_eq!(q.as_f64(), 0.99); |
| 19 | /// |
| 20 | /// // Invalid values are rejected |
| 21 | /// assert!(Quantile::new(1.5).is_err()); |
| 22 | /// assert!(Quantile::new(f64::NAN).is_err()); |
| 23 | /// ``` |
| 24 | #[derive(Clone, Copy, Debug)] |
| 25 | pub struct Quantile(f64); |
| 26 | |
| 27 | impl Quantile { |
| 28 | /// Create a new `Quantile` from a value in `0.0..=1.0`. |
| 29 | /// |
| 30 | /// Returns [`Error::InvalidQuantile`] if the value is outside the |
| 31 | /// valid range or is NaN/infinite. |
| 32 | pub fn new(value: f64) -> Result<Self, Error> { |
| 33 | if (0.0..=1.0).contains(&value) { |
| 34 | Ok(Self(value)) |
| 35 | } else { |
| 36 | Err(Error::InvalidQuantile) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// Returns the underlying `f64` value. |
| 41 | pub fn as_f64(self) -> f64 { |
| 42 | self.0 |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl TryFrom<f64> for Quantile { |
| 47 | type Error = Error; |
| 48 | |
| 49 | fn try_from(value: f64) -> Result<Self, Self::Error> { |
| 50 | Self::new(value) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl PartialEq for Quantile { |
| 55 | fn eq(&self, other: &Self) -> bool { |
| 56 | self.0.to_bits() == other.0.to_bits() |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl Eq for Quantile {} |
| 61 | |
| 62 | impl PartialOrd for Quantile { |
| 63 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 64 | Some(self.cmp(other)) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl Ord for Quantile { |
| 69 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 70 | self.0.partial_cmp(&other.0).unwrap() |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl std::fmt::Display for Quantile { |
| 75 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 76 | write!(f, "{}", self.0) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// The result of a quantile query on a histogram. |
| 81 | /// |
| 82 | /// Contains the requested quantile-to-bucket mappings, the total sample |
| 83 | /// count, and the min/max buckets (the first and last non-zero buckets, |
| 84 | /// representing p0 and p100 respectively). |
| 85 | /// |
| 86 | /// Entries are stored in a [`BTreeMap`] keyed by [`Quantile`], providing |
| 87 | /// sorted iteration and efficient keyed lookups. |
| 88 | /// |
| 89 | /// # Examples |
| 90 | /// |
| 91 | /// ``` |
| 92 | /// use histogram::{Histogram, SampleQuantiles, Quantile}; |
| 93 | /// |
| 94 | /// let mut h = Histogram::new(7, 64).unwrap(); |
| 95 | /// for v in 1..=100 { |
| 96 | /// h.increment(v).unwrap(); |
| 97 | /// } |
| 98 | /// |
| 99 | /// let result = h.quantiles(&[0.5, 0.99]).unwrap().unwrap(); |
| 100 | /// assert_eq!(result.entries().len(), 2); |
| 101 | /// assert!(result.total_count() > 0); |
| 102 | /// |
| 103 | /// // Keyed lookup |
| 104 | /// let q99 = Quantile::new(0.99).unwrap(); |
| 105 | /// let bucket = result.get(&q99).unwrap(); |
| 106 | /// println!("p99: {}-{}", bucket.start(), bucket.end()); |
| 107 | /// ``` |
| 108 | #[derive(Debug, PartialEq)] |
| 109 | pub struct QuantilesResult { |
| 110 | entries: BTreeMap<Quantile, Bucket>, |
| 111 | total_count: u128, |
| 112 | min: Bucket, |
| 113 | max: Bucket, |
| 114 | } |
| 115 | |
| 116 | impl QuantilesResult { |
| 117 | /// Creates a new `QuantilesResult`. |
| 118 | pub(crate) fn new( |
| 119 | entries: BTreeMap<Quantile, Bucket>, |
| 120 | total_count: u128, |
| 121 | min: Bucket, |
| 122 | max: Bucket, |
| 123 | ) -> Self { |
| 124 | Self { |
| 125 | entries, |
| 126 | total_count, |
| 127 | min, |
| 128 | max, |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Returns the quantile-to-bucket mappings, sorted by quantile. |
| 133 | pub fn entries(&self) -> &BTreeMap<Quantile, Bucket> { |
| 134 | &self.entries |
| 135 | } |
| 136 | |
| 137 | /// Returns the quantile-to-bucket mappings, sorted by quantile. |
| 138 | /// |
| 139 | /// Consumes self, returning the mapping by value instead of reference. |
| 140 | pub fn into_entries(self) -> BTreeMap<Quantile, Bucket> { |
| 141 | self.entries |
| 142 | } |
| 143 | |
| 144 | /// Look up the bucket for a specific quantile. |
| 145 | pub fn get(&self, quantile: &Quantile) -> Option<&Bucket> { |
| 146 | self.entries.get(quantile) |
| 147 | } |
| 148 | |
| 149 | /// Returns the total number of observations across all buckets. |
| 150 | pub fn total_count(&self) -> u128 { |
| 151 | self.total_count |
| 152 | } |
| 153 | |
| 154 | /// Returns the minimum bucket (first non-zero bucket, i.e. p0). |
| 155 | pub fn min(&self) -> &Bucket { |
| 156 | &self.min |
| 157 | } |
| 158 | |
| 159 | /// Returns the maximum bucket (last non-zero bucket, i.e. p100). |
| 160 | pub fn max(&self) -> &Bucket { |
| 161 | &self.max |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// Trait for computing quantiles from histogram data. |
| 166 | /// |
| 167 | /// Implemented for [`crate::Histogram`] and [`crate::SparseHistogram`]. |
| 168 | /// [`crate::AtomicHistogram`] does not implement this trait — use |
| 169 | /// [`AtomicHistogram::load()`](crate::AtomicHistogram::load) to get a |
| 170 | /// `Histogram` snapshot first. |
| 171 | /// |
| 172 | /// # Examples |
| 173 | /// |
| 174 | /// ``` |
| 175 | /// use histogram::{Histogram, SparseHistogram, SampleQuantiles}; |
| 176 | /// |
| 177 | /// let mut h = Histogram::new(7, 64).unwrap(); |
| 178 | /// h.increment(100).unwrap(); |
| 179 | /// |
| 180 | /// // Works on both Histogram and SparseHistogram |
| 181 | /// fn show_p99(h: &impl SampleQuantiles) { |
| 182 | /// if let Ok(Some(result)) = h.quantile(0.99) { |
| 183 | /// let bucket = result.entries().values().next().unwrap(); |
| 184 | /// println!("p99: {}-{}", bucket.start(), bucket.end()); |
| 185 | /// } |
| 186 | /// } |
| 187 | /// |
| 188 | /// show_p99(&h); |
| 189 | /// show_p99(&SparseHistogram::from(&h)); |
| 190 | /// ``` |
| 191 | pub trait SampleQuantiles { |
| 192 | /// Compute quantiles for the given values. |
| 193 | /// |
| 194 | /// Each value in `quantiles` must be in `0.0..=1.0`. Returns |
| 195 | /// `Err(Error::InvalidQuantile)` if any value is out of range. |
| 196 | /// Returns `Ok(None)` if the histogram is empty. |
| 197 | fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error>; |
| 198 | |
| 199 | /// Compute a single quantile. Convenience wrapper around [`quantiles`](Self::quantiles). |
| 200 | fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> { |
| 201 | self.quantiles(&[quantile]) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | #[cfg(test)] |
| 206 | mod tests { |
| 207 | use super::*; |
| 208 | use crate::{Histogram, SparseHistogram}; |
| 209 | |
| 210 | #[test] |
| 211 | fn quantile_validation() { |
| 212 | assert!(Quantile::new(0.0).is_ok()); |
| 213 | assert!(Quantile::new(0.5).is_ok()); |
| 214 | assert!(Quantile::new(1.0).is_ok()); |
| 215 | assert!(Quantile::new(-0.1).is_err()); |
| 216 | assert!(Quantile::new(1.1).is_err()); |
| 217 | assert!(Quantile::new(f64::NAN).is_err()); |
| 218 | assert!(Quantile::new(f64::INFINITY).is_err()); |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn quantile_ordering() { |
| 223 | let q1 = Quantile::new(0.5).unwrap(); |
| 224 | let q2 = Quantile::new(0.99).unwrap(); |
| 225 | assert!(q1 < q2); |
| 226 | assert_eq!(q1, Quantile::new(0.5).unwrap()); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn empty_histogram_returns_none() { |
| 231 | let h = Histogram::new(7, 64).unwrap(); |
| 232 | assert_eq!(h.quantiles(&[0.5, 0.99]).unwrap(), None); |
| 233 | assert_eq!(h.quantile(0.5).unwrap(), None); |
| 234 | |
| 235 | let s = SparseHistogram::from(&h); |
| 236 | assert_eq!(s.quantiles(&[0.5, 0.99]).unwrap(), None); |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn invalid_quantile_returns_error() { |
| 241 | let h = Histogram::new(7, 64).unwrap(); |
| 242 | assert_eq!(h.quantiles(&[1.5]), Err(Error::InvalidQuantile)); |
| 243 | assert_eq!(h.quantiles(&[-0.1]), Err(Error::InvalidQuantile)); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn basic_quantiles() { |
| 248 | let mut h = Histogram::new(7, 64).unwrap(); |
| 249 | for v in 0..=100 { |
| 250 | h.increment(v).unwrap(); |
| 251 | } |
| 252 | |
| 253 | let result = h.quantiles(&[0.5, 0.9, 0.99]).unwrap().unwrap(); |
| 254 | assert_eq!(result.entries().len(), 3); |
| 255 | assert_eq!(result.total_count(), 101); |
| 256 | |
| 257 | // min bucket should contain 0 |
| 258 | assert_eq!(result.min().start(), 0); |
| 259 | // max bucket should contain 100 |
| 260 | assert_eq!(result.max().end(), 100); |
| 261 | |
| 262 | // p50 should be around 50 |
| 263 | let q50 = Quantile::new(0.5).unwrap(); |
| 264 | assert_eq!(result.get(&q50).unwrap().end(), 50); |
| 265 | |
| 266 | // p99 should be around 99 |
| 267 | let q99 = Quantile::new(0.99).unwrap(); |
| 268 | assert_eq!(result.get(&q99).unwrap().end(), 99); |
| 269 | } |
| 270 | |
| 271 | #[test] |
| 272 | fn single_sample() { |
| 273 | let mut h = Histogram::new(7, 64).unwrap(); |
| 274 | h.increment(42).unwrap(); |
| 275 | |
| 276 | let result = h.quantile(0.5).unwrap().unwrap(); |
| 277 | assert_eq!(result.total_count(), 1); |
| 278 | assert_eq!(result.min().end(), 42); |
| 279 | assert_eq!(result.max().end(), 42); |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | fn histogram_and_sparse_agree() { |
| 284 | let mut h = Histogram::new(4, 10).unwrap(); |
| 285 | for v in 1..1024 { |
| 286 | h.increment(v).unwrap(); |
| 287 | } |
| 288 | let s = SparseHistogram::from(&h); |
| 289 | |
| 290 | let quantiles = &[0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99, 0.999]; |
| 291 | |
| 292 | let hr = h.quantiles(quantiles).unwrap().unwrap(); |
| 293 | let sr = s.quantiles(quantiles).unwrap().unwrap(); |
| 294 | |
| 295 | assert_eq!(hr.total_count(), sr.total_count()); |
| 296 | assert_eq!(hr.min().range(), sr.min().range()); |
| 297 | assert_eq!(hr.max().range(), sr.max().range()); |
| 298 | |
| 299 | for (hq, sq) in hr.entries().iter().zip(sr.entries().iter()) { |
| 300 | assert_eq!(hq.0, sq.0); |
| 301 | assert_eq!(hq.1.range(), sq.1.range()); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | #[test] |
| 306 | fn duplicate_quantiles_deduped() { |
| 307 | let mut h = Histogram::new(7, 64).unwrap(); |
| 308 | h.increment(50).unwrap(); |
| 309 | |
| 310 | let result = h.quantiles(&[0.5, 0.5, 0.99, 0.99]).unwrap().unwrap(); |
| 311 | // Duplicates are deduped in the BTreeMap |
| 312 | assert_eq!(result.entries().len(), 2); |
| 313 | } |
| 314 | } |