"""Shared helpers: paths, network loading, and labelling each signal approach as NB/SB (Big Bend) or EB/WB (cross street).""" import json, math, pathlib, sys, functools import sumolib ROOT = pathlib.Path(__file__).resolve().parents[1] BUILD = ROOT/"build" SUMO = BUILD/"sumo" BIN = pathlib.Path(sys.executable).parent def corridor(): return json.load(open(BUILD/"corridor.json")) def tls_map(): return json.load(open(SUMO/"tls_map.json")) @functools.lru_cache(maxsize=1) def net(): return sumolib.net.readNet(str(SUMO/"net.net.xml"), withPrograms=True, withConnections=True) def same_street_pred(edge): """Upstream edge on the same street (by name), not the reverse direction; None if none.""" name = edge.getName() cands = [p for p in edge.getIncoming() if p.allows("passenger") and p.getFromNode() != edge.getToNode() and (not name or p.getName() == name)] return max(cands, key=lambda p: p.getLength()) if cands else None def heading(edge, span=25.0): """Direction of travel as the edge ENTERS its end node, measured over the last `span` metres (walking back through same-street edges, so tiny OSM stub edges don't give noise). Returns unit (dx, dy).""" end = edge.getShape()[-1]; pts = list(edge.getShape()); run = edge.getLength(); cur = edge while run < span: p = same_street_pred(cur) if p is None: break pts = list(p.getShape()) + pts; run += p.getLength(); cur = p acc, start = 0.0, pts[0] for a, b in zip(reversed(pts[:-1]), reversed(pts[1:])): acc += math.hypot(b[0]-a[0], b[1]-a[1]) if acc >= span: start = a; break dx, dy = end[0]-start[0], end[1]-start[1] d = math.hypot(dx, dy) or 1.0 return dx/d, dy/d MAIN_NAME = "Big Bend" def approach_label(edge): """Main road (Big Bend, by street name) -> NB/SB by heading; any other street -> EB/WB by heading. Unnamed edges fall back to heading alone.""" dx, dy = heading(edge) name = edge.getName() or "" main = (MAIN_NAME in name) if name else abs(dy) >= abs(dx) if main: return "NB" if dy > 0 else "SB" return "EB" if dx > 0 else "WB" def tls_links(tls_id): """[(link_index, incoming_edge, outgoing_edge, approach_label, direction)] for one traffic light. direction: SUMO turn code s/l/r/t/L/R.""" t = net().getTLS(tls_id) out = [] for inl, outl, idx in t.getConnections(): e_in, e_out = inl.getEdge(), outl.getEdge() d = "s" for c in e_in.getConnections(e_out): if c.getFromLane() == inl and c.getToLane() == outl: d = c.getDirection() out.append((idx, e_in, e_out, approach_label(e_in), d)) return out