"""Figures for the public page as INLINE SVG strings (no image files, so image blockers can't hide them). map_svg: street map of the area from OpenStreetMap data (data/raw/osm/context/*.osm) with the 4 signals highlighted. """ import io, glob, csv, json, re, pathlib import xml.etree.ElementTree as ET import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt ROOT = pathlib.Path(__file__).resolve().parents[1] plt.rcParams.update({"font.family": "serif", "font.serif": ["Times New Roman", "Times", "DejaVu Serif"], "font.size": 10, "svg.fonttype": "none", "axes.edgecolor": "black", "axes.linewidth": 0.8}) def _svg(fig): buf = io.StringIO(); fig.savefig(buf, format="svg", bbox_inches="tight"); plt.close(fig) s = buf.getvalue(); s = s[s.index("]*?) width="[^"]*" height="[^"]*"', r' 1: labels.setdefault(name, []).extend(pts) # highlight the corridor (Big Bend between first and last light) la, lb = lights[0]["lat"]+0.0006, lights[-1]["lat"]-0.0006 for nds, t in ways: if "Big Bend" in t.get("name", "") and t.get("highway") in ROADS: pts = [nodes[n] for n in nds if n in nodes and lb <= nodes[n][1] <= la] if len(pts) >= 2: xs, ys = zip(*pts); ax.plot(xs, ys, color="black", lw=4.2, zorder=3, solid_capstyle="round") for name, pts in labels.items(): pts = [p for p in pts if lon0+0.002 < p[0] < lon1-0.002 and lat0+0.001 < p[1] < lat1-0.0015 and abs(p[0]-lights[0]["lon"]) > 0.005] if not pts: continue pts.sort(); x, y = pts[len(pts)//2] ax.text(x, y+0.0004, name.replace("North ", "").replace("South ", ""), fontsize=7.5, color="#333", style="italic", ha="center", zorder=2, bbox=dict(fc="white", ec="none", pad=0.4, alpha=0.85)) for i, l in enumerate(lights, 1): ax.scatter([l["lon"]], [l["lat"]], s=170, facecolor="white", edgecolor="black", linewidth=2.2, zorder=5) ax.text(l["lon"], l["lat"], str(i), ha="center", va="center", fontsize=9, fontweight="bold", zorder=6) ax.annotate(f"{i}. Big Bend & {l['name']} (#{l['id']})", (l["lon"], l["lat"]), xytext=(-12, 0), textcoords="offset points", ha="right", va="center", fontsize=9, fontweight="bold", zorder=6, bbox=dict(fc="white", ec="black", lw=0.6, pad=2)) ax.text(-90.3065, 38.6505, "Washington University\n(Danforth Campus)", fontsize=8, ha="center", color="#333", zorder=2) ax.text(-90.3245, 38.6495, "Clayton", fontsize=9, ha="center", color="#333", zorder=2, style="italic") ax.text(lon1-0.0003, lat0+0.0003, "Map data © OpenStreetMap contributors", fontsize=6.5, ha="right", va="bottom", color="#555") ax.annotate("N", xy=(lon0+0.0012, lat1-0.0010), xytext=(lon0+0.0012, lat1-0.0030), ha="center", fontsize=10, fontweight="bold", arrowprops=dict(arrowstyle="->", lw=1.2)) ax.set_xlim(lon0, lon1); ax.set_ylim(lat0, lat1); ax.set_aspect(1/0.7815) ax.set_xticks([]); ax.set_yticks([]) for s in ax.spines.values(): s.set_linewidth(1) return _svg(fig) def results_svg(S): items = sorted(S.items(), key=lambda kv: kv[1]["delay_mean"]) fig, ax = plt.subplots(figsize=(6.5, 2.9)) names = [k for k, _ in items] cols = ["black" if k == "county-current" else "#8a8a8a" for k in names] ax.barh(names, [v["delay_mean"] for _, v in items], xerr=[v["delay_sd"] for _, v in items], color=cols, error_kw=dict(lw=0.8)) for i, (_, v) in enumerate(items): ax.text(v["delay_mean"]+v["delay_sd"]+4, i, f"{v['delay_mean']:.0f}", va="center", fontsize=8.5) ax.invert_yaxis(); ax.set_xlabel("corridor delay in SUMO (vehicle-hours per hour)"); ax.spines[["top", "right"]].set_visible(False) ax.set_xlim(0, max(v["delay_mean"] for _, v in items)*1.15) return _svg(fig) def prediction_svg(path): rows = list(csv.DictReader(open(path))) fig, ax = plt.subplots(figsize=(4.2, 3.4)) ax.scatter([float(r["formula"]) for r in rows], [float(r["sumo"]) for r in rows], s=16, color="black") ax.set_xlabel("formula model delay (veh-h/h)"); ax.set_ylabel("SUMO delay (veh-h/h)"); ax.spines[["top", "right"]].set_visible(False) return _svg(fig) def convergence_svg(path): rows = list(csv.DictReader(open(path))) best, cur = [], float("inf") for r in rows: cur = min(cur, float(r["sumo_delay"])); best.append(cur) fig, ax = plt.subplots(figsize=(4.2, 3.4)) ax.plot(range(1, len(best)+1), best, color="black") ax.set_xlabel("SUMO evaluations"); ax.set_ylabel("best delay so far (veh-h/h)"); ax.spines[["top", "right"]].set_visible(False) return _svg(fig)