Worked solutions to the three exercises of Lecture 2. 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: Binary modular exponentiation via invariant (p * a^b) mod m == x0^y0 mod m")
def binary_modexp_with_contract(x0: int, y0: int, mod: int) -> dict:
"""Compute (x0 ** y0) % mod in O(log y0) while asserting the loop invariant every step."""
if y0 < 0 or mod <= 1:
raise ValueError("Require y0 >= 0 and mod > 1.")
target_oracle = pow(x0, y0, mod)
a, b, p = x0 % mod, y0, 1
steps = 0
trace = [(steps, a, b, p)]
assert (p * pow(a, b, mod)) % mod == target_oracle # 1. Initialization
while b > 0:
b_prev = b
if b & 1:
p = (p * a) % mod
a = (a * a) % mod
b //= 2
steps += 1
trace.append((steps, a, b, p))
assert b < b_prev # 3. Strictly decreasing Lyapunov variant
assert (p * pow(a, b, mod)) % mod == target_oracle # 2. Maintenance
# 4. Postcondition: b == 0 and Invariant => p == x0^y0 mod m
return {"result": p, "iterations": steps, "trace": trace}
demo_exp = binary_modexp_with_contract(x0=7, y0=13, mod=1000)
print(f"Step-by-step trace for 7^13 mod 1000 (exact = {pow(7, 13, 1000)}):")
print(f"{'Step':>4s} | {'Base a':>8s} | {'Exp b':>8s} | {'Accum p':>8s} | {'Invariant (p * a^b) mod 1000':>30s}")
print("-" * 70)
for st_i, a_i, b_i, p_i in demo_exp["trace"]:
inv_val = (p_i * pow(a_i, b_i, 1000)) % 1000
print(f"{st_i:4d} | {a_i:8d} | {b_i:8d} | {p_i:8d} | {inv_val:30d}")
huge_exps = [10**k for k in range(1, 19, 3)]
iters_huge = [binary_modexp_with_contract(314159, y_val, 1_000_000_007)["iterations"] for y_val in huge_exps]
print("\nExponents y0 :", huge_exps)
print("Loop steps :", iters_huge, f"({iters_huge[-1]} steps for y0 = 10^16, against 10^16 - 1 multiplications by repeated multiplication)")
assert demo_exp["result"] == pow(7, 13, 1000)
assert iters_huge[-1] == (10**16).bit_length()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Implement Boyer–Moore’s time, space majority-vote algorithm with an explicit constructive pair-cancellation witness verifying at every prefix that elements form disjoint heterogeneous pairs , and test across 40 randomized and adversarial sensor streams.
heading("Exercise 1: Boyer-Moore O(N), O(1)-space majority vote and pair-cancellation proof")
def boyer_moore_majority_with_proof(stream: list[int] | np.ndarray) -> dict:
"""Find strict majority (> N/2) in O(N) while constructively verifying disjoint heterogeneous pair cancellation."""
arr = [int(v) for v in stream]
candidate = None
count = 0
# Constructive proof witness (only for mathematical verification): multiset of unpaired copies + cancelled (u!=v) pairs
cancelled_pairs: list[tuple[int, int]] = []
for idx, x in enumerate(arr, start=1):
if count == 0:
candidate = x
count = 1
elif x == candidate:
count += 1
else:
cancelled_pairs.append((int(candidate), x))
count -= 1
# Assert Boyer-Moore Cancellation Invariant at EVERY prefix arr[:idx]:
assert count + 2 * len(cancelled_pairs) == idx
assert all(u != v for u, v in cancelled_pairs)
actual_freq = sum(1 for v in arr if v == candidate) if candidate is not None else 0
has_majority = actual_freq > (len(arr) // 2)
return {
"majority": candidate if has_majority else None,
"has_majority": has_majority,
"cancelled_pairs_count": len(cancelled_pairs),
}
# Adversarial stream: majority '7' appears 51 times in N=100, interleaved at the very end after 49 distinct decoys
adv_stream = list(range(100, 149)) + [7] * 51
res_adv = boyer_moore_majority_with_proof(adv_stream)
res_none = boyer_moore_majority_with_proof([1, 2, 1, 2, 3, 3])
rng_bm = np.random.default_rng(12)
for trial in range(40):
n_len = 75
if trial % 2 == 0:
maj_val = int(rng_bm.integers(1, 10))
s_trial = [maj_val] * 39 + rng_bm.integers(10, 50, size=36).tolist()
rng_bm.shuffle(s_trial)
out_t = boyer_moore_majority_with_proof(s_trial)
assert out_t["has_majority"] and out_t["majority"] == maj_val
else:
s_trial = rng_bm.integers(0, 20, size=n_len).tolist()
out_t = boyer_moore_majority_with_proof(s_trial)
vals, cnts = np.unique(s_trial, return_counts=True)
oracle_maj = int(vals[np.argmax(cnts)]) if np.max(cnts) > n_len // 2 else None
assert out_t["majority"] == oracle_maj
print(f"Adversarial late-majority result: {res_adv} | No-majority tie result: {res_none}")
assert res_adv["majority"] == 7 and not res_none["has_majority"]
Exercise 1: Boyer-Moore O(N), O(1)-space majority vote and pair-cancellation proof
==================================================================================
Adversarial late-majority result: {'majority': 7, 'has_majority': True, 'cancelled_pairs_count': 25} | No-majority tie result: {'majority': None, 'has_majority': False, 'cancelled_pairs_count': 2}
Explanation. Every time count decrements, one copy of candidate and one distinct element x != candidate annihilate each other. Since any strict majority element owns total votes, heterogeneous pairs can consume at most copies of , forcing at least one uncancelled copy of to survive at the end of Pass 1. Pass 2 confirms actual_freq > N // 2 when no majority exists.
Exercise 2¶
Problem. Demonstrate and quantify two classic loop-invariant bugs: (a) advancing mid += 1 inside the out[mid] > high_pivot swap of Dutch National Flag on [1.0, 9.0, 3.0, 8.0] ([lo_p, hi_p] = [2.0, 5.0]), and (b) pairing mid = (lo + hi) // 2 with lo = mid in binary search on [10, 20].
heading("Exercise 2: Audit of uninspected-swap DNF corruption and zero-progress binary search infinite loop")
# (a) Buggy DNF that increments `mid += 1` after swapping `out[mid]` with `out[hi]`:
def buggy_dnf_advance_mid_on_high(arr: list[float], lo_p: float, hi_p: float) -> list[float]:
out = list(arr)
lo, mid, hi = 0, 0, len(out) - 1
while mid <= hi:
if out[mid] < lo_p:
out[lo], out[mid] = out[mid], out[lo]
lo += 1
mid += 1
elif out[mid] > hi_p:
out[mid], out[hi] = out[hi], out[mid]
hi -= 1
mid += 1 # <-- INVARIANT BUG: out[hi] came from unclassified region and was NEVER inspected
else:
mid += 1
return out
bad_in = [1.0, 9.0, 3.0, 8.0]
buggy_out = buggy_dnf_advance_mid_on_high(bad_in, 2.0, 5.0)
clean_out = representation_scaling.dutch_national_flag_partition(np.array(bad_in), 2.0, 5.0)["partitioned"].tolist()
print(f"(a) Input {bad_in} with pivots [2.0, 5.0]:")
print(f" Buggy DNF output : {buggy_out} <-- 8.0 (>5.0) illegally stranded before 3.0")
print(f" Clean DNF output : {clean_out}")
# (b) Buggy integer binary search with floor division `mid = (lo + hi) // 2` and `lo = mid`:
def detect_binary_search_stall(lo_init: int, hi_init: int, max_steps: int = 25) -> dict:
lo, hi = lo_init, hi_init
for step in range(1, max_steps + 1):
v_prev = hi - lo
mid = (lo + hi) // 2
# Suppose predicate(mid) suggests moving lower bound up: `lo = mid` (instead of upper-mid or lo = mid + 1)
lo = mid
v_next = hi - lo
if v_next == v_prev:
return {"stalled": True, "stall_step": step, "stuck_bounds": (lo, hi)}
return {"stalled": False, "stall_step": max_steps, "stuck_bounds": (lo, hi)}
stall_report = detect_binary_search_stall(0, 7)
print(f"\n(b) Floor-mid + `lo = mid` binary search: {stall_report} (Variant V = hi - lo stops decreasing at hi - lo == 1)")
assert buggy_out.index(8.0) < buggy_out.index(3.0) # Violates sorted zone invariant
assert clean_out == [1.0, 3.0, 8.0, 9.0]
assert stall_report["stalled"] and stall_report["stuck_bounds"] == (6, 7)
Exercise 2: Audit of uninspected-swap DNF corruption and zero-progress binary search infinite loop
==================================================================================================
(a) Input [1.0, 9.0, 3.0, 8.0] with pivots [2.0, 5.0]:
Buggy DNF output : [1.0, 8.0, 3.0, 9.0] <-- 8.0 (>5.0) illegally stranded before 3.0
Clean DNF output : [1.0, 3.0, 8.0, 9.0]
(b) Floor-mid + `lo = mid` binary search: {'stalled': True, 'stall_step': 4, 'stuck_bounds': (6, 7)} (Variant V = hi - lo stops decreasing at hi - lo == 1)
Explanation. In Dutch National Flag, out[lo] is already proved to lie in [lo_p, hi_p] (so swapping lo and mid lets both advance), whereas out[hi] comes from the unclassified zone, so mid must stay put to inspect the newly arrived value. In binary search, lo + (hi - lo) // 2 == lo whenever hi == lo + 1; setting lo = mid gives , violating Lyapunov’s strict decrease rule.
Exercise 3¶
Problem. Implement verify_chemical_valve_fsm(events, omit_low_level_trip=False) controlling batch reactor states (EMPTY, FILLING, FULL_READY, HEATING, DRAINING, LOCKOUT) with actuator tuple (level_low, inlet_open, drain_open, heater_on), plus bfs_find_hazard_trace(omit_low_level_trip) that proves zero reachable hazards for the safe FSM and finds the shortest dry-boil trace when the low-level trip is omitted.
heading("Exercise 3: Implement it yourself — chemical batch-reactor FSM and counterexample model checker")
from collections import deque
REACTOR_ACTUATORS = {
# state: (level_low, inlet_open, drain_open, heater_on)
"EMPTY": (True, False, False, False),
"FILLING": (True, True, False, False),
"FULL_READY": (False, False, False, False),
"HEATING": (False, False, False, True),
"DRAINING": (False, False, True, False),
"UNSAFE_BOIL":(True, False, True, True), # Reachable ONLY if drain/leak occurs during HEATING without interlock
"LOCKOUT": (True, False, False, False),
}
REACTOR_EVENTS = ["CMD_FILL", "LVL_HIGH", "CMD_HEAT", "CMD_STOP_HEAT", "CMD_DRAIN", "LVL_LOW", "FAULT_LEAK", "CMD_RESET"]
def _step_reactor(state: str, ev: str, omit_low_level_trip: bool = False) -> str:
if ev == "FAULT_LEAK":
if state == "HEATING" and omit_low_level_trip:
return "UNSAFE_BOIL"
return "LOCKOUT"
transitions = {
("EMPTY", "CMD_FILL"): "FILLING",
("FILLING", "LVL_HIGH"): "FULL_READY",
("FULL_READY", "CMD_HEAT"): "HEATING",
("HEATING", "CMD_STOP_HEAT"): "FULL_READY",
("FULL_READY", "CMD_DRAIN"): "DRAINING",
("DRAINING", "LVL_LOW"): "EMPTY",
("LOCKOUT", "CMD_RESET"): "EMPTY",
}
return transitions.get((state, ev), state)
def verify_chemical_valve_fsm(events: list[str], omit_low_level_trip: bool = False) -> dict:
"""Simulate deterministic event sequence and audit safety invariants at every step."""
state = "EMPTY"
visited_seq = [state]
violations = 0
for ev in events:
state = _step_reactor(state, ev, omit_low_level_trip=omit_low_level_trip)
visited_seq.append(state)
lvl_low, in_open, dr_open, htr_on = REACTOR_ACTUATORS[state]
if (htr_on and lvl_low) or (in_open and dr_open):
violations += 1
return {"final_state": state, "state_trace": visited_seq, "safety_violations": violations}
def bfs_find_hazard_trace(omit_low_level_trip: bool = False) -> dict:
"""Exhaustive BFS model checker returning shortest counterexample trace if any hazard state is reachable."""
q: deque[tuple[str, list[str]]] = deque([("EMPTY", [])])
seen = {"EMPTY"}
while q:
st, path = q.popleft()
lvl_low, in_open, dr_open, htr_on = REACTOR_ACTUATORS[st]
if (htr_on and lvl_low) or (in_open and dr_open):
return {"safe": False, "reachable_count": len(seen), "counterexample": path, "hazard_state": st}
for ev in REACTOR_EVENTS:
nxt = _step_reactor(st, ev, omit_low_level_trip=omit_low_level_trip)
if nxt not in seen:
seen.add(nxt)
q.append((nxt, path + [ev]))
return {"safe": True, "reachable_count": len(seen), "counterexample": None, "hazard_state": None}
audit_safe = bfs_find_hazard_trace(omit_low_level_trip=False)
audit_buggy = bfs_find_hazard_trace(omit_low_level_trip=True)
sim_safe = verify_chemical_valve_fsm(audit_buggy["counterexample"], omit_low_level_trip=False)
sim_buggy = verify_chemical_valve_fsm(audit_buggy["counterexample"], omit_low_level_trip=True)
print("Safe Interlocked FSM Audit :", audit_safe)
print("Omitted-Trip Buggy FSM Audit:", audit_buggy)
print("Replaying shortest counterexample on Safe FSM -> final state:", sim_safe["final_state"], "| violations:", sim_safe["safety_violations"])
assert audit_safe["safe"] and audit_safe["reachable_count"] == 6
assert not audit_buggy["safe"] and audit_buggy["counterexample"] == ["CMD_FILL", "LVL_HIGH", "CMD_HEAT", "FAULT_LEAK"]
assert sim_safe["safety_violations"] == 0 and sim_safe["final_state"] == "LOCKOUT"
assert sim_buggy["safety_violations"] == 1
Exercise 3: Implement it yourself — chemical batch-reactor FSM and counterexample model checker
===============================================================================================
Safe Interlocked FSM Audit : {'safe': True, 'reachable_count': 6, 'counterexample': None, 'hazard_state': None}
Omitted-Trip Buggy FSM Audit: {'safe': False, 'reachable_count': 7, 'counterexample': ['CMD_FILL', 'LVL_HIGH', 'CMD_HEAT', 'FAULT_LEAK'], 'hazard_state': 'UNSAFE_BOIL'}
Replaying shortest counterexample on Safe FSM -> final state: LOCKOUT | violations: 0
Summary. Breadth-First Search over an explicit FSM is a small example of model checking: it proves that no command sequence reaches dry boiling (heater_on and level_low) or pass-through (inlet_open and drain_open), and when an interlock is missing it returns the shortest failing trace, here four events.