SFWA NMPC · Chapter 4 of 6

How the solver improves a plan

Start with the laziest plan for the hanging pendulum: no torque for two seconds. Running that plan through the model gives its cost, 169.65. The rod just hangs, as far from upright as it can be, for the whole plan. The solver’s job is to change the hundred torques of the plan so that the cost comes down, and to do it in a fixed, small amount of work, because on a controller the next deadline is 20 ms away.

One iteration in four steps

The solver improves a plan by repeating one iteration. An iteration does not search over all possible plans. It looks at how the present plan could be changed a little, and takes one well-chosen step.

  1. Rollout. Clip each planned torque to its limits, run the model stage by stage from the present state, and add up the cost. This gives the motion the plan really produces and the number to beat.
  2. Linearise. Call step_jacobian at every stage of that motion. The Jacobians say how a small change at one stage carries into the next.
  3. Backward pass. Work from the last stage back to the first. At each stage, ask: given what the rest of the plan will cost, how should this torque change? The answer at each stage is a change of torque and a gain, which says how the torque should change further if the state at that stage turns out a little different. Where a torque is already at its limit and wants to go further, the solver holds it there and gives it no gain. The pass also predicts how much the cost should fall if every change is made in full.
  4. Line search. The prediction comes from straight-line approximations, and the pendulum is not a straight line. So the solver tries the changes on the real model: first in full, then half of them, then a quarter. It keeps the first trial that delivers at least 1% of the decrease predicted for it.

The figure shows these steps on the lazy plan, using results recorded from the library. The plan is drawn as a path in the phase plane of the last chapter: angle across, rate up, starting from the dot.

const double alpha = 0.5;  // the share of the backward pass's change to try
int on_limit = 0;
const double cost = solver.forward(pendulum, x, alpha, on_limit);  // 125.203
The phase plane shows plans as paths, all starting at the dark dot. The dashed dark path is the plan before this iteration. Each pale green path is the motion of one trial plan, and the heavy green path is the trial selected with Step length. The torque plot shows the plan before (dashed) and the selected trial (green), between the motor’s limits. In the cost plot, one bar per trial shows what that plan really costs. The dark tick on each bar is the cost the backward pass predicted for it, and the dashed line is the cost of the plan before.

Try it

  1. At iteration 1, select a step length of 1. The backward pass predicted a cost of 100.75 for the full change. The real model gives 206.47, worse than doing nothing: the heavy path flies out of the picture. The approximation was not good that far from the old plan, so the step is refused.
  2. Select 1/2. The cost falls to 125.20, better than predicted, and the step is accepted. The torques now push right, pull left, and push right again. One half-step has found the shape of a swing.
  3. Move to iteration 3. The full step is accepted at once, and 99 of the 100 planned torques are at the motor’s limit. From here on the plan is bang-bang: all it can still adjust is when to reverse.
  4. Step through iterations 4 to 8. The bars shrink toward the dashed line as the predictions and the real costs agree. By iteration 8 the plan costs 90.67 and no trial improves on it by more than a hundredth.

The program that recorded this drives the solver’s steps one at a time. An application never needs to: solve does all of it. The excerpt is here because it is the shortest exact statement of what one iteration is.

iteration.cpp

// 1. Rollout: what the current plan costs from this state.
const NMPC::Result<double> before = solver.solve(pendulum, x, look);
if (!before.usable()) return 1;

// 2. Backward pass: a change to every stage's torque, and the decrease it predicts.
double linear = 0.0, quadratic = 0.0;
int qp_passes = 0;
if (!solver.backward(pendulum, one, linear, quadratic, qp_passes)) return 1;

