Why can paying overtime to speed up most of the tasks in a chemical plant turnaround save no time at all on the restart date? And how can a new road with zero travel time make every commuter slower (Braess 1968)? Both questions are answered by Mental Move #20, Optimize Only Zero-Slack Critical Bottlenecks. In this lecture, you will compute topological schedules, slack floats, and critical paths on dependency DAGs (reductions_constraints.critical_path_dag), uncover the Critical Path Shift trap during task crashing, pinpoint single-point-of-failure network bridges, simulate Braess’s Paradox (selfish Nash equilibrium vs. social optimum), and check max-flow / min-cut duality.
Learning objectives¶
Execute Kahn’s topological sort plus forward/backward pass relaxation (
reductions_constraints.critical_path_dag) to compute earliest/latest schedules, total slack floats, and zero-slack critical paths.Explain why expediting positive-slack tasks saves zero project time and identify exact ‘Critical Path Shift’ knees when crashing bottleneck tasks.
Audit infrastructure networks for single-point-of-failure cut-edges and reproduce Braess’s (1968) Paradox where adding network capacity degrades selfish Wardrop/Nash equilibrium.
Verify Edmonds–Karp Max-Flow == Min-Cut duality and implement stochastic PERT Monte Carlo scheduling to quantify Jensen’s merge-bias delay ().
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. Dependency DAGs, Kahn’s Topological Sort & Critical Path Slack¶
A complex engineering build consists of tasks with durations and precedence edges (“ must finish before can start”). If has a directed cycle, the schedule deadlocks; otherwise Kahn’s in-degree algorithm yields a topological order enabling two linear-time passes:
Forward Pass (Earliest Start / Finish):
Backward Pass (Latest Start / Finish without delaying ):
The difference is the total float task can slip without delaying . Tasks with form the Critical Path—the longest path in the DAG.
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()
Demonstration 1: Plant turnaround critical path, Gantt schedule and slack floats
================================================================================
Mental Move #20 (Optimize Only Zero-Slack Critical Bottlenecks): slack(u) = LS(u) - ES(u) == 0 defines critical path
Task | Dur [h] | ES [h] | EF [h] | LS [h] | Slack [h] | Status
----------------------------------------------------------------------------
A_Purge | 6.0 | 0.0 | 6.0 | 0.0 | 0.0 | CRITICAL
B_Scaffold | 4.0 | 0.0 | 4.0 | 2.0 | 2.0 | buffered
E_Exchanger | 10.0 | 6.0 | 16.0 | 18.0 | 12.0 | buffered
C_ReactorOpen | 8.0 | 6.0 | 14.0 | 6.0 | 0.0 | CRITICAL
F_PipingWeld | 7.0 | 4.0 | 11.0 | 16.0 | 12.0 | buffered
D_Catalyst | 14.0 | 14.0 | 28.0 | 14.0 | 0.0 | CRITICAL
G_ValveCalib | 5.0 | 11.0 | 16.0 | 23.0 | 12.0 | buffered
H_HydroTest | 6.0 | 28.0 | 34.0 | 28.0 | 0.0 | CRITICAL
I_Startup | 5.0 | 34.0 | 39.0 | 34.0 | 0.0 | CRITICAL

