#!/usr/bin/env python3 """Offline evaluation of global plans recorded in a rosbag (and/or the planner's tee log). Answers two questions about SBPLLatticePlanner output, with or without the Voronoi corridor: 1. Smoothness — does the path wind where it could go straight? For every plan the script string-pulls it against the recorded global costmap (greedy line-of-sight shortcutting, robot centre must stay on cells below INSCRIBED) and reports how much of the path length that removes (`slack`). A high `slack` with corridor=on and low with corridor=off means the corridor is bending the path; high in both means the lattice/mprim set is. 2. Cost — plan time / eps / expands, taken from the `[debug/plan] metrics:` lines of the tee log written by the planner (needs `debug_plan: true`). Usage: # record while driving goals (see README "Đánh giá đường đi"): # /global_costmap/costmap /global_costmap/costmap_updates /global_costmap/costmap/plan # /move_base_simple/goal /tf /tf_static python3 eval_plan_bag.py --bag soft=/tmp/eval_soft.bag --bag off=/tmp/eval_off.bag \ --log soft=/tmp/sim_soft.log --log off=/tmp/sim_off.log --cache /tmp/eval_cache \ --csv /tmp/eval.csv --plot /tmp/eval Columns: `detour` = path / straight line; `opt2d_m` = shortest 8-connected point-robot route on the recorded costmap (skimage), `over_opt` = path / opt2d — the honest "how much longer than it had to be"; `slack` = share of the path removed by greedy line-of-sight shortcutting. Each --bag/--log takes `label=path`; labels join bag rows with log rows (matched by goal position, in order). Only the FIRST plan of each goal is scored unless --all-plans is given, because replans start from a moving robot and are not comparable across runs. Requires ROS Noetic python3 (`rosbag`, `numpy`); matplotlib only for --plot. """ import argparse import csv import math import os import pickle import re import sys import numpy as np # OccupancyGrid values written by move_base2's CostmapExporter (costmap_exporter.cpp): # -1 unknown, 0 free, 1..98 inflated, 99 inscribed, 100 lethal, 120 preferred, # 150 critical (overflows int8 to -106). "Passable for the robot centre" = below inscribed. OCC_INSCRIBED = 99 OCC_PREFERRED = 120 def yaw_from_quat(q): return math.atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)) def wrap(a): return (a + math.pi) % (2.0 * math.pi) - math.pi class Grid: def __init__(self, msg, allow_unknown): self.res = msg.info.resolution self.ox = msg.info.origin.position.x self.oy = msg.info.origin.position.y self.w = msg.info.width self.h = msg.info.height self.data = np.array(msg.data, dtype=np.int16).reshape(self.h, self.w) self.allow_unknown = allow_unknown def apply_update(self, upd): patch = np.array(upd.data, dtype=np.int16).reshape(upd.height, upd.width) self.data[upd.y:upd.y + upd.height, upd.x:upd.x + upd.width] = patch def passable_mask(self): d = self.data m = (d >= 0) & (d < OCC_INSCRIBED) m |= d == OCC_PREFERRED if self.allow_unknown: m |= d == -1 return m def to_cell(self, x, y): return (x - self.ox) / self.res, (y - self.oy) / self.res def crop(self, xmin, ymin, xmax, ymax): """Sub-grid covering the world box (clamped to the map). Keeps the cache small.""" cx0 = max(0, int(math.floor((xmin - self.ox) / self.res))) cy0 = max(0, int(math.floor((ymin - self.oy) / self.res))) cx1 = min(self.w, int(math.ceil((xmax - self.ox) / self.res)) + 1) cy1 = min(self.h, int(math.ceil((ymax - self.oy) / self.res)) + 1) g = Grid.__new__(Grid) g.res = self.res g.ox = self.ox + cx0 * self.res g.oy = self.oy + cy0 * self.res g.w = cx1 - cx0 g.h = cy1 - cy0 g.data = self.data[cy0:cy1, cx0:cx1].copy() g.allow_unknown = self.allow_unknown return g def optimal_2d_length(grid, mask, p, q): """Length [m] of the shortest 8-connected point-robot path p->q over passable cells (skimage MCP_Geometric). Lower bound for any footprint path; `path_m / opt2d_m` is how much the lattice, eps and corridor together stretched the path. NaN when skimage is missing or no route.""" try: from skimage.graph import route_through_array except ImportError: return float('nan') cost = np.where(mask, 1.0, 1e6) # blocked cells still traversable at 1e6 so MCP never throws cx0, cy0 = grid.to_cell(p[0], p[1]) cx1, cy1 = grid.to_cell(q[0], q[1]) s = (int(round(cy0)), int(round(cx0))) t = (int(round(cy1)), int(round(cx1))) if not (0 <= s[0] < grid.h and 0 <= s[1] < grid.w and 0 <= t[0] < grid.h and 0 <= t[1] < grid.w): return float('nan') idx, total = route_through_array(cost, s, t, fully_connected=True, geometric=True) if total >= 1e6: return float('nan') # went through a blocked cell: no real route inside the crop idx = np.array(idx) d = np.diff(idx, axis=0) return float(np.sum(np.hypot(d[:, 0], d[:, 1])) * grid.res) def line_of_sight(mask, grid, p, q): """True if every cell under segment p->q (world coords) is passable. Samples at half a cell.""" cx0, cy0 = grid.to_cell(p[0], p[1]) cx1, cy1 = grid.to_cell(q[0], q[1]) n = int(max(2, math.ceil(math.hypot(cx1 - cx0, cy1 - cy0) * 2.0))) xs = np.rint(np.linspace(cx0, cx1, n)).astype(int) ys = np.rint(np.linspace(cy0, cy1, n)).astype(int) if (xs < 0).any() or (ys < 0).any() or (xs >= grid.w).any() or (ys >= grid.h).any(): return False return bool(mask[ys, xs].all()) def string_pull(pts, mask, grid): """Greedy shortcut: from anchor i take the farthest j with clear line of sight. Exact (scans j downward), O(anchors * n) LOS checks — fine for a few hundred points.""" out = [0] i = 0 n = len(pts) while i < n - 1: j = n - 1 while j > i + 1 and not line_of_sight(mask, grid, pts[i], pts[j]): j -= 1 out.append(j) i = j return out def path_metrics(xy, th): """Same definitions as the planner's `[debug/plan] metrics:` line (sbpl_lattice_planner.cpp).""" path_m = 0.0 turn = 0.0 arcs = wiggles = 0 run_sign = last_sign = 0 for i in range(1, len(xy)): path_m += math.hypot(xy[i][0] - xy[i - 1][0], xy[i][1] - xy[i - 1][1]) d = wrap(th[i] - th[i - 1]) turn += abs(d) s = 1 if d > 1e-6 else (-1 if d < -1e-6 else 0) if s == 0: run_sign = 0 continue if s != run_sign: arcs += 1 if last_sign != 0 and s != last_sign: wiggles += 1 run_sign = last_sign = s straight = math.hypot(xy[-1][0] - xy[0][0], xy[-1][1] - xy[0][1]) return xy, dict(pts=len(xy), straight_m=straight, path_m=path_m, detour=path_m / max(straight, 1e-3), turn_deg=math.degrees(turn), arcs=arcs, wiggles=wiggles) def read_bag(path, allow_unknown, all_plans, topics): import rosbag grid = None plans = [] last_goal = None seen_goal_ids = set() with rosbag.Bag(path) as bag: for topic, msg, t in bag.read_messages(topics=[topics['costmap'], topics['costmap'] + '_updates', topics['plan'], topics['goal']]): if topic == topics['costmap']: grid = Grid(msg, allow_unknown) elif topic == topics['costmap'] + '_updates': if grid is not None: grid.apply_update(msg) elif topic == topics['goal']: last_goal = (msg.pose.position.x, msg.pose.position.y) elif topic == topics['plan']: if len(msg.poses) < 2: continue stamp = msg.header.stamp.to_sec() if plans and abs(plans[-1]['stamp'] - stamp) < 1e-6: continue # same plan republished at 10 Hz goal = (round(msg.poses[-1].pose.position.x, 2), round(msg.poses[-1].pose.position.y, 2)) first = goal not in seen_goal_ids seen_goal_ids.add(goal) if not first and not all_plans: continue xy = [(p.pose.position.x, p.pose.position.y) for p in msg.poses] yaw = [yaw_from_quat(p.pose.orientation) for p in msg.poses] crop = None if grid is not None: xs = [c[0] for c in xy] ys = [c[1] for c in xy] crop = grid.crop(min(xs) - CROP_MARGIN_M, min(ys) - CROP_MARGIN_M, max(xs) + CROP_MARGIN_M, max(ys) + CROP_MARGIN_M) plans.append(dict(stamp=stamp, t=t.to_sec(), goal=goal, first=first, xy=xy, yaw=yaw, grid=crop, sent_goal=last_goal)) return plans CROP_MARGIN_M = 20.0 # [m] around the path bbox: room for the optimal 2D route to detour def load_plans(label, path, allow_unknown, all_plans, topics, cache_dir): """Bag read is the slow part (a full costmap is 9 MB per message); cache the extracted plans + cropped grids per label so re-analysis after a script change is seconds, not minutes.""" cache = os.path.join(cache_dir, f'{label}.pkl') if cache_dir else None if cache and os.path.exists(cache) and os.path.getmtime(cache) >= os.path.getmtime(path): with open(cache, 'rb') as f: return pickle.load(f) plans = read_bag(path, allow_unknown, all_plans, topics) if cache: os.makedirs(cache_dir, exist_ok=True) with open(cache, 'wb') as f: pickle.dump(plans, f, protocol=pickle.HIGHEST_PROTOCOL) return plans LOG_RE = re.compile(r'\[debug/plan\] metrics: (.*)$') KV_RE = re.compile(r'(\w+)=(\([^)]*\)|[^\s]+)') def read_log(path): rows = [] with open(path, errors='replace') as f: for line in f: m = LOG_RE.search(line) if not m: continue kv = dict(KV_RE.findall(m.group(1))) gx, gy = kv['goal'].strip('()').split(',') row = dict(goal=(round(float(gx), 2), round(float(gy), 2))) for k in ('straight_m', 'path_m', 'detour', 'turn_deg', 'plan_ms', 'corridor_ms', 'route_m', 'eps', 'raw_m', 'smooth_ms', 'first_cpu_ms'): row[k] = float(kv.get(k, 'nan')) for k in ('arcs', 'wiggles', 'pts', 'expands', 'widen', 'anchors', 'first_expands'): row[k] = int(kv.get(k, '0')) row['corridor'] = kv.get('corridor', '?') row['smooth'] = kv.get('smooth', '?') row['fillets'] = kv.get('fillets', '') rows.append(row) return rows LOG_JOIN_COLS = ('plan_ms', 'corridor_ms', 'route_m', 'eps', 'expands', 'corridor', 'widen', 'raw_m', 'smooth', 'smooth_ms', 'anchors', 'fillets', 'first_cpu_ms', 'first_expands') def match_log(plan_rows, log_rows): """Attach the k-th log row whose goal lies within 0.1 m to the k-th bag plan with that goal (the bag's goal is the plan's last pose, the log's is the requested goal — they differ by the lattice cell rounding, so no exact match).""" used = [False] * len(log_rows) for r in plan_rows: for i, lr in enumerate(log_rows): if not used[i] and math.hypot(lr['goal'][0] - r['goal'][0], lr['goal'][1] - r['goal'][1]) <= 0.1: used[i] = True for k in LOG_JOIN_COLS: r[k] = lr[k] break def evaluate(label, plans): rows = [] for p in plans: xy = p['xy'] _, m = path_metrics(xy, p['yaw']) m.update(label=label, stamp=p['stamp'], goal=p['goal'], first=p['first']) if p['grid'] is not None: mask = p['grid'].passable_mask() idx = string_pull(xy, mask, p['grid']) sc = sum(math.hypot(xy[idx[k]][0] - xy[idx[k - 1]][0], xy[idx[k]][1] - xy[idx[k - 1]][1]) for k in range(1, len(idx))) m['shortcut_m'] = sc m['sc_pts'] = len(idx) m['slack'] = (m['path_m'] - sc) / max(m['path_m'], 1e-3) m['opt2d_m'] = optimal_2d_length(p['grid'], mask, xy[0], xy[-1]) m['over_opt'] = m['path_m'] / m['opt2d_m'] if m['opt2d_m'] > 0 else float('nan') m['_xy'] = xy m['_sc'] = [xy[i] for i in idx] m['_grid'] = p['grid'] else: m['shortcut_m'] = float('nan') m['sc_pts'] = 0 m['slack'] = float('nan') m['opt2d_m'] = float('nan') m['over_opt'] = float('nan') rows.append(m) return rows COLS = ['label', 'goal', 'first', 'straight_m', 'path_m', 'detour', 'opt2d_m', 'over_opt', 'shortcut_m', 'slack', 'turn_deg', 'arcs', 'wiggles', 'pts', 'plan_ms', 'corridor_ms', 'eps', 'expands', 'corridor', 'route_m', 'widen', 'smooth', 'raw_m', 'smooth_ms', 'fillets', 'first_cpu_ms', 'first_expands'] def fmt(v): if isinstance(v, float): return f'{v:.3f}' if abs(v) < 10 else f'{v:.1f}' if isinstance(v, tuple): return f'({v[0]:.1f},{v[1]:.1f})' return str(v) def print_table(rows): widths = {c: max(len(c), *(len(fmt(r.get(c, ''))) for r in rows)) for c in COLS} print(' '.join(c.rjust(widths[c]) for c in COLS)) for r in rows: print(' '.join(fmt(r.get(c, '')).rjust(widths[c]) for c in COLS)) def print_summary(rows): by = {} for r in rows: by.setdefault(r['label'], []).append(r) print('\nsummary (median over plans, first plan per goal):') for label, rs in by.items(): rs = [r for r in rs if r['first']] or rs def med(k): vals = [r[k] for r in rs if k in r] return float(np.nanmedian(vals)) if vals else float('nan') print(f" {label:>10}: n={len(rs)} detour={med('detour'):.3f} over_opt={med('over_opt'):.3f} " f"slack={med('slack'):.3f} turn_deg={med('turn_deg'):.0f} wiggles={med('wiggles'):.0f} " f"plan_ms={med('plan_ms'):.0f} eps={med('eps'):.2f}") def plot(rows, prefix): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt for k, r in enumerate(rows): if '_grid' not in r: continue g = r['_grid'] fig, ax = plt.subplots(figsize=(10, 10)) ax.imshow(g.data, cmap='gray_r', origin='lower', vmin=-1, vmax=100, extent=[g.ox, g.ox + g.w * g.res, g.oy, g.oy + g.h * g.res]) xy = np.array(r['_xy']) sc = np.array(r['_sc']) ax.plot(xy[:, 0], xy[:, 1], 'r-', lw=1.2, label=f"plan {r['path_m']:.1f} m") ax.plot(sc[:, 0], sc[:, 1], 'g--', lw=1.0, label=f"string-pull {r['shortcut_m']:.1f} m") pad = 3.0 ax.set_xlim(xy[:, 0].min() - pad, xy[:, 0].max() + pad) ax.set_ylim(xy[:, 1].min() - pad, xy[:, 1].max() + pad) ax.set_title(f"{r['label']} goal={fmt(r['goal'])} detour={r['detour']:.2f} over_opt={r['over_opt']:.2f} " f"slack={r['slack']:.2f} turn={r['turn_deg']:.0f}deg wiggles={r['wiggles']}") ax.legend(loc='upper right') out = f"{prefix}_{r['label']}_{k:02d}.png" fig.savefig(out, dpi=110, bbox_inches='tight') plt.close(fig) print(f'plot: {out}') def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--bag', action='append', default=[], metavar='LABEL=PATH') ap.add_argument('--log', action='append', default=[], metavar='LABEL=PATH', help='planner tee log; adds plan_ms/eps/expands/corridor columns') ap.add_argument('--csv', help='write all rows here') ap.add_argument('--plot', metavar='PREFIX', help='write _