harryzhang1018's picture
Add reproduction code and README
0c3dd1d verified
Raw History Blame Contribute Delete
7.14 kB
"""Vectorised error/metric helpers (NEW CODE).
error_state_vec reproduces ControlNode.error_state (path_follower.py:135-184)
for many samples at once (used for the 100 Hz log). Equality with the released
function was checked in a parity test.
"""
import numpy as np
TWO_PI = 2 * np.pi
def wrap(a):
return np.arctan2(np.sin(a), np.cos(a))
def wrap_released(theta):
"""path_follower.py:143-146 (while loops), vectorised."""
th = np.array(theta, dtype=float, copy=True)
for _ in range(64):
lo = th < -np.pi
hi = th > np.pi
if not (lo.any() or hi.any()):
break
th[lo] = th[lo] + 2 * np.pi
th[hi] = th[hi] - 2 * np.pi
return th
def heading_error_released(ref, act):
"""Branch logic of path_follower.py:154-169, vectorised (same operation order)."""
ref = np.asarray(ref, dtype=float)
act = np.asarray(act, dtype=float)
out = np.empty(np.broadcast(ref, act).shape)
same = ((ref > 0) & (act > 0)) | ((ref <= 0) & (act <= 0))
c2 = (~same) & (ref <= 0) & (act > 0)
c3 = (~same) & ~c2
out[same] = (ref - act)[same]
a2 = np.abs(ref - act) < np.abs(2 * np.pi + ref - act)
out[c2 & a2] = (-np.abs(act - ref))[c2 & a2]
out[c2 & ~a2] = np.abs(2 * np.pi + ref - act)[c2 & ~a2]
a3 = np.abs(ref - act) < np.abs(2 * np.pi - ref + act)
out[c3 & a3] = np.abs(act - ref)[c3 & a3]
out[c3 & ~a3] = (-np.abs(2 * np.pi - ref + act))[c3 & ~a3]
return out
def nearest_index(x, y, theta, ref, lookahead, chunk=2048):
"""argmin over waypoints of the released squared distance (first minimum)."""
x = np.atleast_1d(np.asarray(x, dtype=float))
y = np.atleast_1d(np.asarray(y, dtype=float))
th = wrap_released(np.atleast_1d(np.asarray(theta, dtype=float)))
px = x + np.cos(th) * lookahead
py = y + np.sin(th) * lookahead
idx = np.empty(len(x), dtype=np.int64)
for i in range(0, len(x), chunk):
d = (px[i:i + chunk, None] - ref[None, :, 0]) ** 2 + (py[i:i + chunk, None] - ref[None, :, 1]) ** 2
idx[i:i + chunk] = d.argmin(axis=1)
return idx
def error_state_vec(x, y, theta, v, ref, lookahead):
"""Returns (E, idx): E[:, 0..3] = released error_state(lookahead) for each sample."""
x = np.atleast_1d(np.asarray(x, dtype=float))
y = np.atleast_1d(np.asarray(y, dtype=float))
v = np.atleast_1d(np.asarray(v, dtype=float))
th = wrap_released(np.atleast_1d(np.asarray(theta, dtype=float)))
idx = nearest_index(x, y, th, ref, lookahead)
r = ref[idx]
err_theta = heading_error_released(r[:, 2], th)
c, s = np.cos(-th), np.sin(-th)
dx, dy = r[:, 0] - x, r[:, 1] - y
e0 = c * dx + (-s) * dy
e1 = s * dx + c * dy
return np.column_stack((e0, e1, err_theta, r[:, 3] - v)), idx
def audit_errors(x, y, yaw, ref):
"""Same formula as errors() in physical/physical_runs.py (zero lookahead):
signed body-frame lateral and wrapped heading error to the nearest waypoint."""
x, y, yaw = (np.asarray(a, dtype=float) for a in (x, y, yaw))
idx = ((x[:, None] - ref[None, :, 0]) ** 2 + (y[:, None] - ref[None, :, 1]) ** 2).argmin(axis=1)
dx, dy = ref[idx, 0] - x, ref[idx, 1] - y
lateral = -np.sin(yaw) * dx + np.cos(yaw) * dy
heading = wrap(ref[idx, 2] - yaw)
return np.column_stack((lateral, heading)), idx
def first_tube_entry(t, lat, head, tube_lat, tube_head):
inside = (np.abs(lat) < tube_lat) & (np.abs(head) < tube_head)
k = np.flatnonzero(inside)
return (float(t[k[0]]), int(k[0])) if len(k) else (None, None)
class ProgressTracker:
"""Forward-window waypoint tracker and completion rule (fixed):
idx starts at 0; each sample, idx += argmin over ref[idx:idx+31] of squared
distance (COG position); completion = first sample with idx == N-1 and
(p - ref[N-1]) . unit(ref[N-1] - ref[N-2]) >= 0. Same rule as
the observer used for the original-ROS reference runs, so runner and
original-ROS reference runs terminate identically."""
def __init__(self, ref, window=31):
self.ref = ref
self.n = len(ref)
self.window = window
d = ref[-1, :2] - ref[-2, :2]
self.last_dir = d / np.linalg.norm(d)
self.idx = 0
self.completed = False
def update(self, x, y):
xy = np.array([x, y])
hi = min(self.n, self.idx + self.window)
win = self.ref[self.idx:hi, :2]
self.idx += int(np.argmin(((win - xy) ** 2).sum(1)))
dmin = float(np.sqrt(((self.ref[:, :2] - xy) ** 2).sum(1).min()))
just = False
if not self.completed and self.idx == self.n - 1 and float((xy - self.ref[-1, :2]) @ self.last_dir) >= 0:
self.completed = True
just = True
return self.idx, dmin, just
# Offline spin / sliding diagnostic, fixed before any
# campaign run. A 100 Hz sample is flagged when |yaw rate| > 1.5 rad/s AND |yaw rate| > 2 x speed / 1.02 m (twice the
# kinematic bound v / R_min at full steering, R_min ~ 1.02 m); a spin is >= 3 consecutive flagged samples. Reported
# separately from settling time and divergence; it never changes an outcome.
SPIN_CRITERION = {'yaw_rate_min_rad_s': 1.5, 'kinematic_factor': 2.0, 'r_min_m': 1.02, 'min_consecutive_samples': 3}
def spin_events(yaw_rate, speed, yaw_rate_min=1.5, factor=2.0, r_min=1.02, n_consecutive=3):
"""Returns (index of the first sample of the first run of n_consecutive flagged samples or None,
number of flagged samples, max |yaw rate|)."""
yr = np.abs(np.asarray(yaw_rate, dtype=float))
sp = np.asarray(speed, dtype=float)
if len(yr) == 0:
return None, 0, None
flag = (yr > yaw_rate_min) & (yr > factor * sp / r_min)
k0 = None
if len(flag) >= n_consecutive:
run = np.convolve(flag.astype(int), np.ones(n_consecutive, dtype=int), 'valid') >= n_consecutive
k = np.flatnonzero(run)
k0 = int(k[0]) if len(k) else None
return k0, int(flag.sum()), float(yr.max())
def divergence_events(steps, dist, dist_m, hold_steps):
"""Offline replay of the ONLINE divergence rule of episode.py on the
100 Hz log. A run is a maximal sequence of consecutive logged samples with dist > dist_m; it is a divergence
event if some sample of the run satisfies step - run_start >= hold_steps (the online rule fires at the first such
sample). Returns a list of {'start_step', 'fire_step', 'end_step'}; end_step = last sample of the run with
dist > dist_m, or None if the run lasts to the end of the log."""
steps = np.asarray(steps, dtype=np.int64)
over = np.asarray(dist, dtype=float) > dist_m
events = []
i, n = 0, len(steps)
while i < n:
if not over[i]:
i += 1
continue
j = i
while j + 1 < n and over[j + 1]:
j += 1
start = int(steps[i])
fired = np.flatnonzero(steps[i:j + 1] - start >= hold_steps)
if len(fired):
events.append({'start_step': start, 'fire_step': int(steps[i + fired[0]]),
'end_step': None if j == n - 1 else int(steps[j])})
i = j + 1
return events