"""Run the 2026 BioBuzz Movement Benchmark with an example controller: an A* planner and a Pedro Pathing-style path follower. python run_benchmark.py # the quick tier: 4,096 moves python run_benchmark.py --all # all 262,144 moves (slow: this controller is plain Python) python run_benchmark.py --category corridor # one category (of the quick tier, or of all with --all) python run_benchmark.py --out results.csv # also save one row per move To benchmark your own controller, write a class like AStarPedro below (start_move and step) and use it in main(). Needs numpy, pandas and pyarrow. """ import argparse import json import os import time import numpy as np import pandas as pd from astar import Planner from pedro import PedroFollower from scoring import TIMEOUT_TICKS, Scorer from sim import RobotSim HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) # ------------------------------------------------------------------------------- the controller class AStarPedro: """Plans a route with A* when a move starts, then follows it with the Pedro-style follower. A controller sees only what the robot knows: its pose estimate, its measured velocity and the points of the move. It returns a body command (forward, left, turn), each in [-1, 1], and a done flag (None if it has none: then it arrives by holding still inside the tolerances, as this one does). """ has_done_flag = False def __init__(self, planner): self.planner = planner self.follower = PedroFollower() def start_move(self, estimate, points): """estimate: (x, y, heading). points: the intermediate points, then the goal, as (x, y, heading).""" route, here = [], tuple(estimate) for p in points: leg = self.planner.plan(here, p) if leg is None: # no route: hold where it is (the move will time out) self.follower.hold(estimate) return route += leg if not route else leg[1:] here = p self.follower.follow(route) def step(self, estimate, velocity, target): forward, left, turn = self.follower.update(tuple(estimate), tuple(velocity)) return forward, left, turn, None # --------------------------------------------------------------------------------- running moves def run_batch(moves, robot, field, planner): """Drive one batch of moves to the end. Returns one result dict per move.""" rows = moves.to_dict("records") starts = [(m["start_x"], m["start_y"], m["start_h"]) for m in rows] start_vels = [(m["vx0"], m["vy0"], m["w0"]) for m in rows] max_ticks = TIMEOUT_TICKS * (int(moves["n_via"].max()) + 1) + 10 sim = RobotSim(robot, field, starts, start_vels, [m["noise_seed"] for m in rows], max_ticks) controllers = [AStarPedro(planner) for _ in rows] scorer = Scorer(rows, field, robot, AStarPedro.has_done_flag) est, vel = sim.sensors() for i, c in enumerate(controllers): c.start_move(est[i], [p[:3] for p in scorer.points[i]]) for _ in range(max_ticks): if scorer.all_finished(): break est, vel = sim.sensors() scorer.next_points(est, sim.vel) targets = scorer.goals() commands = np.zeros((len(rows), 3)) done = [None] * len(rows) for i in np.flatnonzero(~scorer.finished): *cmd, done[i] = controllers[i].step(est[i], vel[i], targets[i]) commands[i] = cmd scorer.judge_done(est, sim.vel, done) commands[scorer.finished] = 0.0 # a finished move stops the motors sim.step(commands) scorer.after_physics(sim, commands) return scorer.results() # ----------------------------------------------------------------------------------- the summary def summarise(results, has_done_flag): r = pd.DataFrame(results) arrived = r[r.outcome == "arrived"] pct = lambda x: f"{100 * x:.2f}%" print(f"\n{len(r):,} moves") print(f" success (arrived, never over the line) {pct(r.success.mean())}") print(f" arrived {pct((r.outcome == 'arrived').mean())}") print(f" wrong done {pct((r.outcome == 'wrong_done').mean()) if has_done_flag else 'n/a (no done flag)'}") print(f" timed out {pct((r.outcome == 'timed_out').mean())}") print(f" stalled {pct((r.outcome == 'stalled').mean())}") print(f" time to goal {arrived.time_s.mean():.2f} s average, {arrived.time_s.quantile(0.9):.2f} s slowest 10%") print(f" final error {arrived.final_error_in.mean():.2f} in, {arrived.final_heading_error_deg.mean():.2f} deg") print(f" path length / shortest path {arrived.path_ratio.mean():.3f}") print(f" touched a wall / a hazard {pct(r.touched_wall.mean())} / {pct(r.touched_hazard.mean())}") print(f" hard hits (over 12 in/s) {pct((r.hard_hits > 0).mean())} of moves") print(f" crossed the centre line {pct(r.crossed_line.mean())}") print(f" closest to a hazard {r.min_hazard_gap_in.quantile(0.05):.2f} in (5th percentile)") print(f" closest to the centre line {r.min_line_gap_in.quantile(0.05):.2f} in (5th percentile)") multi = r[r.points_total > 1] if len(multi): print(f" multi-step: speed at intermediate points {multi.switch_speed_in_s.mean():.1f} in/s average") print("\nby category") by = r.groupby("category", sort=False).agg( moves=("id", "size"), success=("success", "mean"), timed_out=("outcome", lambda o: (o == "timed_out").mean()), time_s=("time_s", "mean"), error_in=("final_error_in", "mean"), hard_hit=("hard_hits", lambda h: (h > 0).mean()), crossed=("crossed_line", "mean")) for k in ("success", "timed_out", "hard_hit", "crossed"): by[k] = (100 * by[k]).map("{:.2f}%".format) print(by.to_string(float_format=lambda v: f"{v:.2f}")) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--all", action="store_true", help="all 262,144 moves instead of the 4,096-move quick tier") ap.add_argument("--category", help="only this category") ap.add_argument("--limit", type=int, help="only the first N moves") ap.add_argument("--batch", type=int, default=512, help="moves simulated together") ap.add_argument("--out", help="save one row per move (.csv)") a = ap.parse_args() robot = json.load(open(os.path.join(ROOT, "robot.json"))) field = json.load(open(os.path.join(ROOT, "field.json"))) moves = pd.read_parquet(os.path.join(ROOT, "moves.parquet")) if not a.all: moves = moves[moves.quick] if a.category: moves = moves[moves.category == a.category] if a.limit: moves = moves.head(a.limit) print(f"{len(moves):,} moves, controller: A* + Pedro-style follower") planner = Planner(field, robot) results, t0 = [], time.time() for b in range(0, len(moves), a.batch): results += run_batch(moves.iloc[b:b + a.batch], robot, field, planner) done = len(results) print(f" {done:,} / {len(moves):,} moves ({time.time() - t0:.0f} s)", flush=True) summarise(results, AStarPedro.has_done_flag) if a.out: pd.DataFrame(results).to_csv(a.out, index=False) print(f"\nper-move results: {a.out}") if __name__ == "__main__": main()