Algorithm Search⌘K

Algorithmadvanced

Disturbance observer

Also called DOB, disturbance observer-based control.

Estimates a lumped disturbance from the input and the output through a nominal inverse model and a filter, and cancels it.

Time
O(n^2 + N n^2) worst
Space
O(n^2) extra
Where
N = the number of updates; n = the order of the filter (the degree of N plus k)
Properties
deterministicexactonlinerecursive
Origin
Kouhei Ohishi, Masato Nakao, Kouhei Ohnishi, Kunio Miyachi, 1987

A disturbance observer estimates an unknown signal dd that enters a plant together with the control input, so that y=P(s)(u+d)y = P(s)(u + d), and subtracts the estimate from the input. It uses a nominal model Pn(s)=N(s)/D(s)P_n(s) = N(s)/D(s) of the plant and a low-pass filter Q(s)Q(s) with Q(0)=1Q(0) = 1:

d^=Q(s)(Pn(s)−1y−u),u=uc−d^.\hat d = Q(s)\bigl(P_n(s)^{-1} y - u\bigr), \qquad u = u_c - \hat d.

Here ucu_c is the output of an outer controller. The term Pn−1yP_n^{-1} y is the input that the nominal plant needs to produce yy, so Pn−1y−uP_n^{-1} y - u is the part of the input that the model cannot explain. This lumped disturbance contains the external load and also the effect of the model error. The filter QQ makes QPn−1Q P_n^{-1} proper and sets the bandwidth of the estimate. A constant disturbance is removed with no steady-state error. An unknown input observer solves a different task: it estimates the state with an error that does not depend on dd, and it needs no filter, but it needs a state-space model and a rank condition. The state observer page compares the observers of this area.

In plain words

A motor must hold a speed, but an unknown load pulls on it. The disturbance observer asks a question at every instant: which input would a perfect motor need to move as the real one moves? The difference between that input and the input that was actually sent is the push of the unknown load. The observer smooths this difference, because the calculation needs a derivative of the measurement and would amplify noise. Then it subtracts the smoothed value from the next input, so the load is cancelled before the main controller has to react. The smoothing decides how fast the observer is and how much noise reaches the motor.

The problem

Input: the nominal plant Pn(s)=N(s)/D(s)P_n(s) = N(s)/D(s), strictly proper with relative degree r=deg⁡D−deg⁡N≥1r = \deg D - \deg N \ge 1 and with all roots of NN in the open left half plane, a time constant τ>0\tau > 0 and an integer order k≥rk \ge r. Output: a state-space realization (Af,Bf,Cf,Df)(A_f, B_f, C_f, D_f) of the two-input filter

d^=D(s) y−N(s) uN(s) (τs+1)k,\hat d = \frac{D(s)\, y - N(s)\, u}{N(s)\,(\tau s + 1)^k},

which is QPn−1y−QuQ P_n^{-1} y - Q u with Q(s)=1/(τs+1)kQ(s) = 1/(\tau s + 1)^k, and the update that runs it in the loop u=uc−d^u = u_c - \hat d.

The condition k≥rk \ge r makes the transfer function from yy proper. The condition on NN makes the filter stable: its poles are the roots of NN and −1/τ-1/\tau. A plant with a zero in the right half plane cannot be inverted in this way. The filter has no direct feedthrough from uu, so the loop u=uc−d^u = u_c - \hat d has no algebraic loop.

The algorithm

  1. DOB-DESIGN(N, D, tau, k)
  2. 1if k < deg D - deg N or N is not Hurwitz: fail ▷ Q P_n^(-1) improper, or unstable inverse
  3. 2a ← N (tau s + 1)^k, divided by its leading coefficient
  4. 3b_y ← D / lead; b_u ← -N / lead ▷ both padded to n + 1 coefficients, n = deg a
  5. 4A_f ← companion matrix of a in observable form; B_f, C_f, D_f from b_y and b_u
  6. 5return A_f, B_f, C_f, D_f
  7. UPDATE(x_f, y, u)
  8. 6x_f' ← A_f x_f + B_f [y; u] ▷ derivative of the filter state
  9. 7d_hat ← C_f x_f + D_f [y; u]
  10. 8u ← u_c - d_hat ▷ D_f has 0 in the u column

Line L1 checks the Hurwitz property of NN by the Routh test, which is exact in rational arithmetic. Line L4 builds the observable canonical form: AfA_f has −a1,…,−an-a_1, \dots, -a_n in its first column and ones on the superdiagonal, Cf=[1,0,…,0]C_f = [1, 0, \dots, 0], the direct term of each input is the leading coefficient β0\beta_0 of its numerator β\beta, and column ii of BfB_f holds βi−β0ai\beta_i - \beta_0 a_i. With k>rk > r the filter is strictly proper in both inputs. With k=rk = r it has a direct term from yy. In discrete time the same filter is discretized, for example by the zero-order hold or the bilinear transform.