Figure 11.1. Gantt chart of the nine turnaround tasks at their earliest start times. Critical tasks (red) have zero slack; for the other tasks (blue) the hatched bar shows the slack, 2 to 12 h. The project takes 39 h.
What Demonstration 1 shows. Out of 9 turnaround tasks, 4 (B_Scaffold, E_Exchanger, F_PipingWeld, G_ValveCalib) carry 2 to 12 hours of slack float. Paying double-time emergency crews to finish E_Exchanger 5 hours early saves 0.0 hours on plant restart because H_HydroTest is still waiting on D_Catalyst (EF = 28 h).
2. Task Crashing Sensitivity & The Bottleneck Knee¶
What happens as we progressively crash (expedite) critical task D_Catalyst ()? Look at the parallel paths feeding H_HydroTest:
Primary critical branch
A -> C -> D: .Secondary branch
A -> E: (slack ), andB -> F -> G: (slack ).
So D_Catalyst can be shortened by up to before A -> C -> D ties with A -> E and B -> F -> G at . Beyond it is no longer the only bottleneck, and the project duration stays at .
heading("Demonstration 2: Crashing non-critical tasks (0 savings) against critical bottleneck knee")
# 1. Crash ALL 4 non-critical tasks by 50% simultaneously -> saves 0.0 hours
tasks_noncrit_crashed = dict(tasks_turnaround)
for u_nc in ["B_Scaffold", "E_Exchanger", "F_PipingWeld", "G_ValveCalib"]:
tasks_noncrit_crashed[u_nc] *= 0.5
cpm_nc = reductions_constraints.critical_path_dag(tasks_noncrit_crashed, deps_turnaround)
assert np.isclose(cpm_nc["project_duration"], cpm["project_duration"], atol=1e-12)
# 2. Sweep crashing reduction delta_d on critical D_Catalyst from 0 to 14 hours:
crash_hrs = np.linspace(0.0, 14.0, 29)
dur_vs_crash = np.zeros_like(crash_hrs)
for idx, dh in enumerate(crash_hrs):
t_mod = dict(tasks_turnaround)
t_mod["D_Catalyst"] = 14.0 - float(dh)
dur_vs_crash[idx] = reductions_constraints.critical_path_dag(t_mod, deps_turnaround)["project_duration"]
# Slope is -1.0 hour/hour for dh <= 12.0 h, then 0.0 hour/hour for dh > 12.0 h (Critical Path Shift):
assert np.isclose(dur_vs_crash[0], 39.0, atol=1e-12)
assert np.isclose(dur_vs_crash[24], 27.0, atol=1e-12) # At dh = 12 h: 39 - 12 = 27 h
assert np.isclose(dur_vs_crash[-1], 27.0, atol=1e-12) # At dh = 14 h: STILL 27 h
print(f"Crashing all 4 non-critical tasks by 50% : {cpm['project_duration']:.1f} h -> {cpm_nc['project_duration']:.1f} h (0.0 h saved: these tasks have slack)")
print(f"Crashing D_Catalyst by 12 h (14 -> 2 h) : 39.0 h -> {dur_vs_crash[24]:.1f} h (12.0 h saved, 1:1 return)")
print(f"Crashing D_Catalyst by 14 h (14 -> 0 h) : 39.0 h -> {dur_vs_crash[-1]:.1f} h (parallel paths E & G took over at 27.0 h)")
fig, ax = plt.subplots(figsize=(7.2, 3.9))
ax.plot(crash_hrs, dur_vs_crash, marker="o", ms=4.5, lw=2.3, color="#C0392B", label="Crashing the critical task D_Catalyst")
ax.axhline(39.0, lw=1.9, ls="--", color="#2166AC", label="Crashing non-critical tasks (flat 39.0 h)")
ax.axvline(12.0, lw=1.5, ls=":", color="#2E8B57", label="Bottleneck shift knee ($\\Delta d = 12\\ \\mathrm{h}$)")
ax.set_xlabel("Hours removed from D_Catalyst [h]")
ax.set_ylabel("Total turnaround makespan $T^*$ [h]")
ax.set_title("Project duration against hours removed from D_Catalyst")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 2: Crashing non-critical tasks (0 savings) against critical bottleneck knee
=========================================================================================
Crashing all 4 non-critical tasks by 50% : 39.0 h -> 39.0 h (0.0 h saved: these tasks have slack)
Crashing D_Catalyst by 12 h (14 -> 2 h) : 39.0 h -> 27.0 h (12.0 h saved, 1:1 return)
Crashing D_Catalyst by 14 h (14 -> 0 h) : 39.0 h -> 27.0 h (parallel paths E & G took over at 27.0 h)

