From 373d3d7af435379bb8903a8273c23a25b69ed1af Mon Sep 17 00:00:00 2001 From: Hawkingrei Date: Thu, 2 Jul 2026 15:07:42 +0800 Subject: [PATCH 1/6] feat(theta): add jaccard similarity --- datasketches/src/theta/jaccard_similarity.rs | 323 ++++++++++++++++++ datasketches/src/theta/mod.rs | 3 + .../tests/theta_jaccard_similarity_test.rs | 147 ++++++++ 3 files changed, 473 insertions(+) create mode 100644 datasketches/src/theta/jaccard_similarity.rs create mode 100644 datasketches/tests/theta_jaccard_similarity_test.rs diff --git a/datasketches/src/theta/jaccard_similarity.rs b/datasketches/src/theta/jaccard_similarity.rs new file mode 100644 index 0000000..090ba28 --- /dev/null +++ b/datasketches/src/theta/jaccard_similarity.rs @@ -0,0 +1,323 @@ +// 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. + +//! Jaccard similarity for Theta sketches. + +use std::collections::BTreeSet; + +use crate::error::Error; +use crate::hash::DEFAULT_UPDATE_SEED; +use crate::hash::compute_seed_hash; +use crate::theta::CompactThetaSketch; +use crate::theta::ThetaIntersection; +use crate::theta::ThetaSketchView; + +const NUM_STD_DEVS: f64 = 2.0; + +/// Jaccard similarity result for two Theta sketches. +/// +/// The entries are lower bound, estimate, and upper bound, matching the C++ +/// `theta_jaccard_similarity::jaccard` result order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JaccardSimilarity { + /// Approximate lower bound for the Jaccard index. + pub lower_bound: f64, + /// Estimate of the Jaccard index. + pub estimate: f64, + /// Approximate upper bound for the Jaccard index. + pub upper_bound: f64, +} + +impl JaccardSimilarity { + fn exact(value: f64) -> Self { + Self { + lower_bound: value, + estimate: value, + upper_bound: value, + } + } +} + +/// Computes Jaccard similarity between Theta sketches. +pub struct ThetaJaccardSimilarity; + +impl ThetaJaccardSimilarity { + /// Computes the Jaccard similarity index with the default update seed. + /// + /// The Jaccard index is `|A intersection B| / |A union B|`. The returned value contains + /// lower bound, estimate, and upper bound. + pub fn jaccard( + sketch_a: &A, + sketch_b: &B, + ) -> Result { + Self::jaccard_with_seed(sketch_a, sketch_b, DEFAULT_UPDATE_SEED) + } + + /// Computes the Jaccard similarity index with an explicit update seed. + /// + /// Returns an error if a non-empty sketch was built with a different seed. + pub fn jaccard_with_seed( + sketch_a: &A, + sketch_b: &B, + seed: u64, + ) -> Result { + if sketch_a.is_empty() && sketch_b.is_empty() { + return Ok(JaccardSimilarity::exact(1.0)); + } + if sketch_a.is_empty() || sketch_b.is_empty() { + return Ok(JaccardSimilarity::exact(0.0)); + } + + let union = compute_union(sketch_a, sketch_b, seed)?; + if identical_sets(sketch_a, sketch_b, &union) { + return Ok(JaccardSimilarity::exact(1.0)); + } + + let mut intersection = ThetaIntersection::new(seed); + intersection.update(sketch_a)?; + intersection.update(sketch_b)?; + intersection.update(&union)?; + let intersection = intersection.result_with_ordered(false); + + ratio_bounds(&union, &intersection) + } +} + +fn compute_union( + sketch_a: &A, + sketch_b: &B, + seed: u64, +) -> Result { + let expected_seed_hash = compute_seed_hash(seed); + if !sketch_a.is_empty() && sketch_a.seed_hash() != expected_seed_hash { + return Err(Error::invalid_argument(format!( + "incompatible seed hash for sketch A: expected {}, got {}", + expected_seed_hash, + sketch_a.seed_hash() + ))); + } + if !sketch_b.is_empty() && sketch_b.seed_hash() != expected_seed_hash { + return Err(Error::invalid_argument(format!( + "incompatible seed hash for sketch B: expected {}, got {}", + expected_seed_hash, + sketch_b.seed_hash() + ))); + } + + let theta = sketch_a.theta64().min(sketch_b.theta64()); + let mut entries = BTreeSet::new(); + entries.extend(sketch_a.iter().filter(|&hash| hash < theta)); + entries.extend(sketch_b.iter().filter(|&hash| hash < theta)); + + Ok(CompactThetaSketch::from_parts( + entries.into_iter().collect(), + theta, + expected_seed_hash, + false, + false, + )) +} + +fn identical_sets( + sketch_a: &A, + sketch_b: &B, + union: &CompactThetaSketch, +) -> bool { + union.num_retained() == sketch_a.num_retained() + && union.num_retained() == sketch_b.num_retained() + && union.theta64() == sketch_a.theta64() + && union.theta64() == sketch_b.theta64() +} + +fn ratio_bounds( + sketch_a: &CompactThetaSketch, + sketch_b: &CompactThetaSketch, +) -> Result { + let theta_a = sketch_a.theta64(); + let theta_b = sketch_b.theta64(); + if theta_b > theta_a { + return Err(Error::invalid_argument(format!( + "theta_a must be <= theta_b: theta_a={theta_a}, theta_b={theta_b}" + ))); + } + + let count_b = sketch_b.num_retained() as u64; + let count_a = if theta_a == theta_b { + sketch_a.num_retained() as u64 + } else { + sketch_a.iter().filter(|&hash| hash < theta_b).count() as u64 + }; + + if count_a == 0 { + return Ok(JaccardSimilarity { + lower_bound: 0.0, + estimate: 0.5, + upper_bound: 1.0, + }); + } + + let f = sketch_b.theta(); + Ok(JaccardSimilarity { + lower_bound: lower_bound_for_b_over_a(count_a, count_b, f)?, + estimate: count_b as f64 / count_a as f64, + upper_bound: upper_bound_for_b_over_a(count_a, count_b, f)?, + }) +} + +fn lower_bound_for_b_over_a(a: u64, b: u64, f: f64) -> Result { + check_ratio_inputs(a, b, f)?; + if a == 0 { + return Ok(0.0); + } + if f == 1.0 { + return Ok(b as f64 / a as f64); + } + Ok(approximate_lower_bound_on_p( + a, + b, + NUM_STD_DEVS * hacky_adjuster(f), + )) +} + +fn upper_bound_for_b_over_a(a: u64, b: u64, f: f64) -> Result { + check_ratio_inputs(a, b, f)?; + if a == 0 { + return Ok(1.0); + } + if f == 1.0 { + return Ok(b as f64 / a as f64); + } + Ok(approximate_upper_bound_on_p( + a, + b, + NUM_STD_DEVS * hacky_adjuster(f), + )) +} + +fn check_ratio_inputs(a: u64, b: u64, f: f64) -> Result<(), Error> { + if a < b { + return Err(Error::invalid_argument(format!( + "a must be >= b: a = {a}, b = {b}" + ))); + } + if !(0.0..=1.0).contains(&f) || f == 0.0 { + return Err(Error::invalid_argument(format!( + "f must be in the range (0.0, 1.0], got {f}" + ))); + } + Ok(()) +} + +fn hacky_adjuster(f: f64) -> f64 { + let tmp = (1.0 - f).sqrt(); + if f <= 0.5 { + tmp + } else { + tmp + (0.01 * (f - 0.5)) + } +} + +fn approximate_lower_bound_on_p(n: u64, k: u64, num_std_devs: f64) -> f64 { + if n == 0 || k == 0 { + 0.0 + } else if k == 1 { + exact_lower_bound_on_p_k_eq_1(n, delta_of_num_stdevs(num_std_devs)) + } else if k == n { + exact_lower_bound_on_p_k_eq_n(n, delta_of_num_stdevs(num_std_devs)) + } else { + let x = abramowitz_stegun_formula_26p5p22((n - k) as f64 + 1.0, k as f64, -num_std_devs); + 1.0 - x + } +} + +fn approximate_upper_bound_on_p(n: u64, k: u64, num_std_devs: f64) -> f64 { + if n == 0 || k == n { + 1.0 + } else if k == n - 1 { + exact_upper_bound_on_p_k_eq_minusone(n, delta_of_num_stdevs(num_std_devs)) + } else if k == 0 { + exact_upper_bound_on_p_k_eq_zero(n, delta_of_num_stdevs(num_std_devs)) + } else { + let x = abramowitz_stegun_formula_26p5p22((n - k) as f64, k as f64 + 1.0, num_std_devs); + 1.0 - x + } +} + +fn delta_of_num_stdevs(kappa: f64) -> f64 { + normal_cdf(-kappa) +} + +fn normal_cdf(x: f64) -> f64 { + 0.5 * (1.0 + erf(x / 2.0_f64.sqrt())) +} + +fn erf(x: f64) -> f64 { + if x < 0.0 { + -erf_of_nonneg(-x) + } else { + erf_of_nonneg(x) + } +} + +fn erf_of_nonneg(x: f64) -> f64 { + let a1 = 0.0705230784; + let a2 = 0.0422820123; + let a3 = 0.0092705272; + let a4 = 0.0001520143; + let a5 = 0.0002765672; + let a6 = 0.0000430638; + let x2 = x * x; + let x3 = x2 * x; + let x4 = x2 * x2; + let x5 = x2 * x3; + let x6 = x3 * x3; + let sum = 1.0 + (a1 * x) + (a2 * x2) + (a3 * x3) + (a4 * x4) + (a5 * x5) + (a6 * x6); + let sum2 = sum * sum; + let sum4 = sum2 * sum2; + let sum8 = sum4 * sum4; + let sum16 = sum8 * sum8; + 1.0 - (1.0 / sum16) +} + +fn abramowitz_stegun_formula_26p5p22(a: f64, b: f64, yp: f64) -> f64 { + let b2m1 = (2.0 * b) - 1.0; + let a2m1 = (2.0 * a) - 1.0; + let lambda = ((yp * yp) - 3.0) / 6.0; + let htmp = (1.0 / a2m1) + (1.0 / b2m1); + let h = 2.0 / htmp; + let term1 = (yp * (h + lambda).sqrt()) / h; + let term2 = (1.0 / b2m1) - (1.0 / a2m1); + let term3 = (lambda + (5.0 / 6.0)) - (2.0 / (3.0 * h)); + let w = term1 - (term2 * term3); + a / (a + (b * (2.0 * w).exp())) +} + +fn exact_upper_bound_on_p_k_eq_zero(n: u64, delta: f64) -> f64 { + 1.0 - delta.powf(1.0 / n as f64) +} + +fn exact_lower_bound_on_p_k_eq_n(n: u64, delta: f64) -> f64 { + delta.powf(1.0 / n as f64) +} + +fn exact_lower_bound_on_p_k_eq_1(n: u64, delta: f64) -> f64 { + 1.0 - (1.0 - delta).powf(1.0 / n as f64) +} + +fn exact_upper_bound_on_p_k_eq_minusone(n: u64, delta: f64) -> f64 { + (1.0 - delta).powf(1.0 / n as f64) +} diff --git a/datasketches/src/theta/mod.rs b/datasketches/src/theta/mod.rs index 03b5e2a..dc6523b 100644 --- a/datasketches/src/theta/mod.rs +++ b/datasketches/src/theta/mod.rs @@ -42,10 +42,13 @@ mod bit_pack; mod hash_table; mod intersection; +mod jaccard_similarity; mod serialization; mod sketch; pub use self::intersection::ThetaIntersection; +pub use self::jaccard_similarity::JaccardSimilarity; +pub use self::jaccard_similarity::ThetaJaccardSimilarity; pub use self::sketch::CompactThetaSketch; pub use self::sketch::ThetaSketch; pub use self::sketch::ThetaSketchBuilder; diff --git a/datasketches/tests/theta_jaccard_similarity_test.rs b/datasketches/tests/theta_jaccard_similarity_test.rs new file mode 100644 index 0000000..aa808d1 --- /dev/null +++ b/datasketches/tests/theta_jaccard_similarity_test.rs @@ -0,0 +1,147 @@ +// 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::ThetaJaccardSimilarity; +use datasketches::theta::ThetaSketch; + +fn assert_jaccard_exact(actual: datasketches::theta::JaccardSimilarity, expected: f64) { + assert_eq!(actual.lower_bound, expected); + assert_eq!(actual.estimate, expected); + assert_eq!(actual.upper_bound, expected); +} + +fn assert_close(actual: f64, expected: f64, margin: f64) { + assert!( + (actual - expected).abs() <= margin, + "actual={actual}, expected={expected}, margin={margin}" + ); +} + +fn sketch_with_range(start: u64, count: u64) -> ThetaSketch { + let mut sketch = ThetaSketch::builder().build(); + for value in start..start + count { + sketch.update(value); + } + sketch +} + +fn sketch_with_range_and_seed(start: u64, count: u64, seed: u64) -> ThetaSketch { + let mut sketch = ThetaSketch::builder().seed(seed).build(); + for value in start..start + count { + sketch.update(value); + } + sketch +} + +#[test] +fn test_empty() { + let sketch_a = ThetaSketch::builder().build(); + let sketch_b = ThetaSketch::builder().build(); + + let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + + assert_jaccard_exact(jaccard, 1.0); +} + +#[test] +fn test_same_sketch_exact_mode() { + let sketch = sketch_with_range(0, 1000); + + let jaccard = ThetaJaccardSimilarity::jaccard(&sketch, &sketch).unwrap(); + assert_jaccard_exact(jaccard, 1.0); + + let jaccard = + ThetaJaccardSimilarity::jaccard(&sketch.compact(true), &sketch.compact(true)).unwrap(); + assert_jaccard_exact(jaccard, 1.0); +} + +#[test] +fn test_full_overlap_exact_mode() { + let sketch_a = sketch_with_range(0, 1000); + let sketch_b = sketch_with_range(0, 1000); + + let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + assert_jaccard_exact(jaccard, 1.0); + + let jaccard = + ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + assert_jaccard_exact(jaccard, 1.0); +} + +#[test] +fn test_disjoint_exact_mode() { + let sketch_a = sketch_with_range(0, 1000); + let sketch_b = sketch_with_range(1000, 1000); + + let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + assert_jaccard_exact(jaccard, 0.0); + + let jaccard = + ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + assert_jaccard_exact(jaccard, 0.0); +} + +#[test] +fn test_half_overlap_estimation_mode() { + let sketch_a = sketch_with_range(0, 10000); + let sketch_b = sketch_with_range(5000, 10000); + + let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + assert_close(jaccard.lower_bound, 0.33, 0.01); + assert_close(jaccard.estimate, 0.33, 0.01); + assert_close(jaccard.upper_bound, 0.33, 0.01); + + let jaccard = + ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + assert_close(jaccard.lower_bound, 0.33, 0.01); + assert_close(jaccard.estimate, 0.33, 0.01); + assert_close(jaccard.upper_bound, 0.33, 0.01); +} + +#[test] +fn test_half_overlap_estimation_mode_custom_seed() { + let seed = 123; + let sketch_a = sketch_with_range_and_seed(0, 10000, seed); + let sketch_b = sketch_with_range_and_seed(5000, 10000, seed); + + let jaccard = ThetaJaccardSimilarity::jaccard_with_seed(&sketch_a, &sketch_b, seed).unwrap(); + assert_close(jaccard.lower_bound, 0.33, 0.01); + assert_close(jaccard.estimate, 0.33, 0.01); + assert_close(jaccard.upper_bound, 0.33, 0.01); + + let jaccard = ThetaJaccardSimilarity::jaccard_with_seed( + &sketch_a.compact(true), + &sketch_b.compact(true), + seed, + ) + .unwrap(); + assert_close(jaccard.lower_bound, 0.33, 0.01); + assert_close(jaccard.estimate, 0.33, 0.01); + assert_close(jaccard.upper_bound, 0.33, 0.01); +} + +#[test] +fn test_seed_mismatch() { + let mut sketch_a = ThetaSketch::builder().build(); + sketch_a.update(1u64); + let mut sketch_b = ThetaSketch::builder().seed(123).build(); + sketch_b.update(1u64); + + assert!(ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).is_err()); +} From e53af3bd768a943ca76d4a5317d704d766056806 Mon Sep 17 00:00:00 2001 From: Hawkingrei Date: Thu, 2 Jul 2026 15:20:31 +0800 Subject: [PATCH 2/6] docs(theta): clarify jaccard similarity --- datasketches/src/theta/jaccard_similarity.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/datasketches/src/theta/jaccard_similarity.rs b/datasketches/src/theta/jaccard_similarity.rs index 090ba28..ddbb912 100644 --- a/datasketches/src/theta/jaccard_similarity.rs +++ b/datasketches/src/theta/jaccard_similarity.rs @@ -16,6 +16,10 @@ // under the License. //! Jaccard similarity for Theta sketches. +//! +//! The Jaccard similarity index is `J(A, B) = |A intersection B| / |A union B|`. +//! It measures how similar two sketches are: `1.0` means they are considered equal, +//! `0.0` means they are disjoint, and `0.95` means the overlap is 95% of the union. use std::collections::BTreeSet; @@ -31,7 +35,8 @@ const NUM_STD_DEVS: f64 = 2.0; /// Jaccard similarity result for two Theta sketches. /// /// The entries are lower bound, estimate, and upper bound, matching the C++ -/// `theta_jaccard_similarity::jaccard` result order. +/// `theta_jaccard_similarity::jaccard` result order. The bounds use a 95.4% +/// confidence interval, equivalent to +/- 2 standard deviations. #[derive(Clone, Copy, Debug, PartialEq)] pub struct JaccardSimilarity { /// Approximate lower bound for the Jaccard index. @@ -58,8 +63,9 @@ pub struct ThetaJaccardSimilarity; impl ThetaJaccardSimilarity { /// Computes the Jaccard similarity index with the default update seed. /// - /// The Jaccard index is `|A intersection B| / |A union B|`. The returned value contains - /// lower bound, estimate, and upper bound. + /// The returned value contains lower bound, estimate, and upper bound. For very large + /// sketches, where the configured nominal entries are `2^25` or `2^26`, this method may + /// produce unstable results. pub fn jaccard( sketch_a: &A, sketch_b: &B, @@ -69,6 +75,10 @@ impl ThetaJaccardSimilarity { /// Computes the Jaccard similarity index with an explicit update seed. /// + /// The returned value contains lower bound, estimate, and upper bound. For very large + /// sketches, where the configured nominal entries are `2^25` or `2^26`, this method may + /// produce unstable results. + /// /// Returns an error if a non-empty sketch was built with a different seed. pub fn jaccard_with_seed( sketch_a: &A, @@ -90,6 +100,8 @@ impl ThetaJaccardSimilarity { let mut intersection = ThetaIntersection::new(seed); intersection.update(sketch_a)?; intersection.update(sketch_b)?; + // Match the C++ implementation: intersect with the union to ensure that the + // final intersection sketch is a subset of the denominator sketch. intersection.update(&union)?; let intersection = intersection.result_with_ordered(false); From 75c384f4d1e7bcd6f65f884a478cbd367fc4561b Mon Sep 17 00:00:00 2001 From: Hawkingrei Date: Thu, 2 Jul 2026 15:31:11 +0800 Subject: [PATCH 3/6] docs(theta): avoid cpp-specific jaccard wording --- datasketches/src/theta/jaccard_similarity.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/datasketches/src/theta/jaccard_similarity.rs b/datasketches/src/theta/jaccard_similarity.rs index ddbb912..3f78dab 100644 --- a/datasketches/src/theta/jaccard_similarity.rs +++ b/datasketches/src/theta/jaccard_similarity.rs @@ -100,8 +100,8 @@ impl ThetaJaccardSimilarity { let mut intersection = ThetaIntersection::new(seed); intersection.update(sketch_a)?; intersection.update(sketch_b)?; - // Match the C++ implementation: intersect with the union to ensure that the - // final intersection sketch is a subset of the denominator sketch. + // Ensure the numerator sketch is a subset of the denominator sketch used by + // the ratio bounds calculation. intersection.update(&union)?; let intersection = intersection.result_with_ordered(false); From fd02014f7138cd32fcc6e4c52a88e8db40a7c767 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 2 Jul 2026 18:14:17 +0800 Subject: [PATCH 4/6] fixup Signed-off-by: tison --- typos.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typos.toml b/typos.toml index c9b22da..8d4c3e4 100644 --- a/typos.toml +++ b/typos.toml @@ -16,8 +16,8 @@ # under the License. [default.extend-words] -# False-Positive Abbreviations "PREINTS" = "PREINTS" +"htmp" = "htmp" [files] extend-exclude = [] From 915e51814b55b4d41e5ea85e3d494c823cf1b05b Mon Sep 17 00:00:00 2001 From: Hawkingrei Date: Sat, 4 Jul 2026 14:40:30 +0800 Subject: [PATCH 5/6] refactor(theta): extract jaccard union utility --- datasketches/src/theta/jaccard_similarity.rs | 41 +------ datasketches/src/theta/mod.rs | 1 + datasketches/src/theta/union.rs | 113 +++++++++++++++++++ 3 files changed, 116 insertions(+), 39 deletions(-) create mode 100644 datasketches/src/theta/union.rs diff --git a/datasketches/src/theta/jaccard_similarity.rs b/datasketches/src/theta/jaccard_similarity.rs index 3f78dab..e80c8a1 100644 --- a/datasketches/src/theta/jaccard_similarity.rs +++ b/datasketches/src/theta/jaccard_similarity.rs @@ -21,14 +21,12 @@ //! It measures how similar two sketches are: `1.0` means they are considered equal, //! `0.0` means they are disjoint, and `0.95` means the overlap is 95% of the union. -use std::collections::BTreeSet; - use crate::error::Error; use crate::hash::DEFAULT_UPDATE_SEED; -use crate::hash::compute_seed_hash; use crate::theta::CompactThetaSketch; use crate::theta::ThetaIntersection; use crate::theta::ThetaSketchView; +use crate::theta::union::ThetaUnion; const NUM_STD_DEVS: f64 = 2.0; @@ -92,7 +90,7 @@ impl ThetaJaccardSimilarity { return Ok(JaccardSimilarity::exact(0.0)); } - let union = compute_union(sketch_a, sketch_b, seed)?; + let union = ThetaUnion::compute(sketch_a, sketch_b, seed)?; if identical_sets(sketch_a, sketch_b, &union) { return Ok(JaccardSimilarity::exact(1.0)); } @@ -109,41 +107,6 @@ impl ThetaJaccardSimilarity { } } -fn compute_union( - sketch_a: &A, - sketch_b: &B, - seed: u64, -) -> Result { - let expected_seed_hash = compute_seed_hash(seed); - if !sketch_a.is_empty() && sketch_a.seed_hash() != expected_seed_hash { - return Err(Error::invalid_argument(format!( - "incompatible seed hash for sketch A: expected {}, got {}", - expected_seed_hash, - sketch_a.seed_hash() - ))); - } - if !sketch_b.is_empty() && sketch_b.seed_hash() != expected_seed_hash { - return Err(Error::invalid_argument(format!( - "incompatible seed hash for sketch B: expected {}, got {}", - expected_seed_hash, - sketch_b.seed_hash() - ))); - } - - let theta = sketch_a.theta64().min(sketch_b.theta64()); - let mut entries = BTreeSet::new(); - entries.extend(sketch_a.iter().filter(|&hash| hash < theta)); - entries.extend(sketch_b.iter().filter(|&hash| hash < theta)); - - Ok(CompactThetaSketch::from_parts( - entries.into_iter().collect(), - theta, - expected_seed_hash, - false, - false, - )) -} - fn identical_sets( sketch_a: &A, sketch_b: &B, diff --git a/datasketches/src/theta/mod.rs b/datasketches/src/theta/mod.rs index dc6523b..4bd466e 100644 --- a/datasketches/src/theta/mod.rs +++ b/datasketches/src/theta/mod.rs @@ -45,6 +45,7 @@ mod intersection; mod jaccard_similarity; mod serialization; mod sketch; +mod union; pub use self::intersection::ThetaIntersection; pub use self::jaccard_similarity::JaccardSimilarity; diff --git a/datasketches/src/theta/union.rs b/datasketches/src/theta/union.rs new file mode 100644 index 0000000..cbf5ad1 --- /dev/null +++ b/datasketches/src/theta/union.rs @@ -0,0 +1,113 @@ +// 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::collections::BTreeSet; + +use crate::error::Error; +use crate::hash::compute_seed_hash; +use crate::theta::CompactThetaSketch; +use crate::theta::ThetaSketchView; + +pub(super) struct ThetaUnion; + +impl ThetaUnion { + pub(super) fn compute( + sketch_a: &A, + sketch_b: &B, + seed: u64, + ) -> Result { + let seed_hash = compute_seed_hash(seed); + validate_seed_hash(sketch_a, seed_hash, "sketch A")?; + validate_seed_hash(sketch_b, seed_hash, "sketch B")?; + + let theta = sketch_a.theta64().min(sketch_b.theta64()); + let mut entries = BTreeSet::new(); + entries.extend(sketch_a.iter().filter(|&hash| hash < theta)); + entries.extend(sketch_b.iter().filter(|&hash| hash < theta)); + + Ok(CompactThetaSketch::from_parts( + entries.into_iter().collect(), + theta, + seed_hash, + false, + sketch_a.is_empty() && sketch_b.is_empty(), + )) + } +} + +fn validate_seed_hash( + sketch: &S, + expected_seed_hash: u16, + label: &str, +) -> Result<(), Error> { + if !sketch.is_empty() && sketch.seed_hash() != expected_seed_hash { + return Err(Error::invalid_argument(format!( + "incompatible seed hash for {label}: expected {}, got {}", + expected_seed_hash, + sketch.seed_hash() + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use crate::hash::DEFAULT_UPDATE_SEED; + use crate::theta::ThetaSketch; + use crate::theta::union::ThetaUnion; + + fn sketch_with_range(start: u64, count: u64) -> ThetaSketch { + let mut sketch = ThetaSketch::builder().build(); + for value in start..start + count { + sketch.update(value); + } + sketch + } + + #[test] + fn exact_mode_half_overlap() { + let sketch_a = sketch_with_range(0, 1000); + let sketch_b = sketch_with_range(500, 1000); + + let union = ThetaUnion::compute(&sketch_a, &sketch_b, DEFAULT_UPDATE_SEED).unwrap(); + + assert!(!union.is_empty()); + assert!(!union.is_estimation_mode()); + assert_eq!(union.estimate(), 1500.0); + } + + #[test] + fn empty_inputs_produce_empty_union() { + let sketch_a = ThetaSketch::builder().build(); + let sketch_b = ThetaSketch::builder().build(); + + let union = ThetaUnion::compute(&sketch_a, &sketch_b, DEFAULT_UPDATE_SEED).unwrap(); + + assert!(union.is_empty()); + assert!(!union.is_estimation_mode()); + assert_eq!(union.num_retained(), 0); + } + + #[test] + fn seed_mismatch_on_non_empty_sketch_returns_error() { + let mut sketch_a = ThetaSketch::builder().seed(123).build(); + sketch_a.update(1u64); + let sketch_b = ThetaSketch::builder().build(); + + assert!(ThetaUnion::compute(&sketch_a, &sketch_b, DEFAULT_UPDATE_SEED).is_err()); + } +} From 57d27af4cd38c76636079260a86a502d15baa612 Mon Sep 17 00:00:00 2001 From: Hawkingrei Date: Sun, 5 Jul 2026 19:17:37 +0800 Subject: [PATCH 6/6] fix(theta): refine jaccard API --- .../src/common/bounds_binomial_proportions.rs | 161 ++++++++++++++++++ datasketches/src/common/mod.rs | 2 + datasketches/src/theta/jaccard_similarity.rs | 161 +++++------------- datasketches/src/theta/mod.rs | 1 - .../tests/theta_jaccard_similarity_test.rs | 57 +++---- 5 files changed, 230 insertions(+), 152 deletions(-) create mode 100644 datasketches/src/common/bounds_binomial_proportions.rs diff --git a/datasketches/src/common/bounds_binomial_proportions.rs b/datasketches/src/common/bounds_binomial_proportions.rs new file mode 100644 index 0000000..ba603a0 --- /dev/null +++ b/datasketches/src/common/bounds_binomial_proportions.rs @@ -0,0 +1,161 @@ +// 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::error::Error; + +/// Computes an approximate lower bound for an unknown binomial proportion. +pub(crate) fn approximate_lower_bound_on_p( + n: u64, + k: u64, + num_std_devs: f64, +) -> Result { + check_inputs(n, k)?; + if n == 0 || k == 0 { + Ok(0.0) + } else if k == 1 { + Ok(exact_lower_bound_on_p_k_eq_1( + n, + delta_of_num_stdevs(num_std_devs), + )) + } else if k == n { + Ok(exact_lower_bound_on_p_k_eq_n( + n, + delta_of_num_stdevs(num_std_devs), + )) + } else { + let x = abramowitz_stegun_formula_26p5p22((n - k) as f64 + 1.0, k as f64, -num_std_devs); + Ok(1.0 - x) + } +} + +/// Computes an approximate upper bound for an unknown binomial proportion. +pub(crate) fn approximate_upper_bound_on_p( + n: u64, + k: u64, + num_std_devs: f64, +) -> Result { + check_inputs(n, k)?; + if n == 0 || k == n { + Ok(1.0) + } else if k == n - 1 { + Ok(exact_upper_bound_on_p_k_eq_minusone( + n, + delta_of_num_stdevs(num_std_devs), + )) + } else if k == 0 { + Ok(exact_upper_bound_on_p_k_eq_zero( + n, + delta_of_num_stdevs(num_std_devs), + )) + } else { + let x = abramowitz_stegun_formula_26p5p22((n - k) as f64, k as f64 + 1.0, num_std_devs); + Ok(1.0 - x) + } +} + +fn check_inputs(n: u64, k: u64) -> Result<(), Error> { + if k > n { + return Err(Error::invalid_argument(format!( + "k cannot exceed n: k={k}, n={n}" + ))); + } + Ok(()) +} + +fn delta_of_num_stdevs(kappa: f64) -> f64 { + normal_cdf(-kappa) +} + +fn normal_cdf(x: f64) -> f64 { + 0.5 * (1.0 + erf(x / 2.0_f64.sqrt())) +} + +fn erf(x: f64) -> f64 { + if x < 0.0 { + -erf_of_nonneg(-x) + } else { + erf_of_nonneg(x) + } +} + +fn erf_of_nonneg(x: f64) -> f64 { + let a1 = 0.0705230784; + let a2 = 0.0422820123; + let a3 = 0.0092705272; + let a4 = 0.0001520143; + let a5 = 0.0002765672; + let a6 = 0.0000430638; + let x2 = x * x; + let x3 = x2 * x; + let x4 = x2 * x2; + let x5 = x2 * x3; + let x6 = x3 * x3; + let sum = 1.0 + (a1 * x) + (a2 * x2) + (a3 * x3) + (a4 * x4) + (a5 * x5) + (a6 * x6); + let sum2 = sum * sum; + let sum4 = sum2 * sum2; + let sum8 = sum4 * sum4; + let sum16 = sum8 * sum8; + 1.0 - (1.0 / sum16) +} + +fn abramowitz_stegun_formula_26p5p22(a: f64, b: f64, yp: f64) -> f64 { + let b2m1 = (2.0 * b) - 1.0; + let a2m1 = (2.0 * a) - 1.0; + let lambda = ((yp * yp) - 3.0) / 6.0; + let htmp = (1.0 / a2m1) + (1.0 / b2m1); + let h = 2.0 / htmp; + let term1 = (yp * (h + lambda).sqrt()) / h; + let term2 = (1.0 / b2m1) - (1.0 / a2m1); + let term3 = (lambda + (5.0 / 6.0)) - (2.0 / (3.0 * h)); + let w = term1 - (term2 * term3); + a / (a + (b * (2.0 * w).exp())) +} + +fn exact_upper_bound_on_p_k_eq_zero(n: u64, delta: f64) -> f64 { + 1.0 - delta.powf(1.0 / n as f64) +} + +fn exact_lower_bound_on_p_k_eq_n(n: u64, delta: f64) -> f64 { + delta.powf(1.0 / n as f64) +} + +fn exact_lower_bound_on_p_k_eq_1(n: u64, delta: f64) -> f64 { + 1.0 - (1.0 - delta).powf(1.0 / n as f64) +} + +fn exact_upper_bound_on_p_k_eq_minusone(n: u64, delta: f64) -> f64 { + (1.0 - delta).powf(1.0 / n as f64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_invalid_counts() { + assert!(approximate_lower_bound_on_p(1, 2, 2.0).is_err()); + assert!(approximate_upper_bound_on_p(1, 2, 2.0).is_err()); + } + + #[test] + fn computes_exact_edge_cases() { + assert_eq!(approximate_lower_bound_on_p(0, 0, 2.0).unwrap(), 0.0); + assert_eq!(approximate_upper_bound_on_p(0, 0, 2.0).unwrap(), 1.0); + assert_eq!(approximate_lower_bound_on_p(10, 0, 2.0).unwrap(), 0.0); + assert_eq!(approximate_upper_bound_on_p(10, 10, 2.0).unwrap(), 1.0); + } +} diff --git a/datasketches/src/common/mod.rs b/datasketches/src/common/mod.rs index 503df72..d846941 100644 --- a/datasketches/src/common/mod.rs +++ b/datasketches/src/common/mod.rs @@ -24,5 +24,7 @@ pub use self::resize::ResizeFactor; #[cfg(feature = "theta")] pub(crate) mod binomial_bounds; +#[cfg(feature = "theta")] +pub(crate) mod bounds_binomial_proportions; #[cfg(feature = "cpc")] pub(crate) mod inv_pow2_table; diff --git a/datasketches/src/theta/jaccard_similarity.rs b/datasketches/src/theta/jaccard_similarity.rs index e80c8a1..05d1612 100644 --- a/datasketches/src/theta/jaccard_similarity.rs +++ b/datasketches/src/theta/jaccard_similarity.rs @@ -21,6 +21,7 @@ //! It measures how similar two sketches are: `1.0` means they are considered equal, //! `0.0` means they are disjoint, and `0.95` means the overlap is 95% of the union. +use crate::common::bounds_binomial_proportions; use crate::error::Error; use crate::hash::DEFAULT_UPDATE_SEED; use crate::theta::CompactThetaSketch; @@ -37,38 +38,22 @@ const NUM_STD_DEVS: f64 = 2.0; /// confidence interval, equivalent to +/- 2 standard deviations. #[derive(Clone, Copy, Debug, PartialEq)] pub struct JaccardSimilarity { - /// Approximate lower bound for the Jaccard index. - pub lower_bound: f64, - /// Estimate of the Jaccard index. - pub estimate: f64, - /// Approximate upper bound for the Jaccard index. - pub upper_bound: f64, + lower_bound: f64, + estimate: f64, + upper_bound: f64, } impl JaccardSimilarity { - fn exact(value: f64) -> Self { - Self { - lower_bound: value, - estimate: value, - upper_bound: value, - } - } -} - -/// Computes Jaccard similarity between Theta sketches. -pub struct ThetaJaccardSimilarity; - -impl ThetaJaccardSimilarity { /// Computes the Jaccard similarity index with the default update seed. /// /// The returned value contains lower bound, estimate, and upper bound. For very large /// sketches, where the configured nominal entries are `2^25` or `2^26`, this method may /// produce unstable results. - pub fn jaccard( + pub fn between( sketch_a: &A, sketch_b: &B, - ) -> Result { - Self::jaccard_with_seed(sketch_a, sketch_b, DEFAULT_UPDATE_SEED) + ) -> Result { + Self::between_with_seed(sketch_a, sketch_b, DEFAULT_UPDATE_SEED) } /// Computes the Jaccard similarity index with an explicit update seed. @@ -78,21 +63,21 @@ impl ThetaJaccardSimilarity { /// produce unstable results. /// /// Returns an error if a non-empty sketch was built with a different seed. - pub fn jaccard_with_seed( + pub fn between_with_seed( sketch_a: &A, sketch_b: &B, seed: u64, - ) -> Result { + ) -> Result { if sketch_a.is_empty() && sketch_b.is_empty() { - return Ok(JaccardSimilarity::exact(1.0)); + return Ok(Self::exact(1.0)); } if sketch_a.is_empty() || sketch_b.is_empty() { - return Ok(JaccardSimilarity::exact(0.0)); + return Ok(Self::exact(0.0)); } let union = ThetaUnion::compute(sketch_a, sketch_b, seed)?; if identical_sets(sketch_a, sketch_b, &union) { - return Ok(JaccardSimilarity::exact(1.0)); + return Ok(Self::exact(1.0)); } let mut intersection = ThetaIntersection::new(seed); @@ -105,6 +90,29 @@ impl ThetaJaccardSimilarity { ratio_bounds(&union, &intersection) } + + /// Returns the approximate lower bound for the Jaccard index. + pub fn lower_bound(&self) -> f64 { + self.lower_bound + } + + /// Returns the estimate of the Jaccard index. + pub fn estimate(&self) -> f64 { + self.estimate + } + + /// Returns the approximate upper bound for the Jaccard index. + pub fn upper_bound(&self) -> f64 { + self.upper_bound + } + + fn exact(value: f64) -> Self { + Self { + lower_bound: value, + estimate: value, + upper_bound: value, + } + } } fn identical_sets( @@ -161,11 +169,11 @@ fn lower_bound_for_b_over_a(a: u64, b: u64, f: f64) -> Result { if f == 1.0 { return Ok(b as f64 / a as f64); } - Ok(approximate_lower_bound_on_p( + bounds_binomial_proportions::approximate_lower_bound_on_p( a, b, NUM_STD_DEVS * hacky_adjuster(f), - )) + ) } fn upper_bound_for_b_over_a(a: u64, b: u64, f: f64) -> Result { @@ -176,11 +184,11 @@ fn upper_bound_for_b_over_a(a: u64, b: u64, f: f64) -> Result { if f == 1.0 { return Ok(b as f64 / a as f64); } - Ok(approximate_upper_bound_on_p( + bounds_binomial_proportions::approximate_upper_bound_on_p( a, b, NUM_STD_DEVS * hacky_adjuster(f), - )) + ) } fn check_ratio_inputs(a: u64, b: u64, f: f64) -> Result<(), Error> { @@ -205,94 +213,3 @@ fn hacky_adjuster(f: f64) -> f64 { tmp + (0.01 * (f - 0.5)) } } - -fn approximate_lower_bound_on_p(n: u64, k: u64, num_std_devs: f64) -> f64 { - if n == 0 || k == 0 { - 0.0 - } else if k == 1 { - exact_lower_bound_on_p_k_eq_1(n, delta_of_num_stdevs(num_std_devs)) - } else if k == n { - exact_lower_bound_on_p_k_eq_n(n, delta_of_num_stdevs(num_std_devs)) - } else { - let x = abramowitz_stegun_formula_26p5p22((n - k) as f64 + 1.0, k as f64, -num_std_devs); - 1.0 - x - } -} - -fn approximate_upper_bound_on_p(n: u64, k: u64, num_std_devs: f64) -> f64 { - if n == 0 || k == n { - 1.0 - } else if k == n - 1 { - exact_upper_bound_on_p_k_eq_minusone(n, delta_of_num_stdevs(num_std_devs)) - } else if k == 0 { - exact_upper_bound_on_p_k_eq_zero(n, delta_of_num_stdevs(num_std_devs)) - } else { - let x = abramowitz_stegun_formula_26p5p22((n - k) as f64, k as f64 + 1.0, num_std_devs); - 1.0 - x - } -} - -fn delta_of_num_stdevs(kappa: f64) -> f64 { - normal_cdf(-kappa) -} - -fn normal_cdf(x: f64) -> f64 { - 0.5 * (1.0 + erf(x / 2.0_f64.sqrt())) -} - -fn erf(x: f64) -> f64 { - if x < 0.0 { - -erf_of_nonneg(-x) - } else { - erf_of_nonneg(x) - } -} - -fn erf_of_nonneg(x: f64) -> f64 { - let a1 = 0.0705230784; - let a2 = 0.0422820123; - let a3 = 0.0092705272; - let a4 = 0.0001520143; - let a5 = 0.0002765672; - let a6 = 0.0000430638; - let x2 = x * x; - let x3 = x2 * x; - let x4 = x2 * x2; - let x5 = x2 * x3; - let x6 = x3 * x3; - let sum = 1.0 + (a1 * x) + (a2 * x2) + (a3 * x3) + (a4 * x4) + (a5 * x5) + (a6 * x6); - let sum2 = sum * sum; - let sum4 = sum2 * sum2; - let sum8 = sum4 * sum4; - let sum16 = sum8 * sum8; - 1.0 - (1.0 / sum16) -} - -fn abramowitz_stegun_formula_26p5p22(a: f64, b: f64, yp: f64) -> f64 { - let b2m1 = (2.0 * b) - 1.0; - let a2m1 = (2.0 * a) - 1.0; - let lambda = ((yp * yp) - 3.0) / 6.0; - let htmp = (1.0 / a2m1) + (1.0 / b2m1); - let h = 2.0 / htmp; - let term1 = (yp * (h + lambda).sqrt()) / h; - let term2 = (1.0 / b2m1) - (1.0 / a2m1); - let term3 = (lambda + (5.0 / 6.0)) - (2.0 / (3.0 * h)); - let w = term1 - (term2 * term3); - a / (a + (b * (2.0 * w).exp())) -} - -fn exact_upper_bound_on_p_k_eq_zero(n: u64, delta: f64) -> f64 { - 1.0 - delta.powf(1.0 / n as f64) -} - -fn exact_lower_bound_on_p_k_eq_n(n: u64, delta: f64) -> f64 { - delta.powf(1.0 / n as f64) -} - -fn exact_lower_bound_on_p_k_eq_1(n: u64, delta: f64) -> f64 { - 1.0 - (1.0 - delta).powf(1.0 / n as f64) -} - -fn exact_upper_bound_on_p_k_eq_minusone(n: u64, delta: f64) -> f64 { - (1.0 - delta).powf(1.0 / n as f64) -} diff --git a/datasketches/src/theta/mod.rs b/datasketches/src/theta/mod.rs index 4bd466e..4ea38a9 100644 --- a/datasketches/src/theta/mod.rs +++ b/datasketches/src/theta/mod.rs @@ -49,7 +49,6 @@ mod union; pub use self::intersection::ThetaIntersection; pub use self::jaccard_similarity::JaccardSimilarity; -pub use self::jaccard_similarity::ThetaJaccardSimilarity; pub use self::sketch::CompactThetaSketch; pub use self::sketch::ThetaSketch; pub use self::sketch::ThetaSketchBuilder; diff --git a/datasketches/tests/theta_jaccard_similarity_test.rs b/datasketches/tests/theta_jaccard_similarity_test.rs index aa808d1..614cb5b 100644 --- a/datasketches/tests/theta_jaccard_similarity_test.rs +++ b/datasketches/tests/theta_jaccard_similarity_test.rs @@ -17,13 +17,13 @@ #![cfg(feature = "theta")] -use datasketches::theta::ThetaJaccardSimilarity; +use datasketches::theta::JaccardSimilarity; use datasketches::theta::ThetaSketch; fn assert_jaccard_exact(actual: datasketches::theta::JaccardSimilarity, expected: f64) { - assert_eq!(actual.lower_bound, expected); - assert_eq!(actual.estimate, expected); - assert_eq!(actual.upper_bound, expected); + assert_eq!(actual.lower_bound(), expected); + assert_eq!(actual.estimate(), expected); + assert_eq!(actual.upper_bound(), expected); } fn assert_close(actual: f64, expected: f64, margin: f64) { @@ -54,7 +54,7 @@ fn test_empty() { let sketch_a = ThetaSketch::builder().build(); let sketch_b = ThetaSketch::builder().build(); - let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + let jaccard = JaccardSimilarity::between(&sketch_a, &sketch_b).unwrap(); assert_jaccard_exact(jaccard, 1.0); } @@ -63,11 +63,10 @@ fn test_empty() { fn test_same_sketch_exact_mode() { let sketch = sketch_with_range(0, 1000); - let jaccard = ThetaJaccardSimilarity::jaccard(&sketch, &sketch).unwrap(); + let jaccard = JaccardSimilarity::between(&sketch, &sketch).unwrap(); assert_jaccard_exact(jaccard, 1.0); - let jaccard = - ThetaJaccardSimilarity::jaccard(&sketch.compact(true), &sketch.compact(true)).unwrap(); + let jaccard = JaccardSimilarity::between(&sketch.compact(true), &sketch.compact(true)).unwrap(); assert_jaccard_exact(jaccard, 1.0); } @@ -76,11 +75,11 @@ fn test_full_overlap_exact_mode() { let sketch_a = sketch_with_range(0, 1000); let sketch_b = sketch_with_range(0, 1000); - let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + let jaccard = JaccardSimilarity::between(&sketch_a, &sketch_b).unwrap(); assert_jaccard_exact(jaccard, 1.0); let jaccard = - ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + JaccardSimilarity::between(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); assert_jaccard_exact(jaccard, 1.0); } @@ -89,11 +88,11 @@ fn test_disjoint_exact_mode() { let sketch_a = sketch_with_range(0, 1000); let sketch_b = sketch_with_range(1000, 1000); - let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); + let jaccard = JaccardSimilarity::between(&sketch_a, &sketch_b).unwrap(); assert_jaccard_exact(jaccard, 0.0); let jaccard = - ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + JaccardSimilarity::between(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); assert_jaccard_exact(jaccard, 0.0); } @@ -102,16 +101,16 @@ fn test_half_overlap_estimation_mode() { let sketch_a = sketch_with_range(0, 10000); let sketch_b = sketch_with_range(5000, 10000); - let jaccard = ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).unwrap(); - assert_close(jaccard.lower_bound, 0.33, 0.01); - assert_close(jaccard.estimate, 0.33, 0.01); - assert_close(jaccard.upper_bound, 0.33, 0.01); + let jaccard = JaccardSimilarity::between(&sketch_a, &sketch_b).unwrap(); + assert_close(jaccard.lower_bound(), 0.33, 0.01); + assert_close(jaccard.estimate(), 0.33, 0.01); + assert_close(jaccard.upper_bound(), 0.33, 0.01); let jaccard = - ThetaJaccardSimilarity::jaccard(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); - assert_close(jaccard.lower_bound, 0.33, 0.01); - assert_close(jaccard.estimate, 0.33, 0.01); - assert_close(jaccard.upper_bound, 0.33, 0.01); + JaccardSimilarity::between(&sketch_a.compact(true), &sketch_b.compact(true)).unwrap(); + assert_close(jaccard.lower_bound(), 0.33, 0.01); + assert_close(jaccard.estimate(), 0.33, 0.01); + assert_close(jaccard.upper_bound(), 0.33, 0.01); } #[test] @@ -120,20 +119,20 @@ fn test_half_overlap_estimation_mode_custom_seed() { let sketch_a = sketch_with_range_and_seed(0, 10000, seed); let sketch_b = sketch_with_range_and_seed(5000, 10000, seed); - let jaccard = ThetaJaccardSimilarity::jaccard_with_seed(&sketch_a, &sketch_b, seed).unwrap(); - assert_close(jaccard.lower_bound, 0.33, 0.01); - assert_close(jaccard.estimate, 0.33, 0.01); - assert_close(jaccard.upper_bound, 0.33, 0.01); + let jaccard = JaccardSimilarity::between_with_seed(&sketch_a, &sketch_b, seed).unwrap(); + assert_close(jaccard.lower_bound(), 0.33, 0.01); + assert_close(jaccard.estimate(), 0.33, 0.01); + assert_close(jaccard.upper_bound(), 0.33, 0.01); - let jaccard = ThetaJaccardSimilarity::jaccard_with_seed( + let jaccard = JaccardSimilarity::between_with_seed( &sketch_a.compact(true), &sketch_b.compact(true), seed, ) .unwrap(); - assert_close(jaccard.lower_bound, 0.33, 0.01); - assert_close(jaccard.estimate, 0.33, 0.01); - assert_close(jaccard.upper_bound, 0.33, 0.01); + assert_close(jaccard.lower_bound(), 0.33, 0.01); + assert_close(jaccard.estimate(), 0.33, 0.01); + assert_close(jaccard.upper_bound(), 0.33, 0.01); } #[test] @@ -143,5 +142,5 @@ fn test_seed_mismatch() { let mut sketch_b = ThetaSketch::builder().seed(123).build(); sketch_b.update(1u64); - assert!(ThetaJaccardSimilarity::jaccard(&sketch_a, &sketch_b).is_err()); + assert!(JaccardSimilarity::between(&sketch_a, &sketch_b).is_err()); }