Algorithm Search⌘K

Algorithmcore

Root locus construction rules

Also called Evans rules.

Computes the features that fix the shape of a root locus from the open-loop poles and zeros, the real axis segments, asymptotes, breakaway points, departure angles and axis crossings.

Time
O((n + m)^3 + t (n + m)^2) worst
Space
O(n + m) extra
Where
m = the number of open-loop zeros; n = the number of open-loop poles; t = the number of iterations of the polynomial root finder
Properties
deterministicnot exactofflineiterative
Origin
Walter R. Evans, 1948

The root locus construction rules compute, from the poles and zeros of the open-loop transfer function G(s)=N(s)/D(s)G(s) = N(s)/D(s) alone, the features that fix the shape of the root locus: the set of points where the closed-loop characteristic polynomial D(s)+KN(s)D(s) + K N(s) has a root for some gain K>0K > 0. The rules give the parts of the real axis on the locus, the straight lines that the branches approach at high gain, the points where branches meet and leave the real axis, the directions in which branches leave the poles and arrive at the zeros, and the gains at which branches cross the imaginary axis. Evans stated them in 1948 for drawing by hand. Each rule follows from one fact: ss is on the locus if and only if G(s)G(s) is a negative real number.

In plain words

A feedback loop has a gain knob. As you turn it up, the closed-loop poles move, and the root locus is the map of their paths. You can compute the paths by solving a polynomial for many gains, but a few rules tell you the shape of the map with little work. Some pieces of the real line are on the map and the others are not. The paths that go to infinity follow straight lines from one common center. Two paths that meet on the real line split off it at a point you can compute. Each path leaves its start point in a direction you can compute, and it ends at a fixed point of the plant or at infinity. The rules also give the gain at which a path crosses into the unstable half of the plane. This page computes all of these features and proves them.

The problem

Input. The open-loop poles p1,…,pnp_1, \ldots, p_n and zeros z1,…,zmz_1, \ldots, z_m, complex numbers with repetition, with n≥1n \ge 1 and m≤nm \le n. The two lists are closed under complex conjugation, so that GG has real coefficients, and no pole equals a zero. Write

D(s)=∏i=1n(s−pi),N(s)=∏k=1m(s−zk),χK(s)=D(s)+KN(s).D(s) = \prod_{i=1}^n (s - p_i), \qquad N(s) = \prod_{k=1}^m (s - z_k), \qquad \chi_K(s) = D(s) + K N(s).

Both DD and NN are monic, so G=N/DG = N/D and the loop transfer function is L=KGL = K G with K>0K > 0. The closed loop with unity negative feedback has the characteristic polynomial χK\chi_K. The locus is the set L={s∈C:χK(s)=0 for some K>0}\mathcal{L} = \{ s \in \mathbb{C} : \chi_K(s) = 0 \text{ for some } K > 0 \}.

Output.

  • the real axis segments, the closure of L∩R\mathcal{L} \cap \mathbb{R}, as a union of closed intervals;
  • if n>mn > m, the centroid σ\sigma and the n−mn - m asymptote angles;
  • the breakaway and break-in points, the points ss where χK\chi_K has a multiple root for some K>0K > 0, with that KK;
  • for each distinct pole of multiplicity μ\mu, the μ\mu departure angles, and for each distinct zero of multiplicity ν\nu, the ν\nu arrival angles;
  • the imaginary axis crossings, the pairs (ω,K)(\omega, K) with ω≥0\omega \ge 0, K>0K > 0 and χK(jω)=0\chi_K(j\omega) = 0; or a flag when K(jω)K(j\omega) is real for every ω\omega, so that whole intervals of the imaginary axis lie on the locus.

Angles are in degrees in [0,360)[0, 360), measured from the positive real axis.

The algorithm

  1. ROOT-LOCUS-RULES(p_1..p_n, z_1..z_m)
  2. 1check n ≥ 1, m ≤ n, both lists closed under conjugation, no pole equal to a zero; D ← ∏(s − p_i), N ← ∏(s − z_k)
  3. 2segments ← the closed real intervals with an odd number of real poles and zeros, with multiplicity, to their right
  4. 3if n > m then σ ← (Σ p_i − Σ z_k)/(n − m); angles ← (2k + 1) · 180/(n − m) for k = 0, ..., n − m − 1
  5. 4W ← Σ_i w_i ∏_{j ≠ i} (s − r_j) ▷ r_i: the distinct poles and zeros; w_i: the multiplicity, negative for a zero
  6. 5breakaways ← the pairs (s, K) with W(s) = 0 and K = −D(s)/N(s) real and positive
  7. 6for each distinct pole p of multiplicity μ: θ_j ← (180 + 360 j + Σ_k ∠(p − z_k) − Σ_{q ≠ p} ∠(p − q))/μ, j = 0, ..., μ − 1
  8. 7for each distinct zero z of multiplicity ν: φ_j ← (180 + 360 j + Σ_i ∠(z − p_i) − Σ_{y ≠ z} ∠(z − y))/ν, j = 0, ..., ν − 1
  9. 8R ← the polynomial with Im D(jω) N(−jω) = ω R(ω²); crossings ← the pairs (ω, K), ω = 0 or ω = √u for a real root u > 0 of R, with K = −D(jω)/N(jω) > 0; if R = 0 then set the flag
  10. 9return segments, σ, angles, breakaways, departures, arrivals, crossings, flag

Line L1 rejects the inputs for which the rules are false: a pole equal to a zero is a fixed root of χK\chi_K for every KK, and a list that is not closed under conjugation gives a GG with complex coefficients, for which the real axis rule fails. Line L2 sweeps the distinct real poles and zeros from right to left and keeps a running count; an interval between two of them is on the locus when the count is odd, and two such intervals that meet at a point of even multiplicity are merged. In line L3 the sums of the complex values are real, because the lists are closed under conjugation.

Line L4 builds W=Q∑iwi/(s−ri)W = Q \sum_i w_i/(s - r_i), where Q=∏i(s−ri)Q = \prod_i (s - r_i) and the sum is the logarithmic derivative D′/D−N′/ND'/D - N'/N. Its roots are the critical points of K(s)=−D(s)/N(s)K(s) = -D(s)/N(s) away from the poles and zeros, and line L5 keeps the ones where KK is a positive real number. The other roots of WW belong to the locus for negative gain. Lines L6 and L7 add the angles of the vectors from all other poles and zeros, as the angle condition asks. In line L8, K(jω)K(j\omega) is real exactly when D(jω)N(jω)‾D(j\omega) \overline{N(j\omega)} is real, and the imaginary part of that product is an odd polynomial in ω\omega. The point ω=0\omega = 0 is tested on its own, with K=−D(0)/N(0)K = -D(0)/N(0).

The implementation works in floating point and finds the roots of WW and RR with the Durand-Kerner method of the shared helper module. It treats a value as real when its imaginary part is at most 10−9(1+∣x∣)10^{-9}(1 + |x|), two poles or zeros as equal when they differ by at most 10−9(1+∣x∣)10^{-9}(1 + |x|), and a gain as real when its imaginary part is at most 10−6(1+∣K∣)10^{-6}(1 + |K|).

Example

A third-order loop. Take G(s)=1/(s(s+1)(s+2))G(s) = 1/(s(s + 1)(s + 2)), so n=3n = 3, m=0m = 0, D=s3+3s2+2sD = s^3 + 3 s^2 + 2 s and N=1N = 1.

line computation result
L2 real values from the right: 00 (count 1), −1-1 (count 2), −2-2 (count 3) segments [−1,0][-1, 0] and (−∞,−2](-\infty, -2]
L3 σ=(0−1−2)/3\sigma = (0 - 1 - 2)/3, angles (2k+1)⋅60(2k + 1) \cdot 60 σ=−1\sigma = -1; 60, 180, 300
L4 W=(s+1)(s+2)+s(s+2)+s(s+1)W = (s + 1)(s + 2) + s(s + 2) + s(s + 1) 3s2+6s+23 s^2 + 6 s + 2
L5 roots −1±1/3-1 \pm 1/\sqrt 3; K=−D(s)K = -D(s) −0.42265-0.42265 with K=0.38490K = 0.38490 kept; −1.57735-1.57735 with K=−0.38490K = -0.38490 rejected
L6 at 0: 180−0−0180 - 0 - 0; at −1-1: 180−180−0180 - 180 - 0; at −2-2: 180−180−180180 - 180 - 180 180, 0, 180
L8 D(jω)=−3ω2+j(2ω−ω3)D(j\omega) = -3\omega^2 + j(2\omega - \omega^3), so R(u)=2−uR(u) = 2 - u ω=2=1.41421\omega = \sqrt 2 = 1.41421, K=6K = 6

