probabilistic_machines 0.1.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,10 +2,20 @@
2
2
 
3
3
  use alloc::vec::Vec;
4
4
 
5
- use crate::{CodecError, TAG_TDIGEST, read8};
5
+ use crate::{Refusal, TAG_TDIGEST, open_frame};
6
6
 
7
+ /// Tag, the two-byte compression, the four-byte cluster count, then the
8
+ /// eight-byte total weight, minimum and maximum.
7
9
  const HEADER_LEN: usize = 31;
8
- const CENTROID_LEN: usize = 16;
10
+ /// Bytes of one scalar field.
11
+ const FIELD_LEN: usize = 8;
12
+ /// A centroid's mean then weight.
13
+ const CENTROID_LEN: usize = 2 * FIELD_LEN;
14
+
15
+ /// Smallest compression a digest is built with. Below it a cluster may hold
16
+ /// more than 40% of the stream around the median, so a quantile there says
17
+ /// nothing.
18
+ pub const MIN_COMPRESSION: u16 = 10;
9
19
 
10
20
  /// Clusters the digest may hold per unit of compression.
11
21
  const CLUSTERS_PER_COMPRESSION: usize = 10;
@@ -17,10 +27,37 @@ const CLUSTERS_PER_COMPRESSION: usize = 10;
17
27
  const WEIGHT_DRIFT: f64 = 1e-6;
18
28
 
19
29
  /// A weighted point: the mean of the values that collapsed into it.
30
+ ///
31
+ /// Every centroid a digest holds has a finite mean and a finite, positive
32
+ /// weight; [`new`](Self::new) holds a hand-built one to that.
20
33
  #[derive(Debug, Clone, Copy, PartialEq)]
21
34
  pub struct Centroid {
22
- pub mean: f64,
23
- pub weight: f64,
35
+ mean: f64,
36
+ weight: f64,
37
+ }
38
+
39
+ impl Centroid {
40
+ /// A centroid, or `None` when `mean` is not finite or `weight` is not
41
+ /// finite and positive.
42
+ #[must_use]
43
+ pub const fn new(mean: f64, weight: f64) -> Option<Self> {
44
+ if !mean.is_finite() || !weight.is_finite() || weight <= 0.0 {
45
+ return None;
46
+ }
47
+ Some(Self { mean, weight })
48
+ }
49
+
50
+ /// The mean of the values that collapsed into this centroid.
51
+ #[must_use]
52
+ pub const fn mean(&self) -> f64 {
53
+ self.mean
54
+ }
55
+
56
+ /// How many values (or how much weight) collapsed into it.
57
+ #[must_use]
58
+ pub const fn weight(&self) -> f64 {
59
+ self.weight
60
+ }
24
61
  }
25
62
 
26
63
  /// Estimates quantiles from clusters whose weight is capped by how close they
