Algorithmcore
PD control with gravity compensation
Also called Takegaki-Arimoto controller.
Joint PD feedback plus a gravity model. With exact gravity, a rigid arm and positive definite gains, every set point is globally asymptotically stable.
- Time
- O(n) per_step
- Space
- O(n) extra
- Where
- n = the number of joints of a serial chain; the bounds are for one control step
- Model
- Real RAM
- Properties
- deterministicnot exactonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Morikazu Takegaki, Suguru Arimoto, 1981
PD control with gravity compensation is a set-point controller for a robot arm. It applies a spring and a damper on each joint error and adds the torque that holds the arm up against gravity. It needs only the gravity part of the dynamic model, not the inertia or the Coriolis terms, and with an exact gravity model, symmetric positive definite gains and a rigid arm, the arm comes to rest at the set point from every initial state. Takegaki and Arimoto proved this in 1981 with a Lyapunov function that is the kinetic energy of the arm plus the energy of the virtual springs. It is the simplest member of the family of passivity-based robot controllers.
In plain words
Imagine a spring and a shock absorber on each joint, pulling the joint toward its goal angle. Without help, gravity drags the arm down, so the arm stops where the spring force balances its weight, short of the goal. Now add, at every moment, exactly the torque that cancels gravity in the current pose. The arm then behaves as if it were weightless with springs on its joints. The springs store energy, the dampers remove it, and the arm can rest only where the springs are relaxed, which is the goal.
This works for a fixed goal. For a moving goal the arm lags behind, and a law such as computed-torque control is better.
The problem
The arm has joints with positions and obeys the manipulator equation
with no contact forces. Here is the symmetric positive definite inertia matrix, the Coriolis and centripetal torques and the gravity torque. A constant set point is given. The task is to choose the torque from the measured and so that and from every initial state.
The algorithm
The controller has a gravity model and gain matrices and , both symmetric positive definite. In practice they are diagonal.
PD-GRAVITY(q, q', q_d, K_p, K_d)- 1
e ← q_d - q - 2
τ ← K_p e - K_d q' + ĝ(q) ▷ spring, damper and gravity - 3
return τ
The damper acts on the joint speed , not on . For a constant set point both are the same up to the sign, because . Line L2 needs only , which is the inverse dynamics at the state with zero acceleration.
Example
Take the planar 2R arm with m and point masses of 1 kg at the link ends, in a vertical plane, with measured from the horizontal and m/s. Its gravity torque is N m. The arm starts at rest at , the set point is rad, and the gains are and .
At the start, line L1 gives . The spring part is N m, the damper part is zero, and N m, so line L2 gives N m.
The table shows where the arm comes to rest in a simulation with RK4, for three gravity models.
| gravity model in line L2 | rest pose (rad) | rest error (rad) |
|---|---|---|
| exact, | ||
| none, (plain PD) | ||
| second mass 1.5 kg, model 1 kg |
Without gravity compensation the first joint hardly moves: at rest , and the gravity torque at the shoulder, about 28.9 N m, needs an error of about 0.29 rad in a spring of 100 N m/rad. With a wrong gravity model, the rest error satisfies .
Correctness
The claim is: if , the gains are symmetric positive definite, and the smallest eigenvalue of is bounded below by a positive constant for all , then is a globally asymptotically stable equilibrium of the closed loop. The proof uses
which is positive definite and radially unbounded in . Along the closed loop, , because the term is zero (the skew symmetry of the arm dynamics). is zero only when , and the only solution that stays in that set is the set point, so the LaSalle invariance principle gives global asymptotic stability. The full proof is in the proof file.
Proof: PD control with gravity compensation makes the set point globally asymptotically stablefull
The arm obeys with . We assume:
- is symmetric, and there is a constant with for all and .
- , and are continuously differentiable, and satisfies for all , , where .
- The gravity model is exact: .
- and are symmetric positive definite, and is constant.
Assumption 2 holds for every factorization of the Coriolis and centripetal torques, because the quadratic form only sees the product , and for the Christoffel choice the matrix is skew-symmetric.
Closed loop. Lines L1 and L2 give with . The gravity terms cancel, and the state obeys
Because , the right side depends only on , so the closed loop is an autonomous system on with a continuously differentiable . Its equilibria have , so and , so . The only equilibrium is .
Lemma 1. The function is positive definite and radially unbounded, and along the closed loop.
Proof. Let be the smallest eigenvalue of . By assumption 1, , which is positive for and tends to infinity as . Also . For the derivative, is symmetric, so
We put in from the closed loop and :
The first and last terms cancel because is symmetric, and the middle terms give by assumption 2. So .
Theorem. Under assumptions 1 to 4, is a globally asymptotically stable equilibrium of the closed loop: every solution tends to , .
Proof. By Lemma 1, , so . The sublevel set is closed, and it is bounded because is radially unbounded. So is compact and positively invariant, and the solution exists for all .
Let . Because is positive definite, is the set of points of with . Let be a solution that stays in for all . Then for all , so and is constant. The closed loop then gives , so . The largest invariant set in is therefore . By the LaSalle invariance principle, every solution that starts in tends to . The initial state was arbitrary, so every solution tends to .
Lyapunov stability of follows from Lemma 1: is positive definite and . Together with the global attraction, is globally asymptotically stable.
Rest error with a wrong gravity model. If and the arm comes to rest at some , then , and the manipulator equation gives . Line L2 at rest gives . Hence . With no gravity model () this is . This relation assumes a rest point; it does not prove that one is reached.
Complexity
In the real-RAM model, with joints and diagonal gains, lines L1 and L2 take operations plus one call of the gravity model. The gravity torque of a serial chain is the output of the recursive Newton-Euler algorithm with zero joint speed and acceleration, which takes operations. So one control step takes time and extra memory. Full gain matrices raise the cost to .
Properties
- Global stability for set points. The result holds from every initial state, with no bound on the gains other than positive definiteness.
- Needs only gravity. The law does not use or , so errors in the inertial parameters do not move the rest pose. Only errors in do.
- Asymptotic, not exponential, by this proof. The Lyapunov function above has a negative semidefinite derivative, so the proof gives asymptotic stability. Local exponential convergence near the set point follows from the linearization, but the rate depends on the pose through .
- Passive structure. The closed loop is the arm with a virtual spring and a virtual damper. This is why the law stays stable when the arm touches a passive environment, a fact that impedance control builds on.
Variants and improvements
- Constant gravity term. Use in place of . This needs no online model, but global stability then needs large enough to dominate the change of over the workspace.
- PID control. An integral term removes the offset from an unknown constant gravity error. For a robot, the resulting stability is only local or semi-global, so the gains need care. See PID controller.
- Adaptive gravity compensation. Since is linear in a few parameters (see linearity in dynamic parameters), the parameters can be estimated online, which gives an adaptive set-point law.
- Tracking. For a moving set point, add feedforward or move to computed-torque control or the Slotine-Li controller, which keep the energy-based proof.
- Energy shaping. Line L2 shapes the potential energy of the arm into the spring energy and injects damping. IDA-PBC generalizes this idea to other mechanical systems.
When to use it
Use it for point-to-point motions and holding a pose, when the gravity model is good but the inertial model is poor or costly to compute. It is the default joint-level law of many torque-controlled arms, and the base of compliant behavior in contact. For fast trajectory tracking use a law with a full model, such as computed-torque control.
Pitfalls
- Conditions of the result. The global stability needs an exact gravity model, a rigid arm (no joint flexibility), and symmetric positive definite gains. A gravity error leaves a rest error with .
- Friction. Static joint friction stops the arm before the set point. The rest error is then the friction torque divided by the spring gain.
- Damping from noisy speeds. The damping term needs , which is often a numerical derivative of the joint angles. Filtering adds phase lag and can destabilize a high-gain loop.
- Not for tracking. With a moving goal, the law has no feedforward term, and the tracking error does not go to zero.
- Slow modes. The decay rate depends on the inertia seen at each joint. The same gains give a fast decay at the wrist and a slow one at the shoulder.
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/pd-control-with-gravity-compensation/. The authors are listed in prov/0ACG13.jsonl.
"""PD control with gravity compensation for a set point, with a planar 2R arm.
The arm obeys M(q) q'' + C(q, q') q' + g(q) = tau. The law is
tau = Kp (qd - q) - Kd q' + g_model(q). With an exact gravity model and
symmetric positive definite gains, the set point qd is globally
asymptotically stable. V = 1/2 q'^T M q' + 1/2 e^T Kp e is a Lyapunov
function with V' = -q'^T Kd q'.
Matrices are lists of rows and vectors are lists. Only the standard library.
"""
import math
GRAVITY = 9.81
class TwoLinkArm:
"""Planar 2R arm in a vertical plane, with point masses at the link ends.
q1 is measured from the horizontal x axis, q2 from link 1. Gravity acts
along -y. C is built from the Christoffel symbols.
"""
def __init__(self, m1=1.0, m2=1.0, l1=1.0, l2=1.0, grav=GRAVITY):
self.m1, self.m2, self.l1, self.l2, self.grav = m1, m2, l1, l2, grav
def mass(self, q):
m1, m2, l1, l2 = self.m1, self.m2, self.l1, self.l2
c2 = math.cos(q[1])
a = (m1 + m2) * l1 * l1 + m2 * l2 * l2 + 2.0 * m2 * l1 * l2 * c2
b = m2 * l2 * l2 + m2 * l1 * l2 * c2
return [[a, b], [b, m2 * l2 * l2]]
def coriolis(self, q, qd):
h = self.m2 * self.l1 * self.l2 * math.sin(q[1])
return [[-h * qd[1], -h * (qd[0] + qd[1])], [h * qd[0], 0.0]]
def gravity(self, q):
m1, m2, l1, l2, gr = self.m1, self.m2, self.l1, self.l2, self.grav
c1, c12 = math.cos(q[0]), math.cos(q[0] + q[1])
return [(m1 + m2) * gr * l1 * c1 + m2 * gr * l2 * c12, m2 * gr * l2 * c12]
def accel(self, q, qd, tau):
"""Solve M q'' = tau - C q' - g for q''."""
m = self.mass(q)
c = self.coriolis(q, qd)
g = self.gravity(q)
r = [tau[i] - c[i][0] * qd[0] - c[i][1] * qd[1] - g[i] for i in range(2)]
return solve2(m, r)
class NoGravity:
"""A gravity model that returns zero: plain PD control."""
def gravity(self, q):
return [0.0] * len(q)
def solve2(a, b):
"""Solve the 2 by 2 system a x = b by Cramer's rule."""
det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
if det == 0.0:
raise ValueError("singular 2 by 2 matrix")
return [(b[0] * a[1][1] - a[0][1] * b[1]) / det, (a[0][0] * b[1] - b[0] * a[1][0]) / det]
def pd_gravity(model, q, qd, q_des, kp, kd):
"""Return tau = Kp (q_des - q) - Kd q' + g_model(q).
kp and kd are lists of diagonal gains. model only needs gravity(q).
"""
n = len(q)
e = [q_des[i] - q[i] for i in range(n)] # @line L1
g = model.gravity(q) # @line L2
tau = [kp[i] * e[i] - kd[i] * qd[i] + g[i] for i in range(n)]
return tau # @line L3
def lyapunov(arm, q, qd, q_des, kp):
"""V = 1/2 q'^T M(q) q' + 1/2 e^T Kp e with diagonal Kp."""
m = arm.mass(q)
n = len(q)
kin = 0.5 * sum(qd[i] * m[i][j] * qd[j] for i in range(n) for j in range(n))
pot = 0.5 * sum(kp[i] * (q_des[i] - q[i]) ** 2 for i in range(n))
return kin + pot
def rk4_step(f, t, x, dt):
"""One classical Runge-Kutta step for x' = f(t, x)."""
k1 = f(t, x)
k2 = f(t + dt / 2, [x[i] + dt / 2 * k1[i] for i in range(len(x))])
k3 = f(t + dt / 2, [x[i] + dt / 2 * k2[i] for i in range(len(x))])
k4 = f(t + dt, [x[i] + dt * k3[i] for i in range(len(x))])
return [x[i] + dt / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(len(x))]
def simulate(arm, model, q_des, q0, qd0, kp, kd, dt, steps):
"""Simulate the closed loop with RK4. Return the list of (t, q, qd)."""
def f(t, x):
q, qd = x[:2], x[2:]
tau = pd_gravity(model, q, qd, q_des, kp, kd)
return qd + arm.accel(q, qd, tau)
x = list(q0) + list(qd0)
out = [(0.0, x[:2], x[2:])]
for k in range(steps):
x = rk4_step(f, k * dt, x, dt)
out.append(((k + 1) * dt, x[:2], x[2:]))
return out
test_pd_control_with_gravity_compensation.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pd-control-with-gravity-compensation/. The authors are listed in prov/0ACG13.jsonl.
import math
import random
from pd_control_with_gravity_compensation import (
NoGravity,
TwoLinkArm,
lyapunov,
pd_gravity,
rk4_step,
simulate,
)
KP = [100.0, 100.0]
KD = [20.0, 20.0]
def test_example_torque():
arm = TwoLinkArm()
tau = pd_gravity(arm, [0.0, 0.0], [0.0, 0.0], [0.3, 0.4], KP, KD)
assert abs(tau[0] - 59.43) < 1e-9
assert abs(tau[1] - 49.81) < 1e-9
def test_converges_from_random_states():
arm = TwoLinkArm()
rng = random.Random(11)
for _ in range(3):
goal = [rng.uniform(-2, 2), rng.uniform(-2, 2)]
q0 = [rng.uniform(-3, 3), rng.uniform(-3, 3)]
qd0 = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
_, q, qd = simulate(arm, arm, goal, q0, qd0, KP, KD, 4e-3, 2000)[-1]
assert max(abs(goal[i] - q[i]) for i in range(2)) < 1e-4
assert max(abs(v) for v in qd) < 1e-3
def test_lyapunov_function_never_increases():
arm = TwoLinkArm(m1=1.2, m2=0.8)
goal = [1.0, -0.5]
out = simulate(arm, arm, goal, [-1.0, 1.5], [2.0, -1.0], KP, KD, 2e-3, 2000)
vs = [lyapunov(arm, q, qd, goal, KP) for _, q, qd in out]
for k in range(len(vs) - 1):
assert vs[k + 1] <= vs[k] + 1e-9
assert vs[-1] < 1e-3 * vs[0]
def test_lyapunov_derivative_formula():
# V' = -q'^T Kd q' along the closed loop, checked by a central difference.
arm = TwoLinkArm(m1=0.7, m2=1.4, l1=0.8, l2=1.1)
goal = [0.2, 0.9]
rng = random.Random(5)
def f(t, x):
tau = pd_gravity(arm, x[:2], x[2:], goal, KP, KD)
return x[2:] + arm.accel(x[:2], x[2:], tau)
for _ in range(10):
x = [rng.uniform(-3, 3), rng.uniform(-3, 3), rng.uniform(-2, 2), rng.uniform(-2, 2)]
h = 1e-5
xp = rk4_step(f, 0.0, x, h)
xm = rk4_step(f, 0.0, x, -h)
dv = (lyapunov(arm, xp[:2], xp[2:], goal, KP) - lyapunov(arm, xm[:2], xm[2:], goal, KP)) / (2 * h)
want = -sum(KD[i] * x[2 + i] ** 2 for i in range(2))
assert abs(dv - want) < 1e-4 * (1 + abs(want))
def test_plain_pd_rests_where_spring_holds_gravity():
arm = TwoLinkArm()
goal = [0.3, 0.4]
_, q, qd = simulate(arm, NoGravity(), goal, [0.0, 0.0], [0.0, 0.0], KP, KD, 5e-3, 3600)[-1]
assert max(abs(v) for v in qd) < 1e-6
g = arm.gravity(q)
for i in range(2):
assert abs(KP[i] * (goal[i] - q[i]) - g[i]) < 1e-6
assert goal[0] - q[0] > 0.2
def test_wrong_gravity_model_offset():
arm = TwoLinkArm(m2=1.5)
model = TwoLinkArm(m2=1.0)
goal = [0.3, 0.4]
_, q, qd = simulate(arm, model, goal, [0.0, 0.0], [0.0, 0.0], KP, KD, 5e-3, 3600)[-1]
assert max(abs(v) for v in qd) < 1e-6
g, gh = arm.gravity(q), model.gravity(q)
for i in range(2):
assert abs(KP[i] * (goal[i] - q[i]) - (g[i] - gh[i])) < 1e-6
assert math.hypot(goal[0] - q[0], goal[1] - q[1]) > 1e-2
History
Takegaki and Arimoto published the result in 1981, in the Journal of Dynamic Systems, Measurement, and Control. They chose a Lyapunov function made of the kinetic energy of the arm and an artificial potential energy, and showed that a manipulator under PD feedback with gravity compensation reaches the set point. This energy view became the start of passivity-based robot control. The textbooks of Spong, Hutchinson and Vidyasagar and of Siciliano et al. present the result with LaSalle's invariance principle.
References
- M. Takegaki and S. Arimoto, A new feedback method for dynamic control of manipulators, Journal of Dynamic Systems, Measurement, and Control 103(2), 1981, pages 119 to 125
- Mark W. Spong, Seth Hutchinson and M. Vidyasagar, Robot Modeling and Control, second edition, Wiley, 2020, Chapter 9, Section 9.2 (PD control revisited)
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 11, Section 11.4.2 (motion control of a multi-joint robot)
- Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics, Modelling, Planning and Control, Springer, 2009, Chapter 8 (motion control, centralized control)
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 0ACG13 Edit this page History Report an error Markdown