Algorithm Search⌘K

Algorithmadvanced

Extremum seeking control

Also called extremum seeking.

Drives a system to the optimum of an unknown performance map by a small periodic dither and demodulation that estimates the gradient.

Time
O(N (n + c)) worst
Space
O(n) extra
Where
N = the number of integration steps; c = the cost of one measurement of the map; n = the number of tuned parameters
Properties
deterministicnot exactonlineiterative
Origin
Miroslav Krstić, Hsin Hsiung Wang, 2000

Extremum seeking control is a feedback method that moves the input θ\theta of a system to the minimum or maximum of a performance map J(θ)J(\theta) that is not known, using only measurements of JJ. It adds a small sine dither asin⁡ωta\sin\omega t to θ\theta, multiplies the measured output by the same sine, and integrates the product; on average this is gradient descent with the gradient estimated from the response to the dither. It is close to derivative-free optimization, but the difference is the setting: derivative-free optimization calls a static function at points that it chooses, one call after the other, while extremum seeking runs continuously in closed loop with a plant that has dynamics and noise, and its gradient estimate comes from the dither and not from separate function calls.

In plain words

You want to find the setting of a knob that gives the best output, but you have no formula for the output. You move the knob a little back and forth in a regular rhythm around its current value. If the output goes up when the knob goes up, the best point is lower; if the output goes down, the best point is higher. A simple filter finds this relation by multiplying the output by the same rhythm and averaging. The result pushes the center of the knob slowly in the good direction. The rhythm must be fast compared with the slow movement of the center, and slow compared with the response of the system, so that each measurement belongs to the right knob position.

The problem

A plant with input θ∈Rn\theta \in \mathbb{R}^n and a scalar output yy is given. After the transients, a constant θ\theta gives the output y=J(θ)y = J(\theta). The map JJ is smooth but unknown, and it has a minimum at an unknown θ∗\theta^* with ∇J(θ∗)=0\nabla J(\theta^*) = 0 and a positive definite Hessian. The aim is to drive θ\theta to a neighborhood of θ∗\theta^* and keep it there, using only measurements of yy. For a maximum, replace JJ by −J-J. On this page the plant has no dynamics, so y=J(θ)y = J(\theta) at each instant; the section Variants and improvements treats a plant with dynamics.

The algorithm

Let θ^\hat\theta be the current estimate. The scheme has four parts.

  • Dither. Apply θ=θ^+d(t)\theta = \hat\theta + d(t) with di(t)=aisin⁡ωitd_i(t) = a_i\sin\omega_i t, a small amplitude ai>0a_i > 0, and distinct frequencies ωi\omega_i for the components.
  • Washout. The high-pass filter η′=h(y−η)\eta' = h(y - \eta) with h>0h > 0 follows the slow part of yy, so y−ηy - \eta is mainly the response to the dither.
  • Demodulation. Multiply: ξi=(y−η)sin⁡ωit\xi_i = (y - \eta)\sin\omega_i t. The mean of ξi\xi_i over one period is about (ai/2) ∂J/∂θi(a_i/2)\,\partial J/\partial\theta_i.
  • Integration. Set θ^i′=−kiξi\hat\theta_i' = -k_i\xi_i with ki>0k_i > 0 for a minimum. For a maximum use ki<0k_i < 0.

The averaged system is θˉi′=−ki(ai/2) ∂J/∂θi(θˉ)\bar\theta_i' = -k_i(a_i/2)\,\partial J/\partial\theta_i(\bar\theta) plus a term of order a3a^3: a gradient flow with the gain kiai/2k_i a_i/2. The implementation integrates θ^\hat\theta and η\eta with the classical fourth order Runge-Kutta method and a fixed step dtdt.

  1. EXTREMUM-SEEKING(J, a, ω, k, h, θ₀, dt, N) ▷ N steps of length dt
  2. 1θ̂ ← θ₀; η ← J(θ₀)
  3. 2for i ← 0 to N - 1 do
  4. 3d ← a sin(ω t) ▷ one sine per component, t = i dt
  5. 4y ← J(θ̂ + d) ▷ measure the map
  6. 5η' ← h (y - η) ▷ washout filter
  7. 6ξ ← (y - η) sin(ω t) ▷ demodulation
  8. 7θ̂' ← -k ξ ▷ integrate the gradient estimate
  9. 8advance θ̂ and η by one RK4 step of length dt
  10. 9return θ̂