Figure 11.2. Project duration against the hours by which D_Catalyst is shortened. Each hour saves one hour until 12 h (dotted), when the parallel branches become critical; shortening the non-critical tasks (dashed) saves nothing.
What Demonstration 2 shows. Shortening any task off the critical path does not change the project duration ( whenever ), the same lesson as Amdahl’s law for parallel programs. Shortening D_Catalyst returns one hour per hour up to and nothing after that.
3. Infrastructure Vulnerability: Single-Point-of-Failure Bridges vs. Redundant Meshes¶
Just as zero-slack tasks govern time schedules, cut-edges (bridges) and minimum-cut bottlenecks govern spatial infrastructure resilience (power grids, water trunklines, data center interconnects). We audit every link of an 8-substation regional transmission graph by measuring the disconnected load or capacity drop when link fails.
heading("Demonstration 3: Single-point-of-failure bridge and link-outage sensitivity audit")
from collections import deque
# 8-node regional water/power corridor: two redundant rings (0-1-2-3 and 4-5-6-7) joined by a SINGLE bridge (3 -> 4)
edges_infra = [
(0, 1, 50.0), (0, 2, 50.0), (1, 3, 50.0), (2, 3, 50.0), # West redundant diamond (cap = 100)
(3, 4, 85.0), # Central canyon bridge (SINGLE POINT OF FAILURE)
(4, 5, 50.0), (4, 6, 50.0), (5, 7, 50.0), (6, 7, 50.0), # East redundant diamond (cap = 100)
]
def edmonds_karp_flow_val(n_v: int, edge_list: list[tuple[int, int, float]], src: int, sink: int) -> float:
cap = np.zeros((n_v, n_v), dtype=float)
for u, v, c in edge_list:
cap[u, v] += c
flow = 0.0
while True:
parent = [-1] * n_v
parent[src] = src
q = deque([src])
while q and parent[sink] == -1:
u = q.popleft()
for v in range(n_v):
if parent[v] == -1 and cap[u, v] > 1e-12:
parent[v] = u
q.append(v)
if parent[sink] == -1:
break
aug = math.inf
v = sink
while v != src:
aug = min(aug, cap[parent[v], v])
v = parent[v]
v = sink
while v != src:
u = parent[v]
cap[u, v] -= aug
cap[v, u] += aug
v = u
flow += aug
return float(flow)
f_nom = edmonds_karp_flow_val(8, edges_infra, 0, 7)
assert np.isclose(f_nom, 85.0, atol=1e-12) # Bottlenecked by bridge (3->4) of capacity 85, NOT the 100-MW diamonds
edge_names = []
rem_flows = []
for idx, (u, v, _) in enumerate(edges_infra):
sub_edges = [e for k, e in enumerate(edges_infra) if k != idx]
edge_names.append(f"{u}->{v}")
rem_flows.append(edmonds_karp_flow_val(8, sub_edges, 0, 7))
rem_flows_arr = np.array(rem_flows)
loss_pct = 100.0 * (f_nom - rem_flows_arr) / f_nom
assert np.isclose(rem_flows_arr[4], 0.0, atol=1e-12) # Bridge 3->4 outage causes 100% blackout
assert np.allclose(rem_flows_arr[:4], 50.0, atol=1e-12) # Diamond link outage retains 50 MW via parallel leg
for nm, rf, lp in zip(edge_names, rem_flows_arr, loss_pct):
print(f"Outage on link {nm:5s} : Remaining Flow = {rf:5.1f} MW (Capacity Loss = {lp:5.1f}%)")
fig, ax = plt.subplots(figsize=(7.4, 3.8))
colors_bar = ["#C0392B" if lp > 90.0 else "#2166AC" for lp in loss_pct]
ax.bar(edge_names, loss_pct, color=colors_bar, width=0.58)
ax.set_xlabel("Removed corridor link $(u \\rightarrow v)$")
ax.set_ylabel("System throughput loss [%]")
ax.set_title("Loss of throughput when one link fails")
plt.show()
Demonstration 3: Single-point-of-failure bridge and link-outage sensitivity audit
=================================================================================
Outage on link 0->1 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 0->2 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 1->3 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 2->3 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 3->4 : Remaining Flow = 0.0 MW (Capacity Loss = 100.0%)
Outage on link 4->5 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 4->6 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 5->7 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)
Outage on link 6->7 : Remaining Flow = 50.0 MW (Capacity Loss = 41.2%)

