"""Formula delay model for the corridor (Webster + platoon delay), N lights. STAND-IN for Michael + Noah's signal_opt.py: same formulation as notes/meeting-prep-2026-11-10.txt, generalized from math-example/model.py. When their code arrives, plans from it are read through plans.py and this file is only used for Study 1's "formula prediction" column (or replaced by their evaluator). Conventions: lights ordered north -> south (index 0 = northmost). Main road = Big Bend (NB, SB); side = EB, WB. SB platoons travel light i -> i+1; NB platoons travel light i+1 -> i. A plan gives C (common cycle), per light g_main (s) and offset_s (time main green starts, relative to light 0). """ import numpy as np from scipy.optimize import minimize H = 3600.0 def webster_terms(C, g, q_vph, s_vph): q, s = q_vph/H, s_vph/H lam = g/C x = q/(lam*s) if lam > 0 else 9.9 if x >= 0.999 or lam <= 0: return 1e3, 1e3, lam, x return C*(1-lam)**2/(2*(1-lam*x)), x**2/(2*q*(1-x)), lam, x def _w_int(a, b, C, gd): gd = min(max(gd, 0.0), C) W = lambda u: 0.0 if u <= gd else C*(u-gd)-(u*u-gd*gd)/2 F = lambda t: np.floor(t/C)*W(C)+W(t-np.floor(t/C)*C) return F(b)-F(a) def platoon_delay(phi, C, g_up, g_down): return _w_int(phi, phi+g_up, C, g_down)/g_up def light_L(cor, l): """Lost time for one light: measured (timing sheet) if present, else the corridor parameter.""" return (l.get("timing") or {}).get("L_s", cor["params"]["L_s"]) def evaluate(cor, C, g_main, offsets, detail=False): """Total delay in vehicle-hours per hour. g_main, offsets: lists in corridor order.""" P = cor["params"]; p = P["p"] lights, links = cor["lights"], cor["links"] n = len(lights); total = 0.0; rows = [] for i, l in enumerate(lights): L = light_L(cor, l) for a in ("NB", "SB", "EB", "WB"): A = l["approaches"][a]; main = a in ("NB", "SB") g = g_main[i] if main else C-L-g_main[i] t1, t2, lam, x = webster_terms(C, g, A["q_vph"], A["s_vph"]) up = i-1 if a == "SB" else (i+1 if a == "NB" else None) if main and up is not None and 0 <= up < n: tau = links[min(i, up)]["tau_s"] phi = (offsets[up]+tau-offsets[i]) % C dp = platoon_delay(phi, C, g_main[up], g_main[i]) d = (1-p)*t1+p*dp+t2; kind = "platoon" else: d = t1+t2; kind = "webster"; phi = None vh = A["q_vph"]*d/H; total += vh rows.append(dict(light=l["id"], approach=a, g=g, x=x, delay_s=d, veh_h=vh, kind=kind, phi=phi)) return (total, rows) if detail else total def constraints(cor, C, g_main): P = cor["params"]; c = [] for i, l in enumerate(cor["lights"]): g = g_main[i]; L = light_L(cor, l) c += [g-P["g_min_s"], C-L-g-P["g_min_s"]] for a in ("NB", "SB", "EB", "WB"): A = l["approaches"][a]; gg = g if a in ("NB", "SB") else C-L-g c.append(P["x_max"]*A["s_vph"]*gg-A["q_vph"]*C) return np.array(c) def optimize(cor, starts=30, seed=0): """Multistart SLSQP over z = [C, g_1..g_n, w_2..w_n] (offsets as fractions of C, light 0 fixed at 0).""" P = cor["params"]; n = len(cor["lights"]); rng = np.random.default_rng(seed) def unpack(z): C = z[0]; g = list(z[1:1+n]); offs = [0.0]+[w*C for w in z[1+n:]] return C, g, offs f = lambda z: evaluate(cor, *unpack(z)) cons = [{"type": "ineq", "fun": lambda z: constraints(cor, z[0], z[1:1+n])}] bounds = [(P["C_min_s"], P["C_max_s"])]+[(P["g_min_s"], None)]*n+[(0, 1)]*(n-1) best, found = None, [] for _ in range(starts): C0 = rng.uniform(P["C_min_s"], P["C_max_s"]) z0 = [C0]+[(C0-light_L(cor, l))*0.55 for l in cor["lights"]]+list(rng.uniform(0, 1, n-1)) r = minimize(f, z0, method="SLSQP", bounds=bounds, constraints=cons, options=dict(maxiter=400, ftol=1e-10)) if r.success and min(constraints(cor, r.x[0], r.x[1:1+n])) > -1e-6: found.append(r.fun) if best is None or r.fun < best[0]: best = (r.fun, r.x) C, g, offs = unpack(best[1]) return dict(total_veh_h=float(best[0]), C=float(C), g_main=g, offsets=offs, n_success=len(found), distinct_optima=sorted(set(float(round(v, 2)) for v in found)))