Algorithm Search⌘K

Algorithmcore

Sliding mode control

Also called variable structure control.

Drives the state to a surface on which the dynamics are as wanted, with a switching control that dominates matched uncertainty.

Time
O(n + q) worst
Space
O(1) extra
Where
n = the order of the system; q = the number of arithmetic operations to evaluate the nominal drift and the input gain once
Properties
deterministicexactonlineiterative
Origin
Vadim I. Utkin, Stanislav V. Emelyanov, Aleksei F. Filippov, 1977

Sliding mode control is a feedback design for systems with uncertain models. It picks a surface s(x)=0s(x) = 0 in the state space on which the motion is the one you want, and a switching control that pushes the state onto the surface from both sides and then holds it there. The switching gain is chosen larger than a bound on the uncertainty, so any uncertainty that enters through the same channel as the input (matched uncertainty) has no effect on the motion along the surface. The price is a discontinuous control, which in a real loop causes chattering.

In plain words

Think of a car that you want to keep on the center line of a road with gusty side wind. You do not try to model the wind. You only decide which side of the line you are on, and steer hard back toward it. If your steering is stronger than the strongest gust, you reach the line in a known time and then stay on it, with the steering flipping left and right very fast. While you ride the line, the car behaves the way the line was designed to make it behave, and the wind does not matter. The design has two parts: choose a good line, and make the push toward it strong enough. The fast flipping is the weak point, because a real steering system cannot switch infinitely fast.

The problem

Input. A system of order nn in controllable canonical form,

x˙i=xi+1(i=1,…,n−1),x˙n=f(x)+b(x) u+d(t,x),\dot x_i = x_{i+1} \quad (i = 1, \dots, n - 1), \qquad \dot x_n = f(x) + b(x)\, u + d(t, x),

with a scalar input uu, a known nominal model f^\hat f of ff, a known input gain b(x)≠0b(x) \neq 0, and an unknown term δ=f−f^+d\delta = f - \hat f + d with a known bound ∣δ(t,x)∣≤D|\delta(t, x)| \le D. This is a control-affine system x˙=F(x)+G(x)u\dot x = F(x) + G(x) u in which the uncertainty enters through the input column GG (matched uncertainty). Also coefficients c1,…,cn−1c_1, \dots, c_{n-1} such that the polynomial λn−1+cn−1λn−2+⋯+c1\lambda^{n-1} + c_{n-1} \lambda^{n-2} + \dots + c_1 is Hurwitz, a gain margin η>0\eta > 0 and a switching gain k≥D+ηk \ge D + \eta.

Output. A feedback u(x)u(x) such that every solution reaches the sliding surface

s(x)=c1x1+⋯+cn−1xn−1+xn=0s(x) = c_1 x_1 + \dots + c_{n-1} x_{n-1} + x_n = 0

within time ∣s(x(0))∣/η|s(x(0))| / \eta, stays on it afterwards, and then goes to 00 exponentially, for every δ\delta that satisfies the bound.

The algorithm

  1. SLIDING-MODE-CONTROL(x, c, f̂, b, k, φ)
  2. 1s ← c_1 x_1 + ... + c_{n-1} x_{n-1} + x_n
  3. 2v ← -f̂(x) - (c_1 x_2 + ... + c_{n-1} x_n)
  4. 3if φ > 0 then σ ← sat(s / φ)
  5. 4else σ ← sgn(s)
  6. 5u ← (v - k σ) / b(x)
  7. 6return u, s

Line L1 computes the sliding variable. Line L2 is the nominal equivalent control: with u=v/bu = v / b and δ=0\delta = 0, the derivative s˙\dot s would be exactly 00. Lines L3 and L4 choose the switching function: sgn⁡\operatorname{sgn} gives the ideal sliding mode, and sat⁡(z)=max⁡(−1,min⁡(1,z))\operatorname{sat}(z) = \max(-1, \min(1, z)) with a layer width ϕ>0\phi > 0 gives the boundary layer version. Line L5 adds the switching term and divides by the input gain. Along the system,

s˙=∑i<ncixi+1+f^+δ+bu=δ−kσ(s).\dot s = \sum_{i<n} c_i x_{i+1} + \hat f + \delta + b u = \delta - k \sigma(s).

A computer runs the algorithm at sampling instants and holds uu between them. The theory assumes that it runs continuously.

Example

Take the double integrator with a sine disturbance, x˙1=x2\dot x_1 = x_2, x˙2=u+0.5sin⁡2t\dot x_2 = u + 0.5 \sin 2t, so f^=0\hat f = 0, b=1b = 1 and D=0.5D = 0.5. Choose s=x1+x2s = x_1 + x_2 (c1=1c_1 = 1), η=1\eta = 1 and k=D+η=1.5k = D + \eta = 1.5. The algorithm gives