Lines L3 to L7 are the right-hand side of the differential equation; RK4 evaluates them four times per step in line L8.

Example

Take J(θ)=(θ−2)2+1J(\theta) = (\theta - 2)^2 + 1, the start θ^(0)=0\hat\theta(0) = 0, the dither a=0.2a = 0.2 and ω=50\omega = 50 rad/s, the gain k=1k = 1 and the washout h=5h = 5. The averaged system is θˉ′=−k(a/2)⋅2(θˉ−2)=−0.2(θˉ−2)\bar\theta' = -k(a/2)\cdot 2(\bar\theta - 2) = -0.2(\bar\theta - 2), so θˉ(t)=2−2e−0.2t\bar\theta(t) = 2 - 2e^{-0.2t}. With RK4 and dt=0.005dt = 0.005 s (6000 steps for 30 s), the simulation gives:

tt θ^(t)\hat\theta(t) θˉ(t)\bar\theta(t) y(t)y(t)
0 0 0 5
2 0.6535 0.6594 3.0959
5 1.2578 1.2642 1.8766
10 1.7235 1.7293 1.1369
15 1.8975 1.9004 1.0022
30 1.9947 1.9950 1.0416

This is a measurement: the largest gap between θ^\hat\theta and θˉ\bar\theta over the run is 0.011. The output yy exceeds the minimum 1 by (asin⁡ωt+θ^−2)2(a\sin\omega t + \hat\theta - 2)^2, which does not die out because the dither never stops; this is the price of the method. The excess is at most (a+∣θ^−2∣)2(a + |\hat\theta - 2|)^2, which tends to a2=0.04a^2 = 0.04 as θ^→2\hat\theta \to 2; at t=30t = 30 it is at most 0.20532=0.04210.2053^2 = 0.0421, and y=1.0416y = 1.0416.

The same loop with a=0.1a = 0.1, ω=10\omega = 10, k=5k = 5 and h=1h = 1 has the averaged rate ka=0.5ka = 0.5 in place of 0.2, but the time scales are not well separated. Then θ^(1)=2.04\hat\theta(1) = 2.04 while θˉ(1)=0.79\bar\theta(1) = 0.79: the washout lags, y−ηy - \eta is large, and the oscillation of θ^\hat\theta is no longer small. The loop still reaches ∣θ^−2∣<0.002|\hat\theta - 2| < 0.002 at t=30t = 30, but the averaged model fails to describe the transient (a measurement).

For two parameters with J=(θ1−1)2+2(θ2+1)2+3J = (\theta_1 - 1)^2 + 2(\theta_2 + 1)^2 + 3, the frequencies 50 and 70 rad/s, a=0.2a = 0.2 and k=1k = 1, the averaged rates are 0.2 and 0.4, and the simulation stays within 0.03 of (1−e−0.2t,−1+e−0.4t)(1 - e^{-0.2t}, -1 + e^{-0.4t}).

Correctness

