Xordas's picture
Benchmark v1: moves, robot, field, example A* + Pedro runner
55752a0 verified
Raw History Blame Contribute Delete
14.2 kB
"""The benchmark robot, simulated: a batch of robots stepped together with numpy.
sim = RobotSim(robot_json, field_json, starts, start_vels, noise_seeds, max_ticks)
est, vel_meas = sim.sensors() # what a controller may read
sim.step(commands) # (N, 3) body commands, forward / left / turn in [-1, 1]
sim.pose, sim.vel # the truth, for scoring only
One control tick (20 ms):
1. wheel powers from the command: mecanum mix, normalised, voltage-compensated against the measured battery
2. stiction: a wheel at rest does not start under its breakaway power
3. drivetrain physics: 4 substeps of 5 ms, the motors seeing the command issued `command_delay_s` earlier
4. contact: the robot is pushed out of walls and hazards, and its velocity into them is removed
5. odometry and velocity measurement, with the robot's sensor noise
The drivetrain model is described in robot.json. Units at the interface: inches, seconds, radians; body velocity
(forward in/s, left in/s, turn rad/s); poses (x, y, heading) in the field frame.
"""
import math
import numpy as np
IN = 0.0254 # m per inch
G = 9.81
QUEUE = 16 # commands remembered for the delay line
class RobotSim:
def __init__(self, robot, field, starts, start_vels, noise_seeds, max_ticks):
self.n = len(starts)
p = robot["drivetrain"]["params"]
k = robot["drivetrain"]["constants"]
w = robot["wheels"]
self.p = {name: float(v) for name, v in p.items()}
self.v_slip, self.v_roll = k["traction_smoothing_m_s"], k["roller_smoothing_m_s"]
self.v_drag, self.w_coul = k["drag_smoothing_m_s"], k["wheel_friction_smoothing_rad_s"]
self.v_ref = k["motor_reference_voltage_v"]
self.R = w["wheel_radius_in"] * IN
L, T = w["wheelbase_in"] * IN, w["trackwidth_in"] * IN
loop = robot["control_loop"]
self.dt, self.n_sub, self.delay = loop["period_s"], loop["physics_substeps"], loop["command_delay_s"]
self.v_nominal = robot["battery"]["nominal_voltage_v"]
self.vbat0 = robot["battery"]["start_voltage_v"]
self.rest_speed = robot["stiction"]["rest_speed_in_s"]
self.breakaway = robot["stiction"]["breakaway"]
s = robot["sensors"]
self.odo_in, self.odo_rad = s["odometry_noise_in"], s["odometry_noise_rad"]
self.vel_noise, self.vbat_noise = np.array(s["velocity_noise"]), s["battery_noise_v"]
self.hl, self.hw = robot["footprint"]["length_in"] / 2, robot["footprint"]["width_in"] / 2
# field: the four walls as large rectangles, then the hazards (x0, x1, y0, y1)
S, wall, big = field["size_in"], field["wall_in"], 200.0
walls = [(-big, wall, -big, S + big), (S - wall, S + big, -big, S + big),
(-big, S + big, -big, wall), (-big, S + big, S - wall, S + big)]
self.rects = np.array(walls + [h["rect"] for h in field["hazards"]], dtype=float)
self.n_walls = 4
self.line_x = field["centre_line_x"]
# wheel geometry relative to the centre of mass; roller directions (fl, fr, bl, br)
pp = self.p
sg = np.array([-1.0, 1.0, 1.0, -1.0])
px0 = np.array([L / 2, L / 2, -L / 2, -L / 2])
py0 = np.array([T / 2, -T / 2, T / 2, -T / 2])
px, py = px0 - pp["com_x"], py0 - pp["com_y"]
g = pp["roller_angle"]
self.c = math.cos(g)
sgs = sg * math.sin(g)
cb = np.full(4, self.c)
self.a = np.stack([cb, sgs, -py * cb + px * sgs], -1) # (4, 3) wheel force direction in body coords
self.b = np.stack([-sgs, cb, sgs * py + px * cb], -1) # (4, 3) free-rolling direction
fx = 0.5 + pp["com_x"] * np.sign(px0) / L
fy = 0.5 + pp["com_y"] * np.sign(py0) / T
self.N = pp["mass"] * G * np.clip(fx * fy, 0.02, None) # (4,) normal load per wheel
self.M = np.array([pp["mass"], pp["mass"], pp["inertia"]])
self.mw = pp["wheel_inertia"] / self.R ** 2
self.kk = self.v_ref / pp["w_free"]
self.Rm = self.v_ref * self.kk / pp["tau_stall"]
self.dm = self.kk * self.kk / self.Rm / self.R ** 2
self.tan_g = math.tan(g)
self.sg, self.px_in, self.py_in = sg, px0 / IN, py0 / IN
# state
self.pose = np.array(starts, dtype=float).reshape(self.n, 3)
self.vel = np.array(start_vels, dtype=float).reshape(self.n, 3)
self.wheel = self._wheel_speeds(self.vel) # rim speed, in/s
self.vbat = np.full(self.n, self.vbat0)
self.charge = np.zeros(self.n)
self.cur = np.zeros((self.n, 4))
self.queue = np.zeros((self.n, QUEUE, 4))
self.est = self.pose.copy()
self.tick = 0
# sensor noise for the whole run, drawn per robot from its noise seed (same draws whatever the controller)
self.noise = np.stack([np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(sd), 1])))
.standard_normal((max_ticks + 1, 8)) for sd in noise_seeds]) # (N, ticks, 8)
self.vel_meas = self.vel + self.noise[:, 0, 3:6] * self.vel_noise
self.contact_wall = np.zeros(self.n, bool)
self.contact_hazard = np.zeros(self.n, bool)
self.impact = np.zeros(self.n)
# ------------------------------------------------------------------ what a controller may read
def sensors(self):
"""(pose estimate (N, 3), measured body velocity (N, 3))."""
return self.est.copy(), self.vel_meas.copy()
# ----------------------------------------------------------------------------------- one tick
def step(self, cmd):
cmd = np.nan_to_num(np.asarray(cmd, dtype=float).reshape(self.n, 3))
cmd = np.clip(cmd, -1.0, 1.0)
z = self.noise[:, min(self.tick, self.noise.shape[1] - 1)]
f, l, t = cmd[:, 0], cmd[:, 1], cmd[:, 2]
power = np.stack([f - l - t, f + l + t, f + l - t, f - l + t], -1)
power /= np.maximum(1.0, np.abs(power).max(-1, keepdims=True))
vb_meas = np.maximum(self.vbat + z[:, 6] * self.vbat_noise, 6.0)
power = np.clip(power * (self.v_nominal / vb_meas)[:, None], -1.0, 1.0)
brk = (self.breakaway * self.v_nominal / np.maximum(self.vbat, 6.0))[:, None]
power = np.where((np.abs(self.wheel) < self.rest_speed) & (np.abs(power) < brk), 0.0, power)
prev_pose = self.pose.copy()
self._physics(power)
pre = self.vel[:, :2].copy()
self._contact()
self.impact = np.linalg.norm(pre - self.vel[:, :2], axis=-1)
self.pose[:, 2] = _wrap(self.pose[:, 2])
self._odometry(prev_pose, z)
self.tick += 1
z = self.noise[:, min(self.tick, self.noise.shape[1] - 1)]
self.vel_meas = self.vel + z[:, 3:6] * self.vel_noise
# ------------------------------------------------------------------------------ drivetrain
def _wheel_speeds(self, vel):
vx, vy, w = vel[:, 0:1], vel[:, 1:2], vel[:, 2:3]
return vx + self.sg * self.tan_g * vy + w * (self.sg * self.tan_g * self.px_in - self.py_in)
def _physics(self, power):
pp, n, dt = self.p, self.n_sub, self.dt
h = dt / n
self.queue = np.concatenate([self.queue[:, 1:], power[:, None]], 1)
u = np.stack([self.vel[:, 0] * IN - self.vel[:, 2] * pp["com_y"],
self.vel[:, 1] * IN + self.vel[:, 2] * pp["com_x"], self.vel[:, 2]], -1) # SI, at the CoM
s = self.wheel * IN
for j in range(n):
back = min(max(math.ceil((self.delay - j * h) / dt - 1e-9), 0), QUEUE - 1)
cmd = self.queue[:, QUEUE - 1 - back]
voc = self.vbat0 - pp["sag_k"] * self.charge
vbus = np.maximum(voc - pp["r_int"] * np.abs(self.cur).sum(-1), 6.0)
u, s, self.cur = self._substep(u, s, cmd, h, vbus)
self.charge = self.charge + np.abs(self.cur).sum(-1) * h
vcx = u[:, 0] + u[:, 2] * pp["com_y"]
vcy = u[:, 1] - u[:, 2] * pp["com_x"]
hm = self.pose[:, 2] + 0.5 * u[:, 2] * h
c, sn = np.cos(hm), np.sin(hm)
self.pose = self.pose + np.stack([(vcx * c - vcy * sn) * h / IN, (vcx * sn + vcy * c) * h / IN, u[:, 2] * h], -1)
self.vel = np.stack([(u[:, 0] + u[:, 2] * pp["com_y"]) / IN, (u[:, 1] - u[:, 2] * pp["com_x"]) / IN, u[:, 2]], -1)
self.wheel = s / IN
voc = self.vbat0 - pp["sag_k"] * self.charge
self.vbat = np.maximum(voc - pp["r_int"] * np.abs(self.cur).sum(-1), 6.0)
def _substep(self, u, s, cmd, h, vbus):
"""One backward-Euler substep with lagged-secant friction; the wheels are eliminated, leaving a 3x3 solve."""
pp, a, b, c = self.p, self.a, self.b, self.c
slip0 = c * s - u @ a.T # (N, 4)
K = pp["mu"] * self.N / self.v_slip * _tanhc(slip0 / self.v_slip) # traction stiffness
Kr = pp["roll_c"] * self.N / self.v_roll * _tanhc((u @ b.T) / self.v_roll)
Kw = (pp["fric_c"] / self.w_coul * _tanhc((s / self.R) / self.w_coul) + pp["fric_v"]) / self.R ** 2
Vm = cmd * vbus[:, None]
d = self.mw / h + self.dm + Kw + K * c * c
r = self.mw / h * s + (self.kk / (self.Rm * self.R)) * Vm
ke = K - K * K * c * c / d
A = np.einsum("ni,ij,ik->njk", ke, a, a) + np.einsum("ni,ij,ik->njk", Kr, b, b)
Mh = self.M / h
dragx = pp["drag_x"] / self.v_drag * _tanhc(u[:, 0] / self.v_drag)
dragy = pp["drag_y"] / self.v_drag * _tanhc(u[:, 1] / self.v_drag)
A[:, 0, 0] += Mh[0] + dragx
A[:, 1, 1] += Mh[1] + dragy
A[:, 2, 2] += Mh[2]
m = pp["mass"]
cor = np.stack([m * u[:, 2] * u[:, 1], -m * u[:, 2] * u[:, 0], np.zeros(self.n)], -1)
rhs = Mh * u + cor + (K * c * r / d) @ a
un = np.linalg.solve(A, rhs[..., None])[..., 0]
sn = (r + K * c * (un @ a.T)) / d
cur = (Vm - self.kk * sn / self.R) / self.Rm
return un, sn, cur
# --------------------------------------------------------------------------------- contact
def _contact(self):
wall_c = hazard_c = None
for it in range(2):
push, hit = _box_vs_rects(self.pose, self.rects, self.hl, self.hw)
if it == 0:
wall_c, hazard_c = hit[:, :self.n_walls].any(-1), hit[:, self.n_walls:].any(-1)
self.pose[:, :2] += push.sum(1)
mag = np.linalg.norm(push, axis=-1, keepdims=True)
u = push / np.maximum(mag, 1e-9)
h = self.pose[:, 2]
c, s = np.cos(h), np.sin(h)
vfx = self.vel[:, 0] * c - self.vel[:, 1] * s
vfy = self.vel[:, 0] * s + self.vel[:, 1] * c
into = np.minimum(vfx[:, None] * u[..., 0] + vfy[:, None] * u[..., 1], 0.0) * hit
vfx = vfx - (into * u[..., 0]).sum(1)
vfy = vfy - (into * u[..., 1]).sum(1)
self.vel[:, 0] = vfx * c + vfy * s
self.vel[:, 1] = -vfx * s + vfy * c
self.contact_wall, self.contact_hazard = wall_c, hazard_c
# -------------------------------------------------------------------------------- odometry
def _odometry(self, prev, z):
"""Dead-wheel odometry: the true motion this tick, in the robot frame, plus noise, added to the estimate."""
dp = self.pose[:, :2] - prev[:, :2]
dh = _wrap(self.pose[:, 2] - prev[:, 2])
mid = prev[:, 2] + dh / 2
c, s = np.cos(mid), np.sin(mid)
df = dp[:, 0] * c + dp[:, 1] * s + z[:, 0] * self.odo_in
dl = -dp[:, 0] * s + dp[:, 1] * c + z[:, 1] * self.odo_in
dhe = dh + z[:, 2] * self.odo_rad
emid = self.est[:, 2] + dhe / 2
ce, se = np.cos(emid), np.sin(emid)
self.est = np.stack([self.est[:, 0] + df * ce - dl * se, self.est[:, 1] + df * se + dl * ce,
_wrap(self.est[:, 2] + dhe)], -1)
# ------------------------------------------------------------------------------------- helpers
def _wrap(a):
return (a + np.pi) % (2 * np.pi) - np.pi
def _tanhc(x):
a = np.maximum(np.abs(x), 1e-4)
return np.tanh(a) / a
def _box_vs_rects(pose, rects, hl, hw):
"""Separating-axis test of each robot's oriented footprint against the axis-aligned rectangles.
Returns (push (N, R, 2): the smallest move out of each overlapped rectangle, hit (N, R))."""
x, y, h = pose[:, 0:1], pose[:, 1:2], pose[:, 2:3]
c, s = np.cos(h), np.sin(h)
x0, x1, y0, y1 = (rects[:, i][None] for i in range(4))
rw, rh = (x1 - x0) / 2, (y1 - y0) / 2
dx, dy = (x0 + x1) / 2 - x, (y0 + y1) / 2 - y
ac, as_ = np.abs(c), np.abs(s)
pf, pl = dx * c + dy * s, -dx * s + dy * c
ov = np.stack([(ac * hl + as_ * hw) + rw - np.abs(dx), (as_ * hl + ac * hw) + rh - np.abs(dy),
hl + (ac * rw + as_ * rh) - np.abs(pf), hw + (as_ * rw + ac * rh) - np.abs(pl)], -1)
hit = (ov > 0).all(-1)
k = ov.argmin(-1)
mn = np.take_along_axis(ov, k[..., None], -1)[..., 0]
one, zero = np.ones_like(dx), np.zeros_like(dx)
cx, sx = np.broadcast_to(c, dx.shape), np.broadcast_to(s, dx.shape)
axes = np.stack([np.stack([one, zero], -1), np.stack([zero, one], -1),
np.stack([cx, sx], -1), np.stack([-sx, cx], -1)], -2) # (N, R, 4, 2)
proj = np.stack([dx, dy, pf, pl], -1)
sgn = np.where(proj >= 0, -1.0, 1.0)
chosen_axis = np.take_along_axis(axes, k[..., None, None].repeat(2, -1), -2)[..., 0, :]
chosen_sgn = np.take_along_axis(sgn, k[..., None], -1)[..., 0]
push = chosen_axis * (chosen_sgn * mn)[..., None] * hit[..., None]
return push, hit
def footprint_corners(pose, hl, hw):
"""(N, 4, 2) corners of each footprint: front-left, front-right, back-right, back-left."""
x, y, h = pose[:, 0], pose[:, 1], pose[:, 2]
c, s = np.cos(h), np.sin(h)
fx, fy, lx, ly = c * hl, s * hl, -s * hw, c * hw
cx = np.stack([x + fx + lx, x + fx - lx, x - fx - lx, x - fx + lx], -1)
cy = np.stack([y + fy + ly, y + fy - ly, y - fy - ly, y - fy + ly], -1)
return np.stack([cx, cy], -1)