SFWA NMPC · Chapter 2 of 6

Build and run your first controller

The overview showed a controller swinging a pendulum up with a motor too weak to lift it. In this chapter you build the library, run that controller on your own machine, and match each line it prints to the motion it describes. It takes about ten minutes, most of them compiling.

1. Get the source and run its own example

These commands fetch the revision this guide was written against, 2.0.0-dev, and build the swing-up example that comes with the library. The first build downloads Eigen 3.2.8, the matrix library NMPC uses, and applies the library’s patches to it.

git clone https://github.com/sfwa/nmpc.git
cd nmpc
git checkout --detach 9f5477db84ffd4de198a8011cd392d1efb3e10a1
cmake -S . -B build-nmpc -G "Unix Makefiles" \
  -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PWD/install" \
  -DNMPC_BUILD_TESTS=OFF -DNMPC_BUILD_BENCHMARKS=OFF
cmake --build build-nmpc --target pendulum --parallel 2
./build-nmpc/examples/pendulum/pendulum

The program prints a line every half second of simulated time and ends with this one.

after 10 s: 0.0000 rad from inverted, rate -0.0000 rad/s, 0 unusable solves

It also exits with status zero only if the rod ended inverted and at rest, so a build script can use it as a check. If you see that line, the compiler, Eigen and the solver work together on your machine.

2. Install the headers

NMPC is header-only: there is no library file to link, and the solver is compiled into each program that uses it. Installing copies the headers, the patched Eigen and a CMake package into the install directory inside the checkout.

cmake --build build-nmpc --parallel 2
cmake --install build-nmpc

3. Build this guide’s examples

Download the examples and save the ZIP in the nmpc directory. It holds one header that describes the pendulum, a short program for each chapter, and a CMake file that builds them all. Run these commands from the same directory as before.

unzip nmpc-examples.zip
cmake -S nmpc-examples -B build-examples -G "Unix Makefiles" \
  -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$PWD/install"
cmake --build build-examples --parallel 2
./build-examples/swingup

The CMake file finds the installed package and links each program to the target nmpc::nmpc, which supplies the include paths and the C++17 requirement. Your own project needs the same three lines.

find_package(nmpc REQUIRED CONFIG)
add_executable(controller controller.cpp)
target_link_libraries(controller PRIVATE nmpc::nmpc)

4. Read what it printed

swingup should print the lines below. The last digits can differ with the compiler and processor.

t  0.00 s  angle  0.050 rad  rate  0.000 rad/s  torque  0.175 N m  cost  125.203
t  0.50 s  angle  0.510 rad  rate  0.601 rad/s  torque -0.350 N m  cost   71.666
t  1.00 s  angle -0.755 rad  rate -3.423 rad/s  torque -0.350 N m  cost   49.009
t  1.50 s  angle -0.151 rad  rate  6.061 rad/s  torque  0.350 N m  cost   11.386
t  2.00 s  angle  2.255 rad  rate  2.257 rad/s  torque  0.350 N m  cost    1.084
t  2.50 s  angle  2.763 rad  rate  0.478 rad/s  torque  0.350 N m  cost    0.200
t  3.00 s  angle  3.063 rad  rate  0.472 rad/s  torque -0.022 N m  cost    0.004
t  3.50 s  angle  3.141 rad  rate  0.015 rad/s  torque -0.007 N m  cost    0.000
t  4.00 s  angle  3.142 rad  rate -0.001 rad/s  torque  0.000 N m  cost    0.000
t  4.50 s  angle  3.142 rad  rate -0.000 rad/s  torque  0.000 N m  cost    0.000
t  5.00 s  angle  3.142 rad  rate  0.000 rad/s  torque  0.000 N m  cost    0.000
t  5.50 s  angle  3.142 rad  rate  0.000 rad/s  torque -0.000 N m  cost    0.000
t  6.00 s  angle  3.142 rad  rate -0.000 rad/s  torque -0.000 N m  cost    0.000
t  6.50 s  angle  3.142 rad  rate -0.000 rad/s  torque  0.000 N m  cost    0.000
t  7.00 s  angle  3.142 rad  rate  0.000 rad/s  torque  0.000 N m  cost    0.000
t  7.50 s  angle  3.142 rad  rate  0.000 rad/s  torque -0.000 N m  cost    0.000
t  8.00 s  angle  3.142 rad  rate -0.000 rad/s  torque -0.000 N m  cost    0.000
t  8.50 s  angle  3.142 rad  rate -0.000 rad/s  torque  0.000 N m  cost    0.000
t  9.00 s  angle  3.142 rad  rate -0.000 rad/s  torque  0.000 N m  cost    0.000
t  9.50 s  angle  3.142 rad  rate  0.000 rad/s  torque  0.000 N m  cost    0.000
after 10 s: 0.0000 rad from inverted, rate 0.0000 rad/s

