hyll 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +8 -0
- data/CHANGELOG.md +36 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +313 -0
- data/Rakefile +12 -0
- data/examples/advance.rb +258 -0
- data/examples/basic.rb +161 -0
- data/lib/hyll/algorithms/enhanced_hyperloglog.rb +343 -0
- data/lib/hyll/algorithms/hyperloglog.rb +759 -0
- data/lib/hyll/constants.rb +29 -0
- data/lib/hyll/factory.rb +34 -0
- data/lib/hyll/utils/hash.rb +65 -0
- data/lib/hyll/utils/math.rb +143 -0
- data/lib/hyll/version.rb +5 -0
- data/lib/hyll.rb +29 -0
- data/sig/hyll.rbs +4 -0
- metadata +80 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 7228e704549545de05c521931f138595621849e8646b911fa27f079bab8a0452
|
4
|
+
data.tar.gz: 0b59d3d971ad26ee4233f9ccfb028386c7bf5a63a995a589b537b0c50e4f5098
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: e89352e88ba060adf982592de13e349403d9bf2c06e71bf9a9ae919e950ac28f730e2d8f3c0a7aa7ab83abd279395569bcaf17b244b9c0d2cc9e27f0c5379fc0
|
7
|
+
data.tar.gz: 559b2f465498a4d9504bb7e2d53b66bca737e748e3a11a06276836aa91bc1cccfae023cca99c1a86ae869b4624cdcd9b79db0b4dac94c414160f8b6e73b04b54
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
@@ -0,0 +1,36 @@
|
|
1
|
+
# Changelog
|
2
|
+
|
3
|
+
All notable changes to this project will be documented in this file.
|
4
|
+
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
7
|
+
|
8
|
+
## [0.1.0] - 2025-03-22
|
9
|
+
|
10
|
+
### Added
|
11
|
+
- Initial implementation of HyperLogLog algorithm
|
12
|
+
- Customizable precision (4-16) with appropriate error rates
|
13
|
+
- Memory-efficient storage optimizations:
|
14
|
+
- Sparse representation for small cardinalities (exact counting)
|
15
|
+
- Dense format with 4-bit register packing (2 registers per byte)
|
16
|
+
- Delta encoding against baseline values
|
17
|
+
- Overflow handling for outlier register values
|
18
|
+
- Maximum Likelihood Estimation (MLE) for improved accuracy
|
19
|
+
- EnhancedHyperLogLog enhanced version of HyperLogLog with additional features
|
20
|
+
- Merge functionality for combining multiple HyperLogLog counters
|
21
|
+
- Serialization and deserialization support
|
22
|
+
- Auto-detection and correction for sequential integer inputs
|
23
|
+
- Method chaining support for all operations
|
24
|
+
- Utility methods:
|
25
|
+
- `add_all` for adding multiple elements at once
|
26
|
+
- `count` for integer cardinality
|
27
|
+
- `mle_cardinality` as an alias for maximum likelihood estimation
|
28
|
+
- Factory method `empty` for creating empty counters
|
29
|
+
- Format conversion methods `to_enhanced` and `to_hll`
|
30
|
+
- Comprehensive test suite with edge case handling
|
31
|
+
|
32
|
+
## About the Release Date
|
33
|
+
|
34
|
+
This first release honors the memory of Philippe Flajolet (1948-2011), the brilliant computer scientist who invented the HyperLogLog algorithm. Flajolet died on March 22, 2011. His pioneering work in probabilistic algorithms and analytic combinatorics revolutionized the way we deal with cardinality estimation problems in large data sets.
|
35
|
+
|
36
|
+
The HyperLogLog algorithm he created (along with co-authors) allows us to count distinct elements in massive datasets with minimal memory requirements, making previously impossible computations feasible.
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 Davide Santangelo
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,313 @@
|
|
1
|
+
# Hyll
|
2
|
+
|
3
|
+
[](https://github.com/davidesantangelo/hyll/actions)
|
4
|
+
|
5
|
+
Hyll is a Ruby implementation of the [HyperLogLog algorithm](https://en.wikipedia.org/wiki/HyperLogLog) for the count-distinct problem, which efficiently approximates the number of distinct elements in a multiset with minimal memory usage. It supports both standard and Enhanced variants, offering a flexible approach for large-scale applications and providing convenient methods for merging, serialization, and maximum likelihood estimation.
|
6
|
+
|
7
|
+
> The name "Hyll" is a shortened form of "HyperLogLog", keeping the characteristic "H" and "LL" sounds.
|
8
|
+
|
9
|
+
## Installation
|
10
|
+
|
11
|
+
Add this line to your application's Gemfile:
|
12
|
+
|
13
|
+
```ruby
|
14
|
+
gem 'hyll'
|
15
|
+
```
|
16
|
+
|
17
|
+
And then execute:
|
18
|
+
|
19
|
+
```bash
|
20
|
+
$ bundle install
|
21
|
+
```
|
22
|
+
|
23
|
+
Or install it yourself as:
|
24
|
+
|
25
|
+
```bash
|
26
|
+
$ gem install hyll
|
27
|
+
```
|
28
|
+
|
29
|
+
## Usage
|
30
|
+
|
31
|
+
### Basic Usage
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
require 'hyll'
|
35
|
+
|
36
|
+
# Create a new HyperLogLog counter with default precision (10)
|
37
|
+
hll = Hyll.new
|
38
|
+
|
39
|
+
# Add elements to the counter
|
40
|
+
hll.add("apple")
|
41
|
+
hll.add("banana")
|
42
|
+
hll.add("cherry")
|
43
|
+
hll.add("apple") # Duplicates don't affect the cardinality
|
44
|
+
|
45
|
+
# Get the estimated cardinality (count of distinct elements)
|
46
|
+
puts hll.cardinality # Output: approximately 3
|
47
|
+
```
|
48
|
+
|
49
|
+
### With Custom Precision
|
50
|
+
|
51
|
+
```ruby
|
52
|
+
# Create with custom precision (4-16)
|
53
|
+
# Higher precision means more memory usage but better accuracy
|
54
|
+
hll = Hyll.new(precision: 12)
|
55
|
+
|
56
|
+
# Add many elements
|
57
|
+
1000.times do |i|
|
58
|
+
hll.add("element-#{i}")
|
59
|
+
end
|
60
|
+
|
61
|
+
puts hll.cardinality # Output: approximately 1000
|
62
|
+
```
|
63
|
+
|
64
|
+
### Using Different Algorithm Variants
|
65
|
+
|
66
|
+
```ruby
|
67
|
+
# Standard HyperLogLog (default)
|
68
|
+
standard_hll = Hyll.new(type: :standard) # You can also use :hll as an alias for :standard
|
69
|
+
|
70
|
+
|
71
|
+
# EnhancedHyperLogLog
|
72
|
+
enhanced_hll = Hyll.new(type: :enhanced)
|
73
|
+
```
|
74
|
+
|
75
|
+
### Adding Multiple Elements
|
76
|
+
|
77
|
+
```ruby
|
78
|
+
# Add multiple elements at once
|
79
|
+
hll.add_all(["apple", "banana", "cherry", "date"])
|
80
|
+
```
|
81
|
+
|
82
|
+
### Merging HyperLogLog Counters
|
83
|
+
|
84
|
+
```ruby
|
85
|
+
# Creating and populating two HLL counters
|
86
|
+
hll1 = Hyll.new(precision: 10)
|
87
|
+
hll2 = Hyll.new(precision: 10)
|
88
|
+
|
89
|
+
hll1.add_all(["apple", "banana", "cherry"])
|
90
|
+
hll2.add_all(["cherry", "date", "elderberry"])
|
91
|
+
|
92
|
+
# Merge hll2 into hll1
|
93
|
+
hll1.merge(hll2)
|
94
|
+
|
95
|
+
puts hll1.cardinality # Output: approximately 5
|
96
|
+
```
|
97
|
+
|
98
|
+
### Using Different Estimation Methods
|
99
|
+
|
100
|
+
```ruby
|
101
|
+
# Standard HyperLogLog estimator
|
102
|
+
puts hll.cardinality
|
103
|
+
|
104
|
+
# Maximum Likelihood Estimator (generally more accurate)
|
105
|
+
puts hll.maximum_likelihood_cardinality
|
106
|
+
# or use the shorter alias
|
107
|
+
puts hll.mle_cardinality
|
108
|
+
```
|
109
|
+
|
110
|
+
### Using EnhancedHyperLogLog Format
|
111
|
+
|
112
|
+
EnhancedHyperLogLog a strictly enhanced version of HyperLogLog with additional features - inspired by Presto's P4HYPERLOGLOG:
|
113
|
+
|
114
|
+
```ruby
|
115
|
+
# Create a EnhancedHyperLogLog directly
|
116
|
+
enhanced = Hyll.new(type: :enhanced)
|
117
|
+
enhanced.add_all(["apple", "banana", "cherry"])
|
118
|
+
|
119
|
+
# Convert from standard HyperLogLog to EnhancedHyperLogLog
|
120
|
+
hll = Hyll.new
|
121
|
+
hll.add_all(["apple", "banana", "cherry"])
|
122
|
+
enhanced = hll.to_enhanced
|
123
|
+
|
124
|
+
# Convert from EnhancedHyperLogLog to standard HyperLogLog
|
125
|
+
hll = enhanced.to_hll
|
126
|
+
|
127
|
+
# Use the streaming cardinality estimator for improved accuracy
|
128
|
+
# This implementation is based on the martingale estimator from Daniel Ting's paper
|
129
|
+
streaming_estimate = enhanced.cardinality(use_streaming: true)
|
130
|
+
|
131
|
+
# Get variance and confidence intervals for the streaming estimate
|
132
|
+
variance = enhanced.streaming_variance
|
133
|
+
bounds = enhanced.streaming_error_bounds(confidence: 0.95) # 95% confidence interval
|
134
|
+
```
|
135
|
+
|
136
|
+
### Serialization and Deserialization
|
137
|
+
|
138
|
+
```ruby
|
139
|
+
# Serialize for storage
|
140
|
+
hll.add_all(["apple", "banana", "cherry"])
|
141
|
+
serialized = hll.serialize
|
142
|
+
|
143
|
+
# Store in a file
|
144
|
+
File.binwrite("hll_data.bin", serialized)
|
145
|
+
|
146
|
+
# Later, restore the HyperLogLog
|
147
|
+
data = File.binread("hll_data.bin")
|
148
|
+
restored_hll = Hyll.deserialize(data)
|
149
|
+
```
|
150
|
+
|
151
|
+
### Creating Empty HLLs with Factory Method
|
152
|
+
|
153
|
+
```ruby
|
154
|
+
# Using the Factory directly for advanced use cases
|
155
|
+
empty_standard = Hyll::Factory.create(type: :standard, precision: 12)
|
156
|
+
empty_enhanced = Hyll::Factory.create(type: :enhanced, precision: 14)
|
157
|
+
|
158
|
+
# Or use the simple module method
|
159
|
+
empty_hll = Hyll.new(precision: 12)
|
160
|
+
```
|
161
|
+
|
162
|
+
## Algorithm Overview
|
163
|
+
|
164
|
+
HyperLogLog is a probabilistic algorithm for counting unique elements in a dataset with very low memory overhead. It was introduced by Flajolet et al. in 2007 as an improvement on the earlier LogLog algorithm.
|
165
|
+
|
166
|
+
The algorithm works through the following principles:
|
167
|
+
|
168
|
+
1. **Hash Function**: Each element is hashed to produce a pseudo-random value.
|
169
|
+
2. **Register Selection**: A portion of the hash is used to select one of `m` registers (where `m = 2^precision`).
|
170
|
+
3. **Register Value**: The algorithm counts the number of leading zeros (+1) in the remaining hash bits. Each register stores the maximum observed value.
|
171
|
+
4. **Cardinality Estimation**: The harmonic mean of the register values is used to estimate the cardinality.
|
172
|
+
|
173
|
+
The algorithm provides a trade-off between memory usage and accuracy:
|
174
|
+
- Lower precision (4-6): Uses less memory but has higher error rates (>10%)
|
175
|
+
- Medium precision (7-11): Uses moderate memory with reasonable error rates (3-10%)
|
176
|
+
- Higher precision (12-16): Uses more memory with better accuracy (<3%)
|
177
|
+
|
178
|
+

|
179
|
+
|
180
|
+
> This chart visualizes the relationship between precision values in HyperLogLog and the theoretical error rates. HyperLogLog is a probabilistic algorithm used for cardinality estimation with a typical error of **1.04/√m** (or **1.04·m⁻¹/²**), where **m = 2^precision** is the number of registers.
|
181
|
+
|
182
|
+
## Performance Comparison
|
183
|
+
|
184
|
+
This table compares different configurations of the HyperLogLog algorithm:
|
185
|
+
|
186
|
+
| Precision | Memory Usage | Error Rate | Max Elements | Implementation |
|
187
|
+
| --------- | ------------ | ---------- | ------------ | -------------- |
|
188
|
+
| 4 | 0.13 KB | ~26% | ~100K | Standard |
|
189
|
+
| 8 | 2.0 KB | ~6.5% | ~10M | Standard |
|
190
|
+
| 10 | 8.0 KB | ~3.25% | ~1B | Standard |
|
191
|
+
| 12 | 32.0 KB | ~1.625% | ~10B | Standard |
|
192
|
+
| 14 | 128.0 KB | ~0.8125% | ~100B | Standard |
|
193
|
+
| 16 | 512.0 KB | ~0.4% | ~1T | Standard |
|
194
|
+
| 10 | 9.0 KB | ~3.25% | ~1B | Enhanced |
|
195
|
+
| 12 | 36.0 KB | ~1.625% | ~10B | Enhanced |
|
196
|
+
|
197
|
+
### Comparison with Other Cardinality Estimators
|
198
|
+
|
199
|
+
| Algorithm | Memory Efficiency | Accuracy (Cardinality) | Merge Support (Cardinality) | Implementation Complexity | Primary Use Case(s) |
|
200
|
+
| ---------------- | ----------------- | ---------------------- | ------------------------------ | ------------------------- | -------------------------------------------------------- |
|
201
|
+
| HyperLogLog | High | High (Approximate) | Yes | Medium | High-scale cardinality estimation |
|
202
|
+
| Linear Counting | Medium | Medium (Approximate) | Limited | Low | Moderate scale cardinality estimation, simplicity |
|
203
|
+
| LogLog | High | Medium (Approximate) | Yes | Low | Very high memory efficiency cardinality estimation |
|
204
|
+
| K-Minimum Values | Medium | High (Approximate) | Yes | Medium | High accuracy cardinality estimation, set operations |
|
205
|
+
| Bloom Filter | Medium | N/A (Membership) | No (Cardinality) / Yes (Union) | Low | Membership testing with false positives, not cardinality |
|
206
|
+
|
207
|
+
### Benchmark Results
|
208
|
+
|
209
|
+
Below are actual performance measurements from an Apple Mac Mini M4 with 24GB RAM:
|
210
|
+
|
211
|
+
| Operation | Implementation | Time (seconds) | Items/Operations |
|
212
|
+
| ----------------------- | -------------------- | -------------- | ---------------- |
|
213
|
+
| Element Addition | Standard HyperLogLog | 0.0176 | 10,000 items |
|
214
|
+
| Element Addition | EnhancedHyperLogLog | 0.0109 | 10,000 items |
|
215
|
+
| Cardinality Calculation | Standard HyperLogLog | 0.0011 | 10 calculations |
|
216
|
+
| Cardinality Calculation | EnhancedHyperLogLog | 0.0013 | 10 calculations |
|
217
|
+
| Serialization | Standard HyperLogLog | 0.0003 | 10 operations |
|
218
|
+
| Deserialization | Standard HyperLogLog | 0.0005 | 10 operations |
|
219
|
+
|
220
|
+
#### Memory Efficiency
|
221
|
+
|
222
|
+
| Data Structure | Memory Usage (bytes) | Items | Compression Ratio |
|
223
|
+
| -------------- | -------------------- | ------- | ----------------- |
|
224
|
+
| Standard Array | 800,040 | 100,000 | 1x |
|
225
|
+
| HyperLogLog | 128 | 100,000 | 6,250x |
|
226
|
+
|
227
|
+
These benchmarks demonstrate HyperLogLog's exceptional memory efficiency, maintaining a compression ratio of over 6,250x compared to storing the raw elements, while still providing accurate cardinality estimates.
|
228
|
+
|
229
|
+
## Features
|
230
|
+
|
231
|
+
- Standard HyperLogLog implementation with customizable precision
|
232
|
+
- Memory-efficient register storage with 4-bit packing (inspired by Facebook's Presto implementation)
|
233
|
+
- Sparse representation for small cardinalities
|
234
|
+
- Dense representation for larger datasets
|
235
|
+
- EnhancedHyperLogLog format for compatibility with other systems
|
236
|
+
- Streaming martingale estimator for improved accuracy with EnhancedHyperLogLog
|
237
|
+
- Maximum Likelihood Estimation for improved accuracy
|
238
|
+
- Merge and serialization capabilities
|
239
|
+
- Factory pattern for creating and deserializing counters
|
240
|
+
|
241
|
+
## Implementation Details
|
242
|
+
|
243
|
+
Hyll offers two main implementations:
|
244
|
+
|
245
|
+
1. **Standard HyperLogLog**: Optimized for accuracy and memory efficiency, uses sparse format for small cardinalities and dense format with 4-bit packing for larger sets.
|
246
|
+
|
247
|
+
2. **EnhancedHyperLogLog**: A strictly dense format similar to Facebook's Presto P4HYPERLOGLOG type, where "P4" refers to the 4-bit precision per register. This format is slightly less memory-efficient but offers better compatibility with other HyperLogLog implementations. It also includes a streaming martingale estimator that can provide up to 1.56x better accuracy for the same memory usage.
|
248
|
+
|
249
|
+
The internal architecture follows a modular approach:
|
250
|
+
|
251
|
+
- `Hyll::Constants`: Shared constants used throughout the library
|
252
|
+
- `Hyll::Utils::Hash`: Hash functions for element processing
|
253
|
+
- `Hyll::Utils::Math`: Mathematical operations for HyperLogLog calculations
|
254
|
+
- `Hyll::HyperLogLog`: The standard implementation
|
255
|
+
- `Hyll::EnhancedHyperLogLog`: The enhanced implementation
|
256
|
+
- `Hyll::Factory`: Factory pattern for creating counters
|
257
|
+
|
258
|
+
## Examples
|
259
|
+
|
260
|
+
A basic examples file has been created to demonstrate how to use Hyll:
|
261
|
+
|
262
|
+
```ruby
|
263
|
+
# examples/basic.rb
|
264
|
+
require 'hyll'
|
265
|
+
|
266
|
+
# Create a new HyperLogLog counter
|
267
|
+
counter = Hyll::HyperLogLog.new
|
268
|
+
|
269
|
+
# Add some elements
|
270
|
+
1000.times { |i| counter.add(i) }
|
271
|
+
|
272
|
+
# Get the cardinality estimate
|
273
|
+
puts "Estimated cardinality: #{counter.count}"
|
274
|
+
|
275
|
+
# Using Maximum Likelihood Estimation (often more accurate)
|
276
|
+
puts "MLE cardinality: #{counter.mle_cardinality}"
|
277
|
+
```
|
278
|
+
|
279
|
+
For a comprehensive overview of all features, see `examples/basic.rb` which includes:
|
280
|
+
- Basic counting
|
281
|
+
- Custom precision settings
|
282
|
+
- Merging counters
|
283
|
+
- Serialization
|
284
|
+
- EnhancedHyperLogLog usage
|
285
|
+
- Batch operations
|
286
|
+
- Large dataset handling
|
287
|
+
- Set operations
|
288
|
+
|
289
|
+
For advanced usage scenarios, check out `examples/advance.rb` which includes:
|
290
|
+
- Set intersection estimation
|
291
|
+
- Working with custom data types
|
292
|
+
- Time-window based cardinality monitoring
|
293
|
+
- Advanced serialization techniques
|
294
|
+
- Precision vs. memory usage benchmarks
|
295
|
+
|
296
|
+
## Development
|
297
|
+
|
298
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
299
|
+
|
300
|
+
## References and Acknowledgements
|
301
|
+
|
302
|
+
- Original HyperLogLog paper: ["HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm"](https://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf) by Philippe Flajolet, Éric Fusy, Olivier Gandouet, and Frédéric Meunier (2007).
|
303
|
+
- Improved bias correction: ["HyperLogLog in Practice: Algorithmic Engineering of a State of the Art Cardinality Estimation Algorithm"](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/40671.pdf) by Stefan Heule, Marc Nunkesser, and Alexander Hall (2013).
|
304
|
+
- Streaming cardinality estimation: ["Streamed Approximate Counting of Distinct Elements: Beating Optimal Batch Methods"](https://research.facebook.com/publications/streamed-approximate-counting-of-distinct-elements/) by Daniel Ting (2014).
|
305
|
+
- Facebook's Presto implementation details: ["HyperLogLog in Presto: A significantly faster way to handle cardinality estimation"](https://engineering.fb.com/2018/12/13/data-infrastructure/hyperloglog/) by Mehrdad Honarkhah and Arya Talebzadeh.
|
306
|
+
|
307
|
+
## Contributing
|
308
|
+
|
309
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/davidesantangelo/hyll. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/davidesantangelo/hyll/blob/master/CODE_OF_CONDUCT.md).
|
310
|
+
|
311
|
+
## License
|
312
|
+
|
313
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|