You are writing a 2D simulation of a differential drive robot in python jax. You want to…
- User
You are writing a 2D simulation of a differential drive robot in python jax. You want to run 1000 robots at the same time, so the code should be vectorised. The states should be x,y for position, theta for the orientation and v for velocity in the direction of the orientation. The control is the speed setting on left and right motor.
Assistant
Here is one way to vectorize a 2D differential drive robot simulation in JAX:
import jax.numpy as jnp from jax import vmap def step(state, left_speed, right_speed): x, y, theta, v = state # Unpack controls vl, vr = left_speed, right_speed # Differential drive kinematics R = 0.5 # wheel radius L = 1.0 # wheel base dt = 0.1 delta_theta = (vr - vl) / L * dt dx = R/2 * (vl + vr) * jnp.cos(theta) * dt dy = R/2 * (vl + vr) * jnp.sin(theta) * dt dv = (vr + vl) / 2 * dt return x + dx, y + dy, theta + delta_theta, v + dv # Vectorized version vstep = vmap(step, in_axes=(0, 0, 0)) # Initial states x0 = jnp.zeros(1000) y0 = jnp.zeros(1000) theta0 = jnp.zeros(1000) v0 = jnp.zeros(1000) states = jnp.stack([x0, y0, theta0, v0], axis=-1) # Controls left_speeds = 0.1 * jnp.ones(1000) right_speeds = 0.2 * jnp.ones(1000) # Step simulation states = vstep(states, left_speeds, right_speeds)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.