Model-Based Control Basics

If you know the physics, you can design the rule that holds a robot on target. Wind pushes a cart. P swings, PD settles 0.15 m off, PID lands on the mark. The best linear rule of all is one matrix times the state.

Pick a controller, set the wind, and press Run. Watch where the teal cart ends up against the yellow target. Then we build, piece by piece, the model, feedback, PID, stability, the eigenvalue test, tracking, LQR and the Riccati recursion.

You need vectors and matrices, what a derivative is and a little Python. No control theory. We build the rest from zero.

Lecture 12 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Before: Lecture 11, Advanced RL. Next: Lecture 13, Optimal Control and Planning I.

Hold a cart on target in the wind

0.60

Illustrative toy. A 1 kg cart is a double integrator; wind is a constant acceleration in m/s². Gains: P has Kp = 4; PD adds Kd = 2.5; PID adds Ki = 1.5. Simulated at 100 Hz for 10 s from 1 m left of the target.

Chapter 0

You Know the Physics. Now What?

See why a plan computed once fails on a small model error, and why a rule that reads the state does not

A drone hovers over a field. A gust shoves it half a metre sideways. What thrust should it send in the next 20 ms, given where it is now?

The last lectures learned behaviour by trial and error. This lecture starts from the other end. You already have a dynamics model: an equation that says how the robot's state changes when you push. The lecture lists where you get one: games with known rules, rigid-body physics and robot simulators. You can also fit a few unknown numbers from data: system identification.

With a model, the work has two steps. Get the model, then choose actions. This lecture is step two. Call the current state x and the action u. The answer is a control law: a rule u = π(x) that maps the state to the action, every tick.

Why not compute a whole plan once and play it back? Try it. The plan below moves a cart 1 m in 4 s. Someone computed it for a 1 kg cart.

Play a plan on the wrong cart

Set the real mass. Pink plays the plan blind. Teal reads its position and corrects. Both aim for the yellow target.

1.25 kg

Illustrative toy. The plan is a smooth push profile for 1 m in 4 s on a 1 kg cart. The feedback rule is u = −4x − 4v toward the target. Both run on a cart of the mass you set.

Work the heavy case. A cart 1.25 times heavier gets 1/1.25 = 0.8 of each planned acceleration. So it travels 0.8 m and stops 0.2 m short. The plan never looks, so it never knows.

Failure. An open-loop plan meets a model error.

Symptom: the robot stops short or overshoots by the same fraction as the error. Measure: log the final position against the plan's. Fix: close the loop, so the rule reads the state every tick.

Here is where the lecture ends up. For a linear model and a quadratic cost, the best possible control law is one matrix times the state: u = −Kx. No network. Chapter 7 shows why.

The road

  1. The state-space model: how the state moves, in two matrices.
  2. Feedback: push harder the farther you are, and the gain limit of a digital loop.
  3. PID: the three terms behind the hero's P, PD and PID buttons.
  4. Stability: does it come home, proved with an energy.
  5. Eigenvalues: read stability off a matrix.
  6. Disturbance and tracking: the hero's Wind slider, and following a moving target.
  7. LQR: the best linear rule for a quadratic cost.
  8. Riccati by hand: the gain, computed backward one step at a time.
  9. Linearize: use all of it on a nonlinear robot.
  10. The field guide: numbers, code, links and the credit.
A plan for a 1 kg cart runs on a 2 kg cart. Why does it stop short, while a feedback rule does not?

Chapter 1

The State-Space Model

Write how a system moves as a state, an input and a rule, and see why commanding acceleration is harder than commanding speed

To control a cart, you first say exactly how it moves. Three words carry it.

The state x is everything you need now to predict the future: for a cart, its position p and velocity v. The input u is what you choose: a force. The dynamics say how fast the state changes, given the state and the input. Write that rate of change as ẋ, said "x-dot".

Two toy systems carry most of the intuition. In the single integrator, the input is the velocity. Stop pushing and it stops. In the double integrator, the input is the acceleration: Newton's law for a 1 kg mass. Stop pushing and it coasts.

