"""Next Drive: run the learned driver (optionally with the safety check) on a simulated intersection scene. Simulation and education only. Usage: python inference.py --seed 10007 --kind mixed --density 2 --driver shield python inference.py --selftest """ import argparse import json import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import drive_core as dc # noqa: E402 from nlrt import load_model # noqa: E402 def load(path=os.path.join(HERE, "model.json")): return load_model(path)["nets"]["policy"] def drive(seed, kind="mixed", density=2, driver="shield", layers=None): sc = dc.make_scenario(seed, kind, density) return sc, dc.run_episode(sc, driver, layers if layers is not None else load(), record=False) def _selftest(): layers = load() with open(os.path.join(HERE, "selftest.json"), encoding="utf-8") as f: cases = json.load(f)["cases"] bad = [] for c in cases: _, r = drive(layers=layers, **c["input"]) got = {k: r[k] for k in c["expected"]} if got != c["expected"]: bad.append({"input": c["input"], "got": got, "expected": c["expected"]}) print(json.dumps({"passed": not bad, "cases": len(cases), "mismatches": bad[:3]})) return not bad if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--selftest", action="store_true") ap.add_argument("--seed", type=int, default=10007) ap.add_argument("--kind", default="mixed", choices=dc.KINDS) ap.add_argument("--density", type=int, default=2) ap.add_argument("--driver", default="shield", choices=["shield", "learned", "rule", "expert"]) a = ap.parse_args() if a.selftest: sys.exit(0 if _selftest() else 1) sc, r = drive(a.seed, a.kind, a.density, a.driver) print(json.dumps({"route": sc["route"], **{k: r[k] for k in ("collision", "collision_with", "red_violations", "reached", "hard_brakes", "overrides", "time")}, "events": r["events"]}, indent=1))