Example

A motor with inertia JJ and an unknown load torque dd has Jω˙=u+dJ\dot\omega = u + d, so P(s)=1/(Js)P(s) = 1/(Js). The nominal model is Pn=1/(Jns)P_n = 1/(J_n s) with Jn=0.01J_n = 0.01, the filter is Q=1/(0.01s+1)Q = 1/(0.01 s + 1) (τ=0.01\tau = 0.01, k=1=rk = 1 = r), and the outer controller is uc=−0.5 ωu_c = -0.5\,\omega, which regulates the speed to 0. Lines L2 to L4 give

x˙f=−100 xf−100 ω−100 u,d^=xf+ω,\dot x_f = -100\, x_f - 100\, \omega - 100\, u, \qquad \hat d = x_f + \omega,

that is, d^=(s ω−100 u)/(s+100)\hat d = (s\,\omega - 100\, u)/(s + 100), which is Q(Jns ω−u)Q(J_n s\, \omega - u). A load step d=−0.1d = -0.1 at t=0t = 0 gives the speeds below. The estimate in the exact case is d^=−0.1(1−e−100t)\hat d = -0.1(1 - e^{-100 t}).

tt 0.01 0.02 0.05 0.1 0.2
no observer -0.079 -0.126 -0.184 -0.199 -0.200
observer, J=JnJ = J_n -0.048 -0.047 -0.015 -0.0013 -9.1e-6
observer, J=2JnJ = 2 J_n -0.034 -0.044 -0.023 0.00059 -2.7e-5

Without the observer the speed settles at −0.1/0.5=−0.2-0.1/0.5 = -0.2: the proportional controller leaves an offset. With the observer and J=JnJ = J_n the speed is ω(t)=−0.2(e−50t−e−100t)\omega(t) = -0.2(e^{-50t} - e^{-100t}), with its largest value −0.05-0.05 at t=ln⁡2/50≈0.014t = \ln 2/50 \approx 0.014, and it returns to 0. With the true inertia twice the nominal one, the closed loop has the poles −37.5±33.1i-37.5 \pm 33.1i, and the offset is still 0.

Correctness

With zero initial conditions and y=P(u+d)y = P(u + d), the estimate is d^=QPn−1P(u+d)−Qu\hat d = Q P_n^{-1} P(u + d) - Qu. If P=PnP = P_n, this is d^=Qd\hat d = Qd for every input uu. With u=uc−d^u = u_c - \hat d the output is

y=PPnPn+Q(P−Pn)(uc+(1−Q)d).y = \frac{P P_n}{P_n + Q(P - P_n)}\bigl(u_c + (1 - Q)d\bigr).

So the observer replaces dd by (1−Q)d(1 - Q)d, which is small where QQ is close to 1. At low frequency the plant seen by the outer controller is close to PnP_n. If the whole loop with the outer controller is stable, the transfer function from dd to yy has the factor (τs+1)k−1(\tau s + 1)^k - 1 in its numerator, which is 0 at s=0s = 0. By the final value theorem a constant disturbance leaves no offset, for every plant PP for which the loop is stable. The full proof, with the check of the realization of line L4, is in proofs/correctness.md. The tests compare the transfer function of the realization with the formula at random complex points, check d^=Qd\hat d = Qd in simulation, the zero offset with J=JnJ = J_n and J=2JnJ = 2J_n, a plant of relative degree 2, and the Routh test against known roots.

Proof: The disturbance observer realizes Q(P_n^(-1) y - u), estimates Q d for an exact model, and leaves no offset for a constant disturbancefull

Let Pn=N/DP_n = N/D with real polynomials NN, DD, r=deg⁡D−deg⁡N≥1r = \deg D - \deg N \ge 1, let τ>0\tau > 0, let k≥max⁡(r,1)k \ge \max(r, 1) be an integer, and let q(s)=(τs+1)kq(s) = (\tau s + 1)^k and Q=1/qQ = 1/q. All transfer functions below are for zero initial conditions.

Lemma 1: the realization