u=−x2−1.5sgn⁡(x1+x2),s˙=0.5sin⁡2t−1.5sgn⁡(s).u = -x_2 - 1.5 \operatorname{sgn}(x_1 + x_2), \qquad \dot s = 0.5 \sin 2t - 1.5 \operatorname{sgn}(s).

From x(0)=(1,0)x(0) = (1, 0), s(0)=1s(0) = 1, so the reaching time is at most ∣s(0)∣/η=1|s(0)| / \eta = 1. On the surface x2=−x1x_2 = -x_1, so x˙1=−x1\dot x_1 = -x_1 and x1x_1 decays like e−te^{-t}, whatever the disturbance does. A 4th order Runge-Kutta simulation with step h=0.002h = 0.002, with uu computed at the start of each step and held over the step, gives:

tt x1x_1 x2x_2 ss
0 1 0 1
0.5 0.85762 -0.49318 0.364431
1 0.56424 -0.56077 0.003476
1.5 0.34247 -0.34532 -0.002847
2 0.20759 -0.21039 -0.002799
3 0.07594 -0.07406 0.001883
4 0.02827 -0.02593 0.002349
6 0.00336 -0.00233 0.001034

The sliding variable first reaches 00 at t=0.858t = 0.858, before the bound 11. After that, ∣s∣≤0.00399|s| \le 0.00399, and the switching term changes sign 365 times in the 500 steps between t=2t = 2 and t=3t = 3. With h=0.001h = 0.001 the band is 0.002000.00200. The simulation shows chattering of the size of the step: the band is (k+D)h=2h(k + D) h = 2h up to a term of order h2h^2, and it is an effect of the sampling, not of the ideal law. With the boundary layer ϕ=0.05\phi = 0.05 the control has no jumps, and ∣s∣|s| stays below ϕD/k=0.0167\phi D / k = 0.0167 (the measured maximum after t=2t = 2 is 0.01660.0166).

Correctness

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

  • The sliding variable obeys s˙=δ−kσ(s)\dot s = \delta - k \sigma(s). This is algebra: line L2 cancels the known part of s˙\dot s and line L5 divides out bb.
  • Theorem (reaching). With σ=sgn⁡\sigma = \operatorname{sgn} and k≥D+ηk \ge D + \eta, ss˙≤−η∣s∣s \dot s \le -\eta |s| wherever s≠0s \neq 0 (the reaching condition). So ∣s∣|s| decreases at rate at least η\eta and reaches 00 before t=∣s(0)∣/ηt = |s(0)| / \eta.
  • Theorem (invariance). Solutions are understood in the sense of Filippov. After ss reaches 00 it cannot leave, because on any interval where s≠0s \neq 0 the function ∣s∣|s| decreases.
  • Theorem (sliding motion). On s=0s = 0, xn=−∑cixix_n = -\sum c_i x_i, so (x1,…,xn−1)(x_1, \dots, x_{n-1}) obeys a linear system in companion form with characteristic polynomial λn−1+cn−1λn−2+⋯+c1\lambda^{n-1} + c_{n-1} \lambda^{n-2} + \dots + c_1. That polynomial is Hurwitz, so the reduced state goes to 00 exponentially, and δ\delta does not appear in the reduced system.
  • Theorem (boundary layer). With σ=sat⁡(s/ϕ)\sigma = \operatorname{sat}(s / \phi), the state enters the layer ∣s∣≤ϕ|s| \le \phi in finite time, and then ∣s∣|s| goes exponentially to the band ∣s∣≤ϕD/k|s| \le \phi D / k. The state is then ultimately bounded, not convergent.
  • Theorem (sampling). If the switching term is held over steps of length hh, the band ∣s∣≤(k+D)h|s| \le (k + D) h is reached in finite time and is never left.

The tests check the identity s˙=δ−kσ(s)\dot s = \delta - k \sigma(s) and the reaching condition exactly in Fraction for 200 random systems with n=1n = 1 to 44, the table above, the reaching time, the band 2h2h for h=0.002h = 0.002 and h=0.001h = 0.001, the boundary layer bound, and a third order system with b(x)=2+cos⁡x1b(x) = 2 + \cos x_1 and s=2x1+3x2+x3s = 2 x_1 + 3 x_2 + x_3.

Proof: Sliding mode control reaches the surface s = 0 within |s(0)| / eta, stays on it, and the reduced motion is exponentially stable for every matched uncertainty within the boundfull

