Algorithm Search⌘K

Algorithmcore

Backstepping

Also called integrator backstepping.

Builds a Lyapunov function and a feedback step by step for a system in strict feedback form, treating each state as a virtual control.

Time
O(3^n q) worst
Space
O(n 2^n) extra
Where
n = the number of states; q = the number of arithmetic operations to evaluate all f_i and g_i once
Properties
deterministicexactonlinerecursive
Origin
Ioannis Kanellakopoulos, Petar V. Kokotović, A. Stephen Morse, Miroslav Krstić, 1991

Backstepping is a recursive design of a feedback and a Lyapunov function for a nonlinear system in strict feedback form, x˙i=fi(x1,…,xi)+gi(x1,…,xi) xi+1\dot x_i = f_i(x_1, \dots, x_i) + g_i(x_1, \dots, x_i)\, x_{i+1}, where each state drives the next one and the input enters last. Step ii treats xi+1x_{i+1} as a virtual input, chooses a desired value αi\alpha_i for it, and adds the square of the error xi+1−αix_{i+1} - \alpha_i to the Lyapunov function. After nn steps the real input appears, and the result is a feedback u=αn(x)u = \alpha_n(x) with a control Lyapunov function V=12∑zi2V = \frac12 \sum z_i^2 whose derivative is −∑cizi2-\sum c_i z_i^2. Unlike feedback linearization, it does not need to cancel every nonlinearity, and it gives the Lyapunov function as part of the result.

In plain words

Think of a chain of tanks, where the first tank is filled from the second, the second from the third, and you control only the last pump. You cannot set the first level directly. So you first decide what the second level should be to drive the first one to its target, as if you could choose it. Then you decide what the third level should be to drive the second one to that wish, and so on, back along the chain to the pump. At each step you also keep a score of how far each level is from its wish. The method chooses every wish so that the total score always goes down. When the score reaches zero, every level is at its target. The work is in the bookkeeping: each wish depends on how the earlier wishes change.

The problem

Input. A system in strict feedback form

x˙i=fi(xˉi)+gi(xˉi) xi+1(i=1,…,n−1),x˙n=fn(xˉn)+gn(xˉn) u,\dot x_i = f_i(\bar x_i) + g_i(\bar x_i)\, x_{i+1} \quad (i = 1, \dots, n - 1), \qquad \dot x_n = f_n(\bar x_n) + g_n(\bar x_n)\, u,

with xˉi=(x1,…,xi)\bar x_i = (x_1, \dots, x_i), a scalar input uu, smooth fi,gi:Ri→Rf_i, g_i : \mathbb{R}^i \to \mathbb{R}, fi(0)=0f_i(0) = 0 and gi(xˉi)≠0g_i(\bar x_i) \neq 0 for every xˉi\bar x_i. Smoothness makes the closed loop locally Lipschitz, so solutions exist and are unique (see the Lipschitz condition and the Picard-Lindelöf theorem). Also gains c1,…,cn>0c_1, \dots, c_n > 0.

Output. A smooth feedback u=αn(x)u = \alpha_n(x) with αn(0)=0\alpha_n(0) = 0, and new coordinates z=Φ(x)z = \Phi(x), such that V=12∣z∣2V = \frac12 |z|^2 is positive definite and proper and

V˙=−∑i=1ncizi2\dot V = -\sum_{i=1}^n c_i z_i^2

along the closed loop. Then the origin is globally asymptotically stable. This is a control-affine system with a special triangular structure; the structure is what makes the construction possible.

The algorithm

  1. BACKSTEPPING(f, g, c, x)
  2. 1α_0 ← 0; z_0 ← 0; g_0 ← 0
  3. 2for i ← 1 to n
  4. 3z_i ← x_i - α_{i-1}(x̄_{i-1})
  5. 4D_i ← Σ_{j<i} ∂α_{i-1}/∂x_j · (f_j(x̄_j) + g_j(x̄_j) x_{j+1})
  6. 5α_i ← (-c_i z_i - g_{i-1} z_{i-1} - f_i(x̄_i) + D_i) / g_i(x̄_i)
  7. 6return u = α_n, z = (z_1, ..., z_n)

Line L3 is the error between the state xix_i and the value αi−1\alpha_{i-1} that the previous step wanted for it. Line L4 is the time derivative of αi−1\alpha_{i-1} along the system, which can be computed from the state alone, because αi−1\alpha_{i-1} depends only on x1,…,xi−1x_1, \dots, x_{i-1} and their derivatives do not involve uu. Line L5 chooses the virtual input αi\alpha_i for xi+1x_{i+1} so that the error ziz_i obeys z˙i=−cizi−gi−1zi−1+gizi+1\dot z_i = -c_i z_i - g_{i-1} z_{i-1} + g_i z_{i+1}. The term −gi−1zi−1-g_{i-1} z_{i-1} cancels the cross term that step i−1i - 1 left in V˙\dot V.

Each αi\alpha_i is a function, and line L4 needs its partial derivatives. A symbolic implementation differentiates formulas. The implementation here evaluates the functions at a point and gets line L4 exactly by forward-mode automatic differentiation: it evaluates αi−1\alpha_{i-1} at x+εvx + \varepsilon v with ε2=0\varepsilon^2 = 0, where vj=fj+gjxj+1v_j = f_j + g_j x_{j+1}, and reads DiD_i from the coefficient of ε\varepsilon. Each step adds one level of nested dual numbers with its own tag.

Example

