Algorithmadvanced
Adaptive backstepping
Also called adaptive integrator backstepping.
Backstepping with unknown parameters, with tuning functions that give one adaptation law for all steps.
- Time
- O((3(n + p))^n (q + n p + p^2)) worst
- Space
- O((n^2 + n p) 2^n) extra
- Where
- n = the number of states; p = the number of unknown parameters; q = the number of arithmetic operations to evaluate all phi_i and beta once
- Model
- Real RAM
- Properties
- deterministicexactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Miroslav Krstić, Ioannis Kanellakopoulos, Petar V. Kokotović, A. Stephen Morse, 1992
Adaptive backstepping is a recursive design of a feedback and a parameter update law for a nonlinear system in parametric strict feedback form, , where is a constant vector of unknown parameters. It follows the steps of backstepping, with an estimate in place of . The difficulty is that each virtual control depends on , so its time derivative contains , which is not known until the last step. The tuning functions design collects one term per step and uses the final in one update law . The result is one estimate per parameter and a Lyapunov function with . The state goes to zero for every initial state, but the estimate need not reach .
In plain words
Backstepping works back along a chain of states and chooses, step by step, what each state should be. Here some numbers in the model are unknown. The controller uses a guess for them and corrects the guess while it runs. Each step depends on the guess, so each step must know how fast the guess changes. That speed is known only at the end, because every step contributes to it. The tuning functions are the parts that each step adds to that speed, and the method plans for the final speed from the start. One correction law then serves all steps. A score made of the tracking errors and the guess error never goes up. So the state goes to zero. The guess stays bounded, but it can settle at a wrong value, because the controller only needs a guess that works.
The problem
Input. A system in parametric strict feedback form
with , a scalar input , an unknown constant , smooth known with , and a smooth known with everywhere. The closed loop is then locally Lipschitz, so solutions exist and are unique (see the Lipschitz condition and the Picard-Lindelöf theorem). Also gains and an adaptation gain , a symmetric positive definite matrix.
Output. A feedback and an update law , with error coordinates , such that
satisfies along the closed loop. Then all signals are bounded and for every and . This is a statement about regulation, not about the equilibrium , which is in general not asymptotically stable.
The algorithm
ADAPTIVE-BACKSTEPPING(φ, β, c, Γ, x, θ̂)- 1
α_0 ← 0; z_0 ← 0; τ_0 ← 0 - 2
for i ← 1 to n - 3
z_i ← x_i - α_{i-1}(x̄_{i-1}, θ̂) - 4
w_i ← φ_i(x̄_i) - Σ_{k<i} ∂α_{i-1}/∂x_k · φ_k(x̄_k) - 5
τ_i ← τ_{i-1} + w_i z_i - 6
α_i ← -z_{i-1} - c_i z_i - w_iᵀθ̂ + Σ_{k<i} ∂α_{i-1}/∂x_k · x_{k+1} + ∂α_{i-1}/∂θ̂ · Γ τ_i + Σ_{k=2}^{i-1} z_k · ∂α_{k-1}/∂θ̂ · Γ w_i - 7
return u = α_n / β(x), θ̂' = Γ τ_n, z = (z_1, ..., z_n)
Line L3 is the error between and the value that the previous step wanted for it. Line L4 is the regressor of : the unknown part of is , because enters through and through the time derivative of . Line L5 is the tuning function. It is the update law that would be right if the design stopped at step . Line L6 has four parts:
- The terms are those of backstepping.
- is the certainty equivalence term: it cancels with the estimate in place of .
- The sum over is the known part of the time derivative of .
- The two terms with handle the derivative of with respect to the estimate. The first uses as a stand-in for the final . The second makes the error of this stand-in skew-symmetric, so that it cancels in . This second sum is empty when .
Line L7 divides by and gives the update law.
The partial derivatives in lines L4 and L6 are of functions, not of numbers. The implementation evaluates every function at a point and gets the partial derivatives exactly by forward-mode automatic differentiation. Step evaluates step once more for each of the variables , with that variable replaced by or , , and reads each partial derivative from the coefficient of . Each step adds one level of nested dual numbers with its own tag.
Example
Take , , with true , unknown to the controller, so , , , , . Use and . With known, this is the example of backstepping.
| line | step 1 | step 2 |
|---|---|---|
| L3 | ||
| L4 | ||
| L5 | ||
| L6 |
So and . Start at and . Then , , , and . A 4th order Runge-Kutta simulation of the state with step , with the controller evaluated inside the right side, gives:
| 0 | 1 | 0 | 0 | 1 | -4 | 1.5 |
| 0.5 | 0.92282 | -2.22663 | 1.64547 | 0.09745 | 1.35718 | 0.63886 |
| 1 | 0.32603 | -0.98258 | 1.64337 | -0.48186 | 1.83703 | 0.37621 |
| 2 | -0.09364 | -0.11940 | 1.63368 | -0.19871 | 0.36530 | 0.22490 |
| 3 | -0.08494 | 0.06198 | 1.63190 | -0.01118 | 0.04281 | 0.20332 |
| 4 | -0.02153 | 0.04477 | 1.63173 | 0.02400 | -0.04481 | 0.20006 |
| 6 | 0.00415 | -0.00287 | 1.63173 | 0.00130 | -0.00257 | 0.19955 |
| 10 | -0.00007 | 0.00011 | 1.63173 | 0.00004 | -0.00008 | 0.19954 |
decreases at every one of the 1000 steps (measurement). The state goes to zero, but the estimate settles at about , not at . The limit of is , all of it from the parameter error. Once is near zero, and the estimate stops moving, because a state at rest carries no information about .
Correctness
The full proof is in proofs/correctness.md. Its main steps:
- Smoothness. By induction, each is a smooth function of with , because .
- The error dynamics. The time derivative of contains . Line L6 used , and the difference is . This gives with and .
- Cancellation. In , the terms cancel as in backstepping, and the terms cancel because the last sum of line L6 is the mirror image of the error of using . What remains is . The update law gives . So .
- Regulation. is nonincreasing, so and are bounded, and so is (it is a continuous function of and ). Then is bounded and , so Barbalat's lemma gives , and then .
- The implementation. Dual numbers follow the sum, product and quotient rules, so lines L4 and L6 are exact with exact data.
The tests check the values at , (, , ), the closed form of the example at 20 random rational points with random gains, the case with and a non-diagonal , and the identity exactly in Fraction for 24 random polynomial systems with and , a non-diagonal and . There, is computed with one more dual direction along the closed-loop vector field, so the check does not use the error equations of the proof. A simulation test checks that is nonincreasing, that is within of zero, the limit of , and one row of the table.
Proof: Adaptive backstepping with tuning functions gives V' = -sum c_i z_i^2, bounded signals and regulation of the state to zerofull
The system is in parametric strict feedback form:
where , is constant and unknown, the maps and are smooth (), for every , and . The gains are positive and is a symmetric positive definite matrix. The estimate is and the error is .
Put , , (line L1). For (line L2) define, as functions of ,
These are lines L3 to L6. Here is a row vector. The controller is and the update law is (line L7). Let
Termination
The algorithm defines once each. The implementation does this by a recursion on that stops at . Each call at level makes calls at level and no other recursive calls, so the recursion tree is finite and the computation ends.
Lemma 1: each alpha_i is smooth and vanishes at x = 0
Each is a smooth function of , and for every . Also , and are smooth, and they vanish at .
Proof. By induction on . For all four are zero. Suppose the claim holds for . Then , , and are built from smooth functions by sums, products and first partial derivatives of the smooth , , so they are smooth. At : ; because every ; ; and every term of is zero: , , , , and again.
Lemma 2: the error dynamics
Along every solution of the closed loop, for , with ,
Proof. By the chain rule and the equations of the system for ,
For , . For , , which is the same with . So
where the terms with were collected with the definition of . Put in . The sum over cancels, , and
because by line L5. The last sum of is . This is the claim.
Lemma 3: the derivative of V
Along the closed loop, .
Proof. Multiply Lemma 2 by and add over .
- The terms and give , because .
- Note that , because . The terms with give . Rename to in the second sum: it is the first sum with the opposite sign, so they cancel. This is the reason for the last sum in line L6.
- The terms with give .
So . Since is constant, , and the derivative of the second part of is , with symmetric. The two terms with cancel.
Lemma 4: the change of coordinates
For each fixed , the map is a bijection of , and is a continuous function of with when .
Proof. Given , the equations for give , then , and so on, in a unique way, and each step is continuous. If , then , and by Lemma 1 every later .
Theorem: boundedness and regulation
For every initial state and estimate , the solution of the closed loop exists for all , and are bounded, is nonincreasing, and as .
Proof. The closed loop in is smooth by Lemma 1 and because , so it is locally Lipschitz and solutions are unique on their maximal interval (Picard-Lindelöf). On this interval is nonincreasing by Lemma 3, so and . The second bound and bound . Then stays in a compact set , and , a continuous function of by Lemma 4, stays in the compact image of . A solution that stays in a compact set cannot have a finite escape time, so .
The right side of the closed loop is continuous, so it is bounded on this compact set, and so is , which is a continuous function of by Lemma 2. So is uniformly continuous. Integrating Lemma 3, . By Barbalat's lemma, .
Last, . The map of Lemma 4 is uniformly continuous on and is zero on . Given , there is such that implies on . Since , for all large .
The theorem does not say that . The proof only gives that is bounded.
Lemma 5: the implementation computes the partial derivatives exactly
The implementation evaluates step at with one coordinate replaced by or , where and the tag of is new. By the dual number lemma of the backstepping proof (sum, product, quotient and power rules hold in for any commutative ring , so also when holds dual numbers with smaller tags), the coefficient of in each returned , , is or at the point. Every tag made inside the call is removed before the call returns, so the split by the new tag is unambiguous. The rest of step is lines L3 to L6 as written, and line L7 divides by and multiplies by . So the code returns , and 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 to evaluate all and once.
- The recursion tree. A call of step calls step once with plain inputs and times with one new dual direction. So step is called at most times.
- The cost of a call. A call of step works on numbers with at most levels of dual parts, and one product at levels costs plain products. Without its recursive calls, it does operations on such numbers.
- Total. per evaluation of the controller.
- Space. The recursion is calls deep, and the call of step keeps numbers with parts, so in total.
The bound is exponential in , like the size of the symbolic formulas, which grow with each differentiation (the explosion of terms). The usual cases have from 2 to 4, and then the cost is small. For the example, the 1000-step simulation runs in well under a second in Python.
Properties
- One estimate per parameter. The update law has states. The earlier overparametrized design used one estimate of per step, states in total.
- Global. The result holds for every initial state and estimate.
- Regulation without identification. always. only if the regressor is rich enough along the solution (persistent excitation), which a regulated state is not.
- Certainty equivalence with corrections. The controller is not the known-parameter controller with replaced by . The terms with are extra, and without them the proof fails (compare certainty equivalence).
- Lyapunov based. The design gives the Lyapunov function, so it can be extended with damping terms and robust modifications.
Variants and improvements
- Overparametrized design. Kanellakopoulos, Kokotović and Morse (1991) used a new estimate of in each step, with its own update law. It is simpler to derive, but it has estimates.
- Modular design. Instead of a Lyapunov update law, one can combine a controller that makes the system input-to-state stable with respect to the parameter error and its derivative, and any identifier with bounded outputs. The book of Krstić, Kanellakopoulos and Kokotović (1995) treats this as the modular approach.
- Robust modifications. With disturbances, the update law of line L7 is changed with parameter projection or a leakage term so that stays bounded.
- Output feedback. When only is measured, adaptive observer backstepping uses filters of the input and output in place of the unmeasured states.
- Command-filtered and dynamic surface versions. They replace the analytic derivatives of the virtual controls by filter outputs, to avoid the growth of the formulas.
- Linear plants. For linear systems with unknown coefficients, model reference adaptive control is the classical alternative.
When to use it
Use it when the model has the parametric strict feedback structure with constant unknown parameters that enter linearly, when you need a global result, and when you can compute the partial derivatives of the virtual controls. Typical cases are mechanical and electromechanical systems with unknown friction or load coefficients that enter in the same equation as a nonlinearity. If the parameters vary in time or the model has unknown disturbances, add the robust modifications or use a robust method such as sliding mode control. If you need the true parameter values, add excitation to the reference signal or identify the parameters separately; the controller alone does not give them.
Pitfalls
- Expecting the estimate to converge at line L7. In the example, settles at about while (measurement). With and , the limits are about and (measurement, step ). The limit depends on the gain and the initial state. Do not use as a parameter estimate without persistent excitation.
- A large adaptation gain at line L6. appears in line L6 multiplied by the partial derivatives of the virtual controls. In the example, the peak of is about with and with (measurement, step ). A small gain is not free either: with the peak of is and rises to , because the estimate learns slowly (measurement).
- Dropping the last sum at line L6. For , without the terms , the terms in do not cancel in general, and the proof no longer applies. The sum is empty for , so a design checked only on second order examples does not show the error.
- Parameter drift at line L7. The update law integrates . With a bounded disturbance or unmodeled dynamics, need not decrease, and can grow without bound while stays small. This is a known property of integral update laws in adaptive control (rule of thumb from that field). Projection or leakage prevents it.
- Finite differences at lines L4 and L6. Each virtual control contains the partial derivatives of the previous one. Nested difference quotients lose about the inverse of the step size in accuracy at each level. Differentiate exactly, as here.
- Sampled implementation. The proof assumes that line L7 is evaluated continuously. With a sampled controller, 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/adaptive-backstepping/. The authors are listed in prov/5JZM0E.jsonl.
"""Adaptive backstepping with tuning functions for a system in parametric
strict feedback form
x_i' = x_(i+1) + phi_i(x_1, ..., x_i)^T theta, i = 1, ..., n - 1,
x_n' = beta(x) u + phi_n(x)^T theta,
with theta in R^p constant and unknown, and beta(x) != 0 known. With the
estimate thetahat and alpha_0 = 0, z_0 = 0, tau_0 = 0, step i computes
z_i = x_i - alpha_(i-1)(x_1, ..., x_(i-1), thetahat)
w_i = phi_i - sum_(k<i) (d alpha_(i-1) / d x_k) phi_k
tau_i = tau_(i-1) + w_i z_i
alpha_i = -z_(i-1) - c_i z_i - w_i^T thetahat
+ sum_(k<i) (d alpha_(i-1) / d x_k) x_(k+1)
+ (d alpha_(i-1) / d thetahat) Gamma tau_i
+ sum_(k=2..i-1) z_k (d alpha_(k-1) / d thetahat) Gamma w_i
and the controller is u = alpha_n / beta(x), thetahat' = Gamma tau_n. Along
the closed loop, V = |z|^2 / 2 + (theta - thetahat)^T Gamma^(-1)
(theta - thetahat) / 2 has V' = -sum c_i z_i^2.
The partial derivatives are computed exactly by forward-mode
differentiation with tagged nested dual numbers: one dual direction for
each of x_1, ..., x_(i-1) and thetahat_1, ..., thetahat_p. With Fraction
inputs and rational phi_i, beta every value is exact.
Precondition: phi is a list of n functions; phi[i] takes [x_1, ..., x_(i+1)]
(0-based i) and returns a list of p numbers, using only +, -, *, / and
integer powers. beta(x) is never zero. c holds n positive gains, and Gamma
is a symmetric positive definite p by p matrix (a list of rows).
Cost: step i evaluates step i - 1 at i - 1 + p + 1 points, one level deeper
in the dual numbers, so one evaluation of the controller costs a number of
operations that grows like the product of (i + p) over the steps, times a
power of 3 for the nested dual products. It is meant for small n.
"""
import itertools
from fractions import Fraction
__all__ = [
"Dual",
"new_tag",
"real_part",
"eps_part",
"stages",
"adaptive_backstepping",
"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 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 _matvec(M, v):
return [sum((M[r][s] * v[s] for s in range(len(v))), 0) for r in range(len(M))]
def _dot(a, b):
return sum((ai * bi for ai, bi in zip(a, b)), 0)
def stages(phi, c, Gamma, i, x, th):
"""Return (alpha, z, w, tau) of steps 0..i at the point (x, thetahat).
alpha has i + 1 entries (alpha[0] = 0); z and w have i entries (z[k] is
z_(k+1)); tau has i + 1 entries of length p (tau[0] = 0).
"""
p = len(th)
if i == 0:
return [0], [], [], [[0] * p] # @line L1
A, Z, W, T = stages(phi, c, Gamma, i - 1, x, th) # @line L2
# dx[k][j] = d alpha_k / d x_(j+1), dth[k][l] = d alpha_k / d thetahat_l
dx = [[0] * (i - 1) for _ in range(i)]
dth = [[0] * p for _ in range(i)]
if i >= 2:
for j in range(i - 1):
t = new_tag()
xd = list(x)
xd[j] = Dual(t, x[j], 1)
Ad = stages(phi, c, Gamma, i - 1, xd, th)[0]
for k in range(i):
dx[k][j] = eps_part(Ad[k], t)
for l in range(p):
t = new_tag()
thd = list(th)
thd[l] = Dual(t, th[l], 1)
Ad = stages(phi, c, Gamma, i - 1, x, thd)[0]
for k in range(i):
dth[k][l] = eps_part(Ad[k], t)
z_i = x[i - 1] - A[i - 1] # @line L3
phi_i = phi[i - 1](x[:i])
w_i = list(phi_i) # @line L4
for k in range(i - 1):
phi_k = phi[k](x[:k + 1])
w_i = [w_i[l] - dx[i - 1][k] * phi_k[l] for l in range(p)] # @line L4
tau_i = [T[i - 1][l] + w_i[l] * z_i for l in range(p)] # @line L5
z_prev = Z[i - 2] if i >= 2 else 0
alpha_i = -z_prev - c[i - 1] * z_i - _dot(w_i, th) # @line L6
for k in range(i - 1):
alpha_i = alpha_i + dx[i - 1][k] * x[k + 1] # @line L6
alpha_i = alpha_i + _dot(dth[i - 1], _matvec(Gamma, tau_i)) # @line L6
Gw = _matvec(Gamma, w_i)
for k in range(2, i):
alpha_i = alpha_i + Z[k - 1] * _dot(dth[k - 1], Gw) # @line L6
return A + [alpha_i], Z + [z_i], W + [w_i], T + [tau_i]
def adaptive_backstepping(phi, beta, c, Gamma, x, th):
"""Return (u, thetahat_dot, z) at the state x and the estimate th."""
n = len(phi)
A, Z, _, T = stages(phi, c, Gamma, n, list(x), list(th))
u = _div(A[n], beta(list(x))) # @line L7
th_dot = _matvec(Gamma, T[n]) # @line L7
return u, th_dot, Z
def closed_loop(phi, beta, c, Gamma, theta):
"""Return F(t, s, u) for the simulation helper, with s = (x, thetahat).
theta is the true parameter, used only by the plant. u is ignored; the
controller is evaluated inside the right side.
"""
n = len(phi)
def F(t, s, u=None):
x, th = list(s[:n]), list(s[n:])
uu, th_dot, _ = adaptive_backstepping(phi, beta, c, Gamma, x, th)
dx = [x[i + 1] + _dot(phi[i](x[:i + 1]), theta) for i in range(n - 1)]
dx.append(beta(x) * uu + _dot(phi[n - 1](x), theta))
return dx + list(th_dot)
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_adaptive_backstepping.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-backstepping/. The authors are listed in prov/5JZM0E.jsonl.
"""Tests for adaptive_backstepping.py. Standard library only, fixed seeds."""
import random
import unittest
from fractions import Fraction as Fr
from adaptive_backstepping import (
Dual,
adaptive_backstepping,
closed_loop,
eps_part,
new_tag,
real_part,
stages,
)
from ctlsim import simulate
# The page example: x1' = x2 + theta x1^2, x2' = u, theta = 1 unknown.
PHI = [lambda x: [x[0] ** 2], lambda x: [0]]
BETA = lambda x: 1 # noqa: E731
C = [1, 1]
GAMMA = [[1]]
def example_u(x1, x2, th, c1=1, c2=1, g=1):
"""The controller of the example, written out by hand."""
z1 = x1
z2 = x2 + c1 * x1 + th * x1 ** 2
w2 = (c1 + 2 * th * x1) * x1 ** 2
tau2 = x1 ** 3 + w2 * z2
u = -z1 - c2 * z2 - w2 * th + (-c1 - 2 * th * x1) * x2 - x1 ** 2 * g * tau2
return u, g * tau2
def vdot_check(phi, beta, c, G, Ginv, theta, x, th):
"""Return (V', -sum c_i z_i^2) at (x, th) along the closed loop.
V' is computed from one extra dual direction along the vector field,
so it uses the chain rule only, not the error equations of the proof.
"""
n, p = len(phi), len(th)
F = closed_loop(phi, beta, c, G, theta)
d = F(0, list(x) + list(th))
t = new_tag()
xd = [Dual(t, x[i], d[i]) for i in range(n)]
thd = [Dual(t, th[l], d[n + l]) for l in range(p)]
_, Z, _, _ = stages(phi, c, G, n, xd, thd)
zs = [real_part(z, t) for z in Z]
zd = [eps_part(z, t) for z in Z]
err = [theta[l] - th[l] for l in range(p)]
th_dot = d[n:]
# V = |z|^2 / 2 + err^T Ginv err / 2, and err' = -th_dot.
vd = sum(a * b for a, b in zip(zs, zd))
vd -= sum(err[r] * Ginv[r][s] * th_dot[s] for r in range(p) for s in range(p))
return vd, -sum(ci * z * z for ci, z in zip(c, zs))
def random_poly(rng, k):
"""A random polynomial in x_1..x_k of degree at most 2, integer terms."""
terms = [(rng.randint(-2, 2), rng.randrange(k), rng.randrange(k + 1)) for _ in range(2)]
def h(x):
s = 0
for a, i, j in terms:
s = s + a * x[i] * (x[j] if j < k else 1)
return s
return h
class TestExample(unittest.TestCase):
def test_initial_values(self):
u, th_dot, z = adaptive_backstepping(PHI, BETA, C, GAMMA, [Fr(1), Fr(0)], [Fr(0)])
self.assertEqual(u, -4)
self.assertEqual(th_dot, [2])
self.assertEqual(z, [1, 1])
def test_closed_form(self):
rng = random.Random(1)
for _ in range(20):
x1, x2, th = (Fr(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(3))
c1, c2, g = (Fr(rng.randint(1, 6), rng.randint(1, 3)) for _ in range(3))
u, th_dot, _ = adaptive_backstepping(PHI, BETA, [c1, c2], [[g]], [x1, x2], [th])
self.assertEqual((u, th_dot[0]), example_u(x1, x2, th, c1, c2, g))
def test_scalar_case(self):
# n = 1: x' = beta u + phi^T theta gives u = (-c z - phi^T th) / beta
# and th' = Gamma phi z.
phi = [lambda x: [x[0] ** 2, x[0]]]
beta = lambda x: 2 + x[0] ** 2 # noqa: E731
x, th = [Fr(3, 2)], [Fr(1, 3), Fr(-2)]
G = [[2, 1], [1, 1]]
u, th_dot, z = adaptive_backstepping(phi, beta, [Fr(5)], G, x, th)
ph = [Fr(9, 4), Fr(3, 2)]
self.assertEqual(z, [Fr(3, 2)])
self.assertEqual(u, (-5 * x[0] - ph[0] * th[0] - ph[1] * th[1]) / beta(x))
self.assertEqual(th_dot, [(2 * ph[0] + ph[1]) * x[0], (ph[0] + ph[1]) * x[0]])
class TestLyapunovIdentity(unittest.TestCase):
def test_example(self):
vd, rhs = vdot_check(PHI, BETA, C, GAMMA, [[1]], [1], [Fr(1), Fr(0)], [Fr(0)])
self.assertEqual(vd, rhs)
self.assertEqual(vd, -2)
def test_random_systems(self):
# Exact V' = -sum c_i z_i^2 on random systems with n = 1..3 and
# p = 1..2, a non-diagonal Gamma and a state-dependent beta.
rng = random.Random(7)
G = [[2, 1], [1, 1]]
Ginv = [[1, -1], [-1, 2]]
count = 0
for n in (1, 2, 3):
for p in (1, 2):
for _ in range(4):
phi = []
for i in range(n):
polys = [random_poly(rng, i + 1) for _ in range(p)]
phi.append(lambda x, polys=polys: [h(x) for h in polys])
beta = lambda x: 1 + x[0] ** 2 # noqa: E731
c = [Fr(rng.randint(1, 4), rng.randint(1, 2)) for _ in range(n)]
Gp = [row[:p] for row in G[:p]]
Gi = Ginv if p == 2 else [[Fr(1, 2)]]
theta = [Fr(rng.randint(-3, 3), 2) for _ in range(p)]
x = [Fr(rng.randint(-6, 6), rng.randint(1, 3)) for _ in range(n)]
th = [Fr(rng.randint(-6, 6), 3) for _ in range(p)]
vd, rhs = vdot_check(phi, beta, c, Gp, Gi, theta, x, th)
self.assertEqual(vd, rhs)
count += 1
self.assertEqual(count, 24)
class TestSimulation(unittest.TestCase):
def test_example_run(self):
# RK4, dt = 0.01, T = 10. Theorem: V is nonincreasing and z -> 0.
# The estimate need not reach theta = 1.
F = closed_loop(PHI, BETA, C, GAMMA, [1])
ts, xs, _ = simulate(F, [1.0, 0.0, 0.0], 0.0, 10.0, 0.01)
V = []
for s in xs:
_, _, z = adaptive_backstepping(PHI, BETA, C, GAMMA, s[:2], s[2:])
V.append((z[0] ** 2 + z[1] ** 2 + (1 - s[2]) ** 2) / 2)
self.assertAlmostEqual(V[0], 1.5)
for k in range(len(V) - 1):
self.assertLessEqual(V[k + 1], V[k] + 1e-9)
x1, x2, th = xs[-1]
self.assertLess(abs(x1) + abs(x2), 1e-3)
self.assertAlmostEqual(th, 1.63173, places=4)
self.assertGreater(abs(th - 1), 0.5)
self.assertAlmostEqual(V[-1], (1 - th) ** 2 / 2, places=6)
# The page table, t = 1.
k = round(1.0 / 0.01)
self.assertAlmostEqual(xs[k][0], 0.32603, places=4)
self.assertAlmostEqual(xs[k][1], -0.98258, places=4)
self.assertAlmostEqual(xs[k][2], 1.64337, places=4)
if __name__ == "__main__":
unittest.main()
History
The first adaptive controllers for nonlinear systems used certainty equivalence and needed growth conditions on the nonlinearities. Kanellakopoulos, Kokotović and Morse (1991) gave a recursive design that is global for every system in parametric strict feedback form, at the price of several estimates of each parameter. Krstić, Kanellakopoulos and Kokotović (1992) introduced the tuning functions, which give one estimate per parameter; the paper is titled "Adaptive nonlinear control without overparametrization". Kokotović's 1991 Bode Prize Lecture, published in 1992, presented the adaptive design as a main use of backstepping, and the 1995 book of Krstić, Kanellakopoulos and Kokotović gave the full theory, including the modular and output feedback designs.
References
- Miroslav Krstić, Ioannis Kanellakopoulos and Petar Kokotović, Nonlinear and Adaptive Control Design, Wiley, 1995, Chapter 4 (tuning functions design), Section 4.2 (parametric strict feedback systems)
- Adaptive nonlinear control without overparametrization, the tuning functions design, with one estimate of each parameter
- Systematic design of adaptive controllers for feedback linearizable systems, the first recursive adaptive design for parametric strict feedback systems, with overparametrization
- Petar V. Kokotović, The joy of feedback: nonlinear and adaptive, IEEE Control Systems Magazine 12(3), 7-17, 1992, the 1991 Bode Prize Lecture; adaptive backstepping
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 5JZM0E Edit this page History Report an error Markdown