The system is

x˙i=xi+1(1≤i≤n−1),x˙n=f^(x)+δ(t,x)+b(x) u,\dot x_i = x_{i+1} \quad (1 \le i \le n - 1), \qquad \dot x_n = \hat f(x) + \delta(t, x) + b(x)\, u,

where f^\hat f and bb are known and continuous, b(x)≠0b(x) \neq 0, and the unknown term δ\delta is measurable in tt, continuous in xx, and satisfies ∣δ(t,x)∣≤D|\delta(t, x)| \le D for all tt and xx. The coefficients c1,…,cn−1c_1, \dots, c_{n-1} make p(λ)=λn−1+cn−1λn−2+⋯+c1p(\lambda) = \lambda^{n-1} + c_{n-1} \lambda^{n-2} + \dots + c_1 Hurwitz, and k≥D+ηk \ge D + \eta with η>0\eta > 0. For n=1n = 1 there are no coefficients and s=x1s = x_1.

Lines L1 to L5 give

s=∑i=1n−1cixi+xn,v=−f^(x)−∑i=1n−1cixi+1,u=v−kσ(s)b(x),s = \sum_{i=1}^{n-1} c_i x_i + x_n, \qquad v = -\hat f(x) - \sum_{i=1}^{n-1} c_i x_{i+1}, \qquad u = \frac{v - k \sigma(s)}{b(x)},

with σ=sgn⁡\sigma = \operatorname{sgn} (line L4) or σ(s)=sat⁡(s/ϕ)\sigma(s) = \operatorname{sat}(s / \phi) for ϕ>0\phi > 0 (line L3). Here ∣⋅∣|\cdot| is the absolute value of a real number, and ∥⋅∥\|\cdot\| is the Euclidean norm of a vector.

Lemma 1: the sliding variable obeys s' = delta - k sigma(s)

Along a solution, wherever the derivative exists,

s˙=∑i=1n−1cix˙i+x˙n=∑i=1n−1cixi+1+f^+δ+bu.\dot s = \sum_{i=1}^{n-1} c_i \dot x_i + \dot x_n = \sum_{i=1}^{n-1} c_i x_{i+1} + \hat f + \delta + b u.

By line L5, bu=v−kσ(s)=−f^−∑i<ncixi+1−kσ(s)b u = v - k \sigma(s) = -\hat f - \sum_{i<n} c_i x_{i+1} - k \sigma(s). Substitution gives s˙=δ−kσ(s)\dot s = \delta - k \sigma(s). □\square

The identity is algebraic, so it holds exactly for exact data. The tests check it in Fraction.

Solutions

With σ=sgn⁡\sigma = \operatorname{sgn} the right side is discontinuous on s=0s = 0, so solutions are taken in the sense of Filippov (Filippov 1988): an absolutely continuous x(t)x(t) whose derivative lies, for almost every tt, in the closed convex hull of the limits of the right side at nearby points. Off the surface this is the ordinary equation. On the surface, σ(0)\sigma(0) is replaced by any value in [−1,1][-1, 1]. In both cases Lemma 1 holds in the form s˙(t)=δ−kσ(t)\dot s(t) = \delta - k \sigma(t) with σ(t)=sgn⁡s(t)\sigma(t) = \operatorname{sgn} s(t) when s(t)≠0s(t) \neq 0 and σ(t)∈[−1,1]\sigma(t) \in [-1, 1] when s(t)=0s(t) = 0, for almost every tt. The function s(t)s(t) is absolutely continuous, because x(t)x(t) is.

Theorem 1: reaching in finite time

Let σ=sgn⁡\sigma = \operatorname{sgn}. On every interval where s(t)≠0s(t) \neq 0,

ddt∣s∣=sgn⁡(s) s˙=sgn⁡(s) δ−k≤D−k≤−η\frac{d}{dt} |s| = \operatorname{sgn}(s)\, \dot s = \operatorname{sgn}(s)\, \delta - k \le D - k \le -\eta

for almost every tt. Equivalently, ss˙≤−η∣s∣s \dot s \le -\eta |s| (the reaching condition). Integrating, ∣s(t)∣≤∣s(0)∣−ηt|s(t)| \le |s(0)| - \eta t for as long as ss has not reached 00. Since ∣s∣≥0|s| \ge 0, ss reaches 00 at some time tr≤∣s(0)∣/ηt_r \le |s(0)| / \eta. □\square

Theorem 2: the surface is invariant