Take x˙1=x12+x2\dot x_1 = x_1^2 + x_2, x˙2=u\dot x_2 = u, with c1=c2=1c_1 = c_2 = 1. Here f1=x12f_1 = x_1^2, g1=1g_1 = 1, f2=0f_2 = 0, g2=1g_2 = 1. The term x12x_1^2 makes the open loop escape to infinity in finite time from x1(0)>0x_1(0) > 0 with x2=0x_2 = 0.

line step 1 step 2
L3 z1=x1z_1 = x_1 z2=x2+x1+x12z_2 = x_2 + x_1 + x_1^2
L4 D1=0D_1 = 0 D2=−(1+2x1)(x12+x2)D_2 = -(1 + 2 x_1)(x_1^2 + x_2)
L5 α1=−x1−x12\alpha_1 = -x_1 - x_1^2 α2=−z2−z1−(1+2x1)(x12+x2)\alpha_2 = -z_2 - z_1 - (1 + 2 x_1)(x_1^2 + x_2)

Expanded, the feedback is u=−2(x1+x2+x12+x13+x1x2)u = -2 (x_1 + x_2 + x_1^2 + x_1^3 + x_1 x_2). In the new coordinates the closed loop is linear:

z˙=[−11−1−1]z,\dot z = \begin{bmatrix} -1 & 1 \\ -1 & -1 \end{bmatrix} z,

so z(t)=e−t[cos⁡tsin⁡t−sin⁡tcos⁡t]z(0)z(t) = e^{-t} \begin{bmatrix} \cos t & \sin t \\ -\sin t & \cos t \end{bmatrix} z(0) and V(t)=V(0) e−2tV(t) = V(0)\, e^{-2t} exactly. Start at x(0)=(1,0)x(0) = (1, 0), so z(0)=(1,2)z(0) = (1, 2), V(0)=2.5V(0) = 2.5 and u(0)=−6u(0) = -6. A 4th order Runge-Kutta simulation with step 0.010.01, with the feedback evaluated inside the right side, gives:

tt x1=z1x_1 = z_1 x2x_2 z2z_2 uu VV
0 1 0 2 -6 2.5
0.5 1.11385 -1.58075 0.77378 -0.78996 0.91970
1 0.81789 -1.39885 0.08797 1.01803 0.33834
2 0.18980 -0.46152 -0.23570 0.63292 0.04579
3 -0.03524 -0.07161 -0.10560 0.20625 0.00620
4 -0.03969 0.02804 -0.01008 0.02252 0.00084
6 0.00099 0.00446 0.00545 -0.01091 0.00002

Over the 800 steps to t=8t = 8, VV differs from 2.5 e−2t2.5\, e^{-2t} by at most 1.7⋅10−91.7 \cdot 10^{-9}, which is the error of the integrator, and it decreases at every step. The first state rises at first, from 1 to about 1.11, because the input needs time to pull x2x_2 negative.

Correctness

The full proof is in proofs/correctness.md. Its main steps:

  • Each αi\alpha_i is smooth and zero at zero. By induction: line L5 divides smooth functions by gi≠0g_i \neq 0, and at x=0x = 0 every term vanishes because fj(0)=0f_j(0) = 0.
  • The error dynamics. The chain rule gives ddtαi−1=Di\frac{d}{dt} \alpha_{i-1} = D_i, because the derivatives of x1,…,xi−1x_1, \dots, x_{i-1} do not involve uu. With xi+1=zi+1+αix_{i+1} = z_{i+1} + \alpha_i and line L5, z˙i=−cizi−gi−1zi−1+gizi+1\dot z_i = -c_i z_i - g_{i-1} z_{i-1} + g_i z_{i+1}.
  • The cross terms cancel. In V˙=∑ziz˙i\dot V = \sum z_i \dot z_i, the sums ∑gizizi+1\sum g_i z_i z_{i+1} and −∑gi−1zi−1zi-\sum g_{i-1} z_{i-1} z_i are the same sum, so V˙=−∑cizi2\dot V = -\sum c_i z_i^2.
  • Global result. x↦zx \mapsto z is triangular with unit diagonal, so it has a smooth inverse. VV is positive definite and proper in xx, and V˙≤−2min⁡ici V\dot V \le -2 \min_i c_i\, V. Lyapunov's direct method gives global asymptotic stability, and zz decays at least like e−min⁡ici te^{-\min_i c_i\, t}.
  • The implementation. Forward-mode differentiation with dual numbers follows the sum, product, quotient and chain rules, so line L4 is exact with exact data.

The tests check the closed form of the example in exact rationals, the identity V˙=−∑cizi2\dot V = -\sum c_i z_i^2 exactly in Fraction for 36 random polynomial systems with n=1,2,3n = 1, 2, 3 (with V˙\dot V computed by one more dual direction along the closed loop), the linear gain u=−(1+c1c2)x1−(c1+c2)x2u = -(1 + c_1 c_2) x_1 - (c_1 + c_2) x_2 for the double integrator, that the triple integrator closed loop has the same characteristic polynomial as the error system, the simulation against V(0)e−2tV(0) e^{-2t} and the rotation formula within 10−810^{-8}, and a system with sin⁡\sin and cos⁡\cos terms.

Proof: Backstepping gives V' = -sum c_i z_i^2 along the closed loop, and the origin of a strict feedback system becomes globally asymptotically stablefull

The system is in strict feedback form:

x˙i=fi(xˉi)+gi(xˉi) xi+1(1≤i≤n−1),x˙n=fn(xˉn)+gn(xˉn) u,\dot x_i = f_i(\bar x_i) + g_i(\bar x_i)\, x_{i+1} \quad (1 \le i \le n - 1), \qquad \dot x_n = f_n(\bar x_n) + g_n(\bar x_n)\, u,