The proof in proofs/correctness.md has three parts. First, the demodulation identity: the mean of (J(θ+asin⁡τ)−c)sin⁡τ(J(\theta + a\sin\tau) - c)\sin\tau over one period is (a/2)J′(θ)+(a3/16)J′′′(θ)+O(a5)(a/2)J'(\theta) + (a^3/16)J'''(\theta) + O(a^5) for any constant cc, and exactly (a/2)J′(θ)(a/2)J'(\theta) for a quadratic JJ. Second, the averaged system: in the time τ=ωt\tau = \omega t the loop is ϵ\epsilon times a periodic vector field with ϵ=1/ω\epsilon = 1/\omega, and its average decouples, with θˉ′=−kM(θˉ)\bar\theta' = -k M(\bar\theta) where MM is the mean above. For a quadratic JJ the averaged equilibrium is exponentially stable with the rate kack a c, where cc is the curvature. Third, by the averaging theorem (Khalil, Theorem 10.4), for ω\omega large enough the real loop has an exponentially attractive periodic solution within O(1/ω)O(1/\omega) of that equilibrium, so θ^\hat\theta converges to an O(1/ω+a2)O(1/\omega + a^2) neighborhood of θ∗\theta^*. This is a local theorem; Tan, Nešić and Mareels (2006) give a semi-global version.

Proof: On average, extremum seeking is a gradient flow, and for a fast dither the loop converges to a small neighborhood of the optimumfull

Notation is that of the page. The map is JJ, the dither is aisin⁡ωita_i\sin\omega_i t, the washout is η′=h(y−η)\eta' = h(y - \eta), and the law is θ^i′=−ki(y−η)sin⁡ωit\hat\theta_i' = -k_i(y - \eta)\sin\omega_i t with y=J(θ^+d(t))y = J(\hat\theta + d(t)). We first treat one parameter, n=1n = 1, with a=a1a = a_1, ω=ω1\omega = \omega_1, k=k1k = k_1.

Claim 1 (demodulation identity). Let s=sin⁡τs = \sin\tau and let ⟨⋅⟩\langle\cdot\rangle be the mean over τ∈[0,2π]\tau \in [0, 2\pi]. For every constant cc and every JJ with five continuous derivatives,

M(θ):=⟨(J(θ+as)−c) s⟩=a2J′(θ)+a316J′′′(θ)+O(a5).M(\theta) := \langle (J(\theta + a s) - c)\, s\rangle = \frac{a}{2}J'(\theta) + \frac{a^3}{16}J'''(\theta) + O(a^5).

If JJ is a polynomial of degree at most 2, then M(θ)=(a/2)J′(θ)M(\theta) = (a/2)J'(\theta) exactly.

Proof. ⟨s⟩=0\langle s\rangle = 0, so the constant cc does not contribute. By Taylor's theorem, J(θ+as)=∑m=04J(m)(θ) amsm/m!+O(a5)J(\theta + a s) = \sum_{m=0}^{4} J^{(m)}(\theta)\,a^m s^m/m! + O(a^5), uniformly in s∈[−1,1]s \in [-1, 1]. The means of the odd powers of ss are zero, and ⟨s2⟩=1/2\langle s^2\rangle = 1/2, ⟨s4⟩=3/8\langle s^4\rangle = 3/8. So ⟨J(θ+as) s⟩=J′(θ) a⟨s2⟩+J′′′(θ) (a3/6)⟨s4⟩+O(a5)=(a/2)J′+(a3/16)J′′′+O(a5)\langle J(\theta + as)\,s\rangle = J'(\theta)\,a\langle s^2\rangle + J'''(\theta)\,(a^3/6)\langle s^4\rangle + O(a^5) = (a/2)J' + (a^3/16)J''' + O(a^5). For a quadratic JJ the Taylor series stops at m=2m = 2 with no remainder, and the term with m=2m = 2 multiplies ⟨s3⟩=0\langle s^3\rangle = 0. □\square

For J=θ4J = \theta^4 the series is finite and gives exactly M=2aθ3+(3/2)a3θM = 2a\theta^3 + (3/2)a^3\theta, which the tests check by a rectangle rule that is exact for these trigonometric polynomials.

Claim 2 (the averaged system). Put τ=ωt\tau = \omega t and ϵ=1/ω\epsilon = 1/\omega. Then the loop is