Let a(s)=sn+a1sn−1+⋯+ana(s) = s^n + a_1 s^{n-1} + \dots + a_n be monic, let β(s)=β0sn+β1sn−1+⋯+βn\beta(s) = \beta_0 s^n + \beta_1 s^{n-1} + \dots + \beta_n, and let AfA_f have −a1,…,−an-a_1, \dots, -a_n in its first column, ones on the superdiagonal and zeros elsewhere, Cf=[1,0,…,0]C_f = [1, 0, \dots, 0], bi=βi−β0aib_i = \beta_i - \beta_0 a_i. Then Cf(sI−Af)−1b+β0=β(s)/a(s)C_f(sI - A_f)^{-1} b + \beta_0 = \beta(s)/a(s).

Proof. Let w(s)=[sn−1,sn−2,…,1]/a(s)w(s) = [s^{n-1}, s^{n-2}, \dots, 1]/a(s). Column 1 of w(sI−Af)w(sI - A_f) is sw1+∑iaiwi=a(s)/a(s)=1s w_1 + \sum_i a_i w_i = a(s)/a(s) = 1. For j≥2j \ge 2, column jj is swj−wj−1=(s⋅sn−j−sn−j+1)/a(s)=0s w_j - w_{j-1} = (s \cdot s^{n-j} - s^{n-j+1})/a(s) = 0. So w(sI−Af)=Cfw(sI - A_f) = C_f, that is, Cf(sI−Af)−1=wC_f(sI - A_f)^{-1} = w for every ss that is not a root of aa. Then

Cf(sI−Af)−1b+β0=∑i=1n(βi−β0ai)sn−i+β0a(s)a(s)=β(s)a(s).□C_f(sI - A_f)^{-1} b + \beta_0 = \frac{\sum_{i=1}^n (\beta_i - \beta_0 a_i) s^{n-i} + \beta_0 a(s)}{a(s)} = \frac{\beta(s)}{a(s)}. \qquad \square

Lemma 2: the filter of lines L1 to L5

If line L1 passes, the realization of line L5 has the transfer function [D,−N]/(Nq)[D, -N]/(Nq) from [y,u][y, u] to d^\hat d, its poles are the roots of NN and −1/τ-1/\tau, all in the open left half plane, and its direct term from uu is 0. If k<rk < r or NN has a root with real part ≥0\ge 0, line L1 raises an error.

Proof. Line L2 sets a=Nq/ca = Nq/c, where cc is the leading coefficient of NqNq, so aa is monic of degree n=deg⁡N+kn = \deg N + k. Line L3 sets βy=D/c\beta_y = D/c and βu=−N/c\beta_u = -N/c. Since deg⁡D=deg⁡N+r≤n\deg D = \deg N + r \le n and deg⁡N=n−k<n\deg N = n - k < n, both fit into n+1n + 1 coefficients, and βu\beta_u has leading coefficient 0. By Lemma 1 the transfer functions are βy/a=D/(Nq)\beta_y/a = D/(Nq) and βu/a=−N/(Nq)\beta_u/a = -N/(Nq), and the direct term from uu is βu,0=0\beta_{u,0} = 0. The poles are the roots of aa.

Line L1 uses the Routh test. A real polynomial has all roots in the open left half plane if and only if all its coefficients and all entries of the first column of its Routh array are nonzero and of one sign (the Routh-Hurwitz criterion). The implementation returns false as soon as an entry is 0 or of the other sign. This is correct, because a zero entry in the first column occurs only if some root has real part ≥0\ge 0. □\square

Lemma 3: the estimate

If y=P(u+d)y = P(u + d), then d^=QPn−1P(u+d)−Qu\hat d = QP_n^{-1}P(u + d) - Qu. If P=PnP = P_n, then d^=Qd\hat d = Qd for every input uu.

Proof. By Lemma 2, d^=(Dy−Nu)/(Nq)=Q(Pn−1y−u)\hat d = (D y - N u)/(Nq) = Q(P_n^{-1} y - u). Substitute yy. If P=PnP = P_n, then Pn−1P=1P_n^{-1}P = 1 and d^=Q(u+d)−Qu=Qd\hat d = Q(u + d) - Qu = Qd. □\square

Lemma 4: the closed loop

Let u=uc−d^u = u_c - \hat d. Then

y=PPnPn+Q(P−Pn)(uc+(1−Q)d).y = \frac{P P_n}{P_n + Q(P - P_n)}\bigl(u_c + (1 - Q)d\bigr).

Proof. By Lemma 3, d^=QPn−1P(uc−d^+d)−Q(uc−d^)\hat d = QP_n^{-1}P(u_c - \hat d + d) - Q(u_c - \hat d). Multiply by PnP_n and collect d^\hat d:

d^ (Pn+Q(P−Pn))=Q(P−Pn)uc+QPd.\hat d\,\bigl(P_n + Q(P - P_n)\bigr) = Q(P - P_n)u_c + QPd.