where xˉi=(x1,…,xi)\bar x_i = (x_1, \dots, x_i). The functions fi,gi:Ri→Rf_i, g_i : \mathbb{R}^i \to \mathbb{R} are smooth (C∞C^\infty), fi(0)=0f_i(0) = 0, and gi(xˉi)≠0g_i(\bar x_i) \neq 0 for every xˉi\bar x_i. The gains c1,…,cnc_1, \dots, c_n are positive. Put α0=0\alpha_0 = 0, z0=0z_0 = 0 and g0=0g_0 = 0, and for i=1,…,ni = 1, \dots, n define

zi=xi−αi−1(xˉi−1),Di=∑j=1i−1∂αi−1∂xj(fj+gjxj+1),αi=−cizi−gi−1zi−1−fi+Digi.z_i = x_i - \alpha_{i-1}(\bar x_{i-1}), \qquad D_i = \sum_{j=1}^{i-1} \frac{\partial \alpha_{i-1}}{\partial x_j} \bigl(f_j + g_j x_{j+1}\bigr), \qquad \alpha_i = \frac{-c_i z_i - g_{i-1} z_{i-1} - f_i + D_i}{g_i}.

These are lines L3, L4 and L5. The feedback is u=αn(x)u = \alpha_n(x) (line L6), and V=12∑i=1nzi2V = \frac12 \sum_{i=1}^n z_i^2.

Termination

The algorithm defines α1,…,αn\alpha_1, \dots, \alpha_n once each. The implementation does this by a recursion on ii that stops at i=0i = 0, so it ends after nn levels.

Lemma 1: each alpha_i is smooth, depends only on the first i states, and is zero at zero

By induction on ii. α0=0\alpha_0 = 0. Suppose the claim holds for αi−1\alpha_{i-1}. Then ziz_i and zi−1z_{i-1} are smooth functions of xˉi\bar x_i. DiD_i uses the first partial derivatives of αi−1\alpha_{i-1}, which are smooth, and the terms fj+gjxj+1f_j + g_j x_{j+1} for j≤i−1j \le i - 1, which depend only on xˉi\bar x_i. gi−1g_{i-1} and fif_i are smooth, and gig_i is smooth and never zero, so the quotient αi\alpha_i is smooth on Ri\mathbb{R}^i. At x=0x = 0: αi−1(0)=0\alpha_{i-1}(0) = 0 gives zi=zi−1=0z_i = z_{i-1} = 0; fj(0)=0f_j(0) = 0 gives fj+gjxj+1=0f_j + g_j x_{j+1} = 0, so Di=0D_i = 0; and fi(0)=0f_i(0) = 0. So αi(0)=0\alpha_i(0) = 0. □\square

Lemma 2: the error dynamics

Along every solution of the closed loop, for i=1,…,ni = 1, \dots, n,

z˙i=−cizi−gi−1zi−1+gizi+1,\dot z_i = -c_i z_i - g_{i-1} z_{i-1} + g_i z_{i+1},

with the convention gnzn+1=0g_n z_{n+1} = 0.

Proof. By the chain rule, ddtαi−1(xˉi−1)=∑j=1i−1∂αi−1∂xjx˙j\frac{d}{dt} \alpha_{i-1}(\bar x_{i-1}) = \sum_{j=1}^{i-1} \frac{\partial \alpha_{i-1}}{\partial x_j} \dot x_j. For j≤i−1≤n−1j \le i - 1 \le n - 1, x˙j=fj+gjxj+1\dot x_j = f_j + g_j x_{j+1}, so this sum is DiD_i. Hence z˙i=x˙i−Di\dot z_i = \dot x_i - D_i.

For i≤n−1i \le n - 1: x˙i=fi+gixi+1\dot x_i = f_i + g_i x_{i+1}, and xi+1=zi+1+αix_{i+1} = z_{i+1} + \alpha_i by the definition of zi+1z_{i+1}. So

z˙i=fi+giαi+gizi+1−Di=fi+(−cizi−gi−1zi−1−fi+Di)+gizi+1−Di=−cizi−gi−1zi−1+gizi+1.\dot z_i = f_i + g_i \alpha_i + g_i z_{i+1} - D_i = f_i + (-c_i z_i - g_{i-1} z_{i-1} - f_i + D_i) + g_i z_{i+1} - D_i = -c_i z_i - g_{i-1} z_{i-1} + g_i z_{i+1}.

For i=ni = n: x˙n=fn+gnu=fn+gnαn\dot x_n = f_n + g_n u = f_n + g_n \alpha_n, and the same computation without the term gnzn+1g_n z_{n+1} gives z˙n=−cnzn−gn−1zn−1\dot z_n = -c_n z_n - g_{n-1} z_{n-1}. □\square

Lemma 3: the derivative of V

Along the closed loop, V˙=−∑i=1ncizi2\dot V = -\sum_{i=1}^n c_i z_i^2.

Proof. By Lemma 2,

V˙=∑i=1nziz˙i=−∑i=1ncizi2−∑i=2ngi−1zi−1zi+∑i=1n−1gizizi+1.\dot V = \sum_{i=1}^n z_i \dot z_i = -\sum_{i=1}^n c_i z_i^2 - \sum_{i=2}^{n} g_{i-1} z_{i-1} z_i + \sum_{i=1}^{n-1} g_i z_i z_{i+1}.