std::printf("iteration %d: the plan costs %.3f\n", iteration, before.cost_before);
// 3. Line search: try the whole change, then half of it, then a quarter...
bool taken = false;
double alpha = 1.0;
for (int trial = 0; trial < one.max_line_search; trial++, alpha *= 0.5) {
    int on_limit = 0;
    const double predicted = -(alpha * linear + alpha * alpha * quadratic);
    const double cost = solver.forward(pendulum, x, alpha, on_limit);
    const double achieved = before.cost_before - cost;
    const bool accept = !taken && predicted > 0.0 && achieved > one.accept_ratio * predicted;
    std::printf("  step %-6.4g predicted cost %8.3f, actual %8.3f  %s\n", alpha,
                before.cost_before - predicted, cost, accept ? "accepted" : taken ? "" : "refused");
iteration 1: the plan costs 169.652
  step 1      predicted cost  100.753, actual  206.472  refused
  step 0.5    predicted cost  134.905, actual  125.203  accepted
  step 0.25   predicted cost  152.204, actual  145.146  
  step 0.125  predicted cost  160.909, actual  156.862  
  step 0.0625 predicted cost  165.276, actual  163.119  
  solve(): 169.652 -> 125.203, 1 of 100 stages at the torque limit
iteration 2: the plan costs 125.203
  step 1      predicted cost   97.030, actual  161.516  refused
  step 0.5    predicted cost  111.009, actual  112.956  accepted
  step 0.25   predicted cost  118.079, actual  116.392  
  step 0.125  predicted cost  121.634, actual  120.688  
  step 0.0625 predicted cost  123.417, actual  122.937  
  solve(): 125.203 -> 112.956, 2 of 100 stages at the torque limit
iteration 3: the plan costs 112.956
  step 1      predicted cost   94.613, actual   92.770  accepted
  step 0.5    predicted cost  103.425, actual  101.123  
  step 0.25   predicted cost  108.101, actual  105.422  
  step 0.125  predicted cost  110.506, actual  108.632  
  step 0.0625 predicted cost  111.725, actual  110.764  
  solve(): 112.956 -> 92.770, 99 of 100 stages at the torque limit
iteration 4: the plan costs 92.770
  step 1      predicted cost   91.160, actual   97.199  refused
  step 0.5    predicted cost   91.897, actual   93.687  refused
  step 0.25   predicted cost   92.317, actual   92.653  accepted
  step 0.125  predicted cost   92.539, actual   92.536  
  step 0.0625 predicted cost   92.654, actual   92.605  
  solve(): 92.770 -> 92.653, 92 of 100 stages at the torque limit

The search stops at the first acceptable step, not the best one. At iteration 4 a step of 1/8 would have cost slightly less than the 1/4 that was taken. Looking further would cost another run of the model for a gain the next iteration picks up anyway.

Once per stage, from the plan before

Eight iterations found a good plan from nothing. A running controller never starts from nothing. Twenty milliseconds ago it had a good plan, and little has changed since. So each solve begins from the previous plan moved on by one stage, a warm start, and by default makes a single iteration. The library calls this a real-time iteration.

This is the loop from the quickstart. advance performs the shift, and solve begins with a fresh rollout from the newly measured state, so the costs it reports before and after refer to the same starting point.

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
}

In the swing-up of the first chapter the plan was improved 164 times in the 3.28 s before the rod stood still, once per stage, and each solve cost the same fixed amount of work. That steadiness is the point. A controller that must finish within its period cannot use a method that is usually fast.

How far ahead, and how much work?

Two numbers set the size of each solve: the length of the plan and the iterations allowed. It is natural to expect that more of either gives a better controller. The pendulum shows that the first matters more than you might guess, and that the second can hurt.

The length of the plan is the solver’s second template argument, which overrides the Stages of the problem. The budget is a field of the options.

horizon.cpp

