Algorithm Search⌘K

Techniquecore

Describing function method

Also called describing function analysis, harmonic balance method.

Replaces a nonlinearity by its gain on a sinusoid, and predicts limit cycles where the Nyquist plot meets minus the inverse describing function.

The describing function method predicts whether a feedback loop with one nonlinear element oscillates, and if so with what amplitude and frequency. It replaces the nonlinearity by its gain on a sinusoid: the ratio of the first harmonic of its output to the input sinusoid. This gain N(a)N(a) depends on the amplitude aa and, for elements with memory, on the frequency. The loop can then sustain the oscillation asin⁡ωta \sin \omega t when G(jω)N(a)=−1G(j\omega) N(a) = -1, where GG is the linear part. Graphically, the Nyquist plot of GG meets the curve of −1/N(a)-1/N(a). The method is approximate. It assumes that the linear part removes the higher harmonics, and it can predict a limit cycle that does not exist, or miss one that does. It is still the usual first tool for oscillations in relay loops, loops with saturation, backlash and friction, and it is the basis of relay autotuning. The idea of keeping only the first harmonic goes back to Krylov and Bogoliubov in the 1930s. In control it was developed around 1950 by several authors independently, among them Kochenburger in the United States and Goldfarb in the Soviet Union.

In plain words

Put a sine wave of amplitude aa into the nonlinear element. The output repeats with the same period, but it is not a sine wave: a relay, for example, gives a square wave. Keep only the part of the output at the input frequency, and divide it by the input. The result is a gain, possibly with a phase shift, that changes with aa. Now treat the loop as linear with this gain. A loop oscillates without decay or growth when the signal comes back around the loop with the same size and the same phase, that is, when the total gain at that frequency is exactly −1-1 in negative feedback. Solve this for the amplitude and the frequency. The answer is correct to the extent that the linear part blocks the harmonics that were dropped.

When it applies

  • The loop has one nonlinear element u=ϕ(e)u = \phi(e) in negative feedback with a linear time-invariant part y=G(s)uy = G(s) u, e=−ye = -y, after a block diagram rearrangement. This is the structure of the Lur'e problem.
  • ϕ\phi is odd, or at least has no bias, so that a symmetric oscillation is plausible. A static ϕ\phi gives a real N(a)N(a). An element with memory, such as a relay with hysteresis or backlash, gives a complex N(a)N(a).
  • GG is low pass: ∣G(jkω)∣|G(jk\omega)| is much smaller than ∣G(jω)∣|G(j\omega)| for k=2,3,…k = 2, 3, \dots near the predicted frequency. This is the filtering hypothesis. A plant with two or more poles beyond the oscillation frequency usually satisfies it.
  • One wants a quick estimate of the amplitude and period of an oscillation, or a design rule to avoid it. For a proof that no oscillation exists, use the circle criterion or the Popov criterion; for a proof that one exists, use the averaging method or a rigorous error bound.

