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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Walter R. Evans, 1948
The root locus construction rules compute, from the poles and zeros of the open-loop transfer function alone, the features that fix the shape of the root locus: the set of points where the closed-loop characteristic polynomial has a root for some gain . 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: is on the locus if and only if 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 and zeros , complex numbers with repetition, with and . The two lists are closed under complex conjugation, so that has real coefficients, and no pole equals a zero. Write
Both and are monic, so and the loop transfer function is with . The closed loop with unity negative feedback has the characteristic polynomial . The locus is the set .
Output.
- the real axis segments, the closure of , as a union of closed intervals;
- if , the centroid and the asymptote angles;
- the breakaway and break-in points, the points where has a multiple root for some , with that ;
- for each distinct pole of multiplicity , the departure angles, and for each distinct zero of multiplicity , the arrival angles;
- the imaginary axis crossings, the pairs with , and ; or a flag when is real for every , so that whole intervals of the imaginary axis lie on the locus.
Angles are in degrees in , measured from the positive real axis.
The algorithm
ROOT-LOCUS-RULES(p_1..p_n, z_1..z_m)- 1
check n ≥ 1, m ≤ n, both lists closed under conjugation, no pole equal to a zero; D ← ∏(s − p_i), N ← ∏(s − z_k) - 2
segments ← the closed real intervals with an odd number of real poles and zeros, with multiplicity, to their right - 3
if n > m then σ ← (Σ p_i − Σ z_k)/(n − m); angles ← (2k + 1) · 180/(n − m) for k = 0, ..., n − m − 1 - 4
W ← Σ_i w_i ∏_{j ≠ i} (s − r_j) ▷ r_i: the distinct poles and zeros; w_i: the multiplicity, negative for a zero - 5
breakaways ← the pairs (s, K) with W(s) = 0 and K = −D(s)/N(s) real and positive - 6
for each distinct pole p of multiplicity μ: θ_j ← (180 + 360 j + Σ_k ∠(p − z_k) − Σ_{q ≠ p} ∠(p − q))/μ, j = 0, ..., μ − 1 - 7
for each distinct zero z of multiplicity ν: φ_j ← (180 + 360 j + Σ_i ∠(z − p_i) − Σ_{y ≠ z} ∠(z − y))/ν, j = 0, ..., ν − 1 - 8
R ← 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 - 9
return 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 for every , and a list that is not closed under conjugation gives a 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 , where and the sum is the logarithmic derivative . Its roots are the critical points of away from the poles and zeros, and line L5 keeps the ones where is a positive real number. The other roots of 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, is real exactly when is real, and the imaginary part of that product is an odd polynomial in . The point is tested on its own, with .
The implementation works in floating point and finds the roots of and with the Durand-Kerner method of the shared helper module. It treats a value as real when its imaginary part is at most , two poles or zeros as equal when they differ by at most , and a gain as real when its imaginary part is at most .
Example
A third-order loop. Take , so , , and .
| line | computation | result |
|---|---|---|
| L2 | real values from the right: (count 1), (count 2), (count 3) | segments and |
| L3 | , angles | ; 60, 180, 300 |
| L4 | ||
| L5 | roots ; | with kept; with rejected |
| L6 | at 0: ; at : ; at : | 180, 0, 180 |
| L8 | , so | , |
At the gain is not positive, so the origin is a start point and not a crossing. The two branches from 0 and move toward each other on , meet at , and leave the axis. They follow the asymptotes at 60 and 300 degrees and cross the imaginary axis at for ; at that gain . The third branch runs from to . The value is the gain margin of the loop with , the same value that the Routh array of gives.
Complex poles and a zero. Take , with poles and the zero . Line L2 gives the segment . Line L3 gives and the single angle 180. Line L4 gives , with roots . At the gain is , a break-in point; at the gain is and the root is rejected. Line L6 at gives degrees, and 225 at . Line L7 at gives , that is 180 degrees. In line L8, has the imaginary part , so has no positive root, and : no crossings, and the loop is stable for every . The complex branch is an arc of the circle .
Complex breakaway points. Take . With the polynomial is , and is a multiple of . The roots are with , and the roots of with . At the closed loop is , so the four branches meet in pairs at two complex points. The departure angle at is 270 degrees. The Routh array of gives the crossing at for , which line L8 also returns.
Correctness
The proofs are in the correctness proof. Each statement holds in exact arithmetic, with exact roots of and .
- Angle and magnitude conditions (proved). For not a pole or zero, if and only if , that is degrees modulo 360; then . Poles and zeros are not in ; they are the limits of the branches as and .
- Real axis segments (proved). A real 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 is odd. Line L2 returns the closure of these points.
- Asymptotes (proved). If , then for large the closed loop has roots near the zeros and roots , with . If , the mean of these roots tends to .
- Breakaway points (proved). has a multiple root at for some if and only if and 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 there are exactly roots near a pole of multiplicity , and their directions from the pole tend to the angles of line L6. For large the same holds at a zero with the angles of line L7.
- Crossings (proved). For , if and only if and , unless 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 and be the poles and zeros, with and , both lists closed under complex conjugation, and no pole equal to a zero. These are the conditions that line L1 checks. Let , , and . Then and are monic with real coefficients and no common root. For the leading coefficient of is 1 if and if , so has degree for every . The locus is . All statements are in exact arithmetic, with the roots of and 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 and are analytic on a closed disc and on its boundary circle, then and have the same number of zeros inside the disc.
Fact 2 (simple roots move analytically). If is a simple root of , then by the implicit function theorem there is an analytic function near with and , and it is the only root near . Its derivative is .
Lemma 1: the angle and magnitude conditions
No pole and no zero is in . For any other , if and only if is a negative real number, that is degrees modulo 360. The gain is then unique: .
Proof. At a pole , for , because . At a zero , . For other , both and are nonzero, and if and only if . Such a exists if and only if is real and negative, and then . The angle of a product is the sum of the angles of the factors, modulo 360 degrees, which gives the angle form.
Lemma 2: the real axis segments
Let be real and not a pole or zero. Then if and only if the number of real poles and real zeros greater than , counted with multiplicity, is odd. The union of the intervals returned by line L2 is the closure of .
Proof. is real because has real coefficients, so by Lemma 1, if and only if . A complex pole or zero , , comes with (closure under conjugation), and the pair gives the factor in or . A real pole or zero gives the factor , which is negative exactly when . So the sign of is , and if and only if is odd.
Let be the distinct real poles and zeros, with multiplicities , and set , . The count is constant on each open interval and equals . Line L2 computes this running sum and records the interval when the sum is odd; on 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 is odd. By the first part, is the union of these open intervals, and its closure is the union of their closures.
Lemma 3: the asymptotes
Let , and degrees. For every there is such that for the polynomial has exactly roots in the disc for each distinct zero of multiplicity , in total roots, and exactly one root in each disc , . If , the mean of these roots tends to .
Proof. Near the zeros: on a small circle around a zero of multiplicity that contains no other root of , and ; then for , on the circle, and by Fact 1 the polynomial has as many zeros inside as , that is . This gives roots near the zeros. (Lemma 5 gives one root per direction at a multiple zero.)
Far away: let and . Then and , so for large
because and . Take the principal -th root of the last factor: for the function is analytic, and . For , if and only if , that is for some . Fix and let . On the circle , the function has , and . For large, on the circle, and by Fact 1, has exactly one zero in the disc. The discs are disjoint for large , because the centers are at distance at least apart when . Together with the roots near the zeros this gives roots, which are all the roots of .
The mean: if , the term has degree , so the coefficient of in is for every , and the sum of all roots is . The roots near the zeros have a sum that tends to , so the sum of the far roots tends to .
So the far branches approach the rays from at the angles , which line L3 returns. For the single far root is , real and going to .
Lemma 4: the breakaway points
Let be the distinct poles and zeros, the multiplicity of as a pole, or minus its multiplicity as a zero, and , the polynomial of line L4. Then with has a multiple root at if and only if and .
Proof. First, in terms of and . Let . The logarithmic derivatives are and , so
Hence with , whose roots are the repeated poles and zeros. Also , so has no root at a pole or zero, and is not the zero polynomial.
Now let . The point is a multiple root of if and only if and . Suppose both hold. Then , since otherwise too, and and would have a common root. So , and substituting into the second equation and multiplying by gives at . As is not a pole or zero (Lemma 1), and . Conversely, let and ; here because does not vanish at zeros. Then , and .
Line L5 keeps exactly the roots of with real and positive, so by Lemma 4 it returns every point where has a multiple root for some , with that gain, and nothing else. Since has the derivative , these points are the critical points of on the locus; this is the rule .
Consequence: where branches meet. By Fact 2, near a gain where all roots of are simple, each root moves analytically with 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 is constant on every interval of gains in 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 be a pole of multiplicity and let for , where the second sum runs over the other poles with multiplicity. For every small enough there is such that for the polynomial has exactly roots in , with and as below, and exactly one of them in each disc . The same holds at a zero of multiplicity for large , with and the angles of line L7.
Proof. Write with . Near , with analytic and . The equation has the roots , because and .
Scale . Then with for a constant , since is analytic. The polynomial has the simple roots , spaced degrees on the unit circle. For when (any when ), the circles are disjoint and on them, and on , . Choose so small that is less than and less than 1. By Fact 1, has exactly one zero in each disc and exactly zeros in . The factor has no zeros near . In the variable this is the claim.
At a zero, write and divide by : with . The same argument with in place of gives the angles , which are the .
So, as grows from 0, the branches that start at leave it in the directions , and as , branches arrive at from the directions . 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 , solved for the angle of .
Lemma 6: the imaginary axis crossings
Write , , , and with for and for modulo 4. Then for real . For , if is not the zero polynomial, if and only if and . The point is in if and only if .
Proof. The coefficients are real, so . Then
and is 0 for even , 1 for and for modulo 4. So the imaginary part is .
By Lemma 1, if and only if and is real and positive. This quotient equals , which is real if and only if ; for that is . If then and ; line L8 rejects this case because the gain is undefined. At , and are real, and Lemma 1 gives the last claim.
Line L8 takes the positive real roots of , sets , and keeps the ones with ; it tests on its own. So, when , its list is exactly with the gains. The crossings for are the conjugates. When , the gain is real for every with , 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 the degree of is , 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 , 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 (Lemma 2); if , the centroid and angles of the asymptotes of the far branches (Lemma 3); every point where has a multiple root for some , 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 , , 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 of Lemma 4; its coefficients are real, because the set of pairs is closed under conjugation, so the conjugate of is . Line L5 applies Lemma 4, and line L8 applies Lemma 6. Every loop runs over a finite list, so the algorithm stops.
Floating point
The implementation computes the roots of and 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 , and the computed roots of at that gain split by about the square root of the unit roundoff; but , so the multiplicity of as a root of is one more than its multiplicity as a root of . At a double root of the root of is therefore simple, and the computed point and its gain are accurate. A root of or whose has an imaginary part close to the tolerance 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 be the number of distinct poles and zeros, and 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 operations; the products and take .
- Lines L2 and L3. Grouping equal values takes and the sort ; the centroid takes .
- Line L4. The implementation forms each of the products of linear factors in , so in all. The sum has degree at most .
- Line L5. Durand-Kerner on costs per iteration, so ; each candidate needs one evaluation of and , .
- Lines L6 and L7. Each distinct pole or zero adds angles: .
- Line L8. The coefficients of take operations. has degree at most , and its roots cost .
The total is operations and extra space. In practice is below 20 and the cost is negligible next to drawing the locus by computing the roots of on a grid of gains, which costs 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 the condition is , 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 , the 180 in lines L6 and L7 becomes 0, and line L5 keeps the roots of with negative . 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 in the Routh array of , and from the auxiliary polynomial of the row of . This gives the same pairs as line L8 and also proves stability between the crossings, by the Routh-Hurwitz criterion.
- A cheaper W. Dividing by each factor with Horner's rule gives each product of line L4 in , so in all. Another way is to form and divide it by the repeated factors.
- Exact counts. With rational poles and zeros, a Sturm sequence of counts the real breakaway candidates in an interval without rounding errors (see real root counting).
- Discrete time. For a sampled loop , lines L2 to L7 hold unchanged in the plane, and the stability boundary is the unit circle. Line L8 then becomes the search for the with real and positive.
- Numerical locus. Design tools compute the roots of 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 on a grid of gains with a polynomial root finder and use the rules to place the grid. The rules need a rational and one gain that enters linearly; for a time delay, use a Padé approximation first.
Pitfalls
- Rejected candidates. Not every root of is a breakaway point. A real root of outside the real axis segments has , and a complex root is a breakaway point only if its 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 relative (see root conditioning). A test of a breakaway point must use a tolerance of this size, not .
- Asymptotes are limits. The branches approach the asymptotes only as , 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 has departure angles spaced by 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 and and . A plant with a negative leading coefficient, such as , needs the negative gain rules.
- The imaginary axis on the locus. If is real for every , as for , 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag V7FWWP Edit this page History Report an error Markdown