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
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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
where is a position that is measured, a velocity that is not, a known input, a known function, and an unknown term with a known bound along the motion. Gains and , a sampling period , and an initial estimate .
Output. Estimates with after a finite time in continuous time, and with errors of order in and in with sampling. Also an estimate of , from the average of the injection term.
The known part 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 .
The algorithm
SMO-STEP(x̂, y, u, f_0, λ, α, h)- 1
e ← y - x̂_1 - 2
v_1 ← λ |e|^{1/2} sgn(e); v_2 ← α sgn(e) - 3
x̂_1 ← x̂_1 + h (x̂_2 + v_1) - 4
x̂_2 ← x̂_2 + h (f_0(y, u) + v_2) - 5
return 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
The errors and then obey
which is the super-twisting closed loop with , and in the place of . Line L5 returns the estimate and the injection , whose average estimates .
Example
Take a pendulum with unknown friction and an unknown external torque,
with and . The observer knows and nothing about . Along this motion and (measured), and is a safe bound. The gains , satisfy the super-twisting condition . The plant is integrated with 4th order Runge-Kutta with step , and the observer takes one step per sample.
| 0.25 | 0.289902 | -0.919116 |
| 0.5 | -0.058885 | -0.780191 |
| 1 | 0.000009 | -0.006787 |
| 2 | -0.000003 | 0.008478 |
Measurements:
- for good from .
- For : and with ; and with . So is of order and of order .
- The mean of over windows of length matches the mean of within .
- A linear observer with the gains , that is , , leaves errors up to in and in , because it has no way to cancel .
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 cancels exactly, because the observer evaluates it at the measured .
- Theorem (finite-time convergence). The error equations are the super-twisting closed loop with , and the perturbation in the equation. If along the motion and , the quadratic Lyapunov function of the super-twisting algorithm proves that after a finite time, with the same bound on that time.
- Theorem (equivalent output injection). Once , the error equation for gives almost everywhere, where is the Filippov value of the injection. So the injection equals , and any low-pass filter or moving average of estimates .
- Sampling. With sampling period , the accuracy is of order in and in (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 and , 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
with known and continuous, known, and measurable in with along the motion considered. The continuous-time form of lines L1 to L4 is
with . Solutions are taken in the sense of Filippov. Here is the absolute value.
Lemma 1: the error equations
Let and . Then and
because , so the known term cancels exactly. In the Filippov sense, is replaced by a value when .
Theorem 1: finite-time convergence
Assume . The error equations are system (1) of the super-twisting proof (proofs/correctness.md of the super-twisting algorithm) with , , , , and the term replaced by , which satisfies . That proof uses only the bound , not the fact that is a derivative, so it applies without change. Hence for all , with
where and are those of that proof with , . So for .
For the page example, , , : , so the condition holds.
Theorem 2: equivalent output injection
For , on an interval, so for almost every . By Lemma 1, for almost every , where is the Filippov value of the injection . So almost everywhere. The value is consistent with this because . For every interval , : the mean of the injection over any window equals the mean of the unknown term.
The sampled implementation
Lines L3 and L4 take explicit Euler steps of length , with sampled at the start of each step. Over one step, the sum of equals , and the integral of equals . Summing over a window of steps of total length ,
so the windowed mean of the injection estimates the mean of with an error at most plus the error of the rectangle rule for . In the page example, and give , and the tests measure .
The size of the errors with sampling, of order in and in , 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 once and does a square root, a sign and a few sums, so it costs time, where is the cost of . The observer keeps two numbers, so the extra space is . A run over samples costs .
For a general system of order with a linear model, the classical first order observer (below) costs per sample with 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 equation is unmatched and is not rejected.
- Estimates the unknown input. The equivalent output injection reconstructs , which is useful for fault detection and for cancelling in the controller.
- Separation holds in practice. Because the error reaches zero in finite time, a controller that uses 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 gives an error in of order (Levant 1998, for the differentiator).
Variants and improvements
- First order sliding mode observer. For a linear system , , the observer with (or for several outputs) reaches a sliding mode on if exceeds the bound on and the matching conditions hold (Edwards and Spurgeon 1998). The injection switches, so its average must be filtered to recover .
- 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 derivatives of the output in finite time, which gives an observer for systems of order in observable form.
- Linear terms. Adding linear terms and 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 along the motion and is tuned for , 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 depends on the unmeasured and the observer uses , the difference adds to , and its bound must be included in .
- Noise at line L2. The term amplifies small noise. Filter the measurement with care, because a filter adds delay, and delay also degrades sliding modes.
- Reading the injection directly. switches between ; it estimates 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 and . 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.
# 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
- Vadim I. Utkin, Sliding Modes in Control and Optimization, Springer, 1992, the chapter on state observers with sliding modes and the equivalent output injection
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag V32494 Edit this page History Report an error Markdown