"""Canonical timing-plan format + baseline generators + readers for outside formats. Plan JSON (plans/.json): { "name": str, "source": str, "C": float (common cycle, s), "lights": { "": { "g_main": float (s), "offset_s": float (s), "C": float (optional per-light cycle) } }, "L_s": float, "notes": str } g_main = Big Bend green; side green = C - L - g_main. offset_s = when Big Bend green starts, relative to the first light. The ONLY place that knows Michael + Noah's output format is `from_their_format()` below. """ import json, sys, pathlib, tomllib sys.path.insert(0, str(pathlib.Path(__file__).parent)) from common import ROOT, corridor import formula PLANS = ROOT/"plans" def save(plan): PLANS.mkdir(exist_ok=True) json.dump(plan, open(PLANS/f"{plan['name']}.json", "w"), indent=1) return plan def load(name): return json.load(open(PLANS/f"{name}.json")) def _ys(cor): out = [] for l in cor["lights"]: A = l["approaches"] out.append((max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("NB", "SB")), max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("EB", "WB")))) return out def _L(l, cor): return formula.light_L(cor, l) def webster_cycle(L, Y, P): return min(max((1.5*L+5)/(1-Y), P["C_min_s"]), P["C_max_s"]) def webster_per_light(cor): """Each light on its own Webster cycle and splits, no coordination (offsets 0).""" P = cor["params"]; L = P["L_s"]; lights = {} for l, (ym, ys) in zip(cor["lights"], _ys(cor)): Li = _L(l, cor); C = webster_cycle(Li, ym+ys, P); g = (C-Li)*ym/(ym+ys) lights[l["id"]] = dict(g_main=round(g, 2), offset_s=0.0, C=round(C, 2)) Cs = [v["C"] for v in lights.values()] return dict(name="webster-per-light", source="baseline: Webster (1958) cycle + splits per light, uncoordinated", C=max(Cs), lights=lights, L_s=L, notes="per-light cycles; offsets 0") def webster_common(cor): """Common cycle = largest Webster cycle; Webster splits; offsets 0 (input to coordination tools).""" P = cor["params"]; L = P["L_s"]; ys = _ys(cor) C = max(webster_cycle(_L(l, cor), ym+yss, P) for l, (ym, yss) in zip(cor["lights"], ys)) lights = {l["id"]: dict(g_main=round((C-_L(l, cor))*ym/(ym+yss), 2), offset_s=0.0) for l, (ym, yss) in zip(cor["lights"], ys)} return dict(name="webster-common", source="baseline: common Webster cycle, Webster splits, offsets 0", C=round(C, 2), lights=lights, L_s=L, notes="") def equal_split(cor): P = cor["params"]; L = P["L_s"]; C = webster_common(cor)["C"] lights = {l["id"]: dict(g_main=round((C-_L(l, cor))/2, 2), offset_s=0.0) for l in cor["lights"]} return dict(name="equal-split", source="baseline: equal green to main and side, common Webster cycle, offsets 0", C=C, lights=lights, L_s=L, notes="") def estimated_current(cor): a = tomllib.load(open(ROOT/"config/assumptions.toml", "rb"))["current_timing"] L = cor["params"]["L_s"]; C = a["C_s"] lights = {l["id"]: dict(g_main=round((C-L)*a["main_share"], 2), offset_s=0.0) for l in cor["lights"]} return dict(name="estimated-current", source=f"ASSUMED placeholder ({a['evidence']})", C=C, lights=lights, L_s=L, notes="replace with stopwatch or County timing sheets") def county_current(cor): """MEASURED current timing: County PM pattern (timing sheets), reduced to the model's two-phase form.""" T = [l["timing"] for l in cor["lights"]] if not all(T): return None C = T[0]["C_s"]; ref = T[0]["main_start_s"] lights = {l["id"]: dict(g_main=t["g_main_s"], offset_s=round((t["main_start_s"]-ref) % C, 2)) for l, t in zip(cor["lights"], T)} return dict(name="county-current", source=f"MEASURED: St. Louis County timing sheets, pattern {T[0]['pattern']} (PM weekday)", C=C, lights=lights, L_s=cor["params"]["L_s"], notes=T[0]["note"] + "; offsets relative to the first light") def formula_optimum(cor, starts=30): r = formula.optimize(cor, starts=starts) lights = {l["id"]: dict(g_main=round(g, 3), offset_s=round(o, 3)) for l, g, o in zip(cor["lights"], r["g_main"], r["offsets"])} return dict(name="formula-optimum-standin", source="stand-in for Michael+Noah: formula model, multistart SLSQP (formula.py)", C=round(r["C"], 3), lights=lights, L_s=cor["params"]["L_s"], notes=f"formula delay {r['total_veh_h']:.2f} veh-h/h; {r['n_success']} successful starts; distinct optima {r['distinct_optima'][:8]}") def sumo_coordinated(cor): """SUMO's built-in tlsCoordinator.py: Webster common-cycle splits + green-wave offsets computed by SUMO from the routes.""" import subprocess, os, xml.etree.ElementTree as ET from common import SUMO, BIN import plan_to_sumo base = webster_common(cor); base["name"] = "_tmp_webster"; plan_to_sumo.write(base) tools = pathlib.Path(sys.executable).parents[1]/"lib" tool = next(tools.glob("python*/site-packages/sumo/tools/tlsCoordinator.py")) out = SUMO/"plans"/"_coord.add.xml" env = dict(os.environ, SUMO_HOME=str(tool.parents[1])) subprocess.run([sys.executable, str(tool), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"routes.rou.xml"), "-a", str(SUMO/"plans"/"_tmp_webster.tls.add.xml"), "-o", str(out)], check=True, env=env, stdout=subprocess.DEVNULL) from common import tls_map rev = {v["tls"]: k for k, v in tls_map().items()} offs = {rev[e.get("id")]: float(e.get("offset")) for e in ET.parse(out).getroot().iter("tlLogic") if e.get("id") in rev} ids = [l["id"] for l in cor["lights"]]; C = base["C"]; o0 = offs[ids[0]] lights = {i: dict(g_main=base["lights"][i]["g_main"], offset_s=round((offs[i]-o0) % C, 2)) for i in ids} return dict(name="sumo-coordinated", source="baseline: SUMO tlsCoordinator.py offsets on the common Webster plan", C=C, lights=lights, L_s=base["L_s"], notes="SUMO built-in green-wave coordination") def from_their_format(path): """Adapter for Michael + Noah's plan files. FORMAT UNKNOWN YET: fill this in when their format arrives. Expected to return a plan dict in the canonical format above.""" raise NotImplementedError("Waiting for Michael + Noah's plan-file format") def formula_delay(cor, plan): """Formula-model delay for a common-cycle plan (None for per-light-cycle plans).""" if any("C" in v for v in plan["lights"].values()): return None ids = [l["id"] for l in cor["lights"]] return formula.evaluate(cor, plan["C"], [plan["lights"][i]["g_main"] for i in ids], [plan["lights"][i]["offset_s"] for i in ids]) def main(): cor = corridor() from common import SUMO have_timing = all(l.get("timing") for l in cor["lights"]) makers = [equal_split, webster_per_light, webster_common, county_current if have_timing else estimated_current, formula_optimum] if have_timing and (PLANS/"estimated-current.json").exists(): (PLANS/"estimated-current.json").unlink() # superseded by measured timing if (SUMO/"routes.rou.xml").exists(): makers.append(sumo_coordinated) for mk in makers: p = save(mk(cor)) fd = formula_delay(cor, p) print(f"{p['name']:24s} C={p['C']:6.1f} formula delay={'n/a' if fd is None else f'{fd:.2f} veh-h/h'}") if __name__ == "__main__": main()