Worked solutions to the three exercises of Lecture 11. 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: Plant turnaround critical path, Gantt schedule and slack floats")
mm20 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 20][0]
print(f"Mental Move #{mm20['id']} ({mm20['name']}): {mm20['invariant']}")
tasks_turnaround = {
"A_Purge": 6.0,
"B_Scaffold": 4.0,
"C_ReactorOpen": 8.0,
"D_Catalyst": 14.0,
"E_Exchanger": 10.0,
"F_PipingWeld": 7.0,
"G_ValveCalib": 5.0,
"H_HydroTest": 6.0,
"I_Startup": 5.0,
}
deps_turnaround = [
("A_Purge", "C_ReactorOpen"),
("A_Purge", "E_Exchanger"),
("B_Scaffold", "C_ReactorOpen"),
("B_Scaffold", "F_PipingWeld"),
("C_ReactorOpen", "D_Catalyst"),
("E_Exchanger", "H_HydroTest"),
("F_PipingWeld", "G_ValveCalib"),
("D_Catalyst", "H_HydroTest"),
("G_ValveCalib", "H_HydroTest"),
("H_HydroTest", "I_Startup"),
]
cpm = reductions_constraints.critical_path_dag(tasks_turnaround, deps_turnaround)
assert np.isclose(cpm["project_duration"], 39.0, atol=1e-12) # A(6)->C(8)->D(14)->H(6)->I(5) = 39 h
assert cpm["critical_path"] == ["A_Purge", "C_ReactorOpen", "D_Catalyst", "H_HydroTest", "I_Startup"]
print(f"{'Task':15s} | {'Dur [h]':>7s} | {'ES [h]':>7s} | {'EF [h]':>7s} | {'LS [h]':>7s} | {'Slack [h]':>9s} | {'Status'}")
print("-" * 76)
for t_name in cpm["topological_order"]:
es_t = cpm["earliest_start"][t_name]
ef_t = cpm["earliest_finish"][t_name]
ls_t = cpm["latest_start"][t_name]
sl_t = cpm["slack"][t_name]
tag = "CRITICAL" if t_name in cpm["critical_path"] else "buffered"
print(f"{t_name:15s} | {tasks_turnaround[t_name]:7.1f} | {es_t:7.1f} | {ef_t:7.1f} | {ls_t:7.1f} | {sl_t:9.1f} | {tag}")
fig, ax = plt.subplots(figsize=(8.0, 4.3))
order_plot = list(reversed(cpm["topological_order"]))
for y_i, u in enumerate(order_plot):
es_u = cpm["earliest_start"][u]
dur_u = tasks_turnaround[u]
sl_u = cpm["slack"][u]
is_crit = u in cpm["critical_path"]
ax.barh(y_i, dur_u, left=es_u, height=0.55, color="#C0392B" if is_crit else "#2166AC")
if sl_u > 1e-9:
ax.barh(y_i, sl_u, left=es_u + dur_u, height=0.25, color="#A9C9E8", hatch="//")
ax.set_yticks(range(len(order_plot)))
ax.set_yticklabels(order_plot)
ax.set_xlabel("Turnaround elapsed time [hours]")
ax.set_title(f"Critical path Gantt chart (total = {cpm['project_duration']:.0f} h; red = zero slack, hatched = float)")
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Across 50 random positive task-duration vectors on the 9-task turnaround DAG, verify exact primal–dual LP duality between Minimum-Time Feasible Milestone Scheduling () and Maximum Source-to-Sink Path Length (), along with precedent feasibility and complementary slackness.
heading("Exercise 1: 50-trial primal-dual verification — min makespan == max DAG path length")
deps_9 = [
("A_Purge", "C_ReactorOpen"), ("A_Purge", "E_Exchanger"),
("B_Scaffold", "C_ReactorOpen"), ("B_Scaffold", "F_PipingWeld"),
("C_ReactorOpen", "D_Catalyst"), ("E_Exchanger", "H_HydroTest"),
("F_PipingWeld", "G_ValveCalib"), ("D_Catalyst", "H_HydroTest"),
("G_ValveCalib", "H_HydroTest"), ("H_HydroTest", "I_Startup"),
]
task_keys = ["A_Purge", "B_Scaffold", "C_ReactorOpen", "D_Catalyst", "E_Exchanger", "F_PipingWeld", "G_ValveCalib", "H_HydroTest", "I_Startup"]
# Enumerate all maximal paths in the DAG once for independent oracle verification:
adj_9 = {u: [] for u in task_keys}
indeg_9 = {u: 0 for u in task_keys}
for u, v in deps_9:
adj_9[u].append(v)
indeg_9[v] += 1
all_paths: list[list[str]] = []
def _enum_paths(u: str, cur: list[str]) -> None:
if not adj_9[u]:
all_paths.append(list(cur))
return
for v in adj_9[u]:
cur.append(v)
_enum_paths(v, cur)
cur.pop()
for s_root in [u for u, d in indeg_9.items() if d == 0]:
_enum_paths(s_root, [s_root])
rng_lp = np.random.default_rng(1101)
max_duality_gap = 0.0
for _ in range(50):
d_vals = rng_lp.uniform(1.0, 20.0, size=len(task_keys))
t_dict = {k: float(v) for k, v in zip(task_keys, d_vals)}
res = reductions_constraints.critical_path_dag(t_dict, deps_9)
# 1. Primal LP schedule feasibility: ES(v) - ES(u) >= d_u and LS(v) - LS(u) >= d_u on every edge (u, v):
for u, v in deps_9:
assert res["earliest_start"][v] - res["earliest_start"][u] >= t_dict[u] - 1e-12
assert res["latest_start"][v] - res["latest_start"][u] >= t_dict[u] - 1e-12
# 2. Dual longest-path optimality: project_duration == max_{path P} sum_{u in P} d_u:
best_path = max(all_paths, key=lambda p: sum(t_dict[u] for u in p))
longest_len = sum(t_dict[u] for u in best_path)
gap = abs(res["project_duration"] - longest_len)
max_duality_gap = max(max_duality_gap, gap)
assert gap < 1e-12
# 3. Complementary slackness: every node on best_path has zero slack
for u in best_path:
assert abs(res["slack"][u]) < 1e-11
print(f"Enumerated {len(all_paths)} source-to-sink paths | Verified 50/50 random duration vectors")
print(f"Maximum Primal-Dual gap |T_makespan - L_longest_path| = {max_duality_gap:.3e} hours")
Exercise 1: 50-trial primal-dual verification — min makespan == max DAG path length
===================================================================================
Enumerated 4 source-to-sink paths | Verified 50/50 random duration vectors
Maximum Primal-Dual gap |T_makespan - L_longest_path| = 1.421e-14 hours
Explanation. Along any path , telescoping the primal precedence inequalities plus and gives Weak Duality . Forward-pass earliest start times construct a feasible schedule whose finish time equals a specific predecessor-tight chain , proving Strong Duality .
Exercise 2¶
Problem. Verify all ValueError guards on critical_path_dag (empty tasks, negative duration, unknown dependency task, and a cyclic dependency deadlock vs. naive unguarded DFS), then audit a Critical Path Shift scenario where crashing a primary task by yields only of net schedule reduction.
heading("Exercise 2: Failure-mode audit — cyclic deadlock detection and critical path shift trap")
# 0. Input & cycle guard checks:
caught = 0
for bad_args in [
({}, []),
({"A": -2.0}, []),
({"A": 3.0}, [("A", "UNKNOWN")]),
({"A": 3.0, "B": 4.0, "C": 5.0}, [("A", "B"), ("B", "C"), ("C", "A")]), # 3-cycle A->B->C->A
]:
try:
reductions_constraints.critical_path_dag(*bad_args)
except ValueError:
caught += 1
assert caught == 4
# Contrast: naive unguarded recursive longest-path function without cycle detection blows the call stack
cyc_adj = {"A": ["B"], "B": ["C"], "C": ["A"]}
def buggy_recursive_ef(u: str) -> float:
return 1.0 + max((buggy_recursive_ef(v) for v in cyc_adj[u]), default=0.0)
hit_recursion_err = False
try:
buggy_recursive_ef("A")
except RecursionError:
hit_recursion_err = True
assert hit_recursion_err
# (b) Critical Path Shift Trap:
# Start -> Primary (20 h) -> End, in parallel with Start -> Secondary (16 h, slack = 4 h) -> End:
tasks_shift = {"Start": 2.0, "Primary_Fab": 20.0, "Secondary_Pkg": 16.0, "Final_QA": 3.0}
deps_shift = [("Start", "Primary_Fab"), ("Start", "Secondary_Pkg"), ("Primary_Fab", "Final_QA"), ("Secondary_Pkg", "Final_QA")]
base_s = reductions_constraints.critical_path_dag(tasks_shift, deps_shift)
assert np.isclose(base_s["project_duration"], 25.0) and np.isclose(base_s["slack"]["Secondary_Pkg"], 4.0)
# Manager pays $50,000 ($5k/h) to crash Primary_Fab by 10 hours (20 -> 10 h), expecting 25 -> 15 h:
tasks_overcrashed = dict(tasks_shift)
tasks_overcrashed["Primary_Fab"] = 10.0
after_s = reductions_constraints.critical_path_dag(tasks_overcrashed, deps_shift)
actual_saved = base_s["project_duration"] - after_s["project_duration"]
wasted_crash_hrs = 10.0 - actual_saved
assert np.isclose(after_s["project_duration"], 21.0)
assert np.isclose(actual_saved, 4.0) and np.isclose(wasted_crash_hrs, 6.0)
assert "Secondary_Pkg" in after_s["critical_path"] and "Primary_Fab" not in after_s["critical_path"]
print("Cycle detection : Kahn's in-degree check raised clean ValueError; naive DFS crashed with RecursionError")
print(f"Critical Path Shift : Crashed Primary_Fab by 10.0 h, saved only {actual_saved:.1f} h (25 -> 21 h); 6.0 h wasted as Secondary_Pkg became critical")
Exercise 2: Failure-mode audit — cyclic deadlock detection and critical path shift trap
=======================================================================================
Cycle detection : Kahn's in-degree check raised clean ValueError; naive DFS crashed with RecursionError
Critical Path Shift : Crashed Primary_Fab by 10.0 h, saved only 4.0 h (25 -> 21 h); 6.0 h wasted as Secondary_Pkg became critical
Explanation. (a) In any cycle , every node has at least one predecessor inside , so its in-degree never drops to 0 during Kahn’s peel-off (len(topo) < len(tasks) detects every cycle in ). (b) Maximum single-task effective crash depth is bounded by the minimum slack of all parallel bypass paths (4.0 h); crashing deeper than 4.0 h requires simultaneously crashing both parallel branches.
Exercise 3¶
Problem. Implement pert_monte_carlo_schedule(tasks_abc, dependencies, n_trials=4000, seed=42) using exact Beta-PERT task-duration sampling (mean = (a + 4m + b)/6). Demonstrate Jensen’s Merge-Bias Inequality () on a parallel chip-tapeout DAG and compute P50 / P90 completion quantiles plus per-task Criticality Index (probability each task lies on the realized critical path).
heading("Exercise 3: Implement it yourself — beta-PERT stochastic scheduling and Jensen's merge bias")
def pert_monte_carlo_schedule(
tasks_abc: dict[str, tuple[float, float, float]],
dependencies: list[tuple[str, str]],
n_trials: int = 4000,
seed: int = 42,
) -> dict:
"""Monte Carlo Beta-PERT project scheduler computing expected makespan, risk quantiles, and criticality index."""
mean_tasks = {u: (a + 4.0 * m + b) / 6.0 for u, (a, m, b) in tasks_abc.items()}
det_cpm = reductions_constraints.critical_path_dag(mean_tasks, dependencies)
topo = det_cpm["topological_order"]
preds: dict[str, list[str]] = {u: [] for u in topo}
succs: dict[str, list[str]] = {u: [] for u in topo}
for u, v in dependencies:
preds[v].append(u)
succs[u].append(v)
rng = np.random.default_rng(seed)
dur_samples: dict[str, np.ndarray] = {}
for u, (a, m, b) in tasks_abc.items():
if b <= a + 1e-12:
dur_samples[u] = np.full(n_trials, float(m))
else:
alpha = 1.0 + 4.0 * (m - a) / (b - a)
beta = 1.0 + 4.0 * (b - m) / (b - a)
dur_samples[u] = a + (b - a) * rng.beta(alpha, beta, size=n_trials)
# Vectorized forward & backward passes across all n_trials simultaneously
es = {u: np.zeros(n_trials) for u in topo}
ef = {}
for u in topo:
if preds[u]:
es[u] = np.maximum.reduce([ef[p] for p in preds[u]])
ef[u] = es[u] + dur_samples[u]
proj_durs = np.maximum.reduce([ef[u] for u in topo])
ls = {}
lf = {}
for u in reversed(topo):
lf[u] = np.minimum.reduce([ls[v] for v in succs[u]]) if succs[u] else proj_durs.copy()
ls[u] = lf[u] - dur_samples[u]
crit_index = {u: float(np.mean(np.abs(ls[u] - es[u]) < 1e-10)) for u in topo}
p50, p90, p95 = np.percentile(proj_durs, [50, 90, 95])
return {
"deterministic_cpm_duration": det_cpm["project_duration"],
"expected_pert_duration": float(np.mean(proj_durs)),
"jensen_merge_bias": float(np.mean(proj_durs) - det_cpm["project_duration"]),
"p50": float(p50),
"p90": float(p90),
"p95": float(p95),
"criticality_index": crit_index,
"duration_samples": proj_durs,
}
# Parallel ASIC tapeout project with 3 near-equal parallel subsystems (Core, SerDes, MemCtrl) merging into Integration:
tapeout_abc = {
"Spec": (2.0, 3.0, 4.0), # mean = 3.0 d
"Core_RTL": (9.0, 14.0, 25.0), # mean = (9 + 56 + 25)/6 = 15.0 d (skewed tail)
"SerDes_PHY": (10.0, 14.5, 22.0), # mean = (10 + 58 + 22)/6 = 15.0 d
"Mem_Ctrl": (8.0, 14.0, 26.0), # mean = (8 + 56 + 26)/6 = 15.0 d
"SoC_Integ": (4.0, 5.0, 6.0), # mean = 5.0 d
}
tapeout_deps = [
("Spec", "Core_RTL"), ("Spec", "SerDes_PHY"), ("Spec", "Mem_Ctrl"),
("Core_RTL", "SoC_Integ"), ("SerDes_PHY", "SoC_Integ"), ("Mem_Ctrl", "SoC_Integ"),
]
pert_res = pert_monte_carlo_schedule(tapeout_abc, tapeout_deps, n_trials=4000, seed=42)
# Deterministic CPM at mean durations sees 3 + max(15, 15, 15) + 5 = 23.0 days,
# whereas E[max(X1, X2, X3)] strictly exceeds max(E[X1], E[X2], E[X3]) = 15.0 by > 2.5 days (Jensen's inequality)
assert np.isclose(pert_res["deterministic_cpm_duration"], 23.0, atol=1e-12)
assert pert_res["jensen_merge_bias"] > 2.2
assert pert_res["p90"] > 28.0
# All 3 parallel branches share non-trivial Criticality Index summing to 1.0:
ci = pert_res["criticality_index"]
assert np.isclose(ci["Core_RTL"] + ci["SerDes_PHY"] + ci["Mem_Ctrl"], 1.0, atol=1e-2)
print(f"Deterministic CPM on Mean Durations : {pert_res['deterministic_cpm_duration']:.2f} days (optimistically biased)")
print(f"Stochastic Beta-PERT Expected Time : {pert_res['expected_pert_duration']:.2f} days (Jensen merge bias = +{pert_res['jensen_merge_bias']:.2f} days)")
print(f"Schedule Risk Quantiles : P50 = {pert_res['p50']:.2f} d | P90 = {pert_res['p90']:.2f} d | P95 = {pert_res['p95']:.2f} d")
print(f"Parallel Branch Criticality Indices : Core={ci['Core_RTL']:.2f}, SerDes={ci['SerDes_PHY']:.2f}, MemCtrl={ci['Mem_Ctrl']:.2f}")
fig, ax = plt.subplots(figsize=(7.4, 4.0))
ax.hist(pert_res["duration_samples"], bins=38, density=True, color="#2166AC", alpha=0.65, edgecolor="white", label="4,000 beta-PERT realizations")
ax.axvline(pert_res["deterministic_cpm_duration"], color="#C0392B", lw=2.3, ls="--", label=f"Deterministic mean CPM ({pert_res['deterministic_cpm_duration']:.1f} d)")
ax.axvline(pert_res["expected_pert_duration"], color="#2E8B57", lw=2.3, label=f"PERT expected mean ({pert_res['expected_pert_duration']:.2f} d)")
ax.axvline(pert_res["p90"], color="#E08214", lw=2.1, ls=":", label=f"90th percentile P90 ({pert_res['p90']:.1f} d)")
ax.set_xlabel("Total tapeout completion time [days]")
ax.set_ylabel("Probability density")
ax.set_title("Distribution of the project duration (Beta-PERT)")
ax.legend(fontsize=8.2)
plt.show()
Exercise 3: Implement it yourself — beta-PERT stochastic scheduling and Jensen's merge bias
===========================================================================================
Deterministic CPM on Mean Durations : 23.00 days (optimistically biased)
Stochastic Beta-PERT Expected Time : 25.50 days (Jensen merge bias = +2.50 days)
Schedule Risk Quantiles : P50 = 25.48 d | P90 = 28.58 d | P95 = 29.56 d
Parallel Branch Criticality Indices : Core=0.33, SerDes=0.32, MemCtrl=0.35

Figure S11.1. Distribution of the project duration over 4,000 Beta-PERT samples. The mean, 25.50 days (solid), lies 2.50 days above the deterministic critical-path value (dashed); the dotted line is the 90th percentile.
Summary. Because is a convex function of parallel branch durations, Jensen’s Inequality guarantees —with strict inequality whenever parallel branches have overlapping uncertainty. Vectorized Beta-PERT simulation shows both the merge bias, +2.50 days, and the tail of the distribution ( days), which a deterministic CPM on mean durations does not show.