At ω=0\omega = 0 the gain −D(0)/N(0)=0-D(0)/N(0) = 0 is not positive, so the origin is a start point and not a crossing. The two branches from 0 and −1-1 move toward each other on [−1,0][-1, 0], meet at −0.42265-0.42265, and leave the axis. They follow the asymptotes at 60 and 300 degrees and cross the imaginary axis at ±j2\pm j\sqrt 2 for K=6K = 6; at that gain χ6=(s+3)(s2+2)\chi_6 = (s + 3)(s^2 + 2). The third branch runs from −2-2 to −∞-\infty. The value K=6K = 6 is the gain margin of the loop with K=1K = 1, the same value that the Routh array of s3+3s2+2s+Ks^3 + 3 s^2 + 2 s + K gives.

Complex poles and a zero. Take G(s)=(s+2)/(s2+2s+2)G(s) = (s + 2)/(s^2 + 2 s + 2), with poles −1±j-1 \pm j and the zero −2-2. Line L2 gives the segment (−∞,−2](-\infty, -2]. Line L3 gives n−m=1n - m = 1 and the single angle 180. Line L4 gives W=(s+2)(2s+2)−(s2+2s+2)=s2+4s+2W = (s + 2)(2 s + 2) - (s^2 + 2 s + 2) = s^2 + 4 s + 2, with roots −2±2-2 \pm \sqrt 2. At −2−2=−3.41421-2 - \sqrt 2 = -3.41421 the gain is 2+22=4.828432 + 2\sqrt 2 = 4.82843, a break-in point; at −2+2-2 + \sqrt 2 the gain is −0.82843-0.82843 and the root is rejected. Line L6 at −1+j-1 + j gives 180+∠(1+j)−∠(2j)=180+45−90=135180 + \angle(1 + j) - \angle(2j) = 180 + 45 - 90 = 135 degrees, and 225 at −1−j-1 - j. Line L7 at −2-2 gives 180+∠(−1−j)+∠(−1+j)=180+225+135=540180 + \angle(-1 - j) + \angle(-1 + j) = 180 + 225 + 135 = 540, that is 180 degrees. In line L8, D(jω)N(−jω)=(2−ω2+2jω)(2−jω)D(j\omega) N(-j\omega) = (2 - \omega^2 + 2 j\omega)(2 - j\omega) has the imaginary part ω(2+ω2)\omega(2 + \omega^2), so R(u)=2+uR(u) = 2 + u has no positive root, and −D(0)/N(0)=−1-D(0)/N(0) = -1: no crossings, and the loop is stable for every K>0K > 0. The complex branch is an arc of the circle ∣s+2∣=2|s + 2| = \sqrt 2.

Complex breakaway points. Take G(s)=1/(s(s+4)(s2+4s+20))G(s) = 1/(s(s + 4)(s^2 + 4 s + 20)). With u=s2+4su = s^2 + 4 s the polynomial is D=u(u+20)D = u (u + 20), and WW is a multiple of D′=(2u+20)(2s+4)D' = (2u + 20)(2 s + 4). The roots are s=−2s = -2 with K=64K = 64, and the roots −2±j6=−2±2.44949j-2 \pm j\sqrt 6 = -2 \pm 2.44949 j of u=−10u = -10 with K=100K = 100. At K=100K = 100 the closed loop is (s2+4s+10)2(s^2 + 4 s + 10)^2, so the four branches meet in pairs at two complex points. The departure angle at −2+4j-2 + 4j is 270 degrees. The Routh array of s4+8s3+36s2+80s+Ks^4 + 8 s^3 + 36 s^2 + 80 s + K gives the crossing at ω=10\omega = \sqrt{10} for K=260K = 260, which line L8 also returns.

Correctness

The proofs are in the correctness proof. Each statement holds in exact arithmetic, with exact roots of WW and RR.

  • Angle and magnitude conditions (proved). For ss not a pole or zero, s∈Ls \in \mathcal{L} if and only if G(s)<0G(s) < 0, that is ∠G(s)=180\angle G(s) = 180 degrees modulo 360; then K=1/∣G(s)∣K = 1/|G(s)|. Poles and zeros are not in L\mathcal{L}; they are the limits of the branches as K→0K \to 0 and K→∞K \to \infty.
  • Real axis segments (proved). A real xx that is not a pole or zero is on the locus if and only if the number of real poles and zeros, with multiplicity, greater than xx is odd. Line L2 returns the closure of these points.
  • Asymptotes (proved). If q=n−m≥1q = n - m \ge 1, then for large KK the closed loop has mm roots near the zeros and qq roots sk(K)=σ+K1/qejθk+o(1)s_k(K) = \sigma + K^{1/q} e^{j\theta_k} + o(1), with θk=(2k+1)180/q\theta_k = (2k + 1)180/q. If q≥2q \ge 2, the mean of these qq roots tends to σ\sigma.
  • Breakaway points (proved). χK\chi_K has a multiple root at s0s_0 for some K>0K > 0 if and only if W(s0)=0W(s_0) = 0 and −D(s0)/N(s0)-D(s_0)/N(s_0) is a positive real number. Branches can meet, and real roots can leave the real axis, only at such points.
  • Departure and arrival angles (proved). For small KK there are exactly μ\mu roots near a pole of multiplicity μ\mu, and their directions from the pole tend to the angles of line L6. For large KK the same holds at a zero with the angles of line L7.
  • Crossings (proved). For ω>0\omega > 0, jω∈Lj\omega \in \mathcal{L} if and only if R(ω2)=0R(\omega^2) = 0 and −D(jω)/N(jω)>0-D(j\omega)/N(j\omega) > 0, unless RR is the zero polynomial. The number of closed-loop poles in the open right half plane can change only at a gain in the list of crossings.
Proof: The root locus rules describe the locus of D + K N exactlyfull

Let p1,…,pnp_1, \ldots, p_n and z1,…,zmz_1, \ldots, z_m be the poles and zeros, with n≥1n \ge 1 and m≤nm \le n, both lists closed under complex conjugation, and no pole equal to a zero. These are the conditions that line L1 checks. Let D(s)=∏i(s−pi)D(s) = \prod_i (s - p_i), N(s)=∏k(s−zk)N(s) = \prod_k (s - z_k), G=N/DG = N/D and χK=D+KN\chi_K = D + K N. Then DD and NN are monic with real coefficients and no common root. For K>0K > 0 the leading coefficient of χK\chi_K is 1 if m<nm < n and 1+K1 + K if m=nm = n, so χK\chi_K has degree nn for every K≥0K \ge 0. The locus is L={s:χK(s)=0 for some K>0}\mathcal{L} = \{ s : \chi_K(s) = 0 \text{ for some } K > 0 \}. All statements are in exact arithmetic, with the roots of WW and RR computed exactly.

Two facts are used several times.

Fact 1 (continuity of the roots). The roots of a polynomial of fixed degree, with multiplicity, depend continuously on its coefficients. More precisely, by Rouché's theorem: if ff and gg are analytic on a closed disc and ∣g∣<∣f∣|g| < |f| on its boundary circle, then ff and f+gf + g have the same number of zeros inside the disc.

Fact 2 (simple roots move analytically). If s0s_0 is a simple root of χK0\chi_{K_0}, then by the implicit function theorem there is an analytic function s(K)s(K) near K0K_0 with s(K0)=s0s(K_0) = s_0 and χK(s(K))=0\chi_K(s(K)) = 0, and it is the only root near s0s_0. Its derivative is s′(K0)=−N(s0)/χK0′(s0)s'(K_0) = -N(s_0)/\chi_{K_0}'(s_0).

Lemma 1: the angle and magnitude conditions