The template

  1. Compute the describing function. For e=asin⁡θe = a \sin \theta, θ=ωt\theta = \omega t, let b1=1π∫02πϕ(asin⁡θ)sin⁡θ dθb_1 = \frac{1}{\pi} \int_0^{2\pi} \phi(a \sin \theta) \sin \theta \, d\theta and a1=1π∫02πϕ(asin⁡θ)cos⁡θ dθa_1 = \frac{1}{\pi} \int_0^{2\pi} \phi(a \sin \theta) \cos \theta \, d\theta. Then N(a)=(b1+ja1)/aN(a) = (b_1 + j a_1)/a. For a static odd ϕ\phi, a1=0a_1 = 0.
  2. Write the harmonic balance equation. With e≈asin⁡ωte \approx a \sin \omega t, u≈u \approx the first harmonic, y=Guy = G u and e=−ye = -y, the first harmonics balance when G(jω)N(a)+1=0G(j\omega) N(a) + 1 = 0, or G(jω)=−1/N(a)G(j\omega) = -1/N(a).
  3. Solve it. For a real NN, the right side is real and negative, so ω\omega is a phase crossover frequency of GG, where arg⁡G(jω)=−180°\arg G(j\omega) = -180°, and N(a)=−1/G(jω)N(a) = -1/G(j\omega) gives aa. For a complex NN, solve the two real equations for (ω,a)(\omega, a), or intersect the Nyquist plot with the curve −1/N(a)-1/N(a) on a plot.
  4. Decide whether the cycle attracts. Replace N(a)N(a) by a constant gain kk. Suppose that the loop is asymptotically stable for kk just below the balance value r=N(a∗)r = N(a^*) and unstable just above it. If NN decreases with aa, then a slightly larger amplitude gives a smaller gain and decays, and a slightly smaller amplitude grows: the predicted cycle attracts. If NN increases with aa, it repels. On the Nyquist plot this is the Loeb criterion: the cycle attracts when the point −1/N(a)-1/N(a) moves out of the region that the plot encircles as aa grows.
  5. Check the filtering hypothesis. Compare ∣G(3jω)∣|G(3j\omega)| with ∣G(jω)∣|G(j\omega)|; for an odd ϕ\phi the third harmonic is the largest one dropped. Confirm the prediction by a simulation whenever the result matters.

The implementation does steps 3 to 5 for a real describing function:

  1. HARMONIC-BALANCE(G, N, [ω_lo, ω_hi], [a_lo, a_hi]) ▷ N(a) real, negative feedback
  2. 1find ω* in [ω_lo, ω_hi] with Im G(jω*) = 0 by bisection; NONE if Im G does not change sign
  3. 2g ← Re G(jω*); if g ≥ 0 then return NONE ▷ the crossing must be on the negative real axis
  4. 3r ← -1/g ▷ harmonic balance needs N(a) = r
  5. 4if N(a_lo) - r and N(a_hi) - r have the same sign then return NONE
  6. 5find a* in [a_lo, a_hi] with N(a*) = r by bisection
  7. 6s ← dN/da at a*, by a central difference
  8. 7q ← |G(3jω*)| / |G(jω*)| ▷ small q supports the filtering hypothesis
  9. 8return (a*, ω*, period 2π/ω*, attracting if s < 0, q)

Line L8 uses the rule of step 4, so it assumes that the loop with a constant gain becomes unstable as the gain passes rr. The module also has the closed forms below, a numerical N(a)N(a) by the midpoint rule for any static ϕ\phi, a Newton solver for a complex N(a)N(a), and a simulation of the loop with the classical Runge-Kutta method to compare the prediction with the true oscillation.

Classic examples

Common describing functions. For a nonlinearity with slope kk and break point δ\delta, and with ρ=δ/a\rho = \delta / a:

Element N(a)N(a)
ideal relay, output ±d\pm d 4dπa\dfrac{4d}{\pi a}
saturation kk for a≤δa \le \delta; 2kπ(arcsin⁡ρ+ρ1−ρ2)\dfrac{2k}{\pi}\left(\arcsin \rho + \rho \sqrt{1 - \rho^2}\right) for a>δa > \delta
dead zone 00 for a≤δa \le \delta; kk minus the saturation value for a>δa > \delta
relay ±d\pm d with hysteresis ±h\pm h 4dπae−jarcsin⁡(h/a)\dfrac{4d}{\pi a} e^{-j \arcsin(h/a)} for a>ha > h

For the relay, the output is a square wave of amplitude dd, whose first harmonic has amplitude 4d/π4d/\pi. For the relay with hysteresis, the square wave is delayed by the angle arcsin⁡(h/a)\arcsin(h/a), so −1/N(a)=−π4d(a2−h2+jh)-1/N(a) = -\frac{\pi}{4d}\left(\sqrt{a^2 - h^2} + j h\right), a horizontal half line at height −πh/(4d)-\pi h/(4d).

