SFWA NMPC · Chapter 1 of 6

SFWA NMPC overview

A half-metre rod with a 0.2 kg weight on its end hangs from a motor shaft. Holding the rod level against gravity takes 0.98 N m of torque. The motor can supply 0.35 N m, about a third of that. Pushing steadily in one direction lifts the weight 21° from hanging and no further. How can this motor stand the rod on end?

It has to swing it. A push to one side, a pull back through the bottom as the weight returns, then a push again: each pass adds a little energy until the weight can climb to the top. The awkward part is that the first useful move takes the rod away from where it should end up. A controller that looks only at the present error will not make that move. A controller that tries out the next two seconds in a model of the pendulum will.

SFWA NMPC is a C++17 library for the second kind of controller. NMPC stands for nonlinear model predictive control: “model predictive” because the controller plans with a model of the system, and “nonlinear” because that model may be any function you can write and differentiate, such as the sine in a pendulum’s equation of motion.

Plan, act, plan again

A plan is a list of commands for the near future. Here it is one motor torque for each of the next 100 stages of 20 ms, which makes a plan two seconds long. The controller runs the plan through the model to predict the motion it would cause, and gives that motion a cost: a number that grows with the rod’s distance from upright, with its speed and with the torque used. Then it adjusts the torques to make the cost smaller, without ever asking for more than the motor has.

Only the first torque of the plan reaches the motor. Twenty milliseconds later the controller measures the pendulum again, drops the stage that has passed, and improves what is left of the plan from the new measurement. Planning never finishes. It moves forward with the clock, which is why the method is also called receding-horizon control.

The figure replays a simulated swing-up controlled this way. The simulation uses the same equations as the controller’s model, so here the model is exact. The last chapter takes that advantage away.

The dark rod is the simulated pendulum, and the dark arrow about the shaft shows the direction and size of the motor’s torque. Green shows the plan the controller holds at this instant: the path it predicts for the weight, drawn winding outward as time runs on, and the rod’s predicted position every half second. In the plots the dark lines are the motion and torque so far, the faint lines are what happened afterwards, and the green lines are the plan for the next two seconds. Dashed lines mark the motor’s limit of ±0.35 N m and the inverted position.

Try it

  1. Leave the time at 0.10 s and follow the green path from the weight. The plan swings right, back through the bottom to the left, then right again and up. That whole manoeuvre is already in the plan a tenth of a second after the start.
  2. Press Play. The rod swings 0.52 rad to the right, then −1.18 rad to the left, and is held inverted from 3.28 s. Watch how closely the faint line of what happened follows each green prediction.
  3. Stop at about 1.5 s, as the rod passes the bottom at full speed. The torque plan is at the motor’s limit for more than a second ahead. The plan has no torque to spare, a fact that matters in the last chapter.
  4. Switch to Clipped linear feedback and play again.

The program behind the figure is short. Everything the pendulum needs is in the four calls of its loop.

swingup.cpp

for (int stage = 0; stage < 500; stage++) {
    if (stage > 0) solver.advance(pendulum, 1);  // drop the stage that has just passed
    const NMPC::Result<double> result = solver.solve(pendulum, x, options);
    if (!result.usable()) return 1;

    const Pendulum::Control torque = solver.policy().u[0];  // the plan's first command
    if (stage % 25 == 0) {
        std::printf("t %5.2f s  angle %6.3f rad  rate %6.3f rad/s  torque %6.3f N m  cost %8.3f\n",
                    stage * pendulum.dt, x(0), x(1), torque(0), result.cost_after);
    }
    x = pendulum.step(0, x, torque);  // the simulated pendulum moves on by one stage
}

advance drops the stage that has just passed. solve improves the rest of the plan from the measured state x. policy().u[0] is the plan’s first torque. The next chapter builds and runs this program.

Where linear feedback stops

The usual way to hold an inverted pendulum is linear feedback: a torque proportional to the angle error plus a torque proportional to the rate. A linear quadratic regulator (LQR) chooses the two proportions that are best for a given cost when the equations are linear, which the pendulum’s nearly are close to upright. The comparison in the figure uses the LQR gains for the same model, cost and two-second horizon, worked out where the rod is inverted, and clips the result to what the motor can deliver.

Near the top this law works well. From the bottom it asks for 9.4 N m, 27 times the motor’s limit, and goes on asking. The motor pushes one way at full torque, the rod swings out to 0.68 rad and back, and nothing in the law ever reverses the push. The rule “more error, more torque” has no way to say “go the other way first”.