No pole and no zero is in L\mathcal{L}. For any other ss, s∈Ls \in \mathcal{L} if and only if G(s)G(s) is a negative real number, that is ∠G(s)=∑k∠(s−zk)−∑i∠(s−pi)=180\angle G(s) = \sum_k \angle(s - z_k) - \sum_i \angle(s - p_i) = 180 degrees modulo 360. The gain is then unique: K=−D(s)/N(s)=1/∣G(s)∣K = -D(s)/N(s) = 1/|G(s)|.

Proof. At a pole pp, χK(p)=KN(p)≠0\chi_K(p) = K N(p) \ne 0 for K>0K > 0, because N(p)≠0N(p) \ne 0. At a zero zz, χK(z)=D(z)≠0\chi_K(z) = D(z) \ne 0. For other ss, both D(s)D(s) and N(s)N(s) are nonzero, and χK(s)=0\chi_K(s) = 0 if and only if K=−D(s)/N(s)=−1/G(s)K = -D(s)/N(s) = -1/G(s). Such a K>0K > 0 exists if and only if G(s)G(s) is real and negative, and then K=1/∣G(s)∣K = 1/|G(s)|. The angle of a product is the sum of the angles of the factors, modulo 360 degrees, which gives the angle form. □\square

Lemma 2: the real axis segments

Let xx be real and not a pole or zero. Then x∈Lx \in \mathcal{L} if and only if the number c(x)c(x) of real poles and real zeros greater than xx, counted with multiplicity, is odd. The union of the intervals returned by line L2 is the closure of L∩R\mathcal{L} \cap \mathbb{R}.

Proof. G(x)G(x) is real because GG has real coefficients, so by Lemma 1, x∈Lx \in \mathcal{L} if and only if G(x)<0G(x) < 0. A complex pole or zero a+jba + jb, b≠0b \ne 0, comes with a−jba - jb (closure under conjugation), and the pair gives the factor (x−a)2+b2>0(x - a)^2 + b^2 > 0 in N(x)N(x) or D(x)D(x). A real pole or zero rr gives the factor x−rx - r, which is negative exactly when r>xr > x. So the sign of G(x)G(x) is (−1)c(x)(-1)^{c(x)}, and G(x)<0G(x) < 0 if and only if c(x)c(x) is odd.

Let x1>x2>⋯>xℓx_1 > x_2 > \cdots > x_\ell be the distinct real poles and zeros, with multiplicities c1,…,cℓc_1, \ldots, c_\ell, and set x0=+∞x_0 = +\infty, xℓ+1=−∞x_{\ell + 1} = -\infty. The count c(x)c(x) is constant on each open interval (xi+1,xi)(x_{i+1}, x_i) and equals c1+⋯+cic_1 + \cdots + c_i. Line L2 computes this running sum and records the interval [xi+1,xi][x_{i+1}, x_i] when the sum is odd; on (x1,∞)(x_1, \infty) the count is 0, which is even. When two recorded intervals share an endpoint, line L2 joins them. So the union of the output intervals is the union of the closures of the open intervals where cc is odd. By the first part, L∩R\mathcal{L} \cap \mathbb{R} is the union of these open intervals, and its closure is the union of their closures. □\square

Lemma 3: the asymptotes

Let q=n−m≥1q = n - m \ge 1, σ=(∑ipi−∑kzk)/q\sigma = (\sum_i p_i - \sum_k z_k)/q and θk=(2k+1) 180/q\theta_k = (2k + 1)\,180/q degrees. For every ε>0\varepsilon > 0 there is K1K_1 such that for K>K1K > K_1 the polynomial χK\chi_K has exactly ν\nu roots in the disc ∣s−z∣<ε|s - z| < \varepsilon for each distinct zero zz of multiplicity ν\nu, in total mm roots, and exactly one root in each disc ∣s−σ−K1/qejθk∣<ε|s - \sigma - K^{1/q} e^{j\theta_k}| < \varepsilon, k=0,…,q−1k = 0, \ldots, q - 1. If q≥2q \ge 2, the mean of these qq roots tends to σ\sigma.

Proof. Near the zeros: on a small circle around a zero zz of multiplicity ν\nu that contains no other root of NDN D, ∣N∣≥η>0|N| \ge \eta > 0 and ∣D∣≤M|D| \le M; then for K>M/ηK > M/\eta, ∣D∣<∣KN∣|D| < |K N| on the circle, and by Fact 1 the polynomial KN+DK N + D has as many zeros inside as KNK N, that is ν\nu. This gives mm roots near the zeros. (Lemma 5 gives one root per direction at a multiple zero.)

Far away: let a=∑ipia = \sum_i p_i and b=∑kzkb = \sum_k z_k. Then D(s)=sn−asn−1+O(sn−2)D(s) = s^n - a s^{n-1} + O(s^{n-2}) and N(s)=sm−bsm−1+O(sm−2)N(s) = s^m - b s^{m-1} + O(s^{m-2}), so for large ∣s∣|s|

D(s)N(s)=sq(1−a−bs+O(s−2))=(s−σ)q(1+O(s−2)),\frac{D(s)}{N(s)} = s^q \left(1 - \frac{a - b}{s} + O(s^{-2})\right) = (s - \sigma)^q \bigl(1 + O(s^{-2})\bigr),

because (s−σ)q=sq(1−qσ/s+O(s−2))(s - \sigma)^q = s^q (1 - q\sigma/s + O(s^{-2})) and qσ=a−bq \sigma = a - b. Take the principal qq-th root of the last factor: for ∣s∣≥ρ0|s| \ge \rho_0 the function h(s)=(s−σ)(1+O(s−2))1/q=s−σ+O(1/s)h(s) = (s - \sigma)(1 + O(s^{-2}))^{1/q} = s - \sigma + O(1/s) is analytic, and D/N=hqD/N = h^q. For ∣s∣≥ρ0|s| \ge \rho_0, χK(s)=0\chi_K(s) = 0 if and only if h(s)q=−Kh(s)^q = -K, that is h(s)=wk:=K1/qejθkh(s) = w_k := K^{1/q} e^{j\theta_k} for some kk. Fix kk and let ck=σ+wkc_k = \sigma + w_k. On the circle ∣s−ck∣=ε|s - c_k| = \varepsilon, the function f(s)=s−ckf(s) = s - c_k has ∣f∣=ε|f| = \varepsilon, and g(s)=h(s)−wk−f(s)=h(s)−(s−σ)=O(1/∣s∣)=O(K−1/q)g(s) = h(s) - w_k - f(s) = h(s) - (s - \sigma) = O(1/|s|) = O(K^{-1/q}). For KK large, ∣g∣<ε|g| < \varepsilon on the circle, and by Fact 1, h−wk=f+gh - w_k = f + g has exactly one zero in the disc. The qq discs are disjoint for large KK, because the centers are at distance at least 2K1/qsin⁡(180/q)2 K^{1/q} \sin(180/q) apart when q≥2q \ge 2. Together with the mm roots near the zeros this gives nn roots, which are all the roots of χK\chi_K.

The mean: if q≥2q \ge 2, the term KNK N has degree m≤n−2m \le n - 2, so the coefficient of sn−1s^{n-1} in χK\chi_K is −a-a for every KK, and the sum of all nn roots is aa. The mm roots near the zeros have a sum that tends to bb, so the sum of the qq far roots tends to a−b=qσa - b = q\sigma. □\square

So the far branches approach the qq rays from σ\sigma at the angles θk\theta_k, which line L3 returns. For q=1q = 1 the single far root is σ−K+o(1)\sigma - K + o(1), real and going to −∞-\infty.

Lemma 4: the breakaway points

Let r1,…,rdr_1, \ldots, r_d be the distinct poles and zeros, wiw_i the multiplicity of rir_i as a pole, or minus its multiplicity as a zero, and W=∑iwi∏j≠i(s−rj)W = \sum_i w_i \prod_{j \ne i} (s - r_j), the polynomial of line L4. Then χK0\chi_{K_0} with K0>0K_0 > 0 has a multiple root at s0s_0 if and only if W(s0)=0W(s_0) = 0 and K0=−D(s0)/N(s0)K_0 = -D(s_0)/N(s_0).

Proof. First, WW in terms of DD and NN. Let Q=∏i(s−ri)Q = \prod_i (s - r_i). The logarithmic derivatives are D′/D=∑polesμi/(s−ri)D'/D = \sum_{\text{poles}} \mu_i/(s - r_i) and N′/N=∑zerosνk/(s−rk)N'/N = \sum_{\text{zeros}} \nu_k/(s - r_k), so

