PID control#

A PID controller adds an integral and a derivative term to proportional feedback. This page adds each term in turn to a simulated heater, and shows what each one changes.

Download this page as a notebook to run its code in JupyterLab. Running the notebooks explains how to set it up. It uses the heater from Introduction to control.

The three terms#

“Proportional-integral-derivative (PID) control is by far the most common way of using feedback in engineering systems.”[1] A PID controller sets its output from the error, the setpoint minus the measurement, as the sum of three terms:

  • Proportional. Depends only on the present error. Raising its gain speeds up the response, but too much gain makes the process variable oscillate.[2]

  • Integral. Sums the error over time, so it keeps pushing until no error is left. It removes steady-state error, but increases overshoot.[2]

  • Derivative. Pushes back when the process variable is changing fast, which reduces overshoot. It’s very sensitive to noise in the measurement, so most real systems use only a little of it.[2]

Adding the terms#

This controller runs every dt seconds. It keeps a running sum of the error for the integral term and the previous error for the derivative term, and limits its output to 0 to 100 %. It stops adding to the sum while its output is limited, so the integral term can’t wind up. The heater has a time constant of 8 s, and the room cools from 20 °C to 10 °C at 20 s. The measurement has 0.1 °C of noise. The process is made up for the simulation:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from learning.style import set_matplotlib_style

set_matplotlib_style()
dt = 0.05  # s per control cycle
t = np.arange(0, 40, dt)
setpoint = 50.0  # °C


class PID:
    """A PID controller with its output limited to 0 to 100 %."""

    def __init__(self, kp, ki=0.0, kd=0.0):
        self.kp, self.ki, self.kd = kp, ki, kd
        self.integral = 0.0
        self.last_error = 0.0

    def update(self, setpoint, measured):
        error = setpoint - measured
        derivative = (error - self.last_error) / dt
        self.last_error = error
        integral = self.integral + error * dt
        output = self.kp * error + self.ki * integral + self.kd * derivative
        if 0 <= output <= 100:  # add to the sum only while the output isn't limited
            self.integral = integral
        return float(np.clip(output, 0, 100))


def simulate(controller, seed=1):
    """Run the heater, and return each cycle's temperature and power."""
    rng = np.random.default_rng(seed)
    temperature = 20.0
    temps, powers = [], []
    for time in t:
        room = 20.0 if time < 20 else 10.0  # °C: the disturbance
        power = controller.update(setpoint, temperature + rng.normal(0, 0.1))  # %
        temperature += dt * (-(temperature - room) + 0.8 * power) / 8.0
        temps.append(temperature)
        powers.append(power)
    return np.array(temps), np.array(powers)


gains = {
    "P": PID(kp=10),
    "PI": PID(kp=10, ki=8),
    "PID": PID(kp=10, ki=8, kd=2),
}
results = {name: simulate(c) for name, c in gains.items()}

fig, (top, bottom) = plt.subplots(2, 1, sharex=True)
top.axhline(setpoint, color="0.5", linestyle="--")
for name, (temps, powers) in results.items():
    top.plot(t, temps, label=name)
    bottom.plot(t, powers)
top.set_ylabel("Temperature (°C)")
top.legend()
bottom.set_ylabel("Heater power (%)")
bottom.set_xlabel("Time (s)")
plt.show()

pd.DataFrame(
    {
        name: {
            "peak before 20 s (°C)": temps[: int(20 / dt)].max(),
            "temperature at 40 s (°C)": temps[-1],
            "output noise, last 5 s (% std)": powers[-int(5 / dt) :].std(),
        }
        for name, (temps, powers) in results.items()
    }
).round(1)
../../_images/152598f581e0612b5a304246e0e633bcc3d7d545f49f02dbf49934f153de02c7.svg
P PI PID
peak before 20 s (°C) 46.7 51.2 51.6
temperature at 40 s (°C) 45.6 50.0 50.0
output noise, last 5 s (% std) 1.1 1.1 7.6

On this heater:

  • P settles below the setpoint, and stays there.

  • PI reaches the setpoint, including after the room cools. It overshoots it on the way up, as the table’s peak shows.

  • PID barely changes the response, but its output is much noisier. The derivative term differentiates the noise in the measurement, as well as the signal.

The derivative term is meant to reduce overshoot,[2] but on this process it has little overshoot to reduce. Control covers step responses, integral windup and loop rates.

Tuning#

Tuning means choosing the three gains. Classic methods such as Ziegler–Nichols tuning give starting values from a simple test of the process.[2][1] Record each attempt, with its gains, so you can compare them afterwards.

In Nominal#

Each tuning attempt is a test, so give each its own dataset, with its gains as properties. A property is a key-value pair stored with the dataset.[3] This code uploads the three runs above:

from nominal.core import NominalClient

client = NominalClient.from_profile("default")

for name, controller in gains.items():
    # one CSV file for each attempt, with a "timestamp" column and the channels below
    dataset = client.create_dataset(
        f"Heater tuning: {name}",
        properties={
            "kp": str(controller.kp),
            "ki": str(controller.ki),
            "kd": str(controller.kd),
        },
    )
    dataset.add_tabular_data(f"tuning-{name}.csv", timestamp_column="timestamp", timestamp_type="iso_8601")

Then plot the attempts’ temperature channels in one workbook, and compare their overshoot and settling time against the gains in each dataset’s properties.[4]

Further reading#

References#