Worked solutions to the three exercises of Lecture 13. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. 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). Prove np.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 .
heading("Exercise 1: Bit-for-bit Bloom filter union homomorphism BF(A u B) == BF(A) | BF(B)")
m_e1 = 8192
k_e1 = 7
set_a = [f"SNS-{i:05d}" for i in range(0, 500)]
set_b = [f"SNS-{i:05d}" for i in range(300, 800)] # Overlap on 300..499 (200 items); union 0..799 (800 items)
union_ab = sorted(set(set_a) | set(set_b))
inter_ab = sorted(set(set_a) & set(set_b))
probe_neg = [f"OUTSIDER-{j:05d}" for j in range(2500)]
def build_bf_bits(items: list[str], m: int, k: int) -> np.ndarray:
bits = np.zeros(m, dtype=bool)
for x in items:
for pos in information_streams._double_hash_positions(x, m, k):
bits[pos] = True
return bits
def query_bf_bits(bits: np.ndarray, q: str, k: int) -> bool:
m = bits.size
return all(bool(bits[pos]) for pos in information_streams._double_hash_positions(q, m, k))
bits_a = build_bf_bits(set_a, m_e1, k_e1)
bits_b = build_bf_bits(set_b, m_e1, k_e1)
bits_union_direct = build_bf_bits(union_ab, m_e1, k_e1)
bits_or_merged = bits_a | bits_b
bits_and_approx = bits_a & bits_b
bits_inter_direct = build_bf_bits(inter_ab, m_e1, k_e1)
bit_exact_union = bool(np.array_equal(bits_or_merged, bits_union_direct))
fn_inter_and = sum(1 for x in inter_ab if not query_bf_bits(bits_and_approx, x, k_e1))
fpr_or = np.mean([query_bf_bits(bits_or_merged, q, k_e1) for q in probe_neg])
fpr_and = np.mean([query_bf_bits(bits_and_approx, q, k_e1) for q in probe_neg])
fpr_inter_direct = np.mean([query_bf_bits(bits_inter_direct, q, k_e1) for q in probe_neg])
print(f"Bitwise equality BF(A) | BF(B) == BF(A u B) across all {m_e1} bits: {bit_exact_union}")
print(f"Merged Union FPR = {100*fpr_or:.3f}% | Bitwise-AND Intersection FN on A n B = {fn_inter_and}")
print(f"Intersection FPR : Bitwise AND (b_A & b_B) = {100*fpr_and:.3f}% vs. fresh BF(A n B) = {100*fpr_inter_direct:.4f}%")
assert bit_exact_union
assert fn_inter_and == 0
assert np.all(bits_and_approx >= bits_inter_direct) # b_A & b_B is a superset bitmask of BF(A n B)
assert fpr_inter_direct <= fpr_and < fpr_or
fig, ax = plt.subplots(figsize=(7.6, 3.9))
labels_bf = ["Node A\n($|A|=500$)", "Node B\n($|B|=500$)", "Merged OR\n$\\mathbf{b}_A \\vee \\mathbf{b}_B$",
"Centralized\n$\\mathrm{BF}(A \\cup B)$", "Bitwise AND\n$\\mathbf{b}_A \\wedge \\mathbf{b}_B$", "Direct\n$\\mathrm{BF}(A \\cap B)$"]
ones_pct = [100 * np.mean(b) for b in [bits_a, bits_b, bits_or_merged, bits_union_direct, bits_and_approx, bits_inter_direct]]
cols_bf = ["#2166AC", "#2166AC", "#2E8B57", "#2E8B57", "#E08214", "#7B4FA3"]
ax.bar(labels_bf, ones_pct, color=cols_bf, edgecolor="k", alpha=0.88)
ax.set_ylabel("Percentage of 8,192 bits set to 1 [%]")
ax.set_title("Bits set: nodes, merged and central filters")
plt.show()
Exercise 1: Bit-for-bit Bloom filter union homomorphism BF(A u B) == BF(A) | BF(B)
==================================================================================
Bitwise equality BF(A) | BF(B) == BF(A u B) across all 8192 bits: True
Merged Union FPR = 0.400% | Bitwise-AND Intersection FN on A n B = 0
Intersection FPR : Bitwise AND (b_A & b_B) = 0.000% vs. fresh BF(A n B) = 0.0000%

