Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
reservoir-sampling.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 RESERVOIR_SAMPLING_H
32# define RESERVOIR_SAMPLING_H
33
45# include <chrono>
46# include <cstdint>
47# include <limits>
48# include <memory>
49# include <iterator>
50
51# include <ah-errors.H>
52# include <ah-random.H>
53# include <tpl_array.H>
54
55namespace Aleph
56{
57
74 template <typename T>
76 {
77 size_t k_;
78 size_t n_seen_ = 0;
79 unsigned long seed_;
80 uint64_t rng_min_;
81 uint64_t rng_max_;
82 uint64_t rng_range_;
86 public:
93 explicit Reservoir_Sampler(const size_t k,
94 const unsigned long seed = static_cast<unsigned long>(
95 std::chrono::high_resolution_clock::now().time_since_epoch().count()))
96 : k_(k), seed_(seed), rng_(seed_)
97 {
98 rng_min_ = static_cast<uint64_t>(Gsl_Compatible_Rng::min());
99 rng_max_ = static_cast<uint64_t>(Gsl_Compatible_Rng::max());
100 rng_range_ = rng_max_ - rng_min_ + 1ULL;
101 if (k_ > 0)
102 reservoir_.reserve(k_);
103 }
104
116 : Reservoir_Sampler(other.k_, other.seed_)
117 {
118 swap(other);
119 }
120
128 {
129 swap(other);
130 return *this;
131 }
132
136 void swap(Reservoir_Sampler & other) noexcept
137 {
138 std::swap(k_, other.k_);
139 std::swap(n_seen_, other.n_seen_);
140 std::swap(seed_, other.seed_);
141 std::swap(rng_min_, other.rng_min_);
142 std::swap(rng_max_, other.rng_max_);
143 std::swap(rng_range_, other.rng_range_);
144 reservoir_.swap(other.reservoir_);
145 std::swap(rng_, other.rng_);
146 }
147
157 void update(const T & val)
158 {
159 ah_overflow_error_if(n_seen_ == std::numeric_limits<size_t>::max())
160 << "Reservoir_Sampler::update: stream length exceeded size_t capacity";
161
162 if (k_ == 0)
163 {
164 ++n_seen_;
165 return;
166 }
167
168 if (n_seen_ < k_)
169 reservoir_.append(val);
170 else
171 {
172 // Probability of replacement is k / (n_seen + 1)
173 ah_overflow_error_if(n_seen_ >= std::numeric_limits<unsigned long>::max())
174 << "Reservoir_Sampler::update: stream length exceeds unsigned long capacity";
175
176 // the bound n_seen_ + 1 of uniform_int() is at most
177 // max() - min(), which is rng_range_ - 1
179 << "Reservoir_Sampler::update: stream length exceeds RNG generator range (" << rng_range_ << ")";
180
181 // Exclusive upper bound for the uniform random index in [0, n_seen_]
182 const auto upper_bound = static_cast<unsigned long>(n_seen_ + 1);
183 const size_t j = rng_->uniform_int(upper_bound);
184 if (j < k_)
185 reservoir_(j) = val;
186 }
187 ++n_seen_;
188 }
189
199 template <std::input_iterator Itor, std::sentinel_for<Itor> Sent>
200 void update(Itor beg, Sent end)
201 {
202 while (beg != end)
203 {
204 update(*beg);
205 ++beg;
206 }
207 }
208
213 [[nodiscard]] const Array<T> & get_sample() const noexcept
214 {
215 return reservoir_;
216 }
217
222 [[nodiscard]] size_t total_seen() const noexcept { return n_seen_; }
223
228 [[nodiscard]] size_t sample_size() const noexcept { return k_; }
229
234 [[nodiscard]] uint64_t rng_range() const noexcept { return rng_range_; }
235
243 void set_n_seen_for_testing(const size_t n)
244 {
245 const size_t expected = (n < k_) ? n : k_;
247 << "set_n_seen_for_testing: inconsistent state: "
248 << "n=" << n << ", k=" << k_
249 << ", reservoir.size()=" << reservoir_.size()
250 << " (expected " << expected << ")";
251 n_seen_ = n;
252 }
253
260 void clear()
261 {
262 reservoir_.clear();
263 n_seen_ = 0;
264 rng_->seed(seed_);
265 }
266 };
267
268
285 template <std::input_iterator Itor, std::sentinel_for<Itor> Sent>
286 [[nodiscard]] inline auto
287 reservoir_sample(Itor beg, Sent end, size_t k,
288 unsigned long seed = static_cast<unsigned long>(
289 std::chrono::high_resolution_clock::now().time_since_epoch().count()))
290 {
291 using T = typename std::iterator_traits<Itor>::value_type;
292 Reservoir_Sampler<T> sampler(k, seed);
293 sampler.update(beg, end);
294 return Array<T>(sampler.get_sample());
295 }
296
297} // namespace Aleph
298
299# endif // RESERVOIR_SAMPLING_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
A Gsl_Compatible_Rng in dynamic memory, so that what holds it grows only by a pointer,...
Definition ah-random.H:494
static constexpr result_type max() noexcept
The greatest number of operator()(): 2^32 - 1.
Definition ah-random.H:259
static constexpr result_type min() noexcept
The least number of operator()().
Definition ah-random.H:256
void seed(const unsigned long s) noexcept
Seeds again, as gsl_rng_set(r, s).
Definition ah-random.H:277
unsigned long uniform_int(const unsigned long n)
An integer in [0, n), each with the same probability, as gsl_rng_uniform_int(r, n).
Definition ah-random.H:302
Incremental reservoir sampler (Algorithm R).
size_t sample_size() const noexcept
Target sample size.
uint64_t rng_range_
Cached range of the RNG (max - min + 1).
void update(const T &val)
Process a new element from the stream.
void swap(Reservoir_Sampler &other) noexcept
Exchange in O(1) the state of this sampler and another.
size_t n_seen_
Total elements seen so far.
void clear()
Reset the sampler while keeping k and seed.
const Array< T > & get_sample() const noexcept
Returns the current random sample.
Reservoir_Sampler(const size_t k, const unsigned long seed=static_cast< unsigned long >(std::chrono::high_resolution_clock::now().time_since_epoch().count()))
Initialize sampler.
Reservoir_Sampler(Reservoir_Sampler &&other)
Take the sample and the generator of another sampler, which is left as a new sampler of the same size...
void update(Itor beg, Sent end)
Process multiple elements.
uint64_t rng_min_
Minimum value produced by RNG.
uint64_t rng_range() const noexcept
RNG output range (max - min + 1).
Gsl_Compatible_Rng_Owner rng_
Random number generator.
Array< T > reservoir_
Current random sample.
uint64_t rng_max_
Maximum value produced by RNG.
void set_n_seen_for_testing(const size_t n)
Forcibly set the internal stream counter (for testing only).
Reservoir_Sampler & operator=(Reservoir_Sampler &&other) noexcept
Exchange this sampler with another, which is left with the previous state of this one.
size_t total_seen() const noexcept
Total elements processed so far.
unsigned long seed_
Stored seed for RNG reset.
Minimal std::expected-style result type for C++20.
Main namespace for Aleph-w library functions.
auto reservoir_sample(Itor beg, Sent end, size_t k, unsigned long seed=static_cast< unsigned long >(std::chrono::high_resolution_clock::now().time_since_epoch().count()))
Convenience function to sample k elements from a range.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
Itor upper_bound(Itor beg, Itor end, const T &value)
Find upper bound in a sorted range.
Definition ahAlgo.H:1239
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Dynamic array container with automatic resizing.