Algorithm Search⌘K

Algorithmadvanced

Sliding mode observer

Also called sliding mode state observer.

An observer with a discontinuous injection term that drives the output error to zero in finite time and is robust to matched uncertainty.

Time
O(N q) worst
Space
O(1) extra
Where
N = the number of samples; q = the number of arithmetic operations to evaluate the known model once
Properties
deterministicnot exactonlineiterative
Origin
Vadim I. Utkin, Christopher Edwards, Sarah K. Spurgeon, Jorge Davila, Leonid Fridman, Arie Levant, 1992

A sliding mode observer is a state observer whose correction term is a switching function of the output error, instead of the linear term Lo(y−y^)L_o (y - \hat y) of the Luenberger observer. The switching term forces the output error to zero in finite time and then keeps it there, even when the model has an unknown bounded term that enters through the same channel as the correction. While the error is held at zero, the average of the switching term equals the unknown term, so the observer also estimates it. This page gives the version for mechanical systems with a measured position, whose correction is the super-twisting algorithm, and describes the classical first order form in the variants.

In plain words

You can measure where a cart is, but not how fast it moves, and you only know part of the forces on it. An observer runs a copy of the cart inside the computer and nudges the copy toward the measured position. A linear observer nudges in proportion to the error, so an unknown force always leaves a small error behind. A sliding mode observer nudges with a fixed strength, always toward the measurement, and its nudge is stronger than the largest unknown force. After a short time the copy sits exactly on the measured position, and its speed matches the real speed. The nudges switch fast between left and right, and their average tells you the unknown force. The weak points are noise on the measurement and the fast switching.

The problem

Input. A system

x˙1=x2,x˙2=f0(x1,u)+F(t,x),y=x1,\dot x_1 = x_2, \qquad \dot x_2 = f_0(x_1, u) + F(t, x), \qquad y = x_1,

where x1x_1 is a position that is measured, x2x_2 a velocity that is not, uu a known input, f0f_0 a known function, and FF an unknown term with a known bound ∣F(t,x(t))∣≤L|F(t, x(t))| \le L along the motion. Gains λ>0\lambda > 0 and α>0\alpha > 0, a sampling period hh, and an initial estimate x^(0)\hat x(0).

Output. Estimates x^1(t),x^2(t)\hat x_1(t), \hat x_2(t) with x^(t)=x(t)\hat x(t) = x(t) after a finite time in continuous time, and with errors of order h2h^2 in x1x_1 and hh in x2x_2 with sampling. Also an estimate of FF, from the average of the injection term.

The known part f0f_0 depends only on the measured position and the input, so the observer can use it with the measured value. Velocity-dependent terms such as friction go into FF.

The algorithm

  1. SMO-STEP(x̂, y, u, f_0, λ, α, h)
  2. 1e ← y - x̂_1
  3. 2v_1 ← λ |e|^{1/2} sgn(e); v_2 ← α sgn(e)
  4. 3x̂_1 ← x̂_1 + h (x̂_2 + v_1)
  5. 4x̂_2 ← x̂_2 + h (f_0(y, u) + v_2)
  6. 5return x̂, v_2

Line L1 computes the output error. Line L2 computes the two injection terms of the super-twisting law. Lines L3 and L4 take one explicit Euler step of the observer

x^˙1=x^2+λ∣e∣1/2sgn⁡(e),x^˙2=f0(y,u)+αsgn⁡(e).\dot{\hat x}_1 = \hat x_2 + \lambda |e|^{1/2} \operatorname{sgn}(e), \qquad \dot{\hat x}_2 = f_0(y, u) + \alpha \operatorname{sgn}(e).

The errors e1=x1−x^1e_1 = x_1 - \hat x_1 and e2=x2−x^2e_2 = x_2 - \hat x_2 then obey

e˙1=e2−λ∣e1∣1/2sgn⁡(e1),e˙2=F(t,x)−αsgn⁡(e1),\dot e_1 = e_2 - \lambda |e_1|^{1/2} \operatorname{sgn}(e_1), \qquad \dot e_2 = F(t, x) - \alpha \operatorname{sgn}(e_1),