ND′−N′DND=D′D−N′N=∑iwis−ri=WQ.\frac{N D' - N' D}{N D} = \frac{D'}{D} - \frac{N'}{N} = \sum_i \frac{w_i}{s - r_i} = \frac{W}{Q}.

Hence ND′−N′D=HWN D' - N' D = H W with H=ND/Q=∏i(s−ri)∣wi∣−1H = N D/Q = \prod_i (s - r_i)^{|w_i| - 1}, whose roots are the repeated poles and zeros. Also W(ri)=wi∏j≠i(ri−rj)≠0W(r_i) = w_i \prod_{j \ne i}(r_i - r_j) \ne 0, so WW has no root at a pole or zero, and WW is not the zero polynomial.

Now let K0>0K_0 > 0. The point s0s_0 is a multiple root of χK0\chi_{K_0} if and only if D(s0)+K0N(s0)=0D(s_0) + K_0 N(s_0) = 0 and D′(s0)+K0N′(s0)=0D'(s_0) + K_0 N'(s_0) = 0. Suppose both hold. Then N(s0)≠0N(s_0) \ne 0, since otherwise D(s0)=0D(s_0) = 0 too, and DD and NN would have a common root. So K0=−D(s0)/N(s0)K_0 = -D(s_0)/N(s_0), and substituting into the second equation and multiplying by N(s0)N(s_0) gives ND′−N′D=0N D' - N' D = 0 at s0s_0. As s0s_0 is not a pole or zero (Lemma 1), H(s0)≠0H(s_0) \ne 0 and W(s0)=0W(s_0) = 0. Conversely, let W(s0)=0W(s_0) = 0 and K0=−D(s0)/N(s0)>0K_0 = -D(s_0)/N(s_0) > 0; here N(s0)≠0N(s_0) \ne 0 because WW does not vanish at zeros. Then χK0(s0)=0\chi_{K_0}(s_0) = 0, and χK0′(s0)=D′(s0)−D(s0)N′(s0)/N(s0)=(HW)(s0)/N(s0)=0\chi_{K_0}'(s_0) = D'(s_0) - D(s_0) N'(s_0)/N(s_0) = (H W)(s_0)/N(s_0) = 0. □\square

Line L5 keeps exactly the roots of WW with −D/N-D/N real and positive, so by Lemma 4 it returns every point where χK\chi_K has a multiple root for some K>0K > 0, with that gain, and nothing else. Since K(s)=−D(s)/N(s)K(s) = -D(s)/N(s) has the derivative −(ND′−N′D)/N2=−HW/N2-(N D' - N' D)/N^2 = -H W/N^2, these points are the critical points of K(s)K(s) on the locus; this is the rule dK/ds=0dK/ds = 0.

Consequence: where branches meet. By Fact 2, near a gain K0K_0 where all roots of χK0\chi_{K_0} are simple, each root moves analytically with KK and no two roots meet. Since the coefficients are real, the conjugate of a root is a root; a simple real root therefore stays real, because its conjugate is a root near it and the root near it is unique. Hence the number of real roots of χK\chi_K is constant on every interval of gains in (0,∞)(0, \infty) that contains no gain from line L5 with a real point. Branches meet, and real roots leave or enter the real axis, only at the points of line L5.

Lemma 5: the departure and arrival angles

Let pp be a pole of multiplicity μ\mu and let θj=(180+360j+∑k∠(p−zk)−∑q≠p∠(p−q))/μ\theta_j = (180 + 360 j + \sum_k \angle(p - z_k) - \sum_{q \ne p} \angle(p - q))/\mu for j=0,…,μ−1j = 0, \ldots, \mu - 1, where the second sum runs over the other poles with multiplicity. For every δ>0\delta > 0 small enough there is K2>0K_2 > 0 such that for 0<K<K20 < K < K_2 the polynomial χK\chi_K has exactly μ\mu roots in ∣s−p∣<2ε|s - p| < 2\varepsilon, with ε=(K∣c∣)1/μ\varepsilon = (K |c|)^{1/\mu} and cc as below, and exactly one of them in each disc ∣s−p−εejθj∣<δε|s - p - \varepsilon e^{j\theta_j}| < \delta \varepsilon. The same holds at a zero zz of multiplicity ν\nu for large KK, with ε=(∣c∣/K)1/ν\varepsilon = (|c|/K)^{1/\nu} and the angles φj=(180+360j+∑i∠(z−pi)−∑y≠z∠(z−y))/ν\varphi_j = (180 + 360 j + \sum_i \angle(z - p_i) - \sum_{y \ne z} \angle(z - y))/\nu of line L7.

Proof. Write D=(s−p)μD1D = (s - p)^\mu D_1 with D1(p)≠0D_1(p) \ne 0. Near pp, χK=D1⋅((s−p)μ+Kc(s))\chi_K = D_1 \cdot \bigl((s - p)^\mu + K c(s)\bigr) with c(s)=N(s)/D1(s)c(s) = N(s)/D_1(s) analytic and c=c(p)≠0c = c(p) \ne 0. The equation (s−p)μ+Kc=0(s - p)^\mu + K c = 0 has the μ\mu roots p+εejθjp + \varepsilon e^{j\theta_j}, because −c=∣c∣ej(180+∠c)-c = |c| e^{j(180 + \angle c)} and ∠c=∠N(p)−∠D1(p)=∑k∠(p−zk)−∑q≠p∠(p−q)\angle c = \angle N(p) - \angle D_1(p) = \sum_k \angle(p - z_k) - \sum_{q \ne p} \angle(p - q).

Scale s=p+εus = p + \varepsilon u. Then (s−p)μ+Kc(s)=εμ(uμ−ejμθ0+g(u))(s - p)^\mu + K c(s) = \varepsilon^\mu \bigl(u^\mu - e^{j \mu \theta_0} + g(u)\bigr) with ∣g(u)∣=∣c(s)−c∣/∣c∣≤Cε∣u∣|g(u)| = |c(s) - c|/|c| \le C \varepsilon |u| for a constant CC, since cc is analytic. The polynomial f(u)=uμ−ejμθ0f(u) = u^\mu - e^{j\mu\theta_0} has the simple roots uj=ejθju_j = e^{j\theta_j}, spaced 360/μ360/\mu degrees on the unit circle. For δ<sin⁡(180/μ)\delta < \sin(180/\mu) when μ≥2\mu \ge 2 (any δ<1\delta < 1 when μ=1\mu = 1), the circles ∣u−uj∣=δ|u - u_j| = \delta are disjoint and ∣f∣≥κ>0|f| \ge \kappa > 0 on them, and on ∣u∣=2|u| = 2, ∣f∣≥2μ−1≥1|f| \ge 2^\mu - 1 \ge 1. Choose K2K_2 so small that 2Cε2 C \varepsilon is less than κ\kappa and less than 1. By Fact 1, f+gf + g has exactly one zero in each disc ∣u−uj∣<δ|u - u_j| < \delta and exactly μ\mu zeros in ∣u∣<2|u| < 2. The factor D1D_1 has no zeros near pp. In the variable ss this is the claim.

At a zero, write N=(s−z)νN1N = (s - z)^\nu N_1 and divide by KK: χK/K=N1⋅((s−z)ν+K−1c(s))\chi_K / K = N_1 \cdot \bigl((s - z)^\nu + K^{-1} c(s)\bigr) with c(s)=D(s)/N1(s)c(s) = D(s)/N_1(s). The same argument with 1/K1/K in place of KK gives the angles (180+360j+∠D(z)−∠N1(z))/ν(180 + 360 j + \angle D(z) - \angle N_1(z))/\nu, which are the φj\varphi_j. □\square

So, as KK grows from 0, the μ\mu branches that start at pp leave it in the directions θj\theta_j, and as K→∞K \to \infty, ν\nu branches arrive at zz from the directions φj\varphi_j. Lines L6 and L7 compute exactly these angles. For a simple pole the formula is the angle condition of Lemma 1 at a point near pp, solved for the angle of s−ps - p.

Lemma 6: the imaginary axis crossings

