Algorithm Search⌘K

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)
Properties
deterministicexactofflineiterative
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 x˙=f(x)+g(x)u\dot x = f(x) + g(x) u with output y=h(x)y = h(x). It differentiates the output along the system, with Lie derivatives, until the input appears. This happens at the relative degree rr, where y(r)=Lfrh(x)+LgLfr−1h(x) uy^{(r)} = L_f^r h(x) + L_g L_f^{r-1} h(x)\, u. Then the feedback u=(v−Lfrh(x))/LgLfr−1h(x)u = (v - L_f^r h(x)) / L_g L_f^{r-1} h(x) cancels the nonlinear terms and leaves y(r)=vy^{(r)} = v, a chain of rr integrators from the new input vv to the output. A linear law for vv 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 LgLfr−1h≠0L_g L_f^{r-1} h \neq 0 along the motion. It also hides n−rn - r 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 ff, g:U→Rng : U \to \mathbb{R}^n and h:U→Rh : U \to \mathbb{R} on an open set U⊆RnU \subseteq \mathbb{R}^n, and a point x0∈Ux_0 \in U. Smoothness makes f+guf + g u locally Lipschitz, so the solutions exist and are unique by the Picard-Lindelöf theorem. For the control law, also a reference yd(t)y_d(t) with rr continuous derivatives, and real numbers c0,…,cr−1c_0, \dots, c_{r-1} such that sr+cr−1sr−1+⋯+c0s^r + c_{r-1} s^{r-1} + \dots + c_0 is Hurwitz.

Output. One of three answers:

  • the relative degree rr at x0x_0, the functions ξi=Lfih\xi_i = L_f^i h for i=0,…,r−1i = 0, \dots, r - 1, a=LgLfr−1ha = L_g L_f^{r-1} h with a(x0)≠0a(x_0) \neq 0, and b=Lfrhb = L_f^r h, together with the feedback u(t,x)u(t, x) that makes the tracking error e=y−yde = y - y_d obey e(r)+cr−1e(r−1)+⋯+c0e=0e^{(r)} + c_{r-1} e^{(r-1)} + \dots + c_0 e = 0;
  • UNDEFINED, if no relative degree exists at x0x_0;
  • NO INPUT EFFECT, if LgLfkh=0L_g L_f^k h = 0 near x0x_0 for all k<nk < n, 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

  1. IO-LINEARIZE(f, g, h, x0)
  2. 1φ ← h; ξ ← empty list
  3. 2for k ← 0 to n - 1
  4. 3append φ to ξ ▷ now ξ[k] = L_f^k h
  5. 4a ← L_g φ
  6. 5if a(x0) ≠ 0
  7. 6b ← L_f φ
  8. 7return (r = k + 1, ξ, a, b)
  9. 8if a is not zero near x0 then return UNDEFINED
  10. 9φ ← L_f φ
  11. 10return NO INPUT EFFECT
  12. CONTROL(t, x) ▷ uses r, ξ, a, b, c, y_d
  13. 11v ← 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 kk, φ=Lfkh\varphi = L_f^k h, and every earlier LgLfjhL_g L_f^j h vanishes near x0x_0. So y(k)=φ(x)y^{(k)} = \varphi(x), and y(k+1)=Lfφ(x)+Lgφ(x) uy^{(k+1)} = L_f \varphi(x) + L_g \varphi(x)\, u. Line L4 takes the coefficient of uu. If it is not zero at x0x_0 (line L5), the relative degree is k+1k + 1 and line L6 takes the rest of the derivative. If it is zero at x0x_0 but not on a neighborhood of x0x_0 (line L8), no relative degree exists at x0x_0. Otherwise the input does not appear yet, and line L9 moves to the next derivative. The loop stops after nn passes at most, because a relative degree is never larger than nn.

Line L11 is the control law. It sets y(r)=vy^{(r)} = v and chooses vv as the reference term yd(r)y_d^{(r)} plus a linear feedback of the errors e(i)=ξ[i](x)−yd(i)(t)e^{(i)} = \xi[i](x) - y_d^{(i)}(t). It divides by a(x)a(x), so it is valid only while a(x)≠0a(x) \neq 0.