which is the super-twisting closed loop with s=e1s = e_1, v=e2v = e_2 and FF in the place of d˙\dot d. Line L5 returns the estimate and the injection v2v_2, whose average estimates FF.

Example

Take a pendulum with unknown friction and an unknown external torque,

x˙1=x2,x˙2=−9.81sin⁡x1+F,F=−0.2x2+0.5sin⁡2t,\dot x_1 = x_2, \qquad \dot x_2 = -9.81 \sin x_1 + F, \qquad F = -0.2 x_2 + 0.5 \sin 2t,

with x(0)=(1,0)x(0) = (1, 0) and x^(0)=(0,0)\hat x(0) = (0, 0). The observer knows f0(y)=−9.81sin⁡yf_0(y) = -9.81 \sin y and nothing about FF. Along this motion ∣x2∣≤2.76|x_2| \le 2.76 and ∣F∣≤1.0|F| \le 1.0 (measured), and L=2L = 2 is a safe bound. The gains λ=3\lambda = 3, α=4\alpha = 4 satisfy the super-twisting condition α>L+2L2/λ2=2.89\alpha > L + 2L^2/\lambda^2 = 2.89. The plant is integrated with 4th order Runge-Kutta with step h=0.002h = 0.002, and the observer takes one step per sample.

tt e1e_1 e2e_2
0.25 0.289902 -0.919116
0.5 -0.058885 -0.780191
1 0.000009 -0.006787
2 -0.000003 0.008478

Measurements:

  • ∣e2∣<0.05|e_2| < 0.05 for good from t=0.774t = 0.774.
  • For t≥3t \ge 3: ∣e1∣≤2.5⋅10−5|e_1| \le 2.5 \cdot 10^{-5} and ∣e2∣≤0.0207|e_2| \le 0.0207 with h=0.002h = 0.002; ∣e1∣≤6.3⋅10−6|e_1| \le 6.3 \cdot 10^{-6} and ∣e2∣≤0.0105|e_2| \le 0.0105 with h=0.001h = 0.001. So e1e_1 is of order h2h^2 and e2e_2 of order hh.
  • The mean of v2v_2 over windows of length 0.50.5 matches the mean of FF within 0.0790.079.
  • A linear observer with the gains (20,100)(20, 100), that is x^˙1=x^2+20e\dot{\hat x}_1 = \hat x_2 + 20 e, x^˙2=f0+100e\dot{\hat x}_2 = f_0 + 100 e, leaves errors up to 0.00570.0057 in x1x_1 and 0.120.12 in x2x_2, because it has no way to cancel FF.

Correctness

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

  • Error equations. Subtracting the observer from the plant gives the equations above. The known term f0(y,u)f_0(y, u) cancels exactly, because the observer evaluates it at the measured y=x1y = x_1.
  • Theorem (finite-time convergence). The error equations are the super-twisting closed loop with s=e1s = e_1, v=e2v = e_2 and the perturbation FF in the vv equation. If ∣F∣≤L|F| \le L along the motion and α>L+2L2/λ2\alpha > L + 2L^2 / \lambda^2, the quadratic Lyapunov function of the super-twisting algorithm proves that e=0e = 0 after a finite time, with the same bound on that time.
  • Theorem (equivalent output injection). Once e1=e2=0e_1 = e_2 = 0, the error equation for e2e_2 gives 0=F−ασ(t)0 = F - \alpha \sigma(t) almost everywhere, where ασ(t)\alpha \sigma(t) is the Filippov value of the injection. So the injection equals FF, and any low-pass filter or moving average of v2v_2 estimates FF.
  • Sampling. With sampling period hh, the accuracy is of order h2h^2 in e1e_1 and hh in e2e_2 (Levant 1993; Davila, Fridman and Levant 2005). The tests measure it.

The tests check one step by hand, the table, the convergence and accuracy for h=0.002h = 0.002 and h=0.001h = 0.001, the equivalent injection, and the comparison with the linear observer.

Proof: The super-twisting sliding mode observer gives the exact state after a finite time, and its averaged injection equals the unknown termfull

