Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
hyperloglog.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31# ifndef HYPERLOGLOG_H
32# define HYPERLOGLOG_H
33
44# include <cmath>
45# include <algorithm>
46# include <bit>
47# include <cstdint>
48
49# include <ah-errors.H>
50# include <tpl_array.H>
51# include <hash-fct.H>
52
53namespace Aleph
54{
67 template <typename T>
69 {
70 uint8_t b_;
71 size_t m_;
72 double alpha_m_;
78 [[nodiscard]] static uint64_t hash64(const T & val) noexcept
79 {
80 static_assert(sizeof(size_t) >= 8,
81 "HyperLogLog requires 64-bit size_t; murmur3hash is 32-bit on this platform");
82 return static_cast<uint64_t>(murmur3hash(val, 0x12345678));
83 }
84
88 [[nodiscard]] static size_t compute_m_or_throw(const uint8_t b)
89 {
90 ah_domain_error_if(b < 4 or b > 16)
91 << "HyperLogLog: b must be in range [4, 16] (got " << static_cast<int>(b) << ")";
92 return static_cast<size_t>(1) << b;
93 }
94
98 [[nodiscard]] static double compute_alpha(const size_t m) noexcept
99 {
100 if (m == 16) return 0.673;
101 if (m == 32) return 0.697;
102 if (m == 64) return 0.709;
103 return 0.7213 / (1.0 + 1.079 / static_cast<double>(m));
104 }
105
106 public:
113 explicit HyperLogLog(const uint8_t b = 12)
114 : b_(b), m_(compute_m_or_throw(b)),
116 registers_(m_, static_cast<uint8_t>(0))
117 {}
118
123 HyperLogLog(const HyperLogLog & other) = default;
124
138 {
139 swap(other);
140 }
141
147 HyperLogLog & operator = (const HyperLogLog & other) = default;
148
156 {
157 swap(other);
158 return *this;
159 }
160
164 void swap(HyperLogLog & other) noexcept
165 {
166 std::swap(b_, other.b_);
167 std::swap(m_, other.m_);
168 std::swap(alpha_m_, other.alpha_m_);
169 registers_.swap(other.registers_);
170 }
171
179 void update(const T & val)
180 {
181 const uint64_t x = hash64(val);
182 const size_t j = x >> (64 - b_); // upper b bits for index
183 const uint64_t w = x << b_ | (static_cast<uint64_t>(1) << (b_ - 1)); // remaining bits
184
185 // count leading zeros in the hash part not used for indexing
186
187 if (const auto rho = static_cast<uint8_t>(std::countl_zero(w) + 1); rho > registers_[j])
188 registers_(j) = rho;
189 }
190
199 [[nodiscard]] double estimate() const noexcept
200 {
201 double z = 0.0;
202 size_t v = 0; // count of empty registers for Linear Counting
203 for (size_t i = 0; i < m_; ++i)
204 {
205 // More efficient and stable than std::pow(2.0, -registers_[i])
206 z += std::ldexp(1.0, -static_cast<int>(registers_[i]));
207 if (registers_[i] == 0)
208 ++v;
209 }
210
211 // Raw estimate
212 double e = alpha_m_ * (static_cast<double>(m_) * static_cast<double>(m_)) / z;
213
214 // Small range correction (Linear Counting)
215 if (e <= 2.5 * static_cast<double>(m_))
216 {
217 if (v > 0)
218 e = static_cast<double>(m_) * std::log(static_cast<double>(m_) / static_cast<double>(v));
219 }
220 // Large range correction: use log1p for numerical stability; saturate when ratio >= 1
221 else
222 {
223 static const double two_to_64 = std::ldexp(1.0, 64);
224 if (e > (1.0 / 30.0) * two_to_64)
225 {
226 const double ratio = e / two_to_64;
227 if (ratio >= 1.0)
228 return two_to_64; // saturate at hash-space limit
229 e = -two_to_64 * std::log1p(-ratio);
230 }
231 }
232
233 return e;
234 }
235
247 void merge(const HyperLogLog & other)
248 {
249 ah_domain_error_if(b_ != other.b_) << "HyperLogLog::merge: precision mismatch";
250
251 for (size_t i = 0; i < m_; ++i)
252 registers_(i) = std::max(registers_[i], other.registers_[i]);
253 }
254
261 void clear()
262 {
263 for (size_t i = 0; i < m_; ++i)
264 registers_(i) = 0;
265 }
266
273 [[nodiscard]] size_t num_registers() const noexcept { return m_; }
274 };
275} // namespace Aleph
276
277# endif // HYPERLOGLOG_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
long double w
Definition btreepic.C:153
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
HyperLogLog cardinality estimator.
Definition hyperloglog.H:69
double estimate() const noexcept
Estimate current cardinality.
HyperLogLog(HyperLogLog &&other)
Take the registers of another estimator, which is left as an empty estimator of the same precision.
Array< uint8_t > registers_
Max leading zeros observed per bucket.
Definition hyperloglog.H:73
HyperLogLog(const uint8_t b=12)
Construct with precision parameter.
static size_t compute_m_or_throw(const uint8_t b)
Validate b and compute m = 2^b.
Definition hyperloglog.H:88
void clear()
Reset all registers to zero.
HyperLogLog & operator=(const HyperLogLog &other)=default
Copy the precision and the registers of another estimator.
double alpha_m_
Bias correction constant.
Definition hyperloglog.H:72
static uint64_t hash64(const T &val) noexcept
Compute 64-bit hash using MurmurHash3.
Definition hyperloglog.H:78
static double compute_alpha(const size_t m) noexcept
Compute bias-correction constant alpha_m from Flajolet et al.
Definition hyperloglog.H:98
void merge(const HyperLogLog &other)
Merge another HyperLogLog into this one (union of sets).
void swap(HyperLogLog &other) noexcept
Exchange in O(1) the state of this estimator and another.
void update(const T &val)
Add an element to the set.
size_t m_
Number of registers (2^b_).
Definition hyperloglog.H:71
size_t num_registers() const noexcept
Number of HyperLogLog registers (2^b).
uint8_t b_
Number of bits for bucket index.
Definition hyperloglog.H:70
HyperLogLog(const HyperLogLog &other)=default
Copy the precision and the registers of another estimator.
Standard hash functions for Aleph types.
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
size_t murmur3hash(const Key &key, std::uint32_t seed)
Definition hash-fct.H:361
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dynamic array container with automatic resizing.