Algorithm Search⌘K

Algorithmresearch

Active disturbance rejection control

Also called ADRC, extended state observer.

Lumps unknown dynamics and disturbances into one extra state, estimates it with an observer of the extended state and cancels it in the control law.

Time
O(n) worst
Space
O(n) extra
Where
n = the order of the plant
Properties
deterministicexactonlineiterative
Origin
Jingqing Han, Zhiqiang Gao, Bao Zhu Guo, Zhi Liang Zhao, 1998

Active disturbance rejection control (ADRC) treats everything in a plant that the designer does not want to model as one signal, the total disturbance, and adds it to the state as an extra component. An observer of this extended state, which is a high-gain observer with one more integrator, estimates the total disturbance from the output. The control law subtracts the estimate and then applies a simple law, such as PD, to what is left: a chain of integrators. The only model data it needs are the order of the plant and a rough value b0b_0 of the input gain. Its linear form has two tuning parameters, the bandwidths of the observer and of the controller.

In plain words

Suppose you push a cart and do not know its friction, its springs, or the wind. Lump all of these into one unknown force. You know how hard you push and you see where the cart goes, so you can work out the unknown force from the difference between how the cart actually moves and how it would move if you were the only one pushing. Once you know the force, push against it, so it cancels. What is left is a cart with no friction, no spring and no wind, which is easy to control. The faster you work out the force, the better the cancellation, but the more the noise on your measurement shakes your push.

The problem

Input. A plant of order two (the method extends to order nn)

y¨=f(t,y,y˙)+bu,\ddot y = f(t, y, \dot y) + b u,

where yy is measured, ff is unknown, and the input gain bb is known only as an estimate b0b_0 of the same sign. A reference rr, a controller bandwidth ωc>0\omega_c > 0 and an observer bandwidth ωo>0\omega_o > 0. A common rule of thumb takes ωo\omega_o several times ωc\omega_c, so that the observer is faster than the loop.

Output. A control u(t)u(t) such that yy follows the response of the PD loop y¨=ωc2(r−y)−2ωcy˙\ddot y = \omega_c^2 (r - y) - 2 \omega_c \dot y, with an error that shrinks as ωo\omega_o grows, and with no steady error for a constant disturbance.

The trick is to write the plant as y¨=F+b0u\ddot y = F + b_0 u, with the total disturbance F=f+(b−b0)uF = f + (b - b_0) u. The extended state is x=(y,y˙,F)x = (y, \dot y, F), with x˙3=F˙\dot x_3 = \dot F unknown.

The algorithm

  1. ADRC-CONTROL(z, r, ω_c, b_0)
  2. 1u_0 ← ω_c² (r - z_1) - 2 ω_c z_2
  3. 2return (u_0 - z_3) / b_0
  4. ADRC-OBSERVER(z, y, u, ω_o, b_0)
  5. 3e ← y - z_1
  6. 4ż_1 ← z_2 + 3 ω_o e
  7. 5ż_2 ← z_3 + 3 ω_o² e + b_0 u
  8. 6ż_3 ← ω_o³ e
  9. 7return ż

Lines L1 and L2 cancel the estimate z3z_3 of FF and apply PD with both poles at −ωc-\omega_c. Lines L3 to L6 are the observer of the extended state, with the gains (3ωo,3ωo2,ωo3)(3 \omega_o, 3 \omega_o^2, \omega_o^3) that put all three of its poles at −ωo-\omega_o. In a sampled implementation, the control is computed at each sample and held, and the observer is integrated over the sample period, or replaced by a discrete observer obtained by zero-order hold discretization.

Example

The plant is y¨=−y−0.5y˙+d(t)+2u\ddot y = -y - 0.5 \dot y + d(t) + 2 u with a step disturbance d=1d = 1 for t≥5t \ge 5. The controller knows none of this, except b0=1.5b_0 = 1.5 (the true bb is 22). The reference is r=1r = 1, ωc=2\omega_c = 2 (so u0=4(r−z1)−4z2u_0 = 4 (r - z_1) - 4 z_2), and ωo=10\omega_o = 10, all states start at 00. The simulation uses 4th order Runge-Kutta with step 0.0020.002, with the control computed once per step and held.

tt yy z3z_3
0.5 0.26861 -0.04604
1 0.55035 -0.55420
2 0.87203 -0.76846
3 0.97251 -0.76831
5 0.99981 -0.75163
5.5 1.04458 -0.14171
6 1.04424 -0.07094
8 1.00524 0.00093
10 1.00016 0.00027