Each line is one instant of a simulated swing-up. The angle is measured in radians from hanging straight down, so 3.142 is inverted. The rate is how fast the angle is changing. The torque is what the controller has just decided to apply for the next 20 ms. The cost is the controller’s own score for its two-second plan after this solve: it falls toward zero as the plan comes to end upright and at rest.

The figure replays the same run. Every dot on the angle plot is one printed line.

The dark rod is the simulated pendulum at the selected line of output, and the dark arrow about the shaft is the motor’s torque. Green is the plan made at that instant: the weight’s predicted path, winding outward with time, and the rod’s predicted position every half second. In the plots, dots mark the printed lines, dark lines show the run up to the selected line, faint lines the rest of it, and green the plan. Dashed lines mark the motor’s limit and the inverted position.

Try it

  1. Step the slider back to 0.00 s. The program prints a torque of 0.175 N m, half the limit: the controller has just made its first, cautious improvement to a plan that began as “no torque”.
  2. Step to 0.50 s. The rod is 0.52 rad to the right and still rising, yet the printed torque is −0.350 N m. The controller is already pulling it back for the swing to the left.
  3. Step to 1.50 s. The rod is passing the bottom at 6 rad/s under full torque, and the green plan carries it over the top.
  4. Step on to 3.50 s and beyond. The cost prints as 0.000 and the torque is a few thousandths of a newton metre: just enough to hold the rod where it is.

5. Read the program

Open nmpc-examples/swingup.cpp. Apart from printing, it has two parts. The first sets up the solver.

swingup.cpp

using Solver = NMPC::Solver<Pendulum>;
static Solver::Workspace workspace;  // holds the plan; a solve allocates nothing
Solver solver(workspace);
Pendulum pendulum;
NMPC::Options<double> options;  // the defaults allow one iteration per solve
if (argc > 1 && argv[1][0] != '-') options.max_iterations = std::atoi(argv[1]);

Pendulum::State x(0.05, 0.0);                // nearly hanging, at rest
solver.reset(x, Pendulum::Control::Zero());  // the first plan applies no torque

Pendulum comes from pendulum.h. It is the control problem: the model, the cost and the torque limit, which the next chapter writes out. The solver is a template on that type, so its matrices have fixed sizes known to the compiler.

The Workspace holds the plan and everything the solver needs while it works. Your program owns it. Declaring it static keeps it off the stack, which matters on a microcontroller. reset fills in a first plan, the same torque at every stage, here zero.

The second part is the control loop. It is shown here without the lines that record the run for the figures.

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
}

Each pass through the loop is one stage, 20 ms of the pendulum’s time.

  1. advance(pendulum, 1) moves the plan on by the stage that has just passed. The plan’s second torque becomes its first, and a copy of the last one fills the gap at the far end.
  2. solve(pendulum, x, options) improves the plan, starting from the pendulum’s state now. With the default options it makes one improving step, which the solver chapter takes apart.
  3. usable() says whether the plan can be trusted. It is false only if the model returned a number that was not finite.
  4. policy().u[0] is the first torque of the improved plan.
  5. pendulum.step stands in for the real pendulum. On hardware this line becomes “send the torque to the motor, wait for the next tick, read the sensors”.

Why the shipped example takes longer

The example you ran in step 1 held the rod inverted from 6.36 s. This guide’s copy does it from 3.28 s. The guide’s pendulum.h differs from the shipped example in two ways: it works in double where the shipped one uses float, and its plan looks 2 s ahead where the shipped one looks 1.5 s. The second difference accounts for the time. The solver chapter shows what a plan can and cannot see at each length.

If your build looks different

Check your understanding

The program prints a cost of 125.203 at 0.00 s and 0.000 from 3.50 s. What is being scored?

The plan, not the past. At each solve the cost is the controller’s score for the two seconds it has just planned. At the start those two seconds are spent far from upright. Once the rod is inverted and still, the best plan is to stay there, which costs almost nothing.

What would you change in the loop to control a real pendulum?

Only the last line. Replace pendulum.step with code that sends torque to the motor and reads the new angle and rate into x. The model in pendulum.h stays, because the solver still plans with it.

Why is the workspace declared static?

It holds the plan and the solver’s working memory, about 15 kB for this problem. A local variable of that size would sit on the stack, which is small on a microcontroller. Static storage has a fixed place and nothing is allocated while the controller runs.

Reference

NameWhat it is
NMPC::Solver<Problem>The solver for one problem type. Solver::Workspace is its memory, owned by the caller.
reset(x, u)A first plan: the command u at every stage from the state x.
advance(problem, n)Move the plan on by n whole stages.
solve(problem, x, options)Improve the plan from the state x. Returns an NMPC::Result.
policy()The plan: x[k], u[k] and the gain K[k] for every stage.
NMPC::Options<T>How much work a solve may do. The defaults allow one iteration.

Build options and install rules · The library’s own examples · Installed-package checks

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