"""OpenStreetMap extract -> SUMO network (build/sumo/net.net.xml) + map of County signal id -> SUMO traffic-light id. Manual fixes (lanes, turn bays) go in config/net_patches/ as netconvert patch files, so the network rebuilds identically. """ import json, subprocess, pathlib, sys, glob, tomllib import sumolib ROOT = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(sys.executable).parent OUT = ROOT/"build/sumo" def main(): OUT.mkdir(parents=True, exist_ok=True) if tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}).get("source", "osm") == "generated": import build_network_gen return build_network_gen.main() net = OUT/"net.net.xml" cfg = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}) cmd = [str(BIN/"netconvert"), "--osm-files", str(ROOT/"data/raw/osm/bigbend.osm"), "-o", str(net), "--junctions.right-before-left.speed-threshold", str(cfg.get("rbl_speed_threshold", 13.89)), "--keep-edges.by-vclass", "passenger", "--remove-edges.isolated", "--osm.turn-lanes", "--geometry.remove", "--roundabouts.guess", "--ramps.guess", "--junctions.join", "--tls.guess-signals", "--tls.join", "--tls.discard-simple", "--tls.default-type", "static", "--tls.ignore-internal-junction-jam", "--output.street-names", "--no-turnarounds.tls", "--no-warnings", "--log", str(OUT/"netconvert.log")] patches = sorted(glob.glob(str(ROOT/"config/net_patches/*.edg.xml"))) for p in patches: cmd += ["--edge-files", p] subprocess.run(cmd, check=True) # patches from config: lane counts by street name (only edges with fewer lanes) and by edge id n0 = sumolib.net.readNet(str(net)) patch = {} for name, k in cfg.get("lanes_by_name", {}).items(): for e in n0.getEdges(): if e.getName() == name and e.getLaneNumber() < k: patch[e.getID()] = k patch.update(cfg.get("lanes_by_edge", {})) if patch: pf = OUT/"lane_patch.edg.xml" pf.write_text("\n" + "".join(f' \n' for i, k in patch.items()) + "\n") subprocess.run([str(BIN/"netconvert"), "-s", str(net), "-e", str(pf), "-o", str(net), "--tls.ignore-internal-junction-jam", "--no-warnings"], check=True) print(f"patched lanes on {len(patch)} edges") cor = json.load(open(ROOT/"build/corridor.json")) n = sumolib.net.readNet(str(net), withPrograms=True) tls_map = {} for l in cor["lights"]: x, y = n.convertLonLat2XY(l["lon"], l["lat"]) best = None for t in n.getTrafficLights(): nodes = {c[0].getEdge().getToNode() for c in t.getConnections()} for nd in nodes: dx, dy = nd.getCoord()[0]-x, nd.getCoord()[1]-y dist = (dx*dx+dy*dy)**0.5 if best is None or dist < best[0]: best = (dist, t.getID()) tls_map[l["id"]] = dict(tls=best[1], dist_m=round(best[0], 1), name=l["name"]) json.dump(tls_map, open(OUT/"tls_map.json", "w"), indent=1) print("network:", net) for k, v in tls_map.items(): print(f" County {k} {v['name']:16s} -> SUMO tls {v['tls']} ({v['dist_m']} m from County coordinate)") if __name__ == "__main__": main()