ENع
→Control in Python
الدرس S4 · Special topics

Designing controllers in Python

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

20 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Design a controller for a mass on a spring and a damper using nothing but plain Python. Store the plant as lists of coefficients, close the loop with list arithmetic, simulate a step with the Runge-Kutta method, find the poles, and measure overshoot and settling time. Then let a for loop search for the gains and check the winner with the python-control library. The P, PI, PD and PID ideas themselves are taught in the lessons "Adding integral and derivative action" and "The PID controller".

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل S4 · تفاعلي
01 / 10

The plant as two lists

Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.

# a transfer function is two lists of coefficients
# G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20
G = [1], [1, 10, 20]
print(G[0][-1] / G[1][-1])     # 0.05
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. The plant as two lists

    Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.

    # a transfer function is two lists of coefficients
    # G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20
    G = [1], [1, 10, 20]
    print(G[0][-1] / G[1][-1])     # 0.05
  2. Simulate a step

    Python cannot read a curve off a formula, so it marches time forward in 1 ms steps with the Runge-Kutta method. Push the mass with 1 N and it creeps to just 0.05 m. We want 1 m: we need a controller.

    # march time forward: controllable canonical form + RK4
    def step(num, den, T=2.0, dt=0.001):
        n = len(den) - 1
        a = [c / den[0] for c in den[1:]]
        b = [0.0] * (n - len(num)) + [c / den[0] for c in num]
        f = lambda x: x[1:] + [1.0 - sum(a[n - 1 - i] * x[i] for i in range(n))]
        x, t, y = [0.0] * n, [], []
        for k in range(round(T / dt) + 1):
            t.append(k * dt)
            y.append(sum(b[n - 1 - i] * x[i] for i in range(n)))
            k1 = f(x)
            k2 = f([xi + dt / 2 * ki for xi, ki in zip(x, k1)])
            k3 = f([xi + dt / 2 * ki for xi, ki in zip(x, k2)])
            k4 = f([xi + dt * ki for xi, ki in zip(x, k3)])
            x = [xi + dt / 6 * (p + 2 * q + 2 * r + s)
                 for xi, p, q, r, s in zip(x, k1, k2, k3, k4)]
        return t, y
    
    t, y = step(*G)               # a 1 N push, plant alone
    print(round(y[-1], 2))        # 0.05
  3. Close the loop in code

    Add a proportional controller, Kp = 300, and feed the position back. Closing the loop is list arithmetic: T = CG / (1 + CG). Multiplying and adding the coefficient lists gives T(s) = 300 / (s² + 10s + 320).

    # polynomials as lists: multiply and add
    def mul(p, q):
        r = [0.0] * (len(p) + len(q) - 1)
        for i, pi in enumerate(p):
            for j, qj in enumerate(q):
                r[i + j] += pi * qj
        return r
    def add(p, q):
        n = max(len(p), len(q))
        p, q = [0] * (n - len(p)) + p, [0] * (n - len(q)) + q
        return [x + y for x, y in zip(p, q)]
    def pid(Kp, Ki=0, Kd=0):      # (Kd s² + Kp s + Ki) / s
        if Ki: return [Kd, Kp, Ki], [1, 0]
        return ([Kd, Kp] if Kd else [Kp]), [1]
    def close(C, G):              # T = CG / (1 + CG)
        num = mul(C[0], G[0])
        return num, add(mul(C[1], G[1]), num)
    
    T = close(pid(300), G)
    print(T)  # ([300.0], [1.0, 10.0, 320.0])
  4. Measure the response

    Step the closed loop, then read numbers off the samples. It overshoots by 40.1 %, settles within 2 % after 0.77 s and ends at 0.94 m, not 1. Proportional control alone leaves a steady-state error.

    # overshoot %, 2 % settling time, final value
    def info(t, y, T):
        yf = T[0][-1] / T[1][-1]   # final value = DC gain
        over = max(0.0, (max(y) - yf) / yf * 100)
        ts = next(t[i + 1] for i in range(len(y) - 1, -1, -1)
                  if abs(y[i] - yf) > 0.02 * abs(yf))
        return round(over, 1), round(ts, 2), round(yf, 2)
    
    t, y = step(*T)
    print(info(t, y, T))   # (40.1, 0.77, 0.94)
  5. The poles explain it

    A root finder gives the closed-loop poles: -5 ± j17.18. They sit far from the real axis, so the damping ratio is only 0.28. Light damping means a big overshoot.

    # roots of the denominator (Durand-Kerner)
    def poles(den):
        a = [c / den[0] for c in den]
        n = len(a) - 1
        z = [(0.4 + 0.9j) ** k for k in range(n)]
        for _ in range(500):
            new = []
            for i, zi in enumerate(z):
                v = 0
                for c in a:
                    v = v * zi + c
                d = 1
                for j, zj in enumerate(z):
                    if j != i:
                        d *= zi - zj
                new.append(zi - v / d)
            z = new
        z.sort(key=lambda p: (p.real, p.imag))
        return [round(p.real, 2) if abs(p.imag) < 1e-9
                else complex(round(p.real, 2), round(p.imag, 2)) for p in z]
    
    print(poles(T[1]))     # [(-5-17.18j), (-5+17.18j)]
  6. Add derivative action

    Derivative action (Kd = 10) pushes against fast motion. The poles move to -10 ± j14.83, the overshoot falls to 15.3 % and the loop settles in 0.29 s. It still ends at 0.94 m.

    T = close(pid(300, 0, 10), G)  # Kp = 300, Kd = 10
    t, y = step(*T)
    print(info(t, y, T), poles(T[1]))
    # (15.3, 0.29, 0.94) [(-10-14.83j), (-10+14.83j)]
  7. Add integral action

    Integral action adds up the error over time and keeps pushing until it is zero. With Kp = 350, Ki = 300 and Kd = 50 the output heads for exactly 1 m, with no overshoot, settling in 0.83 s.

    T = close(pid(350, 300, 50), G)  # Kp, Ki, Kd
    t, y = step(*T)
    print(info(t, y, T), poles(T[1]))
    # (0.0, 0.83, 1.0) [-53.14, -5.9, -0.96]
  8. Let a loop search

    Now Python does the trying. A for loop steps Kd from 0 to 80 and keeps the fastest design with under 5 % overshoot. It picks Kd = 20: 4.1 % overshoot, settled in 0.73 s, faster than Kd = 50.

    # let a loop try the designs: Kd = 0, 10, ..., 80
    best = None
    for Kd in range(0, 81, 10):
        T = close(pid(350, 300, Kd), G)
        t, y = step(*T)
        over, ts, yf = info(t, y, T)
        if over < 5 and (best is None or ts < best[2]):
            best = (Kd, over, ts)
    print(best)            # (20, 4.1, 0.73)
  9. Check with python-control

    The python-control library does the same jobs with tf, feedback and step_info. It reports 4.1 % and 0.73 s for the winner, matching our code. Give it the time grid: its own default stopped one loop at 0.13 s.

    # the same design with python-control (pip install control)
    import control as ct
    import numpy as np
    G = ct.tf([1], [1, 10, 20])
    C = ct.tf([20, 350, 300], [1, 0])   # Kd s² + Kp s + Ki over s
    T = ct.feedback(C * G, 1)
    t = np.linspace(0, 2, 2001)     # give it the time grid
    i = ct.step_info(T, T=t)
    print(round(i['Overshoot'], 1), round(i['SettlingTime'], 2))
    # 4.1 0.73
  10. The design loop

    Every design went round one loop: model, simulate, measure, change the gains. Python makes each lap take milliseconds, so you can try many controllers, then check the winner with a trusted library and on the real machine.

    # the design loop, in four lines of the script
    #   model     G = [1], [1, 10, 20]
    #   design    T = close(pid(Kp, Ki, Kd), G)
    #   simulate  t, y = step(*T)
    #   measure   info(t, y, T) and poles(T[1])
    #   ...change the gains and go round again
    
    #            overshoot  settling  final
    # P          40.1 %   0.77 s    0.94
    # PD         15.3 %   0.29 s    0.94
    # PID         0.0 %   0.83 s    1.00
    # Kd = 20     4.1 %   0.73 s    1.00

اختبار يتاح بعد الخطوة الأخيرة.