Let trt_r be a time with s(tr)=0s(t_r) = 0, and suppose s(t1)≠0s(t_1) \neq 0 for some t1>trt_1 > t_r. Let t0=sup⁡{t∈[tr,t1]:s(t)=0}t_0 = \sup \{ t \in [t_r, t_1] : s(t) = 0 \}. By continuity, s(t0)=0s(t_0) = 0 and s(t)≠0s(t) \neq 0 on (t0,t1](t_0, t_1]. By Theorem 1, ∣s∣|s| is non-increasing on (t0,t1](t_0, t_1], and by absolute continuity ∣s(t1)∣=∣s(t0)∣+∫t0t1ddt∣s∣ dt≤0−η(t1−t0)<0|s(t_1)| = |s(t_0)| + \int_{t_0}^{t_1} \frac{d}{dt}|s|\, dt \le 0 - \eta (t_1 - t_0) < 0. This is impossible. So s(t)=0s(t) = 0 for all t≥trt \ge t_r. □\square

Theorem 3: the motion on the surface

For t≥trt \ge t_r, xn=−∑i<ncixix_n = -\sum_{i<n} c_i x_i. Let ξ=(x1,…,xn−1)\xi = (x_1, \dots, x_{n-1}). Then ξ˙i=ξi+1\dot \xi_i = \xi_{i+1} for i<n−1i < n - 1, and ξ˙n−1=xn=−c1ξ1−⋯−cn−1ξn−1\dot \xi_{n-1} = x_n = -c_1 \xi_1 - \dots - c_{n-1} \xi_{n-1}. So ξ˙=Acξ\dot \xi = A_c \xi, where AcA_c is the companion matrix of p(λ)p(\lambda). Its eigenvalues are the roots of pp, which have negative real parts. So there are constants M≥1M \ge 1 and α>0\alpha > 0 with ∥ξ(t)∥≤Me−α(t−tr)∥ξ(tr)∥\|\xi(t)\| \le M e^{-\alpha (t - t_r)} \|\xi(t_r)\|, and xn=−∑ciξix_n = -\sum c_i \xi_i decays at the same rate. The term δ\delta does not appear in this equation. For n=1n = 1, s=x1=0s = x_1 = 0 already. □\square

Together, Theorems 1 to 3 show that every solution reaches the surface within ∣s(0)∣/η|s(0)| / \eta, stays on it, and then converges to 00 exponentially, for every δ\delta with ∣δ∣≤D|\delta| \le D. In the reduced coordinates the origin is globally asymptotically stable.

Theorem 4: the boundary layer

Let σ(s)=sat⁡(s/ϕ)\sigma(s) = \operatorname{sat}(s / \phi) with ϕ>0\phi > 0. Now the closed loop has a continuous right side. Where ∣s∣≥ϕ|s| \ge \phi, σ=sgn⁡s\sigma = \operatorname{sgn} s and Theorem 1 applies, so ss enters the layer ∣s∣≤ϕ|s| \le \phi within time max⁡(0,∣s(0)∣−ϕ)/η\max(0, |s(0)| - \phi) / \eta; by the argument of Theorem 2 it does not leave it. Inside the layer, s˙=δ−(k/ϕ)s\dot s = \delta - (k / \phi) s, so where s≠0s \neq 0,

ddt∣s∣≤D−kϕ∣s∣.\frac{d}{dt} |s| \le D - \frac{k}{\phi} |s|.

By the comparison lemma (Khalil 2002, Section 3.4), ∣s(t)∣≤ϕDk+(∣s(t1)∣−ϕDk)e−k(t−t1)/ϕ|s(t)| \le \frac{\phi D}{k} + \left(|s(t_1)| - \frac{\phi D}{k}\right) e^{-k (t - t_1) / \phi} after the entry time t1t_1. So lim sup⁡∣s(t)∣≤ϕD/k\limsup |s(t)| \le \phi D / k. Since ϕD/k<ϕ\phi D / k < \phi, this band lies in the layer. With ∣s∣≤ε|s| \le \varepsilon from some time t2t_2 on, the state ξ=(x1,…,xn−1)\xi = (x_1, \dots, x_{n-1}) obeys ξ˙=Acξ+en−1s\dot \xi = A_c \xi + e_{n-1} s, with en−1e_{n-1} the last unit vector, and the variation of constants formula gives ∥ξ(t)∥≤Me−α(t−t2)∥ξ(t2)∥+Mε/α\|\xi(t)\| \le M e^{-\alpha (t - t_2)} \|\xi(t_2)\| + M \varepsilon / \alpha. So ξ\xi is ultimately bounded by any number larger than Mε/αM \varepsilon / \alpha. □\square

