Off-by-one bugs (< against <=, hi against hi - 1) are common even in short while loops. Edsger W. Dijkstra’s remedy was to treat a loop the way a physicist treats a control volume: write the conserved quantity (the loop invariant) and a decreasing quantity (the termination variant) before writing the loop body. This lecture applies Mental Move #6, Write the Loop Invariant Before the Loop, to Russian-peasant binary exponentiation, Dijkstra’s 3-way Dutch National Flag partition (representation_scaling.dutch_national_flag_partition), safety-interlocked Finite-State Machines (FSMs), and mass-conserving flux networks.
Learning objectives¶
Prove loop correctness and termination simultaneously using a Loop Invariant (inductive conservation predicate) and an integer Lyapunov Variant that strictly decreases each iteration.
Partition noisy sensor arrays into 3 ordered quality bands in a single pass with extra memory via
representation_scaling.dutch_national_flag_partition.Design deterministic Finite-State Machine (FSM) valve/protocol controllers and verify unreachable hazard states via exhaustive state-space breadth-first reachability.
Enforce discrete physical conservation laws (mass, charge, probability) as runtime
assertcode contracts using antisymmetric pairwise fluxes .
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. The Anatomy of a Loop Contract: Invariant + Lyapunov Variant ¶
Every deterministic loop updates a state tuple while guard holds. A loop is provably total-correct when four obligations hold:
Initialization: Invariant holds before the first iteration.
Maintenance (Conservation): If holds at the top of the body, then holds at the bottom.
Termination (Lyapunov Variant): An integer function satisfies every step, forbidding infinite loops.
Postcondition: When the loop exits (), the desired mathematical answer follows immediately.
Consider computing for . Multiplying by 1018 times is out of reach; instead, initialize and maintain the exact product-power invariant:
Whenever is odd, peel one factor of into ; then square and halve . At termination , , so forces in at most steps.
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()
Demonstration 1: Binary modular exponentiation via invariant (p * a^b) mod m == x0^y0 mod m
===========================================================================================
Step-by-step trace for 7^13 mod 1000 (exact = 407):
Step | Base a | Exp b | Accum p | Invariant (p * a^b) mod 1000
----------------------------------------------------------------------
0 | 7 | 13 | 1 | 407
1 | 49 | 6 | 7 | 407
2 | 401 | 3 | 7 | 407
3 | 801 | 1 | 807 | 407
4 | 601 | 0 | 407 | 407
Exponents y0 : [10, 10000, 10000000, 10000000000, 10000000000000, 10000000000000000]
Loop steps : [4, 14, 24, 34, 44, 54] (54 steps for y0 = 10^16, against 10^16 - 1 multiplications by repeated multiplication)
In the table,
(p * a^b) mod 1000equals407on every row, from Step 0 (1 * 7^13) to Step 4 (407 * 601^0): each step moves value from the unsettled term into the settled accumulator while decreases to 0. For the loop takes 54 steps.
2. Dijkstra’s 3-Way Partition Invariant (dutch_national_flag_partition)¶
Suppose an inline optical wafer scanner streams thickness readings that must be partitioned in-place into Under-Etched (< lo_p), In-Spec ([lo_p, hi_p]), and Over-Deposited (> hi_p) in one pass. Mental Move #6, Write the Loop Invariant Before the Loop divides the array using three pointers 0 <= lo <= mid <= hi + 1 <= N:
Every iteration inspects A[mid] and shrinks the unclassified middle gap by exactly 1 until ().
heading("Demonstration 2: Dutch national flag 3-zone sensor partition and live zone-evolution carpet")
rng_dnf = np.random.default_rng(24)
raw_readings = rng_dnf.uniform(85.0, 115.0, size=36)
lo_spec, hi_spec = 95.0, 105.0
dnf_res = representation_scaling.dutch_national_flag_partition(raw_readings, lo_spec, hi_spec)
lo_b, mid_b = dnf_res["boundaries"]
part_arr = dnf_res["partitioned"]
print(f"Partitioned N = {raw_readings.size} wafer readings around [{lo_spec}, {hi_spec}] nm:")
print(f" Zone counts -> Under (<95): {lo_b} | In-Spec ([95,105]): {mid_b - lo_b} | Over (>105): {raw_readings.size - mid_b}")
print(f" Swaps = {dnf_res['swaps']} (<= N) | Comparisons = {dnf_res['comparisons']} (<= 2N)")
# Record step-by-step zone state (-1 = <lo, 0 = [lo,hi], 2 = unclassified, +1 = >hi) for visual trace:
work = raw_readings.copy()
lo_i, mid_i, hi_i = 0, 0, work.size - 1
history_rows = []
while mid_i <= hi_i:
row = np.zeros(work.size, dtype=float)
row[:lo_i] = -1.0
row[lo_i:mid_i] = 0.0
row[mid_i : hi_i + 1] = 0.5
row[hi_i + 1 :] = 1.0
history_rows.append(row)
if work[mid_i] < lo_spec:
work[lo_i], work[mid_i] = work[mid_i], work[lo_i]
lo_i += 1
mid_i += 1
elif work[mid_i] > hi_spec:
work[mid_i], work[hi_i] = work[hi_i], work[mid_i]
hi_i -= 1
else:
mid_i += 1
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch
zone_colors = ["#2166AC", "#2E8B57", "#D9DEE4", "#C0392B"] # below, in spec, unclassified, above
zone_index = np.searchsorted([-1.0, 0.0, 0.5, 1.0], np.array(history_rows))
ax1.imshow(zone_index, aspect="auto", cmap=ListedColormap(zone_colors), vmin=-0.5, vmax=3.5, interpolation="nearest")
ax1.set_xlabel("Array index $j$")
ax1.set_ylabel("Loop iteration $k$")
ax1.set_title("Zones of the array at every iteration")
ax1.legend(handles=[Patch(color=c, label=t) for c, t in zip(zone_colors, ["below 95 nm", "in spec", "unclassified", "above 105 nm"])],
loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=4, fontsize=8.0)
idx_x = np.arange(part_arr.size)
ax2.scatter(idx_x[:lo_b], part_arr[:lo_b], color="#2166AC", label="Under-etched (< 95 nm)")
ax2.scatter(idx_x[lo_b:mid_b], part_arr[lo_b:mid_b], color="#2E8B57", label="In-spec ([95, 105] nm)")
ax2.scatter(idx_x[mid_b:], part_arr[mid_b:], color="#C0392B", label="Over-deposited (> 105 nm)")
ax2.axhline(lo_spec, color="gray", ls="--")
ax2.axhline(hi_spec, color="gray", ls="--")
ax2.set_xlabel("Final partitioned index")
ax2.set_ylabel("Film thickness [nm]")
ax2.set_title("Partitioned output")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=3, fontsize=8.0)
label_panels(fig)
plt.show()
assert len(history_rows) == raw_readings.size
assert np.all(part_arr[:lo_b] < lo_spec)
assert np.all((part_arr[lo_b:mid_b] >= lo_spec) & (part_arr[lo_b:mid_b] <= hi_spec))
assert np.all(part_arr[mid_b:] > hi_spec)
Demonstration 2: Dutch national flag 3-zone sensor partition and live zone-evolution carpet
===========================================================================================
Partitioned N = 36 wafer readings around [95.0, 105.0] nm:
Zone counts -> Under (<95): 10 | In-Spec ([95,105]): 14 | Over (>105): 12
Swaps = 22 (<= N) | Comparisons = 62 (<= 2N)