The classical fix is a second, hand-written law that pumps energy into the swing, with a switch to linear feedback near the top. The predictive controller needs no special case. Swinging away and coming back is simply the cheapest two seconds it can find.

What you give the library, and what you get back

You describe the control problem as a C++ type. It has four parts, and the problem chapter writes each one for the pendulum.

You supplyFor the pendulum
A modelThe next angle and rate, given the present ones and a torque held for one stage.
Its derivativesHow much the next state changes for a small change in the state or the torque. They are written by hand and checked against the model in a test.
A costAngle error, rate and torque, each scaled by a weight. The cost is half the sum of their squares.
Limits on the commands−0.35 to +0.35 N m at every stage.

Each solve returns the plan as a policy: for every stage, the predicted state, the command and a feedback gain. The gain says how to change the command if the system is a little off its predicted state, so a fast inner loop can keep correcting between solves. The policy chapter shows what that is worth when the pendulum is tapped.

The library is header-only and written for small processors. The memory a solver needs is fixed by the sizes of the problem, the caller owns it, and a solve allocates nothing. There are no exceptions and no virtual calls. Every type is a template on its scalar, so the same problem can be solved in float on a microcontroller and in double on a desk.

Choosing a controller

Predictive control is the heaviest of the common options. Use the lightest one that does the job.

MethodDecides fromGood fit
PIDOne error, its sum over time and its rate of change, now.One quantity with a well-behaved response. It runs at every sensor sample on almost any processor.
LQRThe whole state now, through a fixed gain matrix.Several coupled quantities near one operating point, with commands that stay inside their limits.
Linear MPCA plan through a linear model, with limits.Limits that shape the motion while one set of linear equations still describes the system. The OSQP example shows how to pose it as a quadratic program.
SFWA NMPCA plan through your own nonlinear model, with limits on each command.Dynamics or costs that change across the motion, a model you already have in C++ with derivatives you can write, and a use for the feedback gains.
A larger toolkit, such as acadosA plan through a symbolic model, with general constraints.Constraints on states, a choice of integrators, or a model written in Python from which a solver is generated.

SFWA NMPC enforces lower and upper bounds on each command. A preference about the state, such as “stay near upright”, goes into the cost, where the solver trades it against everything else. It is a price, not a guarantee.

What fits on a microcontroller

The pendulum is a small problem: two states, one command and 100 stages. To show what a larger one costs, the library’s maintainers count instructions on a Cortex-M7 core under the QEMU emulator for a synthetic problem with the dimensions of their multirotor controller: 17 states, five commands and 30 stages. These figures are for single precision, GCC 13.2.1 at -O2 and the library’s patched Eigen 3.2.8. One build keeps the model’s derivatives for every stage in memory. The other works them out again as each stage needs them.

The same problem, with two ways of storing derivatives
MeasurementStoredPer stage
Instructions for the first solve after a reset2.79 million2.75 million
Instructions to shift the plan and iterate once2.69 million2.65 million
Workspace72.5 kB27.6 kB
Solver object3.3 kB3.3 kB
Stack during a solve8.7 kB10.2 kB

On an STM32H735 at 550 MHz the maintainers measured 1.19 to 1.22 processor cycles per counted instruction for whole solves, which puts one solve of this problem near 6 ms. An instruction count is exact for one build and says nothing about another. To choose a solve period, time your own model on your own board with the rest of the application running.

Linux and macOS suit model development, derivative checks and simulation in either precision. The project tests GCC and Clang on Linux, Apple Clang, and the single-precision Cortex-M7 build. The helpers for inner loops and references used in the last two chapters are marked experimental in this revision of the library, so their interfaces may still change.

Check your understanding

The plan covers two seconds. Why does the controller use only its first 20 ms?

Because 20 ms later it has a new measurement and can do better. The rest of the plan is the controller’s reason for choosing the first torque, and its starting point for the next solve. It is never a commitment.

At 0.10 s the motor is pushing the rod to the right, yet the green path ends on the right only after swinging left. What made the controller plan the swing to the left?

The cost of the whole two seconds. With the torque limit in the plan, pushing right forever leaves the rod 21° from hanging, far from upright, for the whole plan. A plan that swings back and through arrives higher and costs less in total, even though it is further from upright for a moment.

Would the linear feedback law do better with larger gains?

No. It already asks for 27 times what the motor can supply, so the motor is at its limit either way. The law fails because of its form: its torque always points toward the target.

Reference

Library README · Embedded memory measurements · Cortex-M7 instruction counts · Supported configurations · Experimental interfaces

swingup.cpp · linear.cpp · pendulum.h · All the guide’s examples