Algorithm Search⌘K

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 yy toward a goal gg: on its own, it always converges to gg, 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 xx 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 τ\tau, and toward a different goal or from a different start by changing gg or y0y_0. 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 (y,z,x)(y, z, x): the position yy, a scaled velocity z=τy˙z = \tau \dot y, and the phase xx. Given a start y0y_0, a goal gg, a time constant τ>0\tau > 0, gains αz,βz,αx>0\alpha_z, \beta_z, \alpha_x > 0, and weights w1,…,wNw_1, \dots, w_N,

τz˙=αz(βz(g−y)−z)+f(x),τy˙=z,τx˙=−αxx,\tau \dot z = \alpha_z\big(\beta_z (g - y) - z\big) + f(x), \qquad \tau \dot y = z, \qquad \tau \dot x = -\alpha_x x,

with y(0)=y0y(0) = y_0, z(0)=0z(0) = 0 and x(0)=1x(0) = 1. The first two equations are the transformation system, the third the canonical system. The forcing term is

f(x)=∑iψi(x) wi∑iψi(x)  x (g−y0),ψi(x)=exp⁡(−hi(x−ci)2),f(x) = \frac{\sum_{i} \psi_i(x)\, w_i}{\sum_i \psi_i(x)}\; x\, (g - y_0), \qquad \psi_i(x) = \exp\big(-h_i (x - c_i)^2\big),

with centers cic_i spread along the decay of xx and widths hih_i. The code uses N=20N = 20 basis functions with ci=e−αx(i−1)/(N−1)c_i = e^{-\alpha_x (i - 1)/(N - 1)}, hi=1/(ci+1−ci)2h_i = 1/(c_{i+1} - c_i)^2, αz=25\alpha_z = 25, βz=αz/4\beta_z = \alpha_z/4 and αx=4\alpha_x = 4. The choice βz=αz/4\beta_z = \alpha_z/4 makes the spring critically damped; the other values are tuning choices, common in the literature, not derived values.

  1. ROLLOUT(w, y0, g, τ, duration, dt)
  2. 1(y, z, x) ← (y0, 0, 1)
  3. 2ψi ← exp(-hi (x - ci)²) for each i
  4. 3f ← (Σ ψi wi / Σ ψi) · x · (g - y0)
  5. 4ż ← (αz (βz (g - y) - z) + f) / τ
  6. 5ẏ ← z / τ
  7. 6ẋ ← -αx x / τ
  8. 7repeat duration/dt times: advance (y, z, x) by one classical Runge-Kutta step of size dt, with derivatives from L2 to L6
  9. FIT(t, y, ẏ, ÿ of the demonstration, τ) ▷ g ← last y, y0 ← first y
  10. 8f_target ← τ² ÿ - αz (βz (g - y) - τ ẏ) at each sample, and x at each sample from x = exp(-αx t / τ)
  11. 9wi ← Σ ψ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 NN weights plus the parameters y0y_0, gg and τ\tau. 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 dt=0.001dt = 0.001 s gives a maximum error of 0.01270.0127 against the demonstration over [0,1][0, 1], and y(1)=0.99896y(1) = 0.99896. At t=3t = 3 s the state is (y,z,x)≈(0.999997, 1.25×10−5, 6.1×10−6)(y, z, x) \approx (0.999997,\ 1.25 \times 10^{-5},\ 6.1 \times 10^{-6}): the motion has settled at the goal. These are measurements with these settings, checked by the tests with the tolerance 0.030.03 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 NN weights, and it is defined by a differential equation, so it can react to a changed goal during the motion.
  • Plain spring-damper. With f=0f = 0, the DMP is a critically damped spring that converges to gg 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 x(t)=e−αxt/τx(t) = e^{-\alpha_x t/\tau}, so ∣f(x(t))∣≤Wx(t)∣g−y0∣|f(x(t))| \le W x(t) |g - y_0|, where WW is the largest ∣wi∣|w_i|, and the forcing term decays exponentially. The transformation system is a stable linear system driven by this decaying input: with βz=αz/4\beta_z = \alpha_z/4 both of its eigenvalues equal −αz/(2τ)-\alpha_z/(2\tau). A stable linear system with an input that tends to zero has a state that tends to its equilibrium (g,0)(g, 0), so y(t)→gy(t) \to g and z(t)→0z(t) \to 0 from every start, for any weights. In the terms of stability theory, the equilibrium (g,0,0)(g, 0, 0) 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 t=3t = 3 s for the demonstration, and for a new start and goal.

Time scaling (theorem). If (y,z,x)(t)(y, z, x)(t) solves the system with time constant 1, then (y,z,x)(t/τ)(y, z, x)(t/\tau) solves it with time constant τ\tau, because τ\tau divides every right-hand side. So changing τ\tau replays the same motion slower or faster, with the same shape. A discrete version also holds: RK4 with step τ dt\tau\, dt for time constant τ\tau gives the same samples as step dtdt for time constant 1. The tests check this for τ=2\tau = 2 and dt=0.002dt = 0.002, to 10−910^{-9}.

Goal scaling (theorem, and a known weakness). Because ff contains the factor g−y0g - y_0, moving the goal scales the forcing term in proportion to the amplitude of the motion, so the shape is stretched along the coordinate. If g=y0g = y_0, the forcing term vanishes and the motion is a rest. If g−y0g - y_0 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, ff is linear in the weights. Line L9 fits each weight by its own one-dimensional weighted regression, whose solution is unique whenever ∑ψis2>0\sum \psi_i s^2 > 0 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.

dynamic_movement_primitives.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DHD4FD/text.yaml