At rest at y=1y = 1 the plant needs u=(1−d)/2u = (1 - d)/2, so the total disturbance is F=−1+0.5uF = -1 + 0.5 u: −0.75-0.75 before the step and 00 after it. The estimate z3z_3 follows these values. After the step, yy moves away from 11 by at most 0.04770.0477 and returns, with no steady error. The first control is u(0)=4/1.5=2.667u(0) = 4 / 1.5 = 2.667.

The ideal response is that of the PD loop, y=1−(1+2t)e−2ty = 1 - (1 + 2t) e^{-2t}. The largest deviation from it on [0,5)[0, 5) is 0.05140.0514 for ωo=10\omega_o = 10, 0.02410.0241 for ωo=20\omega_o = 20 and 0.01130.0113 for ωo=40\omega_o = 40 (measurement): it falls roughly like 1/ωo1/\omega_o.

Correctness

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

  • Lemma (observer error). The error e=x−ze = x - z obeys e˙1=e2−3ωoe1\dot e_1 = e_2 - 3 \omega_o e_1, e˙2=e3−3ωo2e1\dot e_2 = e_3 - 3 \omega_o^2 e_1, e˙3=F˙−ωo3e1\dot e_3 = \dot F - \omega_o^3 e_1, for any control. The tests check it exactly.
  • Theorem (size of the error). If ∣F˙∣≤M|\dot F| \le M along the motion, then after a transient, ∣e3∣=O(M/ωo)|e_3| = O(M / \omega_o), ∣e2∣=O(M/ωo2)|e_2| = O(M / \omega_o^2), ∣e1∣=O(M/ωo3)|e_1| = O(M / \omega_o^3). This is the bound of the high-gain observer with ε=1/ωo\varepsilon = 1/\omega_o.
  • Theorem (perturbed PD loop). y~=y−r\tilde y = y - r obeys y~¨+2ωcy~˙+ωc2y~=e3+2ωce2+ωc2e1\ddot{\tilde y} + 2 \omega_c \dot{\tilde y} + \omega_c^2 \tilde y = e_3 + 2 \omega_c e_2 + \omega_c^2 e_1 exactly, so the deviation from the PD loop is at most sup⁡∣e3+2ωce2+ωc2e1∣/ωc2\sup |e_3 + 2 \omega_c e_2 + \omega_c^2 e_1| / \omega_c^2 after the transient.
  • Theorem (separation). With f=0f = 0 and b=b0b = b_0, the closed loop has the poles −ωc-\omega_c (twice) and −ωo-\omega_o (three times). The tests check this exactly for random values.
  • Theorem (exact rejection). For a linear plant with a constant disturbance, if the closed loop is Hurwitz, then y→ry \to r, because z3z_3 acts as an integrator. For the example, the Routh-Hurwitz criterion confirms that the loop is Hurwitz, exactly.

The bound ∣F˙∣≤M|\dot F| \le M is not free when b≠b0b \neq b_0, since FF contains uu. For linear plants it follows from the Hurwitz test; for nonlinear plants, Guo and Zhao (2011) prove convergence under bounds on ff, its derivatives and b−b0b - b_0.

Proof: The observer of linear ADRC estimates the total disturbance with an error of order 1 over its bandwidth, and the loop rejects constant disturbances exactlyfull

The plant is y¨=f(t,y,y˙)+bu\ddot y = f(t, y, \dot y) + b u with ff unknown and bb known only as b0≠0b_0 \neq 0. Write it as

y¨=F+b0u,F=f(t,y,y˙)+(b−b0)u,\ddot y = F + b_0 u, \qquad F = f(t, y, \dot y) + (b - b_0) u,

where FF is the total disturbance. Lines L1 to L7 compute

u=ωc2(r−z1)−2ωcz2−z3b0,z˙1=z2+3ωo(y−z1),z˙2=z3+3ωo2(y−z1)+b0u,z˙3=ωo3(y−z1),u = \frac{\omega_c^2 (r - z_1) - 2 \omega_c z_2 - z_3}{b_0}, \qquad \begin{aligned} \dot z_1 &= z_2 + 3 \omega_o (y - z_1), \\ \dot z_2 &= z_3 + 3 \omega_o^2 (y - z_1) + b_0 u, \\ \dot z_3 &= \omega_o^3 (y - z_1), \end{aligned}

with ωc,ωo>0\omega_c, \omega_o > 0 and a constant reference rr. Let x=(y,y˙,F)x = (y, \dot y, F) and e=x−ze = x - z. Here ∥⋅∥\|\cdot\| is the Euclidean norm.