A relay loop. Take G(s)=1/(s(s+1)(s+2))G(s) = 1/(s(s+1)(s+2)) and an ideal relay with d=1d = 1. Then G(jω)=1/(−3ω2+jω(2−ω2))G(j\omega) = 1/(-3\omega^2 + j\omega(2 - \omega^2)), so the phase crossover is ω=2\omega = \sqrt 2, with G(j2)=−1/6G(j\sqrt 2) = -1/6. Harmonic balance gives 4/(πa)=64/(\pi a) = 6, so the prediction is

a=23π≈0.2122,T=2π2≈4.443.a = \frac{2}{3\pi} \approx 0.2122, \qquad T = \frac{2\pi}{\sqrt 2} \approx 4.443.

NN decreases with aa, and the loop with a gain kk becomes unstable as kk passes 66, so the predicted cycle attracts. The exact cycle is known for this plant. With G=12s−1s+1+12(s+2)G = \frac{1}{2s} - \frac{1}{s+1} + \frac{1}{2(s+2)} and a square wave input of half period hh, each mode has a periodic response in closed form, and the condition y(0)=0y(0) = 0 at the switch becomes −h/4+tanh⁡(h/2)−tanh⁡(h)/4=0-h/4 + \tanh(h/2) - \tanh(h)/4 = 0. Its root is h≈2.2755h \approx 2.2755, so the true period is 4.55114.5511 and the true amplitude is 0.220040.22004. The prediction is 2.4%2.4\% low in the period and 3.6%3.6\% low in the amplitude. A simulation agrees with the exact values to better than 0.5%0.5\%. The error is small because ∣G(3j2)∣/∣G(j2)∣≈0.069|G(3j\sqrt 2)| / |G(j\sqrt 2)| \approx 0.069 and the third harmonic of a square wave is 1/31/3 of its fundamental, so the third harmonic in yy is about 2.3%2.3\% of the fundamental.

Relay autotuning uses this experiment to estimate the ultimate gain Ku≈4d/(πa)K_u \approx 4d/(\pi a) and the ultimate period Tu≈TT_u \approx T of a process. Here it would read Ku≈5.79K_u \approx 5.79 and Tu≈4.55T_u \approx 4.55, against the true values 66 and 4.4434.443.

Saturation. Take G(s)=K/(s(s+1)(s+2))G(s) = K/(s(s+1)(s+2)) with a unit saturation (k=1k = 1, δ=1\delta = 1). The Nyquist plot crosses the negative real axis at −K/6-K/6, and −1/N(a)-1/N(a) covers (−∞,−1](-\infty, -1], since NN falls from 11 to 00. For K<6K < 6 the two curves do not meet and no cycle is predicted; the loop with gain 11 is asymptotically stable, and a simulation from y(0)=3y(0) = 3 with K=3K = 3 decays to zero. For K>6K > 6 they meet at N(a)=6/KN(a) = 6/K. For K=10K = 10 this gives a≈2.033a \approx 2.033 at ω=2\omega = \sqrt 2, and the cycle attracts. A simulation gives an amplitude of about 2.072.07 and a period of about 4.494.49.

Relay with hysteresis. With the same plant, d=1d = 1 and h=0.1h = 0.1, the intersection with the half line Im⁡=−π/40\operatorname{Im} = -\pi/40 is at ω≈1.053\omega \approx 1.053 and a≈0.3684a \approx 0.3684, a period of 5.9675.967. The hysteresis adds phase lag, so the frequency is lower than for the ideal relay. A simulation gives about 0.3810.381 and 6.086.08.

Variations

  • Dual-input describing functions. For a nonlinearity without odd symmetry, or with a bias in the loop, use the input b+asin⁡ωtb + a \sin \omega t and balance the mean and the first harmonic together.
  • Random-input describing functions. For a Gaussian input, the best linear gain in the mean square sense is the statistical linearization used for loops driven by noise. Gelb and Vander Velde treat this and the two-sinusoid case.
  • Harmonic balance with more harmonics. Keep the harmonics up to order mm in a truncated Fourier series of the periodic solution and solve the larger algebraic system. Numerical codes for periodic solutions of nonlinear differential equations use this form, and the first-harmonic method of this page is its simplest case.
  • Rigorous versions. Error bounds of Bergen, Franks and Mees take the dropped harmonics into account. They give a region around each intersection that must contain the true cycle and conditions under which a cycle does exist.
  • Exact relay oscillations. For a relay loop, the exact symmetric oscillation can be found from the closed-form response to a square wave, as in the example; Tsypkin's method does this in general.

