File size: 5,741 Bytes
e16fda3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | """Build the per-scenario comparison figure + table for an AWSIM campaign directory,
the analogue of the MetaDrive comparison.png. Overlays every agent's real ego path on the
shared route and reports on-route distance (how far along the straight route the agent
progressed while staying within THRESH metres of it).
python make_comparison.py <scenario_dir> # e.g. campaign/scenarioA
"""
import os, sys, glob, csv
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
THRESH = 5.0
# publication-quality defaults (ICSE tool & demo paper)
plt.rcParams.update({
"figure.dpi": 150, "savefig.dpi": 300,
"font.size": 13, "axes.titlesize": 15, "axes.labelsize": 13,
"legend.fontsize": 10, "xtick.labelsize": 11, "ytick.labelsize": 11,
"axes.linewidth": 1.0, "lines.linewidth": 2.6,
"font.family": "DejaVu Sans", "pdf.fonttype": 42, "ps.fonttype": 42,
})
def load_path(d):
xs, ys = [], []
f = os.path.join(d, "control.csv")
if not os.path.exists(f):
return None
with open(f) as fh:
r = csv.DictReader(fh)
for row in r:
xs.append(float(row["ego_x"])); ys.append(float(row["ego_y"]))
return np.array(list(zip(xs, ys))) if xs else None
def load_route(d):
f = os.path.join(d, "route.csv")
pts = []
if os.path.exists(f):
with open(f) as fh:
r = csv.DictReader(fh)
for row in r:
pts.append((float(row["x"]), float(row["y"])))
return np.array(pts) if pts else None
def on_route_distance(path, route):
"""Max arc length ALONG the route polyline the agent reached while within THRESH m of it.
Works for a straight route (AWSIM) and a curving planned route (MetaDrive)."""
if path is None or route is None or len(route) < 2 or len(path) < 2:
return 0.0
seg = np.diff(route, axis=0)
seglen = np.linalg.norm(seg, axis=1)
cum = np.concatenate([[0.0], np.cumsum(seglen)]) # arc length at each route vertex
best = 0.0
for p in path:
mind, bests = 1e18, 0.0
for i in range(len(route) - 1):
a = route[i]; ab = seg[i]; L2 = float(ab @ ab)
t = 0.0 if L2 < 1e-9 else float(np.clip((p - a) @ ab / L2, 0.0, 1.0))
proj = a + t * ab
d = float(np.linalg.norm(p - proj))
if d < mind:
mind, bests = d, cum[i] + t * seglen[i]
if mind < THRESH:
best = max(best, bests)
return best
def main():
sdir = sys.argv[1]
scen = os.path.basename(sdir.rstrip("/"))
agents = sorted(d for d in glob.glob(os.path.join(sdir, "*")) if os.path.isdir(d))
cmap = plt.get_cmap("tab10")
fig, ax = plt.subplots(figsize=(7.2, 7.2))
route = None
rows = []
allpts = []
order = sorted(range(len(agents)),
key=lambda k: -on_route_distance(load_path(agents[k]), load_route(agents[k]))
if load_path(agents[k]) is not None else 0)
for i in order:
d = agents[i]; name = os.path.basename(d)
path = load_path(d)
if route is None:
route = load_route(d)
if path is None or len(path) < 2:
rows.append((name, 0.0, 0.0)); continue
onr = on_route_distance(path, route)
plen = float(np.sum(np.linalg.norm(np.diff(path, axis=0), axis=1)))
rows.append((name, onr, plen))
allpts.append(path)
ax.plot(path[:, 0], path[:, 1], "-", color=cmap(i % 10), solid_capstyle="round",
label=f"{name} (on-route {onr:.0f} m, drove {plen:.0f} m)")
ax.plot(path[-1, 0], path[-1, 1], "o", color=cmap(i % 10), ms=6, zorder=5)
if route is not None:
ax.plot(route[:, 0], route[:, 1], "-", color="#c7c7c7", lw=9, alpha=.6, zorder=0,
solid_capstyle="round", label="intended route")
ax.plot(route[0, 0], route[0, 1], "o", color="black", ms=11, zorder=6,
markeredgecolor="white", markeredgewidth=1.0, label="start")
if allpts:
P = np.vstack(allpts)
xmin, xmax = P[:, 0].min(), P[:, 0].max(); ymin, ymax = P[:, 1].min(), P[:, 1].max()
mx = max(8.0, 0.12 * max(xmax - xmin, ymax - ymin))
ax.set_xlim(xmin - mx, xmax + mx); ax.set_ylim(ymin - mx, ymax + mx)
ax.set_aspect("equal", adjustable="box")
ax.grid(True, which="both", color="0.9", lw=0.8, zorder=-1)
# legend below the axes so it never overlaps the trajectories (paper-friendly)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.22), ncol=2,
framealpha=0.97, borderpad=0.6, columnspacing=1.4, handlelength=1.8)
_low = sdir.lower()
sim = ("MetaDrive (SCS)" if "metadrive" in _low
else "AlpaSim (NuRec)" if "alpasim" in _low
else "AWSIM (Shinjuku)")
sl = scen.lower()
letter = "A" if "scenarioa" in sl else ("B" if "scenariob" in sl else scen)
seed = ""
if "scs3" in sl or "seed3" in sl:
seed = " (seed 3)"
elif "scs5" in sl or "seed5" in sl:
seed = " (seed 5)"
scen_nice = f"Scenario {letter}{seed}" if letter in ("A", "B") else scen
ax.set_title(f"PCLA agents driving {sim} — {scen_nice}")
ax.set_xlabel("x (m from spawn)", labelpad=8); ax.set_ylabel("y (m from spawn)")
fig.tight_layout()
out = os.path.join(sdir, "comparison.png")
fig.savefig(out, bbox_inches="tight")
fig.savefig(out.replace(".png", ".pdf"), bbox_inches="tight") # vector for the paper
print(f"wrote {out} (+ .pdf)")
print(f"\n{'agent':<22}{'on-route (m)':>14}{'path len (m)':>14}")
for name, onr, plen in sorted(rows, key=lambda r: -r[1]):
print(f"{name:<22}{onr:>14.1f}{plen:>14.1f}")
if __name__ == "__main__":
main()
|