Figure S13.1. Percentage of bits set in Bloom filters for two nodes, for their OR-merge, for a filter built centrally on the union, and for intersections. The OR-merge and the central filter are identical.
Explanation. Setting bits in a Bloom filter is an idempotent, commutative, associative join : inserting maps and updates . Therefore holds identically without approximation. Intersections are different: contains , so it has no false negatives, but bits set by elements outside the intersection can raise its false-positive rate above that of a freshly built . In this example both rates are zero.
Exercise 2¶
Problem. 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.
heading("Exercise 2: Exponential memory decay in naive reservoir sampling and Bloom filter saturation")
# --- Part A: Naive constant-rate reservoir replacement vs. Vitter's Algorithm R ---
n_s, k_s, n_mc_r = 40, 5, 4000
arr_s = np.arange(n_s)
cnt_vitter = np.zeros(n_s, dtype=int)
cnt_naive = np.zeros(n_s, dtype=int)
for tr in range(n_mc_r):
cnt_vitter[information_streams.vitter_reservoir_sample(arr_s, k_s, seed=2000 + tr)] += 1
rng_b = np.random.default_rng(2000 + tr)
res_bug = arr_s[:k_s].copy()
for t in range(k_s, n_s):
# BUG: Unconditionally overwriting a random slot at every step t >= k
res_bug[int(rng_b.integers(0, k_s))] = arr_s[t]
cnt_naive[res_bug] += 1
p_vit = cnt_vitter / float(n_mc_r)
p_bug = cnt_naive / float(n_mc_r)
p_bug_theory = np.array([
((1.0 - 1.0 / k_s) ** (n_s - k_s)) if i < k_s else ((1.0 - 1.0 / k_s) ** (n_s - 1 - i))
for i in range(n_s)
])
print(f"[Part A] Early item i=0 inclusion : Vitter = {p_vit[0]:.4f} (exact 0.1250) vs. Naive Bug = {p_bug[0]:.5f} (theory {p_bug_theory[0]:.5f})")
print(f" Final item i=39 inclusion: Vitter = {p_vit[-1]:.4f} (exact 0.1250) vs. Naive Bug = {p_bug[-1]:.4f} (exact 1.0000)")
assert p_bug[0] < 0.003 and np.isclose(p_bug[-1], 1.0, atol=1e-12)
assert np.allclose(p_bug, p_bug_theory, atol=0.025)
# --- Part B: Saturating a Bloom Filter (cramped m or excessive k = 18) ---
ins_800 = [f"ID-{i:05d}" for i in range(800)]
q_neg_2000 = [f"UNSEEN-{j:05d}" for j in range(2000)]
m_grid = [8000, 4000, 2000, 1000, 512, 256]
fpr_opt_k, fpr_k18, fill_k18 = [], [], []
for mv in m_grid:
r_ok = information_streams.bloom_filter_simulate(ins_800, q_neg_2000, m_bits=mv, k_hashes=None)
r_bad = information_streams.bloom_filter_simulate(ins_800, q_neg_2000, m_bits=mv, k_hashes=18)
fpr_opt_k.append(100.0 * r_ok["empirical_fpr"])
fpr_k18.append(100.0 * r_bad["empirical_fpr"])
fill_k18.append(100.0 * r_bad["bits_set_fraction"])
print(f"[Part B] At m=512 bits, n=800 items, k=18 hashes: bit fill = {fill_k18[-2]:.2f}%, empirical FPR = {fpr_k18[-2]:.2f}%")
assert fill_k18[-2] > 99.9 and fpr_k18[-2] > 99.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(arr_s, p_vit, "b-o", ms=4, lw=1.9, label="Vitter algorithm R ($k/(t+1)$ decay)")
ax1.plot(arr_s, p_bug, "r-s", ms=4, lw=1.9, label="Naive unscaled overwrite (recency bias)")
ax1.plot(arr_s, p_bug_theory, "k:", lw=1.6, label="Exact $(1 - 1/k)^{N-1-i}$")
ax1.set_xlabel("Stream arrival index $i$")
ax1.set_ylabel("Inclusion probability in final reservoir")
ax1.set_title("Naive overwrite forgets early items")
ax1.legend(fontsize=8.1)
x_m = np.arange(len(m_grid))
ax2.plot(x_m, fpr_opt_k, "g-o", ms=5.5, lw=2.1, label="Auto $k^\\star = \\max(1, \\mathrm{round}((m/n)\\ln 2))$")
ax2.plot(x_m, fpr_k18, "r-^", ms=5.5, lw=2.1, label="Hard-coded $k = 18$ hashes (clobbers bits)")
ax2.set_xticks(x_m)
ax2.set_xticklabels([str(mv) for mv in m_grid])
ax2.set_xlabel("Allocated Bloom filter size $m$ [bits] for $n = 800$ items")
ax2.set_ylabel("Empirical false-positive rate [%]")
ax2.set_title("Saturation of an undersized filter")
ax2.legend(fontsize=8.1)
label_panels(fig)
plt.show()
Exercise 2: Exponential memory decay in naive reservoir sampling and Bloom filter saturation
============================================================================================
[Part A] Early item i=0 inclusion : Vitter = 0.1275 (exact 0.1250) vs. Naive Bug = 0.00050 (theory 0.00041)
Final item i=39 inclusion: Vitter = 0.1250 (exact 0.1250) vs. Naive Bug = 1.0000 (exact 1.0000)
[Part B] At m=512 bits, n=800 items, k=18 hashes: bit fill = 100.00%, empirical FPR = 100.00%