Write D(s)=∑adasaD(s) = \sum_a d_a s^a, N(s)=∑bnbsbN(s) = \sum_b n_b s^b, rk=∑a+b=kdanb(−1)br_k = \sum_{a + b = k} d_a n_b (-1)^b, and R(u)=∑i≥0ϵ2i+1r2i+1uiR(u) = \sum_{i \ge 0} \epsilon_{2i+1} r_{2i+1} u^i with ϵk=1\epsilon_k = 1 for k≡1k \equiv 1 and ϵk=−1\epsilon_k = -1 for k≡3k \equiv 3 modulo 4. Then Im⁡D(jω)N(−jω)=ωR(ω2)\operatorname{Im} D(j\omega) N(-j\omega) = \omega R(\omega^2) for real ω\omega. For ω>0\omega > 0, if RR is not the zero polynomial, jω∈Lj\omega \in \mathcal{L} if and only if R(ω2)=0R(\omega^2) = 0 and K=−D(jω)/N(jω)>0K = -D(j\omega)/N(j\omega) > 0. The point 00 is in L\mathcal{L} if and only if −D(0)/N(0)>0-D(0)/N(0) > 0.

Proof. The coefficients are real, so N(jω)‾=N(jω‾)=N(−jω)\overline{N(j\omega)} = N(\overline{j\omega}) = N(-j\omega). Then

D(jω)N(−jω)=∑adajaωa∑bnb(−1)bjbωb=∑kjkrkωk,D(j\omega) N(-j\omega) = \sum_a d_a j^a \omega^a \sum_b n_b (-1)^b j^b \omega^b = \sum_k j^k r_k \omega^k,

and Im⁡jk\operatorname{Im} j^k is 0 for even kk, 1 for k≡1k \equiv 1 and −1-1 for k≡3k \equiv 3 modulo 4. So the imaginary part is ∑k oddϵkrkωk=ωR(ω2)\sum_{k \text{ odd}} \epsilon_k r_k \omega^k = \omega R(\omega^2).

By Lemma 1, jω∈Lj\omega \in \mathcal{L} if and only if N(jω)≠0N(j\omega) \ne 0 and −D(jω)/N(jω)-D(j\omega)/N(j\omega) is real and positive. This quotient equals −D(jω)N(jω)‾/∣N(jω)∣2-D(j\omega) \overline{N(j\omega)}/|N(j\omega)|^2, which is real if and only if ωR(ω2)=0\omega R(\omega^2) = 0; for ω>0\omega > 0 that is R(ω2)=0R(\omega^2) = 0. If N(jω)=0N(j\omega) = 0 then D(jω)≠0D(j\omega) \ne 0 and jω∉Lj\omega \notin \mathcal{L}; line L8 rejects this case because the gain is undefined. At ω=0\omega = 0, D(0)D(0) and N(0)N(0) are real, and Lemma 1 gives the last claim. □\square

Line L8 takes the positive real roots uu of RR, sets ω=u\omega = \sqrt u, and keeps the ones with K>0K > 0; it tests ω=0\omega = 0 on its own. So, when R≠0R \ne 0, its list is exactly L∩{jω:ω≥0}\mathcal{L} \cap \{ j\omega : \omega \ge 0 \} with the gains. The crossings for ω<0\omega < 0 are the conjugates. When R=0R = 0, the gain −D(jω)/N(jω)-D(j\omega)/N(j\omega) is real for every ω\omega with N(jω)≠0N(j\omega) \ne 0, and the part of the axis where it is positive is on the locus; line L8 reports this case with the flag.

Consequence: changes of stability. For K>0K > 0 the degree of χK\chi_K is nn, so by Fact 1 the number of roots in the open right half plane is constant on every interval of gains on which no root lies on the imaginary axis. When R≠0R \ne 0, the gains with a root on the axis are the gains of line L8, a finite set. So the number of unstable closed-loop poles can change only at a listed crossing gain.

The theorem

For every input that passes line L1, the algorithm returns: the closure of L∩R\mathcal{L} \cap \mathbb{R} (Lemma 2); if n>mn > m, the centroid and angles of the asymptotes of the far branches (Lemma 3); every point where χK\chi_K has a multiple root for some K>0K > 0, with its gain, and no other point (Lemma 4); the limit directions of the branches at every pole and zero (Lemma 5); and, unless the flag is set, every point jωj\omega, ω≥0\omega \ge 0, of the locus with its gain (Lemma 6).

Proof. Lines L2, L3, L6 and L7 compute the formulas of Lemmas 2, 3 and 5 directly. In line L3 the centroid is real, because the sums of a conjugation-closed list are real. Line L4 computes the polynomial WW of Lemma 4; its coefficients are real, because the set of pairs (ri,wi)(r_i, w_i) is closed under conjugation, so the conjugate of W(sˉ)W(\bar s) is W(s)W(s). Line L5 applies Lemma 4, and line L8 applies Lemma 6. Every loop runs over a finite list, so the algorithm stops. □\square

Floating point

The implementation computes the roots of WW and RR with the Durand-Kerner method in floating point, and it uses the tolerances stated on the page. The segments, the centroid and the angles are then correct to rounding. A breakaway point is a double root of χK\chi_K, and the computed roots of χK\chi_K at that gain split by about the square root of the unit roundoff; but χK0(s)=N(s)(K0−K(s))\chi_{K_0}(s) = N(s)(K_0 - K(s)), so the multiplicity of s0s_0 as a root of χK0\chi_{K_0} is one more than its multiplicity as a root of WW. At a double root of χK0\chi_{K_0} the root of WW is therefore simple, and the computed point and its gain are accurate. A root of WW or RR whose KK has an imaginary part close to the tolerance 10−6(1+∣K∣)10^{-6}(1 + |K|) can be accepted or rejected wrongly; this is the only case in which the output can differ from the exact one by more than rounding.

Complexity

Let d≤n+md \le n + m be the number of distinct poles and zeros, and tt the number of iterations of the polynomial root finder. The cost is counted in arithmetic operations on complex numbers.

  • Line L1. The conjugation check and the comparisons of poles with zeros take O((n+m)2)O((n + m)^2) operations; the products DD and NN take O(n2+m2)O(n^2 + m^2).
  • Lines L2 and L3. Grouping equal values takes O((n+m)2)O((n + m)^2) and the sort O(dlog⁡d)O(d \log d); the centroid takes O(n+m)O(n + m).
  • Line L4. The implementation forms each of the dd products of d−1d - 1 linear factors in O(d2)O(d^2), so O(d3)O(d^3) in all. The sum has degree at most d−1d - 1.
  • Line L5. Durand-Kerner on WW costs O(d2)O(d^2) per iteration, so O(td2)O(t d^2); each candidate needs one evaluation of DD and NN, O(n+m)O(n + m).
  • Lines L6 and L7. Each distinct pole or zero adds n+mn + m angles: O(d(n+m))O(d (n + m)).
  • Line L8. The coefficients of D(jω)N(−jω)D(j\omega) N(-j\omega) take O(nm+n)O(n m + n) operations. RR has degree at most (n+m−1)/2(n + m - 1)/2, and its roots cost O(t(n+m)2)O(t (n + m)^2).

The total is O((n+m)3+t(n+m)2)O((n + m)^3 + t (n + m)^2) operations and O(n+m)O(n + m) extra space. In practice n+mn + m is below 20 and the cost is negligible next to drawing the locus by computing the roots of χK\chi_K on a grid of gains, which costs O(tn2)O(t n^2) per gain.

Properties

  • Local information from the poles and zeros. Every rule uses only the poles, the zeros and their multiplicities; the gain enters only through the magnitude condition.
  • Exact rules, approximate numbers. In exact arithmetic the output is exact. In floating point the angles, the centroid and the segments are accurate to rounding, while the breakaway points and the crossings carry the errors of the root finder and the tolerances of line L5 and line L8.
  • Not a full locus. The rules fix the shape near the poles, near the zeros, near infinity, on the real axis and on the imaginary axis. Between these places the branches must be computed or sketched.
  • Deterministic. The same input gives the same output.