Lemma 1: the observer error equation

If FF is absolutely continuous in tt along the motion, then for almost every tt

e˙1=e2−3ωoe1,e˙2=e3−3ωo2e1,e˙3=F˙−ωo3e1.\dot e_1 = e_2 - 3 \omega_o e_1, \qquad \dot e_2 = e_3 - 3 \omega_o^2 e_1, \qquad \dot e_3 = \dot F - \omega_o^3 e_1.

Proof. x˙1=y˙=x2\dot x_1 = \dot y = x_2, x˙2=y¨=F+b0u\dot x_2 = \ddot y = F + b_0 u, x˙3=F˙\dot x_3 = \dot F. Subtract the observer, using y−z1=e1y - z_1 = e_1: e˙1=x2−z2−3ωoe1\dot e_1 = x_2 - z_2 - 3 \omega_o e_1, e˙2=F+b0u−z3−3ωo2e1−b0u=e3−3ωo2e1\dot e_2 = F + b_0 u - z_3 - 3 \omega_o^2 e_1 - b_0 u = e_3 - 3 \omega_o^2 e_1, e˙3=F˙−ωo3e1\dot e_3 = \dot F - \omega_o^3 e_1. □\square

The input uu cancels, so the error equation does not depend on the control law. The tests check Lemma 1 exactly in Fraction for 200 random cases.

Theorem 1: the size of the estimation error

Let η=(ωo2e1,ωoe2,e3)\eta = (\omega_o^2 e_1, \omega_o e_2, e_3). Then η˙=ωoA1η+BF˙\dot \eta = \omega_o A_1 \eta + B \dot F with

A1=(−310−301−100),B=(0,0,1)T,A_1 = \begin{pmatrix} -3 & 1 & 0 \\ -3 & 0 & 1 \\ -1 & 0 & 0 \end{pmatrix}, \qquad B = (0, 0, 1)^T,

and det⁡(sI−A1)=(s+1)3\det(sI - A_1) = (s + 1)^3. Let P1=P1T>0P_1 = P_1^T > 0 solve P1A1+A1TP1=−IP_1 A_1 + A_1^T P_1 = -I, let λ1,λ2\lambda_1, \lambda_2 be its smallest and largest eigenvalues, and β=∥P1B∥\beta = \|P_1 B\|; these numbers depend only on A1A_1. If ∣F˙(t)∣≤M|\dot F(t)| \le M on [0,t1)[0, t_1), then for t∈[0,t1)t \in [0, t_1)

∥η(t)∥≤λ2λ1(∥η(0)∥e−ωot/(4λ2)+4βMωo).\|\eta(t)\| \le \sqrt{\frac{\lambda_2}{\lambda_1}} \left( \|\eta(0)\| e^{-\omega_o t / (4 \lambda_2)} + \frac{4 \beta M}{\omega_o} \right).

So after a transient of length O(ln⁡(ωo)/ωo)O(\ln(\omega_o) / \omega_o), ∣e3∣=O(M/ωo)|e_3| = O(M / \omega_o), ∣e2∣=O(M/ωo2)|e_2| = O(M / \omega_o^2) and ∣e1∣=O(M/ωo3)|e_1| = O(M / \omega_o^3).

Proof. From Lemma 1, η˙1=ωo2(e2−3ωoe1)=ωo(η2−3η1)\dot \eta_1 = \omega_o^2 (e_2 - 3 \omega_o e_1) = \omega_o (\eta_2 - 3 \eta_1), η˙2=ωo(e3−3ωo2e1)=ωo(η3−3η1)\dot \eta_2 = \omega_o (e_3 - 3 \omega_o^2 e_1) = \omega_o (\eta_3 - 3 \eta_1), η˙3=F˙−ωoη1\dot \eta_3 = \dot F - \omega_o \eta_1. A1A_1 is the companion matrix of s3+3s2+3s+1=(s+1)3s^3 + 3 s^2 + 3 s + 1 = (s + 1)^3, so it is Hurwitz. With ε=1/ωo\varepsilon = 1/\omega_o this is the scaled error equation εη˙=A1η+εBF˙\varepsilon \dot \eta = A_1 \eta + \varepsilon B \dot F of a high-gain observer of order 33 with δ=F˙\delta = \dot F, and Theorem 1 of that page's proof gives the bound. □\square