The boundary layer gives up exact sliding and exact rejection of δ\delta; it keeps a bound that is proportional to ϕ\phi.

Theorem 5: sampled switching

Suppose the switching term is computed at the instants tj=jht_j = j h and held, so that s˙=δ(t)−ksgn⁡(s(tj))\dot s = \delta(t) - k \operatorname{sgn}(s(t_j)) on [tj,tj+1)[t_j, t_{j+1}), while the rest of the control acts continuously. Let B=(k+D)hB = (k + D) h.

If s(tj)>0s(t_j) > 0, then on the step s˙∈[−(k+D),−(k−D)]\dot s \in [-(k + D), -(k - D)], so ss decreases, and s(t)≥s(tj)−Bs(t) \ge s(t_j) - B on the step. If 0<s(tj)≤B0 < s(t_j) \le B, every value on the step lies in [s(tj)−B,s(tj)]⊂[−B,B][s(t_j) - B, s(t_j)] \subset [-B, B]. The case s(tj)<0s(t_j) < 0 is symmetric, and if s(tj)=0s(t_j) = 0, then ∣s˙∣≤D|\dot s| \le D and ∣s(t)∣≤Dh≤B|s(t)| \le D h \le B on the step. So once ∣s(tj)∣≤B|s(t_j)| \le B at a sample, ∣s(t)∣≤B|s(t)| \le B for all later tt. If ∣s(tj)∣>B|s(t_j)| > B, then ∣s∣|s| decreases by at least (k−D)h≥ηh(k - D) h \ge \eta h over the step, so the band is reached after at most ∣s(0)∣/(ηh)|s(0)| / (\eta h) steps. □\square

In an implementation where the whole control, including vv, is held, s˙\dot s has the extra term ∑ci(xi+1(t)−xi+1(tj))+f^(x(t))−f^(x(tj))\sum c_i (x_{i+1}(t) - x_{i+1}(t_j)) + \hat f(x(t)) - \hat f(x(t_j)), which is of order hh on a bounded set. It adds a term of order h2h^2 to the band. The tests measure ∣s∣≤0.00399|s| \le 0.00399 for h=0.002h = 0.002 and 0.002000.00200 for h=0.001h = 0.001 in the page example, where B=2hB = 2h.

Complexity

Count real operations at unit cost, as in the real RAM. Let qq be the cost to evaluate f^\hat f and bb once. Lines L1 and L2 take O(n)O(n) operations each, and the rest is O(1)O(1), so one evaluation costs O(n+q)O(n + q) time and O(1)O(1) extra space. A simulation with NN steps and a held control evaluates the algorithm NN times; a simulation that evaluates it inside the right side evaluates it 4N4N times with RK4.

Properties

  • Robust to matched uncertainty. Any δ\delta with ∣δ∣≤D|\delta| \le D is rejected on the surface, without a model of δ\delta. This is an invariance property, not only robustness.
  • Not robust to unmatched uncertainty. A term that enters x˙i\dot x_i for i<ni < n is not in the input channel, and the switching cannot cancel it. It changes the motion on the surface.
  • Finite-time reaching. The surface is reached in finite time, with a bound that depends only on ∣s(0)∣|s(0)| and η\eta.
  • Reduced order motion. On the surface the system has order n−1n - 1, and its dynamics are set by the cic_i alone, as in pole placement for a system of order n−1n - 1.
  • Discontinuous. The control jumps on s=0s = 0. The closed loop is a differential equation with a discontinuous right side, and classical existence and uniqueness results such as the Picard-Lindelöf theorem do not apply. Filippov's theory gives the solutions.

Variants and improvements

  • Boundary layer. Replace sgn⁡\operatorname{sgn} by sat⁡(s/ϕ)\operatorname{sat}(s / \phi) (line L3). The control is continuous, and the exact sliding becomes the bound ∣s∣≤ϕD/k|s| \le \phi D / k (Slotine and Li 1991, Chapter 7).
  • State-dependent gain. If the bound D(x)D(x) depends on the state, use k(x)≥D(x)+ηk(x) \ge D(x) + \eta. This keeps the gain small where the uncertainty is small and reduces the chattering.
  • Uncertain input gain. If only bounds 0<bmin⁡≤b(x)≤bmax⁡0 < b_{\min} \le b(x) \le b_{\max} are known, divide by an estimate b^\hat b and raise kk to cover the ratio b/b^b / \hat b (Slotine and Li 1991, Chapter 7).
  • Integral sliding mode. Add an integral term to ss so that the sliding mode starts at t=0t = 0 and the reaching phase disappears.
  • Terminal sliding mode. A nonlinear surface such as x2+c∣x1∣1/2sgn⁡(x1)=0x_2 + c |x_1|^{1/2} \operatorname{sgn}(x_1) = 0 makes the motion on the surface reach the origin in finite time too.
  • Higher order sliding modes. The super-twisting algorithm acts on u˙\dot u instead of uu, gives a continuous control and rejects disturbances with a bounded derivative.
  • Observers. The same idea, with the switching term in an observer, gives the sliding mode observer.