Variants and improvements

  • Negative gain. For K<0K < 0 the condition is G(s)>0G(s) > 0, and the rules change: a real point is on the locus when an even number of real poles and zeros lie to its right, the asymptote angles are k⋅360/(n−m)k \cdot 360/(n - m), the 180 in lines L6 and L7 becomes 0, and line L5 keeps the roots of WW with negative KK. The roots that line L5 rejects are the breakaway points of this complementary locus.
  • Routh array for the crossings. Textbooks find the crossing gain from the row of s1s^1 in the Routh array of χK\chi_K, and ω\omega from the auxiliary polynomial of the row of s2s^2. This gives the same pairs as line L8 and also proves stability between the crossings, by the Routh-Hurwitz criterion.
  • A cheaper W. Dividing QQ by each factor s−ris - r_i with Horner's rule gives each product of line L4 in O(d)O(d), so O(d2)O(d^2) in all. Another way is to form ND′−N′DN D' - N' D and divide it by the repeated factors.
  • Exact counts. With rational poles and zeros, a Sturm sequence of WW counts the real breakaway candidates in an interval without rounding errors (see real root counting).
  • Discrete time. For a sampled loop KG(z)K G(z), lines L2 to L7 hold unchanged in the zz plane, and the stability boundary is the unit circle. Line L8 then becomes the search for the θ\theta with K=−D(ejθ)/N(ejθ)K = -D(e^{j\theta})/N(e^{j\theta}) real and positive.
  • Numerical locus. Design tools compute the roots of χK\chi_K on a grid of gains and join them into branches; the rules give the start and end directions, and the breakaway and crossing gains tell where the grid must be fine.

When to use it

Use the rules to sketch a locus by hand, to check a computed root locus plot, or to answer the questions a plot answers only approximately: the gain at which the loop becomes unstable, the gain at which a pair of real poles becomes complex, and the effect of one added pole or zero of a lead-lag compensator. The crossing gain and frequency are the ultimate gain and frequency of Ziegler-Nichols tuning. For a full picture, compute the roots of χK\chi_K on a grid of gains with a polynomial root finder and use the rules to place the grid. The rules need a rational GG and one gain that enters linearly; for a time delay, use a Padé approximation first.

Pitfalls

  • Rejected candidates. Not every root of WW is a breakaway point. A real root of WW outside the real axis segments has K<0K < 0, and a complex root is a breakaway point only if its KK is real and positive, as in the third example.
  • Double roots are ill-conditioned. At a breakaway gain the closed loop has a double root, and a computed double root splits by about the square root of the unit roundoff, near 10−810^{-8} relative (see root conditioning). A test of a breakaway point must use a tolerance of this size, not 10−1510^{-15}.
  • Asymptotes are limits. The branches approach the asymptotes only as K→∞K \to \infty, and they can cross the asymptotes on the way. A branch near an asymptote is not on it.
  • Multiple poles and zeros. A pole of multiplicity μ\mu has μ\mu departure angles spaced by 360/μ360/\mu degrees; using the formula for a simple pole gives one angle and loses the others.
  • Cancellation. A pole equal to a zero is rejected in line L1. If the cancellation is only approximate, the rules hold, but a short branch from the pole to the nearby zero carries a slow closed-loop pole, and for an unstable pole this pole stays unstable.
  • Signs. The rules assume monic NN and DD and K>0K > 0. A plant with a negative leading coefficient, such as (1−s)/(s+1)2(1 - s)/(s + 1)^2, needs the negative gain rules.
  • The imaginary axis on the locus. If D(jω)N(jω)‾D(j\omega) \overline{N(j\omega)} is real for every ω\omega, as for G=1/(s2+1)G = 1/(s^2 + 1), line L8 sets the flag instead of listing points. Then whole intervals of the axis are on the locus.

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.

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()
root_locus_rules.py 225 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/root-locus-rules/. The authors are listed in prov/V7FWWP.jsonl.

"""Evans rules for the root locus of D(s) + K N(s) = 0, K > 0.

The loop transfer function is K G(s) with G = N/D, N = prod (s - z_k) and
D = prod (s - p_i), so N and D are monic. The input is the list of the n
open-loop poles and the m open-loop zeros, m <= n, closed under complex
conjugation (G has real coefficients), with no pole equal to a zero.

The rules computed here, with the line numbers of the pseudocode:
- L2: the real axis segments of the locus;
- L3: the centroid and the angles of the n - m asymptotes;
- L4, L5: the breakaway and break-in points, the roots s of
  N D' - N' D with K = -D(s)/N(s) real and positive;
- L6, L7: the departure angles at the poles and the arrival angles at the
  zeros, with multiplicity;
- L8: the crossings of the imaginary axis, the real w >= 0 with
  Im(D(jw) N(-jw)) = 0 and K = -D(jw)/N(jw) > 0.

Angles are in degrees in [0, 360). Roots of polynomials come from
ctlmat.polyroots. Tolerances: a pole or zero is real if its imaginary part
is at most 1e-9 (1 + |value|); two poles (or zeros) are the same if they
differ by at most 1e-9 (1 + |value|); a computed K is accepted as real if
its imaginary part is at most 1e-6 (1 + |K|).
"""

import cmath
import math
from dataclasses import dataclass, field

from ctlmat import polyadd, polymul, polyroots, polyval

__all__ = ["LocusRules", "root_locus_rules", "poly_from_roots", "closed_loop_poly"]

_TOL_SAME = 1e-9
_TOL_K = 1e-6


@dataclass
class LocusRules:
    n: int
    m: int
    segments: list = field(default_factory=list)       # [(left, right)], left may be -inf
    centroid: object = None                             # float, or None if n == m
    asymptote_angles: list = field(default_factory=list)
    breakaways: list = field(default_factory=list)      # [(s, K)]
    departures: list = field(default_factory=list)      # [(pole, [angles])]
    arrivals: list = field(default_factory=list)        # [(zero, [angles])]
    crossings: list = field(default_factory=list)       # [(w, K)], w >= 0
    imaginary_axis_on_locus: bool = False               # Im(D(jw) N(-jw)) is identically 0


def _same(a, b):
    return abs(a - b) <= _TOL_SAME * (1.0 + abs(b))


def _is_real(x):
    return abs(x.imag) <= _TOL_SAME * (1.0 + abs(x))


def _group(roots):
    """Distinct values with multiplicities, as [[value, count]]."""
    groups = []
    for r in roots:
        for g in groups:
            if _same(r, g[0]):
                g[1] += 1
                break
        else:
            groups.append([r, 1])
    return groups


def _check_conjugate(roots, what):
    left = list(roots)
    while left:
        r = left.pop()
        if _is_real(r):
            continue
        for i, w in enumerate(left):
            if _same(w, r.conjugate()):
                del left[i]
                break
        else:
            raise ValueError(what + " are not closed under conjugation")


def _poly_c(roots):
    p = [1.0 + 0j]
    for r in roots:
        p = polymul(p, [1.0, -complex(r)])
    return p


def poly_from_roots(roots):
    """Return the monic real polynomial with the given roots, highest power first.

    The roots must be closed under conjugation; the tiny imaginary parts
    left by rounding are dropped.
    """
    return [c.real for c in _poly_c(roots)]


def closed_loop_poly(den, num, k):
    """Return D + K N."""
    return polyadd(den, [k * c for c in num])


def _angle(z):
    """Argument of z in degrees, in [0, 360)."""
    a = math.degrees(cmath.phase(z)) % 360.0
    return 0.0 if a >= 360.0 - 1e-12 else a


def _real_k(den, num, s):
    nv = polyval(num, s)
    if nv == 0:
        return None
    k = -polyval(den, s) / nv
    if abs(k.imag) > _TOL_K * (1.0 + abs(k)):
        return None
    return k.real