The bound needs ∣F˙∣≤M|\dot F| \le M along the motion. F˙\dot F contains (b−b0)u˙(b - b_0) \dot u, and u˙\dot u contains z˙3=ωo3e1\dot z_3 = \omega_o^3 e_1, so for b≠b0b \neq b_0 the bound is not given in advance; it must come from an analysis of the closed loop, such as Theorem 3 for linear plants, or the nonlinear analysis of Guo and Zhao (2011), which this page cites and does not reprove.

Theorem 2: the closed loop as a perturbed PD loop

Let y~=y−r\tilde y = y - r. Then

y~¨+2ωcy~˙+ωc2y~=e3+2ωce2+ωc2e1.\ddot{\tilde y} + 2 \omega_c \dot{\tilde y} + \omega_c^2 \tilde y = e_3 + 2 \omega_c e_2 + \omega_c^2 e_1.

Proof. b0u=ωc2(r−z1)−2ωcz2−z3b_0 u = \omega_c^2 (r - z_1) - 2 \omega_c z_2 - z_3, and zi=xi−eiz_i = x_i - e_i. So y¨=F+b0u=F+ωc2(r−y+e1)−2ωc(y˙−e2)−(F−e3)\ddot y = F + b_0 u = F + \omega_c^2 (r - y + e_1) - 2 \omega_c (\dot y - e_2) - (F - e_3). The FF terms cancel. □\square

The left side has the double pole −ωc-\omega_c. With ωc2e1\omega_c^2 e_1 and 2ωce22 \omega_c e_2 small next to e3e_3 (they carry the extra factors ωc2/ωo2\omega_c^2 / \omega_o^2 and ωc/ωo\omega_c / \omega_o), the deviation of y~\tilde y from the response of the PD loop is the forced response of 1/(s+ωc)21 / (s + \omega_c)^2 to the right side. Its impulse response te−ωctt e^{-\omega_c t} is positive with integral 1/ωc21/\omega_c^2, so an input bounded by mm gives a deviation bounded by m/ωc2m / \omega_c^2 (a theorem, by the convolution bound). So the deviation is of order M/(ωc2ωo)M / (\omega_c^2 \omega_o). The page example measures the maximum deviation from the ideal response 1−(1+2t)e−2t1 - (1 + 2t) e^{-2t} as 0.05140.0514, 0.02410.0241, 0.01130.0113 for ωo=10,20,40\omega_o = 10, 20, 40: each doubling of ωo\omega_o divides it by about 2.132.13.

Theorem 3: separation and exact rejection for linear plants

Let f=−a0y−a1y˙+df = -a_0 y - a_1 \dot y + d with constants a0,a1a_0, a_1 and a constant dd.

(a) If f=0f = 0 and b=b0b = b_0, the closed loop is linear with characteristic polynomial (s+ωc)2(s+ωo)3(s + \omega_c)^2 (s + \omega_o)^3.

(b) In general the closed loop is linear and time invariant in (y,y˙,z1,z2,z3)(y, \dot y, z_1, z_2, z_3), with the constant input (r,d)(r, d). If its matrix is Hurwitz, then y(t)→ry(t) \to r for every constant dd.

Proof. (a) Here F=0F = 0 and ee obeys Lemma 1 with F˙=0\dot F = 0, a system with the polynomial (s+ωo)3(s + \omega_o)^3 (Theorem 1 scaled back). Theorem 2 gives y~\tilde y driven by ee, with the polynomial (s+ωc)2(s + \omega_c)^2. In the coordinates (y~,y~˙,e)(\tilde y, \dot{\tilde y}, e) the matrix is block triangular, so its characteristic polynomial is the product. The tests check this exactly in Fraction for 20 random choices of ωc\omega_c, ωo\omega_o, b0b_0, with the matrix written in the original coordinates.

(b) If the matrix is Hurwitz, the state converges to the unique equilibrium. At the equilibrium, z˙3=ωo3(y−z1)=0\dot z_3 = \omega_o^3 (y - z_1) = 0 gives z1=yz_1 = y; z˙1=z2=0\dot z_1 = z_2 = 0; z˙2=z3+b0u=0\dot z_2 = z_3 + b_0 u = 0, and with L2, b0u=ωc2(r−z1)−z3b_0 u = \omega_c^2 (r - z_1) - z_3, so ωc2(r−y)=0\omega_c^2 (r - y) = 0 and y=ry = r. This holds for every dd, a0a_0, a1a_1 and bb: the state z3z_3 acts as an integrator. □\square

For the page example (a0=1a_0 = 1, a1=1/2a_1 = 1/2, b=2b = 2, b0=3/2b_0 = 3/2, ωc=2\omega_c = 2, ωo=10\omega_o = 10) the characteristic polynomial is

