Algorithm Search⌘K

Techniquecore

Lead-lag compensator

Also called phase-lead compensation, phase-lag compensation.

A first-order compensator that adds phase near crossover when its zero lies below its pole, or raises the low frequency gain when its pole lies below its zero.

A lead-lag compensator is a controller built from first-order factors of the form (1+τzs)/(1+τps)(1 + \tau_z s)/(1 + \tau_p s), one real zero and one real pole, placed in series with the plant PP of a unity negative feedback loop with L=PCL = PC. A lead network has its zero below its pole, C(s)=(1+αTs)/(1+Ts)C(s) = (1 + \alpha T s)/(1 + T s) with α>1\alpha > 1. It adds positive phase in a band of frequencies, and the designer puts that band at the gain crossover to raise the phase margin. A lag network has its pole below its zero, C(s)=(1+Ts)/(1+βTs)C(s) = (1 + T s)/(1 + \beta T s) with β>1\beta > 1. It lowers the gain at high frequency by the factor β\beta with little phase loss there, so the gain at low frequency can be β\beta times higher for the same crossover. Both factors have C(0)=1C(0) = 1, and a separate gain kk sets the error constant. These are the standard building blocks of classical loop shaping on the Bode plot.

In plain words

A plant often has too little phase where its gain curve passes through one, so the closed loop rings or is close to instability. A lead network is a small filter that pushes the phase up in a band of frequencies. The designer puts the top of that band where the loop gain passes through one, and the ringing goes away. The cost is more gain at high frequency, so more sensor noise gets through. A lag network does the opposite job. It cuts the gain at high frequency and keeps the phase almost the same there. So the designer can use a high gain for slow signals, which gives small steady errors, and the loop still has a safe crossover. The cost is a slower loop. A lag-lead network uses one of each.

When it applies

  • The plant is linear, time invariant, and single input single output, with a model P(s)P(s) or a measured frequency response, and the specifications are an error constant, a phase margin or a peak sensitivity, and a crossover frequency or bandwidth.
  • Lead fits when the phase margin is too small at the crossover that the error constant gives, and when the plant phase falls slowly near that crossover. One lead network gives at most 90 degrees, and in practice about 50 to 60 degrees; for more, two networks are used in series.
  • Lag fits when the phase margin is good at a lower frequency and the specifications allow that lower crossover, but the low frequency gain is too small. It does not add phase; it moves the crossover down to a frequency where the plant phase is already good enough.
  • Neither network fixes a plant whose phase falls fast near the wanted crossover, for example with a long time delay or a zero in the right half plane. The Bode gain-phase relation holds for these networks as for any minimum-phase factor, so the phase they add always comes with a gain slope.

The template

The lead network. For C(s)=(1+αTs)/(1+Ts)C(s) = (1 + \alpha T s)/(1 + T s) with α>1\alpha > 1 and T>0T > 0, the phase is φ(ω)=arctan⁡(αTω)−arctan⁡(Tω)\varphi(\omega) = \arctan(\alpha T\omega) - \arctan(T\omega), which is positive for all ω>0\omega > 0. It is largest at the geometric mean of the corner frequencies 1/(αT)1/(\alpha T) and 1/T1/T,

ωm=1Tα,sin⁡φmax⁡=α−1α+1,∣C(jωm)∣=α.\omega_m = \frac{1}{T\sqrt\alpha}, \qquad \sin\varphi_{\max} = \frac{\alpha - 1}{\alpha + 1}, \qquad |C(j\omega_m)| = \sqrt\alpha.

The gain rises from 1 at low frequency to α\alpha at high frequency, and at ωm\omega_m it is halfway in dB, 10log⁡10α10\log_{10}\alpha. Conversely, a lead of φ\varphi degrees needs α=(1+sin⁡φ)/(1−sin⁡φ)\alpha = (1 + \sin\varphi)/(1 - \sin\varphi):

α\alpha 2 4 7.5486 10 13.928
φmax⁡\varphi_{\max} (degrees) 19.47 36.87 50 54.90 60
gain at ωm\omega_m (dB) 3.01 6.02 8.78 10.00 11.44

The lag network. The lag C(s)=(1+Ts)/(1+βTs)C(s) = (1 + T s)/(1 + \beta T s) is the reciprocal of the lead with the same parameters, so its phase is the negative of the lead phase and its gain falls from 1 to 1/β1/\beta. Far above its corners it is almost a pure gain 1/β1/\beta.