Push once, then let go

Purple is the push: 1 unit for one second. Teal is the position. Pick the system and watch what happens after the push ends.

Illustrative toy. The push is u = 1 from t = 1 s to t = 2 s, then 0. Both systems start at rest at position 0.

When the dynamics are linear, two matrices hold all of it. Call A the matrix for how the state moves on its own, and B the matrix for how the input enters.

Say it aloud

x-dot equals A times x, plus B times u.

ẋ
x-dot how fast each part of the state changes now. For the cart: velocity and acceleration.
A
A an n by n matrix: how the state moves with no push. For the cart, n = 2.
x
x the state, n numbers. For the cart: position p in metres and velocity v in m/s.
B
B an n by m matrix: where the push enters the state.
u
u the input, m numbers. For the cart, m = 1: the force per kilogram.
In plain words

Multiply the state x by A. Multiply the input u by B. Add the two: that is x-dot, how fast the state is changing.

With numbers

The double integrator has A = [[0, 1], [0, 0]] and B = [0; 1]. Take p = 2 m, v = 0.5 m/s and u = −1. Then Ax = [0.5; 0] and Bu = [0; −1], so ẋ = [0.5; −1]. The cart moves right at 0.5 m/s and slows by 1 m/s each second.

A computer steps in time. With a time step Δt of 0.1 s, the next state is the old one plus Δt times ẋ. In the example, p becomes 2.05 m and v becomes 0.4 m/s.

Mind the shapes. The controller takes in 2 numbers and puts out 1. A drone flying in a vertical plane has 6 states and 2 inputs. Its A is 6 by 6 and its B is 6 by 2.

Failure. You model a cart as a single integrator.

Symptom: the controller stops pushing at the target and the cart coasts past. Measure: log the velocity after the push ends; nonzero means momentum. Fix: put velocity in the state and treat the input as an acceleration.

In ẋ = Ax + Bu, what do A and B describe?

Chapter 2

Feedback: Push Harder the Farther You Are

Close the loop with one gain, watch the error melt away, and find the gain where a digital loop blows up

The lecture lists the jobs a control law can have: hold a target, track a path, minimize a cost, adapt to change, and survive disturbances. Holding a target comes first, because the others build on it.

Wire a law into the dynamics and nothing is left to choose. The result is the closed-loop system: the dynamics with the controller inside. Designing a controller means choosing the law so the closed loop behaves well.

The simplest law is the proportional controller, or P: push back in proportion to the error. Take the single integrator with target 0. Choose a positive number k, the gain, and push u = −k × x. At x = 2, the push is −2k.

Now the state's rate is −k times itself. So each second the error shrinks by the same fraction: after t seconds it is e to the minus k t times its start. With k = 0.8 per second, the error halves every ln 2 / 0.8 = 0.87 s.

A computer applies the law once every Δt seconds. Each tick multiplies the error by (1 − k × Δt). That factor is where the trouble lives.

Turn up the gain of a digital loop

Blue dots are the error at each 0.1 s tick. The dashed grey curve is the ideal continuous answer. Raise k and find where the dots stop following it.

0.8 /s

Illustrative toy. Single integrator, error starts at 1, the controller runs every Δt = 0.1 s and holds its push between ticks.

Work three gains with Δt = 0.1 s. At k = 5 the factor is 0.5: the error halves each tick. At k = 15 it is −0.5: the error flips sign each tick but shrinks. At k = 25 it is −1.5: it flips and grows. The limit is k × Δt = 2, so k = 20.

Failure. The gain is too high for the loop rate.

Symptom: a buzz that flips sign every tick and grows. Measure: compute k × Δt; above 1 it overshoots, above 2 it diverges. Fix: lower k, or run the loop faster.

Plan or policy

PropertyOpen-loop planClosed-loop policy
ComputesA sequence of inputs, onceA rule u = π(x)
Reads the stateNeverEvery tick
After a gustStays off courseCorrects
Real useChoose the pathHold the robot on the path