Pitfalls

  • The method is not a proof. It can predict a limit cycle that does not exist, and it can miss one that does. The risk is high when GG has a resonance near a harmonic of the predicted frequency, or when GG is not low pass.
  • A missing intersection does not prove that the loop has no oscillation, and it does not prove that the equilibrium is globally asymptotically stable. The guess that the loop is globally asymptotically stable whenever the linear loop is asymptotically stable for every gain in the sector of ϕ\phi is Aizerman's conjecture, which is false in general.
  • Use the sign convention of the loop. With negative feedback the curve is −1/N(a)-1/N(a); with positive feedback it is +1/N(a)+1/N(a).
  • With several intersections, check each one; attracting and repelling predicted cycles often alternate.
  • For an element with memory, NN depends on the frequency too, and the real-NN procedure does not apply.
  • When the phase of GG never reaches −180°-180°, the method predicts no cycle with an ideal relay. The true loop can then switch at a frequency that is limited only by the switching speed of the relay. For G=1/(s(s+1))G = 1/(s(s+1)) a simulation shows solutions that converge to the origin with faster and faster switching.

Code

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.

describing_function.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/describing-function/. The authors are listed in prov/4JVRZW.jsonl.

"""Describing functions and the harmonic balance prediction of limit cycles.

A static nonlinearity phi gets the describing function
N(a) = (b1 + i a1) / a, where b1 and a1 are the first Fourier coefficients
of phi(a sin t) on one period. The closed forms below are for the ideal
relay, the saturation, the dead zone and the relay with hysteresis.

harmonic_balance() follows the pseudocode of the page (lines L1 to L8): for
a real describing function and a linear part G(s) it finds the phase
crossover w of G, solves N(a) = -1 / G(i w) for the amplitude a, and
reports whether the predicted cycle is attracting and how strongly G
filters the third harmonic.

simulate_loop() integrates the loop u = phi(-y), y = G(s) u for a strictly
proper G in controllable canonical form with the classical fourth-order
Runge-Kutta method, so that a prediction can be compared with the true
oscillation. The method is approximate: the prediction can be wrong, and
the tests show by how much in each example.
"""

import cmath
import math


# ------------------------------------------------------------ nonlinearities
def relay(d):
    return lambda x: d if x > 0 else (-d if x < 0 else 0.0)


def saturation(k, delta):
    return lambda x: k * max(-delta, min(delta, x))


def dead_zone(k, delta):
    def phi(x):
        if x > delta:
            return k * (x - delta)
        if x < -delta:
            return k * (x + delta)
        return 0.0
    return phi


# ------------------------------------------------- closed-form describing functions
def df_relay(d, a):
    return 4.0 * d / (math.pi * a)


def df_saturation(k, delta, a):
    if a <= delta:
        return float(k)
    r = delta / a
    return 2.0 * k / math.pi * (math.asin(r) + r * math.sqrt(1.0 - r * r))


def df_dead_zone(k, delta, a):
    return k - df_saturation(k, delta, a)


def df_relay_hysteresis(d, h, a):
    """Complex N(a) of a relay with output +-d that switches at +-h (a > h)."""
    if a <= h:
        raise ValueError("the relay does not switch when a <= h")
    return 4.0 * d / (math.pi * a) * cmath.exp(-1j * math.asin(h / a))


# ------------------------------------------------- numerical describing function
def describing_function(phi, a, m=4096):
    """N(a) = (b1 + i a1) / a for a static phi, by the midpoint rule."""
    h = 2.0 * math.pi / m
    b1 = a1 = 0.0
    for k in range(m):
        t = (k + 0.5) * h
        y = phi(a * math.sin(t))
        b1 += y * math.sin(t)
        a1 += y * math.cos(t)
    return complex(b1 * h / math.pi, a1 * h / math.pi) / a