Let Δ=Pn+Q(P−Pn)\Delta = P_n + Q(P - P_n). Then

u+d=uc−d^+d=Δuc−Q(P−Pn)uc+Δd−QPdΔ=Pnuc+(1−Q)PndΔ,u + d = u_c - \hat d + d = \frac{\Delta u_c - Q(P - P_n)u_c + \Delta d - QPd}{\Delta} = \frac{P_n u_c + (1 - Q)P_n d}{\Delta},

since Δ−QP=Pn−QPn\Delta - QP = P_n - QP_n. Multiply by PP. □\square

Theorem: no offset for a constant disturbance

Let P=Np/DpP = N_p/D_p and let the outer controller be uc=C(s)(yref−y)u_c = C(s)(y_{\mathrm{ref}} - y) with C=Nc/DcC = N_c/D_c. Write the transfer function from dd to yy as a ratio of polynomials. Its denominator is

χ=Dc(NDp(q−1)+NpD)+NcNpNq,\chi = D_c\bigl(N D_p (q - 1) + N_p D\bigr) + N_c N_p N q,

and its numerator is NpNDc(q−1)N_p N D_c (q - 1). If all roots of χ\chi lie in the open left half plane, then for a constant disturbance dd the output yy converges to its value for d=0d = 0.

Proof. With yref=0y_{\mathrm{ref}} = 0, Lemma 4 gives y=G(−Cy+(1−Q)d)y = G(-Cy + (1 - Q)d) with G=PPn/ΔG = PP_n/\Delta, so y=Td dy = T_d\, d with Td=G(1−Q)/(1+GC)T_d = G(1 - Q)/(1 + GC). Let M=NDp(q−1)+NpDM = N D_p (q - 1) + N_p D. Then

Δ=ND+1q(NpDp−ND)=NDpq+NpD−NDpDDpq=MDDpq,\Delta = \frac{N}{D} + \frac{1}{q}\Bigl(\frac{N_p}{D_p} - \frac{N}{D}\Bigr) = \frac{N D_p q + N_p D - N D_p}{D D_p q} = \frac{M}{D D_p q},

so G=NpNq/MG = N_p N q/M, G(1−Q)=NpN(q−1)/MG(1 - Q) = N_p N (q - 1)/M and GC=NpNqNc/(MDc)GC = N_p N q N_c/(M D_c). Hence

Td=NpN(q−1)/M(MDc+NcNpNq)/(MDc)=NpNDc(q−1)χ.T_d = \frac{N_p N (q - 1)/M}{(M D_c + N_c N_p N q)/(M D_c)} = \frac{N_p N D_c (q - 1)}{\chi}.

Every pole of TdT_d is a root of χ\chi, so it lies in the open left half plane. For d(s)=d0/sd(s) = d_0/s, the function s y(s)=Td(s)d0s\,y(s) = T_d(s) d_0 has no pole in the closed right half plane, and the final value theorem gives lim⁡t→∞y(t)=Td(0)d0\lim_{t \to \infty} y(t) = T_d(0) d_0. Since q(0)=1q(0) = 1, the numerator of TdT_d is 0 at s=0s = 0, so the limit is 0. □\square

With minimal realizations of PP, CC and the filter, χ\chi is the characteristic polynomial of the closed loop: its degree deg⁡Dp+deg⁡N+k+deg⁡Dc\deg D_p + \deg N + k + \deg D_c is the total number of states.

Remarks

  • The example. For P=1/(Js)P = 1/(Js), Pn=1/(Jns)P_n = 1/(J_n s), k=1k = 1 and C=kpC = k_p, M=s(Jτs+Jn)M = s(J\tau s + J_n) and χ=Jτs2+(Jn+kpτ)s+kp\chi = J\tau s^2 + (J_n + k_p\tau)s + k_p, which is Hurwitz for all positive parameters. The transfer function from dd to yy is τs/χ\tau s/\chi, and it is 0 at s=0s = 0.
  • Exact arithmetic. With int and Fraction data, lines L1 to L5 compute in Fraction, so the realization of the tests is exact.

Complexity

Let n=deg⁡N+kn = \deg N + k be the order of the filter. Line L1 costs O(n2)O(n^2) for the Routh test, line L2 costs O(nk)O(nk), and lines L3 and L4 cost O(n2)O(n^2) to fill the dense matrices. Each update costs O(n2)O(n^2) with the dense matrix AfA_f, or O(n)O(n) if the companion structure is used. The space is O(n2)O(n^2) for AfA_f, or O(n)O(n) with the companion structure.

