"""corridor.json -> SUMO demand (flows + turn ratios -> jtrrouter routes) and the set of edges we measure delay on. Entries: Big Bend SB at the northmost light, Big Bend NB at the southmost light, and every cross-street approach. Each entry starts up to ENTRY_RUN_M metres upstream (straight-ahead chain of edges) so queues have room. At each of our lights, turn shares come from corridor.json; on the corridor between lights traffic goes straight. Every edge leaving the corridor is a sink (vehicles leave the simulation there). Timing: warm-up WARMUP_S at peak rate, then MEASURE_S measured. Flows stop at WARMUP_S + MEASURE_S. """ import sys, pathlib, json, subprocess, math sys.path.insert(0, str(pathlib.Path(__file__).parent)) from common import SUMO, BIN, corridor, tls_map, net, tls_links, approach_label, heading, same_street_pred WARMUP_S, MEASURE_S, ENTRY_RUN_M = 900, 3600, 300.0 END_S = WARMUP_S + MEASURE_S def straight_successor(edge): """The outgoing edge that continues most straight ahead (passenger-allowed).""" best, hx = None, heading(edge) for e2 in edge.getOutgoing(): if not e2.allows("passenger"): continue shp = e2.getShape(); (x0, y0), (x1, y1) = shp[0], shp[1] d = math.hypot(x1-x0, y1-y0) or 1 dot = hx[0]*(x1-x0)/d + hx[1]*(y1-y0)/d if best is None or dot > best[0]: best = (dot, e2) return best[1] if best and best[0] > 0.7 else None def straight_predecessor(edge): best = None for e0 in edge.getIncoming(): if not e0.allows("passenger"): continue hx = heading(e0); shp = edge.getShape(); (x0, y0), (x1, y1) = shp[0], shp[1] d = math.hypot(x1-x0, y1-y0) or 1 dot = hx[0]*(x1-x0)/d + hx[1]*(y1-y0)/d if best is None or dot > best[0]: best = (dot, e0) return best[1] if best and best[0] > 0.7 else None def main(): cor, tm, n = corridor(), tls_map(), net() ids = [l["id"] for l in cor["lights"]] by_light = {lid: tls_links(tm[lid]["tls"]) for lid in ids} tls_nodes = {lid: {e_in.getToNode().getID() for _, e_in, _, _, _ in by_light[lid]} | {e_in.getFromNode().getID() for _, e_in, _, _, _ in by_light[lid] if e_in.getLength() < 30} for lid in ids} def approach_edges(lid, lab): return sorted({e_in for _, e_in, _, l, _ in by_light[lid] if l == lab}, key=lambda e: -e.getLaneNumber()) rel = {} # (from, to) -> prob measure = set() flows = [] # corridor links between lights: follow straight chain from light i outgoing to light j approach for a, b, lab in [(ids[k], ids[k+1], "SB") for k in range(len(ids)-1)] + [(ids[k+1], ids[k], "NB") for k in range(len(ids)-1)]: targets = set(approach_edges(b, lab)) starts = {e_out for _, e_in, e_out, l, d in by_light[a] if l == lab and d == "s"} for e in starts: chain, cur = [e], e while cur not in targets and len(chain) < 40: nxt = straight_successor(cur) if nxt is None: break rel[(cur.getID(), nxt.getID())] = 1.0; chain.append(nxt); cur = nxt measure.update(x.getID() for x in chain) # turn ratios at our lights + entry flows for l in cor["lights"]: lid = l["id"] for lab, A in l["approaches"].items(): edges = approach_edges(lid, lab) measure.update(e.getID() for e in edges) for e_in in edges: outs = {} for _, ei, eo, lb, d in by_light[lid]: if ei != e_in: continue k = "L" if d in ("l", "L", "t") else ("R" if d in ("r", "R") else "T") outs.setdefault(k, set()).add(eo.getID()) tot = sum(A["turn_share"][k] for k in outs) for k, es in outs.items(): for eo in es: rel[(e_in.getID(), eo)] = A["turn_share"][k]/tot/len(es) entry = (lab in ("EB", "WB")) or (lab == "SB" and lid == ids[0]) or (lab == "NB" and lid == ids[-1]) if not entry or not edges: continue edges_pos = [x for x in edges if x.getLength() > 1.0] or edges e = max(edges_pos, key=lambda x: (x.getLaneNumber(), x.getLength())); run = e.getLength(); chain = [e] while run < ENTRY_RUN_M: p = same_street_pred(chain[0]) or straight_predecessor(chain[0]) own = tls_nodes[lid] other_sig = lambda nd: nd.getType().startswith("traffic_light") and nd.getID() not in own if p is None or other_sig(p.getToNode()) or other_sig(p.getFromNode()): break rel[(p.getID(), chain[0].getID())] = 1.0; chain.insert(0, p); run += p.getLength() measure.update(x.getID() for x in chain) flows.append(dict(id=f"{lid}_{lab}", frm=chain[0].getID(), vph=A["q_vph"])) # balancing flows at the mid-block access point between consecutive lights (unsignalized side streets/driveways). # Propagate each direction analytically: out of light j = through + side-street turns into that direction; # the counted volume into the next light is the target; the difference enters (deficit) or leaves (surplus) mid-block. balancing = [] Ls = cor["lights"] for k in range(len(Ls)-1): north, south = Ls[k], Ls[k+1]; nid, sid = north["id"], south["id"] for tag, frm, to in (("SB", north, south), ("NB", south, north)): A = frm["approaches"]; sh = lambda d, m: A[d]["turn_share"][m] if tag == "SB": # leaving northern light southbound: SB through + EB right + WB left out = A["SB"]["q_vph"]*sh("SB", "T") + A["EB"]["q_vph"]*sh("EB", "R") + A["WB"]["q_vph"]*sh("WB", "L") else: # leaving southern light northbound: NB through + EB left + WB right out = A["NB"]["q_vph"]*sh("NB", "T") + A["EB"]["q_vph"]*sh("EB", "L") + A["WB"]["q_vph"]*sh("WB", "R") target = to["approaches"][tag]["q_vph"] diff = target - out mid, nxt = f"{tag}_mid_{to['id']}", f"{tag}_to_{to['id']}" if diff > 0: # extra traffic joins: right turn in (SB from east side, NB from west side) src = f"{'EIN' if tag == 'SB' else 'WIN'}_{nid}_{sid}" rel[(src, nxt)] = 1.0 flows.append(dict(id=f"bal_{tag}_{nid}_{sid}", frm=src, vph=diff)) else: # traffic leaves: right turn out (SB to west side, NB to east side) snk = f"{'WOUT' if tag == 'SB' else 'EOUT'}_{nid}_{sid}" share = min(-diff/out, 0.9) if out > 0 else 0.0 rel[(mid, nxt)] = 1.0-share; rel[(mid, snk)] = share balancing.append(dict(link=f"{nid}-{sid}", direction=tag, propagated_vph=round(out, 1), target_vph=round(target, 1), balance_vph=round(diff, 1), source="derived", evidence="difference between counted volume into the next light and volume propagated from the previous light")) # sinks: every edge leaving one of our lights that is not a corridor edge sinks = set() for lid in ids: for _, ei, eo, lb, d in by_light[lid]: if eo.getID() not in measure: sinks.add(eo.getID()) sinks.update(e.getID() for e in n.getEdges() if e.getID().startswith(("WOUT_", "EOUT_"))) SUMO.mkdir(parents=True, exist_ok=True) with open(SUMO/"turns.xml", "w") as f: f.write(f'\n \n') for (a, b), p in sorted(rel.items()): f.write(f' \n') f.write(" \n\n") with open(SUMO/"flows.xml", "w") as f: f.write('\n \n') for fl in flows: f.write(f' \n') f.write("\n") subprocess.run([str(BIN/"jtrrouter"), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"flows.xml"), "-t", str(SUMO/"turns.xml"), "--sink-edges", ",".join(sorted(sinks)), "-T", "0,100,0", "--max-edges-factor", "3", "--randomize-flows", "--seed", "42", "-o", str(SUMO/"routes.rou.xml"), "--no-warnings", "--ignore-errors"], check=True) json.dump(dict(measure_edges=sorted(measure), sinks=sorted(sinks), flows=flows, balancing=balancing, warmup_s=WARMUP_S, measure_s=MEASURE_S), open(SUMO/"demand.json", "w"), indent=1) print(f"demand: {len(flows)} entry flows, {len(rel)} turn relations, {len(measure)} measured edges, {len(sinks)} sinks") for fl in flows: print(f" {fl['id']:14s} {fl['vph']:7.1f} veh/h from {fl['frm']}") for b in balancing: print(f" balance {b['link']} {b['direction']}: propagated {b['propagated_vph']:7.1f} target {b['target_vph']:7.1f} -> {b['balance_vph']:+7.1f} veh/h") if __name__ == "__main__": main()