The design steps. First set the gain kk of PP from the error constant. Then:

  1. LEAD-LAG-DESIGN(P, pm, extra) ▷ P already holds the gain k
  2. 1(ωc, pm0) ← gain crossover and phase margin of P
  3. 2if pm0 ≥ pm then return C = 1
  4. 3if a lead network is chosen then
  5. 4φ ← pm - pm0 + extra ▷ extra pays for the move of the crossover
  6. 5α ← (1 + sin φ)/(1 - sin φ)
  7. 6ωm ← the highest ω with |P(jω)| = 1/√α
  8. 7T ← 1/(ωm √α)
  9. 8return C(s) = (1 + αTs)/(1 + Ts)
  10. 9else ▷ a lag network
  11. 10ωc ← the highest ω with arg P(jω) = -180 + pm + extra degrees
  12. 11β ← |P(jωc)|
  13. 12T ← 10/ωc ▷ the lag zero a decade below ωc
  14. 13return C(s) = (1 + Ts)/(1 + βTs)

Then check the result: compute the margins and the peak MsM_s of the sensitivity function, confirm with the closed-loop poles or the Nyquist stability criterion that the loop is asymptotically stable, and look at the step response. If the margin is short, raise extra and repeat.

Why it works. For the lead, the derivative of φ(ω)\varphi(\omega) is zero where αT2ω2=1\alpha T^2\omega^2 = 1, which gives ωm\omega_m, and there tan⁡φmax⁡=(α−1)/(2α)\tan\varphi_{\max} = (\alpha - 1)/(2\sqrt\alpha), which is the same as the sine formula. Line L6 puts ωm\omega_m at the new crossover: the network adds the gain α\sqrt\alpha at ωm\omega_m, so ∣P(jωm)∣=1/α|P(j\omega_m)| = 1/\sqrt\alpha makes ∣L(jωm)∣=1|L(j\omega_m)| = 1. The crossover moves up, where the plant phase is lower, and extra pays for that loss. For the lag, at ωc=10/T\omega_c = 10/T the network has the gain 1/β1/\beta to within 0.5 percent, so ∣L(jωc)∣≈1|L(j\omega_c)| \approx 1 by line L11, and its phase there is about −(1−1/β)/10-(1 - 1/\beta)/10 radians, at most 5.7 degrees, which is why extra is about 5 degrees. The error constant does not change, because C(0)=1C(0) = 1.

Classic examples

A lead network for a fast loop. Let P(s)=10/(s(s+1))P(s) = 10/(s(s + 1)), so the velocity constant is Kv=lim⁡s→0sP(s)=10K_v = \lim_{s \to 0} sP(s) = 10 per second, and ask for a phase margin of at least 45 degrees. Without compensation the crossover is at 3.08423 rad/s, the phase margin is 17.96 degrees and Ms=3.35157M_s = 3.35157. The margin is 27 degrees short; with about 10 degrees extra for the move of the crossover, take a lead of 37 degrees, α=4\alpha = 4 (φmax⁡=36.87\varphi_{\max} = 36.87 degrees). The plant gain is 1/4=1/21/\sqrt 4 = 1/2 where ω2(ω2+1)=400\omega^2(\omega^2 + 1) = 400, that is, at

ωm=(−1+1601)/2=4.41659,T=12ωm=0.11321,αT=0.45284.\omega_m = \sqrt{\big(-1 + \sqrt{1601}\big)/2} = 4.41659, \qquad T = \frac{1}{2\omega_m} = 0.11321, \qquad \alpha T = 0.45284.

The plant phase there is −90−arctan⁡4.41659=−167.24-90 - \arctan 4.41659 = -167.24 degrees, so the new margin is 180−167.24+36.87=49.63180 - 167.24 + 36.87 = 49.63 degrees. The loop

L(s)=10(1+0.45284s)s(s+1)(1+0.11321s)L(s) = \frac{10(1 + 0.45284 s)}{s(s + 1)(1 + 0.11321 s)}

has its only crossover at 4.41659 rad/s, Ms=1.42139M_s = 1.42139 at 6.613 rad/s, an infinite gain margin, and closed-loop poles −3.31691±4.07521j-3.31691 \pm 4.07521j and −3.19936-3.19936. You can check the lead formula by hand with α=4\alpha = 4 and T=1T = 1: at ω=0.5\omega = 0.5, arctan⁡2−arctan⁡0.5=63.43−26.57=36.87\arctan 2 - \arctan 0.5 = 63.43 - 26.57 = 36.87 degrees, and ∣C∣=5/1.25=2|C| = \sqrt 5/\sqrt{1.25} = 2.