The term i=1i = 1 of the first cross sum is absent because g0=0g_0 = 0. Shift the index of the second cross sum by one: ∑i=1n−1gizizi+1=∑i=2ngi−1zi−1zi\sum_{i=1}^{n-1} g_i z_i z_{i+1} = \sum_{i=2}^{n} g_{i-1} z_{i-1} z_i. The two cross sums cancel. □\square

Lemma 4: the change of coordinates

The map Φ:x↦z\Phi : x \mapsto z is a smooth bijection of Rn\mathbb{R}^n with a smooth inverse, and Φ(0)=0\Phi(0) = 0.

Proof. Φ\Phi is smooth by Lemma 1. Given zz, the equations xi=zi+αi−1(xˉi−1)x_i = z_i + \alpha_{i-1}(\bar x_{i-1}) for i=1,2,…,ni = 1, 2, \dots, n determine x1=z1x_1 = z_1, then x2x_2, and so on, in a unique way. So Φ\Phi is a bijection, and the inverse is a composition of smooth maps. Φ(0)=0\Phi(0) = 0 by Lemma 1. □\square

Theorem: global asymptotic stability

With u=αn(x)u = \alpha_n(x), the origin of the closed loop is globally asymptotically stable, and ∣z(t)∣≤e−c t∣z(0)∣|z(t)| \le e^{-c\, t} |z(0)| with c=min⁡icic = \min_i c_i.

Proof. The closed loop x˙=F(x)\dot x = F(x) is smooth by Lemma 1, so it is locally Lipschitz and solutions are unique (Picard-Lindelöf). V(x)=12∣Φ(x)∣2V(x) = \frac12 |\Phi(x)|^2 is smooth. It is positive definite, because V(x)=0V(x) = 0 only if Φ(x)=0\Phi(x) = 0, that is, x=0x = 0 (Lemma 4). It is proper: the sublevel set {V≤r}\{V \le r\} is the image of the compact ball {∣z∣2≤2r}\{|z|^2 \le 2 r\} under the continuous map Φ−1\Phi^{-1}, so it is compact. By Lemma 3, V˙≤−c∣z∣2=−2cV\dot V \le -c |z|^2 = -2 c V, which is negative for x≠0x \neq 0. Every solution stays in the compact set {V≤V(x(0))}\{V \le V(x(0))\}, so it exists for all t≥0t \ge 0. Lyapunov's direct method gives global asymptotic stability. The comparison V˙≤−2cV\dot V \le -2 c V gives V(t)≤e−2ctV(0)V(t) \le e^{-2 c t} V(0), which is the bound on ∣z(t)∣|z(t)|. □\square

Lemma 5: the dual numbers compute D_i exactly

Let RR be a commutative ring that contains the values of the state, and let R[ε]=R[e]/(e2)R[\varepsilon] = R[e]/(e^2) with a new symbol ε\varepsilon. A value a+bεa + b \varepsilon is stored as a dual number with a tag that is larger than every tag inside aa and bb. The operations of the class Dual are the ring operations of R[ε]R[\varepsilon]: (a+bε)+(c+dε)=(a+c)+(b+d)ε(a + b\varepsilon) + (c + d\varepsilon) = (a + c) + (b + d)\varepsilon, (a+bε)(c+dε)=ac+(ad+bc)ε(a + b\varepsilon)(c + d\varepsilon) = a c + (a d + b c)\varepsilon, and (a+bε)/(c+dε)=a/c+bc−adc2ε(a + b\varepsilon)/(c + d\varepsilon) = a/c + \frac{b c - a d}{c^2}\varepsilon when cc is invertible. The functions sin⁡\sin, cos⁡\cos and exp⁡\exp use h(a+bε)=h(a)+h′(a) b εh(a + b\varepsilon) = h(a) + h'(a)\, b\, \varepsilon.

Claim. For every function hh built from these operations and a point xx and direction vv with entries in RR, evaluating hh at x+εvx + \varepsilon v gives h(x)+(∇h(x)⋅v) εh(x) + (\nabla h(x) \cdot v)\, \varepsilon.

Proof. By induction on the expression. Constants and coordinates are clear. For a sum, a product and a quotient, the rules above are the sum, product and quotient rules of differentiation. For sin⁡\sin, cos⁡\cos and exp⁡\exp, the rule is the chain rule. These identities hold in any commutative ring RR, so they hold when RR itself contains dual numbers with smaller tags. □\square

In the implementation, step ii evaluates αi−1\alpha_{i-1} at x+εvx + \varepsilon v with a new tag, where vj=fj+gjxj+1v_j = f_j + g_j x_{j+1} for j<ij < i. By the claim, the coefficient of ε\varepsilon is ∇αi−1⋅v=Di\nabla \alpha_{i-1} \cdot v = D_i, and the part without ε\varepsilon is αi−1(x)\alpha_{i-1}(x). Every tag made inside the evaluation of αi−1\alpha_{i-1} is removed before it returns, so the result has no tag larger than the new one, and the split is unambiguous. The rest of step ii is line L5 as written. So the code returns αn(x)\alpha_n(x) and the errors ziz_i exactly when the inputs are exact rationals and fif_i, gig_i are rational functions, and up to floating point rounding otherwise. ■\blacksquare

Complexity