Properties

  • Two-degree-of-freedom structure. The observer acts as an inner loop that makes the plant behave like PnP_n at low frequency. The outer controller is designed for PnP_n. The tracking response and the disturbance response can be tuned separately.
  • Sensitivity. In the inner loop 1−Q1 - Q plays the role of the sensitivity function and QQ the role of the complementary sensitivity. Measurement noise ν\nu enters the estimate as QPn−1νQP_n^{-1}\nu, so a wide bandwidth of QQ rejects dd better and passes more noise.
  • Relation to integral action. For Pn=1/(Jns)P_n = 1/(J_n s), Q=1/(τs+1)Q = 1/(\tau s + 1) and uc=−kpyu_c = -k_p y, the observer and the gain together are exactly the PI controller u=−(kp+Jn/τ)y−(kp/τ)∫y dtu = -(k_p + J_n/\tau)y - (k_p/\tau)\int y\,dt. The tests check this. The observer gives the integral action a physical meaning: the integral state is the load estimate.
  • Model error as disturbance. The lumped disturbance (Pn−1P−1)(u+d)+d(P_n^{-1}P - 1)(u + d) + d includes the effect of the model error, so the observer also reduces the effect of parameter changes at low frequency.

Variants and improvements

  • State-space form. Add a disturbance state with d˙=0\dot d = 0 to the model and design a Luenberger observer for the augmented system. This is the internal model principle applied to the estimator. Models such as d¨=−ω02d\ddot d = -\omega_0^2 d give observers for sinusoidal disturbances.
  • Extended state observer. Active disturbance rejection control treats the total unknown dynamics as one extra state of a chain of integrators and estimates it with a high-gain observer. It needs less model knowledge than the disturbance observer.
  • Higher-order filters. A larger kk or a filter with a numerator, such as a binomial filter with free numerator coefficients, makes 1−Q1 - Q small to a higher order at s=0s = 0, which also removes ramp disturbances.
  • Discrete time. The filter is discretized, or Pn−1P_n^{-1} is replaced by a one-step-ahead inverse of a discrete model. A delay in the loop is then explicit.
  • Nonlinear disturbance observers. For robot manipulators and other nonlinear plants, the estimate uses the nonlinear inverse dynamics. The overview of Chen, Yang, Guo and Li describes this family.

When to use it

Use a disturbance observer when a low-order nominal model is known, when the plant is minimum phase, and when the disturbances are slow compared with the achievable bandwidth. Typical cases are motion control of motors, positioning stages and robot joints, where load torques and friction act on the input. If the plant has a right-half-plane zero or a long delay, an internal model control design or an observer for an augmented state-space model is usually better. If the state, not the disturbance, is needed with an error independent of dd, use an unknown input observer.

Pitfalls

  • Bandwidth and noise. A small τ\tau gives a fast estimate but passes noise, because QPn−1Q P_n^{-1} approaches a derivative of order rr.
  • Robust stability of the inner loop. In the first-order example the inner loop is stable for every positive JJ and JnJ_n. For plants of higher relative degree, a large model error together with a small τ\tau can make the inner loop unstable. Check the characteristic polynomial of the whole loop, or use a small-gain argument with a bound on the model uncertainty.
  • Non-minimum-phase plants. Pn−1P_n^{-1} is unstable if NN has a root in the right half plane. The algorithm rejects such models.
  • Saturation. The cancellation u=uc−d^u = u_c - \hat d can ask for more input than the actuator gives. The filter then integrates a wrong residual. Use anti-windup measures.
  • Delay. A delay between uu and yy that PnP_n does not contain limits the usable bandwidth of QQ; see time-delay systems.

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
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()
disturbance_observer.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/disturbance-observer/. The authors are listed in prov/1HYDAN.jsonl.

"""Disturbance observer (DOB) for a single-input single-output plant.

The plant is y = P(s) (u + d) with an unknown input disturbance d. The
nominal model is P_n(s) = N(s) / D(s), strictly proper, with a stable
numerator N (minimum phase). The observer estimates d by

    d_hat = Q(s) (P_n(s)^(-1) y - u) = (D(s) y - N(s) u) / (N(s) (tau s + 1)^k),

with the low-pass filter Q(s) = 1 / (tau s + 1)^k. Q P_n^(-1) is proper
when k is at least the relative degree r = deg D - deg N. The control
u = u_c - d_hat cancels the low-frequency part of d. If P = P_n, then
d_hat = Q d exactly.

dob_filter returns a state-space realization (Af, Bf, Cf, Df) of the
two-input filter [y, u] -> d_hat in observable canonical form. Since
k >= 1, there is no direct feedthrough from u, so u = u_c - d_hat has no
algebraic loop. There is a direct feedthrough from y when k = r.
"""

