Algorithmadvanced
STOMP
Also called stochastic trajectory optimization for motion planning.
Improves a trajectory by sampling noisy variants, weighting them by cost, and averaging, so the cost needs no gradient.
- Solves
- Trajectory optimization
- Time
- O(I (K n (d + C) + n^2 d)) worst
- Space
- O(K n d + n^2) extra
- Where
- C = the time to evaluate the state cost at one waypoint; I = the number of iterations; K = the number of samples per iteration; d = the dimension of the configuration space; n = the number of waypoints
- Model
- Real RAM
- Properties
- randomizednot exactofflinerandomized
- Evidence
- Proof sketchCode in 1 languages
STOMP improves a robot trajectory without gradients. In each iteration it adds random smooth noise to the current trajectory several times, evaluates the cost of each noisy copy at every waypoint, and moves each waypoint toward the noisy copies that were cheap there. The noise is drawn from a Gaussian whose covariance is the inverse of a smoothness matrix, the same kind of finite-difference matrix that CHOMP uses for its steps, so the samples are smooth curves and not jagged ones. Because only cost values are used, the cost can be a step function, a collision count, or the output of a simulator. Like all methods for trajectory optimization, STOMP is local, and it has no convergence guarantee; the implementation keeps the best trajectory it has seen.
In plain words
Lay a chain of beads from start to goal. Shake the chain gently many times, each time in a smooth random way, and note for every bead where it was cheap to be. Then move every bead toward the places where its shaken copies did well, and smooth the move so the chain stays smooth. Repeat. Nothing needs to know which way is downhill; it is enough to compare a few tries. The price is randomness: the chain wanders, and once all the tries look the same it keeps wandering without a goal. So the method remembers the best chain it has seen and returns that one. It can still get stuck in a poor local solution, and it does not promise a collision-free result.
The problem
Input: a start and a goal in , a number of free waypoints , a state cost that can be evaluated but need not be differentiable, and a weight for smoothness. Let be the second-difference matrix, with on the diagonal and next to it, and . The total cost is
with and ; the second sum is the sum of squared accelerations. Output: a trajectory with a small . Nothing guarantees a minimum.
This page uses a point robot in the plane () and, for discs, the state cost , which is positive near or inside a disc. The algorithm never uses its gradient.
The algorithm
STOMP(θ, K, λ, σ, I)- 1
for i ← 1 to I do - 2
for k ← 1 to K do - 3
draw ε_k ~ N(0, σ² R⁻¹) for each coordinate; θ̃_k ← θ + ε_k - 4
S_{k,t} ← q(θ̃_{k,t}) for t = 1, …, n - 5
for t ← 1 to n do - 6
P_{k,t} ← exp(-S_{k,t}/λ) / Σ_j exp(-S_{j,t}/λ) for k = 1, …, K - 7
δ̃_t ← Σ_k P_{k,t} ε_{k,t} - 8
θ ← θ + M δ̃ ▷ smooth the update - 9
if Q(θ) < Q(best) then best ← θ - 10
return best
Line L3 draws smooth noise. With , the vector has covariance , and is tridiagonal, so one sample costs per coordinate with the Thomas algorithm. Noise with large accelerations has a small density, so the samples are smooth bumps that vanish at the fixed ends. Line L4 evaluates the state cost of each noisy copy at each waypoint; this is the only place the cost enters, and only its values are used.
Lines L5 to L7 are the core. At each waypoint separately, the costs of the samples become weights by a softmax with temperature : a sample that is cheap at waypoint gets a large weight there. The update is the weighted average of the noise at waypoint . Because the weights are computed per waypoint, a sample that is good in one part of the trajectory and bad in another helps only where it is good. The code subtracts the smallest cost before the exponential; this does not change the weights and prevents overflow.
Line L8 smooths the update with a matrix built from , because the per-waypoint averages of line L7 can be rough. This page follows a common choice: the columns of , each scaled so that its largest entry is . Then each waypoint moves by at most the largest noise value of the iteration (proof, Step 4). Line L9 keeps the best iterate by the total cost , which includes the smoothness term that lines L4 to L7 ignore.
Example
A point moves from to with waypoints. One disc of radius has its center at , so the straight start line cuts it deep. The state cost uses a margin of . The parameters are , , , , and the random seed is 2011.
| iteration | of the iterate | smallest clearance | height of the middle waypoint |
|---|---|---|---|
| 0 | 3.0202 | 0.000 | |
| 1 | 1.9150 | 0.165 | |
| 2 | 1.2449 | 0.253 | |
| 5 | 0.5744 | 0.344 | |
| 7 | 0.0075 | 0.110 | 0.477 |
| 10 | 0.0102 | 0.197 | 0.565 |
| 20 | 0.0211 | 0.307 | 0.800 |
| 50 | 0.0380 | 0.438 | 1.102 |
| 100 | 0.0459 | 0.420 | 1.184 |
The trajectory climbs over the side of the disc away from its center and leaves the margin after seven iterations. is not monotone: it is after iteration 3, after iteration 4, and after iteration 5. Once the trajectory is clear of the margin, more and more samples have state cost zero at every waypoint; where all samples cost zero the weights are uniform and the update is the smoothed mean of the noise. The iterate then drifts at random, upward in this run, and grows again through the smoothness term. Line L9 returns the iterate of iteration 7, with and clearance .
With a cost that has no useful gradient at all, within distance of the disc center and elsewhere, the start line costs (eleven waypoints are inside). With the same parameters and seed 7, sixty iterations return a trajectory with and clearance .
Correctness
STOMP has no convergence guarantee, and the proof does not claim one. It proves what holds for every run. The noise of line L3 has covariance . The weights are positive, sum to one, favor cheaper samples, and do not change when a constant is added to the costs. Each update moves a waypoint by at most the largest noise value of the iteration, and the ends never move. When the costs at every waypoint are equal, the expected update is zero, so the iterates perform a random walk; this is the drift of the example. Finally, the returned trajectory has the smallest among all iterates, so it is never worse than the start. Nothing is proved about collisions: if no sample ever finds a cheaper position, the trajectory stays in collision.
Proof: The noise of STOMP has covariance proportional to the inverse of the smoothness matrix, each update is bounded by the noise, and the returned trajectory is never worse than the startfull
We use the notation of the page and of the code. There are free waypoints between the fixed ends and . is the tridiagonal matrix with on the diagonal and next to it, and . The total cost is with and , for an arbitrary state cost . STOMP gives no convergence guarantee. The statements below are what can be proved about one iteration and about the returned trajectory.
Step 1: the noise has covariance
is nonsingular: has eigenvalues for . Line L3 draws for each coordinate and sets . A linear map of a Gaussian vector is Gaussian, with mean and covariance
So the noise is a zero-mean Gaussian whose density is proportional to : noise with a large sum of squared second differences is unlikely. The two coordinates are independent.
Step 2: the entries of and of are positive
is a symmetric, positive definite matrix with nonpositive entries off the diagonal and an irreducible (connected) pattern, so its inverse has only positive entries (a standard property of such M-matrices; it also follows from the explicit inverse , which one checks by multiplying). Then has positive entries too. The code builds by dividing column of by times its largest entry, so for all , and each column has an entry equal to .
Step 3: the weights
For one waypoint , line L6 sets with . The code subtracts first; this multiplies numerator and denominator by the same factor and does not change .
(a) and .
(b) Adding the same constant to all does not change (the same argument as for the subtraction of the minimum).
(c) If then : the cheaper sample gets more weight.
(d) If all are equal, for all .
(e) As , tends to the uniform distribution on the set of samples with the smallest cost: for such a sample, , and for the others it tends to .
Step 4: one update is bounded by the noise
Fix a coordinate. By line L7, is a convex combination of the noise values at waypoint (Step 3(a)), so . Line L8 adds to waypoint . By Step 2,
So in one iteration no coordinate of any waypoint moves by more than the largest noise value drawn in that iteration. The ends and are not variables and never move.
Step 5: with no information in the costs, the expected update is zero
If at every waypoint all samples have the same state cost, then by Step 3(d), and is the mean of independent draws with mean . So the expected update is , but the update itself is a nonzero random vector with covariance per coordinate. Repeated over many iterations, the iterate performs a random walk. In particular the iterates do not converge, and the smoothness part of , which line L6 never sees, can grow.
Step 6: the returned trajectory
Theorem. Let be the start and the iterates after each pass of lines L2 to L8. The trajectory returned by line L10 is an iterate with
Proof. By induction on the number of passes, after pass the stored trajectory is an iterate among with the smallest . This holds before the loop, where the stored trajectory is . Line L9 replaces it by exactly when is smaller, which keeps the invariant. At the end, take ; the inequality is the case of the minimum.
What is not proved
There is no statement that decreases from one iterate to the next, that the iterates converge, or that the result is free of collision. Step 5 shows that the iterates keep moving at random once the state cost is flat near them, and the example on the page shows of the iterates going up and down. The weighted average of line L7 is a stochastic estimate of a descent direction only when the noise is small and the costs vary across the samples; the method is local, like the other trajectory optimizers. The choice of , , and is a matter of tuning, not of this proof.
Complexity
One iteration draws samples at each, evaluates the state cost at points at each, computes weights and averages, and multiplies by the dense matrix at . So one iteration costs , and is computed once in with tridiagonal solves. The memory is for the samples and for . The cost evaluations usually dominate, because includes collision checks of the whole robot.
There is no bound on the number of iterations, and the seven iterations of the example are a measurement of one run with one seed.
Properties
- Gradient-free. Only values of the state cost are used, so costs from collision checkers, step functions and simulations work.
- Local. The samples explore only near the current trajectory, with a spread set by .
- Randomized. Different seeds give different results; the runs are reproducible only with a fixed seed.
- Not monotone. of the iterates can go up; keeping the best iterate makes the returned value monotone in the number of iterations.
- Smooth updates. The noise and the update are shaped by , so trajectories stay smooth and the ends stay fixed.
- Parallel. The samples are independent and can be evaluated at the same time.
Variants and improvements
- Reuse of samples. Keep the best samples of earlier iterations, with their costs updated, so fewer new samples are needed per iteration.
- Normalized costs. Rescale the costs at each waypoint by their range before line L6, so that the temperature does not depend on the scale of the cost.
- Noise schedule. Shrink over the iterations, so that the drift of the example dies out near the end.
- Constraints. Add constraint violations to the state cost as penalties; there is no hard constraint handling in the basic method.
- Related methods. The cross-entropy method is another sampling optimizer, which refits a distribution to the best samples instead of averaging with weights. CHOMP uses the same smoothness matrix but follows gradients. TrajOpt and GPMP2 use gradients and handle collisions more precisely.
When to use it
Use STOMP when the cost has no useful gradient: a collision checker that only says yes or no, costs from a physics simulation, or terms such as torque limits that are easy to evaluate and hard to differentiate. It is also easy to implement for a new cost. Prefer a gradient method such as CHOMP or TrajOpt when gradients are available and cheap, because they need far fewer cost evaluations. For maze-like problems use a sampling planner first.
Pitfalls
- The temperature. If in line L6 is too small, one sample takes all the weight and the update is as noisy as a single sample; if it is too large, all samples get almost the same weight and the update is the mean noise, which carries no information.
- The noise level. If in line L3 is too small, no sample reaches a cheaper region and the trajectory does not move out of a deep obstacle; if it is too large, the samples are far from the trajectory and the averages are rough.
- Drift. Once the state costs of line L4 are flat, line L8 adds a random walk. Without line L9 the result would depend on when the loop stops.
- Thin obstacles. Line L4 evaluates the cost only at the waypoints, so a thin obstacle between two waypoints is not seen. Check the segments, or use enough waypoints.
- Weights are tuning. The parameters of the original paper (the number of samples, the noise level, the temperature) are chosen for its experiments; they are rules of thumb, not derived values, and other scenes need other values.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stomp/. The authors are listed in prov/2F4S7V.jsonl.
"""STOMP: stochastic trajectory optimization for motion planning.
A point robot moves in the plane from q_0 to q_(n+1) through n free
waypoints theta_1, ..., theta_n. A is the n x n second-difference matrix
(1, -2, 1) and R = A^T A. The total cost of a trajectory is
Q(theta) = sum_t q(theta_t) + (w / 2) sum_t |acc_t|^2,
where q is a state cost (any function, no gradient needed) and acc_t is the
second difference at waypoint t, using the fixed ends.
Each iteration samples K noise trajectories eps_k ~ N(0, sigma^2 R^-1) for
each coordinate, evaluates the state cost of theta + eps_k at every
waypoint, turns the costs at each waypoint into weights
P = exp(-S / lam) / sum exp(-S / lam), averages the noise with these
weights, smooths the average with M (R^-1 with each column scaled so that
its largest entry is 1/n), and adds it to theta. The best trajectory seen,
by Q, is returned.
A is symmetric and tridiagonal, so eps = sigma A^-1 z with z ~ N(0, I) has
the covariance sigma^2 (A^T A)^-1 = sigma^2 R^-1 and costs O(n) to sample.
"""
import math
import random
def straight_line(q0, q1, n):
return [[q0[d] + (q1[d] - q0[d]) * t / (n + 1) for d in range(2)] for t in range(1, n + 1)]
def solve_second_difference(rhs):
"""Solve A x = rhs, A = tridiag(1, -2, 1) of size n (Thomas algorithm)."""
n = len(rhs)
c = [0.0] * n
d = [0.0] * n
beta = -2.0
c[0] = 1.0 / beta
d[0] = rhs[0] / beta
for i in range(1, n):
beta = -2.0 - c[i - 1]
c[i] = 1.0 / beta
d[i] = (rhs[i] - d[i - 1]) / beta
x = [0.0] * n
x[n - 1] = d[n - 1]
for i in range(n - 2, -1, -1):
x[i] = d[i] - c[i] * x[i + 1]
return x
def r_inverse(n):
"""R^-1 = A^-1 A^-1 as a dense n x n list of rows (A is symmetric)."""
cols = []
for j in range(n):
e = [0.0] * n
e[j] = 1.0
cols.append(solve_second_difference(solve_second_difference(e)))
return [[cols[j][i] for j in range(n)] for i in range(n)]
def smoothing_matrix(n):
"""M: R^-1 with each column scaled so that its largest entry is 1/n."""
rinv = r_inverse(n)
m = [[0.0] * n for _ in range(n)]
for j in range(n):
top = max(rinv[i][j] for i in range(n))
for i in range(n):
m[i][j] = rinv[i][j] / (top * n)
return m
def sample_noise(rng, n, sigma):
"""One noise trajectory for both coordinates, each ~ N(0, sigma^2 R^-1)."""
cols = [solve_second_difference([sigma * rng.gauss(0.0, 1.0) for _ in range(n)]) for _ in range(2)]
return [[cols[0][t], cols[1][t]] for t in range(n)]
def weights(costs, lam):
"""exp(-S / lam), normalized; shifting by the minimum avoids overflow."""
lo = min(costs)
e = [math.exp(-(s - lo) / lam) for s in costs]
tot = sum(e)
return [v / tot for v in e]
def control_cost(theta, q0, q1, w):
pts = [list(q0)] + [list(p) for p in theta] + [list(q1)]
s = 0.0
for t in range(1, len(pts) - 1):
for d in range(2):
a = pts[t - 1][d] - 2.0 * pts[t][d] + pts[t + 1][d]
s += 0.5 * w * a * a
return s
def total_cost(theta, q0, q1, state_cost, w):
return sum(state_cost(p) for p in theta) + control_cost(theta, q0, q1, w)
def stomp(q0, q1, n, state_cost, k=20, lam=0.1, sigma=0.05, w=100.0, iters=100, seed=0, theta0=None):
"""Run STOMP. Returns (best theta, best Q, history of Q of the iterates)."""
rng = random.Random(seed)
m = smoothing_matrix(n)
theta = straight_line(q0, q1, n) if theta0 is None else [list(p) for p in theta0]
best, best_q = theta, total_cost(theta, q0, q1, state_cost, w)
hist = [best_q]
for _ in range(iters): # @line L1
noise, costs = [], []
for _ in range(k): # @line L2
eps = sample_noise(rng, n, sigma) # @line L3
noise.append(eps)
costs.append([state_cost([theta[t][0] + eps[t][0], theta[t][1] + eps[t][1]]) for t in range(n)]) # @line L4
avg = [[0.0, 0.0] for _ in range(n)]
for t in range(n): # @line L5
p = weights([costs[j][t] for j in range(k)], lam) # @line L6
for d in range(2):
avg[t][d] = sum(p[j] * noise[j][t][d] for j in range(k)) # @line L7
theta = [[theta[i][d] + sum(m[i][j] * avg[j][d] for j in range(n)) for d in range(2)] for i in range(n)] # @line L8
qv = total_cost(theta, q0, q1, state_cost, w)
hist.append(qv)
if qv < best_q: # @line L9
best, best_q = theta, qv
return best, best_q, hist # @line L10
def disc_hinge(discs, margin):
"""State cost: sum over discs of max(0, margin + r - |p - o|), no gradient used."""
def cost(p):
return sum(max(0.0, margin + r - math.hypot(p[0] - ox, p[1] - oy)) for ox, oy, r in discs)
return cost
def min_clearance(theta, discs):
return min(math.hypot(p[0] - ox, p[1] - oy) - r for p in theta for ox, oy, r in discs)
test_stomp.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stomp/. The authors are listed in prov/2F4S7V.jsonl.
import math
import random
import unittest
from stomp import (
disc_hinge,
min_clearance,
r_inverse,
sample_noise,
smoothing_matrix,
solve_second_difference,
stomp,
total_cost,
weights,
)
Q0, Q1 = [-1.0, 0.0], [1.0, 0.0]
DISC = (0.0, -0.15, 0.5)
class TestWorkedExample(unittest.TestCase):
def test_disc_below_the_line(self):
cost = disc_hinge([DISC], 0.1)
theta, best_q, hist = stomp(Q0, Q1, 19, cost, lam=0.05, sigma=0.02, w=10.0, iters=12, seed=2011)
self.assertAlmostEqual(hist[0], 3.0202, delta=1e-4)
self.assertAlmostEqual(best_q, 0.0075, delta=1e-4)
self.assertEqual(hist.index(min(hist)), 7)
self.assertGreater(min_clearance(theta, [DISC]), 0.1)
# The iterates do not decrease monotonically.
self.assertTrue(any(hist[i + 1] > hist[i] for i in range(len(hist) - 1)))
def test_cost_without_gradient(self):
# A step cost: 1 for each waypoint closer than 0.1 to the disc, else 0.
def step(p):
return 1.0 if math.hypot(p[0] - DISC[0], p[1] - DISC[1]) < DISC[2] + 0.1 else 0.0
theta, best_q, hist = stomp(Q0, Q1, 19, step, lam=0.05, sigma=0.02, w=10.0, iters=60, seed=7)
self.assertEqual(hist[0], 11.0)
self.assertLess(best_q, 0.01)
self.assertGreater(min_clearance(theta, [DISC]), 0.1)
class TestEdgeCases(unittest.TestCase):
def test_noise_covariance_is_r_inverse(self):
rng = random.Random(1)
n, sigma, count = 6, 1.0, 6000
rinv = r_inverse(n)
acc = [[0.0] * n for _ in range(n)]
for _ in range(count):
e = sample_noise(rng, n, sigma)
for i in range(n):
for j in range(n):
acc[i][j] += e[i][0] * e[j][0]
for i in range(n):
for j in range(n):
self.assertAlmostEqual(acc[i][j] / count, rinv[i][j], delta=0.08 * rinv[2][2])
def test_second_difference_solve(self):
rng = random.Random(4)
rhs = [rng.uniform(-1.0, 1.0) for _ in range(7)]
x = solve_second_difference(rhs)
for i in range(7):
v = -2.0 * x[i] + (x[i - 1] if i > 0 else 0.0) + (x[i + 1] if i < 6 else 0.0)
self.assertAlmostEqual(v, rhs[i], places=12)
def test_smoothing_matrix_columns(self):
n = 9
m = smoothing_matrix(n)
for j in range(n):
self.assertAlmostEqual(max(m[i][j] for i in range(n)), 1.0 / n, places=12)
self.assertTrue(all(m[i][j] > 0.0 for i in range(n)))
def test_weights(self):
s = [3.0, 1.0, 2.0, 1.5]
p = weights(s, 0.5)
self.assertAlmostEqual(sum(p), 1.0, places=12)
q = weights([v + 7.0 for v in s], 0.5)
for a, b in zip(p, q):
self.assertAlmostEqual(a, b, places=12)
self.assertEqual(max(range(4), key=lambda i: p[i]), 1)
sharp = weights(s, 1e-6)
self.assertAlmostEqual(sharp[1], 1.0, places=9)
flat = weights([2.0] * 4, 0.5)
self.assertTrue(all(abs(v - 0.25) < 1e-12 for v in flat))
def test_free_space_keeps_best(self):
# No obstacles: the straight line has cost 0 and stays the best.
theta, best_q, hist = stomp(Q0, Q1, 9, lambda p: 0.0, iters=5, seed=3)
self.assertLess(best_q, 1e-20)
self.assertEqual(best_q, hist[0])
self.assertGreater(max(hist), 1e-6) # the iterates themselves drift
class TestRandomized(unittest.TestCase):
def test_best_is_never_worse_than_start(self):
rng = random.Random(2011)
for _ in range(3):
discs = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.3, 0.3), rng.uniform(0.1, 0.3)) for _ in range(2)]
cost = disc_hinge(discs, 0.1)
theta, best_q, hist = stomp(Q0, Q1, 11, cost, k=10, iters=15, seed=rng.randrange(1000))
self.assertLessEqual(best_q, hist[0])
self.assertAlmostEqual(best_q, total_cost(theta, Q0, Q1, cost, 100.0), places=12)
self.assertEqual(best_q, min(hist))
if __name__ == "__main__":
unittest.main()
History
Mrinal Kalakrishnan, Sachin Chitta, Evangelos Theodorou, Peter Pastor and Stefan Schaal presented STOMP at ICRA 2011. It took the smoothness matrix and the idea of measuring steps in its norm from CHOMP, and the weighted averaging of sampled noise from the path integral approach to reinforcement learning developed by Theodorou, Buchli and Schaal. A STOMP planner was added to the MoveIt motion planning framework of ROS, where it is used next to CHOMP and sampling planners.
References
- Mrinal Kalakrishnan, Sachin Chitta, Evangelos Theodorou, Peter Pastor and Stefan Schaal, STOMP: Stochastic trajectory optimization for motion planning, IEEE International Conference on Robotics and Automation (ICRA), 2011, 4569-4574, the whole paper (the original method)
- Matt Zucker, Nathan Ratliff, Anca D. Dragan, Mihail Pivtoraiko, Matthew Klingensmith, Christopher M. Dellin, J. Andrew Bagnell and Siddhartha S. Srinivasa, CHOMP: Covariant Hamiltonian optimization for motion planning, The International Journal of Robotics Research 32(9-10), 2013, 1164-1193, Sections 3.4 and 3.5 (the finite-difference smoothness matrix and steps measured in its norm, which STOMP also uses)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2F4S7V Edit this page History Report an error Markdown