This is an automated email from the ASF dual-hosted git repository.
tisonkun pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datasketches-rust.git
The following commit(s) were added to refs/heads/main by this push:
new ee6e1cc feat(theta): add theta union (#145)
ee6e1cc is described below
commit ee6e1cc432555c3562274ec36fc2dd6419b96701
Author: ZENOTME <[email protected]>
AuthorDate: Sat Jul 18 17:11:13 2026 +0800
feat(theta): add theta union (#145)
Co-authored-by: tison <[email protected]>
---
datasketches/src/bloom/sketch.rs | 2 +-
datasketches/src/common/mod.rs | 2 -
datasketches/src/cpc/pair_table.rs | 2 +-
datasketches/src/cpc/sketch.rs | 2 +-
datasketches/src/hll/aux_map.rs | 2 +-
datasketches/src/hll/container.rs | 2 +-
datasketches/src/hll/sketch.rs | 2 +-
datasketches/src/lib.rs | 2 +
datasketches/src/tdigest/sketch.rs | 8 +-
datasketches/src/theta/hash_table.rs | 60 +-
datasketches/src/theta/intersection.rs | 25 +-
datasketches/src/theta/mod.rs | 22 +-
datasketches/src/theta/sketch.rs | 114 ++--
datasketches/src/theta/union.rs | 184 ++++++
.../src/{common => thetacommon}/binomial_bounds.rs | 0
.../{common/mod.rs => thetacommon/constants.rs} | 26 +-
.../hash_table.rs} | 93 +--
datasketches/src/thetacommon/mod.rs | 53 ++
datasketches/src/thetacommon/union.rs | 248 ++++++++
datasketches/tests/theta_intersection_test.rs | 42 +-
datasketches/tests/theta_union_test.rs | 688 +++++++++++++++++++++
21 files changed, 1365 insertions(+), 214 deletions(-)
diff --git a/datasketches/src/bloom/sketch.rs b/datasketches/src/bloom/sketch.rs
index bfc5f63..4fab1c0 100644
--- a/datasketches/src/bloom/sketch.rs
+++ b/datasketches/src/bloom/sketch.rs
@@ -564,7 +564,7 @@ impl BloomFilter {
/// Returns the estimated size of the filter in bytes
pub fn estimated_size(&self) -> usize {
- std::mem::size_of::<Self>() + self.bit_array.len() *
std::mem::size_of::<u64>()
+ size_of::<Self>() + self.bit_array.len() * size_of::<u64>()
}
}
diff --git a/datasketches/src/common/mod.rs b/datasketches/src/common/mod.rs
index 95d2b2d..d7e0cf5 100644
--- a/datasketches/src/common/mod.rs
+++ b/datasketches/src/common/mod.rs
@@ -22,7 +22,5 @@ mod resize;
pub use self::num_std_dev::NumStdDev;
pub use self::resize::ResizeFactor;
-#[cfg(feature = "theta")]
-pub(crate) mod binomial_bounds;
#[cfg(any(feature = "cpc", feature = "hll"))]
pub(crate) mod inv_pow2_table;
diff --git a/datasketches/src/cpc/pair_table.rs
b/datasketches/src/cpc/pair_table.rs
index d36d68d..4c4de42 100644
--- a/datasketches/src/cpc/pair_table.rs
+++ b/datasketches/src/cpc/pair_table.rs
@@ -249,6 +249,6 @@ impl PairTable {
/// Returns the estimated size of the heap allocations in bytes
pub fn estimated_size(&self) -> usize {
- self.slots.capacity() * std::mem::size_of::<u32>()
+ self.slots.capacity() * size_of::<u32>()
}
}
diff --git a/datasketches/src/cpc/sketch.rs b/datasketches/src/cpc/sketch.rs
index 58cc232..c46a94f 100644
--- a/datasketches/src/cpc/sketch.rs
+++ b/datasketches/src/cpc/sketch.rs
@@ -460,7 +460,7 @@ impl CpcSketch {
.map(|t| t.estimated_size())
.unwrap_or(0);
- std::mem::size_of::<Self>() + heap_size
+ size_of::<Self>() + heap_size
}
}
diff --git a/datasketches/src/hll/aux_map.rs b/datasketches/src/hll/aux_map.rs
index fed7fac..86339a5 100644
--- a/datasketches/src/hll/aux_map.rs
+++ b/datasketches/src/hll/aux_map.rs
@@ -229,7 +229,7 @@ impl AuxMap {
/// Returns the estimated size of the heap allocations in bytes
pub fn estimated_size(&self) -> usize {
- self.entries.len() * std::mem::size_of::<Coupon>()
+ self.entries.len() * size_of::<Coupon>()
}
}
diff --git a/datasketches/src/hll/container.rs
b/datasketches/src/hll/container.rs
index 716f045..e15d6bc 100644
--- a/datasketches/src/hll/container.rs
+++ b/datasketches/src/hll/container.rs
@@ -138,6 +138,6 @@ impl Container {
/// Returns the estimated size of the heap allocations in bytes
pub fn estimated_size(&self) -> usize {
- self.coupons.len() * std::mem::size_of::<Coupon>()
+ self.coupons.len() * size_of::<Coupon>()
}
}
diff --git a/datasketches/src/hll/sketch.rs b/datasketches/src/hll/sketch.rs
index 91d79b0..25ba047 100644
--- a/datasketches/src/hll/sketch.rs
+++ b/datasketches/src/hll/sketch.rs
@@ -434,7 +434,7 @@ impl HllSketch {
Mode::Array8(arr) => arr.estimated_size(),
};
- std::mem::size_of::<Self>() + heap_size
+ size_of::<Self>() + heap_size
}
}
diff --git a/datasketches/src/lib.rs b/datasketches/src/lib.rs
index 65f0ddd..90510d5 100644
--- a/datasketches/src/lib.rs
+++ b/datasketches/src/lib.rs
@@ -45,6 +45,8 @@ pub mod hll;
pub mod tdigest;
#[cfg(feature = "theta")]
pub mod theta;
+#[cfg(feature = "theta")]
+pub mod thetacommon;
// common modules
pub mod codec;
diff --git a/datasketches/src/tdigest/sketch.rs
b/datasketches/src/tdigest/sketch.rs
index 9e14759..765ac13 100644
--- a/datasketches/src/tdigest/sketch.rs
+++ b/datasketches/src/tdigest/sketch.rs
@@ -796,9 +796,9 @@ impl TDigestMut {
/// Returns the estimated size of the sketch in bytes
pub fn estimated_size(&self) -> usize {
- std::mem::size_of::<Self>()
- + self.centroids.capacity() * std::mem::size_of::<Centroid>()
- + self.buffer.capacity() * std::mem::size_of::<f64>()
+ size_of::<Self>()
+ + self.centroids.capacity() * size_of::<Centroid>()
+ + self.buffer.capacity() * size_of::<f64>()
}
}
@@ -1011,7 +1011,7 @@ impl TDigest {
/// Returns the estimated size of the sketch in bytes
pub fn estimated_size(&self) -> usize {
- std::mem::size_of::<Self>() + self.centroids.capacity() *
std::mem::size_of::<Centroid>()
+ size_of::<Self>() + self.centroids.capacity() * size_of::<Centroid>()
}
}
diff --git a/datasketches/src/theta/hash_table.rs
b/datasketches/src/theta/hash_table.rs
index 4fbd5e6..fa9036b 100644
--- a/datasketches/src/theta/hash_table.rs
+++ b/datasketches/src/theta/hash_table.rs
@@ -18,12 +18,8 @@
use std::hash::Hash;
use std::num::NonZeroU64;
-use crate::theta::raw_hash_table::RawHashTable;
-use crate::theta::raw_hash_table::RawHashTableEntry;
-#[cfg(test)]
-pub(crate) use crate::theta::raw_hash_table::starting_sub_multiple;
-#[cfg(test)]
-pub(crate) use
crate::theta::raw_hash_table::starting_theta_from_sampling_probability;
+use crate::thetacommon::RawHashTableEntry;
+use crate::thetacommon::hash_table::RawHashTable;
/// Specific hash table for theta sketch
///
@@ -34,16 +30,22 @@ pub(crate) use
crate::theta::raw_hash_table::starting_theta_from_sampling_probab
/// update the theta to the k-th smallest entry.
pub(super) type ThetaHashTable = RawHashTable<ThetaEntry>;
+/// A retained entry in a Theta sketch.
#[derive(Debug, Clone, Copy)]
-pub(crate) struct ThetaEntry {
+pub struct ThetaEntry {
hash: NonZeroU64,
}
impl ThetaEntry {
- fn new(hash: u64) -> Self {
+ pub(crate) fn new(hash: u64) -> Self {
let hash = NonZeroU64::new(hash).expect("hash must be non-zero");
Self { hash }
}
+
+ /// Return the hash used as this entry's key.
+ pub fn hash(&self) -> u64 {
+ self.hash.get()
+ }
}
impl RawHashTableEntry for ThetaEntry {
@@ -90,18 +92,20 @@ mod tests {
use super::*;
use crate::common::ResizeFactor;
use crate::hash::DEFAULT_UPDATE_SEED;
- use crate::theta::MAX_THETA;
- use crate::theta::MIN_LG_K;
+ use crate::thetacommon::constants::MAX_THETA;
+ use crate::thetacommon::constants::MIN_LG_K;
+ use crate::thetacommon::hash_table::starting_sub_multiple;
+ use
crate::thetacommon::hash_table::starting_theta_from_sampling_probability;
#[test]
fn test_new_hash_table() {
let table = ThetaHashTable::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
assert_eq!(
- table.lg_cur_size,
+ table.lg_cur_size(),
starting_sub_multiple(8 + 1, MIN_LG_K, ResizeFactor::X8.lg_value())
);
- assert_eq!(table.theta, starting_theta_from_sampling_probability(1.0));
+ assert_eq!(table.theta(),
starting_theta_from_sampling_probability(1.0));
assert_eq!(table.num_retained(), 0);
assert!(table.is_empty());
assert_eq!(table.iter().count(), 0);
@@ -119,7 +123,7 @@ mod tests {
assert_ne!(hash1, hash2);
// With low theta, update should be screened out.
- table.theta = 1;
+ table.set_theta(1);
assert!(!table.try_insert("test3"));
}
@@ -136,7 +140,7 @@ mod tests {
assert_eq!(table.num_retained(), 1);
// Force screening and verify insertion fails
- table.theta = 0;
+ table.set_theta(1); // Set theta to a low value to screen out new
entries
assert!(!table.try_insert("screened"));
assert_eq!(table.num_retained(), 1);
assert!(!table.is_empty());
@@ -174,7 +178,7 @@ mod tests {
{
let mut table = ThetaHashTable::new(8, ResizeFactor::X2, 1.0,
DEFAULT_UPDATE_SEED);
- assert_eq!(table.entries.len(), 32);
+ assert_eq!(table.num_entries(), 32);
// Insert enough values to trigger resize (50% threshold)
// Capacity = 32 * 0.5 = 16
@@ -183,14 +187,14 @@ mod tests {
// Table should have resized and all values should be inserted
assert!(table.num_retained() > 0);
assert_eq!(table.num_retained(), inserted);
- assert_eq!(table.entries.len(), 64);
+ assert_eq!(table.num_entries(), 64);
}
// Test different resize factors
{
let mut table = ThetaHashTable::new(8, ResizeFactor::X4, 1.0,
DEFAULT_UPDATE_SEED);
- assert_eq!(table.entries.len(), 32);
+ assert_eq!(table.num_entries(), 32);
// Insert enough values to trigger resize (50% threshold)
// Capacity = 32 * 0.5 = 16
@@ -199,7 +203,7 @@ mod tests {
// Table should have resized and all values should be inserted
assert!(table.num_retained() > 0);
assert_eq!(table.num_retained(), inserted);
- assert_eq!(table.entries.len(), 128);
+ assert_eq!(table.num_entries(), 128);
}
}
@@ -207,9 +211,9 @@ mod tests {
fn test_rebuild() {
let mut table = ThetaHashTable::new(5, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
- assert_eq!(table.lg_cur_size, 6);
- assert_eq!(table.entries.len(), 64);
- assert_eq!(table.theta, MAX_THETA);
+ assert_eq!(table.lg_cur_size(), 6);
+ assert_eq!(table.num_entries(), 64);
+ assert_eq!(table.theta(), MAX_THETA);
// Insert many values to trigger rebuild
for i in 0..100 {
@@ -228,9 +232,9 @@ mod tests {
let _ = table.try_insert(format!("value_{}", i));
}
- assert_eq!(table.lg_cur_size, 6);
- assert!(table.entries.len() >= 64);
- assert!(table.theta < new_theta);
+ assert_eq!(table.lg_cur_size(), 6);
+ assert!(table.num_entries() >= 64);
+ assert!(table.theta() < new_theta);
}
#[test]
@@ -274,8 +278,8 @@ mod tests {
fn test_reset() {
let mut table = ThetaHashTable::new(8, ResizeFactor::X8, 1.0,
DEFAULT_UPDATE_SEED);
let init_theta = table.theta();
- let init_lg_cur = table.lg_cur_size;
- let init_entries = table.entries.len();
+ let init_lg_cur = table.lg_cur_size();
+ let init_entries = table.num_entries();
// Insert some values
for i in 0..10 {
@@ -291,8 +295,8 @@ mod tests {
assert!(table.is_empty());
assert_eq!(table.num_retained(), 0);
assert_eq!(table.theta(), init_theta);
- assert_eq!(table.lg_cur_size, init_lg_cur);
- assert_eq!(table.entries.len(), init_entries);
+ assert_eq!(table.lg_cur_size(), init_lg_cur);
+ assert_eq!(table.num_entries(), init_entries);
assert_eq!(table.iter().count(), 0);
}
diff --git a/datasketches/src/theta/intersection.rs
b/datasketches/src/theta/intersection.rs
index 85d2eb7..6383643 100644
--- a/datasketches/src/theta/intersection.rs
+++ b/datasketches/src/theta/intersection.rs
@@ -19,10 +19,10 @@ use crate::common::ResizeFactor;
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
use crate::theta::CompactThetaSketch;
-use crate::theta::HASH_TABLE_REBUILD_THRESHOLD;
-use crate::theta::MAX_THETA;
use crate::theta::ThetaSketchView;
use crate::theta::hash_table::ThetaHashTable;
+use crate::thetacommon::constants::HASH_TABLE_REBUILD_THRESHOLD;
+use crate::thetacommon::constants::MAX_THETA;
/// Stateful intersection operator for Theta sketches.
///
@@ -93,7 +93,7 @@ impl ThetaIntersection {
self.table.set_theta(if self.table.is_empty() {
MAX_THETA
} else {
- self.table.theta().min(sketch.theta64())
+ self.table.theta().min(sketch.theta())
});
if self.is_valid && self.table.num_retained() == 0 {
@@ -122,7 +122,8 @@ impl ThetaIntersection {
self.table.hash_seed(),
self.table.is_empty(),
);
- for hash in sketch.iter() {
+ for entry in sketch.iter() {
+ let hash = entry.hash();
if !self.table.try_insert_hash(hash) {
return Err(Error::invalid_argument(
"Insert entries from sketch fail, possibly corrupted
input sketch",
@@ -139,7 +140,8 @@ impl ThetaIntersection {
let max_matches =
self.table.num_retained().min(sketch.num_retained());
let mut matched_entries = Vec::with_capacity(max_matches);
let mut count = 0;
- for hash in sketch.iter() {
+ for entry in sketch.iter() {
+ let hash = entry.hash();
if hash < self.table.theta() {
if self.table.contains_hash(hash) {
if matched_entries.len() == max_matches {
@@ -200,24 +202,15 @@ impl ThetaIntersection {
self.is_valid
}
- /// Returns the intersection result as a compact theta sketch (ordered).
- ///
- /// # Panics
- ///
- /// Panics if called before the first [`update`](Self::update).
- pub fn result(&self) -> CompactThetaSketch {
- self.result_with_ordered(true)
- }
-
/// Returns the intersection result as a compact theta sketch.
///
/// # Panics
///
/// Panics if called before the first [`update`](Self::update).
- pub fn result_with_ordered(&self, ordered: bool) -> CompactThetaSketch {
+ pub fn to_sketch(&self, ordered: bool) -> CompactThetaSketch {
assert!(
self.is_valid,
- "ThetaIntersection::result() called before first update()"
+ "ThetaIntersection::to_sketch() called before first update()"
);
let mut hashes: Vec<u64> = self.table.iter().collect();
if ordered {
diff --git a/datasketches/src/theta/mod.rs b/datasketches/src/theta/mod.rs
index 2ca938c..10bfa3e 100644
--- a/datasketches/src/theta/mod.rs
+++ b/datasketches/src/theta/mod.rs
@@ -42,29 +42,15 @@
mod bit_pack;
mod hash_table;
mod intersection;
-mod raw_hash_table;
mod serialization;
mod sketch;
+mod union;
+pub use self::hash_table::ThetaEntry;
pub use self::intersection::ThetaIntersection;
pub use self::sketch::CompactThetaSketch;
pub use self::sketch::ThetaSketch;
pub use self::sketch::ThetaSketchBuilder;
pub use self::sketch::ThetaSketchView;
-
-/// Maximum theta value (signed max for compatibility with Java)
-pub(crate) const MAX_THETA: u64 = i64::MAX as u64;
-/// Minimum log2 of K
-pub(crate) const MIN_LG_K: u8 = 5;
-/// Maximum log2 of K
-pub(crate) const MAX_LG_K: u8 = 26;
-/// Default log2 of K
-pub(crate) const DEFAULT_LG_K: u8 = 12;
-/// Resize threshold (0.5 = 50% load factor)
-pub(crate) const HASH_TABLE_RESIZE_THRESHOLD: f64 = 0.5;
-/// Rebuild threshold (15/16 = 93.75% load factor)
-pub(crate) const HASH_TABLE_REBUILD_THRESHOLD: f64 = 15.0 / 16.0;
-/// Stride hash bits (7 bits for stride calculation)
-pub(crate) const STRIDE_HASH_BITS: u8 = 7;
-/// Stride mask
-pub(crate) const STRIDE_MASK: u64 = (1 << STRIDE_HASH_BITS) - 1;
+pub use self::union::ThetaUnion;
+pub use self::union::ThetaUnionBuilder;
diff --git a/datasketches/src/theta/sketch.rs b/datasketches/src/theta/sketch.rs
index 6ee9a23..5821415 100644
--- a/datasketches/src/theta/sketch.rs
+++ b/datasketches/src/theta/sketch.rs
@@ -29,59 +29,59 @@ use crate::codec::assert::insufficient_data;
use crate::codec::family::Family;
use crate::common::NumStdDev;
use crate::common::ResizeFactor;
-use crate::common::binomial_bounds;
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
use crate::hash::compute_seed_hash;
-use crate::theta::DEFAULT_LG_K;
-use crate::theta::MAX_LG_K;
-use crate::theta::MAX_THETA;
-use crate::theta::MIN_LG_K;
use crate::theta::bit_pack::BLOCK_WIDTH;
use crate::theta::bit_pack::BitPacker;
use crate::theta::bit_pack::BitUnpacker;
use crate::theta::bit_pack::pack_bits_block;
use crate::theta::bit_pack::unpack_bits_block;
+use crate::theta::hash_table::ThetaEntry;
use crate::theta::hash_table::ThetaHashTable;
use crate::theta::serialization;
use crate::theta::serialization::V2_PREAMBLE_EMPTY;
use crate::theta::serialization::V2_PREAMBLE_ESTIMATE;
use crate::theta::serialization::V2_PREAMBLE_PRECISE;
-
-mod private {
- use super::*;
-
- // Sealed trait to prevent external implementations of ThetaSketchView.
- pub trait Sealed {}
-
- impl Sealed for ThetaSketch {}
- impl Sealed for CompactThetaSketch {}
-}
+use crate::thetacommon::RawThetaSketchView;
+use crate::thetacommon::binomial_bounds;
+use crate::thetacommon::constants::DEFAULT_LG_K;
+use crate::thetacommon::constants::MAX_LG_K;
+use crate::thetacommon::constants::MAX_THETA;
+use crate::thetacommon::constants::MIN_LG_K;
/// Read-only view for Theta sketches.
///
/// This trait provides a unified input abstraction for APIs that can accept
either
/// mutable [`ThetaSketch`] or immutable [`CompactThetaSketch`].
-pub trait ThetaSketchView: private::Sealed {
- /// Returns the 16-bit seed hash.
- fn seed_hash(&self) -> u16;
+pub trait ThetaSketchView: RawThetaSketchView<ThetaEntry> {}
- /// Returns theta as `u64`.
- fn theta64(&self) -> u64;
+impl<T: RawThetaSketchView<ThetaEntry>> ThetaSketchView for T {}
- /// Returns true if this sketch is empty.
- fn is_empty(&self) -> bool;
+impl RawThetaSketchView<ThetaEntry> for ThetaSketch {
+ fn seed_hash(&self) -> u16 {
+ ThetaSketch::seed_hash(self)
+ }
- /// Returns an iterator over retained hash values.
- fn iter(&self) -> impl Iterator<Item = u64> + '_;
+ fn theta(&self) -> u64 {
+ ThetaSketch::theta64(self)
+ }
- /// Returns number of retained hash values.
- fn num_retained(&self) -> usize;
+ fn is_empty(&self) -> bool {
+ ThetaSketch::is_empty(self)
+ }
- /// Returns whether retained entries are ordered in ascending order.
fn is_ordered(&self) -> bool {
false
}
+
+ fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
+ self.table.iter_entries().copied()
+ }
+
+ fn num_retained(&self) -> usize {
+ ThetaSketch::num_retained(self)
+ }
}
/// Mutable theta sketch for building from input data
@@ -191,7 +191,7 @@ impl ThetaSketch {
self.table.reset();
}
- /// Return iterator over hash values
+ /// Return iterator over retained entries.
///
/// # Examples
///
@@ -202,8 +202,8 @@ impl ThetaSketch {
/// let mut iter = sketch.iter();
/// assert!(iter.next().is_some());
/// ```
- pub fn iter(&self) -> impl Iterator<Item = u64> + '_ {
- self.table.iter()
+ pub fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
+ self.table.iter_entries().copied()
}
/// Return this sketch in compact (immutable) form.
@@ -220,7 +220,7 @@ impl ThetaSketch {
/// assert_eq!(compact.num_retained(), 1);
/// ```
pub fn compact(&self, ordered: bool) -> CompactThetaSketch {
- let mut entries: Vec<u64> = self.iter().collect();
+ let mut entries: Vec<u64> = self.iter().map(|entry|
entry.hash()).collect();
let empty = self.is_empty();
let theta = if empty {
@@ -316,29 +316,7 @@ impl ThetaSketch {
/// Returns the estimated size of the sketch in bytes
pub fn estimated_size(&self) -> usize {
- std::mem::size_of::<Self>() + self.table.estimated_size()
- }
-}
-
-impl ThetaSketchView for ThetaSketch {
- fn seed_hash(&self) -> u16 {
- ThetaSketch::seed_hash(self)
- }
-
- fn theta64(&self) -> u64 {
- ThetaSketch::theta64(self)
- }
-
- fn is_empty(&self) -> bool {
- ThetaSketch::is_empty(self)
- }
-
- fn iter(&self) -> impl Iterator<Item = u64> + '_ {
- ThetaSketch::iter(self)
- }
-
- fn num_retained(&self) -> usize {
- ThetaSketch::num_retained(self)
+ size_of::<Self>() + self.table.estimated_size()
}
}
@@ -420,9 +398,9 @@ impl CompactThetaSketch {
self.seed_hash
}
- /// Return iterator over retained hash values.
- pub fn iter(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().copied()
+ /// Return iterator over retained entries.
+ pub fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
+ self.entries.iter().copied().map(ThetaEntry::new)
}
/// Returns the approximate lower error bound given the specified number
of Standard Deviations.
@@ -896,16 +874,16 @@ impl CompactThetaSketch {
/// Returns the estimated size of the sketch in bytes
pub fn estimated_size(&self) -> usize {
- std::mem::size_of::<Self>() + self.entries.capacity() *
std::mem::size_of::<u64>()
+ size_of::<Self>() + self.entries.capacity() * size_of::<u64>()
}
}
-impl ThetaSketchView for CompactThetaSketch {
+impl RawThetaSketchView<ThetaEntry> for CompactThetaSketch {
fn seed_hash(&self) -> u16 {
CompactThetaSketch::seed_hash(self)
}
- fn theta64(&self) -> u64 {
+ fn theta(&self) -> u64 {
CompactThetaSketch::theta64(self)
}
@@ -913,16 +891,16 @@ impl ThetaSketchView for CompactThetaSketch {
CompactThetaSketch::is_empty(self)
}
- fn iter(&self) -> impl Iterator<Item = u64> + '_ {
- CompactThetaSketch::iter(self)
+ fn is_ordered(&self) -> bool {
+ CompactThetaSketch::is_ordered(self)
}
- fn num_retained(&self) -> usize {
- CompactThetaSketch::num_retained(self)
+ fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
+ self.entries.iter().copied().map(ThetaEntry::new)
}
- fn is_ordered(&self) -> bool {
- CompactThetaSketch::is_ordered(self)
+ fn num_retained(&self) -> usize {
+ CompactThetaSketch::num_retained(self)
}
}
@@ -1041,13 +1019,13 @@ mod tests {
use super::*;
fn sorted_theta_entries(sketch: &ThetaSketch) -> Vec<u64> {
- let mut entries: Vec<u64> = sketch.iter().collect();
+ let mut entries: Vec<u64> = sketch.iter().map(|entry|
entry.hash()).collect();
entries.sort_unstable();
entries
}
fn sorted_compact_entries(sketch: &CompactThetaSketch) -> Vec<u64> {
- let mut entries: Vec<u64> = sketch.iter().collect();
+ let mut entries: Vec<u64> = sketch.iter().map(|entry|
entry.hash()).collect();
entries.sort_unstable();
entries
}
diff --git a/datasketches/src/theta/union.rs b/datasketches/src/theta/union.rs
new file mode 100644
index 0000000..9f19513
--- /dev/null
+++ b/datasketches/src/theta/union.rs
@@ -0,0 +1,184 @@
+// 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 crate::common::ResizeFactor;
+use crate::error::Error;
+use crate::hash::DEFAULT_UPDATE_SEED;
+use crate::theta::CompactThetaSketch;
+use crate::theta::ThetaSketchView;
+use crate::theta::hash_table::ThetaEntry;
+use crate::thetacommon::constants::DEFAULT_LG_K;
+use crate::thetacommon::constants::MAX_LG_K;
+use crate::thetacommon::constants::MIN_LG_K;
+use crate::thetacommon::union::RawThetaUnion;
+use crate::thetacommon::union::RawThetaUnionPolicy;
+
+/// Stateful union operator for Theta sketches.
+#[derive(Debug)]
+pub struct ThetaUnion {
+ raw: RawThetaUnion<ThetaEntry, NoopUnionPolicy>,
+}
+
+#[derive(Debug)]
+struct NoopUnionPolicy;
+
+impl RawThetaUnionPolicy<ThetaEntry> for NoopUnionPolicy {
+ fn merge(&self, _existing: &mut ThetaEntry, _incoming: ThetaEntry) {}
+}
+
+impl ThetaUnion {
+ /// Create a new builder for ThetaUnion
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::theta::ThetaUnion;
+ /// let _union = ThetaUnion::builder().lg_k(12).build();
+ /// ```
+ pub fn builder() -> ThetaUnionBuilder {
+ ThetaUnionBuilder::default()
+ }
+
+ /// Update this union with a given sketch.
+ pub fn update<S: ThetaSketchView>(&mut self, sketch: &S) -> Result<(),
Error> {
+ self.raw.update(sketch)
+ }
+
+ /// Return this union as a compact sketch.
+ pub fn to_sketch(&self, ordered: bool) -> CompactThetaSketch {
+ let result = self.raw.result(ordered);
+ CompactThetaSketch::from_parts(
+ result
+ .entries
+ .into_iter()
+ .map(|entry| entry.hash())
+ .collect(),
+ result.theta,
+ result.seed_hash,
+ result.ordered,
+ result.empty,
+ )
+ }
+
+ /// Reset the union to empty state.
+ pub fn reset(&mut self) {
+ self.raw.reset();
+ }
+}
+
+/// Builder for [`ThetaUnion`].
+#[derive(Debug, Clone)]
+pub struct ThetaUnionBuilder {
+ lg_k: u8,
+ resize_factor: ResizeFactor,
+ sampling_probability: f32,
+ seed: u64,
+}
+
+impl Default for ThetaUnionBuilder {
+ fn default() -> Self {
+ Self {
+ lg_k: DEFAULT_LG_K,
+ resize_factor: ResizeFactor::X8,
+ sampling_probability: 1.0,
+ seed: DEFAULT_UPDATE_SEED,
+ }
+ }
+}
+
+impl ThetaUnionBuilder {
+ /// Set lg_k (log2 of nominal size k).
+ ///
+ /// # Panics
+ ///
+ /// If lg_k is not in range [5, 26]
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::theta::ThetaUnion;
+ /// let _union = ThetaUnion::builder().lg_k(12).build();
+ /// ```
+ pub fn lg_k(mut self, lg_k: u8) -> Self {
+ assert!(
+ (MIN_LG_K..=MAX_LG_K).contains(&lg_k),
+ "lg_k must be in [{MIN_LG_K}, {MAX_LG_K}], got {lg_k}"
+ );
+ self.lg_k = lg_k;
+ self
+ }
+
+ /// Set resize factor.
+ pub fn resize_factor(mut self, resize_factor: ResizeFactor) -> Self {
+ self.resize_factor = resize_factor;
+ self
+ }
+
+ /// Set sampling probability p.
+ ///
+ /// # Panics
+ ///
+ /// Panics if p is not in range `(0.0, 1.0]`
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::theta::ThetaUnion;
+ /// let _union = ThetaUnion::builder().sampling_probability(0.5).build();
+ /// ```
+ pub fn sampling_probability(mut self, p: f32) -> Self {
+ assert!(
+ (0.0..=1.0).contains(&p) && p > 0.0,
+ "sampling_probability must be in (0.0, 1.0], got {p}"
+ );
+ self.sampling_probability = p;
+ self
+ }
+
+ /// Set hash seed.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::theta::ThetaUnion;
+ /// let _union = ThetaUnion::builder().seed(7).build();
+ /// ```
+ pub fn seed(mut self, seed: u64) -> Self {
+ self.seed = seed;
+ self
+ }
+
+ /// Build the ThetaUnion.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use datasketches::theta::ThetaUnion;
+ /// let _union = ThetaUnion::builder().lg_k(10).build();
+ /// ```
+ pub fn build(self) -> ThetaUnion {
+ ThetaUnion {
+ raw: RawThetaUnion::new(
+ self.lg_k,
+ self.resize_factor,
+ self.sampling_probability,
+ self.seed,
+ NoopUnionPolicy,
+ ),
+ }
+ }
+}
diff --git a/datasketches/src/common/binomial_bounds.rs
b/datasketches/src/thetacommon/binomial_bounds.rs
similarity index 100%
rename from datasketches/src/common/binomial_bounds.rs
rename to datasketches/src/thetacommon/binomial_bounds.rs
diff --git a/datasketches/src/common/mod.rs
b/datasketches/src/thetacommon/constants.rs
similarity index 57%
copy from datasketches/src/common/mod.rs
copy to datasketches/src/thetacommon/constants.rs
index 95d2b2d..c0c7bb2 100644
--- a/datasketches/src/common/mod.rs
+++ b/datasketches/src/thetacommon/constants.rs
@@ -15,14 +15,22 @@
// specific language governing permissions and limitations
// under the License.
-//! Data structures and functions that may be used across all the sketch
families.
+/// Maximum theta value.
+///
+/// The value is `i64::MAX` to be compatible with datasketches-java.
+pub const MAX_THETA: u64 = i64::MAX as u64;
-mod num_std_dev;
-mod resize;
-pub use self::num_std_dev::NumStdDev;
-pub use self::resize::ResizeFactor;
+/// Minimum log2 of K.
+pub const MIN_LG_K: u8 = 5;
+/// Maximum log2 of K.
+pub const MAX_LG_K: u8 = 26;
+/// Default log2 of K.
+pub const DEFAULT_LG_K: u8 = 12;
-#[cfg(feature = "theta")]
-pub(crate) mod binomial_bounds;
-#[cfg(any(feature = "cpc", feature = "hll"))]
-pub(crate) mod inv_pow2_table;
+/// Resize threshold (0.5 = 50% load factor).
+pub const HASH_TABLE_RESIZE_THRESHOLD: f64 = 0.5;
+/// Rebuild threshold (15/16 = 93.75% load factor).
+pub const HASH_TABLE_REBUILD_THRESHOLD: f64 = 15.0 / 16.0;
+
+pub const STRIDE_HASH_BITS: u8 = 7;
+pub const STRIDE_MASK: u64 = (1 << STRIDE_HASH_BITS) - 1;
diff --git a/datasketches/src/theta/raw_hash_table.rs
b/datasketches/src/thetacommon/hash_table.rs
similarity index 85%
rename from datasketches/src/theta/raw_hash_table.rs
rename to datasketches/src/thetacommon/hash_table.rs
index f171a36..91c43fc 100644
--- a/datasketches/src/theta/raw_hash_table.rs
+++ b/datasketches/src/thetacommon/hash_table.rs
@@ -20,28 +20,25 @@ use std::hash::Hash;
use crate::common::ResizeFactor;
use crate::hash::MurmurHash3X64128;
use crate::hash::compute_seed_hash;
-use crate::theta::HASH_TABLE_REBUILD_THRESHOLD;
-use crate::theta::HASH_TABLE_RESIZE_THRESHOLD;
-use crate::theta::MAX_THETA;
-use crate::theta::MIN_LG_K;
-use crate::theta::STRIDE_MASK;
-
-pub(crate) trait RawHashTableEntry {
- fn hash(&self) -> u64;
-}
+use crate::thetacommon::RawHashTableEntry;
+use crate::thetacommon::constants::HASH_TABLE_REBUILD_THRESHOLD;
+use crate::thetacommon::constants::HASH_TABLE_RESIZE_THRESHOLD;
+use crate::thetacommon::constants::MAX_THETA;
+use crate::thetacommon::constants::MIN_LG_K;
+use crate::thetacommon::constants::STRIDE_MASK;
/// Generic hash-table mechanics shared by Theta and Tuple sketches.
///
/// The entry type supplies the retained hash and any sketch-specific payload.
The table owns all
/// theta screening, probing, resizing, rebuilding, trimming, and
logical-empty state.
#[derive(Debug)]
-pub(crate) struct RawHashTable<E> {
- pub(crate) lg_cur_size: u8,
- pub(crate) lg_nom_size: u8,
- pub(crate) lg_max_size: u8,
- pub(crate) resize_factor: ResizeFactor,
- pub(crate) sampling_probability: f32,
- pub(crate) hash_seed: u64,
+pub struct RawHashTable<E> {
+ lg_cur_size: u8,
+ lg_nom_size: u8,
+ lg_max_size: u8,
+ resize_factor: ResizeFactor,
+ sampling_probability: f32,
+ hash_seed: u64,
// Logical emptiness of the source set.
//
@@ -49,14 +46,14 @@ pub(crate) struct RawHashTable<E> {
// * `true` if no updates have been attempted.
//
// This can be false even when `num_retained` is 0.
- pub(crate) is_empty: bool,
+ is_empty: bool,
- pub(crate) theta: u64,
+ theta: u64,
- pub(crate) entries: Vec<Option<E>>,
+ entries: Vec<Option<E>>,
// Number of retained non-zero hashes currently stored in `entries`.
- pub(crate) num_retained: usize,
+ num_retained: usize,
}
impl<E> RawHashTable<E>
@@ -64,7 +61,7 @@ where
E: RawHashTableEntry,
{
/// Create a new hash table.
- pub(crate) fn new(
+ pub fn new(
lg_nom_size: u8,
resize_factor: ResizeFactor,
sampling_probability: f32,
@@ -88,7 +85,7 @@ where
/// # Panics
///
/// Panics if `lg_cur_size > lg_nom_size + 1`. (`lg_nom_size + 1 ==
lg_max_size`)
- pub(crate) fn from_raw_parts(
+ pub fn from_raw_parts(
lg_cur_size: u8,
lg_nom_size: u8,
resize_factor: ResizeFactor,
@@ -119,7 +116,7 @@ where
}
/// Hash a value with the table seed and return the hash.
- pub(crate) fn hash<T: Hash>(&self, value: T) -> u64 {
+ pub fn hash<T: Hash>(&self, value: T) -> u64 {
let mut hasher = MurmurHash3X64128::with_seed(self.hash_seed);
value.hash(&mut hasher);
let (h1, _) = hasher.finish128();
@@ -130,7 +127,7 @@ where
///
/// Returns true if a new entry was created, false otherwise (existing
key, declined insertion,
/// or a hash screened out by theta).
- pub(crate) fn upsert_entry<F>(&mut self, hash: u64, f: F) -> bool
+ pub fn upsert_entry<F>(&mut self, hash: u64, f: F) -> bool
where
F: FnOnce(Option<&mut E>) -> Option<E>,
{
@@ -171,7 +168,7 @@ where
}
/// Returns a reference to the entry stored for `hash`, or `None` if the
hash is not retained.
- pub(crate) fn get_entry(&self, hash: u64) -> Option<&E> {
+ pub fn get_entry(&self, hash: u64) -> Option<&E> {
if hash == 0 {
return None;
}
@@ -183,7 +180,7 @@ where
}
/// Get capacity threshold.
- pub(crate) fn get_capacity(&self) -> usize {
+ pub fn get_capacity(&self) -> usize {
let fraction = if self.lg_cur_size <= self.lg_nom_size {
HASH_TABLE_RESIZE_THRESHOLD
} else {
@@ -193,14 +190,14 @@ where
}
/// Trim the table to nominal size k.
- pub(crate) fn trim(&mut self) {
+ pub fn trim(&mut self) {
if self.num_retained > (1 << self.lg_nom_size) {
self.rebuild();
}
}
/// Reset the table to empty state.
- pub(crate) fn reset(&mut self) {
+ pub fn reset(&mut self) {
let init_theta =
starting_theta_from_sampling_probability(self.sampling_probability);
let init_lg_cur = starting_sub_multiple(
self.lg_nom_size + 1,
@@ -218,47 +215,59 @@ where
}
/// Return number of retained entries.
- pub(crate) fn num_retained(&self) -> usize {
+ pub fn num_retained(&self) -> usize {
self.num_retained
}
/// Get theta.
- pub(crate) fn theta(&self) -> u64 {
+ pub fn theta(&self) -> u64 {
self.theta
}
/// Check logical emptiness of the source set.
- pub(crate) fn is_empty(&self) -> bool {
+ pub fn is_empty(&self) -> bool {
self.is_empty
}
/// Get iterator over retained entries.
- pub(crate) fn iter_entries(&self) -> impl Iterator<Item = &E> + '_ {
+ pub fn iter_entries(&self) -> impl Iterator<Item = &E> + '_ {
self.entries.iter().filter_map(Option::as_ref)
}
+ /// Return number of all entries.
+ #[cfg(test)]
+ pub fn num_entries(&self) -> usize {
+ self.entries.len()
+ }
+
+ /// Get log2 of current size.
+ #[cfg(test)]
+ pub fn lg_cur_size(&self) -> u8 {
+ self.lg_cur_size
+ }
+
/// Get log2 of nominal size.
- pub(crate) fn lg_nom_size(&self) -> u8 {
+ pub fn lg_nom_size(&self) -> u8 {
self.lg_nom_size
}
/// Get the hash of the seed that was used to hash the input.
- pub(crate) fn seed_hash(&self) -> u16 {
+ pub fn seed_hash(&self) -> u16 {
compute_seed_hash(self.hash_seed)
}
/// Set empty flag.
- pub(crate) fn set_empty(&mut self, is_empty: bool) {
+ pub fn set_empty(&mut self, is_empty: bool) {
self.is_empty = is_empty;
}
/// Get the hash seed used by this table.
- pub(crate) fn hash_seed(&self) -> u64 {
+ pub fn hash_seed(&self) -> u64 {
self.hash_seed
}
/// Sets theta value.
- pub(crate) fn set_theta(&mut self, theta: u64) {
+ pub fn set_theta(&mut self, theta: u64) {
assert!(
(1..=MAX_THETA).contains(&theta),
"theta must be in [1, {MAX_THETA}], got {theta}"
@@ -267,7 +276,7 @@ where
}
/// Returns minimal lg_size where rebuild-capacity can hold `count`.
- pub(crate) fn lg_size_from_count_for_rebuild(count: usize, load_factor:
f64) -> u8 {
+ pub fn lg_size_from_count_for_rebuild(count: usize, load_factor: f64) ->
u8 {
let log2 = |n: usize| {
if n == 0 { 0_u8 } else { n.ilog2() as u8 }
};
@@ -281,8 +290,8 @@ where
}
/// Returns the estimated size of the heap allocations in bytes.
- pub(crate) fn estimated_size(&self) -> usize {
- self.entries.capacity() * std::mem::size_of::<Option<E>>()
+ pub fn estimated_size(&self) -> usize {
+ self.entries.capacity() * size_of::<Option<E>>()
}
fn find_in_curr_entries(&self, key: u64) -> Option<usize> {
@@ -380,7 +389,7 @@ where
/// Compute initial lg_size for hash table based on target lg_size, minimum
lg_size, and resize
/// factor. Make sure `lg_target = lg_init + n * lg_resize_factor`, where `n`
is an integer and
/// `lg_init >= lg_min`.
-pub(crate) fn starting_sub_multiple(lg_target: u8, lg_min: u8,
lg_resize_factor: u8) -> u8 {
+pub fn starting_sub_multiple(lg_target: u8, lg_min: u8, lg_resize_factor: u8)
-> u8 {
if lg_target <= lg_min {
lg_min
} else if lg_resize_factor == 0 {
@@ -391,7 +400,7 @@ pub(crate) fn starting_sub_multiple(lg_target: u8, lg_min:
u8, lg_resize_factor:
}
/// Compute initial theta for hash table based on sampling probability.
-pub(crate) fn starting_theta_from_sampling_probability(sampling_probability:
f32) -> u64 {
+pub fn starting_theta_from_sampling_probability(sampling_probability: f32) ->
u64 {
if sampling_probability < 1.0 {
(MAX_THETA as f64 * sampling_probability as f64) as u64
} else {
diff --git a/datasketches/src/thetacommon/mod.rs
b/datasketches/src/thetacommon/mod.rs
new file mode 100644
index 0000000..e0bed52
--- /dev/null
+++ b/datasketches/src/thetacommon/mod.rs
@@ -0,0 +1,53 @@
+// 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.
+
+//! Data structures and functions that may be used across all the Theta sketch
family.
+
+pub(crate) mod binomial_bounds;
+pub(crate) mod constants;
+pub(crate) mod hash_table;
+pub(crate) mod union;
+
+/// An entry retained by a Theta sketch family hash table.
+pub trait RawHashTableEntry {
+ /// Return the hash used as this entry's key.
+ fn hash(&self) -> u64;
+}
+
+/// Read-only input accepted by a raw Theta union.
+///
+/// This trait carries complete retained entries, so tuple unions can use the
same state machine
+/// while merging their per-key summaries.
+pub trait RawThetaSketchView<E: RawHashTableEntry> {
+ /// Return the 16-bit seed hash.
+ fn seed_hash(&self) -> u16;
+
+ /// Return theta as a `u64` threshold.
+ fn theta(&self) -> u64;
+
+ /// Return whether this sketch has not received any updates.
+ fn is_empty(&self) -> bool;
+
+ /// Return whether retained entries are ordered by ascending hash.
+ fn is_ordered(&self) -> bool;
+
+ /// Return an iterator over retained entries.
+ fn iter(&self) -> impl Iterator<Item = E> + '_;
+
+ /// Return the number of retained entries.
+ fn num_retained(&self) -> usize;
+}
diff --git a/datasketches/src/thetacommon/union.rs
b/datasketches/src/thetacommon/union.rs
new file mode 100644
index 0000000..4392d62
--- /dev/null
+++ b/datasketches/src/thetacommon/union.rs
@@ -0,0 +1,248 @@
+// 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 crate::common::ResizeFactor;
+use crate::error::Error;
+use crate::thetacommon::RawHashTableEntry;
+use crate::thetacommon::RawThetaSketchView;
+use crate::thetacommon::constants::MAX_THETA;
+use crate::thetacommon::hash_table::RawHashTable;
+
+/// Merges an incoming entry into an existing entry with the same hash.
+pub trait RawThetaUnionPolicy<E> {
+ fn merge(&self, existing: &mut E, incoming: E);
+}
+
+/// Generic state machine shared by Theta and Tuple unions.
+///
+/// `E` is the retained entry type. Ordinary Theta entries only contain a
hash, while tuple
+/// entries also carry a summary. `P` defines how equal-hash entries are
combined.
+#[derive(Debug)]
+pub struct RawThetaUnion<E, P> {
+ table: RawHashTable<E>,
+ policy: P,
+ union_theta: u64,
+}
+
+/// Raw compact-union state from which a sketch family creates its compact
result type.
+#[derive(Debug)]
+pub struct RawThetaUnionResult<E> {
+ pub entries: Vec<E>,
+ pub theta: u64,
+ pub seed_hash: u16,
+ pub ordered: bool,
+ pub empty: bool,
+}
+
+impl<E, P> RawThetaUnion<E, P>
+where
+ E: RawHashTableEntry,
+{
+ pub fn new(
+ lg_k: u8,
+ resize_factor: ResizeFactor,
+ sampling_probability: f32,
+ seed: u64,
+ policy: P,
+ ) -> Self {
+ let table = RawHashTable::new(lg_k, resize_factor,
sampling_probability, seed);
+ Self {
+ union_theta: table.theta(),
+ table,
+ policy,
+ }
+ }
+
+ /// Incorporate a sketch into the union.
+ pub fn update<S>(&mut self, sketch: &S) -> Result<(), Error>
+ where
+ S: RawThetaSketchView<E>,
+ P: RawThetaUnionPolicy<E>,
+ {
+ if sketch.is_empty() {
+ return Ok(());
+ }
+
+ if self.table.seed_hash() != sketch.seed_hash() {
+ return Err(Error::invalid_argument(format!(
+ "incompatible seed hash: expected {}, got {}",
+ self.table.seed_hash(),
+ sketch.seed_hash(),
+ )));
+ }
+
+ self.table.set_empty(false);
+ self.union_theta = self.union_theta.min(sketch.theta());
+
+ for entry in sketch.iter() {
+ let hash = entry.hash();
+ if hash < self.union_theta && hash < self.table.theta() {
+ self.table.upsert_entry(hash, |existing| match existing {
+ Some(existing) => {
+ self.policy.merge(existing, entry);
+ None
+ }
+ None => Some(entry),
+ });
+ } else if sketch.is_ordered() {
+ break;
+ }
+ }
+ self.union_theta = self.union_theta.min(self.table.theta());
+
+ Ok(())
+ }
+
+ /// Return the current compact-union state.
+ pub fn result(&self, ordered: bool) -> RawThetaUnionResult<E>
+ where
+ E: Clone,
+ {
+ if self.table.is_empty() {
+ return RawThetaUnionResult {
+ entries: Vec::new(),
+ theta: self.union_theta,
+ seed_hash: self.table.seed_hash(),
+ ordered: true,
+ empty: true,
+ };
+ }
+
+ let mut theta = self.union_theta.min(self.table.theta());
+ let mut entries = if self.union_theta >= self.table.theta() {
+ self.table.iter_entries().cloned().collect::<Vec<_>>()
+ } else {
+ self.table
+ .iter_entries()
+ .filter(|entry| entry.hash() < theta)
+ .cloned()
+ .collect::<Vec<_>>()
+ };
+
+ let nominal_num = 1usize << self.table.lg_nom_size();
+ if entries.len() > nominal_num {
+ let (_, kth, _) = entries.select_nth_unstable_by_key(nominal_num,
|entry| entry.hash());
+ theta = kth.hash();
+ entries.truncate(nominal_num);
+ }
+
+ let ordered = ordered || (entries.len() == 1 && theta == MAX_THETA);
+ if ordered {
+ entries.sort_unstable_by_key(RawHashTableEntry::hash);
+ }
+
+ RawThetaUnionResult {
+ entries,
+ theta,
+ seed_hash: self.table.seed_hash(),
+ ordered,
+ empty: false,
+ }
+ }
+
+ /// Reset the union to its initial state.
+ pub fn reset(&mut self) {
+ self.table.reset();
+ self.union_theta = self.table.theta();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::hash::DEFAULT_UPDATE_SEED;
+
+ #[derive(Clone, Debug, Eq, PartialEq)]
+ struct TestEntry {
+ hash: u64,
+ summary: u64,
+ }
+
+ impl RawHashTableEntry for TestEntry {
+ fn hash(&self) -> u64 {
+ self.hash
+ }
+ }
+
+ struct TestSketch {
+ entries: Vec<TestEntry>,
+ }
+
+ impl RawThetaSketchView<TestEntry> for TestSketch {
+ fn seed_hash(&self) -> u16 {
+ crate::hash::compute_seed_hash(DEFAULT_UPDATE_SEED)
+ }
+
+ fn theta(&self) -> u64 {
+ MAX_THETA
+ }
+
+ fn is_empty(&self) -> bool {
+ false
+ }
+
+ fn is_ordered(&self) -> bool {
+ false
+ }
+
+ fn iter(&self) -> impl Iterator<Item = TestEntry> + '_ {
+ self.entries.iter().cloned()
+ }
+
+ fn num_retained(&self) -> usize {
+ self.entries.len()
+ }
+ }
+
+ struct SumPolicy;
+
+ impl RawThetaUnionPolicy<TestEntry> for SumPolicy {
+ fn merge(&self, existing: &mut TestEntry, incoming: TestEntry) {
+ existing.summary += incoming.summary;
+ }
+ }
+
+ #[test]
+ fn merges_equal_hash_entries_with_policy() {
+ let mut union =
+ RawThetaUnion::new(5, ResizeFactor::X1, 1.0, DEFAULT_UPDATE_SEED,
SumPolicy);
+ union
+ .update(&TestSketch {
+ entries: vec![TestEntry {
+ hash: 1,
+ summary: 2,
+ }],
+ })
+ .unwrap();
+ union
+ .update(&TestSketch {
+ entries: vec![TestEntry {
+ hash: 1,
+ summary: 3,
+ }],
+ })
+ .unwrap();
+
+ assert_eq!(
+ union.result(true).entries,
+ vec![TestEntry {
+ hash: 1,
+ summary: 5,
+ }]
+ );
+ }
+}
diff --git a/datasketches/tests/theta_intersection_test.rs
b/datasketches/tests/theta_intersection_test.rs
index 9b98062..bb662b6 100644
--- a/datasketches/tests/theta_intersection_test.rs
+++ b/datasketches/tests/theta_intersection_test.rs
@@ -38,14 +38,14 @@ fn test_has_result_state_machine() {
assert!(!i.has_result());
i.update(&a).unwrap();
assert!(i.has_result());
- assert!(i.result().estimate() >= 1.0);
+ assert!(i.to_sketch(true).estimate() >= 1.0);
}
#[test]
fn test_result_before_update_panics() {
let i = ThetaIntersection::new(123);
let result = std::panic::catch_unwind(|| {
- let _ = i.result();
+ let _ = i.to_sketch(true);
});
assert!(result.is_err());
}
@@ -64,7 +64,7 @@ fn test_update_accepts_compact_sketch() {
i.update(&a.compact(true)).unwrap();
i.update(&b).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(r.estimate() == 1.0);
assert!(r.is_ordered());
@@ -75,7 +75,7 @@ fn test_update_accepts_compact_sketch() {
i.update(&c.compact(false)).unwrap();
- let r = i.result_with_ordered(false);
+ let r = i.to_sketch(false);
assert!(r.estimate() == 0.0);
assert!(!r.is_ordered());
}
@@ -87,7 +87,7 @@ fn test_seed_mismatch_behaviour_for_empty_sketch() {
i.update(&empty_other_seed).unwrap();
assert!(i.has_result());
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(r.is_empty());
}
@@ -111,12 +111,12 @@ fn test_terminal_empty_state_ignores_future_updates() {
i.update(&empty).unwrap();
i.update(&non_empty).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(r.is_empty());
}
#[test]
-fn test_result_with_ordered_false_is_not_ordered() {
+fn test_to_sketch_unordered_is_not_ordered() {
let mut a = ThetaSketch::builder().build();
for i in 0..64 {
a.update(i);
@@ -124,7 +124,7 @@ fn test_result_with_ordered_false_is_not_ordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&a).unwrap();
- let r = i.result_with_ordered(false);
+ let r = i.to_sketch(false);
assert!(!r.is_ordered());
}
@@ -134,14 +134,14 @@ fn test_empty_update_twice() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&empty).unwrap();
- let r1 = i.result();
+ let r1 = i.to_sketch(true);
assert_eq!(r1.num_retained(), 0);
assert!(r1.is_empty());
assert!(!r1.is_estimation_mode());
assert_eq!(r1.estimate(), 0.0);
i.update(&empty).unwrap();
- let r2 = i.result();
+ let r2 = i.to_sketch(true);
assert_eq!(r2.num_retained(), 0);
assert!(r2.is_empty());
assert!(!r2.is_estimation_mode());
@@ -155,7 +155,7 @@ fn test_non_empty_no_retained_keys() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s).unwrap();
- let r1 = i.result();
+ let r1 = i.to_sketch(true);
assert_eq!(r1.num_retained(), 0);
assert!(!r1.is_empty());
assert!(r1.is_estimation_mode());
@@ -163,7 +163,7 @@ fn test_non_empty_no_retained_keys() {
assert_eq!(r1.estimate(), 0.0);
i.update(&s).unwrap();
- let r2 = i.result();
+ let r2 = i.to_sketch(true);
assert_eq!(r2.num_retained(), 0);
assert!(!r2.is_empty());
assert!(r2.is_estimation_mode());
@@ -179,7 +179,7 @@ fn test_exact_half_overlap_unordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1).unwrap();
i.update(&s2).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(!r.is_estimation_mode());
@@ -194,7 +194,7 @@ fn test_exact_half_overlap_ordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1.compact(true)).unwrap();
i.update(&s2.compact(true)).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(!r.is_estimation_mode());
@@ -209,7 +209,7 @@ fn test_exact_disjoint_unordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1).unwrap();
i.update(&s2).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(r.is_empty());
assert!(!r.is_estimation_mode());
@@ -224,7 +224,7 @@ fn test_exact_disjoint_ordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1.compact(true)).unwrap();
i.update(&s2.compact(true)).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(r.is_empty());
assert!(!r.is_estimation_mode());
@@ -239,7 +239,7 @@ fn test_estimation_half_overlap_unordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1).unwrap();
i.update(&s2).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(r.is_estimation_mode());
@@ -254,7 +254,7 @@ fn test_estimation_half_overlap_ordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1.compact(true)).unwrap();
i.update(&s2.compact(true)).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(r.is_estimation_mode());
@@ -271,7 +271,7 @@ fn
test_estimation_half_overlap_ordered_deserialized_compact() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&c1).unwrap();
i.update(&c2).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(r.is_estimation_mode());
@@ -286,7 +286,7 @@ fn test_estimation_disjoint_unordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1).unwrap();
i.update(&s2).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(r.is_estimation_mode());
@@ -301,7 +301,7 @@ fn test_estimation_disjoint_ordered() {
let mut i = ThetaIntersection::new_with_default_seed();
i.update(&s1.compact(true)).unwrap();
i.update(&s2.compact(true)).unwrap();
- let r = i.result();
+ let r = i.to_sketch(true);
assert!(!r.is_empty());
assert!(r.is_estimation_mode());
diff --git a/datasketches/tests/theta_union_test.rs
b/datasketches/tests/theta_union_test.rs
new file mode 100644
index 0000000..e6e9160
--- /dev/null
+++ b/datasketches/tests/theta_union_test.rs
@@ -0,0 +1,688 @@
+// 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.
+
+#![cfg(feature = "theta")]
+
+use datasketches::theta::CompactThetaSketch;
+use datasketches::theta::ThetaSketch;
+use datasketches::theta::ThetaUnion;
+
+fn sketch_with_range(lg_k: u8, start: i64, count: i64) -> ThetaSketch {
+ let mut sketch = ThetaSketch::builder().lg_k(lg_k).build();
+ for value in start..start + count {
+ sketch.update(value);
+ }
+ sketch
+}
+
+fn assert_estimate_close(sketch: &CompactThetaSketch, expected: f64,
tolerance: f64) {
+ assert!(
+ (sketch.estimate() - expected).abs() <= tolerance,
+ "estimate={}, expected={}, tolerance={}, theta={}, retained={}",
+ sketch.estimate(),
+ expected,
+ tolerance,
+ sketch.theta(),
+ sketch.num_retained()
+ );
+}
+
+#[test]
+fn test_empty_union() {
+ let sketch = ThetaSketch::builder().build();
+ let mut union = ThetaUnion::builder().build();
+ let result = union.to_sketch(true);
+ assert_eq!(result.num_retained(), 0);
+ assert!(result.is_empty());
+ assert!(!result.is_estimation_mode());
+
+ union.update(&sketch).unwrap();
+ let result = union.to_sketch(true);
+ assert_eq!(result.num_retained(), 0);
+ assert!(result.is_empty());
+ assert!(!result.is_estimation_mode());
+}
+
+#[test]
+fn test_non_empty_no_retained_keys() {
+ let mut sketch =
ThetaSketch::builder().sampling_probability(0.001).build();
+ sketch.update(1u64);
+
+ let mut union = ThetaUnion::builder().build();
+ union.update(&sketch).unwrap();
+ let result = union.to_sketch(true);
+ assert_eq!(result.num_retained(), 0);
+ assert!(!result.is_empty());
+ assert!(result.is_estimation_mode());
+ assert!((result.theta() - 0.001).abs() < 1e-10);
+}
+
+#[test]
+fn test_exact_mode_half_overlap() {
+ let mut sketch1 = ThetaSketch::builder().build();
+ for value in 0i64..1000i64 {
+ sketch1.update(value);
+ }
+
+ let mut sketch2 = ThetaSketch::builder().build();
+ for value in 500i64..1500i64 {
+ sketch2.update(value);
+ }
+
+ let mut union = ThetaUnion::builder().build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+ let result = union.to_sketch(true);
+ assert!(!result.is_empty());
+ assert!(!result.is_estimation_mode());
+ assert_eq!(result.estimate(), 1500.0);
+
+ union.reset();
+ let reset = union.to_sketch(true);
+ assert_eq!(reset.num_retained(), 0);
+ assert!(reset.is_empty());
+ assert!(!reset.is_estimation_mode());
+}
+
+#[test]
+fn test_exact_mode_half_overlap_compact() {
+ let mut sketch1 = ThetaSketch::builder().build();
+ for value in 0i64..1000i64 {
+ sketch1.update(value);
+ }
+ let compact1 =
CompactThetaSketch::deserialize(&sketch1.compact(true).serialize()).unwrap();
+
+ let mut sketch2 = ThetaSketch::builder().build();
+ for value in 500i64..1500i64 {
+ sketch2.update(value);
+ }
+ let compact2 =
CompactThetaSketch::deserialize(&sketch2.compact(true).serialize()).unwrap();
+
+ let mut union = ThetaUnion::builder().build();
+ union.update(&compact1).unwrap();
+ union.update(&compact2).unwrap();
+ let result = union.to_sketch(true);
+ assert!(!result.is_empty());
+ assert!(!result.is_estimation_mode());
+ assert_eq!(result.estimate(), 1500.0);
+}
+
+#[test]
+fn test_estimation_mode_half_overlap() {
+ let mut sketch1 = ThetaSketch::builder().build();
+ for value in 0i64..10000i64 {
+ sketch1.update(value);
+ }
+
+ let mut sketch2 = ThetaSketch::builder().build();
+ for value in 5000i64..15000i64 {
+ sketch2.update(value);
+ }
+
+ let mut union = ThetaUnion::builder().build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+ let result = union.to_sketch(true);
+ assert!(!result.is_empty());
+ assert!(result.is_estimation_mode());
+ assert!(
+ (result.estimate() - 15000.0).abs() <= 15000.0 * 0.01,
+ "estimate={}, theta={}, retained={}",
+ result.estimate(),
+ result.theta(),
+ result.num_retained()
+ );
+}
+
+#[test]
+fn test_seed_mismatch() {
+ let mut sketch = ThetaSketch::builder().build();
+ sketch.update(1u64);
+
+ let mut union = ThetaUnion::builder().seed(123).build();
+ assert!(union.update(&sketch).is_err());
+}
+
+#[test]
+fn test_larger_k() {
+ let mut sketch1 = ThetaSketch::builder().lg_k(14).build();
+ for value in 0i64..16384i64 {
+ sketch1.update(value);
+ }
+
+ let mut sketch2 = ThetaSketch::builder().lg_k(14).build();
+ for value in 0i64..26384i64 {
+ sketch2.update(value);
+ }
+
+ let mut sketch3 = ThetaSketch::builder().lg_k(14).build();
+ for value in 0i64..86384i64 {
+ sketch3.update(value);
+ }
+
+ let mut union1 = ThetaUnion::builder().lg_k(16).build();
+ union1.update(&sketch2).unwrap();
+ union1.update(&sketch1).unwrap();
+ union1.update(&sketch3).unwrap();
+ let result1 = union1.to_sketch(true);
+ assert_eq!(result1.estimate(), sketch3.estimate());
+
+ let mut union2 = ThetaUnion::builder().lg_k(16).build();
+ union2.update(&sketch1).unwrap();
+ union2.update(&sketch3).unwrap();
+ union2.update(&sketch2).unwrap();
+ let result2 = union2.to_sketch(true);
+ assert_eq!(result2.estimate(), sketch3.estimate());
+}
+
+#[test]
+fn test_exact_union_no_overlap() {
+ let lg_k = 9;
+ let k = 1i64 << lg_k;
+ let sketch1 = sketch_with_range(lg_k, 0, k / 2);
+ let sketch2 = sketch_with_range(lg_k, k / 2, k / 2);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+
+ let result = union.to_sketch(true);
+ assert!(!result.is_empty());
+ assert!(!result.is_estimation_mode());
+ assert_eq!(result.estimate(), k as f64);
+}
+
+#[test]
+fn test_estimation_union_no_overlap() {
+ let lg_k = 12;
+ let k = 1i64 << lg_k;
+ let sketch1 = sketch_with_range(lg_k, 0, 2 * k);
+ let sketch2 = sketch_with_range(lg_k, 2 * k, 2 * k);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+
+ assert_estimate_close(
+ &union.to_sketch(true),
+ (4 * k) as f64,
+ 0.05 * (4 * k) as f64,
+ );
+}
+
+#[test]
+fn test_exact_union_with_overlap() {
+ let lg_k = 9;
+ let k = 1i64 << lg_k;
+ let sketch1 = sketch_with_range(lg_k, 0, k / 2);
+ let sketch2 = sketch_with_range(lg_k, 0, k);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+
+ let result = union.to_sketch(true);
+ assert!(!result.is_empty());
+ assert!(!result.is_estimation_mode());
+ assert_eq!(result.estimate(), k as f64);
+}
+
+#[test]
+fn test_ordered_and_unordered_compact_inputs() {
+ let lg_k = 12;
+ let k = 1i64 << lg_k;
+ let sketch1 = sketch_with_range(lg_k, 0, 2 * k);
+ let sketch2 = sketch_with_range(lg_k + 1, 2 * k, 2 * k);
+ let compact_ordered = sketch2.compact(true);
+ let compact_unordered = sketch2.compact(false);
+
+ let mut ordered_union = ThetaUnion::builder().lg_k(lg_k).build();
+ ordered_union.update(&sketch1).unwrap();
+ ordered_union.update(&compact_ordered).unwrap();
+
+ let mut unordered_union = ThetaUnion::builder().lg_k(lg_k).build();
+ unordered_union.update(&sketch1).unwrap();
+ unordered_union.update(&compact_unordered).unwrap();
+
+ assert_eq!(
+ ordered_union.to_sketch(true).estimate(),
+ unordered_union.to_sketch(true).estimate()
+ );
+ assert_estimate_close(
+ &ordered_union.to_sketch(true),
+ (4 * k) as f64,
+ 0.05 * (4 * k) as f64,
+ );
+}
+
+#[test]
+fn test_result_ordering_forms_have_same_estimate() {
+ let sketch1 = sketch_with_range(12, 0, 8192);
+ let sketch2 = sketch_with_range(12, 8192, 1024);
+
+ let mut union = ThetaUnion::builder().lg_k(12).build();
+ union.update(&sketch1).unwrap();
+ union.update(&sketch2).unwrap();
+
+ let unordered = union.to_sketch(false);
+ let ordered = union.to_sketch(true);
+
+ assert!(!unordered.is_ordered());
+ assert!(ordered.is_ordered());
+ assert_eq!(unordered.estimate(), ordered.estimate());
+}
+
+#[test]
+fn test_multi_union() {
+ let lg_k = 13;
+ let ranges = [
+ (0, 100_000),
+ (100_000, 26_797),
+ (126_797, 26_797),
+ (153_594, 26_797),
+ ];
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+
+ for (start, count) in ranges {
+ let sketch = sketch_with_range(lg_k, start, count);
+ union.update(&sketch).unwrap();
+ }
+
+ assert_estimate_close(&union.to_sketch(true), 180_391.0, 180_391.0 * 0.02);
+}
+
+#[test]
+fn test_result_does_not_reset_union() {
+ let lg_k = 9;
+ let k = 1i64 << lg_k;
+ let compact1 = sketch_with_range(lg_k, 0, k).compact(true);
+ let compact2 = sketch_with_range(lg_k, k, k).compact(true);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&compact1).unwrap();
+ union.update(&compact2).unwrap();
+ let first = union.to_sketch(true);
+ let second = union.to_sketch(true);
+
+ assert_eq!(first.estimate(), second.estimate());
+ assert!(!second.is_empty());
+}
+
+#[test]
+fn test_union_full_overlap() {
+ let lg_k = 9;
+ let k = 1i64 << lg_k;
+ let compact1 = sketch_with_range(lg_k, 0, k).compact(true);
+ let compact2 = sketch_with_range(lg_k, 0, k).compact(true);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&compact1).unwrap();
+ union.update(&compact2).unwrap();
+ let result = union.to_sketch(true);
+
+ assert_eq!(result.estimate(), k as f64);
+}
+
+#[test]
+fn test_ordered_input_early_stop_matches_unordered_input() {
+ let lg_k = 10;
+ let k = 1i64 << lg_k;
+ let mut value = 0i64;
+
+ for _ in 0..10 {
+ let sketch1 = sketch_with_range(lg_k, value, 4 * k);
+ let sketch2 = sketch_with_range(lg_k, value + 2 * k, 4 * k);
+ value += 6 * k;
+ let ordered1 = sketch1.compact(true);
+ let ordered2 = sketch2.compact(true);
+ let unordered1 = sketch1.compact(false);
+ let unordered2 = sketch2.compact(false);
+
+ let mut ordered_union = ThetaUnion::builder().lg_k(lg_k + 1).build();
+ ordered_union.update(&ordered1).unwrap();
+ ordered_union.update(&ordered2).unwrap();
+
+ let mut unordered_union = ThetaUnion::builder().lg_k(lg_k + 1).build();
+ unordered_union.update(&unordered1).unwrap();
+ unordered_union.update(&unordered2).unwrap();
+
+ assert_eq!(
+ ordered_union.to_sketch(true).estimate(),
+ unordered_union.to_sketch(true).estimate()
+ );
+ }
+}
+
+#[test]
+fn test_union_cutback_to_k() {
+ let lg_k = 10;
+ let k = 1i64 << lg_k;
+ let compact1 = sketch_with_range(lg_k, 0, 3 * k).compact(true);
+ let compact2 = sketch_with_range(lg_k, 6 * k, 3 * k).compact(true);
+
+ let mut union = ThetaUnion::builder().lg_k(lg_k).build();
+ union.update(&compact1).unwrap();
+ union.update(&compact2).unwrap();
+ let result = union.to_sketch(true);
+
+ assert_estimate_close(&result, (6 * k) as f64, (6 * k) as f64 * 0.06);
+ assert!(result.num_retained() <= k as usize);
+}
+
+#[test]
+fn test_union_empty_valid_rules() {
+ let empty1 = ThetaSketch::builder().build().compact(true);
+ let empty2 = ThetaSketch::builder().build().compact(true);
+ let mut one = ThetaSketch::builder().build();
+ one.update(1i64);
+ let one = one.compact(true);
+
+ let mut empty_union = ThetaUnion::builder().lg_k(5).build();
+ empty_union.update(&empty1).unwrap();
+ empty_union.update(&empty2).unwrap();
+ assert!(empty_union.to_sketch(true).is_empty());
+
+ let mut left_non_empty_union = ThetaUnion::builder().lg_k(5).build();
+ left_non_empty_union.update(&one).unwrap();
+ left_non_empty_union.update(&empty2).unwrap();
+ assert!(!left_non_empty_union.to_sketch(true).is_empty());
+
+ let mut right_non_empty_union = ThetaUnion::builder().lg_k(5).build();
+ right_non_empty_union.update(&empty1).unwrap();
+ right_non_empty_union.update(&one).unwrap();
+ assert!(!right_non_empty_union.to_sketch(true).is_empty());
+}
+
+#[test]
+fn test_trim_to_k() {
+ let hi_sketch = sketch_with_range(10, 0, 3749);
+ let lo_sketch = sketch_with_range(9, 10_000, 1783);
+
+ let mut union = ThetaUnion::builder().lg_k(10).build();
+ union.update(&hi_sketch).unwrap();
+ union.update(&lo_sketch).unwrap();
+ let result = union.to_sketch(true);
+
+ assert_eq!(result.num_retained(), 1024);
+}
+
+#[test]
+fn test_builder_lg_k() {
+ let sketch = sketch_with_range(10, 0, 1000);
+ let mut union = ThetaUnion::builder().lg_k(10).build();
+ union.update(&sketch).unwrap();
+
+ assert_eq!(union.to_sketch(true).estimate(), 1000.0);
+}
+
+#[derive(Clone, Copy, Debug)]
+enum CornerSketchState {
+ Empty,
+ Exact,
+ Estimation,
+ Degenerate,
+}
+
+fn corner_sketch(state: CornerSketchState, p: f32, value: i64) -> ThetaSketch {
+ let builder = ThetaSketch::builder().lg_k(5);
+ let mut sketch = match state {
+ CornerSketchState::Empty | CornerSketchState::Exact => builder.build(),
+ CornerSketchState::Estimation | CornerSketchState::Degenerate => {
+ builder.sampling_probability(p).build()
+ }
+ };
+ if !matches!(state, CornerSketchState::Empty) {
+ sketch.update(value);
+ }
+ sketch
+}
+
+#[test]
+fn test_corner_case_union_states() {
+ const GT_MIDP_VALUE: i64 = 3;
+ const MIDP: f32 = 0.5;
+ const GT_LOWP_VALUE: i64 = 6;
+ const LOWP: f32 = 0.1;
+ const LT_LOWP_VALUE: i64 = 4;
+
+ let cases = [
+ (
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ 1.0,
+ 0,
+ true,
+ ),
+ (
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ CornerSketchState::Exact,
+ 1.0,
+ GT_MIDP_VALUE,
+ 1.0,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ LOWP as f64,
+ 0,
+ false,
+ ),
+ (
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Exact,
+ 1.0,
+ GT_MIDP_VALUE,
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ 1.0,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Exact,
+ 1.0,
+ GT_MIDP_VALUE,
+ CornerSketchState::Exact,
+ 1.0,
+ GT_MIDP_VALUE,
+ 1.0,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Exact,
+ 1.0,
+ LT_LOWP_VALUE,
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Exact,
+ 1.0,
+ LT_LOWP_VALUE,
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ CornerSketchState::Exact,
+ 1.0,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Estimation,
+ MIDP,
+ LT_LOWP_VALUE,
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Estimation,
+ MIDP,
+ LT_LOWP_VALUE,
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ CornerSketchState::Empty,
+ 1.0,
+ 0,
+ LOWP as f64,
+ 0,
+ false,
+ ),
+ (
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ CornerSketchState::Exact,
+ 1.0,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ (
+ CornerSketchState::Degenerate,
+ MIDP,
+ GT_MIDP_VALUE,
+ CornerSketchState::Degenerate,
+ LOWP,
+ GT_LOWP_VALUE,
+ LOWP as f64,
+ 0,
+ false,
+ ),
+ (
+ CornerSketchState::Degenerate,
+ MIDP,
+ GT_MIDP_VALUE,
+ CornerSketchState::Estimation,
+ LOWP,
+ LT_LOWP_VALUE,
+ LOWP as f64,
+ 1,
+ false,
+ ),
+ ];
+
+ for (
+ state_a,
+ p_a,
+ value_a,
+ state_b,
+ p_b,
+ value_b,
+ expected_theta,
+ expected_count,
+ expected_empty,
+ ) in cases
+ {
+ let sketch_a = corner_sketch(state_a, p_a, value_a);
+ let sketch_b = corner_sketch(state_b, p_b, value_b);
+
+ let mut union = ThetaUnion::builder().build();
+ union.update(&sketch_a).unwrap();
+ union.update(&sketch_b).unwrap();
+ let result = union.to_sketch(true);
+
+ assert!(
+ (result.theta() - expected_theta).abs() < 1e-6,
+ "state_a={state_a:?}, state_b={state_b:?}, theta={}",
+ result.theta()
+ );
+ assert_eq!(
+ result.num_retained(),
+ expected_count,
+ "state_a={state_a:?}, state_b={state_b:?}"
+ );
+ assert_eq!(
+ result.is_empty(),
+ expected_empty,
+ "state_a={state_a:?}, state_b={state_b:?}"
+ );
+
+ let compact_a = sketch_a.compact(true);
+ let compact_b = sketch_b.compact(true);
+ let mut union = ThetaUnion::builder().build();
+ union.update(&compact_a).unwrap();
+ union.update(&compact_b).unwrap();
+ let compact_result = union.to_sketch(true);
+
+ assert!((compact_result.theta() - expected_theta).abs() < 1e-6);
+ assert_eq!(compact_result.num_retained(), expected_count);
+ assert_eq!(compact_result.is_empty(), expected_empty);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]