"""Run plans in SUMO over several seeds and measure corridor delay. Metrics (measurement window only, after warm-up): delay_veh_h_per_h : total time lost on corridor edges (edgeData timeLoss) + insertion delay at entries, in vehicle-hours per hour stops_per_veh : average number of stops (tripinfo waitingCount) per completed trip throughput_vph : trips completed in the window Usage: run_sumo.py [plan names...] [--seeds N] """ import sys, pathlib, json, subprocess, csv, statistics, tempfile, os import xml.etree.ElementTree as ET from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, str(pathlib.Path(__file__).parent)) from common import SUMO, BIN, BUILD import plans as P import plan_to_sumo RUNS = BUILD/"runs" def run_one(plan_name, seed, extra_add=None): dem = json.load(open(SUMO/"demand.json")) w0, w1 = dem["warmup_s"], dem["warmup_s"]+dem["measure_s"] tls_add = SUMO/"plans"/f"{plan_name}.tls.add.xml" out = RUNS/plan_name/f"seed{seed}"; out.mkdir(parents=True, exist_ok=True) meas = out/"edgedata.add.xml" meas.write_text(f'\n') cmd = [str(BIN/"sumo"), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"routes.rou.xml"), "-a", f"{extra_add or tls_add},{meas}", "--seed", str(seed), "--end", str(w1+1800), "--tripinfo-output", str(out/"trips.xml"), "--no-step-log", "--no-warnings", "--time-to-teleport", "300", "--duration-log.disable"] subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL) measure = set(dem["measure_edges"]) loss = 0.0; entered = {} for iv in ET.parse(out/"edges.xml").getroot().iter("interval"): for e in iv.iter("edge"): if e.get("id") in measure: loss += float(e.get("timeLoss", 0)) entered[e.get("id")] = float(e.get("entered", 0)) ddelay = 0.0; stops = []; done = 0 for t in ET.parse(out/"trips.xml").getroot().iter("tripinfo"): dep = float(t.get("depart")) if w0 <= dep < w1: ddelay += float(t.get("departDelay", 0)); stops.append(int(t.get("waitingCount", 0))); done += 1 hours = (w1-w0)/3600 res = dict(plan=plan_name, seed=seed, delay_veh_h_per_h=(loss+ddelay)/3600/hours, edge_timeloss_veh_h=loss/3600, depart_delay_veh_h=ddelay/3600, stops_per_veh=statistics.mean(stops) if stops else 0, throughput_vph=done/hours) json.dump(dict(res, entered=entered), open(out/"metrics.json", "w")) return res def run_plans(names, seeds=10, workers=None): for n in names: plan_to_sumo.write(P.load(n)) jobs = [(n, s) for n in names for s in range(1, seeds+1)] with ThreadPoolExecutor(max_workers=workers or max(1, (os.cpu_count() or 4)-1)) as ex: res = list(ex.map(lambda j: run_one(*j), jobs)) RUNS.mkdir(parents=True, exist_ok=True) with open(RUNS/"all_runs.csv", "a", newline="") as f: w = csv.DictWriter(f, fieldnames=list(res[0].keys())) if f.tell() == 0: w.writeheader() w.writerows(res) summary = {} for n in names: r = [x for x in res if x["plan"] == n] d = [x["delay_veh_h_per_h"] for x in r] summary[n] = dict(delay_mean=statistics.mean(d), delay_sd=statistics.stdev(d) if len(d) > 1 else 0.0, stops_mean=statistics.mean(x["stops_per_veh"] for x in r), throughput_mean=statistics.mean(x["throughput_vph"] for x in r), seeds=len(r)) return summary if __name__ == "__main__": args = sys.argv[1:]; seeds = 10 if "--seeds" in args: i = args.index("--seeds"); seeds = int(args[i+1]); del args[i:i+2] names = args or sorted(p.stem for p in P.PLANS.glob("*.json")) s = run_plans(names, seeds) json.dump(s, open(BUILD/"results_summary.json", "w"), indent=1) for n, v in sorted(s.items(), key=lambda kv: kv[1]["delay_mean"]): print(f"{n:26s} delay {v['delay_mean']:7.2f} ± {v['delay_sd']:5.2f} veh-h/h stops/veh {v['stops_mean']:.2f} " f"throughput {v['throughput_mean']:.0f} veh/h ({v['seeds']} seeds)")