Figure 11.3. Loss of throughput when each link of the eight-substation network fails. Any link of the two redundant diamonds costs 41.2 %; the single bridge 3->4 costs 100 %.
What Demonstration 3 shows. Upgrading any of the eight diamond links from adds of throughput, because the bridge 3->4 limits the flow, and an outage of that one bridge still cuts the flow to zero.
4. Braess’s (1968) Paradox: a Zero-Cost Shortcut That Slows Every Trip¶
Added capacity can even make a network slower. Consider Dietrich Braess’s (1968) 4-node diamond network carrying commuters from to :
Top route : congestion-sensitive bridge [min] followed by wide highway [min].
Bottom route : wide highway [min] followed by congestion-sensitive bridge [min].
Before the Shortcut: Symmetry splits traffic ; every driver takes (the social optimum of this network without the cross-link).
After Opening an Instantaneous Cross-Link (): Because for any , every individual driver sees as strictly faster than and as strictly faster than . In the Wardrop (Nash) equilibrium all traffic takes the path , which loads both bridges fully: every trip takes , 23 % longer than before. The social optimum with the cross-link is 64.69 min on average, so the price of anarchy is .
heading("Demonstration 4: Computational simulation of Braess's (1968) routing paradox")
def solve_braess_diamond(total_flow: float, has_shortcut: bool) -> dict:
"""Compute exact Wardrop User Equilibrium (minimizing Rosenthal potential) & Social Optimum (minimizing total latency)."""
# Flow vector (f1 = S->A->T, f2 = S->B->T, f3 = S->A->B->T) with f1 + f2 + f3 = F, f_i >= 0:
# Link flows: f_SA = f1 + f3, f_BT = f2 + f3, f_AT = f1, f_SB = f2
# By symmetry f1 == f2 = (F - f3)/2 for any f3 in [0, F]
f3_grid = np.linspace(0.0, total_flow, 2001) if has_shortcut else np.array([0.0])
f12 = 0.5 * (total_flow - f3_grid)
f_sa = f12 + f3_grid # = 0.5*(F + f3)
# f_BT = f12 + f3 equals f_SA by symmetry
# Rosenthal (1973) exact potential Phi = int_0^{f_SA} (u/100) du + 45*f_AT + 45*f_SB + int_0^{f_BT} (u/100) du:
rosenthal_pot = 2.0 * (0.5 * (f_sa ** 2) / 100.0) + 45.0 * (2.0 * f12)
idx_ue = int(np.argmin(rosenthal_pot))
f3_ue = float(f3_grid[idx_ue])
f12_ue = 0.5 * (total_flow - f3_ue)
# Experienced user latency at equilibrium:
lat_zig = (f12_ue + f3_ue) / 100.0 + (f12_ue + f3_ue) / 100.0
lat_outer = (f12_ue + f3_ue) / 100.0 + 45.0
ue_latency = lat_zig if f3_ue > total_flow - 1e-6 else (lat_outer if f3_ue < 1e-6 else lat_zig)
# Total system travel time C_tot = f_SA*(f_SA/100) + f_AT*45 + f_SB*45 + f_BT*(f_BT/100):
tot_cost = 2.0 * ((f_sa ** 2) / 100.0) + 90.0 * f12
idx_so = int(np.argmin(tot_cost))
so_avg_latency = float(tot_cost[idx_so] / total_flow)
return {"ue_latency": float(ue_latency), "so_latency": so_avg_latency, "shortcut_share": f3_ue / total_flow}
b_4000_before = solve_braess_diamond(4000.0, has_shortcut=False)
b_4000_after = solve_braess_diamond(4000.0, has_shortcut=True)
assert np.isclose(b_4000_before["ue_latency"], 65.0, atol=1e-9)
assert np.isclose(b_4000_after["ue_latency"], 80.0, atol=1e-9) # +15 min slower for EVERY commuter
assert np.isclose(b_4000_after["so_latency"], 64.6875, atol=1e-2) # Social planner barely uses shortcut (f3* = 500 -> 258,750/4,000)
assert np.isclose(b_4000_after["shortcut_share"], 1.0, atol=1e-9)
demands = np.linspace(500.0, 6000.0, 111)
ue_before = np.array([solve_braess_diamond(float(d), False)["ue_latency"] for d in demands])
ue_after = np.array([solve_braess_diamond(float(d), True)["ue_latency"] for d in demands])
so_after = np.array([solve_braess_diamond(float(d), True)["so_latency"] for d in demands])
# Paradox zone: for F in (3000, 6000) roughly (specifically 2*F/100 > F/200 + 45 => F > 3000 up to F < 9000):
assert np.all(ue_after[demands > 3100.0] > ue_before[demands > 3100.0])
print(f"At F = 4,000 commuters without shortcut : Nash Equilibrium = {b_4000_before['ue_latency']:.1f} min")
print(f"At F = 4,000 commuters with 0-min link : Nash Equilibrium = {b_4000_after['ue_latency']:.1f} min (+15.0 min Braess Paradox)")
print(f"At F = 4,000 Social Optimum with link : Avg Latency = {b_4000_after['so_latency']:.2f} min (Price of Anarchy = {b_4000_after['ue_latency']/b_4000_after['so_latency']:.3f})")
fig, ax = plt.subplots(figsize=(7.5, 4.1))
ax.plot(demands, ue_before, lw=2.2, ls="--", color="#2166AC", label="Nash equilibrium before shortcut")
ax.plot(demands, ue_after, lw=2.4, color="#C0392B", label="Nash equilibrium after 0-min shortcut")
ax.plot(demands, so_after, lw=2.0, ls=":", color="#2E8B57", label="Social optimum (coordinated routing)")
ax.fill_between(demands, ue_before, ue_after, where=(ue_after > ue_before), color="#C0392B", alpha=0.15, label="Braess paradox zone (shortcut hurts)")
ax.set_xlabel("Total network demand $F$ [vehicles/h]")
ax.set_ylabel("Equilibrium commute time [min]")
ax.set_title("Braess's paradox: travel time against demand")
ax.legend(fontsize=8.2)
plt.show()
Demonstration 4: Computational simulation of Braess's (1968) routing paradox
============================================================================
At F = 4,000 commuters without shortcut : Nash Equilibrium = 65.0 min
At F = 4,000 commuters with 0-min link : Nash Equilibrium = 80.0 min (+15.0 min Braess Paradox)
At F = 4,000 Social Optimum with link : Avg Latency = 64.69 min (Price of Anarchy = 1.237)