Real systems use both. A planner picks the path. A feedback law holds the robot on it. Chapter 6 builds that pair.

A P controller on a single integrator runs every 0.1 s with gain k = 30. What happens?

Chapter 3

PID: Spring, Brake and Memory

Add a damping term to stop the swing and an integral term to cancel a steady push

Now take the double integrator: a cart where you choose the acceleration. Apply pure P, u = −x. The cart springs toward 0, passes it at full speed, and swings forever. Nothing removes energy. That is the hero's P button.

Three terms fix three problems. Call the error e the position minus the target. Its rate ė is how fast the error changes. Its integral is the running total of the error over time.

Say it aloud

u equals minus K-p times e, minus K-d times e-dot, minus K-i times the integral of e d-t.

u
u the push the controller sends now, in m/s² for the cart.
Kp
K-p the proportional gain: the stiffness of the spring that pulls toward the target.
e
e the error: position minus target, in metres.
Kd
K-d the derivative gain: the strength of the brake.
ė
e-dot how fast the error changes, in m/s.
Ki
K-i the integral gain: how hard the remembered error pushes.
∫e dt
the integral of e d-t the running total of the error over time, in metre-seconds.
In plain words

Measure the error e, its rate e-dot and its running total. Multiply each by its gain, K-p, K-d and K-i. Add the three with a minus sign: that is the push u.

With numbers

With made-up numbers: Kp = 1, Kd = 2, Ki = 0.1. The cart is at e = 0.5 m, moving back at ė = −0.3 m/s, with a running total of 0.8. Then u = −0.5 + 0.6 − 0.08 = +0.02. P pulls left, D brakes the leftward motion, I adds a nudge. With Δt = 0.1 s, the total becomes 0.8 + 0.5 × 0.1 = 0.85.

TermReacts toFixesToo much gives
PThe error nowPulls toward the targetRinging
DThe error's rateOvershoot and swingingA slow crawl, amplified sensor noise
IThe error's running totalA steady offset from a constant pushSlow, large overshoot

Tune a PID cart in the wind

The cart starts 1 m left of the yellow target and a wind of 0.6 pushes it right. Set Kd to 0 first, then raise it. Then raise Ki.

4.0
0.5
0.0

Illustrative toy. A 1 kg double-integrator cart, constant wind 0.6 m/s², simulated at 100 Hz for 15 s.

Why does PD leave an offset in the wind? At rest the error rate is 0, so the spring alone must cancel the wind: Kp × e = wind. With wind 0.6 and Kp = 4, the cart sits at e = 0.15 m. The integral grows while any error remains, so it ramps the push until the error is exactly 0. The lecture calls this the simplest adaptive controller: it learns the constant push and cancels it.

Failure. Integral windup: the motor saturates while the running total keeps growing.

Symptom: a large, slow overshoot after a long push. Measure: log the running total next to the motor command. Fix: clamp the total, or stop adding to it while the motor is at its limit.

Now build it. One line of code turns a P-only cart into a PID cart.

A PD controller settles a cart 0.15 m from its target in a steady wind. Which term removes the offset, and why?

Chapter 4

Stability: Does It Come Home?

Name the three kinds of stability, then prove one with an energy that can only fall

"It looks like it settles" is not a proof. Control theory asks a precise question. Nudge the system off its rest point, its equilibrium. Does it come back?

KindWhat it meansExample
StableStart near, stay near. It need not return.A pendulum with no friction swings forever in a small arc.
Asymptotically stableStable, and it returns to rest in the end.The same pendulum with a little friction.
Exponentially stableIt returns at least as fast as a shrinking exponential.A damped cart: the error shrinks by a fixed fraction each second.

Each row is stronger than the one above. For linear systems the last two are the same thing, so "it returns" already means "it returns fast".

Slide the damping through zero

Teal is the position after a 1 m nudge. Yellow, below, is the energy. Slide the damping from negative to positive and watch the energy.