from fractions import Fraction

from ctlmat import matvec, polymul

__all__ = ["dob_filter", "filter_rhs", "filter_output", "compensate", "q_filter", "is_hurwitz"]


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:])


def is_hurwitz(p):
    """Return True if every root of the real polynomial p has negative real part.

    Routh test: all coefficients must have one sign, and every entry of the
    first column of the Routh array must have that sign. A zero entry means a
    root on or to the right of the imaginary axis. Exact with int and Fraction
    coefficients.
    """
    p = _strip(p)
    if p[0] == 0:
        raise ValueError("zero polynomial")
    exact = all(isinstance(v, (int, Fraction)) for v in p)
    p = [Fraction(v) if exact else v for v in p]
    if p[0] < 0:
        p = [-v for v in p]
    if any(v <= 0 for v in p):
        return False
    r0, r1 = p[0::2], p[1::2]
    while r1:
        if r1[0] <= 0:
            return False
        f = r0[0] / r1[0]
        new = [r0[i + 1] - f * (r1[i + 1] if i + 1 < len(r1) else 0) for i in range(len(r0) - 1)]
        r0, r1 = r1, new
    return True


def q_filter(tau, k):
    """Return the denominator (tau s + 1)^k of Q(s) as a coefficient list."""
    p = [1]
    for _ in range(k):
        p = polymul(p, [tau, 1])
    return p


def dob_filter(num, den, tau, k):
    """Return (Af, Bf, Cf, Df) of d_hat = (D y - N u) / (N (tau s + 1)^k).

    num and den are N and D, highest power first. Inputs of the filter are
    [y, u]; the output is d_hat. Raises ValueError if tau <= 0, if k is
    less than the relative degree or less than 1, or if N has a root with
    real part >= 0.
    """
    N, D = _strip(num), _strip(den)
    if tau <= 0:
        raise ValueError("tau must be positive")
    r = (len(D) - 1) - (len(N) - 1)
    if r < 1:
        raise ValueError("the nominal plant must be strictly proper")
    if k < r or k < 1:  # @line L1
        raise ValueError("k must be at least the relative degree, or Q P_n^(-1) is not proper")
    if not is_hurwitz(N):
        raise ValueError("N(s) must be stable: P_n^(-1) would be unstable")
    a = polymul(N, q_filter(tau, k))  # @line L2
    n = len(a) - 1
    lead = a[0]
    exact = all(isinstance(v, (int, Fraction)) for v in a + D + N)
    div = (lambda v: Fraction(v) / Fraction(lead)) if exact else (lambda v: v / lead)
    a = [div(v) for v in a]
    by = [0] * (n + 1 - len(D)) + [div(v) for v in D]  # @line L3
    bu = [0] * (n + 1 - len(N)) + [-div(v) for v in N]
    Af = [[-a[i + 1] if j == 0 else (1 if j == i + 1 else 0) for j in range(n)] for i in range(n)]  # @line L4
    Bf, Df = [], []
    cols = []
    for b in (by, bu):
        d0 = b[0]  # coefficient of s^n: the direct feedthrough
        cols.append([b[i + 1] - d0 * a[i + 1] for i in range(n)])
        Df.append(d0)
    Bf = [[cols[0][i], cols[1][i]] for i in range(n)]
    Cf = [1] + [0] * (n - 1)
    return Af, Bf, Cf, Df  # @line L5


def filter_rhs(Af, Bf):
    """Return f(t, xf, (y, u)) = Af xf + Bf [y, u]."""
    def f(t, xf, yu):
        y, u = yu
        return [a + b0 * y + b1 * u for a, (b0, b1) in zip(matvec(Af, xf), Bf)]  # @line L6
    return f


def filter_output(Cf, Df, xf, y, u):
    """Return d_hat = Cf xf + Df [y, u]."""
    return sum(c * x for c, x in zip(Cf, xf)) + Df[0] * y + Df[1] * u  # @line L7


def compensate(u_c, d_hat):
    """Return the plant input u = u_c - d_hat."""
    return u_c - d_hat  # @line L8
test_disturbance_observer.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/disturbance-observer/. The authors are listed in prov/1HYDAN.jsonl.

import math
import random
from fractions import Fraction

import pytest

import ctlmat as cm
from ctlsim import simulate
from disturbance_observer import compensate, dob_filter, filter_output, filter_rhs, is_hurwitz, q_filter


