-
Notifications
You must be signed in to change notification settings - Fork 29
feat: support theta and tuple a-not-b #155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| // 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. | ||
|
|
||
| //! Theta sketch set difference (`A and not B`). | ||
| //! | ||
| //! [`ThetaAnotB`] computes the set difference of two Theta sketches: the keys retained in `A` | ||
| //! that are not present in `B`. The logic lives in the shared raw operator (`RawAnotB`) that also | ||
| //! drives the Tuple a-not-B; Theta entries carry no summary, so nothing needs to be combined. | ||
|
|
||
| use crate::error::Error; | ||
| use crate::hash::DEFAULT_UPDATE_SEED; | ||
| use crate::theta::CompactThetaSketch; | ||
| use crate::theta::ThetaSketchView; | ||
| use crate::thetacommon::a_not_b::RawAnotB; | ||
|
|
||
| /// Set difference operator (`A and not B`) for Theta sketches. | ||
| /// | ||
| /// This is a stateless operator (other than the seed): each call to [`compute`](Self::compute) | ||
| /// takes two input sketches and returns a new [`CompactThetaSketch`]. | ||
| /// | ||
| /// # Examples | ||
| /// | ||
| /// ``` | ||
| /// # use datasketches::theta::{ThetaAnotB, ThetaSketchBuilder}; | ||
| /// let mut a = ThetaSketchBuilder::default().build(); | ||
| /// a.update("apple"); | ||
| /// a.update("banana"); | ||
| /// | ||
| /// let mut b = ThetaSketchBuilder::default().build(); | ||
| /// b.update("banana"); | ||
| /// | ||
| /// let a_not_b = ThetaAnotB::new_with_default_seed(); | ||
| /// let result = a_not_b.compute(&a, &b, true).unwrap(); | ||
| /// assert_eq!(result.num_retained(), 1); // only "apple" survives | ||
| /// ``` | ||
| #[derive(Debug, Clone, Copy)] | ||
| pub struct ThetaAnotB { | ||
| raw: RawAnotB, | ||
| } | ||
|
|
||
| impl ThetaAnotB { | ||
| /// Creates a new set difference operator for the given `seed`. | ||
| pub fn new(seed: u64) -> Self { | ||
| Self { | ||
| raw: RawAnotB::new(seed), | ||
| } | ||
| } | ||
|
|
||
| /// Creates a new set difference operator with the default seed. | ||
| pub fn new_with_default_seed() -> Self { | ||
| Self::new(DEFAULT_UPDATE_SEED) | ||
| } | ||
|
|
||
| /// Computes `a and not b`. | ||
| /// | ||
| /// The result retains every key of `a` (below the combined theta) that is not present in `b`. | ||
| /// If `ordered` is true, the retained entries are sorted ascending by hash. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if either non-trivial input has a seed hash that differs from this | ||
| /// operator's seed. | ||
| pub fn compute<A, B>(&self, a: &A, b: &B, ordered: bool) -> Result<CompactThetaSketch, Error> | ||
| where | ||
| A: ThetaSketchView, | ||
| B: ThetaSketchView, | ||
| { | ||
| let parts = self.raw.compute(a, b, ordered)?; | ||
| Ok(CompactThetaSketch::from_parts( | ||
| parts | ||
| .entries | ||
| .into_iter() | ||
| .map(|entry| entry.hash()) | ||
| .collect(), | ||
| parts.theta, | ||
| parts.seed_hash, | ||
| parts.ordered, | ||
| parts.empty, | ||
| )) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 std::collections::HashSet; | ||
|
|
||
| use crate::error::Error; | ||
| use crate::hash::compute_seed_hash; | ||
| use crate::thetacommon::RawHashTableEntry; | ||
| use crate::thetacommon::RawThetaSketchView; | ||
| use crate::thetacommon::constants::MAX_THETA; | ||
| use crate::thetacommon::hash_table::RawCompactParts; | ||
|
|
||
| /// Stateless set difference (`A and not B`) operator shared by Theta and Tuple sketches. | ||
| /// | ||
| /// `E` is the retained entry type. Ordinary Theta entries only contain a hash, while tuple | ||
| /// entries also carry a summary. Surviving entries are moved from `A` unchanged, so unlike the | ||
| /// union and intersection this operation needs no entry-merge policy. | ||
| #[derive(Debug, Clone, Copy)] | ||
| pub struct RawAnotB { | ||
| seed_hash: u16, | ||
| } | ||
|
|
||
| impl RawAnotB { | ||
| /// Creates a new set difference operator for the given `seed`. | ||
| pub fn new(seed: u64) -> Self { | ||
| Self { | ||
| seed_hash: compute_seed_hash(seed), | ||
| } | ||
| } | ||
|
|
||
| /// Computes `a and not b`. | ||
| /// | ||
| /// The result retains every entry of `a` (below the combined theta) whose hash is not present | ||
| /// in `b`. If `ordered` is true, the retained entries are sorted ascending by hash. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if either non-trivial input has a seed hash that differs from this | ||
| /// operator's seed. | ||
| pub fn compute<E, A, B>(&self, a: &A, b: &B, ordered: bool) -> Result<RawCompactParts<E>, Error> | ||
| where | ||
| E: RawHashTableEntry, | ||
| A: RawThetaSketchView<E>, | ||
| B: RawThetaSketchView<E>, | ||
| { | ||
| // If A is empty the result is an (empty) copy of A. As with the union and intersection, an | ||
| // empty input carries no keys, so its seed is not validated. | ||
| if a.is_empty() { | ||
| return Ok(Self::parts_from_view(a, ordered)); | ||
| } | ||
|
|
||
| // A is non-empty, so its seed must be compatible. | ||
| if a.seed_hash() != self.seed_hash { | ||
| return Err(Error::invalid_argument(format!( | ||
| "A seed hash mismatch: expected {}, got {}", | ||
| self.seed_hash, | ||
| a.seed_hash() | ||
| ))); | ||
| } | ||
|
|
||
| // An empty B subtracts nothing, so the result is simply a copy of A. This also covers the | ||
| // "A is non-empty but has no retained keys" state: B's seed and theta must not influence | ||
| // the result, so we return before touching them. | ||
| if b.is_empty() { | ||
| return Ok(Self::parts_from_view(a, ordered)); | ||
| } | ||
|
|
||
| // B is non-empty, so its seed must be compatible. | ||
| if b.seed_hash() != self.seed_hash { | ||
| return Err(Error::invalid_argument(format!( | ||
| "B seed hash mismatch: expected {}, got {}", | ||
| self.seed_hash, | ||
| b.seed_hash() | ||
| ))); | ||
| } | ||
|
|
||
| let theta = a.theta().min(b.theta()); | ||
| // A is non-empty here; the result only becomes empty if everything is subtracted in exact | ||
| // mode (handled below). | ||
| let mut is_empty = false; | ||
|
|
||
| let entries: Vec<E> = if b.num_retained() == 0 { | ||
| a.iter().filter(|entry| entry.hash() < theta).collect() | ||
| } else if a.is_ordered() && b.is_ordered() { | ||
| // Both inputs are sorted ascending by hash: merge-scan without a hash set. Only | ||
| // b hashes below theta can exclude an a entry (a entries are all < theta), so | ||
| // unexamined b entries at or above theta are harmless. | ||
| let mut b_hashes = b.iter().map(|entry| entry.hash()).peekable(); | ||
| let mut entries = Vec::new(); | ||
| for entry in a.iter() { | ||
| let hash = entry.hash(); | ||
| if hash >= theta { | ||
| break; | ||
| } | ||
| while let Some(&b_hash) = b_hashes.peek() { | ||
| if b_hash < hash { | ||
| b_hashes.next(); | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| if b_hashes.peek() != Some(&hash) { | ||
| entries.push(entry); | ||
| } | ||
| } | ||
| entries | ||
| } else { | ||
| let mut b_keys: HashSet<u64> = HashSet::with_capacity(b.num_retained()); | ||
| for entry in b.iter() { | ||
| let hash = entry.hash(); | ||
| if hash < theta { | ||
| b_keys.insert(hash); | ||
| } else if b.is_ordered() { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| let mut entries = Vec::new(); | ||
| for entry in a.iter() { | ||
| let hash = entry.hash(); | ||
| if hash < theta { | ||
| if !b_keys.contains(&hash) { | ||
| entries.push(entry); | ||
| } | ||
| } else if a.is_ordered() { | ||
| break; | ||
| } | ||
| } | ||
| entries | ||
| }; | ||
|
|
||
| if entries.is_empty() && theta == MAX_THETA { | ||
| is_empty = true; | ||
| } | ||
|
|
||
| let out_ordered = ordered || a.is_ordered(); | ||
| let mut entries = entries; | ||
| if ordered && !a.is_ordered() && entries.len() > 1 { | ||
| entries.sort_unstable_by_key(RawHashTableEntry::hash); | ||
| } | ||
|
|
||
| Ok(RawCompactParts { | ||
| entries, | ||
| theta, | ||
| seed_hash: self.seed_hash, | ||
| ordered: out_ordered, | ||
| empty: is_empty, | ||
| }) | ||
| } | ||
|
|
||
| /// Builds compact parts that are a copy of the view `a`. | ||
| fn parts_from_view<E, V>(a: &V, ordered: bool) -> RawCompactParts<E> | ||
| where | ||
| E: RawHashTableEntry, | ||
| V: RawThetaSketchView<E>, | ||
| { | ||
| let mut entries: Vec<E> = a.iter().collect(); | ||
| let out_ordered = ordered || a.is_ordered(); | ||
| if ordered && !a.is_ordered() && entries.len() > 1 { | ||
| entries.sort_unstable_by_key(RawHashTableEntry::hash); | ||
| } | ||
| RawCompactParts { | ||
| entries, | ||
| theta: a.theta(), | ||
| seed_hash: a.seed_hash(), | ||
| ordered: out_ordered, | ||
| empty: a.is_empty(), | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a_not_bcomes from datasketches-cpp and datasketches-java?@leerho @proost what if we name this set operation as
differenceorexception, sincea_not_bis somewhat strange to me. Or is it actually an idiom in this domain?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Based on the result, it looks like the same as set difference.
@ariesdevil What do you think?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a_not_b is a set difference. However the name a_not_b is a mnemonic that tells you the direction of the difference.
In the math of boolean logic one would write
A \ B := A AND NOT B =$A \cup !B$ $B \cup !A$
or
B \ A := B AND NOT A =
Where "\" is the difference operator.
Note that A \ B != B \ A !
Although C++ allows user defined operators most languages do not. To call the difference function, we need to indicate the direction. We chose to do it by the position of the arguments, and the name of the function is a mnemonic of the direction.
Sketch result a_not_b(Sketch A, Sketch B);
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@leerho Thanks for your information!
Yes the Rust impl also defines the API as:
So I generally agree that
a_not_bprovides more information and avoid the confusion of op direction.Even if we can add methods or operator overrides to
ThetaSketch/TupleSketch, it is not symmetry to the union and intersection interface.One minor comment: any typical reason to name it
TupleAnotBrather thanTupleANotB? WeirdCamelCaseat first glance.