When to use it

Use it when the model has large matched uncertainty with a known bound, when you need a guaranteed reaching time, and when the actuator can tolerate fast switching or a boundary layer is acceptable. It suits electric drives and power converters, where the actuator is a switch anyway, and robot joints with friction and payload uncertainty. If the model is accurate, feedback linearization or backstepping give smooth controls with fewer tuning trade-offs. If the actuator is slow or the plant has light resonances that the switching can excite, prefer a smooth robust design, or use the super-twisting algorithm. If the uncertainty is unmatched, the method alone is not enough.

Pitfalls

  • Gain too small at line L5. If k<Dk < D at some time, the reaching condition fails, and ss can move away from the surface. The bound DD must cover the worst case of the model error and the disturbance together.
  • Gain too large at line L5. The size of the chattering grows with kk. A gain far above D+ηD + \eta wastes actuator effort and excites fast unmodeled dynamics.
  • Wrong surface at line L1. If the polynomial in the cic_i is not Hurwitz, the state reaches the surface and then diverges along it.
  • Small b(x) at line L5. The control is divided by b(x)b(x), so it becomes large where bb is small. If bb changes sign, the method fails.
  • Hidden chattering in simulation. A fixed step simulation of the discontinuous law shows chattering of the size of the step. A variable step solver can become very slow near s=0s = 0 or report a wrong smooth result. State the step with every result.
  • Relative degree. The construction needs the input to appear in s˙\dot s. If ss has relative degree two or more with respect to uu, uu does not appear in s˙\dot s, and the design fails; choose ss so that its relative degree is 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_control.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliding-mode-control/. The authors are listed in prov/WP3VZ0.jsonl.

"""Sliding mode control of a system in controllable canonical form

    x_i' = x_(i+1),   i = 1, ..., n - 1,
    x_n' = f(x) + b(x) u + d(t, x),

with a known nominal model f_hat of f, a known b(x) != 0 and an unknown
term delta = f - f_hat + d with |delta| <= D. The sliding variable is

    s = c_1 x_1 + ... + c_(n-1) x_(n-1) + x_n,

and the control is

    u = (-f_hat(x) - sum_(i < n) c_i x_(i+1) - k sigma(s)) / b(x),

with sigma(s) = sgn(s), or sat(s / phi) for a boundary layer of width
phi > 0. Along the system s' = delta - k sigma(s), so k >= D + eta gives
s s' <= -eta |s| when sigma = sgn.

The input values may be int, Fraction or float. With exact data and exact
f_hat and b, the value of u is exact (the division by b uses Fraction when
both sides are int).
"""

from fractions import Fraction

__all__ = ["sgn", "sat", "sliding_variable", "smc"]


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


def sat(z):
    """Return z clipped to [-1, 1]."""
    if z > 1:
        return 1
    if z < -1:
        return -1
    return z


def _div(p, q):
    if isinstance(p, int) and isinstance(q, int):
        return Fraction(p, q)
    return p / q


def sliding_variable(c, x):
    """s = c_1 x_1 + ... + c_(n-1) x_(n-1) + x_n, for len(c) = len(x) - 1."""
    n = len(x)
    if len(c) != n - 1:
        raise ValueError("c must have len(x) - 1 entries")
    return sum(c[i] * x[i] for i in range(n - 1)) + x[n - 1]


def smc(x, c, f_hat, b, k, phi=0):
    """Return (u, s) for the state x.

    c: the n - 1 coefficients of the sliding surface; the polynomial
       c_1 + c_2 l + ... + c_(n-1) l^(n-2) + l^(n-1) must be Hurwitz.
    f_hat(x): the nominal drift of the last state.
    b(x): the input gain of the last state, never zero.
    k: the switching gain, k >= D + eta with eta > 0.
    phi: 0 for the discontinuous law, or the width of the boundary layer.
    """
    n = len(x)
    if k <= 0:
        raise ValueError("k must be positive")
    if phi < 0:
        raise ValueError("phi must be zero or positive")
    s = sliding_variable(c, x)  # @line L1
    bx = b(x)
    if bx == 0:
        raise ZeroDivisionError("b(x) = 0")
    v = -f_hat(x) - sum(c[i] * x[i + 1] for i in range(n - 1))  # @line L2
    if phi > 0:  # @line L3
        sigma = sat(_div(s, phi))  # @line L3
    else:
        sigma = sgn(s)  # @line L4
    u = _div(v - k * sigma, bx)  # @line L5
    return u, s  # @line L6