@@ -38,18 +75,23 @@ pub struct Centroid {
38
75
  /// million. Below `10 * compression` points nothing is collapsed and the
39
76
  /// quantiles are exact.
40
77
  ///
78
+ /// Every point is finite with a finite, positive weight, and the total weight
79
+ /// stays finite: [`add_weighted`](Self::add_weighted) and
80
+ /// [`merge`](Self::merge) refuse anything else and change nothing.
81
+ ///
41
82
  /// ```
42
83
  /// use probabilistic_machines::TDigest;
43
84
  ///
44
- /// let mut latency = TDigest::new(100);
85
+ /// let mut latency = TDigest::new(100).ok_or("compression below 10")?;
45
86
  /// for ms in 1..=10_000 {
46
- /// latency.add(f64::from(ms));
87
+ /// latency.add(f64::from(ms))?;
47
88
  /// }
48
89
  ///
49
90
  /// assert!((latency.quantile(0.5) - 5_000.0).abs() < 100.0);
50
91
  /// assert!((latency.quantile(0.99) - 9_900.0).abs() < 50.0);
51
92
  /// assert_eq!(latency.quantile(0.0), 1.0);
52
93
  /// assert_eq!(latency.quantile(1.0), 10_000.0);
94
+ /// # Ok::<(), Box<dyn core::error::Error>>(())
53
95
  /// ```
54
96
  #[derive(Debug, Clone, PartialEq)]
55
97
  pub struct TDigest {
@@ -61,8 +103,17 @@ pub struct TDigest {
61
103
  }
62
104
 
63
105
  impl TDigest {
106
+ /// An empty digest, or `None` when `compression` is below
107
+ /// [`MIN_COMPRESSION`].
64
108
  #[must_use]
65
- pub const fn new(compression: u16) -> Self {
109
+ pub const fn new(compression: u16) -> Option<Self> {
110
+ if compression < MIN_COMPRESSION {
111
+ return None;
112
+ }
113
+ Some(Self::empty(compression))
114
+ }
115
+
116
+ const fn empty(compression: u16) -> Self {
66
117
  Self {
67
118
  compression,
68
119
  centroids: Vec::new(),
@@ -72,6 +123,7 @@ impl TDigest {
72
123
  }
73
124
  }
74
125
 
126
+ /// The compression the digest was built with.
75
127
  #[must_use]
76
128
  pub const fn compression(&self) -> u16 {
77
129
  self.compression
@@ -101,28 +153,48 @@ impl TDigest {
101
153
  &self.centroids
102
154
  }
103
155
 
156
+ /// The number of centroids held.
104
157
  #[must_use]
105
158
  pub const fn len(&self) -> usize {
106
159
  self.centroids.len()
107
160
  }
108
161
 
162
+ /// Whether the digest holds no centroid.
109
163
  #[must_use]
110
164
  pub const fn is_empty(&self) -> bool {
111
165
  self.centroids.is_empty()
112
166
  }
113
167
 
114
- /// Adds one observation of `value`, under the same precondition as
115
- /// [`add_weighted`](Self::add_weighted).
116
- pub fn add(&mut self, value: f64) {
117
- self.add_weighted(value, 1.0);
168
+ /// Adds one observation of `value`.
169
+ ///
170
+ /// # Errors
171
+ ///
172
+ /// As [`add_weighted`](Self::add_weighted).
173
+ pub fn add(&mut self, value: f64) -> Result<(), Refusal> {
174
+ self.add_weighted(value, 1.0)
118
175
  }
119
176
 
120
177
  /// Adds a value standing for `weight` observations.
121
178
  ///
122
- /// `value` must be finite, and `weight` finite and positive: the quantiles
123
- /// of a stream carrying anything else mean nothing, and the clusters it
124
- /// leaves are not ones [`decode`](Self::decode) reads back.
125
- pub fn add_weighted(&mut self, value: f64, weight: f64) {
179
+ /// # Errors
180
+ ///
181
+ /// [`Refusal::NotFinite`] when `value` or `weight` is NaN or infinite,
182
+ /// [`Refusal::InvalidWeight`] when `weight` is zero or negative,
183
+ /// [`Refusal::Overflow`] when the total weight would become infinite. The
184
+ /// quantiles of a stream carrying any of these mean nothing, and the
185
+ /// clusters it would leave are not ones [`decode`](Self::decode) reads
186
+ /// back. The digest is unchanged.
187
+ pub fn add_weighted(&mut self, value: f64, weight: f64) -> Result<(), Refusal> {
188
+ if !value.is_finite() || !weight.is_finite() {
189
+ return Err(Refusal::NotFinite);
190
+ }
191
+ if weight <= 0.0 {
192
+ return Err(Refusal::InvalidWeight);
193
+ }
194
+ let count = self.count + weight;
195
+ if !count.is_finite() {
196
+ return Err(Refusal::Overflow);
197
+ }
126
198
  let at = self
127
199
  .centroids
128
200
  .partition_point(|centroid| centroid.mean < value);
@@ -133,7 +205,7 @@ impl TDigest {
133
205
  weight,
134
206
  },
135
207
  );
136
- self.count += weight;
208
+ self.count = count;
137
209
  if value < self.minimum {
138
210
  self.minimum = value;
139
211
  }
@@ -143,12 +215,14 @@ impl TDigest {
143
215
  if self.centroids.len() > self.capacity() {
144
216
  self.compress();
145
217
  }
218
+ Ok(())
146
219
  }
147
220
 
148
- /// Value at quantile `q`, [`f64::NAN`] when empty.
221
+ /// Value at quantile `q`, [`f64::NAN`] when empty or when `q` is not in
222
+ /// `0.0..=1.0` (NaN included): no rank outside the stream has a value.
149
223
  #[must_use]
150
224
  pub fn quantile(&self, q: f64) -> f64 {
151
- if self.centroids.is_empty() {
225
+ if self.centroids.is_empty() || !(0.0..=1.0).contains(&q) {
152
226
  return f64::NAN;
153
227
  }
154
228
 
@@ -204,11 +278,26 @@ impl TDigest {
204
278
 
205
279
  /// Folds another digest in. The result is the same digest you would get by
206
280
  /// feeding one instance both streams, up to the order clusters formed in.
207
- pub fn merge(&mut self, other: &Self) {
281
+ ///
282
+ /// # Errors
283
+ ///
284
+ /// [`Refusal::WrongShape`] when `other` was built with another
285
+ /// compression: compression only merges clusters, so a coarser digest's
286
+ /// clusters would break this one's weight bound, and a finer one's would
287
+ /// claim a precision this one does not keep. [`Refusal::Overflow`] when
288
+ /// the total weight would become infinite. The digest is unchanged.
289
+ pub fn merge(&mut self, other: &Self) -> Result<(), Refusal> {
290
+ if other.compression != self.compression {
291
+ return Err(Refusal::WrongShape);
292
+ }
293
+ let count = self.count + other.count;
294
+ if !count.is_finite() {
295
+ return Err(Refusal::Overflow);
296
+ }
208
297
  self.centroids.extend_from_slice(&other.centroids);
209
298
  self.centroids
210
299
  .sort_unstable_by(|left, right| left.mean.total_cmp(&right.mean));
211
- self.count += other.count;
300
+ self.count = count;
212
301
  if other.minimum < self.minimum {
213
302
  self.minimum = other.minimum;
214
303
  }
@@ -216,6 +305,7 @@ impl TDigest {
216
305
  self.maximum = other.maximum;
217
306
  }
218
307
  self.compress();
308
+ Ok(())
219
309
  }
220
310
 
221
311
  /// Collapses adjacent clusters up to the weight their quantile allows.
@@ -248,13 +338,11 @@ impl TDigest {
248
338
  // A cluster holding nearly all the weight pins every later rank at 1.0,
249
339
  // where the scale function above can merge nothing.
250
340
  while self.centroids.len() > self.capacity() {
251
- self.centroids = self
252
- .centroids
253
- .chunks(2)
254
- .map(|pair| match pair {
255
- [left, right] => fold(*left, *right),
256
- _ => pair[0],
257
- })
341
+ let (pairs, odd) = self.centroids.as_chunks::<2>();
342
+ self.centroids = pairs
343
+ .iter()
344
+ .map(|&[left, right]| fold(left, right))
345
+ .chain(odd.iter().copied())
258
346
  .collect();
259
347
  }
260
348
  }
@@ -262,6 +350,8 @@ impl TDigest {
262
350
  /// Bytes [`encode`](Self::encode) needs, which grows with the cluster count.
263
351
  #[must_use]
264
352
  pub const fn encoded_len(&self) -> usize {
353
+ // The cluster count is capped by the capacity, `compression * 10`, so
354
+ // this stays below ten megabytes.
265
355
  HEADER_LEN + self.centroids.len() * CENTROID_LEN
266
356
  }
267
357
 
@@ -273,43 +363,45 @@ impl TDigest {
273
363
  ///
274
364
  /// # Errors
275
365
  ///
276
- /// [`CodecError::Truncated`] when `out` is shorter than
366
+ /// [`Refusal::Truncated`] when `out` is shorter than
277
367
  /// [`encoded_len`](Self::encoded_len).
278
- pub fn encode(&self, out: &mut [u8]) -> Result<usize, CodecError> {
279
- let length = self.encoded_len();
280
- let Some(frame) = out.get_mut(..length) else {
281
- return Err(CodecError::Truncated);
282
- };
283
- self.write_frame(frame);
284
- Ok(length)
368
+ pub fn encode(&self, out: &mut [u8]) -> Result<usize, Refusal> {
369
+ crate::encode_frame(out, self.encoded_len(), |header, body| {
370
+ self.write_frame(header, body);
371
+ })
285
372
  }
286
373
 
287
374
  /// The digest's frame, exactly [`encoded_len`](Self::encoded_len) bytes.
288
375
  #[must_use]
289
376
  pub fn encoded(&self) -> alloc::boxed::Box<[u8]> {
290
- let mut frame = alloc::vec![0_u8; self.encoded_len()].into_boxed_slice();
291
- self.write_frame(&mut frame);
292
- frame
377
+ crate::encoded_frame(self.encoded_len(), |header, body| {
378
+ self.write_frame(header, body);
379
+ })
293
380
  }
294
381
 
295
382
  /// Fills a frame of exactly [`encoded_len`](Self::encoded_len) bytes.
296
- fn write_frame(&self, frame: &mut [u8]) {
383
+ fn write_frame(&self, header: &mut [u8; HEADER_LEN], body: &mut [u8]) {
297
384
  #[expect(
298
385
  clippy::cast_possible_truncation,
299
386
  reason = "capacity caps the cluster count at compression * CLUSTERS_PER_COMPRESSION"
300
387
  )]
301
388
  let clusters = self.centroids.len() as u32;
302
- frame[0] = TAG_TDIGEST;
303
- frame[1..3].copy_from_slice(&self.compression.to_le_bytes());
304
- frame[3..7].copy_from_slice(&clusters.to_le_bytes());
305
- frame[7..15].copy_from_slice(&self.count.to_le_bytes());
306
- frame[15..23].copy_from_slice(&self.minimum.to_le_bytes());
307
- frame[23..31].copy_from_slice(&self.maximum.to_le_bytes());
308
-
309
- let (slots, _) = frame[HEADER_LEN..].as_chunks_mut::<CENTROID_LEN>();
389
+ let [tag, c0, c1, n0, n1, n2, n3, scalars @ ..] = header;
390
+ *tag = TAG_TDIGEST;
391
+ [*c0, *c1] = self.compression.to_le_bytes();
392
+ [*n0, *n1, *n2, *n3] = clusters.to_le_bytes();
393
+ let (fields, _) = scalars.as_chunks_mut::<FIELD_LEN>();
394
+ for (field, value) in fields
395
+ .iter_mut()
396
+ .zip([self.count, self.minimum, self.maximum])
397
+ {
398
+ *field = value.to_le_bytes();
399
+ }
400
+
401
+ let (fields, _) = body.as_chunks_mut::<FIELD_LEN>();
402
+ let (slots, _) = fields.as_chunks_mut::<2>();
310
403
  for (slot, centroid) in slots.iter_mut().zip(&self.centroids) {
311
- slot[..8].copy_from_slice(&centroid.mean.to_le_bytes());
312
- slot[8..].copy_from_slice(&centroid.weight.to_le_bytes());
404
+ *slot = [centroid.mean.to_le_bytes(), centroid.weight.to_le_bytes()];
313
405
  }
314
406
  }
315
407
 
@@ -317,43 +409,49 @@ impl TDigest {
317
409
  ///
318
410
  /// # Errors
319
411
  ///
320
- /// [`CodecError::Truncated`] when `bytes` is shorter than a header or than
412
+ /// [`Refusal::Truncated`] when `bytes` is shorter than a header or than
321
413
  /// the clusters that header counts,
322
- /// [`CodecError::Tag`] when it holds another structure,
323
- /// [`CodecError::Parameters`] when the clusters, the total weight and the
324
- /// extremes contradict each other.
325
- pub fn decode(bytes: &[u8]) -> Result<Self, CodecError> {
326
- let Some(header) = bytes.get(..HEADER_LEN) else {
327
- return Err(CodecError::Truncated);
414
+ /// [`Refusal::WrongStructure`] when it holds another structure,
415
+ /// [`Refusal::Malformed`] when its compression is below
416
+ /// [`MIN_COMPRESSION`] or the clusters, the total weight and the extremes
417
+ /// contradict each other.
418
+ pub fn decode(bytes: &[u8]) -> Result<Self, Refusal> {
419
+ let (header, body) = open_frame::<HEADER_LEN>(bytes, bytes.len(), TAG_TDIGEST)?;
420
+ let [_, c0, c1, n0, n1, n2, n3, scalars @ ..] = *header;
421
+ let Ok(clusters) = usize::try_from(u32::from_le_bytes([n0, n1, n2, n3])) else {
422
+ return Err(Refusal::Truncated);
328
423
  };
329
- if header[0] != TAG_TDIGEST {
330
- return Err(CodecError::Tag);
331
- }
332
- let counted = u32::from_le_bytes([header[3], header[4], header[5], header[6]]);
333
- let Ok(clusters) = usize::try_from(counted) else {
334
- return Err(CodecError::Truncated);
424
+ let (fields, _) = body.as_chunks::<FIELD_LEN>();
425
+ let (slots, _) = fields.as_chunks::<2>();
426
+ let Some(slots) = slots.get(..clusters) else {
427
+ return Err(Refusal::Truncated);
335
428
  };
336
- if (bytes.len() - HEADER_LEN) / CENTROID_LEN < clusters {
337
- return Err(CodecError::Truncated);
338
- }
339
- let body = &bytes[HEADER_LEN..HEADER_LEN + clusters * CENTROID_LEN];
340
429
 
341
- let mut digest = Self::new(u16::from_le_bytes([header[1], header[2]]));
342
- digest.count = f64::from_le_bytes(read8(&header[7..15]));
343
- digest.minimum = f64::from_le_bytes(read8(&header[15..23]));
344
- digest.maximum = f64::from_le_bytes(read8(&header[23..31]));
345
- let (slots, _) = body.as_chunks::<CENTROID_LEN>();
430
+ let Some(mut digest) = Self::new(u16::from_le_bytes([c0, c1])) else {
431
+ return Err(Refusal::Malformed);
432
+ };
433
+ let (fields, _) = scalars.as_chunks::<FIELD_LEN>();
434
+ let mut fields = fields.iter().copied().map(f64::from_le_bytes);
435
+ // Twenty-four bytes are exactly three fields: none of these is short.
436
+ let (Some(count), Some(minimum), Some(maximum)) =
437
+ (fields.next(), fields.next(), fields.next())
438
+ else {
439
+ return Err(Refusal::Truncated);
440
+ };
441
+ digest.count = count;
442
+ digest.minimum = minimum;
443
+ digest.maximum = maximum;
346
444
  digest.centroids = slots
347
445
  .iter()
348
- .map(|slot| Centroid {
349
- mean: f64::from_le_bytes(read8(&slot[..8])),
350
- weight: f64::from_le_bytes(read8(&slot[8..])),
446
+ .map(|&[mean, weight]| Centroid {
447
+ mean: f64::from_le_bytes(mean),
448
+ weight: f64::from_le_bytes(weight),
351
449
  })
352
450
  .collect();
353
451
  if digest.is_coherent() {
354
452
  Ok(digest)
355
453
  } else {
356
- Err(CodecError::Parameters)
454
+ Err(Refusal::Malformed)
357
455
  }
358
456
  }
359
457
 
@@ -386,10 +484,9 @@ impl TDigest {
386
484
  && last.mean <= self.maximum
387
485
  }
388
486
 
389
- /// Clusters held before compression runs, and never below the one cluster
390
- /// folding cannot reduce further.
487
+ /// Clusters held before compression runs.
391
488
  fn capacity(&self) -> usize {
392
- (usize::from(self.compression) * CLUSTERS_PER_COMPRESSION).max(1)
489
+ usize::from(self.compression) * CLUSTERS_PER_COMPRESSION
393
490
  }
394
491
  }
395
492
 
@@ -398,12 +495,6 @@ impl TDigest {
398
495
  /// Interpolating at half scale keeps the span of two opposite-sign extremes
399
496
  /// inside the finite range, and doubling a mean that lies between two finite
400
497
  /// means cannot leave it.
401
- // Clippy only suggests `mul_add` when `std` provides it; `core` has no
402
- // `f64::mul_add`, so the suggestion would break the `no_std` build.
403
- #[cfg_attr(
404
- feature = "std",
405
- expect(clippy::suboptimal_flops, reason = "mul_add is std-only")
406
- )]
407
498
  fn fold(left: Centroid, right: Centroid) -> Centroid {
408
499
  let weight = left.weight + right.weight;
409
500
  let low = left.mean * 0.5;
@@ -421,12 +512,6 @@ fn fold(left: Centroid, right: Centroid) -> Centroid {
421
512
  /// halved the way [`fold`] averages, which costs nothing while the halves stay
422
513
  /// normal but rounds a subnormal span to zero, so the span is only halved when
423
514
  /// it does not fit.
424
- // Clippy only suggests `mul_add` when `std` provides it; `core` has no
425
- // `f64::mul_add`, so the suggestion would break the `no_std` build.
426
- #[cfg_attr(
427
- feature = "std",
428
- expect(clippy::suboptimal_flops, reason = "mul_add is std-only")
429
- )]
430
515
  fn lerp(at: f64, low_x: f64, low_y: f64, high_x: f64, high_y: f64) -> f64 {
431
516
  if high_x <= low_x {
432
517
  return high_y;