Debian Codegraph @

src/standard.rs

raw symbols SCIP
1 use std::collections::BTreeMap;
2
3 use crate::quantile::{Quantile, QuantilesResult, SampleQuantiles};
4 use crate::{Bucket, Config, Count, Error, SparseHistogram, SparseHistogram32};
5
6 macro_rules! define_histogram {
7 ($name:ident, $iter:ident, $sparse:ident, $count:ty) => {
8 /// A histogram that uses plain counters for each bucket.
9 #[derive(Clone, Debug, PartialEq, Eq)]
10 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
12 pub struct $name {
13 pub(crate) config: Config,
14 pub(crate) buckets: Box<[$count]>,
15 }
16
17 impl $name {
18 /// Construct a new histogram from the provided parameters.
19 pub fn new(grouping_power: u8, max_value_power: u8) -> Result<Self, Error> {
20 let config = Config::new(grouping_power, max_value_power)?;
21 Ok(Self::with_config(&config))
22 }
23
24 /// Creates a new histogram using a provided [`crate::Config`].
25 pub fn with_config(config: &Config) -> Self {
26 let buckets: Box<[$count]> =
27 vec![<$count as Count>::ZERO; config.total_buckets()].into();
28 Self {
29 config: *config,
30 buckets,
31 }
32 }
33
34 /// Creates a new histogram from a config and a vector of buckets.
35 pub fn from_buckets(
36 grouping_power: u8,
37 max_value_power: u8,
38 buckets: Vec<$count>,
39 ) -> Result<Self, Error> {
40 let config = Config::new(grouping_power, max_value_power)?;
41 if config.total_buckets() != buckets.len() {
42 return Err(Error::IncompatibleParameters);
43 }
44 Ok(Self {
45 config,
46 buckets: buckets.into(),
47 })
48 }
49
50 /// Increment the counter for the bucket corresponding to `value` by one.
51 /// Uses wrapping arithmetic on overflow.
52 pub fn increment(&mut self, value: u64) -> Result<(), Error> {
53 self.add(value, <$count as Count>::ONE)
54 }
55
56 /// Add `count` to the bucket containing `value`. Uses wrapping
57 /// arithmetic on overflow.
58 pub fn add(&mut self, value: u64, count: $count) -> Result<(), Error> {
59 let index = self.config.value_to_index(value)?;
60 self.buckets[index] = self.buckets[index].wrapping_add(count);
61 Ok(())
62 }
63
64 /// Get a reference to the raw counters.
65 pub fn as_slice(&self) -> &[$count] {
66 &self.buckets
67 }
68
69 /// Get a mutable reference to the raw counters.
70 pub fn as_mut_slice(&mut self) -> &mut [$count] {
71 &mut self.buckets
72 }
73
74 /// Returns a new histogram with a reduced grouping power. The reduced
75 /// grouping power should lie in the range (0..existing grouping power).
76 ///
77 /// Returns an error if the requested grouping power is not less than the current grouping power.
78 ///
79 /// The difference in grouping powers determines how much histogram size
80 /// is reduced by, with every step approximately halving the total
81 /// number of buckets (and hence total size of the histogram), while
82 /// doubling the relative error.
83 ///
84 /// This works by iterating over every bucket in the existing histogram
85 /// and inserting the contained values into the new histogram. While we
86 /// do not know the exact values of the data points (only that they lie
87 /// within the bucket's range), it does not matter since the bucket is
88 /// not split during downsampling and any value can be used.
89 pub fn downsample(&self, grouping_power: u8) -> Result<Self, Error> {
90 if grouping_power >= self.config.grouping_power() {
91 return Err(Error::IncompatibleParameters);
92 }
93 let mut histogram = Self::new(grouping_power, self.config.max_value_power())?;
94 for (i, n) in self.as_slice().iter().enumerate() {
95 if *n != <$count as Count>::ZERO {
96 let val = self.config.index_to_lower_bound(i);
97 histogram.add(val, *n)?;
98 }
99 }
100 Ok(histogram)
101 }
102
103 /// Adds the other histogram to this histogram and returns the result as a
104 /// new histogram.
105 ///
106 /// An error is returned if the two histograms have incompatible parameters
107 /// or if there is an overflow.
108 pub fn checked_add(&self, other: &Self) -> Result<Self, Error> {
109 if self.config != other.config {
110 return Err(Error::IncompatibleParameters);
111 }
112 let mut result = self.clone();
113 for (this, other) in result.buckets.iter_mut().zip(other.buckets.iter()) {
114 *this = this.checked_add(*other).ok_or(Error::Overflow)?;
115 }
116 Ok(result)
117 }
118
119 /// Adds the other histogram to this histogram and returns the result as a
120 /// new histogram.
121 ///
122 /// An error is returned if the two histograms have incompatible parameters.
123 pub fn wrapping_add(&self, other: &Self) -> Result<Self, Error> {
124 if self.config != other.config {
125 return Err(Error::IncompatibleParameters);
126 }
127 let mut result = self.clone();
128 for (this, other) in result.buckets.iter_mut().zip(other.buckets.iter()) {
129 *this = this.wrapping_add(*other);
130 }
131 Ok(result)
132 }
133
134 /// Subtracts the other histogram from this histogram and returns the result
135 /// as a new histogram.
136 ///
137 /// An error is returned if the two histograms have incompatible parameters
138 /// or if there is an overflow.
139 pub fn checked_sub(&self, other: &Self) -> Result<Self, Error> {
140 if self.config != other.config {
141 return Err(Error::IncompatibleParameters);
142 }
143 let mut result = self.clone();
144 for (this, other) in result.buckets.iter_mut().zip(other.buckets.iter()) {
145 *this = this.checked_sub(*other).ok_or(Error::Underflow)?;
146 }
147 Ok(result)
148 }
149
150 /// Subtracts the other histogram from this histogram and returns the result
151 /// as a new histogram.
152 ///
153 /// An error is returned if the two histograms have incompatible parameters.
154 pub fn wrapping_sub(&self, other: &Self) -> Result<Self, Error> {
155 if self.config != other.config {
156 return Err(Error::IncompatibleParameters);
157 }
158 let mut result = self.clone();
159 for (this, other) in result.buckets.iter_mut().zip(other.buckets.iter()) {
160 *this = this.wrapping_sub(*other);
161 }
162 Ok(result)
163 }
164
165 /// Returns an iterator across the histogram.
166 pub fn iter(&self) -> $iter<'_> {
167 $iter {
168 index: 0,
169 histogram: self,
170 }
171 }
172
173 /// Returns the bucket configuration of the histogram.
174 pub fn config(&self) -> Config {
175 self.config
176 }
177
178 /// Compute quantiles for the given values.
179 ///
180 /// Each value in `quantiles` must be in `0.0..=1.0`. Returns
181 /// `Err(Error::InvalidQuantile)` if any value is out of range,
182 /// `Ok(None)` if the histogram is empty.
183 ///
184 /// This is an inherent forwarder for [`SampleQuantiles::quantiles`].
185 pub fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
186 <Self as SampleQuantiles>::quantiles(self, quantiles)
187 }
188
189 /// Compute a single quantile.
190 ///
191 /// The quantile must be in `0.0..=1.0`. Returns
192 /// `Err(Error::InvalidQuantile)` if out of range, `Ok(None)` if the
193 /// histogram is empty.
194 ///
195 /// This is an inherent forwarder for [`SampleQuantiles::quantile`].
196 pub fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> {
197 <Self as SampleQuantiles>::quantile(self, quantile)
198 }
199 }
200
201 impl SampleQuantiles for $name {
202 fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
203 for q in quantiles {
204 if !(0.0..=1.0).contains(q) {
205 return Err(Error::InvalidQuantile);
206 }
207 }
208 let total_count: u128 = self.buckets.iter().map(|v| v.as_u128()).sum();
209 if total_count == 0 {
210 return Ok(None);
211 }
212 let mut sorted: Vec<Quantile> = quantiles
213 .iter()
214 .map(|&q| Quantile::new(q).unwrap())
215 .collect();
216 sorted.sort();
217 sorted.dedup();
218
219 let mut min_idx = None;
220 let mut max_idx = None;
221 for (i, count) in self.buckets.iter().enumerate() {
222 if *count != <$count as Count>::ZERO {
223 if min_idx.is_none() {
224 min_idx = Some(i);
225 }
226 max_idx = Some(i);
227 }
228 }
229 let min_idx = min_idx.unwrap();
230 let max_idx = max_idx.unwrap();
231
232 let min = Bucket {
233 count: self.buckets[min_idx].as_u128() as u64,
234 range: self.config.index_to_range(min_idx),
235 };
236 let max = Bucket {
237 count: self.buckets[max_idx].as_u128() as u64,
238 range: self.config.index_to_range(max_idx),
239 };
240
241 let mut bucket_idx = 0;
242 let mut partial_sum = self.buckets[bucket_idx].as_u128();
243 let mut entries = BTreeMap::new();
244
245 for quantile in &sorted {
246 let count =
247 std::cmp::max(1, (quantile.as_f64() * total_count as f64).ceil() as u128);
248 loop {
249 if partial_sum >= count {
250 entries.insert(
251 *quantile,
252 Bucket {
253 count: self.buckets[bucket_idx].as_u128() as u64,
254 range: self.config.index_to_range(bucket_idx),
255 },
256 );
257 break;
258 }
259 if bucket_idx == (self.buckets.len() - 1) {
260 break;
261 }
262 bucket_idx += 1;
263 partial_sum += self.buckets[bucket_idx].as_u128();
264 }
265 }
266
267 Ok(Some(QuantilesResult::new(entries, total_count, min, max)))
268 }
269 }
270
271 impl<'a> IntoIterator for &'a $name {
272 type Item = Bucket;
273 type IntoIter = $iter<'a>;
274 fn into_iter(self) -> Self::IntoIter {
275 $iter {
276 index: 0,
277 histogram: self,
278 }
279 }
280 }
281
282 /// An iterator across the histogram buckets.
283 pub struct $iter<'a> {
284 index: usize,
285 histogram: &'a $name,
286 }
287
288 impl Iterator for $iter<'_> {
289 type Item = Bucket;
290 fn next(&mut self) -> Option<Bucket> {
291 if self.index >= self.histogram.buckets.len() {
292 return None;
293 }
294 let bucket = Bucket {
295 count: self.histogram.buckets[self.index].as_u128() as u64,
296 range: self.histogram.config.index_to_range(self.index),
297 };
298 self.index += 1;
299 Some(bucket)
300 }
301 }
302
303 impl ExactSizeIterator for $iter<'_> {
304 fn len(&self) -> usize {
305 self.histogram.buckets.len() - self.index
306 }
307 }
308
309 impl std::iter::FusedIterator for $iter<'_> {}
310
311 // Requires: `$sparse.count` is `Vec<$count>` (the same count type as `$name`).
312 // Task 4 enforces this when defining SparseHistogram32 alongside Histogram32.
313 impl From<&$sparse> for $name {
314 fn from(other: &$sparse) -> Self {
315 let mut histogram = $name::with_config(&other.config);
316 for (index, count) in other.index.iter().zip(other.count.iter()) {
317 histogram.buckets[*index as usize] = *count;
318 }
319 histogram
320 }
321 }
322 };
323 }
324
325 define_histogram!(Histogram, Iter, SparseHistogram, u64);
326 define_histogram!(Histogram32, Iter32, SparseHistogram32, u32);
327
328 // Deprecated forwarding methods — only on the u64 variant to avoid proliferating
329 // deprecated APIs onto the new u32 type. Mirrors the same pattern in sparse.rs.
330 impl Histogram {
331 /// Return a collection of percentiles from this histogram.
332 ///
333 /// Each percentile should be in the inclusive range `0.0..=1.0`. For
334 /// example, the 50th percentile (median) can be found using `0.5`.
335 ///
336 /// The results will be sorted by the percentile.
337 #[deprecated(note = "Use the SampleQuantiles trait")]
338 #[allow(deprecated)]
339 pub fn percentiles(&self, percentiles: &[f64]) -> Result<Option<Vec<(f64, Bucket)>>, Error> {
340 Ok(SampleQuantiles::quantiles(self, percentiles)
341 .map_err(|e| match e {
342 Error::InvalidQuantile => Error::InvalidPercentile,
343 other => other,
344 })?
345 .map(|qr| {
346 qr.entries()
347 .iter()
348 .map(|(q, b)| (q.as_f64(), b.clone()))
349 .collect()
350 }))
351 }
352
353 /// Return a single percentile from this histogram.
354 ///
355 /// The percentile should be in the inclusive range `0.0..=1.0`. For
356 /// example, the 50th percentile (median) can be found using `0.5`.
357 #[deprecated(note = "Use the SampleQuantiles trait")]
358 pub fn percentile(&self, percentile: f64) -> Result<Option<Bucket>, Error> {
359 #[allow(deprecated)]
360 self.percentiles(&[percentile])
361 .map(|v| v.map(|x| x.first().unwrap().1.clone()))
362 }
363 }
364
365 #[cfg(test)]
366 mod tests {
367 use super::*;
368 use rand::RngExt;
369
370 #[cfg(target_pointer_width = "64")]
371 #[test]
372 fn size() {
373 assert_eq!(std::mem::size_of::<Histogram>(), 48);
374 }
375
376 #[test]
377 // Tests quantiles (replaces the deprecated percentile/percentiles tests).
378 fn quantiles() {
379 let mut histogram = Histogram::new(7, 64).unwrap();
380
381 assert_eq!(histogram.quantile(0.5).unwrap(), None);
382 assert_eq!(histogram.quantiles(&[0.5, 0.9, 0.99, 0.999]).unwrap(), None);
383
384 for i in 0..=100 {
385 let _ = histogram.increment(i);
386 let r = histogram.quantile(0.0).unwrap().unwrap();
387 assert_eq!(
388 r.get(&Quantile::new(0.0).unwrap()),
389 Some(&Bucket {
390 count: 1,
391 range: 0..=0,
392 })
393 );
394 let r = histogram.quantile(1.0).unwrap().unwrap();
395 assert_eq!(
396 r.get(&Quantile::new(1.0).unwrap()),
397 Some(&Bucket {
398 count: 1,
399 range: i..=i,
400 })
401 );
402 }
403 let r = histogram.quantile(0.0).unwrap().unwrap();
404 assert_eq!(r.get(&Quantile::new(0.0).unwrap()).unwrap().end(), 0);
405 let r = histogram.quantile(0.25).unwrap().unwrap();
406 assert_eq!(r.get(&Quantile::new(0.25).unwrap()).unwrap().end(), 25);
407 let r = histogram.quantile(0.50).unwrap().unwrap();
408 assert_eq!(r.get(&Quantile::new(0.50).unwrap()).unwrap().end(), 50);
409 let r = histogram.quantile(0.75).unwrap().unwrap();
410 assert_eq!(r.get(&Quantile::new(0.75).unwrap()).unwrap().end(), 75);
411 let r = histogram.quantile(0.90).unwrap().unwrap();
412 assert_eq!(r.get(&Quantile::new(0.90).unwrap()).unwrap().end(), 90);
413 let r = histogram.quantile(0.99).unwrap().unwrap();
414 assert_eq!(r.get(&Quantile::new(0.99).unwrap()).unwrap().end(), 99);
415 let r = histogram.quantile(0.999).unwrap().unwrap();
416 assert_eq!(r.get(&Quantile::new(0.999).unwrap()).unwrap().end(), 100);
417
418 assert_eq!(histogram.quantile(-1.0), Err(Error::InvalidQuantile));
419 assert_eq!(histogram.quantile(1.01), Err(Error::InvalidQuantile));
420
421 let _ = histogram.increment(1024);
422 let r = histogram.quantile(0.999).unwrap().unwrap();
423 assert_eq!(
424 r.get(&Quantile::new(0.999).unwrap()),
425 Some(&Bucket {
426 count: 1,
427 range: 1024..=1031,
428 })
429 );
430 }
431
432 #[test]
433 fn min() {
434 let mut histogram = Histogram::new(7, 64).unwrap();
435
436 assert_eq!(histogram.quantile(0.0).unwrap(), None);
437
438 let _ = histogram.increment(10);
439 let r = histogram.quantile(0.0).unwrap().unwrap();
440 assert_eq!(r.get(&Quantile::new(0.0).unwrap()).unwrap().end(), 10);
441
442 let _ = histogram.increment(4);
443 let r = histogram.quantile(0.0).unwrap().unwrap();
444 assert_eq!(r.get(&Quantile::new(0.0).unwrap()).unwrap().end(), 4);
445 }
446
447 #[test]
448 fn downsample() {
449 let mut histogram = Histogram::new(8, 32).unwrap();
450 let mut vals: Vec<u64> = Vec::with_capacity(10000);
451 use rand::SeedableRng;
452 let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
453
454 for _ in 0..vals.capacity() {
455 let v: u64 = rng.random_range(1..2_u64.pow(histogram.config.max_value_power() as u32));
456 vals.push(v);
457 let _ = histogram.increment(v);
458 }
459 vals.sort();
460
461 let mut percentiles: Vec<f64> = Vec::with_capacity(109);
462 for i in 20..99 {
463 percentiles.push(i as f64 / 100.0);
464 }
465 let mut tail = vec![
466 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999, 0.9999, 1.0,
467 ];
468 percentiles.append(&mut tail);
469
470 let h = histogram.clone();
471 let grouping_power = histogram.config.grouping_power();
472 for factor in 1..grouping_power {
473 let error = histogram.config.error();
474
475 for p in &percentiles {
476 let v = vals[((*p * (vals.len() as f64)) as usize) - 1];
477 let q = histogram.quantile(*p).unwrap().unwrap();
478 let vhist = q.get(&Quantile::new(*p).unwrap()).unwrap().end();
479 let e = (v.abs_diff(vhist) as f64) * 100.0 / (v as f64);
480 assert!(e < error);
481 }
482
483 histogram = h.downsample(grouping_power - factor).unwrap();
484 }
485 }
486
487 fn build_histograms() -> (Histogram, Histogram, Histogram, Histogram) {
488 let mut h1 = Histogram::new(1, 3).unwrap();
489 let mut h2 = Histogram::new(1, 3).unwrap();
490 let mut h3 = Histogram::new(1, 3).unwrap();
491 let h4 = Histogram::new(7, 32).unwrap();
492
493 for i in 0..h1.config().total_buckets() {
494 h1.as_mut_slice()[i] = 1;
495 h2.as_mut_slice()[i] = 1;
496 h3.as_mut_slice()[i] = u64::MAX;
497 }
498
499 (h1, h2, h3, h4)
500 }
501
502 #[test]
503 fn checked_add() {
504 let (h, h_good, h_overflow, h_mismatch) = build_histograms();
505 assert_eq!(
506 h.checked_add(&h_mismatch),
507 Err(Error::IncompatibleParameters)
508 );
509 let r = h.checked_add(&h_good).unwrap();
510 assert_eq!(r.as_slice(), &[2, 2, 2, 2, 2, 2]);
511 assert_eq!(h.checked_add(&h_overflow), Err(Error::Overflow));
512 }
513
514 #[test]
515 fn wrapping_add() {
516 let (h, h_good, h_overflow, h_mismatch) = build_histograms();
517 assert_eq!(
518 h.wrapping_add(&h_mismatch),
519 Err(Error::IncompatibleParameters)
520 );
521 let r = h.wrapping_add(&h_good).unwrap();
522 assert_eq!(r.as_slice(), &[2, 2, 2, 2, 2, 2]);
523 let r = h.wrapping_add(&h_overflow).unwrap();
524 assert_eq!(r.as_slice(), &[0, 0, 0, 0, 0, 0]);
525 }
526
527 #[test]
528 fn checked_sub() {
529 let (h, h_good, h_overflow, h_mismatch) = build_histograms();
530 assert_eq!(
531 h.checked_sub(&h_mismatch),
532 Err(Error::IncompatibleParameters)
533 );
534 let r = h.checked_sub(&h_good).unwrap();
535 assert_eq!(r.as_slice(), &[0, 0, 0, 0, 0, 0]);
536 assert_eq!(h.checked_sub(&h_overflow), Err(Error::Underflow));
537 }
538
539 #[test]
540 fn wrapping_sub() {
541 let (h, h_good, h_overflow, h_mismatch) = build_histograms();
542 assert_eq!(
543 h.wrapping_sub(&h_mismatch),
544 Err(Error::IncompatibleParameters)
545 );
546 let r = h.wrapping_sub(&h_good).unwrap();
547 assert_eq!(r.as_slice(), &[0, 0, 0, 0, 0, 0]);
548 let r = h.wrapping_sub(&h_overflow).unwrap();
549 assert_eq!(r.as_slice(), &[2, 2, 2, 2, 2, 2]);
550 }
551
552 #[test]
553 fn from_buckets() {
554 let mut histogram = Histogram::new(8, 32).unwrap();
555 for i in 0..=100 {
556 let _ = histogram.increment(i);
557 }
558 let buckets = histogram.as_slice();
559 let constructed = Histogram::from_buckets(8, 32, buckets.to_vec()).unwrap();
560 assert!(constructed == histogram);
561 }
562
563 #[cfg(target_pointer_width = "64")]
564 #[test]
565 fn size_u32() {
566 assert_eq!(std::mem::size_of::<Histogram32>(), 48);
567 }
568
569 #[test]
570 fn increment_u32() {
571 let mut h = Histogram32::new(7, 64).unwrap();
572 h.increment(5).unwrap();
573 h.increment(5).unwrap();
574 h.increment(5).unwrap();
575 let result = h.quantile(0.5).unwrap().unwrap();
576 let q = Quantile::new(0.5).unwrap();
577 assert_eq!(result.get(&q).unwrap().count(), 3u64);
578 }
579
580 #[test]
581 fn add_u32_wraps_at_max() {
582 let mut h = Histogram32::new(2, 4).unwrap();
583 h.add(1, u32::MAX).unwrap();
584 h.add(1, 1).unwrap();
585 assert_eq!(h.as_slice()[1], 0u32);
586 }
587
588 #[test]
589 fn checked_add_u32_overflow() {
590 let mut h1 = Histogram32::new(1, 3).unwrap();
591 let mut h2 = Histogram32::new(1, 3).unwrap();
592 h1.as_mut_slice()[0] = u32::MAX;
593 h2.as_mut_slice()[0] = 1;
594 assert_eq!(h1.checked_add(&h2), Err(Error::Overflow));
595 }
596
597 #[test]
598 fn iter_u32_widens_count_to_u64() {
599 let mut h = Histogram32::new(2, 4).unwrap();
600 h.add(1, 5u32).unwrap();
601 let bucket = h.iter().find(|b| b.count() > 0).unwrap();
602 let count: u64 = bucket.count();
603 assert_eq!(count, 5);
604 }
605 }