0.60

Illustrative toy. A spring of stiffness 1 and a damper c on a 1 kg mass: acceleration = −x − c × v. Released at x = 1 m, v = 0.

For a big system you cannot solve the equations and look. Lyapunov's idea skips the solving. Find an energy that is zero at the target and positive everywhere else. Show it never rises. Then the system must drain toward the bottom.

Take the device's spring and damper: position x, velocity v, stiffness 1 and damping c. Its energy V is half the squared position plus half the squared velocity. Its rate of change is x × v + v × (−x − c × v). The first two terms cancel.

Say it aloud

V-dot equals minus c times v squared.

V̇
V-dot how fast the energy V = ½(x² + v²) changes, in joules per second for a 1 kg mass.
c
c the damping: the brake strength, set by the controller.
v²
v squared the velocity times itself, never negative.
In plain words

The spring only moves energy between position and velocity. The damper removes energy at the rate c times v squared. So if c is positive, V can only fall.

With numbers

With made-up numbers: c = 0.6 and v = 0.5 m/s give V̇ = −0.6 × 0.25 = −0.15 per second. With c = 0, V̇ = 0: the energy stays put and the cart swings forever. That is stable, and no more.

The lecture's own example is the single integrator with u = −Kx. Use the energy ½x². Its rate is −Kx², which is below zero for every nonzero x when K is positive. So the loop is exponentially stable, and you never solved it.

Failure. A loop that is stable but not asymptotically stable.

Symptom: it never settles, and any steady push moves it off. Measure: plot the energy; flat means no damping. Fix: add damping, the D term.

A nudged system swings forever in a small band and never settles. Which kind of stability does it have?

Chapter 5

Eigenvalues: Read Stability Off the Matrix

Build the closed-loop matrix, find its eigenvalues, and check their real parts

For a linear system you do not need to simulate to know if it settles. The answer sits in one matrix.

Wire the law u = −Kx into ẋ = Ax + Bu, where K is the gain matrix. The closed loop is ẋ = (A − BK)x. The eigenvalues of A − BK are the rates of its natural motions, its modes. Call one eigenvalue λ. Each mode moves like e to the λ t.

For the double integrator with a PD law, K = [Kp, Kd] and A − BK = [[0, 1], [−Kp, −Kd]]. Its eigenvalues solve one quadratic.

Say it aloud

Lambda squared plus K-d times lambda plus K-p equals zero.

λ²
lambda squared the eigenvalue times itself.
Kd
K-d the brake gain of the PD law.
λ
lambda an eigenvalue: a complex number σ + iω. Its real part σ sets growth or decay; its imaginary part ω sets the swing rate.
Kp
K-p the spring gain of the PD law.
In plain words

Pick the gains K-p and K-d. Solve the quadratic for its two roots lambda. If both have a negative real part, every mode shrinks and the loop is exponentially stable.

With numbers

Kp = 1 and Kd = 2 give (λ + 1)² = 0, so λ = −1 twice: the error decays like e−t. Set Kd = 0 and λ = ±i: real part 0, a swing that never ends. Kp = 4 and Kd = 1 give λ = −0.5 ± 1.94i: a swing at 1.94 rad/s inside an envelope that shrinks like e−0.5t.

Why the real part? Write λ = σ + iω. Then eλt = eσt × (cos ωt + i sin ωt). The first factor is the envelope. The second only swings.

Real part σEnvelopeVerdict
Below 0ShrinksExponentially stable
Exactly 0ConstantMarginal: swings forever
Above 0GrowsUnstable

A matrix whose eigenvalues all have negative real parts is Hurwitz. Choosing K means choosing where these eigenvalues, also called poles, sit.

Drag the gains, move the poles

Left: the complex plane, with the stable half shaded green. Purple dots are the two poles. Right: the cart's response from 1 m. Drop Kd to 0 and watch the poles reach the line.

1.0
2.0

Illustrative toy. Double integrator with u = −Kpp − Kdv. A negative Kd is a wrong-sign brake, here to show an unstable case.