def describing_function_hysteresis(d, h, a, m=4096):
    """N(a) of the relay with hysteresis from its output on one period."""
    step = 2.0 * math.pi / m
    state = -d  # on the way up from -a the relay is at -d
    b1 = a1 = 0.0
    for k in range(m):
        t = (k + 0.5) * step
        x = a * math.sin(t)
        if x >= h:
            state = d
        elif x <= -h:
            state = -d
        b1 += state * math.sin(t)
        a1 += state * math.cos(t)
    return complex(b1 * step / math.pi, a1 * step / math.pi) / a


# ------------------------------------------------------------- linear parts
def tf(num, den):
    """G(s) = num(s) / den(s), coefficients with the highest power first."""
    def ev(c, s):
        v = 0j
        for x in c:
            v = v * s + x
        return v
    return lambda s: ev(num, s) / ev(den, s)


def _bisect(f, lo, hi, tol=1e-13, it=200):
    flo = f(lo)
    for _ in range(it):
        mid = 0.5 * (lo + hi)
        fm = f(mid)
        if (fm > 0) == (flo > 0):
            lo, flo = mid, fm
        else:
            hi = mid
        if hi - lo < tol * max(1.0, abs(hi)):
            break
    return 0.5 * (lo + hi)


# ------------------------------------------------------------ harmonic balance
def harmonic_balance(G, N, w_lo, w_hi, a_lo, a_hi):
    """Predict a limit cycle for a real describing function N(a).

    G(s) is the linear part, Im G(i w) must change sign once on
    [w_lo, w_hi], and N(a) - r must change sign once on [a_lo, a_hi].
    Returns None when harmonic balance has no solution there. The flag
    'attracting' assumes the usual case in which the loop with a constant
    gain k in place of N is asymptotically stable for k < r and unstable
    for k > r near the crossing.
    """
    if (G(1j * w_lo).imag > 0) == (G(1j * w_hi).imag > 0):  # @line L1
        return None  # @line L1
    w = _bisect(lambda x: G(1j * x).imag, w_lo, w_hi)  # @line L1
    g = G(1j * w).real  # @line L2
    if g >= 0:  # @line L2
        return None  # @line L2
    r = -1.0 / g  # @line L3
    if (N(a_lo) - r > 0) == (N(a_hi) - r > 0):  # @line L4
        return None  # @line L4
    a = _bisect(lambda x: N(x) - r, a_lo, a_hi)  # @line L5
    da = 1e-6 * a  # @line L6
    slope = (N(a + da) - N(a - da)) / (2 * da)  # @line L6
    q = abs(G(3j * w)) / abs(G(1j * w))  # @line L7
    return {"a": a, "w": w, "period": 2 * math.pi / w, "gain": r,  # @line L8
            "attracting": slope < 0, "filter": q}  # @line L8


def harmonic_balance_complex(G, N, w0, a0, tol=1e-12, it=100):
    """Solve G(i w) N(a) + 1 = 0 for (w, a) by Newton's method.

    N may be complex, for example a relay with hysteresis. The Jacobian is
    taken by central differences. Returns None if Newton does not converge.
    """
    w, a = float(w0), float(a0)
    for _ in range(it):
        F = G(1j * w) * N(a) + 1
        if abs(F) < tol:
            return {"a": a, "w": w, "period": 2 * math.pi / w}
        hw, ha = 1e-7 * w, 1e-7 * a
        Fw = (G(1j * (w + hw)) * N(a) - G(1j * (w - hw)) * N(a)) / (2 * hw)
        Fa = (G(1j * w) * N(a + ha) - G(1j * w) * N(a - ha)) / (2 * ha)
        det = Fw.real * Fa.imag - Fa.real * Fw.imag
        if det == 0:
            return None
        dw = (F.real * Fa.imag - Fa.real * F.imag) / det
        step_a = (Fw.real * F.imag - F.real * Fw.imag) / det
        w, a = w - dw, a - step_a
        if w <= 0 or a <= 0:
            return None
    return None


