Algorithmcore
Input-output linearization
Also called input-output feedback linearization.
Differentiates the output until the input appears, at the relative degree r, and sets u = (v - L_f^r h) / (L_g L_f^(r-1) h), so that y^(r) = v. The zero dynamics must be checked apart.
- Time
- O(n^3 p q) worst
- Space
- O(n^2 p) extra
- Where
- n = the number of states; p = the largest number of terms of a function L_f^k h for k at most r; q = the largest number of terms of an entry of f or g (operations on exact rationals at unit cost)
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alberto Isidori, Arthur J. Krener, Claudio Gori Giorgi, Salvatore Monaco, 1981
Input-output linearization is a feedback design for a nonlinear control-affine system with output . It differentiates the output along the system, with Lie derivatives, until the input appears. This happens at the relative degree , where . Then the feedback cancels the nonlinear terms and leaves , a chain of integrators from the new input to the output. A linear law for then places the poles of the tracking error. The method is exact, not an approximation around a point, but it is local: it needs a relative degree, and it needs along the motion. It also hides states from the output. Their behavior is given by the zero dynamics, and the method is safe only when these are stable.
In plain words
Take the output and ask how it changes. If the input does not appear in its rate of change, ask how that rate changes, and so on. After a few steps the input appears, multiplied by some factor and added to other terms that depend on the state. Choose the input so that it removes those other terms and divides out the factor. What is left is a very simple machine: the output is the input passed through a fixed number of integrators. That machine is easy to control with the usual linear tools. The price is that some parts of the state are no longer visible in the output. Before you use the method, check that those hidden parts settle by themselves, or the output will look fine while the state runs away.
The problem
Input. Smooth , and on an open set , and a point . Smoothness makes locally Lipschitz, so the solutions exist and are unique by the Picard-Lindelöf theorem. For the control law, also a reference with continuous derivatives, and real numbers such that is Hurwitz.
Output. One of three answers:
- the relative degree at , the functions for , with , and , together with the feedback that makes the tracking error obey ;
- UNDEFINED, if no relative degree exists at ;
- NO INPUT EFFECT, if near for all , so the input does not reach the output.
This is output tracking with a known reference and known derivatives, a special case of the output regulation problem. The algorithm makes the error equation linear. Internal stability of the other states is a separate condition.
The algorithm
IO-LINEARIZE(f, g, h, x0)- 1
φ ← h; ξ ← empty list - 2
for k ← 0 to n - 1 - 3
append φ to ξ ▷ now ξ[k] = L_f^k h - 4
a ← L_g φ - 5
if a(x0) ≠ 0 - 6
b ← L_f φ - 7
return (r = k + 1, ξ, a, b) - 8
if a is not zero near x0 then return UNDEFINED - 9
φ ← L_f φ - 10
return NO INPUT EFFECT CONTROL(t, x) ▷ uses r, ξ, a, b, c, y_d- 11
v ← y_d^(r)(t) - Σ_{i<r} c_i (ξ[i](x) - y_d^(i)(t)); return u = (v - b(x)) / a(x)
Lines L2 to L9 compute the output derivatives one by one. At the start of pass , , and every earlier vanishes near . So , and . Line L4 takes the coefficient of . If it is not zero at (line L5), the relative degree is and line L6 takes the rest of the derivative. If it is zero at but not on a neighborhood of (line L8), no relative degree exists at . Otherwise the input does not appear yet, and line L9 moves to the next derivative. The loop stops after passes at most, because a relative degree is never larger than .
Line L11 is the control law. It sets and chooses as the reference term plus a linear feedback of the errors . It divides by , so it is valid only while .
The implementation works with polynomial , and with exact rational coefficients, and it differentiates exactly. For a polynomial, "zero near " is the same as "the zero polynomial", so the test at line L8 is exact. With general smooth functions, the test needs symbolic computation or a proof by hand.
Example
Take the system with three states
and . The algorithm runs as follows.
| pass | (line L3) | (line L4) | action | |
|---|---|---|---|---|
| 0 | is the zero polynomial, line L9: | |||
| 1 | line L6: , return |
So , , and . Because everywhere, the law at line L11 is defined at every state. The third state is internal. With held at zero it obeys , so the system is minimum phase.
Choose and , so the error polynomial is , and track . Line L11 becomes
Start at . Then and , and the solution of is exactly . A 4th order Runge-Kutta simulation with step , with the feedback evaluated inside the right side, gives:
| 0 | 1 | 0 | 0 | 1 | 0.5 |
| 1 | 1.20935 | 0.17242 | 0.78337 | 0.36788 | -0.57495 |
| 2 | 1.04463 | -0.55148 | 1.16292 | 0.13534 | -1.03120 |
| 3 | 0.19091 | -1.03978 | 0.68541 | 0.04979 | -1.29899 |
| 4 | -0.73849 | -0.67196 | 0.38791 | 0.01832 | 0.49061 |
| 5 | -0.95219 | 0.27692 | 0.70636 | 0.00674 | 0.87036 |
The error column is : , , and so on. Over the whole run, differs from by at most , which is the error of the integrator. The internal state stays bounded, because it is driven by through the stable dynamics .
Correctness
The full proof is in proofs/correctness.md. Its main steps:
- Termination. The loop runs at most times.
- The three answers are right. At the start of pass , and vanishes near for . A return at line L7 then matches the definition of the relative degree. A return at line L8 is right, because no can satisfy the definition when is zero at but not near it. A return at line L10 is right, because a relative degree is at most . That bound comes from the identity for (and for ), proved by induction on with . It makes an matrix of rank that factors through .
- The closed loop. While the state stays where and the lower vanish, for and . So the error obeys .
The tests check the example, compare , and with the Markov parameters and the rows for 60 random integer linear systems, check the Lie derivative against the slope of and the bracket identity on random polynomials, and check that the simulated error equals within .
Proof: IO-LINEARIZE finds the relative degree when it exists, reports when it does not, and the feedback gives the linear error equationfull
The system is , , with , an open subset of , and , , of class on . For a function and a vector field , . The bracket is , and , .
The system has relative degree at if for all in a neighborhood of and all , and .
The test at line L8 asks whether vanishes on a neighborhood of . In the implementation , and are polynomials with rational coefficients, and the test is " is the zero polynomial". Lemma 1 shows that the two tests agree for polynomials.
Lemma 1: a polynomial that vanishes on an open set is zero
Let be a polynomial in variables that is zero on an open ball around . Write . This is a polynomial in , and its coefficient of is . All partial derivatives of at are zero, because is zero on a neighborhood of . So is the zero polynomial, and so is .
Lemma 2: the bracket identity
For a function and fields , : .
Proof. By the product rule,
Swap and and subtract. The second derivatives of are symmetric, so the first sums cancel. What remains is .
Lemma 3: the anti-triangular identity
Let be an open set on which for . Then on , for all with ,
Proof. Induction on . For the claim is the hypothesis when , and it is trivial when . Suppose that it holds for , and let . Lemma 2 with and gives
In the first term , so the function in the brackets is zero on the open set , and its derivative along is zero on too. In the second term the index sum is . If , the term is zero by the induction hypothesis. If , the term is , and with the minus sign in front the result is .
Lemma 4: a relative degree is at most
If the system has relative degree at , then , and the row vectors are linearly independent.
Proof. Let be the neighborhood in the definition and . Let be the matrix with rows and the matrix with columns , for . The entry of is . By Lemma 3 it is zero when and when . So is zero above the anti-diagonal and has nonzero entries on it, and . Then . So and .
Termination
The loop at line L2 runs at most times. Each pass computes two Lie derivatives, one evaluation at and one zero test. For polynomials with rational coefficients each of these is a finite computation. So IO-LINEARIZE stops after at most passes.
Correctness of the three outcomes
Invariant: at the start of the pass with index , , the list holds , and vanishes on a neighborhood of for every . It holds for by line L1. A pass that does not return reaches line L9 only when the test at line L8 says that vanishes near , and line L9 sets , so the invariant holds for . For polynomials, "vanishes near " and "is the zero polynomial" are the same by Lemma 1, and finitely many neighborhoods have an open intersection.
Return at line L7. Here vanishes near for and . This is the definition with . The returned is , and .
Return at line L8. Here vanishes near for , , and does not vanish on any neighborhood of . Suppose that the relative degree exists at . If , then , which is false. If , the same value is , which is false. If , the definition makes zero on a neighborhood of , which is false. So no relative degree exists at , and UNDEFINED is the correct answer.
Return at line L10. All passes ended at line L9, so vanishes on a neighborhood of for . Suppose that the system has a relative degree at some point . Then , so , which contradicts Lemma 4. So no point near has a relative degree. In the polynomial case is all of . NO INPUT EFFECT is the correct answer.
The closed loop
Let IO-LINEARIZE return , , , , and let be an open neighborhood of on which for and . Let be times continuously differentiable. Line L11 applies
On the closed-loop field is continuous in and in , so it is locally Lipschitz in , and the Picard-Lindelöf theorem gives one solution for as long as it stays in .
Along this solution, for ,
so by induction for . One more derivative gives . Let . Then for , and
So the error obeys while the state stays in . Its characteristic polynomial is , and if this polynomial is Hurwitz, and its first derivatives go to zero exponentially. This says nothing about the other state coordinates. They must be checked separately, with the zero dynamics.
Complexity
Count operations on exact rationals as unit cost, as in the real RAM. A polynomial with terms in variables takes space, for its exponent vectors.
- One Lie derivative. takes partial derivatives, each, and products of a polynomial with at most terms by one with at most terms. Each product forms exponent vectors of length . So one Lie derivative costs .
- The loop. Each pass computes at most two Lie derivatives and one evaluation at , which costs . There are at most passes, so the time is .
- Space. The list holds at most polynomials of at most terms, so .
- The control law. Line L11 evaluates polynomials, per sample for the polynomial representation.
The number is the weak point. Each Lie derivative multiplies by the entries of , so the degree grows with and the number of terms can grow fast. This is expression swell. A sparse polynomial representation, as here, helps when the system has few terms. Coefficient sizes of the exact rationals can also grow, which the unit cost model hides.
Properties
- Exact, not approximate. The cancellation holds on a whole region, not only at , unlike a design on the Jacobian linearization.
- Local. It needs the relative degree to exist and along the motion. In the example , so the result is global for the output.
- Model based. The feedback cancels and divides by . Model errors leave terms that the linear law for must tolerate.
- Blind to the internal state. The closed loop has the zero dynamics as an unobservable part. The output behaves well whatever these do.
- Invariant. The relative degree, and the zero dynamics do not depend on the choice of coordinates.
Variants and improvements
- Full-state linearization. If , there are no internal states. The coordinates and the same feedback make the whole system linear. This is the case of feedback linearization, and the conditions for feedback linearizability say when some output with exists.
- Several inputs and outputs. With inputs and outputs, take derivatives of . If the decoupling matrix is nonsingular, one feedback makes each output a separate chain of integrators. This is noninteracting control (Isidori, Chapter 5). When the matrix is singular, dynamic extension adds integrators at the inputs and can make it nonsingular.
- Robot arms. For with output , every joint has relative degree 2, and the decoupling matrix is , which is always invertible. The feedback is the computed torque method.
- Output feedback. The law needs . A high-gain observer estimates these derivatives from .
- Robust versions. Sliding mode control uses the same normal form with a switching law that tolerates bounded model errors. Backstepping avoids cancelling useful terms and handles systems in strict feedback form.
When to use it
Use it when the model is accurate, the relative degree is defined on the whole operating region, stays away from zero there, and the system is minimum phase for the chosen output. Then it gives the same error dynamics at every operating point, which a design on one Jacobian linearization cannot.
Prefer a linear design on the Jacobian linearization when the state stays near one equilibrium. Prefer sliding mode control or backstepping when the model has large errors or when some nonlinear terms help stability and should not be cancelled. Prefer nonlinear MPC when input or state limits matter, since the cancelling input can be large. For a non-minimum phase output, do not use it directly: choose another output, or use a method that accounts for the zero dynamics.
Pitfalls
- Testing only at the point. If line L8 is left out, a coefficient that is zero at but not near it is skipped. For , , , , pass 1 has with , and the loop without line L8 goes on to report with . But near the input already appears in , so the feedback is wrong. Keep line L8: it returns UNDEFINED here.
- Finite differences. Computing lines L4, L6 and L9 with difference quotients loses accuracy at each level, and the test at line L5 then compares noise with zero. Differentiate exactly (symbolic or automatic differentiation), as the implementation does.
- Ignoring the zero dynamics. Line L11 makes the output follow whatever the internal state does. For , , , with , and the zero dynamics are . Holding makes grow like . Check the zero dynamics before you apply line L11.
- Division by a small . Line L11 divides by . If the motion approaches a point where , the input grows without bound. The result holds only on the region where . Keep the motion away from the singular set, or saturate and accept the loss of exactness.
- Sampled implementation. The proof assumes that line L11 is evaluated continuously. If is computed at samples and held, the cancellation is not exact. In the example, with the input held over each RK4 step of , the deviation of from reaches ; with a hold of it reaches . The error still decays, but it no longer equals .
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
# 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()
input_output_linearization.py 258 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/input-output-linearization/. The authors are listed in prov/VH21RF.jsonl.
"""Input-output linearization of a single-input single-output system
x' = f(x) + g(x) u, y = h(x), x in R^n,
where f, g and h have polynomial entries with exact rational coefficients.
The algorithm differentiates the output along the system with exact Lie
derivatives L_f phi = (d phi / dx) f until the input appears. The first k
with L_g L_f^k h (x0) != 0 gives the relative degree r = k + 1 at x0. Then
y^(i) = L_f^i h (x) for i < r,
y^(r) = L_f^r h (x) + L_g L_f^(r-1) h (x) u,
and the feedback u = (v - L_f^r h) / (L_g L_f^(r-1) h) makes y^(r) = v.
A polynomial vanishes on a neighborhood of a point if and only if it is the
zero polynomial, so the test "L_g L_f^k h = 0 near x0" is exact here. No
finite differences are used. The internal dynamics are not examined: the
caller must check that they stay bounded (see the zero dynamics page).
"""
from fractions import Fraction
__all__ = [
"Poly",
"variables",
"lie_derivative",
"lie_bracket",
"IOLinearization",
"io_linearize",
"tracking_control",
"closed_loop",
]
class Poly:
"""A polynomial in n variables: a dict from exponent tuples to Fractions."""
__slots__ = ("n", "terms")
def __init__(self, n, terms=None):
self.n = n
self.terms = {}
for e, c in (terms or {}).items():
if len(e) != n:
raise ValueError("exponent tuple of the wrong length")
c = Fraction(c)
if c != 0:
self.terms[tuple(e)] = c
@classmethod
def const(cls, n, c):
return cls(n, {(0,) * n: c})
@classmethod
def var(cls, n, i):
e = [0] * n
e[i] = 1
return cls(n, {tuple(e): 1})
def _lift(self, other):
if isinstance(other, Poly):
if other.n != self.n:
raise ValueError("polynomials in different numbers of variables")
return other
if isinstance(other, (int, Fraction)):
return Poly.const(self.n, other)
return NotImplemented
def __add__(self, other):
other = self._lift(other)
if other is NotImplemented:
return other
t = dict(self.terms)
for e, c in other.terms.items():
t[e] = t.get(e, 0) + c
return Poly(self.n, t)
__radd__ = __add__
def __neg__(self):
return Poly(self.n, {e: -c for e, c in self.terms.items()})
def __sub__(self, other):
other = self._lift(other)
if other is NotImplemented:
return other
return self + (-other)
def __rsub__(self, other):
return (-self) + other
def __mul__(self, other):
other = self._lift(other)
if other is NotImplemented:
return other
t = {}
for e1, c1 in self.terms.items():
for e2, c2 in other.terms.items():
e = tuple(a + b for a, b in zip(e1, e2))
t[e] = t.get(e, 0) + c1 * c2
return Poly(self.n, t)
__rmul__ = __mul__
def __pow__(self, k):
if not isinstance(k, int) or k < 0:
raise ValueError("only powers by integers k >= 0")
out = Poly.const(self.n, 1)
for _ in range(k):
out = out * self
return out
def __eq__(self, other):
other = self._lift(other)
if other is NotImplemented:
return False
return self.terms == other.terms
def __hash__(self):
return hash((self.n, frozenset(self.terms.items())))
def is_zero(self):
return not self.terms
def diff(self, i):
"""The exact partial derivative with respect to x_i."""
t = {}
for e, c in self.terms.items():
if e[i] > 0:
d = list(e)
d[i] -= 1
d = tuple(d)
t[d] = t.get(d, 0) + c * e[i]
return Poly(self.n, t)
def __call__(self, x):
"""Evaluate at x. The entries of x may be int, Fraction, float or Poly."""
if len(x) != self.n:
raise ValueError("point of the wrong dimension")
total = 0
for e, c in self.terms.items():
term = c
for xi, k in zip(x, e):
if k:
term = term * xi ** k
total = total + term
return total
def __repr__(self):
if not self.terms:
return "0"
parts = []
for e in sorted(self.terms, reverse=True):
mono = "*".join(f"x{i + 1}" + (f"^{k}" if k > 1 else "") for i, k in enumerate(e) if k)
parts.append(f"{self.terms[e]}" + ("*" + mono if mono else ""))
return " + ".join(parts)
def variables(n):
"""The coordinate functions x1, ..., xn as polynomials."""
return tuple(Poly.var(n, i) for i in range(n))
def lie_derivative(phi, f):
"""L_f phi = sum_i (d phi / d x_i) f_i, exactly."""
if len(f) != phi.n:
raise ValueError("the vector field and the function have different dimensions")
out = Poly(phi.n)
for i, fi in enumerate(f):
out = out + phi.diff(i) * fi
return out
def lie_bracket(f, g):
"""[f, g] = (dg/dx) f - (df/dx) g, the sign used by Isidori and Khalil."""
return [lie_derivative(gi, f) - lie_derivative(fi, g) for fi, gi in zip(f, g)]
class IOLinearization:
"""The result of io_linearize.
status is "ok", "undefined" (L_g L_f^k h vanishes at x0 but not near x0,
so no relative degree exists at x0) or "no input effect" (L_g L_f^k h is
zero for k = 0, ..., n - 1, so no relative degree exists near x0).
For status "ok": r is the relative degree, xi = [h, L_f h, ...,
L_f^(r-1) h], a = L_g L_f^(r-1) h with a(x0) != 0, and b = L_f^r h.
For "undefined", k is the index with the bad L_g L_f^k h, kept in a.
"""
def __init__(self, status, r=None, xi=None, a=None, b=None, k=None):
self.status = status
self.r = r
self.xi = xi or []
self.a = a
self.b = b
self.k = k
def __repr__(self):
return f"IOLinearization(status={self.status!r}, r={self.r}, a={self.a!r}, b={self.b!r})"
def io_linearize(f, g, h, x0):
"""Find the relative degree of y = h(x) at x0 and the linearizing terms."""
n = h.n
if len(f) != n or len(g) != n or len(x0) != n:
raise ValueError("f, g, h and x0 must have the same dimension n")
if any(p.n != n for p in list(f) + list(g)):
raise ValueError("every entry of f and g must be a polynomial in n variables")
phi = h # @line L1
xi = [] # @line L1
for k in range(n): # @line L2
xi.append(phi) # @line L3
a = lie_derivative(phi, g) # @line L4
if a(x0) != 0: # @line L5
b = lie_derivative(phi, f) # @line L6
return IOLinearization("ok", r=k + 1, xi=xi, a=a, b=b) # @line L7
if not a.is_zero(): # @line L8
return IOLinearization("undefined", xi=xi, a=a, k=k) # @line L8
phi = lie_derivative(phi, f) # @line L9
return IOLinearization("no input effect", xi=xi) # @line L10
def tracking_control(lin, c, yd):
"""The feedback u(t, x) that makes y track y_d.
c = [c_0, ..., c_(r-1)] are the coefficients of s^r + c_(r-1) s^(r-1)
+ ... + c_0, which should be Hurwitz. yd = [y_d, y_d', ..., y_d^(r)] is a
list of r + 1 functions of t. The tracking error e = y - y_d then obeys
e^(r) + c_(r-1) e^(r-1) + ... + c_0 e = 0 while a(x) != 0.
"""
if lin.status != "ok":
raise ValueError("the system has no relative degree at the point")
r = lin.r
if len(c) != r or len(yd) != r + 1:
raise ValueError("need r coefficients and r + 1 reference derivatives")
def u(t, x):
v = yd[r](t) - sum(c[i] * (float(lin.xi[i](x)) - yd[i](t)) for i in range(r)) # @line L11
return (v - float(lin.b(x))) / float(lin.a(x)) # @line L11
return u
def closed_loop(f, g, control):
"""The closed-loop field F(t, x, _) = f(x) + g(x) control(t, x), in float.
The control is evaluated inside the field, so an RK4 step integrates the
closed loop itself and not a zero-order hold of the input.
"""
def F(t, x, _u=None):
u = control(t, x)
return [float(fi(x)) + float(gi(x)) * u for fi, gi in zip(f, g)]
return F
test_input_output_linearization.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/input-output-linearization/. The authors are listed in prov/VH21RF.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlsim
from input_output_linearization import (
Poly,
closed_loop,
io_linearize,
lie_bracket,
lie_derivative,
tracking_control,
variables,
)
def page_system():
x1, x2, x3 = variables(3)
zero = Poly(3)
f = [x2, x1 * x3 - x2 ** 3, -x3 + x1 ** 2]
g = [zero, 1 + x1 ** 2, zero]
return f, g, x1
def random_poly(rng, n, terms=4, deg=3):
t = {}
for _ in range(terms):
e = [0] * n
for _ in range(rng.randint(0, deg)):
e[rng.randrange(n)] += 1
t[tuple(e)] = Fraction(rng.randint(-5, 5), rng.randint(1, 3))
return Poly(n, t)
def linear_field(A):
n = len(A)
xs = variables(n)
return [sum((Poly.const(n, A[i][j]) * xs[j] for j in range(n)), Poly(n)) for i in range(n)]
def test_page_example():
f, g, h = page_system()
x1, x2, x3 = variables(3)
lin = io_linearize(f, g, h, (0, 0, 0))
assert lin.status == "ok" and lin.r == 2
assert lin.xi == [x1, x2]
assert lin.a == 1 + x1 ** 2
assert lin.b == x1 * x3 - x2 ** 3
def test_lie_derivative_is_the_directional_derivative():
# d/dt h(x0 + t v) at t = 0 equals grad h(x0) . v; compute it by
# substitution into a polynomial in t, without the diff method.
rng = random.Random(11)
for _ in range(40):
n = rng.randint(1, 4)
h = random_poly(rng, n)
f = [random_poly(rng, n) for _ in range(n)]
x0 = [Fraction(rng.randint(-3, 3), rng.randint(1, 2)) for _ in range(n)]
v = [fi(x0) for fi in f]
t = Poly.var(1, 0)
curve = [Poly.const(1, a) + Poly.const(1, b) * t for a, b in zip(x0, v)]
along = h(curve)
along = along if isinstance(along, Poly) else Poly.const(1, along)
slope = along.terms.get((1,), Fraction(0))
assert lie_derivative(h, f)(x0) == slope
def test_bracket_identity():
# L_[f,g] h = L_f L_g h - L_g L_f h, exactly.
rng = random.Random(5)
for _ in range(25):
n = rng.randint(1, 3)
f = [random_poly(rng, n, 3, 2) for _ in range(n)]
g = [random_poly(rng, n, 3, 2) for _ in range(n)]
h = random_poly(rng, n, 3, 3)
lhs = lie_derivative(h, lie_bracket(f, g))
rhs = lie_derivative(lie_derivative(h, g), f) - lie_derivative(lie_derivative(h, f), g)
assert lhs == rhs
def test_bracket_sign():
# [Ax, b] = -A b for a linear f and a constant g.
f = linear_field([[0, 1], [-2, -3]])
g = [Poly(2), Poly.const(2, 1)]
assert lie_bracket(f, g) == [Poly.const(2, -1), Poly.const(2, 3)]
def test_linear_systems_against_markov_parameters():
# For x' = A x + B u, y = C x: L_g L_f^k h = C A^k B and L_f^r h = C A^r x.
rng = random.Random(2024)
for trial in range(60):
n = rng.randint(1, 5)
A = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
B = [rng.randint(-1, 1) * rng.randint(0, 1) for _ in range(n)]
C = [rng.randint(-1, 1) * rng.randint(0, 1) for _ in range(n)]
if trial % 7 == 0 and n >= 2:
# input and output on separate decoupled blocks: no input effect
k = n // 2
A = [[A[i][j] if (i < k) == (j < k) else 0 for j in range(n)] for i in range(n)]
B = [B[i] if i < k else 0 for i in range(n)]
C = [C[i] if i >= k else 0 for i in range(n)]
xs = variables(n)
f = linear_field(A)
g = [Poly.const(n, b) for b in B]
h = sum((Poly.const(n, c) * x for c, x in zip(C, xs)), Poly(n))
lin = io_linearize(f, g, h, [0] * n)
markov = []
row = C[:]
for _ in range(n + 1):
markov.append(sum(a * b for a, b in zip(row, B)))
row = [sum(row[i] * A[i][j] for i in range(n)) for j in range(n)]
nz = [k for k in range(n) if markov[k] != 0]
if not nz:
assert lin.status == "no input effect"
continue
r = nz[0] + 1
assert lin.status == "ok" and lin.r == r
assert lin.a == Poly.const(n, markov[r - 1])
row = C[:]
for _ in range(r):
row = [sum(row[i] * A[i][j] for i in range(n)) for j in range(n)]
assert lin.b == sum((Poly.const(n, c) * x for c, x in zip(row, xs)), Poly(n))
def test_isidori_identity_on_page_example():
# L_(ad_f^j g) L_f^i h is 0 for i + j <= r - 2 and (-1)^j L_g L_f^(r-1) h for i + j = r - 1.
f, g, h = page_system()
lin = io_linearize(f, g, h, (0, 0, 0))
r = lin.r
ads = [g]
for _ in range(r - 1):
ads.append(lie_bracket(f, ads[-1]))
for i in range(r):
for j in range(r - i):
val = lie_derivative(lin.xi[i], ads[j])
if i + j <= r - 2:
assert val.is_zero()
else:
assert val == (-1) ** j * lin.a
def test_relative_degree_equal_to_n():
x1, x2, x3 = variables(3)
zero = Poly(3)
f = [x2, x3 + x1 ** 2, x1 * x2]
g = [zero, zero, 1 + x2 ** 2]
lin = io_linearize(f, g, x1, (0, 0, 0))
assert lin.status == "ok" and lin.r == 3
assert lin.xi == [x1, x2, x3 + x1 ** 2]
assert lin.a == 1 + x2 ** 2
assert lin.b == 3 * x1 * x2
def test_undefined_and_no_input_effect():
y1, y2 = variables(2)
f = [y2, Poly(2)]
g = [y1, Poly.const(2, 1)]
bad = io_linearize(f, g, y1, (0, 1))
assert bad.status == "undefined" and bad.k == 0 and bad.a == y1
good = io_linearize(f, g, y1, (1, 0))
assert good.status == "ok" and good.r == 1
# y = x2 with x1' = u, x2' = -x2: the input never reaches the output
f2 = [Poly(2), -y2]
g2 = [Poly.const(2, 1), Poly(2)]
none = io_linearize(f2, g2, y2, (0, 0))
assert none.status == "no input effect"
with pytest.raises(ValueError):
tracking_control(none, [1], [math.sin, math.cos])
with pytest.raises(ValueError):
io_linearize(f2, g2, y2, (0, 0, 0))
def test_closed_loop_tracking_matches_the_error_equation():
# RK4 on the closed loop, dt = 0.01 to t = 5 (500 steps). With c = [2, 3]
# the error obeys e'' + 3 e' + 2 e = 0, and from x(0) = (1, 0, 0) with
# y_d = sin t the exact error is e(t) = exp(-t). Tolerance 1e-8.
f, g, h = page_system()
lin = io_linearize(f, g, h, (0, 0, 0))
yd = [math.sin, math.cos, lambda t: -math.sin(t)]
u = tracking_control(lin, [2, 3], yd)
F = closed_loop(f, g, u)
dt, t1 = 0.01, 5.0
steps = round(t1 / dt)
assert abs(steps * dt - t1) < 1e-12 and steps == 500
ts, xs, _ = ctlsim.simulate(F, [1.0, 0.0, 0.0], 0.0, t1, dt)
assert len(ts) == steps + 1
for t, x in zip(ts, xs):
assert abs(x[0] - math.sin(t) - math.exp(-t)) < 1e-8
assert abs(x[1] - math.cos(t) + math.exp(-t)) < 1e-8
assert abs(x[2]) < 2.0 # the internal state stays bounded
assert abs(xs[-1][0] - math.sin(5.0)) < 0.0068
def test_sampled_feedback_is_only_approximate():
# With a zero-order hold of 0.05 s the cancellation is not exact; the
# error still decays but no longer equals exp(-t).
f, g, h = page_system()
lin = io_linearize(f, g, h, (0, 0, 0))
yd = [math.sin, math.cos, lambda t: -math.sin(t)]
u = tracking_control(lin, [2, 3], yd)
def plant(t, x, uu):
return [float(fi(x)) + float(gi(x)) * uu for fi, gi in zip(f, g)]
ts, xs, _ = ctlsim.simulate(plant, [1.0, 0.0, 0.0], 0.0, 5.0, 0.01, control=u, hold=0.05)
worst = max(abs(x[0] - math.sin(t) - math.exp(-t)) for t, x in zip(ts, xs))
assert 1e-6 < worst < 0.1
assert abs(xs[-1][0] - math.sin(5.0)) < 0.05
History
The computed torque method for robot arms uses the same cancellation in a special case. Isidori, Krener, Gori-Giorgi and Monaco (1981) solved the nonlinear decoupling problem by feedback with the tools of differential geometry, and the paper led to the idea of the zeros of a nonlinear system. Byrnes and Isidori then introduced the normal form and the zero dynamics, and their 1991 paper stated the minimum phase condition under which the cancelling feedback stabilizes the whole state. The method is standard in the textbooks of Isidori (1995, Chapter 4), Slotine and Li (1991, Chapter 6) and Khalil (2002, Chapter 13).
References
- Alberto Isidori, Nonlinear Control Systems, third edition, Springer, 1995, Chapter 4 (Nonlinear feedback for single-input single-output systems), the normal form, the zero dynamics and asymptotic output tracking; Chapter 5 for several inputs and outputs
- Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 13.2, Input-Output Linearization, and Section 13.4, State Feedback Control (stabilization and tracking)
- Jean-Jacques E. Slotine and Weiping Li, Applied Nonlinear Control, Prentice Hall, 1991, Chapter 6, Feedback Linearization; Section 6.1.3 for the idea of input-output linearization
- Nonlinear decoupling via feedback: a differential geometric approach, the decoupling problem for systems with several inputs and outputs, solved with the derivatives of the outputs along the system
- Asymptotic stabilization of minimum phase nonlinear systems, the minimum phase condition that makes the cancelling feedback safe for the internal state
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 VH21RF Edit this page History Report an error Markdown