Real controllers run in discrete time, and there the boundary changes. For xt+1 = (A − BK)xt, every tick multiplies each mode by λ. So every eigenvalue needs a magnitude below 1: inside the unit circle, not the left half-plane.

Failure. A gain with the wrong sign.

Symptom: the robot drifts away faster and faster. Measure: np.linalg.eigvals(A - B @ K); one real part above 0, or one magnitude above 1 in discrete time. Fix: flip the sign, then place the poles to the left.

Now test it in code. You build A − BK and read off the largest eigenvalue magnitude.

For a continuous-time closed loop ẋ = (A − BK)x, which condition guarantees exponential stability?

Chapter 6

Disturbance and Tracking

See why exponential stability buys robustness, then follow a moving target with a feedforward term

The real world never matches the model. The lecture splits the gap in two. Robust control survives an error you cannot learn. Adaptive control estimates an error you can learn, and cancels it.

Add a constant push d to the single integrator under P control. Now the rate is −k × x + d. It stops changing where the two cancel, at x = d / k. With d = 0.6 and k = 4, the offset is 0.15.

A bounded push buys a bounded error, and a bigger gain shrinks it. This is input-to-state stability (ISS). An exponentially stable loop has it; a merely stable one does not.

Now the target moves. Call the desired path xd(t), its velocity ẋd and its acceleration ẍd. The lecture's tracking law for the double integrator is:

Say it aloud

u equals minus K-p times x minus x-d, minus K-d times x-dot minus x-d-dot, plus x-d-double-dot.

u
u the push, an acceleration in m/s².
Kp
K-p the spring gain.
x − xd
x minus x-d the tracking error: where the cart is minus where the path is now.
Kd
K-d the brake gain.
ẋ − ẋd
x-dot minus x-d-dot the velocity error.
ẍd
x-d-double-dot the feedforward: the acceleration the path itself needs.
In plain words

Run PD on the tracking error x minus x-d and the velocity error. Then add x-d-double-dot, the acceleration the path needs. The added term does the work you can predict; feedback only cleans up.

With numbers

The path is xd = 0.6 sin(1.2t). At its peak, xd = 0.6, ẋd = 0 and ẍd = −0.6 × 1.44 = −0.864. The cart is at x = 0.5 and at rest. With Kp = 4 and Kd = 2.5: u = 0.4 − 0 − 0.864 = −0.464. The feedforward already turns the cart back with the path.

Why it works: write the error e = x − xd and substitute. The feedforward cancels the path's acceleration and leaves the PD equation from Chapter 5, now on the error: ë + Kdė + Kpe = 0. For a fixed target, ẋd and ẍd are 0 and it is plain PD.

Chase a moving target in the wind

Yellow is the path, teal is the cart. Turn the feedforward off and watch the cart lag. Raise the wind and watch it sit off the path.

0.00

Illustrative toy. Path 0.6 sin(1.2t) m, gains Kp = 4 and Kd = 2.5, a 1 kg cart starting on the path. The error read-out averages the last 6 s.

Failure. Tracking with feedback only.

Symptom: the robot follows the path late, by a steady phase. Measure: plot the error against the path's acceleration; they line up. Fix: add the feedforward term ẍd.

In the tracking law, what does the term ẍd do?

Chapter 7

LQR: The Best Linear Rule

Write down what a run costs, and get the optimal gain matrix from one equation

Which gains are best? Write down what "best" costs, and the answer drops out. This is the linear quadratic regulator (LQR).

LQR charges two things at every instant. It charges the state for being away from 0, weighted by a matrix Q. It charges the push for its size, weighted by a matrix R. The total over all time is the cost J.

Say it aloud

J equals the integral from zero to infinity of x-transpose Q x plus u-transpose R u, d-t.

