1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use crate::error::Error;
use crate::index_mapping::{
CubicallyInterpolatedMapping, IndexMapping, IndexMappingLayout, LogarithmicMapping,
};
use crate::input::Input;
use crate::serde;
use crate::store::{
BinEncodingMode, CollapsingHighestDenseStore, CollapsingLowestDenseStore, Store,
UnboundedSizeDenseStore,
};
pub struct DDSketch<I: IndexMapping, S: Store> {
index_mapping: I,
min_indexed_value: f64,
max_indexed_value: f64,
negative_value_store: S,
positive_value_store: S,
zero_count: f64,
}
#[derive(PartialEq)]
pub struct Flag {
marker: u8,
}
pub enum FlagType {
SketchFeatures = 0b00,
PositiveStore = 0b01,
IndexMapping = 0b10,
NegativeStore = 0b11,
}
impl<I: IndexMapping, S: Store> DDSketch<I, S> {
pub fn accept(&mut self, value: f64) {
self.accept_with_count(value, 1.0);
}
pub fn accept_with_count(&mut self, value: f64, count: f64) {
if count < 0.0 {
return;
}
if value < -self.max_indexed_value || value > self.max_indexed_value {
return;
}
if value > self.min_indexed_value {
self.positive_value_store
.add(self.index_mapping.index(value), 1.0);
} else if value < -self.min_indexed_value {
self.negative_value_store
.add(self.index_mapping.index(-value), 1.0);
} else {
self.zero_count += 1.0;
}
}
pub fn is_empty(&self) -> bool {
self.zero_count == 0.0
&& self.negative_value_store.is_empty()
&& self.positive_value_store.is_empty()
}
pub fn clear(&mut self) {
self.negative_value_store.clear();
self.positive_value_store.clear();
self.zero_count = 0.0;
}
pub fn get_count(&mut self) -> f64 {
self.zero_count
+ self.negative_value_store.get_total_count()
+ self.positive_value_store.get_total_count()
}
pub fn get_sum(&mut self) -> Option<f64> {
let count = self.get_count();
if count <= 0.0 {
return None;
}
let mut sum = 0.0;
self.negative_value_store.foreach(|index: i32, count: f64| {
sum -= self.index_mapping.value(index) * count;
});
self.positive_value_store.foreach(|index: i32, count: f64| {
sum += self.index_mapping.value(index) * count;
});
Some(sum)
}
pub fn get_max(&mut self) -> Option<f64> {
return if !self.positive_value_store.is_empty() {
Some(
self.index_mapping
.value(self.positive_value_store.get_max_index()),
)
} else if self.zero_count > 0.0 {
Some(0.0)
} else if !self.negative_value_store.is_empty() {
Some(
-self
.index_mapping
.value(self.negative_value_store.get_min_index()),
)
} else {
None
};
}
pub fn get_min(&mut self) -> Option<f64> {
return if !self.negative_value_store.is_empty() {
Some(
-self
.index_mapping
.value(self.negative_value_store.get_max_index()),
)
} else if self.zero_count > 0.0 {
Some(0.0)
} else if !self.positive_value_store.is_empty() {
Some(
self.index_mapping
.value(self.positive_value_store.get_min_index()),
)
} else {
None
};
}
pub fn get_average(&mut self) -> Option<f64> {
let count = self.get_count();
if count <= 0.0 {
return None;
}
return Some(self.get_sum()? / count);
}
pub fn get_value_at_quantile(self: &mut DDSketch<I, S>, quantile: f64) -> Option<f64> {
if quantile < 0.0 || quantile > 1.0 {
return None;
}
let count = self.get_count();
if count <= 0.0 {
return None;
}
let rank = quantile * (count - 1.0);
let mut n: f64 = 0.0;
let negative_bin_iterator = self.negative_value_store.get_descending_iter();
for bin in negative_bin_iterator {
n += bin.1;
if n > rank {
return Some(-self.index_mapping.value(bin.0));
}
}
n += self.zero_count;
if n > rank {
return Some(0.0);
}
let positive_bin_iterator = self.positive_value_store.get_ascending_iter();
for bin in positive_bin_iterator {
n += bin.1;
if n > rank {
return Some(self.index_mapping.value(bin.0));
}
}
None
}
pub fn decode_and_merge_with(&mut self, input: &mut impl Input) -> Result<(), Error> {
while input.has_remaining() {
let flag = Flag::decode(input)?;
let flag_type = flag.get_type()?;
match flag_type {
FlagType::PositiveStore => {
let mode = BinEncodingMode::of_flag(flag.get_marker())?;
self.positive_value_store
.decode_and_merge_with(input, mode)?;
}
FlagType::NegativeStore => {
let mode = BinEncodingMode::of_flag(flag.get_marker())?;
self.negative_value_store
.decode_and_merge_with(input, mode)?;
}
FlagType::IndexMapping => {
let layout = IndexMappingLayout::of_flag(&flag)?;
let gamma = input.read_double_le()?;
let index_offset = input.read_double_le()?;
match layout {
IndexMappingLayout::LogCubic => {
let decoded_index_mapping =
CubicallyInterpolatedMapping::with_gamma_offset(
gamma,
index_offset,
);
if self.index_mapping.to_string() != decoded_index_mapping.to_string() {
return Err(Error::InvalidArgument("Unmatched IndexMapping"));
}
}
IndexMappingLayout::LOG => {
let decoded_index_mapping =
LogarithmicMapping::with_gamma_offset(gamma, index_offset);
if self.index_mapping.to_string() != decoded_index_mapping.to_string() {
return Err(Error::InvalidArgument("Unmatched IndexMapping"));
}
}
_ => {
return Err(Error::InvalidArgument("Unsupported IndexMapping"));
}
}
}
FlagType::SketchFeatures => {
if Flag::ZERO_COUNT == flag {
self.zero_count += serde::decode_var_double(input)?;
} else {
serde::ignore_exact_summary_statistic_flags(input, flag)?;
}
}
}
}
Ok(())
}
pub fn merge_with(&mut self, other: &mut DDSketch<I, S>) -> Result<(), Error> {
if self.index_mapping.to_string() != other.index_mapping.to_string() {
return Err(Error::InvalidArgument("Unmatched indexMapping."));
}
self.negative_value_store
.merge_with(&mut other.negative_value_store);
self.positive_value_store
.merge_with(&mut other.positive_value_store);
self.zero_count += other.zero_count;
return Ok(());
}
}
impl DDSketch<CubicallyInterpolatedMapping, CollapsingLowestDenseStore> {
pub fn collapsing_lowest_dense(
relative_accuracy: f64,
max_num_bins: usize,
) -> Result<DDSketch<CubicallyInterpolatedMapping, CollapsingLowestDenseStore>, Error> {
let index_mapping =
CubicallyInterpolatedMapping::with_relative_accuracy(relative_accuracy)?;
let negative_value_store = CollapsingLowestDenseStore::with_capacity(max_num_bins)?;
let positive_value_store = CollapsingLowestDenseStore::with_capacity(max_num_bins)?;
let min_indexed_value = f64::max(0.0, index_mapping.min_indexable_value());
let max_indexed_value = index_mapping.max_indexable_value();
let zero_count = 0.0;
Ok(DDSketch {
index_mapping,
negative_value_store,
positive_value_store,
min_indexed_value,
max_indexed_value,
zero_count,
})
}
}
impl DDSketch<CubicallyInterpolatedMapping, CollapsingHighestDenseStore> {
pub fn collapsing_highest_dense(
relative_accuracy: f64,
max_num_bins: usize,
) -> Result<DDSketch<CubicallyInterpolatedMapping, CollapsingHighestDenseStore>, Error> {
let index_mapping =
CubicallyInterpolatedMapping::with_relative_accuracy(relative_accuracy)?;
let negative_value_store = CollapsingHighestDenseStore::with_capacity(max_num_bins)?;
let positive_value_store = CollapsingHighestDenseStore::with_capacity(max_num_bins)?;
let min_indexed_value = f64::max(0.0, index_mapping.min_indexable_value());
let max_indexed_value = index_mapping.max_indexable_value();
let zero_count = 0.0;
Ok(DDSketch {
index_mapping,
negative_value_store,
positive_value_store,
min_indexed_value,
max_indexed_value,
zero_count,
})
}
}
impl DDSketch<CubicallyInterpolatedMapping, UnboundedSizeDenseStore> {
pub fn unbounded_dense(
relative_accuracy: f64,
) -> Result<DDSketch<CubicallyInterpolatedMapping, UnboundedSizeDenseStore>, Error> {
let index_mapping =
CubicallyInterpolatedMapping::with_relative_accuracy(relative_accuracy)?;
let negative_value_store = UnboundedSizeDenseStore::new();
let positive_value_store = UnboundedSizeDenseStore::new();
let min_indexed_value = f64::max(0.0, index_mapping.min_indexable_value());
let max_indexed_value = index_mapping.max_indexable_value();
let zero_count = 0.0;
Ok(DDSketch {
index_mapping,
negative_value_store,
positive_value_store,
min_indexed_value,
max_indexed_value,
zero_count,
})
}
}
impl DDSketch<LogarithmicMapping, CollapsingLowestDenseStore> {
pub fn logarithmic_collapsing_lowest_dense(
relative_accuracy: f64,
max_num_bins: usize,
) -> Result<DDSketch<LogarithmicMapping, CollapsingLowestDenseStore>, Error> {
let index_mapping = LogarithmicMapping::with_relative_accuracy(relative_accuracy)?;
let negative_value_store = CollapsingLowestDenseStore::with_capacity(max_num_bins)?;
let positive_value_store = CollapsingLowestDenseStore::with_capacity(max_num_bins)?;
let min_indexed_value = f64::max(0.0, index_mapping.min_indexable_value());
let max_indexed_value = index_mapping.max_indexable_value();
let zero_count = 0.0;
Ok(DDSketch {
index_mapping,
negative_value_store,
positive_value_store,
min_indexed_value,
max_indexed_value,
zero_count,
})
}
}
impl DDSketch<LogarithmicMapping, CollapsingHighestDenseStore> {
pub fn logarithmic_collapsing_highest_dense(
relative_accuracy: f64,
max_num_bins: usize,
) -> Result<DDSketch<LogarithmicMapping, CollapsingHighestDenseStore>, Error> {
let index_mapping = LogarithmicMapping::with_relative_accuracy(relative_accuracy)?;
let negative_value_store = CollapsingHighestDenseStore::with_capacity(max_num_bins)?;
let positive_value_store = CollapsingHighestDenseStore::with_capacity(max_num_bins)?;
let min_indexed_value = f64::max(0.0, index_mapping.min_indexable_value());
let max_indexed_value = index_mapping.max_indexable_value();
let zero_count = 0.0;
Ok(DDSketch {
index_mapping,
negative_value_store,
positive_value_store,
min_indexed_value,
max_indexed_value,
zero_count,
})
}
}
impl Flag {
pub const ZERO_COUNT: Flag = Flag::with_type(FlagType::SketchFeatures, 1);
pub const COUNT: Flag = Flag::with_type(FlagType::SketchFeatures, 0x28);
pub const SUM: Flag = Flag::with_type(FlagType::SketchFeatures, 0x21);
pub const MIN: Flag = Flag::with_type(FlagType::SketchFeatures, 0x22);
pub const MAX: Flag = Flag::with_type(FlagType::SketchFeatures, 0x23);
pub const fn new(marker: u8) -> Flag {
Flag { marker }
}
pub fn decode(input: &mut impl Input) -> Result<Flag, Error> {
let marker = input.read_byte()?;
Ok(Flag::new(marker))
}
pub fn get_type(&self) -> Result<FlagType, Error> {
FlagType::value_of(self.marker & 3)
}
pub fn get_marker(&self) -> u8 {
self.marker
}
const fn with_type(flag_type: FlagType, sub_flag: u8) -> Flag {
let t = flag_type as u8;
Flag::new(t | (sub_flag << 2))
}
}
impl FlagType {
pub fn value_of(t: u8) -> Result<FlagType, Error> {
match t {
0b00 => Ok(FlagType::SketchFeatures),
0b01 => Ok(FlagType::PositiveStore),
0b10 => Ok(FlagType::IndexMapping),
0b11 => Ok(FlagType::NegativeStore),
_ => Err(Error::InvalidArgument("Unknown FlagType.")),
}
}
}