Figure S13.2. Two failure modes. (a) Inclusion probability of each stream position for Vitter’s algorithm and for a naive overwrite, which forgets early items exponentially. (b) False-positive rate against the filter size for the optimal and a fixed number of hashes; with 18 hashes the filter saturates.
Explanation. (a) Without decaying the acceptance probability as , a reservoir becomes an exponentially weighted moving window where the very last arrival enters with probability while survives with . (b) Hardcoding hashes when attempts bit writes into 512 slots (), flipping every single bit to 1 so every unseen query falsely reports 'PRESENT'.
Exercise 3¶
Problem. Implement misra_gries_heavy_hitters(stream, k_counters) in pure Python/NumPy maintaining at most k_counters (item -> count) entries: if item is tracked, increment its counter; else if fewer than k_counters items are tracked, insert item: 1; else decrement all k_counters counters 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("Exercise 3: Implement it yourself — deterministic O(k) Misra-Gries heavy-hitters summary")
from collections import Counter
def misra_gries_heavy_hitters(stream: list[str], k_counters: int) -> dict:
"""Deterministic Misra-Gries (1982) frequent-items sketch using at most k_counters active keys."""
k = int(k_counters)
if k < 1:
raise ValueError("Require k_counters >= 1.")
counters: dict[str, int] = {}
decrements = 0
max_keys_held = 0
for x in stream:
if x in counters:
counters[x] += 1
elif len(counters) < k:
counters[x] = 1
else:
# Cancel a (k + 1)-tuple of pairwise distinct items (x plus all k active keys):
decrements += 1
dead = []
for key in counters:
counters[key] -= 1
if counters[key] == 0:
dead.append(key)
for key in dead:
del counters[key]
if len(counters) > max_keys_held:
max_keys_held = len(counters)
return {
"counters": dict(counters),
"batch_decrements": decrements,
"max_active_keys": max_keys_held,
"error_bound": len(stream) / float(k + 1),
}
# Test 1: 10,000-event Zipfian stream with k_counters = 9 (guarantees catching all f > N/10 = 1,000):
rng_mg = np.random.default_rng(1309)
n_mg = 10000
ranks_mg = np.arange(1, 301, dtype=float)
p_mg = (ranks_mg ** (-1.25)) / np.sum(ranks_mg ** (-1.25))
zipf_stream = [f"VIBE-{i:03d}" for i in rng_mg.choice(300, size=n_mg, p=p_mg)]
exact_zipf = Counter(zipf_stream)
mg_9 = misra_gries_heavy_hitters(zipf_stream, k_counters=9)
bound_9 = n_mg / 10.0
# Verify exact invariant: sum(counters) + (k + 1) * decrements == N? Wait: each purge removes k from counters and drops 1 incoming item -> total mass removed per decrement is exact (k + 1)
assert sum(mg_9["counters"].values()) + (9 + 1) * mg_9["batch_decrements"] == n_mg
assert mg_9["max_active_keys"] <= 9
for item, f_true in exact_zipf.items():
c_est = mg_9["counters"].get(item, 0)
assert f_true - bound_9 - 1e-12 <= c_est <= f_true
if f_true > bound_9:
assert item in mg_9["counters"] and c_est >= 1
# Test 2: Sweep k_counters in [4, 9, 19, 39, 79] and verify worst-case error <= N / (k + 1):
k_grid_mg = [4, 9, 19, 39, 79]
emp_max_under, theo_mg_bound = [], []
for kv in k_grid_mg:
res_k = misra_gries_heavy_hitters(zipf_stream, k_counters=kv)
max_u = max(f_true - res_k["counters"].get(it, 0) for it, f_true in exact_zipf.items())
emp_max_under.append(max_u)
theo_mg_bound.append(n_mg / float(kv + 1))
assert max_u <= res_k["error_bound"] + 1e-12
print(f"Conservation check: sum(c) + (k+1)*decrements = {sum(mg_9['counters'].values()) + 10*mg_9['batch_decrements']} == N = {n_mg}")
print(f"k = 9 active counters retained all {sum(1 for f in exact_zipf.values() if f > bound_9)} heavy hitters (> {bound_9:.0f} occurrences) with max underestimate = {emp_max_under[1]} <= {theo_mg_bound[1]:.0f}")
fig, ax = plt.subplots(figsize=(7.5, 4.1))
ax.loglog(k_grid_mg, theo_mg_bound, "k--", lw=2.0, label="Deterministic worst-case bound $N / (k + 1)$")
ax.loglog(k_grid_mg, emp_max_under, "b-o", ms=6, lw=2.2, label="Empirical max underestimate $\\max_x (f_x - \\hat{c}_x)$")
ax.set_xlabel("Number of Misra-Gries counters $k$ (memory budget)")
ax.set_ylabel("Maximum frequency underestimate [counts]")
ax.set_title("Misra-Gries underestimate against counters")
ax.legend(fontsize=8.4)
log_ticks(ax, "x", [4, 8, 16, 32, 64])
plt.show()
Exercise 3: Implement it yourself — deterministic O(k) Misra-Gries heavy-hitters summary
========================================================================================
Conservation check: sum(c) + (k+1)*decrements = 10000 == N = 10000
k = 9 active counters retained all 2 heavy hitters (> 1000 occurrences) with max underestimate = 762 <= 1000

Figure S13.3. Largest underestimate of the Misra–Gries summary against the number of counters , below the worst-case bound (dashed).
Summary. Notice the contrast between Count-Min Sketch (, randomized upper bound via hashing) and Misra-Gries (, deterministic lower bound via -way cancellation): every decrement step destroys exactly one copy of distinct items (sum(counters) + (k+1)*decrements == N), so an item appearing times cannot be cancelled to zero no matter how adversarially the remaining stream is ordered.