Figure 2.1. Dutch national flag partition of 36 wafer readings. (a) State of the array at every iteration: the unclassified zone (grey) shrinks by exactly one cell per step while the low zone (blue) grows from the left, the high zone (red) from the right and the in-spec zone (green) between them. (b) The partitioned output, with the two thresholds at 95 and 105 nm.
What Demonstration 2 shows.
Look at the left heatmap: the pale orange unclassified wedge (
mid .. hi) narrows by strictly one column per row, so the loop ends after exactly steps, while blue (< 95) grows from the left and red (> 105) grows from the right.
3. Finite-State Machines (FSMs) & Safety-Interlock Reachability¶
Industrial autoclaves, radiation therapy beams, and TCP network sockets are safer when they are not written with scattered boolean flags (if is_hot and not is_venting and is_purged: ...), whose combinations are hard to test. Modeling the controller as an explicit Deterministic Finite-State Machine restricts execution to well-defined states and lets us prove via exhaustive Breadth-First Search (BFS) over all transition edges that hazardous combinations (such as opening an atmospheric vent while pressurized with toxic /syngas) are unreachable from under every possible input sequence .
heading("Demonstration 3: High-pressure autoclave interlock FSM and exhaustive reachability proof")
# State outputs: (n2_purged, pressurized, rxn_heater_on, atm_vent_open)
FSM_OUTPUTS = {
"IDLE_OPEN": (False, False, False, True),
"SEALED_PURGING": (False, False, False, False),
"PURGED_READY": (True, False, False, False),
"PRESSURIZED": (True, True, False, False),
"REACTING_HOT": (True, True, True, False),
"COOL_DEPRESS": (True, False, False, False),
"ESTOP_LOCK": (False, False, False, False),
}
FSM_DELTA = {
("IDLE_OPEN", "SEAL_PURGE"): "SEALED_PURGING",
("SEALED_PURGING", "N2_OK"): "PURGED_READY",
("PURGED_READY", "FEED_GAS"): "PRESSURIZED",
("PRESSURIZED", "IGNITE_HEATER"): "REACTING_HOT",
("REACTING_HOT", "QUENCH_DEPRESS"):"COOL_DEPRESS",
("PRESSURIZED", "QUENCH_DEPRESS"): "COOL_DEPRESS",
("COOL_DEPRESS", "OPEN_VENT"): "IDLE_OPEN",
("ESTOP_LOCK", "SUPERVISOR_RESET"):"SEALED_PURGING",
}
ALL_EVENTS = ["SEAL_PURGE", "N2_OK", "FEED_GAS", "IGNITE_HEATER", "QUENCH_DEPRESS", "OPEN_VENT", "ESTOP", "SUPERVISOR_RESET"]
def step_autoclave_fsm(state: str, event: str) -> tuple[str, bool]:
"""Deterministic transition function delta(q, sigma); ESTOP overrides from any active state."""
if event == "ESTOP":
return "ESTOP_LOCK", True
if (state, event) in FSM_DELTA:
return FSM_DELTA[(state, event)], True
return state, False # Illegal out-of-order command deterministically rejected
# Exhaustive BFS reachability audit from q0 = "IDLE_OPEN" across all events:
visited = {"IDLE_OPEN"}
queue = ["IDLE_OPEN"]
while queue:
curr = queue.pop(0)
for ev in ALL_EVENTS:
nxt, _ = step_autoclave_fsm(curr, ev)
if nxt not in visited:
visited.add(nxt)
queue.append(nxt)
print(f"Reachable states from IDLE_OPEN ({len(visited)}/{len(FSM_OUTPUTS)}): {sorted(visited)}")
for st in sorted(visited):
purged, press, hot, vent = FSM_OUTPUTS[st]
# Safety Invariant 1: Never pressurized or hot while atmospheric vent is open
assert not (vent and (press or hot))
# Safety Invariant 2: Never pressurized with reactant gas without N2 oxygen purge
assert not (press and not purged)
# Test an adversarial operator command sequence attempting to ignite heater directly from IDLE_OPEN:
adv_seq = ["IGNITE_HEATER", "FEED_GAS", "SEAL_PURGE", "OPEN_VENT", "N2_OK", "FEED_GAS", "IGNITE_HEATER", "OPEN_VENT", "ESTOP"]
cur_q = "IDLE_OPEN"
rejected_cmds = []
for cmd in adv_seq:
cur_q, accepted = step_autoclave_fsm(cur_q, cmd)
if not accepted:
rejected_cmds.append(cmd)
print("Adversarial trace rejected illegal commands:", rejected_cmds, "| Final safe state:", cur_q)
assert len(visited) == 7
assert rejected_cmds == ["IGNITE_HEATER", "FEED_GAS", "OPEN_VENT", "OPEN_VENT"] and cur_q == "ESTOP_LOCK"
Demonstration 3: High-pressure autoclave interlock FSM and exhaustive reachability proof
========================================================================================
Reachable states from IDLE_OPEN (7/7): ['COOL_DEPRESS', 'ESTOP_LOCK', 'IDLE_OPEN', 'PRESSURIZED', 'PURGED_READY', 'REACTING_HOT', 'SEALED_PURGING']
Adversarial trace rejected illegal commands: ['IGNITE_HEATER', 'FEED_GAS', 'OPEN_VENT', 'OPEN_VENT'] | Final safe state: ESTOP_LOCK
What Demonstration 3 shows.
Finite verification of infinite traces: Even though an operator can press buttons infinitely many times (), BFS visits all states and transitions and so proves that neither
vent and pressnor unpurged pressurization can ever occur.
4. Physical Conservation Laws as Runtime Code Contracts¶
In finite-volume fluid dynamics, chemical kinetics, and Markov chains, total mass/probability is a loop invariant. Why do buggy diffusive codes slowly gain or lose mass over thousands of steps? Because computing flux and separately (or clipping negative concentrations locally after updating) breaks exact antisymmetry . We contrast an antisymmetric face-flux update (with CFL positivity bound ) against a naive node-clipped update.
heading("Demonstration 4: Antisymmetric conservative fluxes against mass-leaking clipped updates")
n_cells = 24
m_init = np.zeros(n_cells, dtype=float)
m_init[4:8] = 25.0 # Total initial mass M0 = 100.0 kg in a closed ring of 24 tanks
m0_total = float(np.sum(m_init))
# Conductance matrix on a closed ring + 2 cross-pipes:
edges = [(i, (i + 1) % n_cells, 0.32) for i in range(n_cells)] + [(2, 14, 0.25), (8, 20, 0.25)]
dt_safe = 0.45 # Satisfies positivity invariant 1 - dt * sum_j k_ij > 0
m_cons = m_init.copy()
m_buggy = m_init.copy()
mass_hist_cons, mass_hist_buggy, entropy_hist = [], [], []
for step in range(160):
# 1. Conservative edge-based loop: compute each edge flux ONCE and apply -J to i, +J to j
dm = np.zeros_like(m_cons)
for i, j, k_ij in edges:
flux_ij = k_ij * (m_cons[i] - m_cons[j]) * dt_safe
dm[i] -= flux_ij
dm[j] += flux_ij
m_cons = m_cons + dm
assert np.all(m_cons >= -1.0e-15)
assert np.isclose(np.sum(m_cons), m0_total, rtol=1e-13) # Runtime conservation contract
# 2. Buggy over-stepped explicit update with post-hoc floor max(m, 0) ("silent mass creation"):
dm_b = np.zeros_like(m_buggy)
for i, j, k_ij in edges:
flux_b = k_ij * (m_buggy[i] - m_buggy[j]) * 1.45
dm_b[i] -= flux_b
dm_b[j] += flux_b
m_buggy = np.maximum(m_buggy + dm_b, 0.0)
mass_hist_cons.append(float(np.sum(m_cons)))
mass_hist_buggy.append(float(np.sum(m_buggy)))
p_norm = np.clip(m_cons / m0_total, 1.0e-30, 1.0)
entropy_hist.append(float(-np.sum(p_norm * np.log(p_norm))))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
ax1.plot(mass_hist_cons, "-", color="#2E8B57", lw=2.2, label="Antisymmetric face flux (conserved)")
ax1.plot(mass_hist_buggy, "--", color="#C0392B", lw=2.1, label="Over-stepped + `np.maximum(m, 0)` bug")
ax1.set_xlabel("Time step $t$")
ax1.set_ylabel(r"Total system mass $\sum_i m_i(t)$ [kg]")
ax1.set_title("Total mass: conservative and clipped updates")
ax1.legend(fontsize=8.2)
ax2.plot(entropy_hist, "-", color="#2166AC", lw=2.2, label=r"Mixing entropy $S(t) = -\sum p_i \ln p_i$")
ax2.axhline(math.log(n_cells), color="gray", ls=":", label=r"Uniform equilibrium $\ln N$")
ax2.set_xlabel("Time step $t$")
ax2.set_ylabel("Shannon mixing entropy $S$ [nats]")
ax2.set_title(r"Mixing entropy rises monotonically")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
print(f"Final Conservative Mass = {mass_hist_cons[-1]:.12f} kg | Buggy Clipped Mass = {mass_hist_buggy[-1]:.2f} kg (+{mass_hist_buggy[-1]-100:.1f}% fake mass)")
assert abs(mass_hist_cons[-1] - 100.0) < 1.0e-12
assert mass_hist_buggy[-1] > 115.0
assert np.all(np.diff(entropy_hist) >= -1.0e-14)
Demonstration 4: Antisymmetric conservative fluxes against mass-leaking clipped updates
=======================================================================================