J
J the total cost of a run. Lower is better.
∫0∞
the integral from zero to infinity add up the cost at every instant, from now on.
xTQx
x-transpose Q x the state cost: the squared error, weighted by Q. Q says which errors matter.
uTRu
u-transpose R u the effort cost: the squared push, weighted by R. R says how dear the motors are.
dt
d-t a small slice of time.
In plain words

At each instant, square the error and weigh it by Q. Square the push and weigh it by R. Add both, then add over all time. That is J.

With numbers

With made-up numbers, one state: x = 1, u = −1, Q = 1 and R = 0.1. The running cost is 1 × 1 + 0.1 × 1 = 1.1 per second. Raise R to 10 and the same push costs 10 per second.

The result: for a linear model and this cost, the best of all controllers is linear state feedback. The gain comes from a matrix P. P solves a matrix equation called the algebraic Riccati equation; a library call such as scipy.linalg.solve_continuous_are solves it.

Say it aloud

u equals minus K x, where K equals R-inverse times B-transpose times P.

u
u the optimal push.
K
K the LQR gain matrix, m by n.
x
x the state now.
K =
K equals how to compute the gain once, offline.
R−1
R-inverse the inverse of the effort weight: dear motors mean a small gain.
BT
B-transpose picks out the parts of the state the push can reach.
P
P the cost-to-go matrix: xTPx is the least cost left from state x. It is the value function of earlier lectures.
In plain words

Solve the Riccati equation for P once. Multiply R-inverse, B-transpose and P to get K. At run time, multiply the state x by K and negate: that is u.

With numbers

For the double-integrator cart with Q = diag(1, 0) and R = 1, the solver gives P = [[1.414, 1], [1, 1.414]]. BTP is P's bottom row, so K = [1, 1.414] and u = −p − 1.414v. The poles are −0.71 ± 0.71i: stable.

LQR is optimal and stable together. Under mild conditions on A, B, Q and R, the matrix A − BK is Hurwitz. Dynamic programming (the Hamilton-Jacobi-Bellman equation) and Pontryagin's principle both lead to it.

Trade error against effort

The cart starts 1 m off. Teal is the position, purple the optimal push. Slide toward cheap error, then toward cheap effort.

1.0

Illustrative toy. Double integrator, Q = diag(q, 0), R = r. For this system the Riccati solution gives K = [√(q/r), √(2√(q/r))], checked against scipy.

The first push is −K1 × 1 m: 10 m/s² at Q/R = 100, 1 m/s² at Q/R = 1. For this cart, every ratio keeps the same response shape and changes only its speed.

Failure. Q/R set too high for a real motor.

Symptom: the motor saturates at the start and the response no longer matches the design. Measure: the first push is K times the largest error you expect; compare it with the motor limit. Fix: raise R.

In LQR, what happens to the optimal controller when you raise R relative to Q?

Chapter 8

Riccati by Hand: The Gain, Backward

Run discrete LQR as dynamic programming, from the last step back to the first, with numbers

The continuous Riccati equation needs a library. The discrete, finite-horizon version is a loop small enough to run by hand. It shows where the gain comes from: dynamic programming, run backward in time, like value iteration in Lecture 7.

Take one state, xt+1 = A xt + B ut. Each step costs Q xt² + R ut², and the last step N costs Qf xN². The least cost left from step t is Pt x²: the cost-to-go. At the end, PN = Qf. Then step back.

Say it aloud

K-t equals A B P-t-plus-one over R plus B squared P-t-plus-one. P-t equals Q plus A squared P-t-plus-one, minus A B P-t-plus-one K-t.

Kt
K-t the best gain at step t: push ut = −Ktxt.
A, B
A, B the model: next state = A times state plus B times push.
Pt+1
P-t-plus-one the cost-to-go weight one step later, already known.
R
R the cost of a push, per unit squared.
Pt
P-t the new cost-to-go weight at step t.
Q
Q the cost of the error, per unit squared, at each step.
In plain words

Start at the end, where P is Q-f. For one step back, pick the gain K-t that balances the push cost R against the cost-to-go P-t-plus-one of where you land. Then compute P-t. Repeat until step 0.