# ------------------------------------------------------------------ simulation
def simulate_loop(num, den, nonlinearity, x0, dt, T, hysteresis=None):
    """Simulate u = phi(-y), y = (num/den) u, with den monic and deg num < deg den.

    The state is the controllable canonical form. The input is held over
    each RK4 step. With hysteresis = (d, h) the relay with hysteresis is
    used instead of 'nonlinearity'. Returns the samples of y and the step.
    """
    n = len(den) - 1
    if abs(den[0] - 1.0) > 0 or len(num) > n:
        raise ValueError("den must be monic and G strictly proper")
    c = [0.0] * (n - len(num)) + [float(v) for v in num]
    c = list(reversed(c))  # c[i] multiplies x_{i+1}
    a = [float(v) for v in reversed(den[1:])]  # a[i] multiplies x_{i+1}

    def out(x):
        return sum(ci * xi for ci, xi in zip(c, x))

    def f(x, u):
        dx = x[1:] + [u - sum(ai * xi for ai, xi in zip(a, x))]
        return dx

    x = [float(v) for v in x0]
    steps = int(round(T / dt))
    ys = [out(x)]
    state = None
    if hysteresis is not None:
        d, h = hysteresis
        state = d if -out(x) >= 0 else -d
    for _ in range(steps):
        e = -out(x)
        if hysteresis is not None:
            if e >= h:
                state = d
            elif e <= -h:
                state = -d
            u = state
        else:
            u = nonlinearity(e)
        k1 = f(x, u)
        k2 = f([xi + dt / 2 * ki for xi, ki in zip(x, k1)], u)
        k3 = f([xi + dt / 2 * ki for xi, ki in zip(x, k2)], u)
        k4 = f([xi + dt * ki for xi, ki in zip(x, k3)], u)
        x = [xi + dt / 6 * (p + 2 * q + 2 * r + s) for xi, p, q, r, s in zip(x, k1, k2, k3, k4)]
        ys.append(out(x))
    return ys


def measure_cycle(ys, dt, last=4):
    """Amplitude and period of the oscillation over the last upward zero crossings."""
    ups = []
    for k in range(1, len(ys)):
        if ys[k - 1] < 0 <= ys[k]:
            ups.append((k - 1) + (-ys[k - 1]) / (ys[k] - ys[k - 1]))
    if len(ups) < last + 1:
        return None
    period = (ups[-1] - ups[-1 - last]) / last * dt
    start = int(ups[-1 - last])
    seg = ys[start:int(ups[-1]) + 1]
    amp = (max(seg) - min(seg)) / 2
    return {"a": amp, "period": period}
test_describing_function.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/describing-function/. The authors are listed in prov/4JVRZW.jsonl.

import math

import pytest

from describing_function import (
    dead_zone,
    describing_function,
    describing_function_hysteresis,
    df_dead_zone,
    df_relay,
    df_relay_hysteresis,
    df_saturation,
    harmonic_balance,
    harmonic_balance_complex,
    measure_cycle,
    relay,
    saturation,
    simulate_loop,
    tf,
)

DEN = [1, 3, 2, 0]  # s (s + 1) (s + 2)


def exact_relay_cycle():
    """Exact symmetric oscillation of the relay loop with 1 / (s (s + 1) (s + 2)).

    G = 1/(2s) - 1/(s + 1) + 1/(2 (s + 2)). For a square wave input of
    half period h, the periodic response of each mode is known in closed
    form, and y(0) = 0 gives -h/4 + tanh(h/2) - tanh(h)/4 = 0.
    """
    def g(h):
        return -h / 4 + math.tanh(h / 2) - math.tanh(h) / 4

    lo, hi = 2.0, 2.5
    for _ in range(100):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if g(mid) > 0 else (lo, mid)
    h = (lo + hi) / 2
    x1, x2 = -math.tanh(h / 2), -math.tanh(h) / 2

    def y(t):
        e1, e2 = math.exp(-t), math.exp(-2 * t)
        return 0.5 * (t - h / 2) - (e1 * x1 + 1 - e1) + 0.5 * (e2 * x2 + (1 - e2) / 2)

    vals = [y(h * k / 20000) for k in range(1, 20000)]
    assert max(vals) < 0  # one sign change per half period
    return 2 * h, -min(vals)