The implementation works with polynomial ff, gg and hh with exact rational coefficients, and it differentiates exactly. For a polynomial, "zero near x0x_0" 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

x˙1=x2,x˙2=x1x3−x23+(1+x12) u,x˙3=−x3+x12,y=x1,\dot x_1 = x_2, \qquad \dot x_2 = x_1 x_3 - x_2^3 + (1 + x_1^2)\, u, \qquad \dot x_3 = -x_3 + x_1^2, \qquad y = x_1,

and x0=0x_0 = 0. The algorithm runs as follows.

pass kk φ\varphi (line L3) a=Lgφa = L_g \varphi (line L4) a(x0)a(x_0) action
0 x1x_1 00 00 aa is the zero polynomial, line L9: φ←x2\varphi \leftarrow x_2
1 x2x_2 1+x121 + x_1^2 11 line L6: b=x1x3−x23b = x_1 x_3 - x_2^3, return r=2r = 2

So r=2r = 2, ξ=(x1,x2)\xi = (x_1, x_2), a=1+x12a = 1 + x_1^2 and b=x1x3−x23b = x_1 x_3 - x_2^3. Because a≥1a \ge 1 everywhere, the law at line L11 is defined at every state. The third state is internal. With yy held at zero it obeys x˙3=−x3\dot x_3 = -x_3, so the system is minimum phase.

Choose c0=2c_0 = 2 and c1=3c_1 = 3, so the error polynomial is s2+3s+2=(s+1)(s+2)s^2 + 3 s + 2 = (s + 1)(s + 2), and track yd=sin⁡ty_d = \sin t. Line L11 becomes

u=−sin⁡t−2(x1−sin⁡t)−3(x2−cos⁡t)−x1x3+x231+x12.u = \frac{-\sin t - 2 (x_1 - \sin t) - 3 (x_2 - \cos t) - x_1 x_3 + x_2^3}{1 + x_1^2}.

Start at x(0)=(1,0,0)x(0) = (1, 0, 0). Then e(0)=1e(0) = 1 and e˙(0)=0−1=−1\dot e(0) = 0 - 1 = -1, and the solution of e¨+3e˙+2e=0\ddot e + 3 \dot e + 2 e = 0 is exactly e(t)=e−te(t) = e^{-t}. A 4th order Runge-Kutta simulation with step 0.010.01, with the feedback evaluated inside the right side, gives:

tt x1x_1 x2x_2 x3x_3 e=x1−sin⁡te = x_1 - \sin t uu
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 e−te^{-t}: 0.36788=e−10.36788 = e^{-1}, 0.13534=e−20.13534 = e^{-2}, and so on. Over the whole run, x1x_1 differs from sin⁡t+e−t\sin t + e^{-t} by at most 4⋅10−104 \cdot 10^{-10}, which is the error of the integrator. The internal state x3x_3 stays bounded, because it is driven by x12x_1^2 through the stable dynamics x˙3=−x3\dot x_3 = -x_3.

Correctness

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

  • Termination. The loop runs at most nn times.
  • The three answers are right. At the start of pass kk, φ=Lfkh\varphi = L_f^k h and LgLfjhL_g L_f^j h vanishes near x0x_0 for j<kj < k. A return at line L7 then matches the definition of the relative degree. A return at line L8 is right, because no rr can satisfy the definition when LgLfkhL_g L_f^k h is zero at x0x_0 but not near it. A return at line L10 is right, because a relative degree is at most nn. That bound comes from the identity LadfjgLfih=(−1)jLgLfr−1hL_{\mathrm{ad}_f^j g} L_f^i h = (-1)^j L_g L_f^{r-1} h for i+j=r−1i + j = r - 1 (and 00 for i+j<r−1i + j < r - 1), proved by induction on jj with L[f,g]=LfLg−LgLfL_{[f,g]} = L_f L_g - L_g L_f. It makes an r×rr \times r matrix of rank rr that factors through Rn\mathbb{R}^n.
  • The closed loop. While the state stays where a≠0a \neq 0 and the lower LgLfkhL_g L_f^k h vanish, y(i)=ξ[i](x)y^{(i)} = \xi[i](x) for i<ri < r and y(r)=b(x)+a(x)u=vy^{(r)} = b(x) + a(x) u = v. So the error obeys e(r)+cr−1e(r−1)+⋯+c0e=0e^{(r)} + c_{r-1} e^{(r-1)} + \dots + c_0 e = 0.