With numbers

With made-up numbers: A = B = Q = R = Qf = 1. From P = 1: K = 1/(1 + 1) = 0.5 and P = 1 + 1 − 0.5 = 1.5. Next: K = 1.5/2.5 = 0.6 and P = 2.5 − 0.9 = 1.6. Then K = 0.615, P = 1.615. It settles at P = 1.618 and K = 0.618.

Why move only halfway at first, u = −0.5x? From x = 1, landing on 0 costs a push of 1. Halfway costs a push of 0.25 plus a future cost of 0.25. Total 0.5, half the price.

Sweep the cost-to-go backward

Yellow bars are the cost-to-go Pt, purple bars the gain Kt, for 10 steps. Press Step back from the end. Then change R.

1.00

Illustrative toy. A = B = Q = Qf = 1, horizon N = 10, scalar state.

Run it long enough and P stops changing. At that fixed point, P solves the discrete algebraic Riccati equation. Here it is the golden ratio, 1.618. The infinite-horizon LQR gain is the limit of this loop. With matrices, the same two lines read K = (R + BTPB)−1BTPA and P = Q + ATPA − ATPBK.

Failure. Sweeping forward from step 0.

Symptom: gains that do not match any solver. Measure: compare the converged K with scipy.linalg.solve_discrete_are. Fix: start from PN = Qf and go backward; each step needs the cost of the future.

Why does finite-horizon LQR compute its gains backward in time?

Chapter 9

Linearize: Use It on a Nonlinear Robot

Replace a curve with its tangent near the operating point, and measure where that stops being true

LQR needs A and B. Real robots are not linear. A pendulum held upright feels a gravity torque that grows like the sine of its tilt, not like the tilt.

The fix is linearization. Pick an operating point, a state and input where the system rests. Near it, replace the dynamics with their slopes. A is the slope with respect to the state, and B the slope with respect to the input. These slopes are the Jacobians.

For a pendulum of length ℓ balanced upright, call the tilt θ, the angular acceleration θ̈ and the gravity g. Call the motor torque per unit inertia u.

Say it aloud

Theta-double-dot equals g over l times sine theta, plus u, which is about g over l times theta, plus u.

θ̈
theta-double-dot the angular acceleration, in rad/s².
g/ℓ
g over l gravity divided by length: 9.81 per s² for a 1 m pendulum.
sin θ
sine theta the true shape of the gravity torque. It curves away from θ as the tilt grows.
u
u the motor's push, in rad/s².
≈
is about true near the operating point, θ = 0.
θ
theta the tilt from upright, in radians.
In plain words

Near upright, sine theta is almost theta. Swap one for the other and the pendulum is linear: A = [[0, 1], [g/ℓ, 0]] and B = [0; 1]. Now LQR applies.

With numbers

With g/ℓ = 9.81: at θ = 0.2 rad, the true acceleration is 9.81 × 0.199 = 1.95 and the linear one 1.96, 0.7% high. At θ = 1 rad, the true one is 8.25 and the linear one 9.81, 19% high.

Let the pendulum fall, then check the model

Set the starting tilt and press Drop. Teal is the real pendulum, dotted grey its start. The pink dashed ghost is what the linear model predicts. Compare them after 0.4 s.

20°

Illustrative toy. A 1 m pendulum with no motor, released at rest from the tilt you set, simulated for 0.4 s.

The lecture's 2-D drone works the same way. At hover, its sine and cosine terms flatten: sideways acceleration grows with tilt, and vertical acceleration grows with extra thrust. LQR on that linear model holds a hover well, as long as the drone does not tilt far. For big moves, you linearize again at each step along a path: that is iLQR and DDP, in Lecture 13.

Failure. LQR used far from its operating point.

Symptom: it holds small nudges and loses large ones. Measure: compare the model's one-step prediction with the real next state, at several tilts. Fix: re-linearize along the path, or use a nonlinear method.

The honest limits

You design LQR on a pendulum linearized at upright. Where should you trust it least?