def test_closed_forms_match_fourier_integrals():
    for a in (0.3, 1.0, 2.5, 7.0):
        assert describing_function(relay(1.5), a).real == pytest.approx(df_relay(1.5, a), rel=1e-5)
        assert describing_function(saturation(2.0, 1.0), a).real == pytest.approx(df_saturation(2.0, 1.0, a), rel=1e-6)
        assert describing_function(dead_zone(2.0, 1.0), a).real == pytest.approx(df_dead_zone(2.0, 1.0, a), abs=1e-6)
        assert abs(describing_function(relay(1.5), a).imag) < 1e-9
    for a in (0.2, 0.5, 3.0):
        num = describing_function_hysteresis(1.0, 0.1, a, m=20000)
        assert abs(num - df_relay_hysteresis(1.0, 0.1, a)) < 1e-3 * abs(num)


def test_inverse_hysteresis_df_is_a_horizontal_line():
    d, h = 2.0, 0.3
    for a in (0.31, 0.5, 1.0, 4.0):
        z = -1 / df_relay_hysteresis(d, h, a)
        assert z.imag == pytest.approx(-math.pi * h / (4 * d))
        assert z.real == pytest.approx(-math.pi * math.sqrt(a * a - h * h) / (4 * d))


def test_saturation_and_dead_zone_limits():
    assert df_saturation(3.0, 1.0, 0.5) == 3.0
    assert df_saturation(3.0, 1.0, 1e6) == pytest.approx(4 * 3.0 / (math.pi * 1e6), rel=1e-6)
    assert df_dead_zone(3.0, 1.0, 1.0) == pytest.approx(0.0)
    vals = [df_saturation(1.0, 1.0, 1 + 0.5 * k) for k in range(20)]
    assert all(x > y for x, y in zip(vals, vals[1:]))


def test_relay_prediction():
    r = harmonic_balance(tf([1], DEN), lambda a: df_relay(1.0, a), 0.5, 5.0, 1e-3, 10.0)
    assert r["w"] == pytest.approx(math.sqrt(2), rel=1e-10)
    assert r["gain"] == pytest.approx(6.0, rel=1e-10)
    assert r["a"] == pytest.approx(2 / (3 * math.pi), rel=1e-10)
    assert r["period"] == pytest.approx(math.pi * math.sqrt(2), rel=1e-10)
    assert r["attracting"]
    assert r["filter"] == pytest.approx(0.06917, abs=1e-5)


def test_relay_prediction_against_the_true_cycle():
    T, A = exact_relay_cycle()
    assert T == pytest.approx(4.5511, abs=1e-4)
    assert A == pytest.approx(0.22004, abs=1e-5)
    ys = simulate_loop([1], DEN, relay(1.0), [0.1, 0.0, 0.0], 1e-3, 30.0)
    m = measure_cycle(ys, 1e-3)
    assert m["period"] == pytest.approx(T, rel=5e-3)
    assert m["a"] == pytest.approx(A, rel=5e-3)
    # The prediction is low by about 2.4 % in the period and 3.6 % in the amplitude.
    assert (math.pi * math.sqrt(2) - T) / T == pytest.approx(-0.0238, abs=1e-3)
    assert (2 / (3 * math.pi) - A) / A == pytest.approx(-0.0356, abs=1e-3)


