Suppose firmware for a wind-turbine microcontroller with 4 KB of free memory (an assumed figure) has to monitor a CAN-bus telemetry stream of frames per second, frames per day. The stream cannot be stored, a set or dict of all IDs would not fit, and the stream length is not known in advance. Streaming algorithms handle four such tasks with a fixed amount of memory and one pass (Mental Move #22: Summarize Infinite Streams with One-Sided Sketches): (1) Vitter’s Reservoir Sampling (information_streams.vitter_reservoir_sample) maintains an exact uniform sample of frames without knowing ; (2) Bloom Filters (information_streams.bloom_filter_simulate) block duplicate packet IDs in ~10 bits/item with no false negatives; (3) Count-Min Sketches (information_streams.count_min_sketch_frequencies) isolate heavy-hitter vibration spikes with strict one-sided error ; and (4) HyperLogLog / trailing-zero sketches count millions of distinct IDs in 64 bytes.
Learning objectives¶
Prove and verify the inductive uniformity invariant of Vitter’s Algorithm R (
information_streams.vitter_reservoir_sample) across arbitrary unknown stream lengths.Derive the Bloom Filter false-positive curve , locate the optimal hash count (
information_streams.bloom_filter_simulate), and verify exact zero false negatives.Track Zipfian heavy-hitter frequencies in fixed RAM via
information_streams.count_min_sketch_frequenciesand verify the one-sided Markov error bound .Implement deterministic Misra-Gries frequent-items summaries and compare HyperLogLog register RAM against linear
setgrowth.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Exact Uniform Sampling Without Knowing : Vitter’s Reservoir Algorithm R¶
How do you pick items uniformly at random from a stream when is unknown until the stream ends? Vitter’s (1985) Algorithm R (information_streams.vitter_reservoir_sample) initializes reservoir . Upon seeing item (, 0-indexed, so items seen so far), draw integer ; if , overwrite reservoir[j] = x_t.
Inductive Invariant Proof ()¶
Base case (): Every one of the first items is in with probability .
Inductive step (): Newcomer enters iff , which occurs with exact probability . Any existing member (present with probability by induction) is evicted iff lands on its specific slot (probability ). Hence survives with probability:
Every telescoping denominator cancels cleanly.
heading("Demonstration 1: Vitter's reservoir sampling empirical uniformity and O(k) memory")
n_stream = 50
k_res = 5
n_trials = 5000
stream_ids = np.arange(n_stream)
inclusion_counts = np.zeros(n_stream, dtype=int)
for tr in range(n_trials):
samp = information_streams.vitter_reservoir_sample(stream_ids, k_sample=k_res, seed=10000 + tr)
inclusion_counts[samp] += 1
emp_probs = inclusion_counts / float(n_trials)
exact_p = k_res / float(n_stream)
max_dev = float(np.max(np.abs(emp_probs - exact_p)))
print(f"Stream length N = {n_stream}, Reservoir k = {k_res}, Monte Carlo runs = {n_trials}")
print(f"Theoretical inclusion probability k/N = {exact_p:.4f}")
print(f"Empirical min / mean / max inclusion = {np.min(emp_probs):.4f} / {np.mean(emp_probs):.4f} / {np.max(emp_probs):.4f} (max |err| = {max_dev:.4f})")
assert np.isclose(np.mean(emp_probs), exact_p, atol=1e-12)
assert max_dev < 0.022 # within ~3*sqrt(0.1*0.9/5000) = 0.0127 binomial standard error
# Telescoping analytical trace of item i=0, i=12, i=30 survival probability vs. stream index t:
t_axis = np.arange(k_res, n_stream + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.bar(stream_ids, emp_probs, color="#2166AC", edgecolor="white", width=0.82, alpha=0.85, label="Empirical $\\hat{p}_i$ (5,000 runs)")
ax1.axhline(exact_p, color="r", ls="--", lw=2.0, label=f"Exact uniform $k/N = {exact_p:.2f}$")
ax1.set_ylim(0.0, 0.16)
ax1.set_xlabel("Arrival position $i$ in stream ($0 \\dots 49$)")
ax1.set_ylabel("Final inclusion probability")
ax1.set_title("Inclusion frequency by arrival position")
ax1.legend(fontsize=8.3)
for item_i, col, lbl in [(0, "#2E8B57", "Early item $i=0$"), (14, "#7B4FA3", "Mid item $i=14$"), (34, "#E08214", "Late item $i=34$")]:
t_valid = np.arange(max(k_res, item_i + 1), n_stream + 1)
ax2.plot(t_valid, k_res / t_valid.astype(float), lw=2.2, color=col, label=lbl)
ax2.axhline(exact_p, color="k", ls=":", lw=1.4, label=f"Common endpoint $k/N = {exact_p:.2f}$")
ax2.set_xlabel("Items observed so far $t$")
ax2.set_ylabel("Probability item $i$ is in $R_t$")
ax2.set_title("Inclusion probability $k/t$ during the stream")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Demonstration 1: Vitter's reservoir sampling empirical uniformity and O(k) memory
=================================================================================
Stream length N = 50, Reservoir k = 5, Monte Carlo runs = 5000
Theoretical inclusion probability k/N = 0.1000
Empirical min / mean / max inclusion = 0.0900 / 0.1000 / 0.1118 (max |err| = 0.0118)

Figure 13.1. Reservoir sampling with from a stream of 50 items. (a) Inclusion frequency of each item over 5,000 runs; all lie close to . (b) Exact inclusion probability of three items against the number of items seen; all reach at the end.
What Demonstration 1 shows. In the right panel, item enters with probability 1 and survives many gentle attrition steps, while late item enters with small probability and undergoes far fewer attrition steps—yet at every stopping time all curves lie on the same line , with only items held in memory. The empirical inclusion frequencies over 5000 runs range from 0.090 to 0.112 around .
2. Bloom Filters (bloom_filter_simulate) & The Optimal Hash Count ¶
Suppose an edge gateway must suppress duplicate distress-packet UUIDs ( unique packets) using only ()—far too small to store UUID strings (). Burton Bloom’s (1970) Filter allocates an -bit array initialized to False and hashes each inserted key to bit positions , setting those bits to True.
Zero False Negatives (): If was inserted, all of its bits remain
Trueforever.False Positive Tradeoff: After insertions, the fraction of bits still
Falseis , so an unseen query finds all of its probed bitsTrueby coincidence with probability:
Too few hashes () suffer frequent single-bit collisions; too many hashes () clobber the bit array toward ones. Differentiating shows the unique global minimum occurs when exactly of the bits are set ():
heading("Demonstration 2: Bloom filter hash-count U-curve and guaranteed zero false negatives")
n_ins = 800
m_bits = 8000 # m / n = 10.0 bits per item (= 1,000 bytes of SRAM)
ins_packets = [f"PKT-{i:06d}" for i in range(n_ins)]
neg_queries = [f"NEW-{j:06d}" for j in range(3000)]
all_queries = ins_packets + neg_queries
k_sweep = list(range(1, 17))
emp_fpr_list, theo_fpr_list, fill_frac_list, fn_list = [], [], [], []
for kv in k_sweep:
res_bf = information_streams.bloom_filter_simulate(ins_packets, all_queries, m_bits=m_bits, k_hashes=kv)
emp_fpr_list.append(100.0 * res_bf["empirical_fpr"])
theo_fpr_list.append(100.0 * res_bf["theoretical_fpr"])
fill_frac_list.append(100.0 * res_bf["bits_set_fraction"])
fn_list.append(res_bf["false_negatives"])
res_auto = information_streams.bloom_filter_simulate(ins_packets, all_queries, m_bits=m_bits, k_hashes=None)
k_star_theory = (m_bits / n_ins) * math.log(2.0)
print(f"Bit budget m/n = {m_bits/n_ins:.1f} bits/item -> Analytical k* = (m/n) ln 2 = {k_star_theory:.2f} (auto-selected k = {res_auto['k_hashes']})")
print(f"At optimal k = {res_auto['k_hashes']}: bit fill = {100*res_auto['bits_set_fraction']:.1f}% (~50%), empirical FPR = {100*res_auto['empirical_fpr']:.2f}% (theory = {100*res_auto['theoretical_fpr']:.2f}%)")
print(f"Total false negatives across all 16 hash settings (12,800 positive queries): {sum(fn_list)}")
assert sum(fn_list) == 0 and res_auto["k_hashes"] == 7
assert emp_fpr_list[6] < emp_fpr_list[0] and emp_fpr_list[6] < emp_fpr_list[-1]
assert 48.0 < fill_frac_list[6] < 53.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(k_sweep, theo_fpr_list, "k--", lw=2.0, label="Theory $(1 - e^{-kn/m})^k$")
ax1.plot(k_sweep, emp_fpr_list, "b-o", ms=5, lw=2.1, label="Empirical FPR (3,000 unseen IDs)")
ax1.axvline(k_star_theory, color="r", ls=":", lw=1.6, label=f"$k^\\star = (m/n)\\ln 2 = {k_star_theory:.2f}$")
ax1.set_xlabel("Number of hash functions $k$")
ax1.set_ylabel("False-positive rate [%]")
ax1.set_title("False-positive rate ($m/n = 10$ bits per item)")
ax1.legend(fontsize=8.2)
ax2.plot(k_sweep, fill_frac_list, "g-s", ms=5, lw=2.1, label="Fraction of bits set to 1 [%]")
ax2.axhline(50.0, color="r", ls="--", lw=1.6, label="Maximum-entropy $50\\%$ bit density at $k^\\star$")
ax2.axvline(k_star_theory, color="k", ls=":", lw=1.4)
ax2.set_xlabel("Number of hash functions $k$")
ax2.set_ylabel("Bit-array saturation [%]")
ax2.set_title("Fraction of bits set")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Demonstration 2: Bloom filter hash-count U-curve and guaranteed zero false negatives
====================================================================================
Bit budget m/n = 10.0 bits/item -> Analytical k* = (m/n) ln 2 = 6.93 (auto-selected k = 7)
At optimal k = 7: bit fill = 50.0% (~50%), empirical FPR = 0.70% (theory = 0.82%)
Total false negatives across all 16 hash settings (12,800 positive queries): 0

Figure 13.2. Bloom filter with 10 bits per item. (a) False-positive rate against the number of hash functions: theory (dashed) and 3,000 queries of unseen IDs (points); the minimum lies near . (b) Fraction of bits set, which passes 50 % at .
What Demonstration 2 shows. At the bit array is ones, and the measured false-positive rate is against from Eq. (2.1). Referring back to Lecture 12, an -bit array carries its maximum possible Shannon information () only when half its bits are 1 and half are 0.
3. Count-Min Sketch (count_min_sketch_frequencies): Heavy Hitters in Fixed RAM¶
A Bloom filter answers membership (seen before?), but what if we need event frequencies (e.g., spotting the top 5 chattering CAN-bus fault codes out of millions of IDs)? Cormode & Muthukrishnan’s (2005) Count-Min Sketch maintains a tiny integer matrix :
Update(): Increment in every row .
Query(): Return .
Because hash collisions only add non-negative counts from other items, obeys a strict one-sided invariant (). Choosing width guarantees by Markov’s inequality on each row () and independence across rows that:
heading("Demonstration 3: Count-min sketch on Zipfian fault streams and one-sided error scaling")
rng_cms = np.random.default_rng(1303)
n_distinct = 500
ranks = np.arange(1, n_distinct + 1, dtype=float)
zipf_probs = (ranks ** (-1.15)) / np.sum(ranks ** (-1.15))
n_events = 12000
sampled_idx = rng_cms.choice(n_distinct, size=n_events, p=zipf_probs)
stream_codes = [f"ERR-{idx:04d}" for idx in sampled_idx]
cms_res = information_streams.count_min_sketch_frequencies(stream_codes, width_w=128, depth_d=4)
top12_codes = [f"ERR-{i:04d}" for i in range(12)]
true_top12 = [cms_res["exact_counts"].get(c, 0) for c in top12_codes]
est_top12 = [cms_res["estimates"].get(c, 0) for c in top12_codes]
print(f"Stream N = {n_events} events across {len(cms_res['exact_counts'])} active fault codes; CMS table = 4 x 128 = 512 counters")
print(f"Min overestimate = {cms_res['min_overestimate']} (must be >= 0), mean = {cms_res['mean_overestimate']:.2f}, max = {cms_res['max_overestimate']} (bound e*N/w = {cms_res['epsilon_bound_per_N']*n_events:.1f})")
assert cms_res["min_overestimate"] >= 0
assert cms_res["max_overestimate"] <= cms_res["epsilon_bound_per_N"] * n_events
# Sweep CMS width w in [32, 64, 128, 256, 512] and compare empirical 99th-percentile / mean error vs e/w:
widths = [32, 64, 128, 256, 512]
mean_err_frac, max_err_frac, markov_bound = [], [], []
for wv in widths:
r_w = information_streams.count_min_sketch_frequencies(stream_codes, width_w=wv, depth_d=4)
assert r_w["min_overestimate"] >= 0
mean_err_frac.append(r_w["mean_overestimate"] / n_events)
max_err_frac.append(r_w["max_overestimate"] / n_events)
markov_bound.append(r_w["epsilon_bound_per_N"])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
x12 = np.arange(12)
ax1.bar(x12 - 0.18, true_top12, width=0.35, color="#2E8B57", edgecolor="k", label="Exact count $f_i$")
ax1.bar(x12 + 0.18, est_top12, width=0.35, color="#2166AC", edgecolor="k", label="CMS estimate $\\hat{f}_i \\geq f_i$ ($4\\times 128$)")
ax1.set_xticks(x12)
ax1.set_xticklabels([f"#{i}" for i in range(12)])
ax1.set_xlabel("Heavy-hitter fault rank")
ax1.set_ylabel("Event count in 12,000-frame window")
ax1.set_title("Heavy hitters with 512 counters")
ax1.legend(fontsize=8.2)
ax2.loglog(widths, markov_bound, "k--", lw=2.0, label="Markov bound $\\epsilon = e / w$")
ax2.loglog(widths, max_err_frac, "r-s", ms=5, lw=2.0, label="Max normalized error $(\\hat{f} - f)/N$")
ax2.loglog(widths, mean_err_frac, "b-o", ms=5, lw=2.1, label="Mean normalized error")
ax2.set_xlabel("Count-min sketch table width $w$ (log scale)")
ax2.set_ylabel("Normalized additive error $/ N$ (log scale)")
ax2.set_title("Error against table width")
ax2.legend(fontsize=8.2)
log_ticks(ax2, "x", [32, 64, 128, 256, 512])
label_panels(fig)
plt.show()
Demonstration 3: Count-min sketch on Zipfian fault streams and one-sided error scaling
======================================================================================
Stream N = 12000 events across 487 active fault codes; CMS table = 4 x 128 = 512 counters
Min overestimate = 0 (must be >= 0), mean = 13.34, max = 157 (bound e*N/w = 254.8)

Figure 13.3. Count–min sketch on a synthetic Zipf stream of 12,000 events. (a) Exact and estimated counts of the twelve most frequent codes with 4 × 128 counters; no estimate is low. (b) Maximum and mean error per event against the table width , with the bound (dashed), which holds with high probability, not for every item.
What Demonstration 3 shows. In this synthetic Zipf stream the additive bound (254.8 counts) is small compared with the most frequent code (), and the largest measured overestimate is 157 counts. The heavy hitters therefore stand well above the collision noise, with 512 counters (2 KB at 4 bytes per counter).
4. Distinct-Element Cardinality in 64 Bytes: HyperLogLog Trailing-Zero Intuition¶
How can a router count 107 distinct sensor IDs with a few hundred bytes instead of megabytes of hash-set keys? Flajolet, Fusy, Gandouet & Meunier’s (2007) HyperLogLog (HLL) uses a simple fact: in uniformly hashed 64-bit integers, only 1 in distinct hashes begins with leading zeros followed by a 1.
Use the top bits of the hash to route each item into one of independent sub-stream registers (just 64 bytes total).
Store the maximum position of the first
1-bit seen in the remaining 58 bits of each bucket.Combine the noisy exponential estimators via their harmonic mean (which suppresses outlier single-hash jackpots):
heading("Demonstration 4: 64-byte HyperLogLog cardinality sketch against exact set memory growth")
import hashlib
def hyperloglog_64byte_estimate(items: list[str], b_bits: int = 6) -> tuple[float, int]:
"""Pure-Python 64-register HyperLogLog distinct-count estimator using 64-bit SHA-256 prefixes."""
m = 1 << b_bits
alpha_m = 0.709 if m == 64 else 0.7213 / (1.0 + 1.079 / m)
regs = np.zeros(m, dtype=np.uint8)
rem_bits = 64 - b_bits
mask_rem = (1 << rem_bits) - 1
for s in items:
h64 = int.from_bytes(hashlib.sha256(s.encode("utf-8")).digest()[:8], "big")
bucket = h64 >> rem_bits
w = h64 & mask_rem
rho = (rem_bits - w.bit_length()) + 1 if w > 0 else (rem_bits + 1)
if rho > regs[bucket]:
regs[bucket] = rho
raw_est = alpha_m * (m * m) / float(np.sum(2.0 ** (-regs.astype(float))))
# Small-range linear-counting correction when empty registers remain:
zeros = int(np.sum(regs == 0))
if raw_est <= 2.5 * m and zeros > 0:
raw_est = m * math.log(m / float(zeros))
return raw_est, int(regs.nbytes)
card_targets = [100, 300, 1000, 3000, 8000, 20000]
hll_estimates, exact_ram_bytes, hll_ram_bytes = [], [], []
all_unique_pool = [f"DEV-NODE-{i:07d}" for i in range(card_targets[-1])]
for n_true in card_targets:
# Add duplicate bursts so total stream length > n_true (verifying idempotence on duplicates):
sub_stream = all_unique_pool[:n_true] + all_unique_pool[: min(n_true, 500)]
est_n, hll_b = hyperloglog_64byte_estimate(sub_stream, b_bits=6)
exact_set = set(sub_stream)
# Approximate memory footprint of exact set (hash table + 16-char ID payloads):
set_bytes = sys.getsizeof(exact_set) + len(exact_set) * 64 if "sys" in globals() else len(exact_set) * 72
hll_estimates.append(est_n)
hll_ram_bytes.append(hll_b)
exact_ram_bytes.append(len(exact_set) * 72)
rel_errs = [abs(e - t) / t for e, t in zip(hll_estimates, card_targets)]
print(f"64-Register HLL RAM = {hll_ram_bytes[-1]} bytes (constant) vs. Exact ID Set at N=20,000 = {exact_ram_bytes[-1]/1024:.1f} KB ({exact_ram_bytes[-1]//hll_ram_bytes[-1]}x larger)")
print(f"Mean relative cardinality error across {card_targets}: {100*np.mean(rel_errs):.2f}% (theoretical 1.04/sqrt(64) = 13.0%)")
assert all(b == 64 for b in hll_ram_bytes)
assert max(rel_errs) < 0.25 and np.mean(rel_errs) < 0.14
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.loglog(card_targets, card_targets, "k--", lw=1.8, label="Exact cardinality $N$")
ax1.loglog(card_targets, hll_estimates, "b-o", ms=6, lw=2.2, label="64-byte HyperLogLog $\\hat{N}$")
ax1.set_xlabel("True distinct device IDs $N$")
ax1.set_ylabel("Estimated distinct IDs $\\hat{N}$")
ax1.set_title("Distinct count with 64 registers")
ax1.legend(fontsize=8.3)
ax2.loglog(card_targets, np.array(exact_ram_bytes) / 1024.0, "r-s", ms=5, lw=2.2, label="Exact set ($\\mathcal{O}(N)$ memory)")
ax2.loglog(card_targets, np.array(hll_ram_bytes) / 1024.0, "g-^", ms=6, lw=2.2, label="HyperLogLog RAM ($0.0625$ KB flat)")
ax2.set_xlabel("True distinct device IDs $N$")
ax2.set_ylabel("Memory footprint [KB, log scale]")
ax2.set_title("Memory of an exact set and of the sketch")
ax2.legend(fontsize=8.3)
label_panels(fig)
plt.show()
Demonstration 4: 64-byte HyperLogLog cardinality sketch against exact set memory growth
=======================================================================================
64-Register HLL RAM = 64 bytes (constant) vs. Exact ID Set at N=20,000 = 1406.2 KB (22500x larger)
Mean relative cardinality error across [100, 300, 1000, 3000, 8000, 20000]: 6.23% (theoretical 1.04/sqrt(64) = 13.0%)

Figure 13.4. HyperLogLog with 64 one-byte registers. (a) Estimated against true number of distinct IDs. (b) Memory of an exact set against the constant 64 bytes of the sketch.
What Demonstration 4 shows.
With 64 one-byte registers, the mean relative error over the six stream lengths is , within the standard error expected for one estimate. An exact set of the 20,000 IDs takes about 1.4 MB.
Inside the algorithm¶
We inspect all three core streaming primitives in information_streams (vitter_reservoir_sample, bloom_filter_simulate, and count_min_sketch_frequencies) and replace the Monte Carlo check of Demonstration 1 with an exact propagation of the inclusion probabilities, exact_markov_reservoir_probabilities(N, k), that reproduces Vitter’s to rounding error ().
Check against the library¶
heading("Inside the algorithm: Reservoir, Bloom and count-min source + exact Markov uniformity check")
print(show_source(information_streams.vitter_reservoir_sample))
print(show_source(information_streams.bloom_filter_simulate))
print(show_source(information_streams.count_min_sketch_frequencies))
def exact_markov_reservoir_probabilities(n_total: int, k_sample: int) -> np.ndarray:
"""Propagate exact deterministic inclusion probabilities p_i(t) step-by-step for t = 0 .. n_total-1."""
assert 1 <= k_sample <= n_total
p_in = np.zeros(n_total, dtype=np.float64)
p_in[:k_sample] = 1.0
for t in range(k_sample, n_total):
# Step t sees (t + 1)-th item (0-indexed):
# - New item t enters with probability k / (t + 1)
# - Each prior item in reservoir is evicted with probability (k / (t + 1)) * (1 / k) = 1 / (t + 1)
p_in[:t] *= 1.0 - 1.0 / float(t + 1)
p_in[t] = float(k_sample) / float(t + 1)
return p_in
p_markov = exact_markov_reservoir_probabilities(n_total=128, k_sample=11)
target_p = 11.0 / 128.0
max_mach_err = float(np.max(np.abs(p_markov - target_p)))
print(f"Exact Markov chain propagation (N=128, k=11): target k/N = {target_p:.16f}")
print(f"Max |p_i(N) - k/N| across all 128 stream positions = {max_mach_err:.3e}")
assert np.allclose(p_markov, target_p, rtol=1e-15, atol=1e-15)
assert np.isclose(np.sum(p_markov), 11.0, rtol=1e-15, atol=1e-15)
Inside the algorithm: Reservoir, Bloom and count-min source + exact Markov uniformity check
===========================================================================================
def vitter_reservoir_sample(stream: np.ndarray, k_sample: int, seed: int = 42) -> np.ndarray:
"""Draw an exact uniform subset of size k_sample in one O(N) pass and O(k) memory via Vitter's Algorithm R."""
arr = np.asarray(stream).ravel()
k = int(k_sample)
if k < 1 or k > arr.size:
raise ValueError("Require 1 <= k_sample <= len(stream).")
rng = np.random.default_rng(seed)
reservoir = arr[:k].copy()
for t in range(k, arr.size):
j = int(rng.integers(0, t + 1))
if j < k:
reservoir[j] = arr[t]
return reservoir
def bloom_filter_simulate(
items_insert: list[str],
items_query: list[str],
m_bits: int,
k_hashes: int | None = None,
) -> dict:
"""Simulate a m_bits Bloom Filter with optimal or user-specified k_hashes; verifies zero false negatives."""
n_ins = len(set(items_insert))
if m_bits < 8 or n_ins < 1:
raise ValueError("Require m_bits >= 8 and at least one inserted item.")
k = max(1, round((m_bits / n_ins) * math.log(2.0))) if k_hashes is None else int(k_hashes)
if k < 1:
raise ValueError("k_hashes must be >= 1.")
bits = np.zeros(int(m_bits), dtype=bool)
inserted_truth = set(items_insert)
for item in items_insert:
for pos in _double_hash_positions(item, int(m_bits), k):
bits[pos] = True
fp = 0
fn = 0
neg_queries = 0
for q in items_query:
present_est = all(bool(bits[pos]) for pos in _double_hash_positions(q, int(m_bits), k))
present_true = q in inserted_truth
if present_true and not present_est:
fn += 1
elif (not present_true) and present_est:
fp += 1
if not present_true:
neg_queries += 1
emp_fpr = (fp / neg_queries) if neg_queries > 0 else 0.0
theo_fpr = (1.0 - math.exp(-k * n_ins / float(m_bits))) ** k
return {
"k_hashes": k,
"bits_set_fraction": float(np.mean(bits)),
"false_positives": fp,
"false_negatives": fn,
"empirical_fpr": emp_fpr,
"theoretical_fpr": theo_fpr,
}
def count_min_sketch_frequencies(stream_items: list[str], width_w: int, depth_d: int) -> dict:
"""Estimate item frequencies in O(w*d) memory via Count-Min Sketch (guaranteed zero underestimation)."""
w = int(width_w)
d = int(depth_d)
if w < 2 or d < 1 or not stream_items:
raise ValueError("Require width_w >= 2, depth_d >= 1, and non-empty stream_items.")
table = np.zeros((d, w), dtype=np.int64)
for item in stream_items:
digest = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
for r in range(d):
col = (h1 + (r + 1) * h2 + 0x9E3779B97F4A7C15 * r) % w
table[r, col] += 1
exact = dict(Counter(stream_items))
estimates: dict[str, int] = {}
errors: list[int] = []
for item, true_c in exact.items():
digest = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
est = min(
int(table[r, (h1 + (r + 1) * h2 + 0x9E3779B97F4A7C15 * r) % w])
for r in range(d)
)
estimates[item] = est
errors.append(est - true_c)
return {
"estimates": estimates,
"exact_counts": exact,
"min_overestimate": min(errors),
"max_overestimate": max(errors),
"mean_overestimate": float(np.mean(errors)),
"epsilon_bound_per_N": math.e / w,
}
Exact Markov chain propagation (N=128, k=11): target k/N = 0.0859375000000000
Max |p_i(N) - k/N| across all 128 stream positions = 6.939e-17
Exercises¶
Worked solutions are in 13_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify the Distributed Merge (Semilattice Join) Property of Bloom Filters: given two overlapping edge-sensor packet sets (500 IDs) and (500 IDs, sharing 200 common IDs so and ), construct bit vectors , , and centralized using identical SHA-256 double hashing (
m_bits = 8192,k_hashes = 7). Provenp.array_equal(b_A | b_B, b_AuB)bit-for-bit, and verify that achieves 0 false negatives on while bounding its false-positive rate relative to .Find how it fails. Diagnose two destructive streaming anti-patterns: (a) Compare Vitter’s
vitter_reservoir_sample(, ) against a naive unscaled replacement loop (reservoir[rng.integers(0, k)] = stream[t]for every ) across runs and verify the exact exponential forgetting formula for ; (b) Sweep Bloom filter bit size downward from to 256 bits (plus excessive hashes) for items to expose catastrophic 100% bit-array saturation.Implement it yourself. Implement
misra_gries_heavy_hitters(stream, k_counters)in pure Python/NumPy maintaining at mostk_counters(item -> count)entries: ifitemis tracked, increment its counter; else if fewer thank_countersitems are tracked, insertitem: 1; else decrement allk_counterscounters by 1 and purge zeros. Prove and verify on both a 10,000-element Zipfian telemetry stream and a worst-case adversarial stream that every decrement step cancels distinct items, guaranteeing and 100% recall of all heavy hitters with .
heading("Self-check for the exercises")
assert max_dev < 0.022 and max_mach_err < 1e-14, "Vitter reservoir uniformity check failed"
assert sum(fn_list) == 0 and res_auto["k_hashes"] == 7, "Bloom filter zero-FN or optimal k* check failed"
assert cms_res["min_overestimate"] >= 0, "Count-Min Sketch one-sided error invariant violated"
assert all(b == 64 for b in hll_ram_bytes), "HyperLogLog constant 64-byte footprint check failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.