"""Generate a clean SUMO corridor network from build/corridor.json (real distances, lanes, speeds). Why: the raw OpenStreetMap network carries unsignalized merges, split carriageways and slip lanes around Forsyth and Clayton Rd that jam the simulation and are outside the model's scope. This network keeps what the model is about: 4 signalized intersections at their real spacing, Big Bend with 2 through lanes + a left-turn bay per approach, cross streets with their real approach lanes, posted speeds. Geometry: light positions projected from County coordinates (local metres). Each light gets cross-street legs of SIDE_LEG_M east and west; Big Bend extends END_LEG_M north of the first light and south of the last. """ import json, math, pathlib, subprocess, sys ROOT = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(sys.executable).parent OUT = ROOT/"build/sumo" END_LEG_M, SIDE_LEG_M, BAY_M = 600.0, 400.0, 60.0 MAIN = "Big Bend Boulevard" def xy(lat, lon, lat0, lon0): return ((lon-lon0)*111320*math.cos(math.radians(lat0)), (lat-lat0)*110540) def main(): global BAY_M import tomllib BAY_M = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}).get("bay_m", BAY_M) cor = json.load(open(ROOT/"build/corridor.json")) L = cor["lights"]; lat0, lon0 = L[-1]["lat"], L[-1]["lon"] P = {l["id"]: xy(l["lat"], l["lon"], lat0, lon0) for l in L} speed = {} for k in cor["links"]: speed[(k["from"], k["to"])] = speed[(k["to"], k["from"])] = k["speed_mps"] v_end_n, v_end_s = cor["links"][0]["speed_mps"], cor["links"][-1]["speed_mps"] v_side = 13.41 # 30 mph cross streets (MoDOT: Forsyth/Wydown unposted -> 30 mph assumed; FPP 40, Clayton 35 below) side_speed = {"Forest Park Parkway": 17.88, "Clayton Road": 15.65} nodes, edges, cons, mid_cons = [], [], [], [] side_nt = {} def node(i, x, y, t="priority"): nodes.append(f' ') def edge(i, a, b, lanes, v, name): edges.append(f' ') ids = [l["id"] for l in L] for l in L: x, y = P[l["id"]] node(f"J{l['id']}", x, y, "traffic_light") for d, sx in (("W", -1), ("E", 1)): node(f"{d}{l['id']}", x+sx*SIDE_LEG_M, y) node(f"{d}b{l['id']}", x+sx*BAY_M, y) # left-turn bay start on the cross street for d, sy in (("Nb", 1), ("Sb", -1)): # bay start nodes on Big Bend node(f"{d}{l['id']}", x, y+sy*BAY_M) xn, yn = P[ids[0]]; xs, ys = P[ids[-1]] node("NEND", xn, yn+END_LEG_M); node("SEND", xs, ys-END_LEG_M) mids = set() def bb_chain(a_node, b_light, v, tag): """Big Bend from a_node towards light b: plain 2-lane edge to the bay start, then a 3-lane bay edge (left bay). Between two lights the plain part is split at a mid-block access point (balancing flows, see build_demand).""" come_from_north = tag == "SB" bay = f"Nb{b_light}" if come_from_north else f"Sb{b_light}" if a_node[:2] in ("Sb", "Nb"): a = a_node[2:] north, south = (a, b_light) if come_from_north else (b_light, a) m = f"M{north}_{south}" if m not in mids: mids.add(m) (xa, ya), (xb, yb) = P[north], P[south] mx, my = (xa+xb)/2, ((ya-BAY_M)+(yb+BAY_M))/2 node(m, mx, my); node(f"DW{north}_{south}", mx-80, my); node(f"DE{north}_{south}", mx+80, my) nm = f"Access {north}-{south}" edge(f"WIN_{north}_{south}", f"DW{north}_{south}", m, 1, 8.94, nm) edge(f"WOUT_{north}_{south}", m, f"DW{north}_{south}", 1, 8.94, nm) edge(f"EIN_{north}_{south}", f"DE{north}_{south}", m, 1, 8.94, nm) edge(f"EOUT_{north}_{south}", m, f"DE{north}_{south}", 1, 8.94, nm) edge(f"{tag}_mid_{b_light}", a_node, m, 2, v, MAIN) mid_cons.append((tag, f"{tag}_mid_{b_light}", f"{tag}_to_{b_light}", north, south)) a_node = m edge(f"{tag}_to_{b_light}", a_node, bay, 2, v, MAIN) edge(f"{tag}_bay_{b_light}", bay, f"J{b_light}", 3, v, MAIN) cons.append((f"{tag}_to_{b_light}", f"{tag}_bay_{b_light}", None)) return f"{tag}_bay_{b_light}" out_edges = {} # southbound chain prev = "NEND"; v = v_end_n for i, lid in enumerate(ids): bb_chain(prev if i == 0 else f"Sb{ids[i-1]}", lid, v if i == 0 else speed[(ids[i-1], lid)], "SB") if i+1 < len(ids): edge(f"SB_from_{lid}", f"J{lid}", f"Sb{lid}", 2, speed[(lid, ids[i+1])], MAIN) else: edge(f"SB_from_{lid}", f"J{lid}", "SEND", 2, v_end_s, MAIN) out_edges[(lid, "S")] = f"SB_from_{lid}" # northbound chain rev = ids[::-1] for i, lid in enumerate(rev): bb_chain("SEND" if i == 0 else f"Nb{rev[i-1]}", lid, v_end_s if i == 0 else speed[(rev[i-1], lid)], "NB") if i+1 < len(rev): edge(f"NB_from_{lid}", f"J{lid}", f"Nb{lid}", 2, speed[(lid, rev[i+1])], MAIN) else: edge(f"NB_from_{lid}", f"J{lid}", "NEND", 2, v_end_n, MAIN) out_edges[(lid, "N")] = f"NB_from_{lid}" # cross streets for l in L: lid, name = l["id"], l["cross_street"]; vs = side_speed.get(name, v_side) A = l["approaches"] # approach = through lanes (approach lanes minus the left lane, at least 1) + a left-turn bay at the stop line nt = {d: max(A[d]["lanes"]-1, 1) for d in ("EB", "WB")} edge(f"EB_up_{lid}", f"W{lid}", f"Wb{lid}", nt["EB"], vs, name) edge(f"EB_in_{lid}", f"Wb{lid}", f"J{lid}", nt["EB"]+1, vs, name) edge(f"WB_up_{lid}", f"E{lid}", f"Eb{lid}", nt["WB"], vs, name) edge(f"WB_in_{lid}", f"Eb{lid}", f"J{lid}", nt["WB"]+1, vs, name) edge(f"EB_out_{lid}", f"J{lid}", f"E{lid}", nt["WB"], vs, name) edge(f"WB_out_{lid}", f"J{lid}", f"W{lid}", nt["EB"], vs, name) side_nt[lid] = nt # explicit lane-to-lane connections at each light (lane 0 = rightmost) con_xml = [] def c(fe, te, fl, tl): con_xml.append(f' ') for k, (fe, te, _) in enumerate(cons): # plain -> bay: 2 lanes feed 3 (lane 1 also feeds the bay) c(fe, te, 0, 0); c(fe, te, 1, 1); c(fe, te, 1, 2) for tag, fe, te, north, south in mid_cons: # mid-block access: right turns only (no crossing conflicts) c(fe, te, 0, 0); c(fe, te, 1, 1) if tag == "SB": c(fe, f"WOUT_{north}_{south}", 0, 0); c(f"EIN_{north}_{south}", te, 0, 0) else: c(fe, f"EOUT_{north}_{south}", 0, 0); c(f"WIN_{north}_{south}", te, 0, 0) for l in L: lid = l["id"]; A = l["approaches"] # Big Bend bays: lane0 R+T, lane1 T, lane2 L sb_t, sb_r, sb_l = out_edges[(lid, "S")], f"WB_out_{lid}", f"EB_out_{lid}" nb_t, nb_r, nb_l = out_edges[(lid, "N")], f"EB_out_{lid}", f"WB_out_{lid}" for bay, t, r, lft in ((f"SB_bay_{lid}", sb_t, sb_r, sb_l), (f"NB_bay_{lid}", nb_t, nb_r, nb_l)): c(bay, t, 0, 0); c(bay, t, 1, 1); c(bay, r, 0, 0); c(bay, lft, 2, 0) # cross streets: EB in -> through EB_out, right = SB_from (south), left = NB_from (north) for side, t, r, lft in (("EB", f"EB_out_{lid}", out_edges[(lid, "S")], out_edges[(lid, "N")]), ("WB", f"WB_out_{lid}", out_edges[(lid, "N")], out_edges[(lid, "S")])): nt = side_nt[lid][side]; nout = side_nt[lid]["WB" if side == "EB" else "EB"] up, fe = f"{side}_up_{lid}", f"{side}_in_{lid}" for i in range(nt): c(up, fe, i, i) c(up, fe, nt-1, nt) # leftmost through lane also feeds the left bay c(fe, r, 0, 0) # right turn from the curb lane for i in range(nt): c(fe, t, i, min(i, nout-1)) # through lanes c(fe, lft, nt, 1) # left bay -> inner lane of Big Bend OUT.mkdir(parents=True, exist_ok=True) (OUT/"gen.nod.xml").write_text("\n"+"\n".join(nodes)+"\n\n") (OUT/"gen.edg.xml").write_text("\n"+"\n".join(edges)+"\n\n") (OUT/"gen.con.xml").write_text("\n"+"\n".join(con_xml)+"\n\n") net = OUT/"net.net.xml" subprocess.run([str(BIN/"netconvert"), "-n", str(OUT/"gen.nod.xml"), "-e", str(OUT/"gen.edg.xml"), "-x", str(OUT/"gen.con.xml"), "-o", str(net), "--no-turnarounds", "--tls.default-type", "static", "--no-warnings", "--offset.disable-normalization"], check=True) tls_map = {l["id"]: dict(tls=f"J{l['id']}", dist_m=0.0, name=l["name"]) for l in L} json.dump(tls_map, open(OUT/"tls_map.json", "w"), indent=1) print("generated network:", net) _LANES = {} def tout_lanes(edge_id, light): A = light["approaches"] if edge_id.startswith("EB_out"): return max(A["WB"]["lanes"], 1) if A["WB"]["lanes"] < 3 else 2 if edge_id.startswith("WB_out"): return max(A["EB"]["lanes"], 1) if A["EB"]["lanes"] < 3 else 2 return 2 if __name__ == "__main__": main()