tisonkun commented on code in PR #400: URL: https://github.com/apache/datasketches-rust/pull/400#discussion_r4658952524
########## datasketches/src/ddsketch/sketch.rs: ########## @@ -0,0 +1,832 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::fmt; + +use super::DEFAULT_RELATIVE_ACCURACY; +use super::iter::DdSketchIter; +use super::mapping::IndexMapping; +use super::mapping::MappingKind; +use super::serialization::deserialize_compat_sketch; +use super::serialization::deserialize_sketch; +use super::serialization::serialize_compat_sketch; +use super::serialization::serialize_sketch; +use super::store::Store; +use super::store::StoreKind; +use super::store::validate_store_kind; +use crate::error::Error; + +/// Builder for configuring and constructing a [`DdSketch`]. +/// +/// Defaults to `relative_accuracy = 0.01`, [`MappingKind::Cubic`], and +/// [`StoreKind::CollapsingLowestDense`] with `2048` bins per sign. +/// +/// # Examples +/// +/// ``` +/// use datasketches::ddsketch::DdSketchBuilder; +/// use datasketches::ddsketch::MappingKind; +/// use datasketches::ddsketch::StoreKind; +/// +/// let mut sketch = DdSketchBuilder::new(0.005) +/// .mapping(MappingKind::Logarithmic) +/// .store(StoreKind::Sparse) +/// .build()?; +/// sketch.update(42.0); +/// assert_eq!(sketch.total_weight(), 1); +/// # Ok::<(), datasketches::error::Error>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct DdSketchBuilder { + relative_accuracy: f64, + mapping_kind: MappingKind, + store_kind: StoreKind, +} + +impl Default for DdSketchBuilder { + fn default() -> Self { + Self::new(DEFAULT_RELATIVE_ACCURACY) + } +} + +impl DdSketchBuilder { + /// Creates a builder with the given `relative_accuracy` and default mapping and store settings. + pub fn new(relative_accuracy: f64) -> Self { + Self { + relative_accuracy, + mapping_kind: MappingKind::default(), + store_kind: StoreKind::default(), + } + } + + /// Sets the index mapping curve used to assign positive magnitudes to bucket indices. + #[inline] + pub fn mapping(mut self, mapping_kind: MappingKind) -> Self { + self.mapping_kind = mapping_kind; + self + } + + /// Sets the bin storage strategy used for both positive and negative stores. + #[inline] + pub fn store(mut self, store_kind: StoreKind) -> Self { + self.store_kind = store_kind; + self + } + + /// Validates configuration parameters and creates an empty [`DdSketch`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`, or if `store` specifies a collapsing + /// dense store with `max_num_bins` outside `1..=67_108_864`. + pub fn build(self) -> Result<DdSketch, Error> { + validate_store_kind(self.store_kind)?; + let mapping = IndexMapping::from_accuracy(self.mapping_kind, self.relative_accuracy)?; + let negative = Store::new(self.store_kind)?; + let positive = Store::new(self.store_kind)?; + Ok(DdSketch::from_parts(mapping, negative, positive, 0, 0)) + } +} + +/// Mergeable quantile sketch over finite `f64` values with relative-value error guarantees. +/// +/// See the [module documentation](super) for accuracy, memory, and compatibility details. +#[derive(Clone)] +pub struct DdSketch { + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, +} + +impl fmt::Debug for DdSketch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DdSketch") + .field("relative_accuracy", &self.mapping.relative_accuracy()) + .field("mapping_kind", &self.mapping.kind()) + .field("store_kind", &self.positive.kind()) + .field("is_empty", &self.is_empty()) + .field("total_weight", &self.total_weight) + .field("zero_weight", &self.zero_weight) + .field("num_retained", &self.num_retained()) + .field("min_value", &self.min_value()) + .field("max_value", &self.max_value()) + .finish() + } +} + +impl Default for DdSketch { + fn default() -> Self { + DdSketchBuilder::default() + .build() + .expect("default DDSketch configuration is valid") + } +} + +impl DdSketch { + /// Creates an empty sketch with the given `relative_accuracy`, [`MappingKind::Cubic`], and + /// [`StoreKind::default()`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let sketch = DdSketch::new(0.01)?; + /// assert!(sketch.is_empty()); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn new(relative_accuracy: f64) -> Result<Self, Error> { + DdSketchBuilder::new(relative_accuracy).build() + } + + pub(super) fn from_parts( + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, + ) -> Self { + debug_assert_eq!( + negative.total_weight() + zero_weight + positive.total_weight(), + total_weight + ); + Self { + mapping, + negative, + positive, + zero_weight, + total_weight, + } + } + + #[inline] + pub(super) const fn mapping(&self) -> IndexMapping { + self.mapping + } + + #[inline] + pub(super) const fn positive_store(&self) -> &Store { + &self.positive + } + + #[inline] + pub(super) const fn negative_store(&self) -> &Store { + &self.negative + } + + /// Returns the relative value accuracy guaranteed for non-collapsed buckets. + #[inline] + pub fn relative_accuracy(&self) -> f64 { + self.mapping.relative_accuracy() + } + + /// Returns the index mapping curve used by this sketch. + #[inline] + pub fn mapping_kind(&self) -> MappingKind { + self.mapping.kind() + } + + /// Returns the bin storage strategy used by this sketch. + #[inline] + pub fn store_kind(&self) -> StoreKind { + self.positive.kind() + } + + /// Returns the magnitude threshold below or at which inputs map to the zero bucket. + /// + /// Any finite input `x` with `|x| <= self.zero_threshold()` increments + /// [`zero_weight`](Self::zero_weight) and is approximated by `0.0`. + #[inline] + pub fn zero_threshold(&self) -> f64 { + self.mapping.min_indexable_value() + } + + /// Returns `true` if this sketch has not recorded any finite observations. + #[inline] + pub fn is_empty(&self) -> bool { + self.total_weight == 0 + } + + /// Returns the accumulated stream weight across all buckets. + #[inline] + pub fn total_weight(&self) -> u64 { + self.total_weight + } + + /// Returns the accumulated stream weight in the zero bucket. + #[inline] + pub fn zero_weight(&self) -> u64 { + self.zero_weight + } + + /// Returns the number of non-empty buckets currently retained by this sketch, including the + /// zero bucket when [`zero_weight`](Self::zero_weight) is non-zero. + #[inline] + pub fn num_retained(&self) -> usize { + self.negative.num_occupied() + + usize::from(self.zero_weight != 0) + + self.positive.num_occupied() + } + + /// Returns an implementation-dependent estimate of heap memory usage in bytes. + pub fn estimated_size(&self) -> usize { + self.negative + .estimated_size() + .saturating_add(self.positive.estimated_size()) + } + + /// Updates this sketch with a single observation. + /// + /// [`f64::NAN`], [`f64::INFINITY`], and [`f64::NEG_INFINITY`] values are ignored. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(10.0); + /// assert_eq!(sketch.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update(&mut self, value: f64) { + self.update_with_weight(value, 1); + } + + /// Updates this sketch with `value` repeated `weight` times. + /// + /// [`f64::NAN`], [`f64::INFINITY`], [`f64::NEG_INFINITY`], and a `weight` of `0` are no-ops. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Cross-language compatibility + /// + /// In the reference DDSketch implementations, Go rejects `NaN`, infinite, and negative-count + /// inputs with an error, whereas Java rejects out-of-range finite/infinite and negative-count + /// inputs while counting `NaN` into the zero bucket; both accept fractional `f64` counts. This + /// method ignores non-finite values and accumulates exact `u64` integer weights; keep + /// per-bucket weights (and [`total_weight`](Self::total_weight) for Java quantile readers) at + /// or below `2^53 - 1` when serializing with [`serialize_compat`](Self::serialize_compat). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update_with_weight(25.0, 100); + /// assert_eq!(sketch.total_weight(), 100); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update_with_weight(&mut self, value: f64, weight: u64) { + if !value.is_finite() || weight == 0 { Review Comment: Thanks for the comparison table. Keeping non-finite inputs ignored by default for now and revisiting configurable input policies in follow-ups sounds good. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