test_sliding_mode_control.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sliding-mode-control/. The authors are listed in prov/WP3VZ0.jsonl.

import math
import random
from fractions import Fraction

import ctlsim
from sliding_mode_control import sat, sgn, sliding_variable, smc

# Simulations: classical RK4 (ctlsim) with step DT, the control computed at
# the start of each step and held over the step (a sampled controller).
# Tolerances are stated at each check.
DT = 0.002


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


def page_plant(t, x, u):
    # x1' = x2, x2' = u + d with d = 0.5 sin 2t, so D = 0.5.
    return [x[1], u + 0.5 * math.sin(2 * t)]


def page_control(phi=0):
    # s = x1 + x2, f_hat = 0, b = 1, k = 1.5 = D + eta with eta = 1.
    return lambda t, x: smc(x, [1.0], lambda x: 0.0, lambda x: 1.0, 1.5, phi)[0]


def run_page(dt, phi=0, T=6.0):
    n = steps(T, dt)
    ts, xs, us = ctlsim.simulate(page_plant, [1.0, 0.0], 0.0, T, dt, control=page_control(phi))
    assert len(ts) == n + 1
    ss = [x[0] + x[1] for x in xs]
    return ts, xs, us, ss


def test_helpers():
    assert [sgn(-2), sgn(0), sgn(Fraction(1, 3))] == [-1, 0, 1]
    assert [sat(-3), sat(Fraction(1, 2)), sat(7)] == [-1, Fraction(1, 2), 1]
    assert sliding_variable([2, 3], [1, -1, 4]) == 2 - 3 + 4


def test_sliding_derivative_exact():
    # s' = delta - k sigma(s) exactly, for random rational data, n = 1..4.
    rng = random.Random(7)
    for _ in range(200):
        n = rng.randint(1, 4)
        x = [Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(n)]
        c = [Fraction(rng.randint(1, 9), rng.randint(1, 3)) for _ in range(n - 1)]
        a = Fraction(rng.randint(-5, 5), 2)
        bconst = Fraction(rng.randint(1, 6), rng.randint(1, 4)) * rng.choice([-1, 1])
        delta = Fraction(rng.randint(-7, 7), 3)
        k = abs(delta) + 1
        phi = rng.choice([0, Fraction(1, 2)])

        def f_hat(x):
            return a * x[0] * x[-1] - x[0] ** 2

        def b(x):
            return bconst * (1 + x[0] ** 2)

        u, s = smc(x, c, f_hat, b, k, phi)
        assert s == sliding_variable(c, x)
        xdot_n = f_hat(x) + delta + b(x) * u
        xdot = x[1:] + [xdot_n]
        sdot = sum(c[i] * xdot[i] for i in range(n - 1)) + xdot[n - 1]
        sigma = sat(s / phi) if phi else sgn(s)
        assert sdot == delta - k * sigma
        if phi == 0 and s != 0:
            # reaching condition s s' <= -eta |s| with eta = k - |delta| = 1
            assert s * sdot <= -abs(s)


def test_page_example_reaching_and_band():
    ts, xs, us, ss = run_page(DT)
    assert len(us) == 3000
    # the table values on the page, to 5e-6
    table = {
        0.5: (0.85762, -0.49318, 0.364431),
        1.0: (0.56424, -0.56077, 0.003476),
        2.0: (0.20759, -0.21039, -0.002799),
        6.0: (0.00336, -0.00233, 0.001034),
    }
    for t, (a, b, s) in table.items():
        i = steps(t)
        assert abs(xs[i][0] - a) < 5e-6 and abs(xs[i][1] - b) < 5e-6 and abs(ss[i] - s) < 5e-6
    # reaching time: theorem bound |s(0)| / eta = 1; measured 0.858
    t_reach = next(t for t, s in zip(ts, ss) if s <= 0)
    assert t_reach <= 1.0
    assert abs(t_reach - 0.858) < 1e-9
    # after reaching, |s| <= (k + D) dt up to O(dt^2); measured 0.00399
    band = max(abs(s) for t, s in zip(ts, ss) if t >= t_reach)
    assert band <= 2.0 * DT * 1.01
    # the sampled law switches at almost every step (chattering)
    switches = sum(1 for i in range(1, len(us)) if 2 <= ts[i] < 3 and sgn(us[i] + xs[i][1]) != sgn(us[i - 1] + xs[i - 1][1]))
    assert switches > 300
    # on the surface x1' = -x1 + s, so x1 decays; measured x1(6) = 0.00336
    assert abs(xs[-1][0]) < 0.004