The plant is

x˙1=x2,x˙2=f0(x1,u)+F(t,x),y=x1,\dot x_1 = x_2, \qquad \dot x_2 = f_0(x_1, u) + F(t, x), \qquad y = x_1,

with f0f_0 known and continuous, u(t)u(t) known, and F(t,x(t))F(t, x(t)) measurable in tt with ∣F(t,x(t))∣≤L|F(t, x(t))| \le L along the motion considered. The continuous-time form of lines L1 to L4 is

x^˙1=x^2+λ∣e∣1/2sgn⁡(e),x^˙2=f0(y,u)+αsgn⁡(e),e=y−x^1,\dot{\hat x}_1 = \hat x_2 + \lambda |e|^{1/2} \operatorname{sgn}(e), \qquad \dot{\hat x}_2 = f_0(y, u) + \alpha \operatorname{sgn}(e), \qquad e = y - \hat x_1,

with λ,α>0\lambda, \alpha > 0. Solutions are taken in the sense of Filippov. Here ∣⋅∣|\cdot| is the absolute value.

Lemma 1: the error equations

Let e1=x1−x^1e_1 = x_1 - \hat x_1 and e2=x2−x^2e_2 = x_2 - \hat x_2. Then e=y−x^1=e1e = y - \hat x_1 = e_1 and

e˙1=x2−x^2−λ∣e1∣1/2sgn⁡(e1)=e2−λ∣e1∣1/2sgn⁡(e1),\dot e_1 = x_2 - \hat x_2 - \lambda |e_1|^{1/2} \operatorname{sgn}(e_1) = e_2 - \lambda |e_1|^{1/2} \operatorname{sgn}(e_1),
e˙2=f0(x1,u)+F−f0(y,u)−αsgn⁡(e1)=F(t,x)−αsgn⁡(e1),\dot e_2 = f_0(x_1, u) + F - f_0(y, u) - \alpha \operatorname{sgn}(e_1) = F(t, x) - \alpha \operatorname{sgn}(e_1),

because y=x1y = x_1, so the known term cancels exactly. In the Filippov sense, sgn⁡(e1)\operatorname{sgn}(e_1) is replaced by a value σ(t)∈[−1,1]\sigma(t) \in [-1, 1] when e1(t)=0e_1(t) = 0. □\square

Theorem 1: finite-time convergence

Assume α>L+2L2/λ2\alpha > L + 2L^2/\lambda^2. The error equations are system (1) of the super-twisting proof (proofs/correctness.md of the super-twisting algorithm) with s=e1s = e_1, v=e2v = e_2, k1=λk_1 = \lambda, k2=αk_2 = \alpha, and the term d˙(t)\dot d(t) replaced by ρ(t)=F(t,x(t))\rho(t) = F(t, x(t)), which satisfies ∣ρ(t)∣≤L|\rho(t)| \le L. That proof uses only the bound ∣d˙∣≤L|\dot d| \le L, not the fact that d˙\dot d is a derivative, so it applies without change. Hence e1=e2=0e_1 = e_2 = 0 for all t≥Tt \ge T, with

T=2λmax⁡(P)1/2 V(0)1/2q,V(0)=ζ(0)TPζ(0),ζ(0)=(∣e1(0)∣1/2sgn⁡e1(0), e2(0)),T = \frac{2 \lambda_{\max}(P)^{1/2}\, V(0)^{1/2}}{q}, \qquad V(0) = \zeta(0)^T P \zeta(0), \qquad \zeta(0) = (|e_1(0)|^{1/2} \operatorname{sgn} e_1(0),\ e_2(0)),

where PP and qq are those of that proof with k1=λk_1 = \lambda, k2=αk_2 = \alpha. So x^(t)=x(t)\hat x(t) = x(t) for t≥Tt \ge T. □\square

For the page example, λ=3\lambda = 3, α=4\alpha = 4, L=2L = 2: L+2L2/λ2=2+8/9<4L + 2L^2/\lambda^2 = 2 + 8/9 < 4, so the condition holds.

Theorem 2: equivalent output injection