s5+692s4+442s3+100183s2+220723s+160003,s^5 + \tfrac{69}{2} s^4 + 442 s^3 + \tfrac{10018}{3} s^2 + \tfrac{22072}{3} s + \tfrac{16000}{3},

and the first column of its Routh array is positive (computed exactly in the tests), so the Routh-Hurwitz criterion says the matrix is Hurwitz. By (b), y→1y \to 1 before and after the step in dd. With the same gains, the loop is Hurwitz for b=1/100b = 1/100 and b=8b = 8 and not for b=17/2b = 17/2: a gain error b/b0b / b_0 up to about 5.35.3 is tolerated here, and the bound is not symmetric. For a plant that is not linear, convergence of the estimates and of the output is a theorem of Guo and Zhao (2011) under bounds on ff and its derivatives and on b−b0b - b_0; this page cites it.

Complexity

Count real operations at unit cost, as in the real RAM. For a plant of order nn, the observer has n+1n + 1 states, and one evaluation of the control law and the observer costs O(n)O(n) operations and O(n)O(n) space. The observer poles are at −ωo-\omega_o, so an explicit integrator needs a step that is small compared with 1/ωo1/\omega_o; here ωoh≤0.08\omega_o h \le 0.08.

Properties

  • Little model needed. Only the order and b0b_0; the rest is estimated. A wrong b0b_0 is absorbed into FF. In the example, with b0=1.5b_0 = 1.5, the loop is Hurwitz for b=1/100b = 1/100 and b=8b = 8 and not for b=8.5b = 8.5 (theorem, by the exact Routh test); a bisection puts the limit near b=8.01b = 8.01 (measurement). The gain error it tolerates is not symmetric.
  • Integral action built in. The estimate z3z_3 integrates the output error, so constant disturbances are rejected with zero steady error, like the I term of a PID controller.
  • Two parameters. ωc\omega_c sets the speed of the response; ωo\omega_o sets how fast disturbances are estimated. The noise in uu grows with ωo\omega_o.
  • Asymptotic, not exact, for varying disturbances. A disturbance that changes leaves an error of order ∣F˙∣/ωo|\dot F| / \omega_o in the estimate.
  • Linear for linear plants. The linear form is a linear controller of order n+1n + 1 for the plant, which can be analyzed with transfer functions.

Variants and improvements

  • Nonlinear ADRC. Han's original form replaces the linear gains by nonlinear functions of the error with a fractional power near zero, and adds a tracking differentiator that shapes the reference. It can give faster convergence with smaller gains but has more parameters.
  • Higher order. For y(n)=f+buy^{(n)} = f + b u the observer has n+1n + 1 states with gains from (s+ωo)n+1(s + \omega_o)^{n+1}, and the control is a state feedback with poles at −ωc-\omega_c.
  • Discrete and sampled forms. A discrete observer, a prediction of one sample, or a current estimator for systems with delay.
  • Models in the observer. If part of ff is known, add it to line L5, so the observer only estimates the rest. This makes FF and F˙\dot F smaller.
  • Generalized observers. More integrators in the extended state, for disturbances that are ramps or polynomials in time, or a sliding mode observer in place of the high-gain one.

When to use it

Use it for plants of known order with large uncertainty in the dynamics and slowly changing disturbances, where a model is costly and PID tuning is not good enough, such as motion control, motors and process control. Compared with a disturbance observer built around a nominal model, it needs less model. If the plant has a good model and the disturbance has a known form, use the internal model principle or model based design instead. If the measurement noise is large, the observer bandwidth must stay low, and the benefit shrinks.

Pitfalls

  • Peaking at the start. If z(0)z(0) is far from the state, the observer estimates at lines L4 to L6 have a large transient and uu peaks. Start with z1(0)=y(0)z_1(0) = y(0), or limit uu, or raise ωo\omega_o gradually.
  • Wrong sign of b0. Line L2 then adds the disturbance instead of cancelling it, and the loop is unstable.
  • Too large a gain error. The loop tolerates only a range of b/b0b / b_0; in the example, about 5.35.3 at most. Check it on the linearized loop.
  • Actuator limits. When uu saturates, the cancellation at line L2 fails and z3z_3 keeps integrating, as in integrator windup. Feed the saturated uu, not the computed one, to line L5.
  • Noise and sampling. The noise in uu grows with ωo\omega_o to a high power, and the sampling period must be small compared with 1/ωo1/\omega_o.
  • Not a model of F. z3z_3 includes (b−b0)u(b - b_0) u and the unmodeled dynamics; it is not a measurement of the physical disturbance alone.

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.

active_disturbance_rejection_control.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/active-disturbance-rejection-control/. The authors are listed in prov/1YHBZH.jsonl.

"""Linear active disturbance rejection control for a plant of order two

    y'' = f(t, y, y') + b u,

where f (the total disturbance) is unknown and b is known only roughly, as
b0. Write the plant as y'' = F + b0 u with F = f + (b - b0) u, and estimate
z = (y, y', F) with an observer of the extended state (bandwidth wo):

    z1' = z2 + 3 wo (y - z1),
    z2' = z3 + 3 wo^2 (y - z1) + b0 u,
    z3' = wo^3 (y - z1).

The control cancels the estimate z3 and applies a PD law (bandwidth wc):

    u = (wc^2 (r - z1) - 2 wc z2 - z3) / b0.

If z3 = F exactly, the loop is y'' = wc^2 (r - y) - 2 wc y', with the double
pole -wc. With f = 0 and b = b0 the poles are -wc (twice) and -wo (three times).

control and eso_rhs keep int and Fraction inputs exact.
"""

from fractions import Fraction

__all__ = ["control", "eso_rhs", "observer_gains"]


def _div(a, b):
    if b == 0:
        raise ValueError("b0 must be nonzero")
    if isinstance(a, int) and isinstance(b, int):
        return Fraction(a, b)
    return a / b


def observer_gains(wo):
    """Gains (3 wo, 3 wo^2, wo^3): all three observer poles at -wo."""
    if wo <= 0:
        raise ValueError("wo must be positive")
    return 3 * wo, 3 * wo ** 2, wo ** 3


def control(z, r, wc, b0):
    """Control from the estimate z = (z1, z2, z3) and the reference r."""
    if wc <= 0:
        raise ValueError("wc must be positive")
    u0 = wc ** 2 * (r - z[0]) - 2 * wc * z[1]  # @line L1
    return _div(u0 - z[2], b0)  # @line L2


def eso_rhs(z, y, u, wo, b0):
    """Derivative of the estimate z for the measured output y and input u."""
    b1, b2, b3 = observer_gains(wo)
    e = y - z[0]  # @line L3
    d1 = z[1] + b1 * e  # @line L4
    d2 = z[2] + b2 * e + b0 * u  # @line L5
    d3 = b3 * e  # @line L6
    return [d1, d2, d3]  # @line L7
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
test_active_disturbance_rejection_control.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/active-disturbance-rejection-control/. The authors are listed in prov/1YHBZH.jsonl.

import math
import random
from fractions import Fraction

import ctlsim
from active_disturbance_rejection_control import control, eso_rhs, observer_gains

# Simulations: classical RK4 (ctlsim) on the joint state (y, y', z1, z2, z3)
# with step DT = 0.002; the control is computed once per step from the
# estimate and held over the step (a sampled controller). Tolerances are
# stated at each check.
DT = 0.002
B, B0, WC, R = 2.0, 1.5, 2.0, 1.0


def steps(T, dt):
    n = round(T / dt)
    assert abs(n * dt - T) < 1e-12
    return n


def dist(t):
    return 1.0 if t >= 5 else 0.0


def run(wo, T):
    # plant y'' = -y - 0.5 y' + d(t) + b u with b = 2; the controller uses b0 = 1.5
    def f(t, x, u):
        return [x[1], -x[0] - 0.5 * x[1] + dist(t) + B * u] + eso_rhs(x[2:], x[0], u, wo, B0)

    def ctrl(t, x):
        return control(x[2:], R, WC, B0)

    ts, xs, us = ctlsim.simulate(f, [0.0] * 5, 0.0, T, DT, control=ctrl)
    assert len(us) == steps(T, DT) <= 10000
    return ts, xs, us


def ideal(t):
    # y'' = wc^2 (1 - y) - 2 wc y', y(0) = y'(0) = 0
    return 1 - (1 + WC * t) * math.exp(-WC * t)


def charpoly(A):
    # Faddeev-LeVerrier in exact arithmetic: coefficients of det(sI - A), leading 1.
    n = len(A)
    M = [[Fraction(0)] * n for _ in range(n)]
    c = [Fraction(1)]
    for k in range(1, n + 1):
        AM = [[sum(A[i][l] * M[l][j] for l in range(n)) for j in range(n)] for i in range(n)]
        M = [[AM[i][j] + (c[-1] if i == j else 0) for j in range(n)] for i in range(n)]
        AM = [[sum(A[i][l] * M[l][j] for l in range(n)) for j in range(n)] for i in range(n)]
        c.append(-sum(AM[i][i] for i in range(n)) / k)
    return c


def polymul(p, q):
    out = [Fraction(0)] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            out[i + j] += a * b
    return out


def routh_first_column(c):
    # first column of the Routh array of c[0] s^n + ... + c[n]; None if a pivot is 0
    c = [Fraction(v) for v in c]
    rows = [c[0::2], c[1::2]]
    w = len(rows[0])
    rows = [r + [Fraction(0)] * (w - len(r)) for r in rows]
    for _ in range(len(c) - 2):
        a, b = rows[-2], rows[-1]
        if b[0] == 0:
            return None
        rows.append([(b[0] * a[i + 1] - a[0] * b[i + 1]) / b[0] for i in range(w - 1)] + [Fraction(0)])
    return [r[0] for r in rows]


def hurwitz(c):
    col = routh_first_column(c)
    return col is not None and all(v > 0 for v in col)


def closed_loop_matrix(wc, wo, b0, b=None, a0=0, a1=0):
    # plant y'' = -a0 y - a1 y' + b u (b = b0 by default), state (y, y', z1, z2, z3), r = 0
    b = b0 if b is None else b
    b1, b2, b3 = observer_gains(wo)
    urow = [0, 0, -wc ** 2 / b0, -2 * wc / b0, -1 / b0]
    return [
        [0, 1, 0, 0, 0],
        [-a0, -a1] + [b * a for a in urow[2:]],
        [b1, 0, -b1, 1, 0],
        [b2, 0, -b2 + b0 * urow[2], b0 * urow[3], 1 + b0 * urow[4]],
        [b3, 0, -b3, 0, 0],
    ]


def test_separated_poles_exact():
    # with f = 0 and b = b0: det(sI - A) = (s + wc)^2 (s + wo)^3, exactly
    A = closed_loop_matrix(Fraction(2), Fraction(10), Fraction(3, 2))
    assert charpoly(A) == [1, 34, 424, 2320, 5200, 4000]
    rng = random.Random(5)
    for _ in range(20):
        wc = Fraction(rng.randint(1, 30), rng.randint(1, 5))
        wo = Fraction(rng.randint(1, 60), rng.randint(1, 5))
        b0 = Fraction(rng.choice([-1, 1]) * rng.randint(1, 9), rng.randint(1, 4))
        target = polymul(polymul([1, wc], [1, wc]), polymul(polymul([1, wo], [1, wo]), [1, wo]))
        assert charpoly(closed_loop_matrix(wc, wo, b0)) == target


def test_page_loop_hurwitz_exact():
    # page plant y'' = -y - 0.5 y' + 2 u, b0 = 3/2, wc = 2, wo = 10
    cp = charpoly(closed_loop_matrix(Fraction(2), Fraction(10), Fraction(3, 2), Fraction(2), 1, Fraction(1, 2)))
    assert cp == [1, Fraction(69, 2), 442, Fraction(10018, 3), Fraction(22072, 3), Fraction(16000, 3)]
    assert hurwitz(cp)
    # the gain error b / b0 the loop tolerates: b = 8 is Hurwitz, b = 17/2 is not
    for b, ok in [(Fraction(1, 100), True), (Fraction(8), True), (Fraction(17, 2), False)]:
        assert hurwitz(charpoly(closed_loop_matrix(Fraction(2), Fraction(10), Fraction(3, 2), b, 1, Fraction(1, 2)))) == ok
    # the Routh test itself: (s + 1)^5 is Hurwitz, s^2 - s + 1 is not
    assert hurwitz([1, 5, 10, 10, 5, 1]) and not hurwitz([1, -1, 1])


def test_observer_error_equation_exact():
    # x = (y, y', F) with y'' = F + b0 u: the error x - z obeys
    # e1' = e2 - 3 wo e1, e2' = e3 - 3 wo^2 e1, e3' = F' - wo^3 e1
    rng = random.Random(3)
    for _ in range(200):
        y, yd, F, Fd, u = (Fraction(rng.randint(-30, 30), rng.randint(1, 7)) for _ in range(5))
        z = [Fraction(rng.randint(-30, 30), rng.randint(1, 7)) for _ in range(3)]
        wo = Fraction(rng.randint(1, 40), rng.randint(1, 3))
        b0 = Fraction(rng.randint(1, 9), rng.randint(1, 4))
        zd = eso_rhs(z, y, u, wo, b0)
        e = [y - z[0], yd - z[1], F - z[2]]
        xd = [yd, F + b0 * u, Fd]
        ed = [a - b for a, b in zip(xd, zd)]
        assert ed == [e[1] - 3 * wo * e[0], e[2] - 3 * wo ** 2 * e[0], Fd - wo ** 3 * e[0]]


def test_control_cancels_estimate_exact():
    z = [Fraction(1, 3), Fraction(-2, 5), Fraction(7, 4)]
    u = control(z, 1, 2, Fraction(3, 2))
    # b0 u + z3 = wc^2 (r - z1) - 2 wc z2
    assert Fraction(3, 2) * u + z[2] == 4 * (1 - z[0]) - 4 * z[1]
    assert control([0, 0, 0], 1, 2, 3) == Fraction(4, 3)


def test_page_table():
    # wo = 10: (t, y, z3), within 5e-5
    ts, xs, us = run(10.0, 10.0)
    table = [(0.5, 0.26861, -0.04604), (1, 0.55035, -0.55420), (2, 0.87203, -0.76846), (3, 0.97251, -0.76831), (5, 0.99981, -0.75163), (5.5, 1.04458, -0.14171), (6, 1.04424, -0.07094), (8, 1.00524, 0.00093), (10, 1.00016, 0.00027)]
    for t, y, z3 in table:
        x = xs[steps(t, DT)]
        assert abs(x[0] - y) < 5e-5 and abs(x[4] - z3) < 5e-5
    # u(0) = 4 / 1.5 = 2.667. The total disturbance is F = -y - 0.5 y' + d + (b - b0) u;
    # at rest at y = 1 the plant needs u = (1 - d) / b, so F = -0.75 before t = 5
    # and F = 0 after it, which z3 approaches in the table.
    assert abs(us[0] - 4 / 1.5) < 1e-12
    # largest |y - 1| after the step disturbance: 0.0477, within 1 percent
    after = max(abs(x[0] - 1) for t, x in zip(ts, xs) if t >= 5)
    assert abs(after - 0.0477) < 0.01 * 0.0477


def test_deviation_from_ideal_scales_with_bandwidth():
    # max |y - ideal| for t < 5: wo = 10: 0.0514, 20: 0.0241, 40: 0.0113, within 1 percent;
    # each doubling of wo roughly halves it
    measured = {}
    for wo, want in [(10.0, 0.0514), (20.0, 0.0241), (40.0, 0.0113)]:
        ts, xs, us = run(wo, 5.0)
        dev = max(abs(x[0] - ideal(t)) for t, x in zip(ts, xs) if t < 5)
        assert abs(dev - want) < 0.01 * want
        measured[wo] = dev
    assert 2.0 < measured[10.0] / measured[20.0] < 2.3 and 2.0 < measured[20.0] / measured[40.0] < 2.3


def test_errors():
    for bad in [lambda: observer_gains(0), lambda: control([0, 0, 0], 1, 0, 1), lambda: control([0, 0, 0], 1, 2, 0), lambda: eso_rhs([0, 0, 0], 1, 0, -1, 1)]:
        try:
            bad()
        except ValueError:
            continue
        raise AssertionError("no error")

History

Jingqing Han developed ADRC in China in the 1990s, as an alternative to PID that keeps its independence of models but estimates and cancels the disturbance actively. His English paper of 2009 summarizes the ideas: the tracking differentiator, the observer of the extended state, and nonlinear feedback. Zhiqiang Gao (2003) proposed the linear form in which all observer poles are placed at one bandwidth and all controller poles at another, which reduced tuning to the choice of two numbers. Guo and Zhao (2011) proved convergence of the observer and the closed loop for a class of nonlinear plants with uncertainty.

References

  1. J. Han, From PID to active disturbance rejection control, IEEE Transactions on Industrial Electronics 56(3), 900-906, 2009, the total disturbance as an extra state, the observer of the extended state, and the nonlinear form of the controller
  2. Z. Gao, Scaling and bandwidth-parameterization based controller tuning, Proceedings of the American Control Conference, 4989-4996, 2003, the linear form with all observer poles at the observer bandwidth and all controller poles at the controller bandwidth
  3. B.-Z. Guo and Z.-L. Zhao, On the convergence of an extended state observer for nonlinear systems with uncertainty, Systems and Control Letters 60(6), 420-430, 2011, convergence of the observer and of the closed loop for nonlinear plants with uncertainty

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