Count real operations at unit cost, as in the real RAM. Let qq be the number of operations needed to evaluate all fif_i and gig_i once at a point.

  • The recursion. Step ii evaluates step i−1i - 1 once, on numbers with one more level of dual parts. A number with dd levels has 2d2^d parts, and one product of such numbers costs 3d3^d products of plain numbers (the rule (a+bε)(c+dε)=ac+(ad+bc)ε(a + b\varepsilon)(c + d\varepsilon) = ac + (ad + bc)\varepsilon applied at each level). Step ii runs at n−in - i levels and evaluates at most all the fjf_j and gjg_j, so the total is ∑iO(3n−iq)=O(3nq)\sum_i O(3^{n-i} q) = O(3^n q) operations per evaluation of the feedback.
  • Space. Each level keeps a state of nn numbers with up to 2d2^d parts, so O(n2n)O(n 2^n) in total.
  • Simulation. A closed-loop RK4 simulation with NN steps evaluates the feedback 4N4 N times.

The exponential factor comes from the nested derivatives. A symbolic implementation computes αn\alpha_n once as a formula, but the formula grows fast with nn, because each step differentiates the previous virtual control and multiplies by the terms fj+gjxj+1f_j + g_j x_{j+1}. This growth is known as the explosion of terms. For small nn (the usual case is 2 to 4) either way is cheap.

Properties

  • Constructive. The output includes a Lyapunov function, not only a feedback, so the result can be combined with other Lyapunov-based tools: Sontag's formula applied to the same VV, input-to-state stability arguments or adaptation.
  • Global. Under the stated hypotheses, the result holds for every initial state, not only near an equilibrium.
  • Exponential in z. ∣z(t)∣≤e−min⁡ici t∣z(0)∣|z(t)| \le e^{-\min_i c_i\, t} |z(0)|. In xx this gives local exponential stability, because z=Φ(x)z = \Phi(x) is a diffeomorphism with Φ(0)=0\Phi(0) = 0.
  • Not unique. Line L5 is one choice. Any αi\alpha_i that makes V˙i\dot V_i negative works, and good choices keep useful nonlinear terms (see the pitfalls).

Variants and improvements

  • Avoiding cancellations. Line L5 cancels fif_i even when fif_i helps. For x˙1=−x13+x2\dot x_1 = -x_1^3 + x_2, the choice α1=−c1x1\alpha_1 = -c_1 x_1 keeps the damping term −x13-x_1^3 and uses less input than α1=−c1x1+x13\alpha_1 = -c_1 x_1 + x_1^3 (Krstić, Kanellakopoulos and Kokotović 1995, Section 2.4.3).
  • Nonlinear damping. If x˙i\dot x_i has an unknown bounded term φi(xˉi)Tδ(t)\varphi_i(\bar x_i)^T \delta(t), adding −κi∣φi∣2zi-\kappa_i |\varphi_i|^2 z_i to αi\alpha_i keeps the state bounded (Section 2.5.1 of the same book; Khalil 2002, Section 14.2.2).
  • Unknown constant parameters. Adaptive backstepping adds an update law for the parameters and tuning functions so that one update law serves all steps.
  • Avoiding the derivatives. Dynamic surface control and command-filtered backstepping pass each αi\alpha_i through a first order filter and use the filter state and its derivative instead of DiD_i. This removes the explosion of terms at the cost of an error that the analysis must bound.
  • Several inputs and block structure. The same steps work when each xix_i is a vector and gig_i is an invertible matrix (block backstepping).
  • Output feedback. When only x1x_1 is measured, an observer replaces the unmeasured states. The high-gain observer and observer backstepping are the usual routes.

When to use it

Use it when the system is in strict feedback form, or can be brought to it by a change of coordinates, and when you want a global result with a Lyapunov function, for example to add adaptation or to prove robustness. It suits mechanical and electromechanical systems where a force drives a velocity that drives a position. Prefer input-output linearization when the system is not triangular but has a well defined relative degree and stable zero dynamics. Prefer sliding mode control when the model has large matched uncertainty. When the input is limited, the global result does not survive saturation, and a design that takes the limit into account, such as model predictive control, is often better.

Pitfalls

  • Division by a small g_i at line L5. The design needs gi≠0g_i \neq 0 everywhere. If gig_i is small somewhere, αi\alpha_i is large there, and so are all later virtual controls and the input. If gig_i vanishes somewhere, the result is only local, on a region that avoids the zero set.
  • Finite differences at line L4. Each DiD_i differentiates αi−1\alpha_{i-1}, which already contains derivatives of αi−2\alpha_{i-2}. Difference quotients nest, and the rounding error grows by about the inverse of the step size at each level. Differentiate exactly, symbolically or with automatic differentiation as here.
  • Cancelling a useful term at line L5. The term −fi-f_i in line L5 removes stabilizing nonlinearities too, and the input then grows like the cancelled term. In the example, uu contains −2x13-2 x_1^3 because line L5 cancels the destabilizing x12x_1^2; for a helpful term such as −x13-x_1^3 the cancellation is a waste.
  • Large inputs. The feedback is polynomial of high degree when the fif_i are. In the example, u(0)=−6u(0) = -6 for a unit initial state, and uu grows like x13x_1^3. With input limits the global guarantee is lost.
  • Sampled implementation. The proof assumes that line L6 is evaluated continuously. With a computer, the input is held between samples, and V˙=−∑cizi2\dot V = -\sum c_i z_i^2 holds only approximately.

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.

backstepping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backstepping/. The authors are listed in prov/W1XYZE.jsonl.

