Debian Codegraph @

src/config.rs

raw symbols SCIP
1 use crate::Error;
2 use core::ops::RangeInclusive;
3
4 #[cfg(feature = "serde")]
5 use serde::{Deserialize, Serialize};
6
7 /// The configuration of a histogram which determines the bucketing strategy and
8 /// therefore the relative error and memory utilization of a histogram.
9 /// * `grouping_power` - controls the number of buckets that are used to span
10 /// consecutive powers of two. Lower values result in less memory usage since
11 /// fewer buckets will be created. However, this will result in larger
12 /// relative error as each bucket represents a wider range of values.
13 /// * `max_value_power` - controls the largest value which can be stored in the
14 /// histogram. `2^(max_value_power) - 1` is the inclusive upper bound for the
15 /// representable range of values.
16 ///
17 /// # How to choose parameters for your data
18 /// Please see <https://observablehq.com/@iopsystems/h2histogram> for an
19 /// in-depth discussion about the bucketing strategy and an interactive
20 /// calculator that lets you explore how these parameters result in histograms
21 /// with varying error guarantees and memory utilization requirements.
22 ///
23 /// # The short version
24 /// ## Grouping Power
25 /// `grouping_power` should be set such that `2^(-1 * grouping_power)` is an
26 /// acceptable relative error. Rephrased, we can plug-in the acceptable
27 /// relative error into `grouping_power = ceil(log2(1/e))`. For example, if we
28 /// want to limit the error to 0.1% (0.001) we should set `grouping_power = 7`.
29 ///
30 /// ## Max Value Power
31 /// `max_value_power` should be the closest power of 2 that is larger than the
32 /// largest value you expect in your data. If your only guarantee is that the
33 /// values are all `u64`, then setting this to `64` may be reasonable if you
34 /// can tolerate a bit of relative error.
35 ///
36 /// ## Resulting size
37 ///
38 /// If we want to allow any value in a range of unsigned types, the amount of
39 /// memory for the histogram is approximately:
40 ///
41 /// | grouping_power | error | u16 | u32 | u64 |
42 /// |----------------|-------|---------|---------|---------|
43 /// | 2 | 25% | 0.6 KiB | 1 KiB | 2 KiB |
44 /// | 3 | 12.5% | 1 KiB | 2 KiB | 4 KiB |
45 /// | 4 | 6.25% | 2 KiB | 4 KiB | 8 KiB |
46 /// | 5 | 3.13% | 3 KiB | 7 KiB | 15 KiB |
47 /// | 6 | 1.56% | 6 KiB | 14 KiB | 30 KiB |
48 /// | 7 | .781% | 10 KiB | 26 KiB | 58 KiB |
49 /// | 8 | .391% | 18 KiB | 50 KiB | 114 KiB |
50 /// | 9 | .195% | 32 KiB | 96 KiB | 224 KiB |
51 /// | 10 | .098% | 56 KiB | 184 KiB | 440 KiB |
52 /// | 11 | .049% | 96 KiB | 352 KiB | 864 KiB |
53 /// | 12 | .025% | 160 KiB | 672 KiB | 1.7 MiB |
54 ///
55 /// Halve all sizes for `*32` histograms (`Histogram32`, `AtomicHistogram32`,
56 /// `SparseHistogram32`, `CumulativeROHistogram32`).
57 ///
58 /// # Constraints:
59 /// * `max_value_power` must be in the range `0..=64`
60 /// * `max_value_power` must be greater than `grouping_power`
61 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
62 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
63 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
64 pub struct Config {
65 max: u64,
66 grouping_power: u8,
67 max_value_power: u8,
68 cutoff_power: u8,
69 cutoff_value: u64,
70 lower_bin_count: u32,
71 upper_bin_divisions: u32,
72 upper_bin_count: u32,
73 }
74
75 impl Config {
76 /// Create a new histogram `Config` from the parameters. See the struct
77 /// documentation [`crate::Config`] for the meaning of the parameters and
78 /// their constraints.
79 pub const fn new(grouping_power: u8, max_value_power: u8) -> Result<Self, Error> {
80 // we only allow values up to 2^64
81 if max_value_power > 64 {
82 return Err(Error::MaxPowerTooHigh);
83 }
84
85 // check that the other parameters make sense together
86 if grouping_power >= max_value_power {
87 return Err(Error::MaxPowerTooLow);
88 }
89
90 // the cutoff is the point at which the linear range divisions and the
91 // logarithmic range subdivisions diverge.
92 //
93 // for example:
94 // when a = 0, the linear range has bins with width 1.
95 // if b = 7 the logarithmic range has 128 subdivisions.
96 // this means that for 0..128 we must be representing the values exactly
97 // but we also represent 128..256 exactly since the subdivisions divide
98 // that range into bins with the same width as the linear portion.
99 //
100 // therefore our cutoff power = a + b + 1
101
102 // note: because a + b must be less than n which is a u8, a + b + 1 must
103 // be less than or equal to u8::MAX. This means our cutoff power will
104 // always fit in a u8
105 let cutoff_power = grouping_power + 1;
106 let cutoff_value = 2_u64.pow(cutoff_power as u32);
107 let upper_bin_divisions = 2_u32.pow(grouping_power as u32);
108
109 let max = if max_value_power == 64 {
110 u64::MAX
111 } else {
112 2_u64.pow(max_value_power as u32) - 1
113 };
114
115 let lower_bin_count = cutoff_value as u32;
116 let upper_bin_count = (max_value_power - cutoff_power) as u32 * upper_bin_divisions;
117
118 Ok(Self {
119 max,
120 grouping_power,
121 max_value_power,
122 cutoff_power,
123 cutoff_value,
124 lower_bin_count,
125 upper_bin_divisions,
126 upper_bin_count,
127 })
128 }
129
130 /// Returns the grouping power that was used to create this configuration.
131 pub const fn grouping_power(&self) -> u8 {
132 self.grouping_power
133 }
134
135 /// Returns the max value power that was used to create this configuration.
136 pub const fn max_value_power(&self) -> u8 {
137 self.max_value_power
138 }
139
140 /// Returns the relative error (in percentage) of this configuration. This
141 /// only applies to the logarithmic bins of the histogram (linear bins have
142 /// a width of 1 and no error). For histograms with no logarithmic bins,
143 /// error for the entire histogram is zero.
144 pub fn error(&self) -> f64 {
145 match self.grouping_power == self.max_value_power - 1 {
146 true => 0.0,
147 false => 100.0 / 2_u64.pow(self.grouping_power as u32) as f64,
148 }
149 }
150
151 /// Return the total number of buckets needed for this config.
152 pub const fn total_buckets(&self) -> usize {
153 (self.lower_bin_count + self.upper_bin_count) as usize
154 }
155
156 /// Converts a value to a bucket index. Returns an error if the value is
157 /// outside of the range for the config.
158 pub(crate) fn value_to_index(&self, value: u64) -> Result<usize, Error> {
159 if value < self.cutoff_value {
160 return Ok(value as usize);
161 }
162
163 if value > self.max {
164 return Err(Error::OutOfRange);
165 }
166
167 let power = 63 - value.leading_zeros();
168 let log_bin = power - self.cutoff_power as u32;
169 let offset = (value - (1 << power)) >> (power - self.grouping_power as u32);
170
171 Ok((self.lower_bin_count + log_bin * self.upper_bin_divisions + offset as u32) as usize)
172 }
173
174 /// Convert a bucket index to a lower bound.
175 pub(crate) fn index_to_lower_bound(&self, index: usize) -> u64 {
176 let g = index as u64 >> self.grouping_power;
177 let h = index as u64 - g * (1 << self.grouping_power);
178
179 if g < 1 {
180 h
181 } else {
182 (1 << (self.grouping_power as u64 + g - 1)) + (1 << (g - 1)) * h
183 }
184 }
185
186 /// Convert a bucket index to a upper inclusive bound.
187 pub(crate) fn index_to_upper_bound(&self, index: usize) -> u64 {
188 if index as u32 == self.lower_bin_count + self.upper_bin_count - 1 {
189 return self.max;
190 }
191 let g = index as u64 >> self.grouping_power;
192 let h = index as u64 - g * (1 << self.grouping_power) + 1;
193
194 if g < 1 {
195 h - 1
196 } else {
197 (1 << (self.grouping_power as u64 + g - 1)) + (1 << (g - 1)) * h - 1
198 }
199 }
200
201 /// Convert a bucket index to a range.
202 pub(crate) fn index_to_range(&self, index: usize) -> RangeInclusive<u64> {
203 self.index_to_lower_bound(index)..=self.index_to_upper_bound(index)
204 }
205 }
206
207 #[cfg(test)]
208 mod tests {
209 use super::*;
210
211 #[cfg(target_pointer_width = "64")]
212 #[test]
213 fn sizes() {
214 assert_eq!(std::mem::size_of::<Config>(), 32);
215 }
216
217 #[test]
218 // Test that the number of buckets matches the expected count
219 fn total_buckets() {
220 let config = Config::new(2, 64).unwrap();
221 assert_eq!(config.total_buckets(), 252);
222
223 let config = Config::new(7, 64).unwrap();
224 assert_eq!(config.total_buckets(), 7424);
225
226 let config = Config::new(14, 64).unwrap();
227 assert_eq!(config.total_buckets(), 835_584);
228
229 let config = Config::new(2, 4).unwrap();
230 assert_eq!(config.total_buckets(), 12);
231 }
232
233 #[test]
234 // Test value to index conversions
235 fn value_to_idx() {
236 let config = Config::new(7, 64).unwrap();
237 assert_eq!(config.value_to_index(0), Ok(0));
238 assert_eq!(config.value_to_index(1), Ok(1));
239 assert_eq!(config.value_to_index(256), Ok(256));
240 assert_eq!(config.value_to_index(257), Ok(256));
241 assert_eq!(config.value_to_index(258), Ok(257));
242 assert_eq!(config.value_to_index(512), Ok(384));
243 assert_eq!(config.value_to_index(515), Ok(384));
244 assert_eq!(config.value_to_index(516), Ok(385));
245 assert_eq!(config.value_to_index(1024), Ok(512));
246 assert_eq!(config.value_to_index(1031), Ok(512));
247 assert_eq!(config.value_to_index(1032), Ok(513));
248 assert_eq!(config.value_to_index(u64::MAX - 1), Ok(7423));
249 assert_eq!(config.value_to_index(u64::MAX), Ok(7423));
250 }
251
252 #[test]
253 // Test index to lower bound conversion
254 fn idx_to_lower_bound() {
255 let config = Config::new(7, 64).unwrap();
256 assert_eq!(config.index_to_lower_bound(0), 0);
257 assert_eq!(config.index_to_lower_bound(1), 1);
258 assert_eq!(config.index_to_lower_bound(256), 256);
259 assert_eq!(config.index_to_lower_bound(384), 512);
260 assert_eq!(config.index_to_lower_bound(512), 1024);
261 assert_eq!(
262 config.index_to_lower_bound(7423),
263 18_374_686_479_671_623_680
264 );
265 }
266
267 #[test]
268 // Test index to upper bound conversion
269 fn idx_to_upper_bound() {
270 let config = Config::new(7, 64).unwrap();
271 assert_eq!(config.index_to_upper_bound(0), 0);
272 assert_eq!(config.index_to_upper_bound(1), 1);
273 assert_eq!(config.index_to_upper_bound(256), 257);
274 assert_eq!(config.index_to_upper_bound(384), 515);
275 assert_eq!(config.index_to_upper_bound(512), 1031);
276 assert_eq!(config.index_to_upper_bound(7423), u64::MAX);
277 }
278
279 #[test]
280 // Test index to range conversion
281 fn idx_to_range() {
282 let config = Config::new(7, 64).unwrap();
283 assert_eq!(config.index_to_range(0), 0..=0);
284 assert_eq!(config.index_to_range(1), 1..=1);
285 assert_eq!(config.index_to_range(256), 256..=257);
286 assert_eq!(config.index_to_range(384), 512..=515);
287 assert_eq!(config.index_to_range(512), 1024..=1031);
288 assert_eq!(
289 config.index_to_range(7423),
290 18_374_686_479_671_623_680..=u64::MAX
291 );
292 }
293 }