The tests check the example, compare rr, aa and bb with the Markov parameters CAkBC A^{k} B and the rows CArC A^r for 60 random integer linear systems, check the Lie derivative against the slope of h(x0+tf(x0))h(x_0 + t f(x_0)) and the bracket identity on random polynomials, and check that the simulated error equals e−te^{-t} within 10−810^{-8}.

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 x˙=f(x)+g(x)u\dot x = f(x) + g(x) u, y=h(x)y = h(x), with x∈Ux \in U, an open subset of Rn\mathbb{R}^n, and ff, gg, hh of class C∞C^\infty on UU. For a function φ\varphi and a vector field XX, LXφ=∂φ∂xXL_X \varphi = \frac{\partial \varphi}{\partial x} X. The bracket is [f,g]=∂g∂xf−∂f∂xg[f, g] = \frac{\partial g}{\partial x} f - \frac{\partial f}{\partial x} g, and adf0g=g\mathrm{ad}_f^0 g = g, adfj+1g=[f,adfjg]\mathrm{ad}_f^{j+1} g = [f, \mathrm{ad}_f^j g].

The system has relative degree rr at x0x_0 if LgLfkh(x)=0L_g L_f^k h(x) = 0 for all xx in a neighborhood of x0x_0 and all k<r−1k < r - 1, and LgLfr−1h(x0)≠0L_g L_f^{r-1} h(x_0) \neq 0.

The test at line L8 asks whether a=Lgφa = L_g \varphi vanishes on a neighborhood of x0x_0. In the implementation ff, gg and hh are polynomials with rational coefficients, and the test is "aa 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 pp be a polynomial in nn variables that is zero on an open ball around x0x_0. Write q(z)=p(x0+z)q(z) = p(x_0 + z). This is a polynomial in zz, and its coefficient of zαz^\alpha is ∂αp(x0)/α!\partial^\alpha p(x_0) / \alpha!. All partial derivatives of pp at x0x_0 are zero, because pp is zero on a neighborhood of x0x_0. So qq is the zero polynomial, and so is p(x)=q(x−x0)p(x) = q(x - x_0). □\square

Lemma 2: the bracket identity

For a C2C^2 function φ\varphi and C1C^1 fields ff, gg: L[f,g]φ=LfLgφ−LgLfφL_{[f,g]} \varphi = L_f L_g \varphi - L_g L_f \varphi.

Proof. By the product rule,

LfLgφ=∑i,k∂2φ∂xi∂xkgkfi+∑i,k∂φ∂xk∂gk∂xifi.L_f L_g \varphi = \sum_{i,k} \frac{\partial^2 \varphi}{\partial x_i \partial x_k} g_k f_i + \sum_{i,k} \frac{\partial \varphi}{\partial x_k} \frac{\partial g_k}{\partial x_i} f_i.

Swap ff and gg and subtract. The second derivatives of φ\varphi are symmetric, so the first sums cancel. What remains is ∑k∂φ∂xk(∂g∂xf−∂f∂xg)k=L[f,g]φ\sum_k \frac{\partial \varphi}{\partial x_k} \left( \frac{\partial g}{\partial x} f - \frac{\partial f}{\partial x} g \right)_k = L_{[f,g]} \varphi. □\square

Lemma 3: the anti-triangular identity

Let VV be an open set on which LgLfkh=0L_g L_f^k h = 0 for k=0,…,r−2k = 0, \dots, r - 2. Then on VV, for all i,j≥0i, j \ge 0 with i+j≤r−1i + j \le r - 1,