A lag network for the same plant. Keep Kv=10K_v = 10 and ask for a phase margin of 50 degrees with a lag network, with extra = 5 degrees. The plant phase is −90−arctan⁡ω-90 - \arctan\omega, which is −125-125 degrees at ωc=tan⁡35∘=0.70021\omega_c = \tan 35^\circ = 0.70021. There β=∣P(jωc)∣=11.6987\beta = |P(j\omega_c)| = 11.6987, and T=10/ωc=14.2815T = 10/\omega_c = 14.2815, so

C(s)=1+14.2815s1+167.07s.C(s) = \frac{1 + 14.2815 s}{1 + 167.07 s}.

The network costs 5.22 degrees at ωc\omega_c, a little more than the 5 degrees allowed. The loop has its crossover at 0.70279 rad/s, a phase margin of 49.70 degrees, Ms=1.48123M_s = 1.48123 and closed-loop poles −0.46513±0.75762j-0.46513 \pm 0.75762j and −0.07573-0.07573.

loop crossover (rad/s) phase margin (degrees) MsM_s slowest closed-loop pole high frequency gain of CC
PP alone 3.08423 17.96 3.35157 −0.5±3.12250j-0.5 \pm 3.12250j 1
with the lead 4.41659 49.63 1.42139 −3.19936-3.19936 4
with the lag 0.70279 49.70 1.48123 −0.07573-0.07573 0.0855

Both designs reach about the same margin with the same KvK_v, but in different ways. The lead keeps the loop fast and raises its noise gain by 4. The lag makes the loop about six times slower, and its slowest pole sits near the lag zero at −1/T=−0.07002-1/T = -0.07002, so the step response has a small slow tail.

Variations

  • Lag-lead network. A lag network and a lead network in series, the lag for the error constant and the lead for the margin. A common form is ((1+T1s)/(1+βT1s))((1+T2s)/(1+T2s/β))\big((1 + T_1 s)/(1 + \beta T_1 s)\big)\big((1 + T_2 s)/(1 + T_2 s/\beta)\big) with one parameter for both parts.
  • Two leads in series. For more than about 60 degrees, two networks of half the lead each need a much smaller total α\alpha: two networks of 30 degrees need α=3\alpha = 3 each, so 9 in total, against α=13.93\alpha = 13.93 for one network of 60 degrees.
  • PD and PI as limits. If T→0T \to 0 with αT=Td\alpha T = T_d fixed, the lead becomes 1+Tds1 + T_d s, the PD factor. If β→∞\beta \to \infty, β\beta times the lag becomes (1+Ts)/(Ts)(1 + T s)/(T s), the PI factor of a PID controller. The lead is a PD factor with a filter, and the lag is a PI factor with a finite low frequency gain.
  • Design on other charts. The same networks can be placed on the Nichols chart, where the lead moves the curve to the right near crossover, or with the root locus, where the zero and pole are put to pull the dominant closed-loop poles to a wanted place.
  • Digital lead and lag. A network for a sampled loop is designed in continuous time and then mapped, for example by the bilinear transform (controller discretization), or designed directly in zz.
  • Notation. Ogata writes the lead as (Ts+1)/(αTs+1)(Ts + 1)/(\alpha T s + 1) with 0<α<10 < \alpha < 1, the reciprocal of the α\alpha used here.

Pitfalls

  • Too much lead. A large α\alpha moves the crossover far up, where the plant phase is low, so each added degree of lead buys less margin. The high frequency gain α\alpha also multiplies sensor noise into the actuator. Above about α=10\alpha = 10 to 15, use two networks or change the specifications.
  • Forgetting the move of the crossover. The lead adds the gain α\sqrt\alpha at ωm\omega_m, so a design that puts ωm\omega_m at the old crossover ends with a crossover at a higher frequency and a smaller margin than planned.
  • A lag zero too close to crossover. If the lag zero is put a factor 5 below the crossover instead of 10, the lag costs more phase at the crossover. In the example the margin then falls to 44.43 degrees, and with a factor 20 it rises to 52.36 degrees, but the slow closed-loop pole moves from −0.16459-0.16459 to −0.03638-0.03638, which makes the tail of the step response longer.
  • The slow tail of a lag. A lag design leaves a closed-loop pole near the lag zero. The pair nearly cancels in the reference response, but the slow pole shows fully in the response to a load disturbance.
  • Trusting the phase margin alone. Check MsM_s and the gain margin too, and check stability of the closed loop; a loop with an unstable plant can have a good-looking phase margin and still be unstable.
  • A plant with a delay or a zero in the right half plane. The phase of such a plant falls fast with frequency, so the lead loses its effect when the crossover moves up. The crossover frequency then has a limit that no lead network can remove.

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
lead_lag_compensator.py 319 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lead-lag-compensator/. The authors are listed in prov/8T0JHX.jsonl.