def root_locus_rules(poles, zeros=()):
    """Return a LocusRules record for the poles and zeros of G."""
    poles = [complex(p) for p in poles]
    zeros = [complex(z) for z in zeros]
    n, m = len(poles), len(zeros)
    if n == 0 or m > n:  # @line L1
        raise ValueError("need at least one pole and no more zeros than poles")
    _check_conjugate(poles, "poles")
    _check_conjugate(zeros, "zeros")
    for z in zeros:
        if any(_same(z, p) for p in poles):
            raise ValueError("a pole equals a zero; cancel it first")
    den = poly_from_roots(poles)
    num = poly_from_roots(zeros)
    out = LocusRules(n=n, m=m)

    # L2: a real point is on the locus when an odd number of real poles and
    # zeros (with multiplicity) lie to its right.
    reals = _group([complex(x.real, 0.0) for x in poles + zeros if _is_real(x)])
    reals.sort(key=lambda g: -g[0].real)
    count = 0
    segs = []
    for i, (x, c) in enumerate(reals):  # @line L2
        count += c
        if count % 2 == 1:
            left = reals[i + 1][0].real if i + 1 < len(reals) else -math.inf
            right = x.real
            if segs and segs[-1][0] == right:
                segs[-1] = (left, segs[-1][1])
            else:
                segs.append((left, right))
    out.segments = sorted(segs)

    # L3: asymptotes.
    if n > m:  # @line L3
        out.centroid = (sum(p.real for p in poles) - sum(z.real for z in zeros)) / (n - m)
        out.asymptote_angles = [(2 * k + 1) * 180.0 / (n - m) for k in range(n - m)]

    # L4: W = (N D' - N' D) / (repeated factors), built from the distinct roots.
    pg = _group(poles)
    zg = _group(zeros)
    distinct = [g[0] for g in pg] + [g[0] for g in zg]
    weights = [g[1] for g in pg] + [-g[1] for g in zg]
    w = [0j]
    for i, wt in enumerate(weights):  # @line L4
        term = _poly_c([r for j, r in enumerate(distinct) if j != i])
        w = polyadd(w, [wt * c for c in term])
    w = [c.real for c in w]  # the terms come in conjugate pairs, so W is real
    wbig = max(abs(c) for c in w)
    while len(w) > 1 and abs(w[0]) <= 1e-12 * wbig:
        w.pop(0)
    # L5: keep the roots of W where K = -D/N is real and positive.
    for s in polyroots(w):  # @line L5
        k = _real_k(den, num, s)
        if k is not None and k > 0:
            out.breakaways.append((complex(s.real, 0.0) if _is_real(s) else s, k))

    # L6: departure angles.
    for p, mu in pg:  # @line L6
        base = 180.0 + sum(math.degrees(cmath.phase(p - z)) for z in zeros)
        base -= sum(math.degrees(cmath.phase(p - q)) for q in poles if not _same(q, p))
        out.departures.append((p, sorted(_angle(cmath.exp(1j * math.radians((base + 360.0 * j) / mu))) for j in range(mu))))
    # L7: arrival angles.
    for z, nu in zg:  # @line L7
        base = 180.0 + sum(math.degrees(cmath.phase(z - p)) for p in poles)
        base -= sum(math.degrees(cmath.phase(z - y)) for y in zeros if not _same(y, z))
        out.arrivals.append((z, sorted(_angle(cmath.exp(1j * math.radians((base + 360.0 * j) / nu))) for j in range(nu))))

    # L8: imaginary axis crossings. With D and N real and ascending
    # coefficients d_a, n_b, the coefficient of w^k in D(jw) N(-jw) is
    # j^k r_k with r_k = sum over a + b = k of d_a n_b (-1)^b. Its imaginary
    # part is r_k for k = 1 mod 4, -r_k for k = 3 mod 4 and 0 for even k, so
    # Im(D(jw) N(-jw)) = w R(w^2).
    da = den[::-1]
    na = num[::-1]
    r = [0.0] * (len(da) + len(na) - 1)
    for a, dv in enumerate(da):
        for b, nv in enumerate(na):
            r[a + b] += dv * nv * (-1) ** b
    rasc = [(r[k] if k % 4 == 1 else -r[k]) for k in range(1, len(r), 2)]  # @line L8
    big = max((abs(c) for c in rasc), default=0.0)
    found = []
    k0 = _real_k(den, num, 0j)
    if k0 is not None and k0 > 0:
        found.append((0.0, k0))
    if big == 0.0:
        out.imaginary_axis_on_locus = True
    else:
        rdesc = rasc[::-1]
        while rdesc and abs(rdesc[0]) <= 1e-12 * big:
            rdesc.pop(0)
        for u in (polyroots(rdesc) if len(rdesc) > 1 else []):
            if abs(u.imag) > 1e-7 * (1.0 + abs(u)) or u.real <= 0:
                continue
            om = math.sqrt(u.real)
            k = _real_k(den, num, 1j * om)
            if k is not None and k > 0 and not any(_same(om, f[0]) for f in found):
                found.append((om, k))
    out.crossings = sorted(found)
    return out  # @line L9
test_root_locus_rules.py 241 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/root-locus-rules/. The authors are listed in prov/V7FWWP.jsonl.

import cmath
import math
import random

import pytest

from ctlmat import polyroots, polyval
from root_locus_rules import closed_loop_poly, poly_from_roots, root_locus_rules

# Closed-loop roots come from ctlmat.polyroots (Durand-Kerner, float).
# Tolerances: 1e-9 on simple roots, 1e-6 on double roots, 1 degree on
# angles read from roots at a distance 1e-3 from a pole or a zero.

SQ2, SQ3 = math.sqrt(2.0), math.sqrt(3.0)


def angle_deg(z):
    return math.degrees(cmath.phase(z)) % 360.0


def angle_gap(a, b):
    d = abs(a - b) % 360.0
    return min(d, 360.0 - d)


def match_angles(got, want, tol):
    """True if the two lists of angles agree as multisets, within tol degrees."""
    left = list(want)
    for a in got:
        best = min(range(len(left)), key=lambda i: angle_gap(a, left[i]))
        if angle_gap(a, left[best]) > tol:
            return False
        left.pop(best)
    return not left


def on_segments(x, segs, tol=1e-6):
    return any(lo - tol <= x <= hi + tol for lo, hi in segs)


def test_third_order_check_values():
    r = root_locus_rules([0, -1, -2])
    assert r.segments == [(-math.inf, -2.0), (-1.0, 0.0)]
    assert r.centroid == -1.0 and r.asymptote_angles == [60.0, 180.0, 300.0]
    assert len(r.breakaways) == 1
    s, k = r.breakaways[0]
    assert abs(s - (-1 + 1 / SQ3)) < 1e-12 and abs(k - 2 / (3 * SQ3)) < 1e-12
    assert len(r.crossings) == 1
    w, k = r.crossings[0]
    assert abs(w - SQ2) < 1e-12 and abs(k - 6.0) < 1e-12
    assert [a for _, (a,) in r.departures] == [180.0, 0.0, 180.0]
    # at K = 6 the closed loop is (s + 3)(s^2 + 2)
    roots = polyroots(closed_loop_poly(poly_from_roots([0, -1, -2]), [1.0], 6.0))
    assert abs(roots[0] + 3) < 1e-9 and abs(roots[1] + SQ2 * 1j) < 1e-9


def test_complex_poles_and_a_zero():
    r = root_locus_rules([-1 + 1j, -1 - 1j], [-2])
    assert r.segments == [(-math.inf, -2.0)]
    assert r.asymptote_angles == [180.0]
    (s, k), = r.breakaways
    assert abs(s - (-2 - SQ2)) < 1e-12 and abs(k - (2 + 2 * SQ2)) < 1e-10
    dep = dict((p, a) for p, a in r.departures)
    assert abs(dep[-1 + 1j][0] - 135.0) < 1e-9 and abs(dep[-1 - 1j][0] - 225.0) < 1e-9
    assert abs(r.arrivals[0][1][0] - 180.0) < 1e-9
    assert r.crossings == []
    # the complex branch is the circle |s + 2| = sqrt 2
    for k in (0.5, 1.0, 2.0, 4.0):
        for z in polyroots(closed_loop_poly(poly_from_roots([-1 + 1j, -1 - 1j]), [1.0, 2.0], k)):
            assert abs(abs(z + 2) - SQ2) < 1e-9


def test_triple_pole_ultimate_gain():
    r = root_locus_rules([-1, -1, -1])
    assert r.segments == [(-math.inf, -1.0)]
    assert r.breakaways == []
    (p, angles), = r.departures
    assert p == -1 and match_angles(angles, [60.0, 180.0, 300.0], 1e-9)
    (w, k), = r.crossings
    assert abs(w - SQ3) < 1e-12 and abs(k - 8.0) < 1e-12