def test_saturation_loop():
    K = 10
    r = harmonic_balance(tf([K], DEN), lambda a: df_saturation(1.0, 1.0, a), 0.5, 5.0, 1.0 + 1e-9, 100.0)
    assert df_saturation(1.0, 1.0, r["a"]) == pytest.approx(0.6)
    assert r["a"] == pytest.approx(2.0331, abs=1e-4)
    assert r["attracting"]
    ys = simulate_loop([K], DEN, saturation(1.0, 1.0), [0.1, 0.0, 0.0], 4e-3, 50.0)
    m = measure_cycle(ys, 4e-3)
    assert m["a"] == pytest.approx(r["a"], rel=0.03)
    assert m["period"] == pytest.approx(r["period"], rel=0.02)


def test_no_cycle_when_the_linear_loop_is_asymptotically_stable():
    K = 3  # the loop with gain 1 is asymptotically stable for K < 6
    r = harmonic_balance(tf([K], DEN), lambda a: df_saturation(1.0, 1.0, a), 0.5, 5.0, 1.0 + 1e-9, 100.0)
    assert r is None
    ys = simulate_loop([K], DEN, saturation(1.0, 1.0), [3.0, 0.0, 0.0], 4e-3, 60.0)
    assert max(abs(v) for v in ys[-500:]) < 0.05


def test_second_order_plant_has_no_phase_crossover():
    assert harmonic_balance(tf([1], [1, 1, 0]), lambda a: df_relay(1.0, a), 0.01, 100.0, 1e-3, 10.0) is None


def test_relay_with_hysteresis():
    d, h = 1.0, 0.1
    G = tf([1], DEN)
    r = harmonic_balance_complex(G, lambda a: df_relay_hysteresis(d, h, a), 1.0, 0.3)
    assert abs(G(1j * r["w"]) * df_relay_hysteresis(d, h, r["a"]) + 1) < 1e-10
    assert G(1j * r["w"]).imag == pytest.approx(-math.pi * h / (4 * d))
    assert r["a"] == pytest.approx(0.36836, abs=1e-5)
    assert r["period"] == pytest.approx(5.9667, abs=1e-4)
    ys = simulate_loop([1], DEN, None, [0.1, 0.0, 0.0], 2e-3, 40.0, hysteresis=(d, h))
    m = measure_cycle(ys, 2e-3)
    assert m["a"] == pytest.approx(r["a"], rel=0.05)
    assert m["period"] == pytest.approx(r["period"], rel=0.03)

Exercises

  1. Derive N(a)=4d/(πa)N(a) = 4d/(\pi a) for the ideal relay from the integral for b1b_1.
  2. Derive the describing function of the saturation, and show that it decreases from kk to 00 as aa goes from δ\delta to ∞\infty.
  3. For the relay with hysteresis, show that −1/N(a)-1/N(a) lies on the line Im⁡z=−πh/(4d)\operatorname{Im} z = -\pi h/(4d), and explain why hysteresis lowers the frequency of a relay oscillation.
  4. Predict the oscillation of an ideal relay with d=1d = 1 in a loop with G(s)=1/(s+1)3G(s) = 1/(s+1)^3. (Answer: ω=3\omega = \sqrt 3, G(j3)=−1/8G(j\sqrt 3) = -1/8, a=1/(2π)≈0.159a = 1/(2\pi) \approx 0.159, T≈3.628T \approx 3.628. A simulation gives about 0.1630.163 and 3.683.68.)
  5. For the saturation loop with K=20K = 20, find the predicted amplitude and decide whether the cycle attracts. (Answer: a≈4.20a \approx 4.20; it attracts.)

References

  1. Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 7.2, The Describing Function Method
  2. Arthur Gelb and Wallace E. Vander Velde, Multiple-Input Describing Functions and Nonlinear System Design, McGraw-Hill, 1968, Chapter 2, the sinusoidal-input describing function and its tables for common nonlinearities
  3. N. Krylov and N. Bogoliubov, Introduction to Non-Linear Mechanics, translated by S. Lefschetz, Annals of Mathematics Studies 11, Princeton University Press, 1943, the method of equivalent linearization by the first harmonic

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples