sketches_ddsketch/
config.rs

1#[cfg(feature = "use_serde")]
2use serde::{Deserialize, Serialize};
3
4const DEFAULT_MAX_BINS: u32 = 2048;
5const DEFAULT_ALPHA: f64 = 0.01;
6const DEFAULT_MIN_VALUE: f64 = 1.0e-9;
7
8/// The configuration struct for constructing a `DDSketch`
9#[derive(Copy, Clone, Debug, PartialEq)]
10#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
11pub struct Config {
12    pub max_num_bins: u32,
13    pub gamma: f64,
14    gamma_ln: f64,
15    min_value: f64,
16    pub offset: i32,
17}
18
19fn log_gamma(value: f64, gamma_ln: f64) -> f64 {
20    value.ln() / gamma_ln
21}
22
23impl Config {
24    /// Construct a new `Config` struct with specific parameters. If you are unsure of how to
25    /// configure this, the `defaults` method constructs a `Config` with built-in defaults.
26    ///
27    /// `max_num_bins` is the max number of bins the DDSketch will grow to, in steps of 128 bins.
28    pub fn new(alpha: f64, max_num_bins: u32, min_value: f64) -> Self {
29        let gamma_ln = (2.0 * alpha) / (1.0 - alpha);
30        let gamma_ln = gamma_ln.ln_1p();
31
32        Config {
33            max_num_bins,
34            gamma: 1.0 + (2.0 * alpha) / (1.0 - alpha),
35            gamma_ln,
36            min_value,
37            offset: 1 - (log_gamma(min_value, gamma_ln) as i32),
38        }
39    }
40
41    /// Return a `Config` using built-in default settings
42    pub fn defaults() -> Self {
43        Self::new(DEFAULT_ALPHA, DEFAULT_MAX_BINS, DEFAULT_MIN_VALUE)
44    }
45
46    pub fn key(&self, v: f64) -> i32 {
47        self.log_gamma(v).ceil() as i32
48    }
49
50    pub fn value(&self, key: i32) -> f64 {
51        self.pow_gamma(key) * (2.0 / (1.0 + self.gamma))
52    }
53
54    pub fn log_gamma(&self, value: f64) -> f64 {
55        log_gamma(value, self.gamma_ln)
56    }
57
58    pub fn pow_gamma(&self, key: i32) -> f64 {
59        ((key as f64) * self.gamma_ln).exp()
60    }
61
62    pub fn min_possible(&self) -> f64 {
63        self.min_value
64    }
65}
66
67impl Default for Config {
68    fn default() -> Self {
69        Self::new(DEFAULT_ALPHA, DEFAULT_MAX_BINS, DEFAULT_MIN_VALUE)
70    }
71}