def test_lead_design_loop():
    # K / (s (s + 2)(s + 6)) with K = 117/8 has the poles -6.5 and -0.75 +- 1.299j
    roots = polyroots(closed_loop_poly(poly_from_roots([0, -2, -6]), [1.0], 117 / 8))
    assert abs(roots[0] + 6.5) < 1e-9
    assert abs(roots[1] - complex(-0.75, -1.5 * SQ3 / 2)) < 1e-9
    r = root_locus_rules([0, -2, -6])
    (w, k), = r.crossings
    assert abs(w - math.sqrt(12)) < 1e-12 and abs(k - 96.0) < 1e-9


def test_imaginary_axis_on_locus():
    r = root_locus_rules([1j, -1j])
    assert r.imaginary_axis_on_locus and r.crossings == []
    assert r.segments == [] and r.breakaways == []
    assert match_angles([a for _, (a,) in r.departures], [90.0, 270.0], 1e-9)


def test_crossing_at_the_origin():
    # (s - 1)(s + 2) + K: a real pole passes 0 at K = 2
    r = root_locus_rules([1, -2])
    assert (0.0, 2.0) in [(w, round(k, 12)) for w, k in r.crossings]


def test_bad_input():
    with pytest.raises(ValueError):
        root_locus_rules([])
    with pytest.raises(ValueError):
        root_locus_rules([-1], [-2, -3])
    with pytest.raises(ValueError):
        root_locus_rules([-1 + 1j, -2])
    with pytest.raises(ValueError):
        root_locus_rules([-1, -2], [-1])


def random_case(rng):
    """Poles and zeros of a random real G, with distinct values at least 0.2 apart."""
    while True:
        n = rng.randint(1, 5)
        m = rng.randint(0, n)
        values = []

        def fill(count):
            out = []
            while len(out) < count:
                if count - len(out) >= 2 and rng.random() < 0.4:
                    a, b = rng.uniform(-4, 1), rng.uniform(0.3, 3)
                    out += [complex(a, b), complex(a, -b)]
                elif out and rng.random() < 0.2 and abs(out[-1].imag) == 0:
                    out.append(out[-1])
                else:
                    out.append(complex(rng.uniform(-5, 1.5), 0.0))
            return out
        poles, zeros = fill(n), fill(m)
        values = []
        for v in poles + zeros:
            if all(v != w for w in values):
                values.append(v)
        if any(abs(v - w) < 0.2 for i, v in enumerate(values) for w in values[:i]):
            continue
        if any(z == p for z in zeros for p in poles):
            continue
        return poles, zeros


def kgrid(lo, hi, count):
    return [lo * (hi / lo) ** (i / (count - 1)) for i in range(count)]


def cases(seed, count):
    rng = random.Random(seed)
    return [random_case(rng) for _ in range(count)]


def test_real_axis_rule_random():
    for poles, zeros in cases(1, 60):
        r = root_locus_rules(poles, zeros)
        den, num = poly_from_roots(poles), poly_from_roots(zeros)
        crit = [v.real for v in poles + zeros if v.imag == 0]
        for i in range(301):
            x = -10 + 15 * i / 300 + 0.001
            if any(abs(x - c) < 1e-3 for c in crit):
                continue
            k = -polyval(den, x) / polyval(num, x)
            assert (k > 0) == on_segments(x, r.segments, 0.0), (poles, zeros, x)
        # every real closed-loop pole lies on a segment
        for k in kgrid(1e-3, 1e3, 13):
            for z in polyroots(closed_loop_poly(den, num, k)):
                if z.imag == 0:
                    assert on_segments(z.real, r.segments, 1e-6 * (1 + abs(z))), (poles, zeros, k, z)


def test_asymptotes_random():
    for poles, zeros in cases(2, 60):
        r = root_locus_rules(poles, zeros)
        q = len(poles) - len(zeros)
        if q == 0:
            assert r.centroid is None and r.asymptote_angles == []
            continue
        den, num = poly_from_roots(poles), poly_from_roots(zeros)
        k = 1e8
        roots = sorted(polyroots(closed_loop_poly(den, num, k)), key=abs)
        far = roots[-q:]
        assert match_angles([angle_deg(z - r.centroid) for z in far], r.asymptote_angles, 1.0)
        if q >= 2:
            mean = sum(far) / q
            assert abs(mean - r.centroid) < 1e-3, (poles, zeros)


def test_departure_and_arrival_random():
    for poles, zeros in cases(3, 60):
        r = root_locus_rules(poles, zeros)
        den, num = poly_from_roots(poles), poly_from_roots(zeros)
        rho = 1e-3
        for p, angles in r.departures:
            mu = len(angles)
            rest = [q for q in poles if q != p]
            c = abs(polyval(num, p)) / math.prod(abs(p - q) for q in rest)
            k = rho ** mu / c
            near = [z for z in polyroots(closed_loop_poly(den, num, k)) if abs(z - p) < 10 * rho]
            assert len(near) == mu
            assert match_angles([angle_deg(z - p) for z in near], angles, 1.0), (poles, zeros, p)
        for zr, angles in r.arrivals:
            nu = len(angles)
            rest = [y for y in zeros if y != zr]
            c = abs(polyval(den, zr)) / math.prod(abs(zr - y) for y in rest)
            k = c / rho ** nu
            near = [z for z in polyroots(closed_loop_poly(den, num, k)) if abs(z - zr) < 10 * rho]
            assert len(near) == nu
            assert match_angles([angle_deg(z - zr) for z in near], angles, 1.0), (poles, zeros, zr)


def count_changes(den, num, grid, predicate):
    """Indices i where the number of closed-loop roots with the property changes from grid[i] to grid[i + 1]."""
    counts = [sum(1 for z in polyroots(closed_loop_poly(den, num, k)) if predicate(z)) for k in grid]
    return [i for i in range(len(grid) - 1) if counts[i] != counts[i + 1]]


def test_breakaways_and_crossings_random():
    grid = kgrid(1e-3, 1e3, 91)
    for poles, zeros in cases(4, 25):
        r = root_locus_rules(poles, zeros)
        den, num = poly_from_roots(poles), poly_from_roots(zeros)
        for s, k in r.breakaways:
            roots = polyroots(closed_loop_poly(den, num, k))
            assert sum(1 for z in roots if abs(z - s) < 1e-6 * (1 + abs(s))) >= 2, (poles, zeros, s, k)
        for w, k in r.crossings:
            roots = polyroots(closed_loop_poly(den, num, k))
            assert min(abs(z - 1j * w) for z in roots) < 1e-6 * (1 + w), (poles, zeros, w, k)
        real_k = [k for s, k in r.breakaways if s.imag == 0]
        for i in count_changes(den, num, grid, lambda z: z.imag == 0):
            lo, hi = grid[max(i - 1, 0)], grid[min(i + 2, len(grid) - 1)]
            assert any(lo <= k <= hi for k in real_k), (poles, zeros, grid[i])
        cross_k = [k for w, k in r.crossings]
        for i in count_changes(den, num, grid, lambda z: z.real > 0):
            lo, hi = grid[max(i - 1, 0)], grid[min(i + 2, len(grid) - 1)]
            assert any(lo <= k <= hi for k in cross_k), (poles, zeros, grid[i])

History

Walter R. Evans published the graphical analysis of control systems by the paths of the closed-loop roots in 1948, with the angle and magnitude conditions and the rules for sketching the paths from the open-loop poles and zeros. In 1950 he showed how to use the locus to choose the gain and the compensation. Before the method, designers found closed-loop poles by factoring the characteristic polynomial for each gain, or worked in the frequency domain with the Nyquist and Bode methods. After computers took over the computation of the roots, the rules stayed in use to read and check root locus plots.

References

  1. W. R. Evans, Graphical analysis of control systems, Transactions of the American Institute of Electrical Engineers 67(1) (1948) 547-551, the whole paper (the angle and magnitude conditions and the rules for the graphical construction)
  2. W. R. Evans, Control system synthesis by root locus method, Transactions of the American Institute of Electrical Engineers 69(1) (1950) 66-69, the whole paper (the use of the locus to choose the gain and the compensation)
  3. Gene F. Franklin, J. David Powell and Abbas Emami-Naeini, Feedback Control of Dynamic Systems, eighth edition, Pearson, 2019, Chapter 5, The Root-Locus Design Method (the guidelines for sketching a root locus)
  4. Katsuhiko Ogata, Modern Control Engineering, fifth edition, Prentice Hall, 2010, Chapter 6, on the analysis and design of control systems by the root locus method (the general rules for constructing root loci)

About this page

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

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