"""Lead and lag compensators, designed on the Bode plot of the loop.

A transfer function is a pair (num, den) of polynomials in s, highest power
first. The loop is the unity negative feedback loop with L = P C.

- lead(alpha, T) is C(s) = (1 + alpha T s) / (1 + T s) with alpha > 1.
- lag(beta, T) is C(s) = (1 + T s) / (1 + beta T s) with beta > 1.

Both have C(0) = 1, so a separate gain k sets the low frequency gain.
Phases are in degrees and frequencies in rad/s.
"""

import bisect
import cmath
import functools
import math

from ctlmat import polyadd, polymul, polyroots, polyval

__all__ = [
    "lead", "lag", "series", "freq", "phase_deg", "max_lead",
    "alpha_for_phase", "place_lead", "design_lag", "margins",
    "design", "closed_loop_poles",
]

W_LO = 1e-4
W_HI = 1e4
PER_DECADE = 200


def lead(alpha, T):
    """Return (num, den) of the lead network (1 + alpha T s) / (1 + T s)."""
    if not alpha > 1 or not T > 0:
        raise ValueError("lead: need alpha > 1 and T > 0")
    return [alpha * T, 1.0], [T, 1.0]


def lag(beta, T):
    """Return (num, den) of the lag network (1 + T s) / (1 + beta T s)."""
    if not beta > 1 or not T > 0:
        raise ValueError("lag: need beta > 1 and T > 0")
    return [T, 1.0], [beta * T, 1.0]


def series(*systems):
    """Return the product of the transfer functions (num, den)."""
    num, den = [1.0], [1.0]
    for n, d in systems:
        num = polymul(num, n)
        den = polymul(den, d)
    return num, den


def freq(num, den, w):
    """Return the complex value G(j w)."""
    s = 1j * w
    return polyval(num, s) / polyval(den, s)


def _trailing(p):
    """Return (number of roots at s = 0, lowest nonzero coefficient)."""
    count = 0
    for c in reversed(p):
        if c != 0:
            return count, c
        count += 1
    raise ValueError("zero polynomial")


def phase_deg(num, den, w):
    """Return the continuous phase of G(j w) in degrees, for W_LO <= w <= W_HI.

    At low frequency G(j w) is close to c (j w)^m, where m is the number of
    zeros at s = 0 minus the number of poles there, so the phase starts at
    90 m degrees (minus 180 if c < 0). From there the phase is unwrapped
    along a logarithmic grid, so it has no jumps of 360 degrees.
    """
    return _cached_phase_fn(tuple(num), tuple(den))(w)


@functools.lru_cache(maxsize=64)
def _cached_phase_fn(num, den):
    return _phase_fn(list(num), list(den))


def _phase_fn(num, den):
    zn, cn = _trailing(num)
    zd, cd = _trailing(den)
    base = 90.0 * (zn - zd) + (0.0 if cn / cd > 0 else -180.0)
    grid = _grid()
    unwrapped = []
    ref = base
    for w in grid:
        raw = math.degrees(cmath.phase(freq(num, den, w)))
        ref = raw + 360.0 * round((ref - raw) / 360.0)
        unwrapped.append(ref)

    def ph(w):
        if not W_LO <= w <= W_HI:
            raise ValueError("phase_deg: w is outside the grid")
        i = min(bisect.bisect_left(grid, w), len(grid) - 1)
        raw = math.degrees(cmath.phase(freq(num, den, w)))
        return raw + 360.0 * round((unwrapped[i] - raw) / 360.0)

    return ph


def max_lead(alpha, T):
    """Return (phi_max in degrees, omega_m, |C(j omega_m)|) of lead(alpha, T)."""
    if not alpha > 1 or not T > 0:
        raise ValueError("max_lead: need alpha > 1 and T > 0")
    phi = math.degrees(math.asin((alpha - 1) / (alpha + 1)))
    return phi, 1.0 / (T * math.sqrt(alpha)), math.sqrt(alpha)


def alpha_for_phase(phi):
    """Return alpha whose lead network has a largest phase of phi degrees."""
    if not 0 < phi < 90:
        raise ValueError("alpha_for_phase: need 0 < phi < 90 degrees")
    s = math.sin(math.radians(phi))
    return (1 + s) / (1 - s)