// The solver's second argument overrides the problem's own number of stages.
template <int Stages>
double swing_up(int iterations, Trace& trace) {
    using Solver = NMPC::Solver<Pendulum, Stages>;
    static typename Solver::Workspace workspace;
    Solver solver(workspace);
    NMPC::Options<double> options;
    options.max_iterations = iterations;

The figure replays twenty simulated swing-ups, for five plan lengths and four budgets.

using Solver = NMPC::Solver<Pendulum, 100>;  // stages of 20 ms in the plan
NMPC::Options<double> options;
options.max_iterations = 1;
The drawing shows the simulated pendulum where it is after ten seconds of the selected run. The grey path is the weight’s travel, winding outward with time, and the shaded sector is as far as the rod swung to either side. The plot shows the rod’s angle over the first ten seconds, with the inverted position dashed. The table gives, for all twenty runs, the time from which the rod was held inverted and still. The selected run is outlined.

Try it

  1. Select a 1.0 s plan. The rod rocks from side to side and never rises, whatever the budget. One swing of this pendulum takes 1.4 s. A plan shorter than that cannot contain both a swing away from the top and the reward for it, so swinging away always looks like a loss.
  2. Select 1.5 s, the length used by the example that ships with the library. With one iteration per solve the rod is up at 6.36 s. Raise the budget to 2, 5 and 10. The swing-up takes longer each time, and at 10 it never happens.
  3. Select 2.0 s. The rod is up at about 3.3 s with every budget.
  4. Select 3.0 s. The longer plan is no faster, and each of its solves is half as much work again.

The second step is the surprising one. More iterations bring each plan closer to the best plan for its own window of time. But the best 1.5 s, taken alone, is not always a piece of a good swing-up. With one iteration per solve the plan changes less at each stage and carries more of its history forward, and here that happens to help. It is not something to rely on. When the outcome depends on the budget, the plan is too short: lengthen it until the answer stops changing, as it does here at 2 s.

The work of a solve grows in proportion to the number of stages, so the cure has a price. This is the main tuning decision for a predictive controller, and a simulation of this kind is the way to make it.

plan length   iterations per solve:      1       2       5      10
   0.8 s                                  -       -       -       -
   1.0 s                                  -       -       -       -
   1.5 s                             6.36 s  8.16 s 10.38 s       -
   2.0 s                             3.28 s  3.26 s  3.26 s  3.26 s
   3.0 s                             3.66 s  3.58 s  4.80 s  4.40 s

Setting the budgets

NMPC::Options limits a solve in units of work, never in seconds, so a solve does the same arithmetic wherever it runs. The defaults are the smallest useful budgets.

OptionDefaultLimits
max_iterations1Iterations per solve. Give a solve more after a reset, when it starts from a poor plan.
max_line_search5Step lengths tried per iteration: 1, 1/2, 1/4 and so on.
max_regularisation_retries1Extra backward passes when one fails or its step is refused. Each retry damps the proposed changes more strongly.
max_box_iterations32Passes of the method that holds torques at their limits, at each stage of the backward pass.
accept_ratio0.01The share of its predicted decrease a trial must deliver to be accepted.
out_of_time, time_contextnoneAn optional function the solver asks before each backward pass and each trial. When it returns true the solve stops with the best plan so far, and result.out_of_time is set.

The deadline function is for a solve that must publish within its period whatever happens. It is checked between blocks of work, so the rollout, the linearisation and a pass already under way still run to completion. Allow for the longest of those when you choose the deadline.

Reading the result

Every solve returns an NMPC::Result. Check usable() before using the plan, and log the rest while you tune.

StatusWhat happened
IterationLimitThe budget was spent. With one iteration per solve this is the ordinary result.
ConvergedThe backward pass predicted no decrease that the number type can resolve. The plan is as good as this precision can verify.
NoProgressNo trial was accepted. The plan is the old one rolled out from the new state, and it is still usable.
NumericalFailureThe first rollout produced a number that was not finite. The plan is exactly as it was before the call, and usable() is false.
FieldUse
cost_before, cost_afterThe plan’s cost from the new state before the first step, and as returned. Their difference is what this solve bought.
predicted_decreaseWhat the last backward pass expected of a full step. When this is a large share of cost_before, the plan and the state have parted company. That is the sign to reset the plan and give the next solve several iterations.
stages_on_boundStages of the returned plan with a command at a limit. A high count can be right, as in the swing-up.
iterations, accepted_steps, backward_passes, line_search_trials, box_iterationsThe work done.
invalid_predictionsBackward passes that predicted an increase and were repeated. A count above zero says max_box_iterations is too small for the plans the solver starts from.
out_of_timeThe deadline function stopped the solve.

If a solve is not usable, the plan already in force is untouched and can carry on into its next stage. Choose a safe command, call reset with it, and let the next solve start afresh.

Fitting the plan in memory

A solver needs memory in three places, and you provide all three. The workspace holds the plan, a trial plan, the gains and, by default, every stage’s Jacobians. The solver object holds the scales of the last solve. The stack holds the matrices of one stage while a solve runs.

If the workspace is too large, the solver can make each stage’s Jacobians as the backward pass reaches that stage and not keep them. The plans it returns are the same. The price is more stack, and making the Jacobians again when a backward pass is repeated.

memory.cpp

using Solver = NMPC::Solver<Pendulum>;  // keeps every stage's Jacobians for the iteration
using CompactSolver = NMPC::Solver<Pendulum, Pendulum::Stages, NMPC::Jacobians::PerStage>;
                      stored Jacobians   made per stage
workspace                  15256 bytes      10464 bytes
solver object                168 bytes        168 bytes

For the pendulum the saving is one hundred stages of a 2 × 2 and a 2 × 1 matrix of doubles, about 4.8 kB of the 15.3 kB workspace. The overview gives the same comparison for a problem with 17 states, where the saving is 45 kB.

Check your understanding

The full step at iteration 1 made the plan worse. Was the backward pass wrong?

It was right about the direction and wrong about the distance. Its prediction is built from derivatives at the old plan, and it holds only near that plan. The line search exists to find out how near: half the step was a large improvement.

Why does a torque held at its limit get no gain?

A gain says how to change the torque if the state is off the plan. A torque at its limit that wants to go further has nowhere to go, so the honest answer is no change. An inner loop that uses the gains can therefore do nothing during those stages, which is most of the swing-up.

Your controller works with one iteration per solve and fails with five. What should you try first?

A longer plan. A result that depends on the budget means the plan cannot see far enough for its best window to be part of a good motion.

Reference

NameWhat it is
NMPC::Solver<Problem, N, Storage>A solver for a plan of N stages (the problem’s Stages by default), keeping Jacobians NMPC::Jacobians::Stored or making them PerStage.
solve(problem, x, options)Rollout from x, then up to max_iterations iterations.
rollout, linearise, backward, forwardThe steps of an iteration, public so that each can be timed. They use the bounds and scales of the last solve.
advance(problem, n), advance_fraction(f)Move the plan on by whole stages, or blend each command toward the next when the solve period is a fraction of a stage.
workspace()Read access to the solver’s memory, including the last trial plan.

Solver.h · BoxQP.h · Options.h · Result.h · Workspace.h

iteration.cpp · horizon.cpp · memory.cpp