Suppose a microgrid designer asks: What is the minimum LiFePO4 battery capacity [MWh] needed to survive a 168-hour winter wind-and-solar drought with round-trip losses and inverter clipping without ever dropping below state of charge? Because curtailment at full charge and the reserve floor are non-smooth, history-dependent nonlinearities, there is no closed-form algebraic inverse. Yet answering the forward yes/no question, ‘Does a battery of fixed size survive all 168 hours?’, is a trivial 168-step loop, and survival is monotone in (False ... False, True ... True). Binary-searching the answer (divide_spatial.parametric_binary_search_min) solves the inverse design problem to a tolerance of in 41 forward simulations (Demonstration 2; the load and generation data are synthetic). This lecture covers Mental Moves #11–#12: parametric search, Master-Theorem recursion trees, mergesort_with_inversions, and unimodal golden-section search.
Learning objectives¶
Predict recursive divide-and-conquer scaling via the Master Theorem across leaf-dominated (), balanced (), and root-dominated () regimes.
Invert hard engineering sizing & scheduling problems into monotone yes/no feasibility checks via
divide_spatial.parametric_binary_search_minandparametric_binary_search_int.Piggyback global disorder statistics (exact pairwise inversions and Kendall ) onto sorting using
divide_spatial.mergesort_with_inversions.Minimize noisy or non-differentiable unimodal engineering cost functions without derivatives via golden-section bracket reduction.
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. Recursion Trees & The Master Theorem ¶
Splitting a problem of size into subproblems of size with divide/merge work creates a tree of depth . At depth , there are nodes each doing work, so level- total work is a geometric series with ratio :
heading("Demonstration 1: Empirical verification of all three master-theorem regimes")
def eval_recurrence_work(n: int, a: int, b: int, d: int) -> float:
"""Exact work count of T(N) = a * T(N // b) + N^d with base T(1) = 1."""
if n <= 1:
return 1.0
return a * eval_recurrence_work(n // b, a, b, d) + float(n ** d)
n_pows = np.array([2 ** k for k in range(4, 13)], dtype=float)
cases = [
("Root-dominated (a=1, b=2, d=1 -> O(N))", 1, 2, 1, "O(N)"),
("Balanced tree (a=2, b=2, d=1 -> O(N log N))", 2, 2, 1, "O(N log N)"),
("Karatsuba split (a=3, b=2, d=1 -> O(N^1.585))", 3, 2, 1, "O(N^2)"),
("Leaf-dominated (a=4, b=2, d=1 -> O(N^2))", 4, 2, 1, "O(N^2)"),
]
fig, ax = plt.subplots(figsize=(7.8, 4.2))
for label, a_c, b_c, d_c, _ in cases:
w_vals = np.array([eval_recurrence_work(int(n_v), a_c, b_c, d_c) for n_v in n_pows])
fit_r = invariants_complexity.fit_empirical_complexity(n_pows, w_vals)
theo_exp = max(float(d_c), math.log(a_c, b_c))
print(f"{label:46s} | Fitted p = {fit_r['exponent_p']:.3f} | Master max(d, log_b a) = {theo_exp:.3f}")
ax.loglog(n_pows, w_vals, "o-", lw=2.0, label=f"{label.split('->')[0].strip()} (p={fit_r['exponent_p']:.2f})")
if a_c != b_c ** d_c:
assert abs(fit_r["exponent_p"] - theo_exp) < 0.06
ax.set_xlabel("Problem size $N = 2^k$")
ax.set_ylabel("Total recursion-tree work $T(N)$")
ax.set_title("Three regimes of the master theorem")
ax.legend(fontsize=8.0)
plt.show()
Demonstration 1: Empirical verification of all three master-theorem regimes
===========================================================================
Root-dominated (a=1, b=2, d=1 -> O(N)) | Fitted p = 1.005 | Master max(d, log_b a) = 1.000
Balanced tree (a=2, b=2, d=1 -> O(N log N)) | Fitted p = 1.169 | Master max(d, log_b a) = 1.000
Karatsuba split (a=3, b=2, d=1 -> O(N^1.585)) | Fitted p = 1.607 | Master max(d, log_b a) = 1.585
Leaf-dominated (a=4, b=2, d=1 -> O(N^2)) | Fitted p = 2.005 | Master max(d, log_b a) = 2.000

Figure 4.1. Work of synthetic recursions for . The fitted exponents, 1.00, 1.17, 1.61 and 2.00, follow the three regimes of the master theorem (, and ).
Karatsuba multiplication uses products of half-width integers instead of . Removing one recursive call per split lowers the leaf exponent from to , and the fitted exponent, 1.607, agrees.
2. “Binary-Searching the Answer” on Monotone Feasibility (parametric_binary_search_min)¶
Mental Move #11, Binary-Search the Answer on Monotone Feasibility: Whenever an optimization problem asks for the minimum capacity/budget/deadline such that a complex system succeeds, check whether feasibility is monotone (). If so, maintain the bracket invariant:
We apply parametric_binary_search_min to size a 168-hour solar+wind island microgrid battery (with charging/discharging efficiencies , full-charge curtailment, and a minimum reserve floor), and parametric_binary_search_int to size the minimum fleet of parallel chemical autoclaves needed to finish 28 ordered batch jobs within 48 hours.
heading("Demonstration 2: Parametric binary search — microgrid battery sizing and autoclave fleet dispatch")
hours = np.arange(168, dtype=float)
# 7-day solar + wind generation with a severe Days 3-5 calm/cloudy "dunkelflaute" dip vs industrial load [MW]:
drought_env = 1.0 - 0.72 * np.exp(-((hours - 90.0) / 28.0) ** 2)
gen_mw = drought_env * (18.0 * np.maximum(0.0, np.sin(math.pi * ((hours % 24.0) - 6.0) / 12.0)) + 7.5 + 2.5 * np.cos(hours / 9.0))
load_mw = 9.2 + 2.1 * np.sin(2.0 * math.pi * (hours - 8.0) / 24.0)
net_surplus_mw = gen_mw - load_mw
def simulate_microgrid_soc(cap_mwh: float) -> tuple[bool, np.ndarray]:
"""Forward 168-h battery simulator (starts 85% charged, curtails above cap_mwh, fails if SoC < 10% cap)."""
if cap_mwh <= 0.0:
return False, np.zeros(hours.size + 1)
soc = np.empty(hours.size + 1, dtype=float)
soc[0] = 0.85 * cap_mwh
eta_c, eta_d = 0.94, 0.94
floor_mwh = 0.10 * cap_mwh
for t_i, dp in enumerate(net_surplus_mw):
nxt = soc[t_i] + (eta_c * dp if dp >= 0.0 else dp / eta_d)
soc[t_i + 1] = min(cap_mwh, nxt)
if soc[t_i + 1] < floor_mwh:
soc[t_i + 1 :] = soc[t_i + 1]
return False, soc
return True, soc
bat_opt = divide_spatial.parametric_binary_search_min(lambda c: simulate_microgrid_soc(c)[0], lo=0.0, hi=500.0, tol=1.0e-9)
e_min = bat_opt["threshold"]
print(f"Minimum microgrid battery E_min = {e_min:.6f} MWh found in {bat_opt['evaluations']} forward simulations")
# Discrete integer parametric search: minimum number of parallel reactors K to complete sequential jobs <= 48.0 h:
job_hours = np.array([6.5, 4.0, 8.0, 5.5, 7.0, 3.5, 9.0, 6.0, 5.0, 7.5, 8.5, 4.5, 6.0, 7.0,
5.0, 8.0, 6.5, 4.0, 7.5, 5.5, 6.0, 8.5, 4.5, 5.0, 7.0, 6.0, 5.5, 6.5])
deadline_h = 48.0
def fleet_finishes_on_time(k_reactors: int) -> bool:
if k_reactors < 1:
return False
# Assign each next job in queue to whichever reactor becomes free earliest:
loads = [0.0] * k_reactors
for jh in job_hours:
idx_min = int(np.argmin(loads))
loads[idx_min] += float(jh)
if loads[idx_min] > deadline_h:
return False
return True
fleet_opt = divide_spatial.parametric_binary_search_int(fleet_finishes_on_time, lo=1, hi=len(job_hours))
k_min = fleet_opt["threshold"]
print(f"Minimum parallel autoclave fleet K_min = {k_min} units (evals = {fleet_opt['evaluations']} vs {len(job_hours)} linear scan)")
_, soc_under = simulate_microgrid_soc(0.85 * e_min)
_, soc_exact = simulate_microgrid_soc(e_min)
_, soc_over = simulate_microgrid_soc(1.20 * e_min)
fig, ax = plt.subplots(figsize=(8.0, 4.1))
ax.plot(soc_under / (0.85 * e_min) * 100.0, "--", color="#C0392B", lw=1.9, label=f"Undersized 0.85 E_min ({0.85*e_min:.1f} MWh -> blackout)")
ax.plot(soc_exact / e_min * 100.0, "-", color="#2166AC", lw=2.3, label=f"Optimal E_min ({e_min:.1f} MWh -> grazes 10% floor)")
ax.plot(soc_over / (1.20 * e_min) * 100.0, "-.", color="#2E8B57", lw=1.8, label=f"Oversized 1.20 E_min ({1.20*e_min:.1f} MWh)")
ax.axhline(10.0, color="k", ls=":", lw=1.4, label="10% minimum reserve contract")
ax.set_xlabel("Simulation time $t$ [hours]")
ax.set_ylabel("Battery state of charge [%]")
ax.set_title("Battery sized by binary search on the answer")
ax.legend(fontsize=8.2)
plt.show()
assert bat_opt["feasible"] and simulate_microgrid_soc(e_min)[0] and not simulate_microgrid_soc(e_min - 1.0e-6)[0]
assert fleet_opt["feasible"] and fleet_finishes_on_time(k_min) and not fleet_finishes_on_time(k_min - 1)
Demonstration 2: Parametric binary search — microgrid battery sizing and autoclave fleet dispatch
=================================================================================================
Minimum microgrid battery E_min = 228.232777 MWh found in 41 forward simulations
Minimum parallel autoclave fleet K_min = 4 units (evals = 6 vs 28 linear scan)

Figure 4.2. State of charge of the microgrid battery over the synthetic seven-day record. At the bisected capacity (solid) the battery just touches the 10 % reserve (dotted) at the bottom of the calm, cloudy spell; at it runs empty, at it keeps a margin.
In the solid blue curve the battery sized at just touches the reserve floor at the bottom of the calm, cloudy spell and then recovers; a battery smaller fails. The bisection needed 41 simulations and no derivatives.
3. Piggybacking Global Inversions onto MergeSort (mergesort_with_inversions)¶
In stratified ocean/atmospheric columns (buoyancy density inversions where heavier fluid sits above lighter fluid) and sensor rank-correlation tests, an inversion is a pair of indices with . Counting all pairs takes .
Mental Move #12, Piggyback Global Counts onto Divide-and-Conquer: During the merge step of divide_spatial.mergesort_with_inversions, both left and right halves are already sorted. Whenever left[i] > right[j], every remaining element in left[i : nl] is also strictly greater than right[j], contributing nl - i cross-inversions in a single integer addition.
heading("Demonstration 3: O(N log N) stratification disorder and inversion counting via MergeSort")
# Verify boundary cases: sorted (0), reverse-sorted (N*(N-1)//2), and random against O(N^2) oracle:
n_check = 120
sorted_res = divide_spatial.mergesort_with_inversions(np.arange(n_check, dtype=float))
rev_res = divide_spatial.mergesort_with_inversions(np.arange(n_check, 0, -1, dtype=float))
rng_inv = np.random.default_rng(19)
noisy_col = np.linspace(1020.0, 1028.0, n_check) + rng_inv.normal(0.0, 1.2, size=n_check)
ms_res = divide_spatial.mergesort_with_inversions(noisy_col)
oracle_inv = sum(1 for i in range(n_check) for j in range(i + 1, n_check) if noisy_col[i] > noisy_col[j])
print(f"Sorted inversions : {sorted_res['inversions']} (exact = 0)")
print(f"Reverse-sorted inversions : {rev_res['inversions']} (exact N(N-1)/2 = {n_check*(n_check-1)//2})")
print(f"Turbulent density profile : MergeSort = {ms_res['inversions']} vs Brute-Force = {oracle_inv} (comps = {ms_res['comparisons']} vs {n_check*(n_check-1)//2})")
sizes_ms = np.array([100, 200, 400, 800, 1600, 3200], dtype=float)
comps_ms = [divide_spatial.mergesort_with_inversions(rng_inv.normal(size=int(s)))["comparisons"] for s in sizes_ms]
fit_ms = invariants_complexity.fit_empirical_complexity(sizes_ms, np.array(comps_ms, dtype=float))
print(f"MergeSort empirical complexity class: {fit_ms['complexity_class']} (fitted p = {fit_ms['exponent_p']:.3f})")
assert sorted_res["inversions"] == 0
assert rev_res["inversions"] == n_check * (n_check - 1) // 2
assert ms_res["inversions"] == oracle_inv
assert np.all(np.diff(ms_res["sorted"]) >= 0.0)
assert fit_ms["complexity_class"] == "O(N log N)"
Demonstration 3: O(N log N) stratification disorder and inversion counting via MergeSort
========================================================================================
Sorted inversions : 0 (exact = 0)
Reverse-sorted inversions : 7140 (exact N(N-1)/2 = 7140)
Turbulent density profile : MergeSort = 1082 vs Brute-Force = 1082 (comps = 613 vs 7140)
MergeSort empirical complexity class: O(N log N) (fitted p = 1.189)
At ,
mergesort_with_inversionscounts the inversions in comparisons instead of , a factor of 154 fewer. For the ratio estimated from is about .
4. Derivative-Free Unimodal Optimization: Golden-Section Search¶
What if we want to minimize a continuous cost (such as annualized pipe capital + turbulent pumping OPEX + non-differentiable V-shaped thermal expansion penalty ) without derivatives? Binary search does not apply directly to values unless we compute derivatives, because goes down then up (unimodal). Golden-Section Search places interior probes at golden-ratio fractions and (), reusing one interior evaluation on every step to shrink the bracket by .
heading("Demonstration 4: Golden-section unimodal optimization on non-smooth pipe total annual cost")
def total_pipe_cost_nonsmooth(diam_m: float) -> float:
"""Annualized pipe CAPEX + pumping power + non-differentiable flange-adapter kinks [kUSD/yr]."""
capex = 42.0 * (diam_m ** 1.55)
pumping = 0.048 * (diam_m ** (-4.75))
kink_penalty = 3.2 * abs(diam_m - 0.25) + 1.8 * max(0.0, 0.18 - diam_m)
return capex + pumping + kink_penalty
def golden_section_minimize(fn, a: float, b: float, tol: float = 1.0e-10) -> dict:
"""Minimize strictly unimodal function fn on [a, b] reusing one interior evaluation per iteration."""
inv_phi = (math.sqrt(5.0) - 1.0) / 2.0 # 0.6180339887...
inv_phi2 = (3.0 - math.sqrt(5.0)) / 2.0 # 0.3819660112...
left, right = float(a), float(b)
h = right - left
x1 = left + inv_phi2 * h
x2 = left + inv_phi * h
f1, f2 = fn(x1), fn(x2)
evals = 2
while h > tol:
h *= inv_phi
evals += 1
if f1 < f2:
right, x2, f2 = x2, x1, f1
x1 = left + inv_phi2 * h
f1 = fn(x1)
else:
left, x1, f1 = x1, x2, f2
x2 = left + inv_phi * h
f2 = fn(x2)
x_opt = 0.5 * (left + right)
return {"x_min": x_opt, "f_min": fn(x_opt), "evaluations": evals + 1}
gs_res = golden_section_minimize(total_pipe_cost_nonsmooth, a=0.08, b=0.60, tol=1.0e-10)
d_grid = np.linspace(0.08, 0.60, 4000)
j_grid = np.array([total_pipe_cost_nonsmooth(float(d)) for d in d_grid])
d_grid_best = float(d_grid[int(np.argmin(j_grid))])
print(f"Golden-section optimal diameter D* = {gs_res['x_min']:.9f} m (min cost = {gs_res['f_min']:.6f} kUSD/yr) in {gs_res['evaluations']} evals")
assert abs(gs_res["x_min"] - d_grid_best) < 2.0e-4
assert gs_res["f_min"] <= float(np.min(j_grid)) + 1.0e-12
Demonstration 4: Golden-section unimodal optimization on non-smooth pipe total annual cost
==========================================================================================
Golden-section optimal diameter D* = 0.402569367 m (min cost = 14.355057 kUSD/yr) in 50 evals
Inside the algorithm¶
We inspect divide_spatial.parametric_binary_search_min and divide_spatial.mergesort_with_inversions, and implement Hoare/Dijkstra Randomized Quickselect (quickselect_kth_order_statistic), which combines Lecture 2’s 3-way partition invariant with Lecture 4’s root-dominated recursion ( expected comparisons) to find the exact median or -th quantile without sorting the discarded half.
Check against the library¶
heading("Inside the algorithm: Parametric search, MergeSort and O(N) randomized quickselect")
print(show_source(divide_spatial.parametric_binary_search_min))
print(show_source(divide_spatial.mergesort_with_inversions))
def quickselect_kth_order_statistic(values: np.ndarray, k_index: int, seed: int = 0) -> dict:
"""Select exact 0-indexed k-th smallest element in O(N) expected comparisons via 3-way partition pruning."""
work = np.asarray(values, dtype=float).ravel().copy()
if not (0 <= k_index < work.size):
raise ValueError("Require 0 <= k_index < len(values).")
rng = np.random.default_rng(seed)
lo_b, hi_b = 0, work.size - 1
total_comps = 0
while lo_b < hi_b:
piv = float(work[int(rng.integers(lo_b, hi_b + 1))])
# 3-way partition work[lo_b : hi_b + 1] around piv -> handles massive duplicate ties in O(N)
lt, i, gt = lo_b, lo_b, hi_b
while i <= gt:
total_comps += 1
if work[i] < piv:
work[lt], work[i] = work[i], work[lt]
lt += 1
i += 1
elif work[i] > piv:
total_comps += 1
work[i], work[gt] = work[gt], work[i]
gt -= 1
else:
total_comps += 1
i += 1
if k_index < lt:
hi_b = lt - 1
elif k_index > gt:
lo_b = gt + 1
else:
return {"kth_value": piv, "comparisons": total_comps}
return {"kth_value": float(work[lo_b]), "comparisons": total_comps}
rng_qs = np.random.default_rng(123)
big_arr = rng_qs.normal(100.0, 15.0, size=4096)
qs_med = quickselect_kth_order_statistic(big_arr, k_index=2048, seed=7)
ms_full = divide_spatial.mergesort_with_inversions(big_arr)
print(f"N = 4096 median -> Quickselect = {qs_med['kth_value']:.10f} ({qs_med['comparisons']:,d} comps) vs MergeSort = {ms_full['sorted'][2048]:.10f} ({ms_full['comparisons']:,d} comps)")
assert qs_med["kth_value"] == float(ms_full["sorted"][2048])
assert qs_med["comparisons"] < 0.45 * ms_full["comparisons"]
Inside the algorithm: Parametric search, MergeSort and O(N) randomized quickselect
==================================================================================
def parametric_binary_search_min(
predicate: Callable[[float], bool],
lo: float,
hi: float,
tol: float = 1e-9,
max_iter: int = 80,
) -> dict:
"""Binary-search the minimum real x in [lo, hi] satisfying a monotone predicate (False ... False, True ... True)."""
if lo > hi or tol <= 0.0:
raise ValueError("Require lo <= hi and tol > 0.")
evals = 1
if not predicate(float(hi)):
return {"threshold": math.nan, "evaluations": evals, "feasible": False}
evals += 1
if predicate(float(lo)):
return {"threshold": float(lo), "evaluations": evals, "feasible": True}
left, right = float(lo), float(hi)
for _ in range(max_iter):
if (right - left) <= tol:
break
mid = 0.5 * (left + right)
evals += 1
if predicate(mid):
right = mid
else:
left = mid
return {"threshold": right, "evaluations": evals, "feasible": True}
def mergesort_with_inversions(values: np.ndarray) -> dict:
"""Sort 1-D array in O(N log N) via divide-and-conquer MergeSort while counting exact pairwise inversions."""
arr = np.asarray(values, dtype=float).ravel().tolist()
stats = [0, 0] # [inversions, comparisons]
def _sort(sub: list[float]) -> list[float]:
n = len(sub)
if n <= 1:
return sub
mid = n // 2
left = _sort(sub[:mid])
right = _sort(sub[mid:])
merged: list[float] = []
i = 0
j = 0
nl = len(left)
nr = len(right)
while i < nl and j < nr:
stats[1] += 1
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
# Every remaining element in sorted left[i:] is strictly > right[j].
stats[0] += nl - i
j += 1
if i < nl:
merged.extend(left[i:])
if j < nr:
merged.extend(right[j:])
return merged
sorted_list = _sort(arr)
return {
"sorted": np.array(sorted_list, dtype=float),
"inversions": stats[0],
"comparisons": stats[1],
}
N = 4096 median -> Quickselect = 99.9655620645 (10,825 comps) vs MergeSort = 99.9655620645 (43,978 comps)
Exercises¶
Worked solutions are in 04_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify the exact identity using
divide_spatial.mergesort_with_inversionsagainst concordant/discordant pair counting across identity (), reverse (), and 30 random permutations of distinct sensors.Find how it fails. Demonstrate (a) how
parametric_binary_search_minfails silently on a non-monotone rotor resonance predicate over with resonance peaks near 35 and 78 rad/s (the search misses the unsafe band around 78 rad/s), and (b) how changing<=to<in MergeSort fabricates fake inversions on a constant sensor vector.Implement it yourself. Implement
min_relay_radius_connected(coords, max_hops)using BFS from gateway station0insidedivide_spatial.parametric_binary_search_minonconstants_benchmarks.make_sensor_station_coords(n_stations=50, seed=42). Verify monotonically decreasing acrossmax_hops in [1, 2, 3, 4, 6, 49], cross-check against exact discrete pairwise distance binary search, and plot the 4-hop radio relay tree.
heading("Self-check for the exercises")
assert bat_opt["feasible"] and fleet_opt["feasible"]
assert ms_res["inversions"] == oracle_inv
assert qs_med["kth_value"] == float(ms_full["sorted"][2048])
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.