def _grid():
    n = int(round(math.log10(W_HI / W_LO) * PER_DECADE))
    return [W_LO * (W_HI / W_LO) ** (i / n) for i in range(n + 1)]


def _bisect(f, a, b, iters=100):
    """Root of f between a and b (f(a), f(b) of opposite signs), in log w."""
    fa = f(a)
    la, lb = math.log(a), math.log(b)
    for _ in range(iters):
        lm = 0.5 * (la + lb)
        fm = f(math.exp(lm))
        if (fm > 0) == (fa > 0):
            la, fa = lm, fm
        else:
            lb = lm
    return math.exp(0.5 * (la + lb))


def _crossings(f, grid):
    out = []
    prev_w, prev_f = grid[0], f(grid[0])
    for w in grid[1:]:
        fw = f(w)
        if fw == 0:
            out.append(w)
        elif (fw > 0) != (prev_f > 0) and prev_f != 0:
            out.append(_bisect(f, prev_w, w))
        prev_w, prev_f = w, fw
    return out


def _log_gain(num, den):
    return lambda w: math.log(abs(freq(num, den, w)))


def place_lead(num, den, alpha):
    """Place lead(alpha, T) on the plant (num, den), gain already set.

    The largest lead is put at the new crossover: omega_m is the highest
    frequency where |P(j omega)| = 1/sqrt(alpha), because the lead adds
    sqrt(alpha) of gain there. Return (C_num, C_den, omega_m, T).
    """
    if not alpha > 1:
        raise ValueError("place_lead: need alpha > 1")
    target = -0.5 * math.log(alpha)
    lg = _log_gain(num, den)
    xs = _crossings(lambda w: lg(w) - target, _grid())
    if not xs:
        raise ValueError("place_lead: |P| never equals 1/sqrt(alpha)")
    wm = xs[-1]
    T = 1.0 / (wm * math.sqrt(alpha))
    cn, cd = lead(alpha, T)
    return cn, cd, wm, T


def design_lag(num, den, pm, allowance=5.0, ratio=10.0):
    """Design lag(beta, T) for a phase margin of pm degrees on the plant.

    The new crossover omega_c is the highest frequency where the plant phase
    is -180 + pm + allowance degrees; the allowance pays for the phase lag
    that the lag network keeps at omega_c. Then beta = |P(j omega_c)|, so
    that the lag brings the gain at omega_c down to 1, and the lag zero
    1/T is put a factor ratio below omega_c. Return (C_num, C_den, omega_c,
    beta, T).
    """
    if not 0 < pm < 180 or not ratio > 1:
        raise ValueError("design_lag: need 0 < pm < 180 and ratio > 1")
    target = -180.0 + pm + allowance
    ph = _phase_fn(num, den)
    xs = _crossings(lambda w: ph(w) - target, _grid())
    if not xs:
        raise ValueError("design_lag: the plant phase never reaches the target")
    wc = xs[-1]
    beta = abs(freq(num, den, wc))
    if not beta > 1:
        raise ValueError("design_lag: |P| is not above 1 at the new crossover")
    T = ratio / wc
    cn, cd = lag(beta, T)
    return cn, cd, wc, beta, T


def _golden_max(f, a, b, iters=80):
    g = (math.sqrt(5) - 1) / 2
    la, lb = math.log(a), math.log(b)
    x1 = lb - g * (lb - la)
    x2 = la + g * (lb - la)
    f1, f2 = f(math.exp(x1)), f(math.exp(x2))
    for _ in range(iters):
        if f1 < f2:
            la, x1, f1 = x1, x2, f2
            x2 = la + g * (lb - la)
            f2 = f(math.exp(x2))
        else:
            lb, x2, f2 = x2, x1, f1
            x1 = lb - g * (lb - la)
            f1 = f(math.exp(x1))
    w = math.exp(0.5 * (la + lb))
    return f(w), w