LadfjgLfih={0if i+j≤r−2,(−1)jLgLfr−1hif i+j=r−1.L_{\mathrm{ad}_f^j g} L_f^i h = \begin{cases} 0 & \text{if } i + j \le r - 2, \\ (-1)^j L_g L_f^{r-1} h & \text{if } i + j = r - 1. \end{cases}

Proof. Induction on jj. For j=0j = 0 the claim is the hypothesis when i≤r−2i \le r - 2, and it is trivial when i=r−1i = r - 1. Suppose that it holds for jj, and let i+j+1≤r−1i + j + 1 \le r - 1. Lemma 2 with X=adfjgX = \mathrm{ad}_f^j g and φ=Lfih\varphi = L_f^i h gives

Ladfj+1gLfih=Lf(LadfjgLfih)−LadfjgLfi+1h.L_{\mathrm{ad}_f^{j+1} g} L_f^i h = L_f \left( L_{\mathrm{ad}_f^j g} L_f^i h \right) - L_{\mathrm{ad}_f^j g} L_f^{i+1} h.

In the first term i+j≤r−2i + j \le r - 2, so the function in the brackets is zero on the open set VV, and its derivative along ff is zero on VV too. In the second term the index sum is i+j+1i + j + 1. If i+j+1≤r−2i + j + 1 \le r - 2, the term is zero by the induction hypothesis. If i+j+1=r−1i + j + 1 = r - 1, the term is (−1)jLgLfr−1h(-1)^j L_g L_f^{r-1} h, and with the minus sign in front the result is (−1)j+1LgLfr−1h(-1)^{j+1} L_g L_f^{r-1} h. □\square

Lemma 4: a relative degree is at most nn

If the system has relative degree rr at x0x_0, then r≤nr \le n, and the row vectors dh(x0),dLfh(x0),…,dLfr−1h(x0)dh(x_0), dL_f h(x_0), \dots, dL_f^{r-1} h(x_0) are linearly independent.

Proof. Let VV be the neighborhood in the definition and a0=LgLfr−1h(x0)≠0a_0 = L_g L_f^{r-1} h(x_0) \neq 0. Let RR be the r×nr \times n matrix with rows dLfih(x0)dL_f^i h(x_0) and SS the n×rn \times r matrix with columns adfjg(x0)\mathrm{ad}_f^j g(x_0), for i,j=0,…,r−1i, j = 0, \dots, r - 1. The entry (i,j)(i, j) of RSR S is LadfjgLfih(x0)L_{\mathrm{ad}_f^j g} L_f^i h(x_0). By Lemma 3 it is zero when i+j≤r−2i + j \le r - 2 and (−1)ja0(-1)^j a_0 when i+j=r−1i + j = r - 1. So RSR S is zero above the anti-diagonal and has nonzero entries on it, and det⁡(RS)=±a0r≠0\det(R S) = \pm a_0^r \neq 0. Then r=rank⁡(RS)≤rank⁡R≤min⁡(r,n)r = \operatorname{rank}(R S) \le \operatorname{rank} R \le \min(r, n). So rank⁡R=r\operatorname{rank} R = r and r≤nr \le n. □\square

Termination

The loop at line L2 runs at most nn times. Each pass computes two Lie derivatives, one evaluation at x0x_0 and one zero test. For polynomials with rational coefficients each of these is a finite computation. So IO-LINEARIZE stops after at most nn passes.

Correctness of the three outcomes

Invariant: at the start of the pass with index kk, φ=Lfkh\varphi = L_f^k h, the list ξ\xi holds h,Lfh,…,Lfk−1hh, L_f h, \dots, L_f^{k-1} h, and LgLfjhL_g L_f^j h vanishes on a neighborhood of x0x_0 for every j<kj < k. It holds for k=0k = 0 by line L1. A pass that does not return reaches line L9 only when the test at line L8 says that a=LgLfkha = L_g L_f^k h vanishes near x0x_0, and line L9 sets φ=Lfk+1h\varphi = L_f^{k+1} h, so the invariant holds for k+1k + 1. For polynomials, "vanishes near x0x_0" and "is the zero polynomial" are the same by Lemma 1, and finitely many neighborhoods have an open intersection.

Return at line L7. Here LgLfjhL_g L_f^j h vanishes near x0x_0 for j<kj < k and LgLfkh(x0)≠0L_g L_f^k h(x_0) \neq 0. This is the definition with r=k+1r = k + 1. The returned ξ\xi is (h,…,Lfr−1h)(h, \dots, L_f^{r-1} h), a=LgLfr−1ha = L_g L_f^{r-1} h and b=Lfrhb = L_f^r h.

Return at line L8. Here LgLfjhL_g L_f^j h vanishes near x0x_0 for j<kj < k, LgLfkh(x0)=0L_g L_f^k h(x_0) = 0, and LgLfkhL_g L_f^k h does not vanish on any neighborhood of x0x_0. Suppose that the relative degree rr exists at x0x_0. If r−1<kr - 1 < k, then LgLfr−1h(x0)=0L_g L_f^{r-1} h(x_0) = 0, which is false. If r−1=kr - 1 = k, the same value is LgLfkh(x0)=0L_g L_f^k h(x_0) = 0, which is false. If r−1>kr - 1 > k, the definition makes LgLfkhL_g L_f^k h zero on a neighborhood of x0x_0, which is false. So no relative degree exists at x0x_0, and UNDEFINED is the correct answer.

Return at line L10. All nn passes ended at line L9, so LgLfkhL_g L_f^k h vanishes on a neighborhood WW of x0x_0 for k=0,…,n−1k = 0, \dots, n - 1. Suppose that the system has a relative degree rr at some point p∈Wp \in W. Then LgLfr−1h(p)≠0L_g L_f^{r-1} h(p) \neq 0, so r−1≥nr - 1 \ge n, which contradicts Lemma 4. So no point near x0x_0 has a relative degree. In the polynomial case WW is all of Rn\mathbb{R}^n. NO INPUT EFFECT is the correct answer.

The closed loop

Let IO-LINEARIZE return rr, ξ\xi, aa, bb, and let VV be an open neighborhood of x0x_0 on which LgLfkh=0L_g L_f^k h = 0 for k<r−1k < r - 1 and a(x)≠0a(x) \neq 0. Let ydy_d be rr times continuously differentiable. Line L11 applies

u=v−b(x)a(x),v=yd(r)(t)−∑i=0r−1ci(Lfih(x)−yd(i)(t)).u = \frac{v - b(x)}{a(x)}, \qquad v = y_d^{(r)}(t) - \sum_{i=0}^{r-1} c_i \left( L_f^i h(x) - y_d^{(i)}(t) \right).

On VV the closed-loop field is continuous in tt and C1C^1 in xx, so it is locally Lipschitz in xx, and the Picard-Lindelöf theorem gives one solution x(t)x(t) for as long as it stays in VV.

Along this solution, for i≤r−2i \le r - 2,

ddtLfih(x)=Lfi+1h(x)+LgLfih(x) u=Lfi+1h(x),\frac{d}{dt} L_f^i h(x) = L_f^{i+1} h(x) + L_g L_f^i h(x)\, u = L_f^{i+1} h(x),

so by induction y(i)=Lfih(x)y^{(i)} = L_f^i h(x) for i=0,…,r−1i = 0, \dots, r - 1. One more derivative gives y(r)=Lfrh(x)+LgLfr−1h(x) u=b(x)+a(x)u=vy^{(r)} = L_f^r h(x) + L_g L_f^{r-1} h(x)\, u = b(x) + a(x) u = v. Let e=y−yde = y - y_d. Then e(i)=Lfih(x)−yd(i)e^{(i)} = L_f^i h(x) - y_d^{(i)} for i<ri < r, and

e(r)=y(r)−yd(r)=v−yd(r)=−∑i=0r−1cie(i).e^{(r)} = y^{(r)} - y_d^{(r)} = v - y_d^{(r)} = -\sum_{i=0}^{r-1} c_i e^{(i)}.

So the error obeys e(r)+cr−1e(r−1)+⋯+c0e=0e^{(r)} + c_{r-1} e^{(r-1)} + \dots + c_0 e = 0 while the state stays in VV. Its characteristic polynomial is sr+cr−1sr−1+⋯+c0s^r + c_{r-1} s^{r-1} + \dots + c_0, and if this polynomial is Hurwitz, ee and its first r−1r - 1 derivatives go to zero exponentially. This says nothing about the other n−rn - r state coordinates. They must be checked separately, with the zero dynamics. ■\blacksquare

Complexity

Count operations on exact rationals as unit cost, as in the real RAM. A polynomial with pp terms in nn variables takes O(np)O(n p) space, for its exponent vectors.

  • One Lie derivative. Lfφ=∑i∂φ∂xifiL_f \varphi = \sum_i \frac{\partial \varphi}{\partial x_i} f_i takes nn partial derivatives, O(np)O(n p) each, and nn products of a polynomial with at most pp terms by one with at most qq terms. Each product forms pqp q exponent vectors of length nn. So one Lie derivative costs O(n2pq)O(n^2 p q).
  • The loop. Each pass computes at most two Lie derivatives and one evaluation at x0x_0, which costs O(np)O(n p). There are at most nn passes, so the time is O(n3pq)O(n^3 p q).
  • Space. The list ξ\xi holds at most nn polynomials of at most pp terms, so O(n2p)O(n^2 p).
  • The control law. Line L11 evaluates r+2r + 2 polynomials, O(n2p)O(n^2 p) per sample for the polynomial representation.

The number pp is the weak point. Each Lie derivative multiplies by the entries of ff, so the degree grows with kk 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 x0x_0, unlike a design on the Jacobian linearization.
  • Local. It needs the relative degree to exist and a(x)≠0a(x) \neq 0 along the motion. In the example a≥1a \ge 1, so the result is global for the output.
  • Model based. The feedback cancels b(x)b(x) and divides by a(x)a(x). Model errors leave terms that the linear law for vv 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, a(x0)≠0a(x_0) \neq 0 and the zero dynamics do not depend on the choice of coordinates.

Variants and improvements

  • Full-state linearization. If r=nr = n, there are no internal states. The coordinates (h,Lfh,…,Lfn−1h)(h, L_f h, \dots, L_f^{n-1} h) 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 r=nr = n exists.
  • Several inputs and outputs. With mm inputs and mm outputs, take rir_i derivatives of yiy_i. If the m×mm \times m decoupling matrix LgjLfri−1hiL_{g_j} L_f^{r_i - 1} h_i 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 M(q)q¨+C(q,q˙)q˙+G(q)=τM(q) \ddot q + C(q, \dot q) \dot q + G(q) = \tau with output qq, every joint has relative degree 2, and the decoupling matrix is M(q)−1M(q)^{-1}, which is always invertible. The feedback is the computed torque method.
  • Output feedback. The law needs ξ=(y,y˙,…,y(r−1))\xi = (y, \dot y, \dots, y^{(r-1)}). A high-gain observer estimates these derivatives from yy.
  • 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, LgLfr−1hL_g L_f^{r-1} h 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 x0x_0 but not near it is skipped. For x˙1=x2+x32\dot x_1 = x_2 + x_3^2, x˙2=x3\dot x_2 = x_3, x˙3=u\dot x_3 = u, y=x1y = x_1, pass 1 has a=2x3a = 2 x_3 with a(0)=0a(0) = 0, and the loop without line L8 goes on to report r=3r = 3 with a=1a = 1. But near 00 the input already appears in y¨=x3+2x3u\ddot y = x_3 + 2 x_3 u, 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 ydy_d whatever the internal state does. For A=[01−2−3]A = \begin{bmatrix} 0 & 1 \\ -2 & -3 \end{bmatrix}, B=[01]B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, C=[−11]C = \begin{bmatrix} -1 & 1 \end{bmatrix}, with G(s)=(s−1)/(s2+3s+2)G(s) = (s - 1)/(s^2 + 3 s + 2), r=1r = 1 and the zero dynamics are η˙=η\dot\eta = \eta. Holding y=0y = 0 makes x1x_1 grow like ete^t. Check the zero dynamics before you apply line L11.
  • Division by a small a(x)a(x). Line L11 divides by a(x)a(x). If the motion approaches a point where a=0a = 0, the input grows without bound. The result holds only on the region where a≠0a \neq 0. 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 uu is computed at samples and held, the cancellation is not exact. In the example, with the input held over each RK4 step of 0.010.01, the deviation of x1x_1 from sin⁡t+e−t\sin t + e^{-t} reaches 0.00320.0032; with a hold of 0.050.05 it reaches 0.0160.016. The error still decays, but it no longer equals e−te^{-t}.

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.

ctlsim.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example