def tf_of_realization(Af, Bf, Cf, Df, s):
    """Return the two transfer functions [y -> d_hat, u -> d_hat] at the complex point s."""
    n = len(Af)
    M = [[(s if i == j else 0) - Af[i][j] for j in range(n)] for i in range(n)]
    out = []
    for j in range(2):
        x = cm.solve([[complex(v) for v in r] for r in M], [complex(Bf[i][j]) for i in range(n)])
        out.append(sum(c * v for c, v in zip(Cf, x)) + Df[j])
    return out


def test_transfer_function_matches_formula():
    rng = random.Random(10)
    cases = [
        ([1], [Fraction(1, 100), 0], Fraction(1, 100), 1),  # 1 / (J s)
        ([1], [1, 2, 0], Fraction(1, 10), 2),  # 1 / (s^2 + 2 s), k = r
        ([1], [1, 2, 0], Fraction(1, 10), 3),  # k > r
        ([1, 3], [1, 4, 5, 2], Fraction(1, 5), 2),  # (s + 3) / (s^3 + 4 s^2 + 5 s + 2)
    ]
    for N, D, tau, k in cases:
        Af, Bf, Cf, Df = dob_filter(N, D, tau, k)
        den = cm.polymul(N, q_filter(tau, k))
        assert len(Af) == len(den) - 1
        assert Df[1] == 0  # no feedthrough from u
        for _ in range(5):
            s = complex(rng.uniform(-3, 3), rng.uniform(-3, 3))
            got = tf_of_realization(Af, Bf, Cf, Df, s)
            want_y = cm.polyval(D, s) / cm.polyval(den, s)
            want_u = -cm.polyval(N, s) / cm.polyval(den, s)
            assert abs(got[0] - want_y) < 1e-9 * (1 + abs(want_y))
            assert abs(got[1] - want_u) < 1e-9 * (1 + abs(want_u))


def test_feedthrough_from_y_only_when_k_equals_r():
    assert dob_filter([1], [1, 2, 0], 1, 2)[3][0] != 0
    assert dob_filter([1], [1, 2, 0], 1, 3)[3][0] == 0


def motor_run(J, Jn, tau, kp, load, t1, use_dob, k=1, t_on=0.05):
    """Speed loop for J w' = u + d with u_c = kp (r - w), r = 0, d = -load for t >= t_on."""
    Af, Bf, Cf, Df = dob_filter([1], [Jn, 0], tau, k)
    Af = [[float(v) for v in r] for r in Af]
    Bf = [[float(v) for v in r] for r in Bf]
    Cf = [float(v) for v in Cf]
    Df = [float(v) for v in Df]
    frhs = filter_rhs(Af, Bf)
    nf = len(Af)

    def d(t):
        return -load if t >= t_on else 0.0

    def control(w, xf):
        uc = kp * (0.0 - w)
        if not use_dob:
            return uc, 0.0
        dh = filter_output(Cf, Df, xf, w, 0.0)  # Df[1] = 0, so u is not needed
        return compensate(uc, dh), dh

    def f(t, s, _):
        w, xf = s[0], s[1:]
        u, _dh = control(w, xf)
        return [(u + d(t)) / J] + frhs(t, xf, (w, u))

    ts, ss, _ = simulate(f, [0.0] * (1 + nf), 0.0, t1, 0.0005)
    dhs = [control(s[0], s[1:])[1] for s in ss]
    return ts, [s[0] for s in ss], dhs


def test_estimate_is_filtered_disturbance_when_model_is_exact():
    tau, J = 0.01, 0.01
    # the load acts from t = 0, so no RK4 step crosses a jump of d
    ts, ws, dhs = motor_run(J, J, tau, 0.5, 0.1, 0.2, True, t_on=0.0)
    assert min(ws) < -1e-3  # the speed moves, so the estimate is not trivial
    for t, dh in zip(ts, dhs):
        want = -0.1 * (1 - math.exp(-t / tau))
        assert abs(dh - want) < 1e-7  # RK4 error with dt = tau / 20


def test_offset_removed():
    J, tau, kp, load = 0.01, 0.01, 0.5, 0.1
    _, ws, _ = motor_run(J, J, tau, kp, load, 1.0, False)
    assert abs(ws[-1] - (-load / kp)) < 1e-6  # offset 0.2 rad/s without the observer
    _, ws, _ = motor_run(J, J, tau, kp, load, 1.0, True)
    assert abs(ws[-1]) < 1e-6
    # the true inertia is twice the nominal one: still no offset
    _, ws, _ = motor_run(2 * J, J, tau, kp, load, 2.0, True)
    assert abs(ws[-1]) < 1e-6