Figure 11.4. Braess’s network: equilibrium travel time against the demand . Above about 3,000 vehicles per hour the Wardrop equilibrium with the zero-time cross-link (solid) is slower than without it (dashed); at the times are 80 and 65 min. The dotted curve is the social optimum with the link.
Inside the algorithm¶
Critical paths and flow networks share a duality between a bottleneck and a bound:
Longest Path (Critical Path) Minimum Project Makespan (you cannot finish faster than your longest serial chain, and setting start times achieves that exact chain length).
Maximum - Flow Minimum - Cut Capacity (Ford & Fulkerson, 1956): when Edmonds–Karp terminates with no augmenting path in the residual network , the set of vertices still reachable from
srcin defines an - cut whose saturated forward capacity equalsmax_flow. We inspectcritical_path_dagand check Max-Flow / Min-Cut duality from scratch.
Check against the library¶
heading("Inside the algorithm: critical_path_dag and Edmonds-Karp max-flow / min-cut duality")
print(show_source(reductions_constraints.critical_path_dag))
from collections import deque
def max_flow_min_cut_edmonds_karp(cap_matrix: np.ndarray, src: int, sink: int) -> dict:
"""Compute exact Max-Flow and constructively extract the Minimum Cut (S_cut, T_cut) via residual reachability."""
res = np.asarray(cap_matrix, dtype=float).copy()
orig = res.copy()
n = res.shape[0]
max_flow = 0.0
while True:
parent = np.full(n, -1, dtype=int)
parent[src] = src
q = deque([src])
while q and parent[sink] == -1:
u = q.popleft()
for v in range(n):
if parent[v] == -1 and res[u, v] > 1e-12:
parent[v] = u
q.append(v)
if parent[sink] == -1:
break
bottleneck = math.inf
v = sink
while v != src:
bottleneck = min(bottleneck, float(res[parent[v], v]))
v = int(parent[v])
v = sink
while v != src:
u = int(parent[v])
res[u, v] -= bottleneck
res[v, u] += bottleneck
v = u
max_flow += bottleneck
# Residual BFS from src identifies the exact Min-Cut partition S_cut:
s_reach = np.zeros(n, dtype=bool)
s_reach[src] = True
q_cut = deque([src])
while q_cut:
u = q_cut.popleft()
for v in range(n):
if not s_reach[v] and res[u, v] > 1e-12:
s_reach[v] = True
q_cut.append(v)
s_nodes = [i for i in range(n) if s_reach[i]]
t_nodes = [i for i in range(n) if not s_reach[i]]
cut_edges = [(u, v, float(orig[u, v])) for u in s_nodes for v in t_nodes if orig[u, v] > 0.0]
cut_cap = sum(c for _, _, c in cut_edges)
return {"max_flow": max_flow, "min_cut_capacity": cut_cap, "S_cut": s_nodes, "T_cut": t_nodes, "cut_edges": cut_edges}
# Test on a 6-node refinery pipeline network and cross-check against all 2^(6-2) = 16 s-t cuts:
cap_pipe = np.array([
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
], dtype=float)
ek = max_flow_min_cut_edmonds_karp(cap_pipe, src=0, sink=5)
assert np.isclose(ek["max_flow"], 23.0, atol=1e-12)
assert np.isclose(ek["max_flow"], ek["min_cut_capacity"], atol=1e-12)
# Exhaustively evaluate all 2^4 = 16 s-t cuts separating node 0 from node 5:
all_cuts = []
for mask in range(1 << 4):
s_set = {0} | {k + 1 for k in range(4) if (mask >> k) & 1}
t_set = set(range(6)) - s_set
all_cuts.append(sum(float(cap_pipe[u, v]) for u in s_set for v in t_set))
assert np.isclose(min(all_cuts), ek["max_flow"], atol=1e-12)
print(f"Max-Flow = {ek['max_flow']:.1f} == Min-Cut Capacity = {ek['min_cut_capacity']:.1f} (Brute-force min over 16 cuts = {min(all_cuts):.1f})")
print(f"Min-Cut Partition S = {ek['S_cut']}, T = {ek['T_cut']} | Saturated Bottleneck Pipes = {ek['cut_edges']}")
Inside the algorithm: critical_path_dag and Edmonds-Karp max-flow / min-cut duality
===================================================================================
def critical_path_dag(tasks: dict[str, float], dependencies: list[tuple[str, str]]) -> dict:
"""Compute topological order, earliest/latest schedules, slack floats, and critical path on a project DAG."""
if not tasks or any(d < 0.0 for d in tasks.values()):
raise ValueError("Require non-empty tasks with durations >= 0.")
adj: dict[str, list[str]] = {u: [] for u in tasks}
preds: dict[str, list[str]] = {u: [] for u in tasks}
indeg: dict[str, int] = {u: 0 for u in tasks}
for u, v in dependencies:
if u not in tasks or v not in tasks:
raise ValueError(f"Unknown task in dependency ({u!r}, {v!r}).")
adj[u].append(v)
preds[v].append(u)
indeg[v] += 1
q: deque[str] = deque(sorted([u for u, deg in indeg.items() if deg == 0]))
topo: list[str] = []
while q:
u = q.popleft()
topo.append(u)
for v in sorted(adj[u]):
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
if len(topo) != len(tasks):
raise ValueError("Dependency graph contains a cycle; Critical Path Method requires a DAG.")
es: dict[str, float] = {}
ef: dict[str, float] = {}
for u in topo:
es[u] = max((ef[p] for p in preds[u]), default=0.0)
ef[u] = es[u] + float(tasks[u])
proj_dur = max(ef.values())
ls: dict[str, float] = {}
lf: dict[str, float] = {}
for u in reversed(topo):
lf[u] = min((ls[v] for v in adj[u]), default=proj_dur)
ls[u] = lf[u] - float(tasks[u])
slack = {u: ls[u] - es[u] for u in topo}
crit_nodes = [u for u in topo if abs(slack[u]) < 1e-11]
return {
"topological_order": topo,
"project_duration": float(proj_dur),
"earliest_start": es,
"earliest_finish": ef,
"latest_start": ls,
"latest_finish": lf,
"slack": slack,
"critical_path": crit_nodes,
}
Max-Flow = 23.0 == Min-Cut Capacity = 23.0 (Brute-force min over 16 cuts = 23.0)
Min-Cut Partition S = [0, 1, 2, 4], T = [3, 5] | Saturated Bottleneck Pipes = [(1, 3, 12.0), (4, 3, 7.0), (4, 5, 4.0)]
Exercises¶
Worked solutions are in 11_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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.
Find how it fails. Verify all
ValueErrorguards oncritical_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.Implement it yourself. 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("Self-check for the exercises")
assert np.isclose(cpm["project_duration"], 39.0, atol=1e-12) and np.isclose(cpm_nc["project_duration"], 39.0, atol=1e-12)
assert np.isclose(rem_flows_arr[4], 0.0, atol=1e-12)
assert np.isclose(b_4000_before["ue_latency"], 65.0) and np.isclose(b_4000_after["ue_latency"], 80.0)
assert np.isclose(ek["max_flow"], ek["min_cut_capacity"], atol=1e-12)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.