For t≥Tt \ge T, e2=0e_2 = 0 on an interval, so e˙2=0\dot e_2 = 0 for almost every t≥Tt \ge T. By Lemma 1, 0=F(t,x(t))−ασ(t)0 = F(t, x(t)) - \alpha \sigma(t) for almost every t≥Tt \ge T, where ασ(t)\alpha \sigma(t) is the Filippov value of the injection v2v_2. So ασ(t)=F(t,x(t))\alpha \sigma(t) = F(t, x(t)) almost everywhere. The value σ(t)∈[−1,1]\sigma(t) \in [-1, 1] is consistent with this because ∣F∣≤L<α|F| \le L < \alpha. For every interval [a,b]⊂[T,∞)[a, b] \subset [T, \infty), 1b−a∫abασ dt=1b−a∫abF dt\frac{1}{b - a} \int_a^b \alpha \sigma\, dt = \frac{1}{b - a} \int_a^b F\, dt: the mean of the injection over any window equals the mean of the unknown term. □\square

The sampled implementation

Lines L3 and L4 take explicit Euler steps of length hh, with ee sampled at the start of each step. Over one step, the sum of hv2h v_2 equals x^2(tj+1)−x^2(tj)−hf0(yj,uj)\hat x_2(t_{j+1}) - \hat x_2(t_j) - h f_0(y_j, u_j), and the integral of FF equals x2(tj+1)−x2(tj)−∫f0(x1,u) dtx_2(t_{j+1}) - x_2(t_j) - \int f_0(x_1, u)\, dt. Summing over a window of mm steps of total length W=mhW = m h,

1m∑v2−1W∫F dt=e2(start)−e2(end)W+1W(∫f0 dt−h∑f0(yj,uj)),\frac{1}{m} \sum v_2 - \frac{1}{W} \int F\, dt = \frac{e_2(\text{start}) - e_2(\text{end})}{W} + \frac{1}{W} \left( \int f_0\, dt - h \sum f_0(y_j, u_j) \right),

so the windowed mean of the injection estimates the mean of FF with an error at most 2max⁡∣e2∣/W2 \max |e_2| / W plus the error of the rectangle rule for f0f_0. In the page example, max⁡∣e2∣=0.0207\max |e_2| = 0.0207 and W=0.5W = 0.5 give 0.0830.083, and the tests measure 0.0790.079.

The size of the errors with sampling, of order h2h^2 in e1e_1 and hh in e2e_2, follows from the homogeneity of the super-twisting algorithm (Levant 1993); this page does not reprove it, and the tests measure it.

Complexity

Count real operations at unit cost, as in the real RAM. Each sample evaluates f0f_0 once and does a square root, a sign and a few sums, so it costs O(q)O(q) time, where qq is the cost of f0f_0. The observer keeps two numbers, so the extra space is O(1)O(1). A run over NN samples costs O(Nq)O(N q).

For a general system of order nn with a linear model, the classical first order observer (below) costs O(np)O(n p) per sample with pp outputs, for the matrix products.

Properties

  • Finite-time exact estimation. In continuous time the estimate equals the state after a finite time. A Luenberger or high-gain observer converges only asymptotically, or to a neighborhood when there is an unknown term.
  • Robust to matched uncertainty. An unknown term in the equation where the injection acts has no effect after convergence. A term in the x˙1\dot x_1 equation is unmatched and is not rejected.
  • Estimates the unknown input. The equivalent output injection reconstructs FF, which is useful for fault detection and for cancelling FF in the controller.
  • Separation holds in practice. Because the error reaches zero in finite time, a controller that uses x^\hat x uses the true state after that time. With bounded inputs the separation principle argument then works without the usual linear assumptions, as long as the state stays bounded during the transient.
  • Sensitive to noise. The square root term reacts strongly to small errors, so measurement noise of size ε\varepsilon gives an error in e2e_2 of order ε1/2\varepsilon^{1/2} (Levant 1998, for the differentiator).

