Skip to content

Sample a stream of unknown length

A reservoir sampler keeps a uniform sample of fixed size, however many items pass through.

import {
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
} from 'knotkit/prng'
import {
function reservoirSampler<T>(random: RandomSource, capacity: number): ReservoirSampler<T>

Create a uniform reservoir sampler over a stream of unknown length.

Vitter's Algorithm R: the first capacity values fill the reservoir, and the n-th value after that replaces a uniformly drawn slot with probability capacity / n. One draw per value past the reservoir keeps every observed value at inclusion probability capacity / n after each one.

The sampler accepts at most 2^32 values, the same population bound sampleIndices accepts, because the slot draw for the n-th value asks uniformInt for a bound of n.

Replaying the same values against the same source state reproduces every replacement and every snapshot.

@param ― random - Function returning values in [0, 1).

@param ― capacity - The maximum number of retained values, from 0 through 2^32 - 1.

@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when capacity is not a safe integer in 0..2^32 - 1. Validation happens before the source is ever called.

reservoirSampler
} from 'knotkit/sampling'
const
const sampler: ReservoirSampler<string>
sampler
=
reservoirSampler<string>(random: RandomSource, capacity: number): ReservoirSampler<string>

Create a uniform reservoir sampler over a stream of unknown length.

Vitter's Algorithm R: the first capacity values fill the reservoir, and the n-th value after that replaces a uniformly drawn slot with probability capacity / n. One draw per value past the reservoir keeps every observed value at inclusion probability capacity / n after each one.

The sampler accepts at most 2^32 values, the same population bound sampleIndices accepts, because the slot draw for the n-th value asks uniformInt for a bound of n.

Replaying the same values against the same source state reproduces every replacement and every snapshot.

@param ― random - Function returning values in [0, 1).

@param ― capacity - The maximum number of retained values, from 0 through 2^32 - 1.

@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when capacity is not a safe integer in 0..2^32 - 1. Validation happens before the source is ever called.

reservoirSampler
<string>(
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
(7), 3)
for (const
const request: string
request
of ['GET /', 'GET /a', 'POST /b', 'GET /c', 'GET /d', 'PUT /e']) {
const sampler: ReservoirSampler<string>
sampler
.
ReservoirSampler<string>.add: (value: string) => void

Observe one stream value, retaining it with probability capacity / seenCount() once the reservoir has filled. O(1) amortized.

Consumes no draw for the first capacity values and exactly one uniformInt draw for every value after them, including any rejection draws uniformInt performs internally. A sampler of capacity zero never draws. When this throws, the value was not observed: seenCount() and snapshot() are left as they were.

@throws ― {SamplingInvalidInputError} With code STREAM_LIMIT_EXCEEDED when the sampler has already observed 2^32 values.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

add
(
const request: string
request
)
}
const sampler: ReservoirSampler<string>
sampler
.
ReservoirSampler<string>.snapshot(): readonly string[]

A fresh copy of the retained values in slot order. O(capacity).

Slot order is deterministic under replay, but it is neither stream order nor a uniformly random order; pass the result through shuffled when a random order matters. Values are held by reference and never cloned. Consumes no draw and leaves the sampler unchanged, and mutating the returned array does not affect it.

snapshot
() // ['PUT /e', 'GET /c', 'POST /b']

Every item seen so far has the same chance of being in the sample. Memory is the sample size, not the stream length.

Modules: knotkit/sampling · knotkit/prng · API reference