def margins(num, den):
    """Return a dict of the margins of the loop L = num/den.

    Keys: "wgc" (gain crossover frequencies), "pm" (smallest phase margin in
    degrees, None without a gain crossover), "wpc" (phase crossover
    frequencies, where the phase passes -180 + 360 k), "gm" (smallest
    1/|L| over the phase crossovers, math.inf without one), "ms" and "wms"
    (the peak of |S| = 1/|1 + L| and its frequency).
    """
    grid = _grid()
    lg = _log_gain(num, den)
    ph = _phase_fn(num, den)
    wgc = _crossings(lg, grid)
    pms = []
    for w in wgc:
        p = ph(w) + 180.0
        pms.append((p + 180.0) % 360.0 - 180.0)
    hs = [(ph(w) + 180.0) / 360.0 for w in grid]
    wpc = []
    for i in range(1, len(grid)):
        k0, k1 = math.floor(hs[i - 1]), math.floor(hs[i])
        if k0 != k1:
            k = max(k0, k1)
            wpc.append(_bisect(lambda w: ph(w) + 180.0 - 360.0 * k, grid[i - 1], grid[i]))
    gms = [1.0 / abs(freq(num, den, w)) for w in wpc]

    def s_mag(w):
        return 1.0 / abs(1.0 + freq(num, den, w))

    vals = [s_mag(w) for w in grid]
    i = max(range(len(grid)), key=lambda j: vals[j])
    a = grid[max(i - 1, 0)]
    b = grid[min(i + 1, len(grid) - 1)]
    ms, wms = _golden_max(s_mag, a, b)
    if vals[i] > ms:
        ms, wms = vals[i], grid[i]
    return {
        "wgc": wgc,
        "pm": min(pms) if pms else None,
        "wpc": wpc,
        "gm": min(gms) if gms else math.inf,
        "ms": ms,
        "wms": wms,
    }


def design(num, den, pm, kind="lead", extra=None):
    """LEAD-LAG-DESIGN: a lead or lag network for a phase margin of pm degrees.

    The plant (num, den) already holds the gain set by the error constant.
    extra is the phase allowance in degrees (default 10 for lead, 5 for
    lag). Return (C_num, C_den); C = 1 if the plant already has the margin.
    """
    if kind not in ("lead", "lag"):
        raise ValueError("design: kind must be 'lead' or 'lag'")
    if not 0 < pm < 180:
        raise ValueError("design: need 0 < pm < 180")
    if extra is None:
        extra = 10.0 if kind == "lead" else 5.0
    m = margins(num, den)  # @line L1
    pm0 = m["pm"]
    if pm0 is None:
        raise ValueError("design: the plant has no gain crossover")
    if pm0 >= pm:  # @line L2
        return [1.0], [1.0]
    grid = _grid()
    if kind == "lead":  # @line L3
        phi = pm - pm0 + extra  # @line L4
        alpha = alpha_for_phase(phi)  # @line L5
        lg = _log_gain(num, den)
        target = -0.5 * math.log(alpha)
        xs = _crossings(lambda w: lg(w) - target, grid)  # @line L6
        if not xs:
            raise ValueError("design: |P| never equals 1/sqrt(alpha)")
        wm = xs[-1]
        T = 1.0 / (wm * math.sqrt(alpha))  # @line L7
        return lead(alpha, T)  # @line L8
    ph = _phase_fn(num, den)  # @line L9
    xs = _crossings(lambda w: ph(w) - (-180.0 + pm + extra), grid)  # @line L10
    if not xs:
        raise ValueError("design: the plant phase never reaches the target")
    wc = xs[-1]
    beta = abs(freq(num, den, wc))  # @line L11
    if not beta > 1:
        raise ValueError("design: |P| is not above 1 at the new crossover")
    T = 10.0 / wc  # @line L12
    return lag(beta, T)  # @line L13


def closed_loop_poles(num, den):
    """Return the roots of den + num, the poles of L / (1 + L)."""
    return polyroots(polyadd(den, num))
test_lead_lag_compensator.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lead-lag-compensator/. The authors are listed in prov/8T0JHX.jsonl.

import math
import random

import pytest

import ctlmat as cm
from lead_lag_compensator import (
    alpha_for_phase,
    closed_loop_poles,
    design,
    design_lag,
    freq,
    lag,
    lead,
    margins,
    max_lead,
    phase_deg,
    place_lead,
    series,
)

PLANT = ([10.0], [1.0, 1.0, 0.0])


def test_ctlmat_self_test():
    assert cm._self_test()


def test_dc_and_high_frequency_gain():
    num, den = lead(4.0, 0.5)
    assert freq(num, den, 0.0) == 1.0
    assert abs(freq(num, den, 1e9) - 4.0) < 1e-6
    num, den = lag(8.0, 2.0)
    assert freq(num, den, 0.0) == 1.0
    assert abs(freq(num, den, 1e9) - 1.0 / 8.0) < 1e-6