"""Integrator backstepping for a system in strict feedback form

    x_i' = f_i(x_1, ..., x_i) + g_i(x_1, ..., x_i) x_(i+1),   i = 1, ..., n - 1,
    x_n' = f_n(x_1, ..., x_n) + g_n(x_1, ..., x_n) u,

with g_i != 0. Step i treats x_(i+1) as a virtual input and defines

    z_i     = x_i - alpha_(i-1)(x_1, ..., x_(i-1)),      alpha_0 = 0,
    D_i     = sum over j < i of (d alpha_(i-1) / d x_j) (f_j + g_j x_(j+1)),
    alpha_i = (-c_i z_i - g_(i-1) z_(i-1) - f_i + D_i) / g_i,

with z_0 = 0 and g_0 = 0. The feedback is u = alpha_n. Along the closed loop
z_i' = -c_i z_i - g_(i-1) z_(i-1) + g_i z_(i+1), so V = sum z_i^2 / 2 has
V' = -sum c_i z_i^2.

D_i is computed exactly by forward-mode differentiation: alpha_(i-1) is
evaluated at x + e v with a new infinitesimal e (e^2 = 0), where
v_j = f_j + g_j x_(j+1), and D_i is the coefficient of e. The numbers are
nested dual numbers with tags, so that the derivatives of different steps do
not mix. With Fraction inputs and rational f_i, g_i every value is exact.

Precondition: f and g are lists of n functions; f[i] and g[i] take the list
[x_1, ..., x_(i+1)] (0-based i) and use only +, -, *, / and integer powers,
or the functions sin, cos and exp of this module. c holds n positive gains.

Cost: step i evaluates step i - 1 once on dual numbers with one more level,
and a dual number with d levels has 2^d parts. One evaluation of the
feedback therefore costs O(2^n) evaluations of the f_i and g_i, up to a
factor n.
"""

import itertools
import math
from fractions import Fraction

__all__ = [
    "Dual",
    "new_tag",
    "sin",
    "cos",
    "exp",
    "real_part",
    "eps_part",
    "virtual_controls",
    "backstepping",
    "lyapunov",
    "closed_loop",
]

_TAGS = itertools.count(1)


def new_tag():
    """Return a tag larger than every tag handed out before."""
    return next(_TAGS)


def _tag(x):
    return x.tag if isinstance(x, Dual) else 0


def _div(p, q):
    # int / int would give a float; keep exact values exact.
    if isinstance(p, int) and isinstance(q, int):
        return Fraction(p, q)
    return p / q


def _split(x, t):
    if isinstance(x, Dual) and x.tag == t:
        return x.re, x.eps
    return x, 0


class Dual:
    """re + eps e with e^2 = 0. re and eps may be Duals with smaller tags."""

    __slots__ = ("tag", "re", "eps")

    def __init__(self, tag, re, eps):
        self.tag = tag
        self.re = re
        self.eps = eps

    def __add__(self, other):
        t = max(_tag(self), _tag(other))
        a, b = _split(self, t)
        c, d = _split(other, t)
        return Dual(t, a + c, b + d)

    __radd__ = __add__

    def __neg__(self):
        return Dual(self.tag, -self.re, -self.eps)

    def __pos__(self):
        return self

    def __sub__(self, other):
        return self + (-other)

    def __rsub__(self, other):
        return (-self) + other

    def __mul__(self, other):
        t = max(_tag(self), _tag(other))
        a, b = _split(self, t)
        c, d = _split(other, t)
        return Dual(t, a * c, a * d + b * c)

    __rmul__ = __mul__

    def __truediv__(self, other):
        t = max(_tag(self), _tag(other))
        a, b = _split(self, t)
        c, d = _split(other, t)
        return Dual(t, _div(a, c), _div(b * c - a * d, c * c))

    def __rtruediv__(self, other):
        t = self.tag
        a, b = _split(other, t)
        c, d = self.re, self.eps
        return Dual(t, _div(a, c), _div(b * c - a * d, c * c))

    def __pow__(self, k):
        if not isinstance(k, int) or k < 0:
            raise ValueError("only nonnegative integer powers")
        result = 1
        for _ in range(k):
            result = result * self
        return result


def sin(x):
    """sin that accepts Dual numbers."""
    if isinstance(x, Dual):
        return Dual(x.tag, sin(x.re), cos(x.re) * x.eps)
    return math.sin(x)


def cos(x):
    """cos that accepts Dual numbers."""
    if isinstance(x, Dual):
        return Dual(x.tag, cos(x.re), -sin(x.re) * x.eps)
    return math.cos(x)


def exp(x):
    """exp that accepts Dual numbers."""
    if isinstance(x, Dual):
        e = exp(x.re)
        return Dual(x.tag, e, e * x.eps)
    return math.exp(x)


def real_part(x, t):
    """The part of x without the infinitesimal of tag t."""
    return _split(x, t)[0]


def eps_part(x, t):
    """The coefficient of the infinitesimal of tag t in x."""
    return _split(x, t)[1]


def _alphas(f, g, c, i, x):
    """Return [alpha_0(x), ..., alpha_i(x)] as values at the point x."""
    if i == 0:
        return [0]  # @line L1
    t = new_tag()
    xd = list(x)
    for j in range(i - 1):
        v = f[j](x[:j + 1]) + g[j](x[:j + 1]) * x[j + 1]
        xd[j] = Dual(t, x[j], v)
    prev = _alphas(f, g, c, i - 1, xd)  # @line L2
    a = [real_part(p, t) for p in prev]
    z_i = x[i - 1] - a[i - 1]  # @line L3
    d_i = eps_part(prev[i - 1], t)  # @line L4
    if i >= 2:
        z_prev = x[i - 2] - a[i - 2]
        g_prev = g[i - 2](x[:i - 1])
    else:
        z_prev = 0  # @line L1
        g_prev = 0  # @line L1
    alpha_i = _div(-c[i - 1] * z_i - g_prev * z_prev - f[i - 1](x[:i]) + d_i, g[i - 1](x[:i]))  # @line L5
    return a + [alpha_i]


def virtual_controls(f, g, c, x):
    """Return [alpha_0(x), ..., alpha_n(x)], the virtual controls at x."""
    return _alphas(f, g, c, len(f), list(x))


def backstepping(f, g, c, x):
    """Return (u, z): the feedback u = alpha_n(x) and the errors z_1..z_n."""
    a = virtual_controls(f, g, c, x)
    z = [x[i] - a[i] for i in range(len(f))]
    return a[-1], z  # @line L6


def lyapunov(f, g, c, x):
    """Return V(x) = sum z_i^2 / 2."""
    _, z = backstepping(f, g, c, x)
    return _div(sum(zi * zi for zi in z), 2)


def closed_loop(f, g, c):
    """Return F(t, x, u) of the closed loop for the simulation helper.

    The feedback is evaluated inside the right side; u is ignored.
    """
    n = len(f)

    def F(t, x, u=None):
        uu, _ = backstepping(f, g, c, x)
        dx = [f[i](x[:i + 1]) + g[i](x[:i + 1]) * x[i + 1] for i in range(n - 1)]
        dx.append(f[n - 1](x) + g[n - 1](x) * uu)
        return dx
    return F
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
test_backstepping.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backstepping/. The authors are listed in prov/W1XYZE.jsonl.

import math
import random
from fractions import Fraction

import ctlsim
from backstepping import (
    Dual,
    backstepping,
    closed_loop,
    eps_part,
    lyapunov,
    new_tag,
    real_part,
    sin,
    virtual_controls,
)

# Simulations: classical RK4 (ctlsim), step DT = 0.01, feedback evaluated
# inside the right side. Tolerances are stated at each check.
DT = 0.01


def steps(T):
    n = round(T / DT)
    assert abs(n * DT - T) < 1e-12
    return n


def page_system():
    # x1' = x1^2 + x2, x2' = u, c = (1, 1).
    f = [lambda xb: xb[0] ** 2, lambda xb: 0]
    g = [lambda xb: 1, lambda xb: 1]
    return f, g, [1, 1]


def vdot_along_closed_loop(f, g, c, x):
    """V' at x along the closed loop, by one more dual direction (exact)."""
    F = closed_loop(f, g, c)
    v = F(0, x)
    t = new_tag()
    xd = [Dual(t, xi, vi) for xi, vi in zip(x, v)]
    _, z = backstepping(f, g, c, xd)
    zr = [real_part(zi, t) for zi in z]
    zd = [eps_part(zi, t) for zi in z]
    return sum(a * b for a, b in zip(zr, zd)), zr


def random_rational(rng, lo=-3, hi=3):
    return Fraction(rng.randint(lo * 12, hi * 12), rng.randint(1, 12))


def random_strict_feedback(rng, n):
    """Random polynomial f_i and g_i = k_i + x_1^2 with k_i > 0."""
    f, g = [], []
    for i in range(n):
        coef = [Fraction(rng.randint(-3, 3)) for _ in range(i + 1)]
        quad = [Fraction(rng.randint(-2, 2)) for _ in range(i + 1)]
        mix = Fraction(rng.randint(-2, 2))
        k = Fraction(rng.randint(1, 3))

        def fi(xb, coef=coef, quad=quad, mix=mix):
            s = 0
            for a, q, xj in zip(coef, quad, xb):
                s = s + a * xj + q * xj * xj
            return s + mix * xb[0] * xb[-1]

        def gi(xb, k=k):
            return k + xb[0] * xb[0]

        f.append(fi)
        g.append(gi)
    return f, g


def test_page_closed_form_exact():
    f, g, c = page_system()
    rng = random.Random(1)
    for _ in range(200):
        x1, x2 = random_rational(rng), random_rational(rng)
        u, z = backstepping(f, g, c, [x1, x2])
        expected = -(x2 + x1 + x1 ** 2) - x1 - (1 + 2 * x1) * (x1 ** 2 + x2)
        assert u == expected
        assert z == [x1, x2 + x1 + x1 ** 2]
        a = virtual_controls(f, g, c, [x1, x2])
        assert a[1] == -x1 - x1 ** 2


def test_lyapunov_derivative_identity_exact():
    # V' = -sum c_i z_i^2 exactly, for random strict feedback systems.
    rng = random.Random(2)
    for n in (1, 2, 3):
        for _ in range(12):
            f, g = random_strict_feedback(rng, n)
            c = [Fraction(rng.randint(1, 4), rng.randint(1, 2)) for _ in range(n)]
            for _ in range(3):
                x = [random_rational(rng, -2, 2) for _ in range(n)]
                vdot, z = vdot_along_closed_loop(f, g, c, x)
                assert vdot == -sum(ci * zi * zi for ci, zi in zip(c, z))


def test_linear_chain_gain():
    # x1' = x2, x2' = u: u = -(1 + c1 c2) x1 - (c1 + c2) x2.
    f = [lambda xb: 0, lambda xb: 0]
    g = [lambda xb: 1, lambda xb: 1]
    rng = random.Random(4)
    for _ in range(50):
        c1, c2 = Fraction(rng.randint(1, 9), 3), Fraction(rng.randint(1, 9), 3)
        x = [random_rational(rng), random_rational(rng)]
        u, _ = backstepping(f, g, [c1, c2], x)
        assert u == -(1 + c1 * c2) * x[0] - (c1 + c2) * x[1]