Variants and improvements

  • First order sliding mode observer. For a linear system x˙=Ax+Bu+Dξ\dot x = A x + B u + D \xi, y=Cxy = C x, the observer x^˙=Ax^+Bu+Lo(y−Cx^)+Gnν\dot{\hat x} = A \hat x + B u + L_o (y - C \hat x) + G_n \nu with ν=ρsgn⁡(y−Cx^)\nu = \rho \operatorname{sgn}(y - C \hat x) (or ρ(y−Cx^)/∥y−Cx^∥\rho (y - C\hat x) / \|y - C\hat x\| for several outputs) reaches a sliding mode on y=Cx^y = C \hat x if ρ\rho exceeds the bound on ξ\xi and the matching conditions hold (Edwards and Spurgeon 1998). The injection switches, so its average must be filtered to recover ξ\xi.
  • Utkin's cascade observer. For a system in observable form, a chain of first order sliding modes estimates one state at a time: each step reaches the sliding mode, and the filtered injection of that step is the next measured output (Utkin 1992).
  • Higher order differentiators. Levant's arbitrary order robust exact differentiator estimates nn derivatives of the output in finite time, which gives an observer for systems of order n+1n + 1 in observable form.
  • Linear terms. Adding linear terms k1ek_1 e and k2ek_2 e to the injections speeds up the transient from far away.

When to use it

Use it when the position (or a similar output) is measured with low noise, the model has an unknown term with a known bound in the equation where the injection acts, and you need the velocity and the unknown term quickly and exactly, for example for fault detection, for friction compensation or for a controller that cancels the disturbance. If the measurement is noisy, a Kalman filter or a high-gain observer with a moderate gain is usually better. If the model is accurate, a Luenberger observer with a good linearization is simpler. For linear systems with unknown inputs and no bound, the unknown input observer decouples them by geometry instead.

Pitfalls

  • Bound L too small at line L2. If ∣F∣>L|F| > L along the motion and α\alpha is tuned for LL, the error can leave zero. Check the bound over the whole range of states, including the transient.
  • Unknown term in f_0 at line L4. If f0f_0 depends on the unmeasured x2x_2 and the observer uses x^2\hat x_2, the difference f0(x)−f0(x^)f_0(x) - f_0(\hat x) adds to FF, and its bound must be included in LL.
  • Noise at line L2. The term ∣e∣1/2|e|^{1/2} amplifies small noise. Filter the measurement with care, because a filter adds delay, and delay also degrades sliding modes.
  • Reading the injection directly. v2v_2 switches between ±α\pm \alpha; it estimates FF only after averaging. A window that is too short gives a noisy estimate; one that is too long lags.
  • Large sampling period. The errors grow like h2h^2 and hh. With a slow sampling rate, the observer can be worse than a linear one.

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()
sliding_mode_observer.py 62 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliding-mode-observer/. The authors are listed in prov/V32494.jsonl.

"""A sliding mode observer with super-twisting injection for systems

    x1' = x2,
    x2' = f0(x1, u) + F(t, x1, x2),   y = x1,

where f0 is known, F is unknown and |F| <= L along the motion. The observer is

    xh1' = xh2 + lam |e|^(1/2) sgn(e),
    xh2' = f0(y, u) + alpha sgn(e),      e = y - xh1,

and is run in sampled form with explicit Euler steps of length h. The
errors e1 = x1 - xh1 and e2 = x2 - xh2 obey the super-twisting equations

    e1' = e2 - lam |e1|^(1/2) sgn(e1),   e2' = F - alpha sgn(e1),

so e1 and e2 reach zero in finite time when alpha > L + 2 L^2 / lam^2, and
then the average of alpha sgn(e) equals F (the equivalent output injection).
"""

import math

__all__ = ["sgn", "SlidingModeObserver"]


def sgn(s):
    """Return -1, 0 or 1."""
    return (s > 0) - (s < 0)