@pytest.mark.parametrize("alpha", [1.5, 2.0, 4.0, 10.0, 100.0])
def test_max_lead_formula_against_sweep(alpha):
    T = 0.7
    num, den = lead(alpha, T)
    phi, wm, gain = max_lead(alpha, T)
    best = max((phase_deg(num, den, 10 ** (k / 2000.0)), 10 ** (k / 2000.0)) for k in range(-8000, 8001))
    assert abs(best[0] - phi) < 1e-5
    assert abs(math.log(best[1] / wm)) < 2e-3
    assert abs(abs(freq(num, den, wm)) - gain) < 1e-12
    assert abs(wm - math.sqrt((1 / T) * (1 / (alpha * T)))) < 1e-12


def test_known_lead_angles():
    assert abs(max_lead(2.0, 1.0)[0] - 19.4712206) < 1e-6
    assert abs(max_lead(4.0, 1.0)[0] - 36.8698976) < 1e-6
    assert abs(max_lead(10.0, 1.0)[0] - 54.9031988) < 1e-6
    assert abs(max_lead(10.0, 1.0)[1] - 0.316227766) < 1e-9


def test_alpha_for_phase_inverts_max_lead():
    rng = random.Random(8)
    for _ in range(50):
        phi = rng.uniform(1.0, 85.0)
        alpha = alpha_for_phase(phi)
        assert abs(max_lead(alpha, 1.0)[0] - phi) < 1e-9


def test_lag_is_inverse_of_lead():
    rng = random.Random(80)
    for _ in range(20):
        r = rng.uniform(1.5, 30.0)
        T = rng.uniform(0.1, 10.0)
        a, b = lead(r, T)
        c, d = lag(r, T)
        for w in (0.01, 0.3, 1.0, 7.0):
            assert abs(freq(a, b, w) * freq(c, d, w) - 1.0) < 1e-12
            assert abs(phase_deg(a, b, w) + phase_deg(c, d, w)) < 1e-9


def test_check_loop_margins():
    m = margins([1.0], [1.0, 3.0, 2.0, 0.0])
    assert abs(m["pm"] - 53.4108) < 1e-3
    assert abs(m["wgc"][0] - 0.445748) < 1e-5
    assert abs(m["gm"] - 6.0) < 1e-9
    assert abs(m["wpc"][0] - math.sqrt(2.0)) < 1e-9


def test_three_lags_gain_margin():
    m = margins([3.0], [1.0, 3.0, 3.0, 1.0])
    assert abs(m["gm"] - 8.0 / 3.0) < 1e-9
    assert abs(m["wpc"][0] - math.sqrt(3.0)) < 1e-9


def test_uncompensated_plant():
    m = margins(*PLANT)
    assert abs(m["wgc"][0] - 3.08423) < 1e-5
    assert abs(m["pm"] - 17.9642) < 1e-3
    assert m["gm"] == math.inf
    assert abs(m["ms"] - 3.35157) < 1e-5


def test_lead_example():
    cn, cd, wm, T = place_lead(*PLANT, 4.0)
    assert abs(wm - math.sqrt((-1.0 + math.sqrt(1601.0)) / 2.0)) < 1e-9
    assert abs(T - 0.113210) < 1e-6
    assert abs(phase_deg(*PLANT, wm) + 90.0 + math.degrees(math.atan(wm))) < 1e-9
    L = series(PLANT, (cn, cd))
    m = margins(*L)
    assert len(m["wgc"]) == 1
    assert abs(m["wgc"][0] - wm) < 1e-9
    assert abs(m["pm"] - 49.6276) < 1e-3
    assert abs(m["ms"] - 1.42139) < 1e-5
    assert all(p.real < 0 for p in closed_loop_poles(*L))


def test_lag_example():
    cn, cd, wc, beta, T = design_lag(*PLANT, 50.0)
    assert abs(wc - math.tan(math.radians(35.0))) < 1e-9
    assert abs(beta - 11.6987) < 1e-4
    assert abs(T - 14.2815) < 1e-4
    L = series(PLANT, (cn, cd))
    m = margins(*L)
    assert abs(m["wgc"][0] - 0.702794) < 1e-5
    assert abs(m["pm"] - 49.6989) < 1e-3
    assert abs(m["ms"] - 1.48123) < 1e-5
    poles = closed_loop_poles(*L)
    assert all(p.real < 0 for p in poles)
    slow = max(p.real for p in poles)
    assert abs(slow + 0.075732) < 1e-5