def test_band_halves_with_step():
    ts, xs, us, ss = run_page(0.001)
    t_reach = next(t for t, s in zip(ts, ss) if s <= 0)
    band = max(abs(s) for t, s in zip(ts, ss) if t >= t_reach)
    assert band <= 2.0 * 0.001 * 1.01
    assert band > 1.9 * 0.001


def test_boundary_layer():
    # with sat(s / phi) and phi = 0.05, |s| ends within phi D / k = 0.01667
    # (measured 0.01663) and u has no jumps
    ts, xs, us, ss = run_page(DT, phi=0.05)
    assert max(abs(s) for t, s in zip(ts, ss) if t >= 2) <= 0.05 * 0.5 / 1.5
    jumps = max(abs(us[i] - us[i - 1]) for i in range(1, len(us)))
    assert jumps < 0.1


def test_third_order_with_nonlinear_gain():
    # x''' = sin x1 + (2 + cos x1) u + 0.3 cos t, s = 2 x1 + 3 x2 + x3,
    # k = 1.3 = D + 1, so reaching takes at most |s(0)| = 2 (measured 1.764).
    def plant(t, x, u):
        return [x[1], x[2], math.sin(x[0]) + (2 + math.cos(x[0])) * u + 0.3 * math.cos(t)]

    def control(t, x):
        return smc(x, [2.0, 3.0], lambda x: math.sin(x[0]), lambda x: 2 + math.cos(x[0]), 1.3)[0]

    T = 10.0
    ts, xs, us = ctlsim.simulate(plant, [1.0, 0.0, 0.0], 0.0, T, DT, control=control)
    assert len(us) == steps(T) == 5000
    ss = [2 * x[0] + 3 * x[1] + x[2] for x in xs]
    t_reach = next(t for t, s in zip(ts, ss) if s <= 0)
    assert t_reach <= 2.0
    assert max(abs(s) for t, s in zip(ts, ss) if t >= t_reach) < 2.0 * 1.3 * DT
    # on s = 0 the reduced system has the poles -1 and -2
    assert max(abs(v) for v in xs[-1]) < 0.002


def test_errors():
    for bad in [
        lambda: smc([1.0, 0.0], [1.0], lambda x: 0.0, lambda x: 1.0, 0.0),
        lambda: smc([1.0, 0.0], [1.0], lambda x: 0.0, lambda x: 1.0, 1.0, -1.0),
        lambda: smc([1.0, 0.0], [1.0, 2.0], lambda x: 0.0, lambda x: 1.0, 1.0),
        lambda: smc([1.0, 0.0], [1.0], lambda x: 0.0, lambda x: 0.0, 1.0),
    ]:
        try:
            bad()
        except (ValueError, ZeroDivisionError):
            continue
        raise AssertionError("no error")

History

Switching feedback with sliding motions was studied from the late 1950s in the Soviet Union, in the group of Stanislav Emelyanov in Moscow, with Vadim Utkin as a main contributor. Utkin's 1977 survey in IEEE Transactions on Automatic Control presented the equivalent control and the invariance to matched disturbances to a Western audience, and his 1992 book gave the full theory. Aleksei Filippov's work on differential equations with discontinuous right sides, collected in his 1988 book, gave the solutions of the closed loop a precise meaning. Slotine (1984) introduced the boundary layer to trade exactness for a continuous control, and Levant (1993) started the line of higher order sliding modes.

References

  1. Variable structure systems with sliding modes, the survey of sliding modes, the equivalent control and the invariance to matched disturbances
  2. Vadim I. Utkin, Sliding Modes in Control and Optimization, Springer, 1992, the equivalent control method and the conditions for the existence of a sliding mode
  3. A. F. Filippov, Differential Equations with Discontinuous Righthand Sides, Kluwer, 1988, the definition of solutions of differential equations with a discontinuous right side
  4. Jean-Jacques E. Slotine and Weiping Li, Applied Nonlinear Control, Prentice Hall, 1991, Chapter 7 (Sliding Control), the sliding condition, the reaching time and the boundary layer
  5. Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 14.1, Sliding mode control
  6. Christopher Edwards and Sarah K. Spurgeon, Sliding Mode Control, Theory and Applications, Taylor and Francis, 1998, the introductory chapters on the sliding surface, the reaching condition and matched uncertainty

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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