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
- Model
- Real RAM
- Properties
- deterministicexactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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, , where each state drives the next one and the input enters last. Step treats as a virtual input, chooses a desired value for it, and adds the square of the error to the Lyapunov function. After steps the real input appears, and the result is a feedback with a control Lyapunov function whose derivative is . 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
with , a scalar input , smooth , and for every . 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 .
Output. A smooth feedback with , and new coordinates , such that is positive definite and proper and
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
BACKSTEPPING(f, g, c, x)- 1
α_0 ← 0; z_0 ← 0; g_0 ← 0 - 2
for i ← 1 to n - 3
z_i ← x_i - α_{i-1}(x̄_{i-1}) - 4
D_i ← Σ_{j<i} ∂α_{i-1}/∂x_j · (f_j(x̄_j) + g_j(x̄_j) x_{j+1}) - 5
α_i ← (-c_i z_i - g_{i-1} z_{i-1} - f_i(x̄_i) + D_i) / g_i(x̄_i) - 6
return u = α_n, z = (z_1, ..., z_n)
Line L3 is the error between the state and the value that the previous step wanted for it. Line L4 is the time derivative of along the system, which can be computed from the state alone, because depends only on and their derivatives do not involve . Line L5 chooses the virtual input for so that the error obeys . The term cancels the cross term that step left in .
Each 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 at with , where , and reads from the coefficient of . Each step adds one level of nested dual numbers with its own tag.
Example
Take , , with . Here , , , . The term makes the open loop escape to infinity in finite time from with .
| line | step 1 | step 2 |
|---|---|---|
| L3 | ||
| L4 | ||
| L5 |
Expanded, the feedback is . In the new coordinates the closed loop is linear:
so and exactly. Start at , so , and . A 4th order Runge-Kutta simulation with step , with the feedback evaluated inside the right side, gives:
| 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 , differs from by at most , 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 negative.
Correctness
The full proof is in proofs/correctness.md. Its main steps:
- Each is smooth and zero at zero. By induction: line L5 divides smooth functions by , and at every term vanishes because .
- The error dynamics. The chain rule gives , because the derivatives of do not involve . With and line L5, .
- The cross terms cancel. In , the sums and are the same sum, so .
- Global result. is triangular with unit diagonal, so it has a smooth inverse. is positive definite and proper in , and . Lyapunov's direct method gives global asymptotic stability, and decays at least like .
- 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 exactly in Fraction for 36 random polynomial systems with (with computed by one more dual direction along the closed loop), the linear gain for the double integrator, that the triple integrator closed loop has the same characteristic polynomial as the error system, the simulation against and the rotation formula within , and a system with and 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:
where . The functions are smooth (), , and for every . The gains are positive. Put , and , and for define
These are lines L3, L4 and L5. The feedback is (line L6), and .
Termination
The algorithm defines once each. The implementation does this by a recursion on that stops at , so it ends after levels.
Lemma 1: each alpha_i is smooth, depends only on the first i states, and is zero at zero
By induction on . . Suppose the claim holds for . Then and are smooth functions of . uses the first partial derivatives of , which are smooth, and the terms for , which depend only on . and are smooth, and is smooth and never zero, so the quotient is smooth on . At : gives ; gives , so ; and . So .
Lemma 2: the error dynamics
Along every solution of the closed loop, for ,
with the convention .
Proof. By the chain rule, . For , , so this sum is . Hence .
For : , and by the definition of . So
For : , and the same computation without the term gives .
Lemma 3: the derivative of V
Along the closed loop, .
Proof. By Lemma 2,
The term of the first cross sum is absent because . Shift the index of the second cross sum by one: . The two cross sums cancel.
Lemma 4: the change of coordinates
The map is a smooth bijection of with a smooth inverse, and .
Proof. is smooth by Lemma 1. Given , the equations for determine , then , and so on, in a unique way. So is a bijection, and the inverse is a composition of smooth maps. by Lemma 1.
Theorem: global asymptotic stability
With , the origin of the closed loop is globally asymptotically stable, and with .
Proof. The closed loop is smooth by Lemma 1, so it is locally Lipschitz and solutions are unique (Picard-Lindelöf). is smooth. It is positive definite, because only if , that is, (Lemma 4). It is proper: the sublevel set is the image of the compact ball under the continuous map , so it is compact. By Lemma 3, , which is negative for . Every solution stays in the compact set , so it exists for all . Lyapunov's direct method gives global asymptotic stability. The comparison gives , which is the bound on .
Lemma 5: the dual numbers compute D_i exactly
Let be a commutative ring that contains the values of the state, and let with a new symbol . A value is stored as a dual number with a tag that is larger than every tag inside and . The operations of the class Dual are the ring operations of : , , and when is invertible. The functions , and use .
Claim. For every function built from these operations and a point and direction with entries in , evaluating at gives .
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 , and , the rule is the chain rule. These identities hold in any commutative ring , so they hold when itself contains dual numbers with smaller tags.
In the implementation, step evaluates at with a new tag, where for . By the claim, the coefficient of is , and the part without is . Every tag made inside the evaluation of 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 is line L5 as written. So the code returns and the errors exactly when the inputs are exact rationals and , are rational functions, and up to floating point rounding otherwise.
Complexity
Count real operations at unit cost, as in the real RAM. Let be the number of operations needed to evaluate all and once at a point.
- The recursion. Step evaluates step once, on numbers with one more level of dual parts. A number with levels has parts, and one product of such numbers costs products of plain numbers (the rule applied at each level). Step runs at levels and evaluates at most all the and , so the total is operations per evaluation of the feedback.
- Space. Each level keeps a state of numbers with up to parts, so in total.
- Simulation. A closed-loop RK4 simulation with steps evaluates the feedback times.
The exponential factor comes from the nested derivatives. A symbolic implementation computes once as a formula, but the formula grows fast with , because each step differentiates the previous virtual control and multiplies by the terms . This growth is known as the explosion of terms. For small (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 , 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. . In this gives local exponential stability, because is a diffeomorphism with .
- Not unique. Line L5 is one choice. Any that makes negative works, and good choices keep useful nonlinear terms (see the pitfalls).
Variants and improvements
- Avoiding cancellations. Line L5 cancels even when helps. For , the choice keeps the damping term and uses less input than (Krstić, Kanellakopoulos and Kokotović 1995, Section 2.4.3).
- Nonlinear damping. If has an unknown bounded term , adding to 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 through a first order filter and use the filter state and its derivative instead of . 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 is a vector and is an invertible matrix (block backstepping).
- Output feedback. When only 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 everywhere. If is small somewhere, is large there, and so are all later virtual controls and the input. If vanishes somewhere, the result is only local, on a region that avoids the zero set.
- Finite differences at line L4. Each differentiates , which already contains derivatives of . 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 in line L5 removes stabilizing nonlinearities too, and the input then grows like the cancelled term. In the example, contains because line L5 cancels the destabilizing ; for a helpful term such as the cancellation is a waste.
- Large inputs. The feedback is polynomial of high degree when the are. In the example, for a unit initial state, and grows like . 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 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.
# 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 , 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
- 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
- Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 14.3, Backstepping
- 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)
- 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
- 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.
| 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 W1XYZE Edit this page History Report an error Markdown