dθ^dτ=−ϵk (J(θ^+asin⁡τ)−η)sin⁡τ,dηdτ=ϵh (J(θ^+asin⁡τ)−η),\frac{d\hat\theta}{d\tau} = -\epsilon k\,(J(\hat\theta + a\sin\tau) - \eta)\sin\tau,\qquad \frac{d\eta}{d\tau} = \epsilon h\,(J(\hat\theta + a\sin\tau) - \eta),

which is ϵf(τ,z)\epsilon f(\tau, z) with ff of period 2π2\pi in τ\tau. Its average, with η\eta and θ^\hat\theta frozen over one period, is

dθˉdτ=−ϵk M(θˉ),dηˉdτ=ϵh (Jˉ(θˉ)−ηˉ),Jˉ(θ)=⟨J(θ+as)⟩.\frac{d\bar\theta}{d\tau} = -\epsilon k\,M(\bar\theta),\qquad \frac{d\bar\eta}{d\tau} = \epsilon h\,(\bar J(\bar\theta) - \bar\eta),\qquad \bar J(\theta) = \langle J(\theta + a s)\rangle.

Proof. ⟨ηsin⁡τ⟩=η⟨s⟩=0\langle\eta\sin\tau\rangle = \eta\langle s\rangle = 0 for a frozen η\eta, so the first equation is −ϵk M-\epsilon k\,M by Claim 1 with c=ηc = \eta. The second follows from the definition of Jˉ\bar J. □\square

The averaged system is triangular: θˉ\bar\theta does not depend on ηˉ\bar\eta. For J(θ)=c(θ−θ∗)2+J∗J(\theta) = c(\theta - \theta^*)^2 + J^* with c>0c > 0, Claim 1 gives M(θ)=ac(θ−θ∗)M(\theta) = a c(\theta - \theta^*), so in the time tt, θˉ(t)=θ∗+(θ(0)−θ∗)e−kac t\bar\theta(t) = \theta^* + (\theta(0) - \theta^*)e^{-kac\,t}. In the example of the page, c=1c = 1, θ∗=2\theta^* = 2, θ(0)=0\theta(0) = 0, which gives θˉ(t)=2−2e−kat\bar\theta(t) = 2 - 2e^{-kat}. The equilibrium of the averaged system is θˉ=θ∗\bar\theta = \theta^* and ηˉ=Jˉ(θ∗)=J∗+ca2/2\bar\eta = \bar J(\theta^*) = J^* + ca^2/2. Its Jacobian, in the time τ\tau, is lower triangular with the eigenvalues −ϵkac-\epsilon kac and −ϵh-\epsilon h, both negative for k>0k > 0 and h>0h > 0, so the equilibrium is exponentially stable (in the sense of Lyapunov, with an exponential rate), and since the averaged system is linear in this case, from every initial state.

