Modeladvanced
Dynamic movement primitives
Also called DMP.
A stable second-order attractor system plus a learned forcing term, which encodes a demonstrated motion and adapts it to new goals.
Dynamic movement primitives (DMPs) represent a motion, such as a reach or a stroke, as the solution of a small system of differential equations rather than as a list of points or a polynomial. The core is a damped spring that pulls the position toward a goal : on its own, it always converges to , smoothly and without overshoot. A learned forcing term pushes the spring along the shape of a demonstrated motion. The forcing term is driven by a phase variable that decays from 1 to 0, so it fades out and the spring alone finishes the motion at the goal. The weights of the forcing term are fitted to one demonstration by linear regression. After that, the same equations produce the motion again, faster or slower by changing one time constant , and toward a different goal or from a different start by changing or . Ijspeert, Nakanishi and Schaal (2002) introduced the model for imitation learning on humanoid robots; the 2013 paper of Ijspeert, Nakanishi, Hoffmann, Pastor and Schaal, which spells the name "dynamical movement primitives", is the standard reference. This page covers the discrete (point-to-point) DMP of one coordinate.
The machine
A discrete DMP for one coordinate has the state : the position , a scaled velocity , and the phase . Given a start , a goal , a time constant , gains , and weights ,
with , and . The first two equations are the transformation system, the third the canonical system. The forcing term is
with centers spread along the decay of and widths . The code uses basis functions with , , , and . The choice makes the spring critically damped; the other values are tuning choices, common in the literature, not derived values.
ROLLOUT(w, y0, g, τ, duration, dt)- 1
(y, z, x) ← (y0, 0, 1) - 2
ψi ← exp(-hi (x - ci)²) for each i - 3
f ← (Σ ψi wi / Σ ψi) · x · (g - y0) - 4
ż ← (αz (βz (g - y) - z) + f) / τ - 5
ẏ ← z / τ - 6
ẋ ← -αx x / τ - 7
repeat duration/dt times: advance (y, z, x) by one classical Runge-Kutta step of size dt, with derivatives from L2 to L6 FIT(t, y, ẏ, ÿ of the demonstration, τ) ▷ g ← last y, y0 ← first y- 8
f_target ← τ² ÿ - αz (βz (g - y) - τ ẏ) at each sample, and x at each sample from x = exp(-αx t / τ) - 9
wi ← Σ ψi(x) s f_target / Σ ψi(x) s², with s = x (g - y0)
Line L8 solves the transformation system for the forcing term that would reproduce the demonstration exactly. Line L9 fits each weight by locally weighted regression, a weighted least-squares problem with one unknown per basis function. Line L7 integrates the initial value problem with the classical fourth-order Runge-Kutta method.
What it counts
The model describes a motion by weights plus the parameters , and . It does not count time or cost; what matters is what the motion does when the parameters change.
A measured example. The demonstration is the minimum-jerk motion from 0 to 1 in 1 s, sampled every millisecond. After FIT with the values above, ROLLOUT with RK4 at s gives a maximum error of against the demonstration over , and . At s the state is : the motion has settled at the goal. These are measurements with these settings, checked by the tests with the tolerance on the error.
Relation to other models
- Polynomial trajectories. A minimum-jerk or quintic motion is fixed by its end states and duration. A DMP can encode any smooth demonstrated shape, at the cost of weights, and it is defined by a differential equation, so it can react to a changed goal during the motion.
- Plain spring-damper. With , the DMP is a critically damped spring that converges to with no overshoot; the tests check that this motion is monotone. The forcing term is what makes the motion take the demonstrated shape.
- Imitation learning. DMPs are a representation for imitation learning from one demonstration. Probabilistic movement primitives and Gaussian process models represent distributions over motions from many demonstrations instead.
- Rhythmic DMPs. Replacing the decaying phase by a phase oscillator and the basis functions by periodic ones gives a model of periodic motions (Ijspeert et al. 2013).
- Trajectory generation. A DMP gives positions, velocities and accelerations over time, like any method of the trajectory generation problem, but it does not enforce velocity or acceleration limits.
Known results in the model
Convergence to the goal (theorem). The phase is , so , where is the largest , and the forcing term decays exponentially. The transformation system is a stable linear system driven by this decaying input: with both of its eigenvalues equal . A stable linear system with an input that tends to zero has a state that tends to its equilibrium , so and from every start, for any weights. In the terms of stability theory, the equilibrium of the whole system is globally asymptotically stable. Ijspeert et al. (2013) discuss this property; for the unforced part, a quadratic Lyapunov function gives it directly. The tests check convergence at s for the demonstration, and for a new start and goal.
Time scaling (theorem). If solves the system with time constant 1, then solves it with time constant , because divides every right-hand side. So changing replays the same motion slower or faster, with the same shape. A discrete version also holds: RK4 with step for time constant gives the same samples as step for time constant 1. The tests check this for and , to .
Goal scaling (theorem, and a known weakness). Because contains the factor , moving the goal scales the forcing term in proportion to the amplitude of the motion, so the shape is stretched along the coordinate. If , the forcing term vanishes and the motion is a rest. If changes sign, the shape is mirrored. Ijspeert et al. (2013) discuss these effects and alternatives for the scaling factor.
Learning is linear (theorem). For a fixed phase, is linear in the weights. Line L9 fits each weight by its own one-dimensional weighted regression, whose solution is unique whenever on the data.
Other results. The 2013 paper treats coupling terms that add obstacle avoidance or contact forces, several coordinates sharing one phase, and online changes of the goal; these are beyond this page.
Code
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/dynamic-movement-primitives/. The authors are listed in prov/DHD4FD.jsonl.
"""Discrete dynamic movement primitive for one coordinate.
The system, in the form of Ijspeert, Nakanishi, Hoffmann, Pastor and Schaal (2013):
tau z' = alpha_z (beta_z (g - y) - z) + f(x)
tau y' = z
tau x' = -alpha_x x
f(x) = (sum_i psi_i(x) w_i / sum_i psi_i(x)) x (g - y0), psi_i(x) = exp(-h_i (x - c_i)^2)
fit() learns the weights w_i from one demonstration by locally weighted
regression. rollout() integrates the system with the classical Runge-Kutta
method. The gains alpha_z = 25, beta_z = alpha_z / 4 (critical damping) and
alpha_x = 4 are tuning choices, not derived values.
"""
import math
class DMP:
def __init__(self, n_basis=20, alpha_z=25.0, beta_z=None, alpha_x=4.0):
self.alpha_z = alpha_z
self.beta_z = alpha_z / 4 if beta_z is None else beta_z
self.alpha_x = alpha_x
# Centers spaced evenly in time, so geometrically in the phase x.
self.c = [math.exp(-alpha_x * i / (n_basis - 1)) for i in range(n_basis)]
self.h = [1.0 / (self.c[i + 1] - self.c[i]) ** 2 for i in range(n_basis - 1)]
self.h.append(self.h[-1])
self.w = [0.0] * n_basis
self.y0 = 0.0
self.g = 1.0
def forcing(self, x, y0, g):
psi = [math.exp(-h * (x - c) ** 2) for h, c in zip(self.h, self.c)] # @line L2
total = sum(psi)
if total == 0:
return 0.0
return sum(p * w for p, w in zip(psi, self.w)) / total * x * (g - y0) # @line L3
def fit(self, ts, ys, yds, ydds, tau):
"""Learn w from samples of a demonstration (time, position, velocity, acceleration)."""
self.y0, self.g = ys[0], ys[-1]
az, bz, ax = self.alpha_z, self.beta_z, self.alpha_x
xs = [math.exp(-ax * t / tau) for t in ts]
ft = [tau * tau * a - az * (bz * (self.g - y) - tau * v) for y, v, a in zip(ys, yds, ydds)] # @line L8
s = [x * (self.g - self.y0) for x in xs]
for i, (h, c) in enumerate(zip(self.h, self.c)):
gam = [math.exp(-h * (x - c) ** 2) for x in xs]
num = sum(si * gi * fi for si, gi, fi in zip(s, gam, ft))
den = sum(si * si * gi for si, gi in zip(s, gam))
self.w[i] = num / den if den > 0 else 0.0 # @line L9
def derivs(self, state, g, tau):
y, z, x = state
f = self.forcing(x, self.y0, g)
zd = (self.alpha_z * (self.beta_z * (g - y) - z) + f) / tau # @line L4
yd = z / tau # @line L5
xd = -self.alpha_x * x / tau # @line L6
return (yd, zd, xd)
def rollout(self, tau, duration, dt=0.001, y0=None, g=None):
"""Integrate from rest; return lists of times and positions. y0 and g may differ from the demo."""
if y0 is not None:
self.y0 = y0
g = self.g if g is None else g
state = (self.y0, 0.0, 1.0) # @line L1
ts, ys = [0.0], [state[0]]
n = int(round(duration / dt))
for k in range(n): # @line L7
k1 = self.derivs(state, g, tau)
k2 = self.derivs(tuple(s + dt / 2 * d for s, d in zip(state, k1)), g, tau)
k3 = self.derivs(tuple(s + dt / 2 * d for s, d in zip(state, k2)), g, tau)
k4 = self.derivs(tuple(s + dt * d for s, d in zip(state, k3)), g, tau)
state = tuple(s + dt / 6 * (a + 2 * b + 2 * c + d) for s, a, b, c, d in zip(state, k1, k2, k3, k4))
ts.append((k + 1) * dt)
ys.append(state[0])
self.last_state = state
return ts, ys
test_dynamic_movement_primitives.py 64 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-movement-primitives/. The authors are listed in prov/DHD4FD.jsonl.
"""Tests: the DMP reproduces a minimum-jerk demonstration, converges to the goal, and scales in time and goal."""
from dynamic_movement_primitives import DMP
def demo(y0, g, T, n=1001):
"""Samples of the minimum-jerk motion from y0 to g in time T."""
ts, ys, vs, accs = [], [], [], []
for k in range(n):
t = T * k / (n - 1)
u = t / T
d = g - y0
ts.append(t)
ys.append(y0 + d * u ** 3 * (10 - 15 * u + 6 * u * u))
vs.append(d * 30 * u * u * (1 - u) ** 2 / T)
accs.append(d * 60 * u * (1 - u) * (1 - 2 * u) / (T * T))
return ts, ys, vs, accs
def fitted():
dmp = DMP()
ts, ys, vs, accs = demo(0.0, 1.0, 1.0)
dmp.fit(ts, ys, vs, accs, tau=1.0)
return dmp, ys
def test_reproduces_demonstration():
dmp, ys = fitted()
_, out = dmp.rollout(tau=1.0, duration=1.0)
err = max(abs(a - b) for a, b in zip(out, ys))
assert err < 0.03 # measured: the fit with 20 basis functions is close, not exact
def test_converges_to_goal():
dmp, _ = fitted()
_, out = dmp.rollout(tau=1.0, duration=3.0)
y, z, x = dmp.last_state
assert abs(y - 1.0) < 1e-3 and abs(z) < 1e-2 and x < 1e-5
def test_new_goal_and_start_still_converge():
dmp, _ = fitted()
for y0, g in ((0.0, 2.0), (1.0, -0.5), (0.3, 0.3)):
_, out = dmp.rollout(tau=1.0, duration=3.0, y0=y0, g=g)
assert out[0] == y0
assert abs(out[-1] - g) < 1e-3 * max(1.0, abs(g - y0))
def test_without_forcing_term_is_critically_damped():
dmp = DMP()
_, out = dmp.rollout(tau=1.0, duration=2.0)
# No overshoot: the position rises monotonically toward the goal 1.
assert all(b >= a - 1e-12 for a, b in zip(out, out[1:]))
assert out[-1] <= 1.0 + 1e-12
def test_time_scaling():
dmp, _ = fitted()
_, fast = dmp.rollout(tau=1.0, duration=1.0, dt=0.001)
_, slow = dmp.rollout(tau=2.0, duration=2.0, dt=0.002)
# Doubling tau plays the same motion at half speed.
assert max(abs(a - b) for a, b in zip(fast, slow)) < 1e-9
References
- Auke Jan Ijspeert, Jun Nakanishi and Stefan Schaal, Movement imitation with nonlinear dynamical systems in humanoid robots, IEEE International Conference on Robotics and Automation, 2002, 1398-1403, the whole paper (the dynamical system with a learned nonlinear term, and learning it from a demonstration)
- Auke Jan Ijspeert, Jun Nakanishi, Heiko Hoffmann, Peter Pastor and Stefan Schaal, Dynamical movement primitives, learning attractor models for motor behaviors, Neural Computation 25(2), 2013, 328-373, the whole paper (the transformation and canonical systems, the forcing term, locally weighted regression, stability, and the invariance properties)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DHD4FD Edit this page History Report an error Markdown