Final Conservative Mass = 100.000000000000 kg | Buggy Clipped Mass = 4754.87 kg (+4654.9% fake mass)
Figure 2.2. Conservation as a code contract on a diffusion network. (a) Total mass against time step: the antisymmetric face-flux update keeps 100 kg exactly, while clipping negative values after an over-large step creates mass. (b) The mixing entropy of the conservative update rises monotonically towards its equilibrium value .
Inside the algorithm¶
We inspect representation_scaling.dutch_national_flag_partition and construct instrumented_dnf_with_invariant_assertions, which checks the loop contract (the zone bounds, conservation of the multiset of values and the strict decrease of ) before and after every iteration.
Check against the library¶
heading("Inside the algorithm: Dutch national flag instrumented with full per-step contract assertions")
print(show_source(representation_scaling.dutch_national_flag_partition))
def instrumented_dnf_with_invariant_assertions(arr: np.ndarray, low_pivot: float, high_pivot: float) -> dict:
"""Execute 3-way partition while asserting all 4 loop-invariant clauses and variant decrease at every step."""
out = np.asarray(arr, dtype=float).ravel().copy()
orig_sorted = np.sort(out)
n = out.size
lo, mid, hi = 0, 0, n - 1
checked_iters = 0
def _assert_contract() -> None:
assert 0 <= lo <= mid <= hi + 1 <= n
assert np.all(out[:lo] < low_pivot)
assert np.all((out[lo:mid] >= low_pivot) & (out[lo:mid] <= high_pivot))
assert np.all(out[hi + 1 :] > high_pivot)
assert np.array_equal(np.sort(out), orig_sorted) # Exact multiset conservation
_assert_contract()
while mid <= hi:
v_before = hi - mid + 1
if out[mid] < low_pivot:
out[lo], out[mid] = out[mid], out[lo]
lo += 1
mid += 1
elif out[mid] > high_pivot:
out[mid], out[hi] = out[hi], out[mid]
hi -= 1
else:
mid += 1
v_after = hi - mid + 1
assert v_after == v_before - 1
_assert_contract()
checked_iters += 1
return {"partitioned": out, "boundaries": (lo, mid), "checked_iterations": checked_iters}
rng_inst = np.random.default_rng(99)
test_vec = rng_inst.choice([-5.0, 0.0, 2.5, 5.0, 10.0], size=64) # Includes exact boundary ties
inst_res = instrumented_dnf_with_invariant_assertions(test_vec, 0.0, 5.0)
lib_res = representation_scaling.dutch_national_flag_partition(test_vec, 0.0, 5.0)
print(f"Verified all 5 contract assertions across {inst_res['checked_iterations']} iterations (including boundary ties)")
assert inst_res["checked_iterations"] == test_vec.size
assert np.array_equal(inst_res["partitioned"], lib_res["partitioned"])
assert inst_res["boundaries"] == lib_res["boundaries"]
Inside the algorithm: Dutch national flag instrumented with full per-step contract assertions
=============================================================================================
def dutch_national_flag_partition(arr: np.ndarray, low_pivot: float, high_pivot: float) -> dict:
"""Dijkstra 3-way loop-invariant partition (< low_pivot | [low_pivot, high_pivot] | > high_pivot) in O(N)."""
if low_pivot > high_pivot:
raise ValueError("Require low_pivot <= high_pivot.")
out = np.asarray(arr, dtype=float).ravel().copy()
lo = 0
mid = 0
hi = out.size - 1
comparisons = 0
swaps = 0
# Loop invariant: out[:lo] < low_pivot <= out[lo:mid] <= high_pivot < out[hi+1:]
while mid <= hi:
comparisons += 1
if out[mid] < low_pivot:
out[lo], out[mid] = out[mid], out[lo]
swaps += 1
lo += 1
mid += 1
else:
comparisons += 1
if out[mid] > high_pivot:
out[mid], out[hi] = out[hi], out[mid]
swaps += 1
hi -= 1
else:
mid += 1
return {"partitioned": out, "boundaries": (lo, mid), "comparisons": comparisons, "swaps": swaps}
Verified all 5 contract assertions across 64 iterations (including boundary ties)
Exercises¶
Worked solutions are in 02_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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.
Find how it fails. Demonstrate and quantify two classic loop-invariant bugs: (a) advancing
mid += 1inside theout[mid] > high_pivotswap of Dutch National Flag on[1.0, 9.0, 3.0, 8.0]([lo_p, hi_p] = [2.0, 5.0]), and (b) pairingmid = (lo + hi) // 2withlo = midin binary search on[10, 20].Implement it yourself. 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), plusbfs_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("Self-check for the exercises")
assert demo_exp["result"] == pow(7, 13, 1000)
assert np.array_equal(inst_res["partitioned"], lib_res["partitioned"])
assert abs(mass_hist_cons[-1] - 100.0) < 1.0e-12
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.