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.
- 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.
- Linearise. Call
step_jacobianat every stage of that motion. The Jacobians say how a small change at one stage carries into the next. - 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.
- 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.203const 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
Try it
- 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.
- 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.
- 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.
- 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.
// 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.
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.
// 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;using Solver = NMPC::Solver<Pendulum, 100>; // stages of 20 ms in the plan
NMPC::Options<double> options;
options.max_iterations = 1;
Try it
- 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.
- 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.
- Select 2.0 s. The rod is up at about 3.3 s with every budget.
- 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.
| Option | Default | Limits |
|---|---|---|
max_iterations | 1 | Iterations per solve. Give a solve more after a reset, when it starts from a poor plan. |
max_line_search | 5 | Step lengths tried per iteration: 1, 1/2, 1/4 and so on. |
max_regularisation_retries | 1 | Extra backward passes when one fails or its step is refused. Each retry damps the proposed changes more strongly. |
max_box_iterations | 32 | Passes of the method that holds torques at their limits, at each stage of the backward pass. |
accept_ratio | 0.01 | The share of its predicted decrease a trial must deliver to be accepted. |
out_of_time, time_context | none | An 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.
| Status | What happened |
|---|---|
IterationLimit | The budget was spent. With one iteration per solve this is the ordinary result. |
Converged | The backward pass predicted no decrease that the number type can resolve. The plan is as good as this precision can verify. |
NoProgress | No trial was accepted. The plan is the old one rolled out from the new state, and it is still usable. |
NumericalFailure | The first rollout produced a number that was not finite. The plan is exactly as it was before the call, and usable() is false. |
| Field | Use |
|---|---|
cost_before, cost_after | The plan’s cost from the new state before the first step, and as returned. Their difference is what this solve bought. |
predicted_decrease | What 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_bound | Stages 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_iterations | The work done. |
invalid_predictions | Backward 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_time | The 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.
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
| Name | What 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, forward | The 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