For a general JJ with a nondegenerate minimum, M(θ)=0M(\theta) = 0 has by Claim 1 and the implicit function theorem a root θa=θ∗−(a2/8) J′′′(θ∗)/J′′(θ∗)+O(a4)\theta_a = \theta^* - (a^2/8)\,J'''(\theta^*)/J''(\theta^*) + O(a^4) for small aa, and M′(θa)=(a/2)J′′(θ∗)+O(a3)>0M'(\theta_a) = (a/2)J''(\theta^*) + O(a^3) > 0, so the averaged equilibrium is exponentially stable and has a bias of order a2a^2.

Claim 3 (the real loop). Let the averaged system have an exponentially stable equilibrium zˉ\bar z (Claim 2), and let ff be continuously differentiable with bounded derivatives on a neighborhood. Then there is ω0\omega_0 such that, for every ω>ω0\omega > \omega_0, the loop has a unique periodic solution of period 2π/ω2\pi/\omega in an O(1/ω)O(1/\omega) neighborhood of zˉ\bar z, this solution is exponentially attractive, and every solution that starts close enough to zˉ\bar z stays within O(1/ω)O(1/\omega) of the solution of the averaged system for all t≥0t \ge 0.

Proof. This is the averaging theorem for periodic systems (Khalil, Nonlinear Systems, Section 10.4, Theorem 10.4) applied to Claim 2 with ϵ=1/ω\epsilon = 1/\omega. The theorem needs ff periodic in τ\tau and continuously differentiable with bounded derivatives in zz on compact sets, which holds when JJ is twice continuously differentiable. □\square

Consequence. Combining Claims 2 and 3, θ^(t)=θ^\hat\theta(t) = \hat\theta of the periodic solution plus a decaying term, and the periodic solution is within O(1/ω)O(1/\omega) of θa\theta_a, which is within O(a2)O(a^2) of θ∗\theta^*. So lim sup⁡t→∞∣θ^(t)−θ∗∣=O(1/ω+a2)\limsup_{t\to\infty}|\hat\theta(t) - \theta^*| = O(1/\omega + a^2), and the output stays within O(a2+1/ω)O(a^2 + 1/\omega) of J∗J^*; the dither alone raises the mean of yy by Jˉ(θ∗)−J∗=a2J′′(θ∗)/4+O(a4)\bar J(\theta^*) - J^* = a^2J''(\theta^*)/4 + O(a^4).

Several parameters. For n>1n > 1 with frequencies ωi=νiω\omega_i = \nu_i\omega, νi\nu_i distinct positive integers, the vector field is periodic with period 2π2\pi in τ\tau. For a quadratic JJ, the mean of J(θ+∑jajsin⁡νjτ)sin⁡νiτJ(\theta + \sum_j a_j\sin\nu_j\tau)\sin\nu_i\tau has three kinds of terms: the linear term gives (ai/2) ∂iJ(a_i/2)\,\partial_iJ, because ⟨sin⁡νjτsin⁡νiτ⟩=δij/2\langle\sin\nu_j\tau\sin\nu_i\tau\rangle = \delta_{ij}/2; the quadratic terms are products sin⁡νjτ sin⁡νlτ sin⁡νiτ\sin\nu_j\tau\,\sin\nu_l\tau\,\sin\nu_i\tau, which are sums of products of a cosine and a sine with integer frequencies, and their mean is zero; and the constant terms give zero. So the averaged law is θˉi′=−ki(ai/2) ∂iJ(θˉ)\bar\theta_i' = -k_i(a_i/2)\,\partial_iJ(\bar\theta), the gradient flow with the diagonal gain diag(kiai/2)\mathrm{diag}(k_ia_i/2), and Claim 3 applies in the same way. In the example of the page, ν=(5,7)\nu = (5, 7) with ω=10\omega = 10, and the rates are k1a1⋅1=0.2k_1 a_1\cdot 1 = 0.2 and k2a2⋅2=0.4k_2 a_2\cdot 2 = 0.4.

The tests check Claim 1 exactly for random quadratic data and for θ4\theta^4, compare the simulated loop with the averaged solution, and compare the limit for J=eθ−2θJ = e^\theta - 2\theta with a brute force grid search for the minimizer ln⁡2\ln 2.

Complexity

The cost is that of a fixed step simulation in the real-RAM model. Each RK4 step evaluates the right-hand side four times, and each evaluation costs one measurement of the map (cc operations) and O(n)O(n) for the dither, the demodulation and the update. So NN steps cost O(N(n+c))O(N(n + c)) and the memory is O(n)O(n) besides the output samples. In a real loop, the measurement is the plant itself, and the controller costs O(n)O(n) per sample.

Properties

  • Gradient flow on average. Theorem for a quadratic map: the averaged update is exactly −ki(ai/2) ∂J/∂θi-k_i(a_i/2)\,\partial J/\partial\theta_i, with no bias.
  • Bias for other maps. The averaged equilibrium solves M(θ)=0M(\theta) = 0, which differs from θ∗\theta^* by O(a2)O(a^2). For J=θ4J = \theta^4 at θ=1\theta = 1 and a=0.1a = 0.1, the mean is 0.20150.2015 in place of (a/2)J′=0.2(a/2)J' = 0.2 (an exact computation, checked in the tests).
  • Persistent oscillation. The dither stays on, so yy oscillates around J(θ^)J(\hat\theta) with a mean excess of about a2J′′/4a^2 J''/4. The loss is the price for a gradient estimate.
  • Time scales. The analysis needs the plant to be fast, the dither to be slower than the plant, and the adaptation kak a to be slower than the dither. These conditions are qualitative; the constants in the theorems are not explicit.
  • Local result. The averaging theorem gives convergence from a neighborhood of θ∗\theta^* or, for a quadratic map, from a compact set that grows as ω\omega grows.

Variants and improvements

  • Plant with dynamics. If θ\theta drives a plant with an exponentially attractive equilibrium x=ℓ(θ)x = \ell(\theta) and J(θ)=h(ℓ(θ))J(\theta) = h(\ell(\theta)), the dither must be slow compared with the plant. Krstić and Wang (2000) proved local convergence for this case with averaging and singular perturbation.
  • Phase compensation. When the plant shifts the phase of the dither, demodulate with sin⁡(ωt−ϕ)\sin(\omega t - \phi) for a phase estimate ϕ\phi; otherwise the gain of the averaged loop shrinks by cos⁡ϕ\cos\phi.
  • Newton based extremum seeking. Estimate the Hessian with a second demodulation signal and invert it, so the rate does not depend on the curvature.
  • Stochastic dither. Replace the sines by random signals; this is close to stochastic approximation and to the simultaneous perturbation method SPSA.
  • Sliding mode and relay versions. Replace the sine by a switching signal; they are faster but give a larger oscillation.

When to use it

Use extremum seeking when a plant has an optimum that moves slowly, the map is unknown, and the output can be measured continuously, for example the power of a wind turbine or a solar panel, the efficiency of a combustion process, or the formation flight of aircraft. It needs no model, but it is slow, because the dither must be slower than the plant and the adaptation slower than the dither. If the map can be evaluated cheaply and on demand, use derivative-free optimization or hill climbing. If a model is available, a model based optimizer is faster.

Pitfalls

  • Poor time scale separation. With a large gain or a slow dither, the averaged model fails; the second example shows a large overshoot.
  • Equal frequencies. Two components with the same frequency cannot be separated by the demodulation; use distinct frequencies, and for a map with cubic or higher terms avoid frequencies that are sums or differences of others.
  • Wrong sign of the gain. With k>0k > 0 the loop seeks a minimum and with k<0k < 0 a maximum. A wrong sign sends θ^\hat\theta away from the optimum.
  • Plant phase lag. A dither faster than the plant arrives with a phase shift; above 9090 degrees the update has the wrong sign.
  • Noise and drift. Measurement noise at the dither frequency enters the gradient estimate; a slow drift of the map without a washout filter adds a bias.

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()
extremum_seeking_control.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extremum-seeking-control/. The authors are listed in prov/Y83ZRN.jsonl.

"""Classical perturbation based extremum seeking for a static map.

The performance y = J(theta) is measured, but J is unknown. The scheme
applies theta = thetah + a sin(omega t) (one dither per component, with
distinct frequencies), removes the slow part of y with a washout filter
y - eta, eta' = h (y - eta), multiplies by sin(omega t) (demodulation), and
integrates:

    thetah_i' = -k_i (y - eta) sin(omega_i t).

For k_i > 0 this seeks a minimum; for k_i < 0 a maximum. On average,
thetah_i' is about -k_i (a_i / 2) dJ/dtheta_i: gradient descent with the
gain k_i a_i / 2.

The simulation uses the classical RK4 method with a fixed step dt from
ctlsim. The time t1 must be an integer multiple of dt.
"""

import math

from ctlsim import rk4_step

__all__ = ["esc_simulate", "demodulated_average"]


def _steps(t1, dt):
    n = round(t1 / dt)
    assert abs(n * dt - t1) <= 1e-9 * max(1.0, abs(t1)), "dt must divide t1"
    return n


def esc_simulate(J, a, omega, k, h, theta0, t1, dt, every=1):
    """Simulate extremum seeking on the map J (a function of a list).

    a, omega, k and theta0 are lists with one entry per parameter. Returns
    (ts, thetahs, ys) sampled every `every` steps, where thetahs holds the
    estimates (without the dither) and ys the measured J.
    """
    n = len(theta0)
    s = [float(v) for v in theta0] + [J([float(v) for v in theta0])]  # @line L1

    def f(t, z, _u):
        th, eta = z[:n], z[n]
        d = [a[i] * math.sin(omega[i] * t) for i in range(n)]  # @line L3
        y = J([th[i] + d[i] for i in range(n)])  # @line L4
        deta = h * (y - eta)  # @line L5
        xi = [(y - eta) * math.sin(omega[i] * t) for i in range(n)]  # @line L6
        dth = [-k[i] * xi[i] for i in range(n)]  # @line L7
        return dth + [deta]

    N = _steps(t1, dt)
    ts, ths, ys = [0.0], [s[:n]], [s[n]]
    for i in range(N):  # @line L2
        s = rk4_step(f, i * dt, s, None, dt)  # @line L8
        if (i + 1) % every == 0:
            t = (i + 1) * dt
            ts.append(t)
            ths.append(s[:n])
            ys.append(J([s[j] + a[j] * math.sin(omega[j] * t) for j in range(n)]))
    return ts, ths, ys  # @line L9


def demodulated_average(J1, theta, a, omega, m=2000):
    """Average of (J1(theta + a sin wt) - J1(theta)) sin wt over one period.

    J1 is a scalar function. The average is computed by the rectangle rule
    with m points, which is exact for trigonometric polynomials of degree
    below m. For J1 smooth it equals (a / 2) J1'(theta) + O(a^3).
    """
    T = 2.0 * math.pi / omega
    s = 0.0
    for j in range(m):
        t = j * T / m
        s += (J1(theta + a * math.sin(omega * t)) - J1(theta)) * math.sin(omega * t)
    return s / m
test_extremum_seeking_control.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extremum-seeking-control/. The authors are listed in prov/Y83ZRN.jsonl.

"""Tests for extremum seeking. RK4 with a fixed step; tolerances are stated."""

import math
import random
import unittest

from extremum_seeking_control import demodulated_average, esc_simulate

DT, T1 = 0.005, 30.0  # 6000 steps per run


def quad(th):
    return (th[0] - 2.0) ** 2 + 1.0


class TestDemodulation(unittest.TestCase):
    def test_quadratic_gives_exact_half_gradient(self):
        rng = random.Random(1)
        for _ in range(5):
            th, a, w = rng.uniform(-3, 3), rng.uniform(0.05, 0.5), rng.uniform(5, 50)
            got = demodulated_average(lambda x: (x - 2.0) ** 2 + 1.0, th, a, w)
            self.assertAlmostEqual(got, (a / 2) * 2 * (th - 2.0), places=10)

    def test_quartic_has_third_order_bias(self):
        # (theta + a s)^4 s averages to 4 theta^3 a / 2 + 4 theta a^3 (3 / 8)
        th, a = 1.0, 0.1
        got = demodulated_average(lambda x: x ** 4, th, a, 10.0)
        self.assertAlmostEqual(got, 2 * th ** 3 * a + 1.5 * th * a ** 3, places=10)


class TestClosedLoop(unittest.TestCase):
    def test_tracks_averaged_gradient_flow(self):
        # averaged system: thetah' = -k a (thetah - 2), so thetah = 2 - 2 exp(-k a t)
        a, k = 0.2, 1.0
        ts, ths, _ = esc_simulate(quad, [a], [50.0], [k], 5.0, [0.0], T1, DT)
        dev = max(abs(v[0] - (2.0 - 2.0 * math.exp(-k * a * t))) for t, v in zip(ts, ths))
        self.assertLess(dev, 0.02)

    def test_maximum_with_negative_gain(self):
        ts, ths, _ = esc_simulate(lambda th: 1.0 - (th[0] - 2.0) ** 2, [0.2], [50.0], [-1.0], 5.0, [0.0], T1, DT)
        self.assertLess(max(abs(v[0] - 2.0) for t, v in zip(ts, ths) if t >= 25.0), 0.02)

    def test_against_grid_search(self):
        # reference: brute force minimum of exp(theta) - 2 theta on a grid of step 0.001
        def J(th):
            return math.exp(th[0]) - 2.0 * th[0]
        best = min((J([i / 1000.0]), i / 1000.0) for i in range(-3000, 3001))[1]
        self.assertAlmostEqual(best, math.log(2.0), places=3)
        ts, ths, _ = esc_simulate(J, [0.2], [50.0], [1.0], 5.0, [0.0], T1, DT)
        self.assertLess(max(abs(v[0] - best) for t, v in zip(ts, ths) if t >= 25.0), 0.02)

    def test_two_parameters_distinct_frequencies(self):
        def J(th):
            return (th[0] - 1.0) ** 2 + 2.0 * (th[1] + 1.0) ** 2 + 3.0
        ts, ths, _ = esc_simulate(J, [0.2, 0.2], [50.0, 70.0], [1.0, 1.0], 5.0, [0.0, 0.0], T1, DT)
        # averaged system: theta1 = 1 - exp(-0.2 t), theta2 = -1 + exp(-0.4 t)
        dev = max(max(abs(v[0] - (1 - math.exp(-0.2 * t))), abs(v[1] - (-1 + math.exp(-0.4 * t))))
                  for t, v in zip(ts, ths))
        self.assertLess(dev, 0.03)
        self.assertLess(max(abs(ths[-1][0] - 1.0), abs(ths[-1][1] + 1.0)), 0.01)

    def test_poor_time_scale_separation(self):
        # k = 5, omega = 10, washout h = 1: it still converges, but far from the averaged flow
        ts, ths, _ = esc_simulate(quad, [0.1], [10.0], [5.0], 1.0, [0.0], T1, DT)
        dev = max(abs(v[0] - (2.0 - 2.0 * math.exp(-0.5 * t))) for t, v in zip(ts, ths))
        self.assertGreater(dev, 1.0)
        self.assertLess(abs(ths[-1][0] - 2.0), 0.01)

    def test_dt_must_divide_t1(self):
        with self.assertRaises(AssertionError):
            esc_simulate(quad, [0.1], [10.0], [1.0], 1.0, [0.0], 1.0, 0.3)


if __name__ == "__main__":
    unittest.main()

History

Extremum seeking is one of the oldest adaptive methods. Leblanc (1922) is often cited as the first use, for the power transfer to an electric tram. Draper and Li (1951) studied the optimization of the spark timing of an engine with a similar loop, and the method was common in the 1950s and 1960s under names such as optimalizing control. A general proof of local convergence for a plant with dynamics came only with Krstić and Wang (2000). Tan, Nešić and Mareels (2006) proved semi-global practical convergence. Ariyur and Krstić (2003) give a full account of the design.

References

  1. Kartik B. Ariyur and Miroslav Krstić, Real-Time Optimization by Extremum-Seeking Control, Wiley 2003, Chapter 1, Introduction to extremum seeking (the basic scheme with a dither, a washout filter and a demodulator, and the averaging analysis)
  2. Miroslav Krstić and Hsin-Hsiung Wang, Stability of extremum seeking feedback for general nonlinear dynamic systems, Automatica 36(4), 2000, pages 595 to 601 (the local convergence theorem for a plant with dynamics)
  3. Ying Tan, Dragan Nešić and Iven Mareels, On non-local stability properties of extremum seeking control, Automatica 42(6), 2006, pages 889 to 903 (semi-global practical convergence with a tuning of the dither amplitude, the frequency and the gain)
  4. Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall 2002, Chapter 10, Section 10.4, Averaging (the averaging theorem for periodic systems used in the proof)

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