Chapter 10

The Field Guide

Keep the terms, the numbers, the checks and the core code on one page

Write the model as ẋ = Ax + Bu. Close the loop with a law that reads the state. PID adds a spring, a brake and a memory. Prove stability with an energy, or with the eigenvalues of A − BK. For a quadratic cost, LQR gives the optimal gain from the Riccati equation, and the discrete version runs backward by hand.

Terms and numbers

TermWhat it isNumber from this page
State-space modelẋ = Ax + Bup = 2, v = 0.5, u = −1 give ẋ = [0.5; −1]
P controlu = −kx; error decays like e−ktk = 0.8 halves the error every 0.87 s
Digital gain limitDiverges past k × Δt = 2Δt = 0.1 s: k = 20
PIDSpring, brake, memoryOne step gives u = +0.02
Steady offsetPD in a constant push: d / Kp0.6 / 4 = 0.15 m
Lyapunov energyV̇ = −cv² ≤ 0c = 0.6, v = 0.5: −0.15 per s
Eigenvalue testReal parts < 0; discrete: magnitudes < 1Kp = 1, Kd = 2: λ = −1 twice
LQR gainK = R−1BTPCart, Q = diag(1, 0), R = 1: K = [1, 1.414]
Riccati recursionBackward from PN = QfP: 1, 1.5, 1.6 … 1.618
Linearizationsin θ ≈ θ near upright0.7% off at 0.2 rad, 19% at 1 rad

Checklist

  1. Put velocity in the state of anything with mass.
  2. Check k × Δt, or the discrete eigenvalue magnitudes, before you raise a gain.
  3. Compute eigvals(A - B @ K) for every gain you ship.
  4. Add the I term, with a clamp, when a constant push leaves an offset.
  5. Add feedforward when you track a moving path.
  6. Start LQR with Q = I and R = I, then scale by the errors and pushes you can accept.
  7. Check that the first push stays under the motor limit.

The core as code

pythonimport numpy as np
from scipy.linalg import solve_continuous_are

A = np.array([[0., 1.], [0., 0.]])      # cart: state [position, velocity], shape (2, 2)
B = np.array([[0.], [1.]])             # push enters the velocity, shape (2, 1)
Q = np.diag([1., 0.]); R = np.array([[1.]])

P = solve_continuous_are(A, B, Q, R)          # cost-to-go matrix, (2, 2)
K = np.linalg.solve(R, B.T @ P)              # K = R^-1 B^T P  -> [[1.0, 1.414]]
assert (np.linalg.eigvals(A - B @ K).real < 0).all()   # Hurwitz: stable

def lqr(x):                                  # x: (2,) state -> u: (1,) push
    return -K @ x

def pid_step(e, e_dot, total, Kp, Kd, Ki, dt):
    total += e * dt                            # running total of the error
    return -Kp * e - Kd * e_dot - Ki * total, total

Where it sits

The lectures before this one learned a policy from reward with no model. This one designs the policy from a known model. Lecture 13 adds horizons, constraints and nonlinearity: MPC, discrete LQR derived step by step, SQP and iLQR. Model-based RL then learns the model these methods need.

Keep going

The takeaway. Read the state, push back, and prove it comes home. For a linear model and a quadratic cost, the best rule is one matrix: u = −Kx.
You have a linear model and a quadratic cost. What form does the optimal controller take?

Now press Present or Teach and rebuild the lecture on a blank page. Cover the model, PID, stability, the eigenvalue test, the LQR cost and one Riccati step. Then go back to the hero and say which chapter explains each controller's ending.

Credit and source

This lesson re-teaches Lecture 12 of CMU 16-831, Introduction to Robot Learning (Spring 2024), taught by Guanya Shi. The course site is 16-831-s24.github.io, with slides on the lectures page. The explanations, toys and devices here are our own.

CMU 16-831 Lecture 12: Model-Based Control Basics
The course site · Lectures and slides · Next: Optimal Control and Planning I · Back to Gleams