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
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Miroslav Krstić, Hsin Hsiung Wang, 2000
Extremum seeking control is a feedback method that moves the input of a system to the minimum or maximum of a performance map that is not known, using only measurements of . It adds a small sine dither to , 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 and a scalar output is given. After the transients, a constant gives the output . The map is smooth but unknown, and it has a minimum at an unknown with and a positive definite Hessian. The aim is to drive to a neighborhood of and keep it there, using only measurements of . For a maximum, replace by . On this page the plant has no dynamics, so at each instant; the section Variants and improvements treats a plant with dynamics.
The algorithm
Let be the current estimate. The scheme has four parts.
- Dither. Apply with , a small amplitude , and distinct frequencies for the components.
- Washout. The high-pass filter with follows the slow part of , so is mainly the response to the dither.
- Demodulation. Multiply: . The mean of over one period is about .
- Integration. Set with for a minimum. For a maximum use .
The averaged system is plus a term of order : a gradient flow with the gain . The implementation integrates and with the classical fourth order Runge-Kutta method and a fixed step .
EXTREMUM-SEEKING(J, a, ω, k, h, θ₀, dt, N) ▷ N steps of length dt- 1
θ̂ ← θ₀; η ← J(θ₀) - 2
for i ← 0 to N - 1 do - 3
d ← a sin(ω t) ▷ one sine per component, t = i dt - 4
y ← J(θ̂ + d) ▷ measure the map - 5
η' ← h (y - η) ▷ washout filter - 6
ξ ← (y - η) sin(ω t) ▷ demodulation - 7
θ̂' ← -k ξ ▷ integrate the gradient estimate - 8
advance θ̂ and η by one RK4 step of length dt - 9
return θ̂
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 , the start , the dither and rad/s, the gain and the washout . The averaged system is , so . With RK4 and s (6000 steps for 30 s), the simulation gives:
| 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 and over the run is 0.011. The output exceeds the minimum 1 by , which does not die out because the dither never stops; this is the price of the method. The excess is at most , which tends to as ; at it is at most , and .
The same loop with , , and has the averaged rate in place of 0.2, but the time scales are not well separated. Then while : the washout lags, is large, and the oscillation of is no longer small. The loop still reaches at , but the averaged model fails to describe the transient (a measurement).
For two parameters with , the frequencies 50 and 70 rad/s, and , the averaged rates are 0.2 and 0.4, and the simulation stays within 0.03 of .
Correctness
The proof in proofs/correctness.md has three parts. First, the demodulation identity: the mean of over one period is for any constant , and exactly for a quadratic . Second, the averaged system: in the time the loop is times a periodic vector field with , and its average decouples, with where is the mean above. For a quadratic the averaged equilibrium is exponentially stable with the rate , where is the curvature. Third, by the averaging theorem (Khalil, Theorem 10.4), for large enough the real loop has an exponentially attractive periodic solution within of that equilibrium, so converges to an neighborhood of . 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 , the dither is , the washout is , and the law is with . We first treat one parameter, , with , , .
Claim 1 (demodulation identity). Let and let be the mean over . For every constant and every with five continuous derivatives,
If is a polynomial of degree at most 2, then exactly.
Proof. , so the constant does not contribute. By Taylor's theorem, , uniformly in . The means of the odd powers of are zero, and , . So . For a quadratic the Taylor series stops at with no remainder, and the term with multiplies .
For the series is finite and gives exactly , which the tests check by a rectangle rule that is exact for these trigonometric polynomials.
Claim 2 (the averaged system). Put and . Then the loop is
which is with of period in . Its average, with and frozen over one period, is
Proof. for a frozen , so the first equation is by Claim 1 with . The second follows from the definition of .
The averaged system is triangular: does not depend on . For with , Claim 1 gives , so in the time , . In the example of the page, , , , which gives . The equilibrium of the averaged system is and . Its Jacobian, in the time , is lower triangular with the eigenvalues and , both negative for and , 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 with a nondegenerate minimum, has by Claim 1 and the implicit function theorem a root for small , and , so the averaged equilibrium is exponentially stable and has a bias of order .
Claim 3 (the real loop). Let the averaged system have an exponentially stable equilibrium (Claim 2), and let be continuously differentiable with bounded derivatives on a neighborhood. Then there is such that, for every , the loop has a unique periodic solution of period in an neighborhood of , this solution is exponentially attractive, and every solution that starts close enough to stays within of the solution of the averaged system for all .
Proof. This is the averaging theorem for periodic systems (Khalil, Nonlinear Systems, Section 10.4, Theorem 10.4) applied to Claim 2 with . The theorem needs periodic in and continuously differentiable with bounded derivatives in on compact sets, which holds when is twice continuously differentiable.
Consequence. Combining Claims 2 and 3, of the periodic solution plus a decaying term, and the periodic solution is within of , which is within of . So , and the output stays within of ; the dither alone raises the mean of by .
Several parameters. For with frequencies , distinct positive integers, the vector field is periodic with period in . For a quadratic , the mean of has three kinds of terms: the linear term gives , because ; the quadratic terms are products , 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 , the gradient flow with the diagonal gain , and Claim 3 applies in the same way. In the example of the page, with , and the rates are and .
The tests check Claim 1 exactly for random quadratic data and for , compare the simulated loop with the averaged solution, and compare the limit for with a brute force grid search for the minimizer .
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 ( operations) and for the dither, the demodulation and the update. So steps cost and the memory is besides the output samples. In a real loop, the measurement is the plant itself, and the controller costs per sample.
Properties
- Gradient flow on average. Theorem for a quadratic map: the averaged update is exactly , with no bias.
- Bias for other maps. The averaged equilibrium solves , which differs from by . For at and , the mean is in place of (an exact computation, checked in the tests).
- Persistent oscillation. The dither stays on, so oscillates around with a mean excess of about . 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 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 or, for a quadratic map, from a compact set that grows as grows.
Variants and improvements
- Plant with dynamics. If drives a plant with an exponentially attractive equilibrium and , 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 for a phase estimate ; otherwise the gain of the averaged loop shrinks by .
- 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 the loop seeks a minimum and with a maximum. A wrong sign sends away from the optimum.
- Plant phase lag. A dither faster than the plant arrives with a phase shift; above 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 Y83ZRN Edit this page History Report an error Markdown