def charpoly3(M):
    tr = M[0][0] + M[1][1] + M[2][2]
    minors = sum(M[i][i] * M[j][j] - M[i][j] * M[j][i] for i, j in ((0, 1), (0, 2), (1, 2)))
    det = (M[0][0] * (M[1][1] * M[2][2] - M[1][2] * M[2][1])
           - M[0][1] * (M[1][0] * M[2][2] - M[1][2] * M[2][0])
           + M[0][2] * (M[1][0] * M[2][1] - M[1][1] * M[2][0]))
    return [1, -tr, minors, -det]


def test_triple_integrator_poles_match_error_system():
    # For a chain of 3 integrators the closed loop is x' = (A - B K) x, which
    # is similar to the error system z' = M z (g_i = 1).
    f = [lambda xb: 0] * 3
    g = [lambda xb: 1] * 3
    c = [Fraction(1), Fraction(2), Fraction(3)]
    K = [-backstepping(f, g, c, [Fraction(int(i == j)) for j in range(3)])[0] for i in range(3)]
    Acl = [[0, 1, 0], [0, 0, 1], [-K[0], -K[1], -K[2]]]
    M = [[-c[0], 1, 0], [-1, -c[1], 1], [0, -1, -c[2]]]
    assert charpoly3(Acl) == charpoly3(M)


def test_simulation_page_example():
    # z' = [[-1, 1], [-1, -1]] z, so V(t) = V(0) exp(-2 t) and
    # z(t) = exp(-t) [[cos t, sin t], [-sin t, cos t]] z(0).
    f, g, c = page_system()
    ts, xs, _ = ctlsim.simulate(closed_loop(f, g, c), [1.0, 0.0], 0.0, 8.0, DT)
    assert len(xs) == steps(8.0) + 1
    vs = [lyapunov(f, g, c, x) for x in xs]
    assert all(vs[i + 1] < vs[i] for i in range(len(vs) - 1))
    for t, x, v in zip(ts, xs, vs):
        assert abs(v - 2.5 * math.exp(-2 * t)) < 1e-8
        _, z = backstepping(f, g, c, x)
        e = math.exp(-t)
        assert abs(z[0] - e * (math.cos(t) + 2 * math.sin(t))) < 1e-8
        assert abs(z[1] - e * (-math.sin(t) + 2 * math.cos(t))) < 1e-8
    table = {1.0: (0.81789, -1.39885, 1.01803), 2.0: (0.18980, -0.46152, 0.63292)}
    for T, (x1, x2, u) in table.items():
        x = xs[steps(T)]
        assert abs(x[0] - x1) < 1e-5 and abs(x[1] - x2) < 1e-5
        assert abs(backstepping(f, g, c, x)[0] - u) < 1e-5
    assert math.hypot(*xs[-1]) < 2e-3


def test_three_states_with_sine_simulation():
    # x1' = sin(x1) + x2, x2' = x1 x2 + (2 + cos x1) x3, x3' = x2^2 + u.
    from backstepping import cos
    f = [lambda xb: sin(xb[0]), lambda xb: xb[0] * xb[1], lambda xb: xb[1] * xb[1]]
    g = [lambda xb: 1, lambda xb: 2 + cos(xb[0]), lambda xb: 1]
    c = [1.0, 1.0, 1.0]
    rng = random.Random(9)
    for _ in range(20):
        x = [rng.uniform(-1, 1) for _ in range(3)]
        vdot, z = vdot_along_closed_loop(f, g, c, x)
        target = -sum(zi * zi for zi in z)
        assert abs(vdot - target) < 1e-9 * (1 + abs(target))
    ts, xs, _ = ctlsim.simulate(closed_loop(f, g, c), [0.5, -0.5, 0.2], 0.0, 12.0, 0.02)
    vs = [lyapunov(f, g, c, x) for x in xs]
    assert all(vs[i + 1] <= vs[i] for i in range(len(vs) - 1))
    assert max(abs(v) for v in xs[-1]) < 1e-3

History

The step that adds one integrator to a system with a known stabilizing feedback and Lyapunov function, with the new function V+12(xn+1−α(x))2V + \frac12 (x_{n+1} - \alpha(x))^2, appears in the nonlinear stabilization literature of the late 1980s; Sontag's book states it as a lemma (Section 5.9). Kanellakopoulos, Kokotović and Morse (1991) turned the repeated use of this step into a systematic procedure for systems in strict feedback form with unknown parameters. Kokotović's 1991 Bode Prize Lecture, published in 1992 as "The joy of feedback", explained the procedure and its name, and the 1995 book of Krstić, Kanellakopoulos and Kokotović gave the full theory, including tuning functions and the methods that avoid useless cancellations.

References

  1. Miroslav Krstić, Ioannis Kanellakopoulos and Petar Kokotović, Nonlinear and Adaptive Control Design, Wiley, 1995, Section 2.2 (Backstepping) with 2.2.1 Integrator backstepping; Section 2.3.1 Strict-feedback systems; Section 2.4.3 Avoiding cancellations; Section 2.5.1 Nonlinear damping
  2. Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 14.3, Backstepping
  3. Eduardo D. Sontag, Mathematical Control Theory, second edition, Springer, 1998, Section 5.9, Lemma 5.9.5 (adding an integrator to a stabilizable system, with W = V + |z - k(x)|^2 / 2)
  4. Petar V. Kokotović, The joy of feedback: nonlinear and adaptive, IEEE Control Systems Magazine 12(3), 7-17, 1992, the 1991 Bode Prize Lecture; the backstepping procedure and its adaptive form
  5. Systematic design of adaptive controllers for feedback linearizable systems, the recursive design for systems in parametric strict feedback form

Where this leads

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example