def test_lead_crossover_is_omega_m_random():
    rng = random.Random(8030)
    for _ in range(10):
        k = rng.uniform(2.0, 50.0)
        alpha = rng.uniform(2.0, 15.0)
        plant = ([k], [1.0, 1.0, 0.0])
        cn, cd, wm, T = place_lead(*plant, alpha)
        L = series(plant, (cn, cd))
        m = margins(*L)
        assert abs(m["wgc"][-1] - wm) < 1e-7 * wm
        phi = max_lead(alpha, T)[0]
        assert abs(m["pm"] - (180.0 + phase_deg(*plant, wm) + phi)) < 1e-7


def test_design_lead_meets_margin():
    cn, cd = design(*PLANT, 45.0)
    alpha = cn[0] / cd[0]
    assert abs(max_lead(alpha, cd[0])[0] - (45.0 - 17.9642 + 10.0)) < 1e-3
    m = margins(*series(PLANT, (cn, cd)))
    assert m["pm"] >= 45.0
    assert abs(m["pm"] - 49.7) < 0.2


def test_design_lag_matches_example():
    cn, cd = design(*PLANT, 50.0, kind="lag")
    cn2, cd2, wc, beta, T = design_lag(*PLANT, 50.0)
    assert max(abs(x - y) for x, y in zip(cn + cd, cn2 + cd2)) < 1e-9


def test_design_returns_one_when_margin_is_met():
    assert design([1.0], [1.0, 3.0, 2.0, 0.0], 45.0) == ([1.0], [1.0])


def test_bad_input():
    with pytest.raises(ValueError):
        design(*PLANT, 45.0, kind="notch")
    with pytest.raises(ValueError):
        lead(1.0, 1.0)
    with pytest.raises(ValueError):
        lead(2.0, 0.0)
    with pytest.raises(ValueError):
        lag(0.5, 1.0)
    with pytest.raises(ValueError):
        alpha_for_phase(90.0)
    with pytest.raises(ValueError):
        design_lag(*PLANT, 0.0)
    with pytest.raises(ValueError):
        design_lag([0.1], [1.0, 1.0, 0.0], 50.0)
    with pytest.raises(ValueError):
        place_lead([1.0], [1.0, 1.0], 1e9)

Exercises

  1. Show that the phase of the lead network is largest at ωm=1/(Tα)\omega_m = 1/(T\sqrt\alpha) and that sin⁡φmax⁡=(α−1)/(α+1)\sin\varphi_{\max} = (\alpha - 1)/(\alpha + 1).
  2. Which α\alpha gives a lead of 50 degrees? (Answer: α=7.5486\alpha = 7.5486.)
  3. Find the phase of the lead network with α=4\alpha = 4 and T=1T = 1 at ω=1\omega = 1. (Answer: arctan⁡4−arctan⁡1=30.96\arctan 4 - \arctan 1 = 30.96 degrees.)
  4. Redo the lead example with α=10\alpha = 10. (Answer: ωm=5.57913\omega_m = 5.57913, T=0.056680T = 0.056680, a phase margin of 65.06 degrees and Ms=1.21983M_s = 1.21983.)
  5. Show that the lag network has the phase arctan⁡(Tω)−arctan⁡(βTω)\arctan(T\omega) - \arctan(\beta T\omega), that it is the reciprocal of the lead network with the same parameters, and that at ω=10/T\omega = 10/T its phase is close to −(1−1/β)/10-(1 - 1/\beta)/10 radians.
  6. Show that β(1+Ts)/(1+βTs)→(1+Ts)/(Ts)\beta(1 + T s)/(1 + \beta T s) \to (1 + T s)/(T s) as β→∞\beta \to \infty.
  7. Explain why a lag network does not change the velocity constant of the loop, while it lowers the crossover frequency.

References

  1. Katsuhiko Ogata, Modern Control Engineering, fifth edition, Prentice Hall, 2010, Section 7-11, Lead Compensation, Section 7-12, Lag Compensation, and Section 7-13, Lag-Lead Compensation (frequency-response design; Ogata writes the lead network with a parameter below 1)
  2. Gene F. Franklin, J. David Powell and Abbas Emami-Naeini, Feedback Control of Dynamic Systems, eighth edition, Pearson, 2019, Section 6.7.2, Lead Compensation, and Section 6.7.4, Lag Compensation
  3. Karl Johan Åström and Richard M. Murray, Feedback Systems, An Introduction for Scientists and Engineers, second edition, Princeton University Press, 2021, Chapter 12, Frequency Domain Design (lead and lag compensation as part of loop shaping)

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 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