class SlidingModeObserver:
    """Sampled super-twisting observer for a second order mechanical system.

    f0(y, u): the known part of x2'. lam, alpha: the injection gains.
    h: the sampling period. xh0: the initial estimate (xh1, xh2).
    """

    def __init__(self, f0, lam, alpha, h, xh0=(0.0, 0.0)):
        if lam <= 0 or alpha <= 0:
            raise ValueError("lam and alpha must be positive")
        if h <= 0:
            raise ValueError("h must be positive")
        self.f0 = f0
        self.lam = lam
        self.alpha = alpha
        self.h = h
        self.xh = list(xh0)
        self.injection = 0.0

    def step(self, y, u=None):
        """Use the sample y at the current instant; return the next estimate."""
        x1, x2 = self.xh
        e = y - x1  # @line L1
        v1 = self.lam * math.sqrt(abs(e)) * sgn(e)  # @line L2
        v2 = self.alpha * sgn(e)  # @line L2
        n1 = x1 + self.h * (x2 + v1)  # @line L3
        n2 = x2 + self.h * (self.f0(y, u) + v2)  # @line L4
        self.xh = [n1, n2]
        self.injection = v2
        return list(self.xh)  # @line L5
test_sliding_mode_observer.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliding-mode-observer/. The authors are listed in prov/V32494.jsonl.

import math

import ctlsim
from sliding_mode_observer import SlidingModeObserver, sgn

# The plant is integrated with classical RK4 (ctlsim) with step dt = h, the
# sampling period of the observer; the observer itself takes one explicit
# Euler step per sample, as a sampled implementation does. Tolerances are
# stated at each check.

G, FR = 9.81, 0.2


def F(t, x):
    # the unknown part: friction and an external torque, |F| <= 1.1 here
    return -FR * x[1] + 0.5 * math.sin(2 * t)


def pend(t, x, u):
    return [x[1], -G * math.sin(x[0]) + F(t, x)]


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


def run(h, T=5.0, lam=3.0, alpha=4.0):
    obs = SlidingModeObserver(lambda y, u: -G * math.sin(y), lam, alpha, h)
    est = [list(obs.xh)]
    inj = []

    def sample(t, x):
        est.append(obs.step(x[0]))
        inj.append(obs.injection)
        return None

    ts, xs, us = ctlsim.simulate(pend, [1.0, 0.0], 0.0, T, h, control=sample)
    assert len(us) == steps(T, h)
    e1 = [x[0] - e[0] for x, e in zip(xs, est)]
    e2 = [x[1] - e[1] for x, e in zip(xs, est)]
    return ts, xs, e1, e2, inj


def test_one_step_by_hand():
    obs = SlidingModeObserver(lambda y, u: -y, 2.0, 3.0, 0.5, xh0=(0.0, 1.0))
    # e = 4, v1 = 2 * 2 = 4, v2 = 3; xh1 = 0 + 0.5 (1 + 4), xh2 = 1 + 0.5 (-4 + 3)
    assert obs.step(4.0) == [2.5, 0.5]
    assert obs.injection == 3.0
    # e = 2.5 - 2.5 = 0: no injection
    assert obs.step(2.5) == [2.75, 0.5 + 0.5 * (-2.5)]
    assert obs.injection == 0.0


def test_gains_certified():
    # alpha > L + 2 L^2 / lam^2 with L = 2, a safe bound on |F| for this motion
    lam, alpha, L = 3.0, 4.0, 2.0
    assert alpha > L + 2 * L * L / (lam * lam)


def test_page_example():
    h = 0.002
    ts, xs, e1, e2, inj = run(h)
    assert max(abs(F(t, x)) for t, x in zip(ts, xs)) < 1.1
    table = {0.25: (0.289902, -0.919116), 0.5: (-0.058885, -0.780191), 1.0: (0.000009, -0.006787), 2.0: (-0.000003, 0.008478)}
    for t, (a, b) in table.items():
        i = steps(t, h)
        assert abs(e1[i] - a) < 5e-7 and abs(e2[i] - b) < 5e-7
    # |e2| < 0.05 for good from t = 0.774 (measured)
    i = steps(0.774, h)
    assert all(abs(v) < 0.05 for v in e2[i:]) and abs(e2[i - 1]) >= 0.05
    late = steps(3.0, h)
    assert max(abs(v) for v in e1[late:]) < 3e-5
    assert max(abs(v) for v in e2[late:]) < 0.025
    # equivalent output injection: the mean of alpha sgn(e) over windows of
    # 0.5 matches the mean of F within 0.079 (measured), below 2 max|e2| / 0.5
    w = steps(0.5, h)
    errs = []
    for i0 in range(late, len(inj) - w + 1, w):
        mean_inj = sum(inj[i0:i0 + w]) / w
        mean_F = sum(F(ts[i], xs[i]) for i in range(i0, i0 + w)) / w
        errs.append(abs(mean_inj - mean_F))
    assert len(errs) == 4 and max(errs) < 0.085


def test_accuracy_with_sampling_period():
    # halving h: e1 drops about 4 times (order h^2), e2 about 2 times (order h)
    h = 0.001
    ts, xs, e1, e2, inj = run(h)
    late = steps(3.0, h)
    m1 = max(abs(v) for v in e1[late:])
    m2 = max(abs(v) for v in e2[late:])
    assert m1 < 8e-6 and m2 < 0.012
    assert 2.5e-5 / m1 > 3 and 0.0207 / m2 > 1.7


def test_linear_observer_is_worse():
    # xh1' = xh2 + 20 e, xh2' = f0 + 100 e: the unknown F leaves an error of
    # 0.0057 in e1 and 0.12 in e2 (measured), more than 100 and 5 times the
    # sliding mode observer.
    h = 0.002
    xh = [0.0, 0.0]
    est = [list(xh)]

    def sample(t, x):
        e = x[0] - xh[0]
        xh[0], xh[1] = xh[0] + h * (xh[1] + 20.0 * e), xh[1] + h * (-G * math.sin(x[0]) + 100.0 * e)
        est.append(list(xh))
        return None

    ts, xs, us = ctlsim.simulate(pend, [1.0, 0.0], 0.0, 5.0, h, control=sample)
    late = steps(3.0, h)
    m1 = max(abs(x[0] - e[0]) for x, e in zip(xs[late:], est[late:]))
    m2 = max(abs(x[1] - e[1]) for x, e in zip(xs[late:], est[late:]))
    assert m1 > 100 * 2.6e-5 and m2 > 5 * 0.021


def test_errors_and_sign():
    assert [sgn(-0.1), sgn(0.0), sgn(3)] == [-1, 0, 1]
    for bad in [lambda: SlidingModeObserver(lambda y, u: 0.0, 0.0, 1.0, 0.1), lambda: SlidingModeObserver(lambda y, u: 0.0, 1.0, 1.0, 0.0)]:
        try:
            bad()
        except ValueError:
            continue
        raise AssertionError("no error")

History

Utkin's 1992 book, which collected the Soviet work on sliding modes, described observers that use switching injection and the idea of reading an unknown signal from the average of the switching term, the equivalent output injection. Edwards and Spurgeon developed observers of this kind for uncertain linear systems in the 1990s, with conditions on the system structure under which the unknown inputs can be rejected and reconstructed, and they summarized the work in their 1998 book. After Levant (1998) showed that the super-twisting algorithm gives a robust exact differentiator, Davila, Fridman and Levant (2005) built an observer for mechanical systems on it, which estimates the velocity in finite time from the position alone. Higher order sliding mode observers and differentiators are now a standard tool for fault detection and output feedback.

References

  1. Vadim I. Utkin, Sliding Modes in Control and Optimization, Springer, 1992, the chapter on state observers with sliding modes and the equivalent output injection
  2. Christopher Edwards and Sarah K. Spurgeon, Sliding Mode Control, Theory and Applications, Taylor and Francis, 1998, the chapter on sliding mode observers for uncertain linear systems
  3. J. Davila, L. Fridman and A. Levant, Second-order sliding-mode observer for mechanical systems, IEEE Transactions on Automatic Control 50(11), 1785-1789, 2005, the super-twisting observer for x1' = x2, x2' = f(t, x1, x2, u) with a measured position, and its finite-time convergence
  4. A. Levant, Robust exact differentiation via sliding mode technique, Automatica 34(3), 379-384, 1998, the robust exact differentiator based on the super-twisting algorithm

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