def test_equivalent_to_pi_for_first_order_case():
    # DOB with P_n = 1 / (Jn s), Q = 1 / (tau s + 1) and u_c = -kp w is the PI
    # controller u = -(kp + Jn / tau) w - (kp / tau) * integral of w.
    J, Jn, tau, kp = 0.02, 0.01, 0.01, 0.5
    ts, ws, _ = motor_run(J, Jn, tau, kp, 0.1, 0.3, True, t_on=0.0)
    Kp, Ki = kp + Jn / tau, kp / tau

    def f(t, s, _):
        w, z = s
        return [(-Kp * w - Ki * z - 0.1) / J, w]

    _, ss, _ = simulate(f, [0.0, 0.0], 0.0, 0.3, 0.0005)
    assert max(abs(a - b[0]) for a, b in zip(ws, ss)) < 1e-9


def test_higher_order_plant_constant_disturbance():
    # P = P_n = 1 / (s^2 + 2 s), k = 2: d_hat = Q d, so d_hat tends to d.
    N, D, tau, k = [1], [1, 2, 0], 0.05, 2
    Af, Bf, Cf, Df = dob_filter(N, D, tau, k)
    Af = [[float(v) for v in r] for r in Af]
    Bf = [[float(v) for v in r] for r in Bf]
    frhs = filter_rhs(Af, Bf)

    def f(t, s, _):
        x1, x2, xf = s[0], s[1], s[2:]
        u = math.sin(3 * t)
        d = 0.7
        return [x2, -2 * x2 + u + d] + frhs(t, xf, (x1, u))

    ts, ss, _ = simulate(f, [0.0] * (2 + len(Af)), 0.0, 1.0, 0.001)
    s = ss[-1]
    dh = filter_output(Cf, [float(v) for v in Df], s[2:], s[0], math.sin(3 * ts[-1]))
    want = 0.7 * (1 - math.exp(-1.0 / tau) * (1 + 1.0 / tau))  # step response of 1 / (tau s + 1)^2
    assert abs(dh - want) < 1e-6


def test_is_hurwitz_against_roots():
    rng = random.Random(11)
    assert is_hurwitz([1, 2, 3, 4])  # 2 * 3 > 4
    assert not is_hurwitz([1, 1, 1, 1])  # roots -1 and +-i
    assert not is_hurwitz([1, 0, 1])
    assert is_hurwitz([5]) and is_hurwitz([-1, -3, -2])
    for _ in range(200):
        m = rng.randint(1, 5)
        roots = []
        while len(roots) < m:
            re = rng.choice([-3, -2, -1, 1, 2]) * rng.randint(1, 3)
            if len(roots) <= m - 2 and rng.random() < 0.5:
                im = rng.randint(1, 3)
                roots += [complex(re, im), complex(re, -im)]
            else:
                roots.append(complex(re, 0))
        p = [1]
        for z in roots:
            p = cm.polymul(p, [1, -z])
        p = [int(round(c.real)) for c in p]
        assert is_hurwitz(p) == all(z.real < 0 for z in roots)


def test_rejections():
    with pytest.raises(ValueError):
        dob_filter([1, 1, 1, 1], [1, 0, 0, 0, 0], 0.1, 1)  # N has the roots +-i
    with pytest.raises(ValueError):
        dob_filter([1], [1, 2, 0], 0.1, 1)  # k < relative degree
    with pytest.raises(ValueError):
        dob_filter([1], [1, 0], 0, 1)  # tau = 0
    with pytest.raises(ValueError):
        dob_filter([1, -1], [1, 2, 3], 0.1, 1)  # N has the root s = 1
    with pytest.raises(ValueError):
        dob_filter([1, 1], [1, 2], 0.1, 1)  # not strictly proper

History

Ohnishi and his coworkers developed the disturbance observer for motion control of DC motors in the 1980s. Ohishi, Nakao, Ohnishi and Miyachi (1987) used it to make a position servo insensitive to the load. The method spread to hard disk drives, robot joints and many other motion systems. Chen, Yang, Guo and Li (2016) surveyed disturbance-observer-based control and its relation to the extended state observer and other methods.

References

  1. Kouhei Ohishi, Masato Nakao, Kouhei Ohnishi and Kunio Miyachi, Microprocessor-controlled DC motor for load-insensitive position servo system, IEEE Transactions on Industrial Electronics 34(1), 44-49, 1987, the disturbance observer of the DC motor and the cancellation of the load torque
  2. Wen-Hua Chen, Jun Yang, Lei Guo and Shihua Li, Disturbance-observer-based control and related methods, an overview, IEEE Transactions on Industrial Electronics 63(2), 1083-1095, 2016, the frequency-domain disturbance observer with a Q filter, and its relation to other disturbance estimation methods

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
  • at least three sources
  • a scene preset for the example