The pendulum stands on end, balanced by the controller of the earlier chapters. Someone taps the weight. The solver last ran a few milliseconds ago and will not run again for most of a stage, and its plan for the next two seconds says “apply no torque, nothing will happen”. Near the top, an error in the rod’s position grows about eighty-fold every second. What should the motor do in the meantime, and what should the next solve make of the surprise?
The plan is a policy
The solver returns more than a list of torques. For every stage k, solver.policy() holds three things: the state the plan predicts at the start of the stage, x[k], the command, u[k], and a feedback gain, K[k]. The gain comes from the backward pass. It answers the question “if the system is a little off its predicted state at this stage, how should the command change?”
For the balanced pendulum the plan’s torque is zero and its gain is −3.03 N m per radian and −0.57 N m per radian per second. Suppose the rod is 0.02 rad past upright and moving away at 0.5 rad/s. The corrected torque is the plan’s zero, plus −3.03 × 0.02, plus −0.57 × 0.5, which comes to −0.34 N m. That is almost everything the motor has, pushing back.
The correction is one multiplication, so it can run far more often than the solver does. In this chapter’s example the solver runs once per 20 ms stage, and an inner loop runs every millisecond, a tick. The example’s loop.h holds both.
const auto stage = plan.at(tick); // the stage in force at this tick
if ((tick - plan.origin) % ticks_per_stage == 0) predicted = stage.x;
planned = stage.u;
torque = planned;
if (feedback) torque = plan.feedback(stage.index, x, predicted); // u + K * (x - predicted)
torque = NMPC::clamp(torque, lower, upper);plan.at(tick) finds the stage in force. planned keeps the plan’s own torque, which the next excerpt needs. plan.feedback returns u + K × (x − predicted), and NMPC::clamp keeps the result within the motor’s limits. The subtraction uses the problem’s own difference, so it is also correct for states that hold a rotation.
The gain acts about a point that moves. stage.x is the plan’s prediction for the start of the stage. Twelve ticks into the stage the plan expects the rod to have moved on, and comparing the measurement with the stage’s starting state would report an error that is not there. The example therefore carries the prediction forward with the model at every tick, beside the simulated pendulum.
x = pendulum.substep(x, torque(0), tick_s()); // the pendulum itself
predicted = pendulum.substep(predicted, planned(0), tick_s()); // the plan's own predictionTap the pendulum
The figure runs that loop in your browser, in real time: the simulated pendulum, a solve every 20 ms and the inner loop every millisecond, compiled from loop.h. The rod starts inverted and at rest. A tap is a sudden change of its rate, and you deliver it by nudging the weight. The inner loop can run with or without the gain, and each solve can start from either of two states. That gives four loops to compare.
// Once per stage:
const Pendulum::State start = predicted;
solver.solve(pendulum, start, options);
// Every millisecond:
const auto stage = plan.at(tick);
Pendulum::Control torque = plan.feedback(stage.index, x, predicted);
torque = NMPC::clamp(torque, lower, upper);
// When you nudge the weight:
x(1) += tap; // rad/s, positive counter-clockwise// Once per stage:
const Pendulum::State start = predicted;
solver.solve(pendulum, start, options);
// Every millisecond:
const auto stage = plan.at(tick);
Pendulum::Control torque = plan.feedback(stage.index, x, predicted);
torque = NMPC::clamp(torque, lower, upper);
// When you nudge the weight:
x(1) += tap; // rad/s, positive counter-clockwise
Try it
- Click the weight. The opening setting is the plan with its stored gain, each solve starting from the plan’s own prediction, and a click is a tap of 1.0 rad/s. The motor answers within a millisecond, at its limit. The rod gets 0.081 rad from upright and is at rest again 0.72 s after the tap. The green plan never moves: as far as the solver is concerned, nothing happened.
- Switch Between solves to Plan’s torque only and click the weight again. Now nothing responds to the tap at all. The plan says zero torque, the motor applies zero torque, and the rod falls. It stays down, because the plan still shows it standing.
- Leave the rod hanging and switch Each solve starts from to Measured state. This is the loop of the quickstart: every solve sees the real pendulum, and within a few seconds it has swung the rod back up. Once the rod is still, click it. It falls anyway, swings right round, and is brought back up about 2.8 s after the tap.
- Keep the measured start, turn the stored gain back on and click again. The rod falls just the same.
- Return to the opening setting. Flick the weight gently, then harder, and read the size of each tap under the figure. Taps of up to 1.6 rad/s are caught: at 1.5 rad/s the rod gets 0.24 rad from upright. A faster tap is not: the rod falls and is left swinging about the bottom, the motor at its limit against a plan that still shows the rod standing. Stand the rod up again starts afresh.
Step 3 needs explaining, because a solve that starts from the measurement sounds like the best-informed one. Each solve begins by rolling out the old plan’s torques from its starting state. The old plan says zero torque. From the tapped state, zero torque for two seconds is a fall to the bottom, and that fall is what the solver then tries to improve. One iteration improves a plan a little, as the last chapter showed. A little better than a fall is still a fall, so the plan in force becomes “fall, then swing up again”, and its gain belongs to that motion.
Whether one iteration turns that fall into a catch depends on the size of the tap, and not in any orderly way. With the gain off and the measured start, a tap of 1.5 rad/s happens to be caught, 0.33 rad from upright, while taps of 1.0 and 2.0 rad/s are not. A loop that catches some taps by accident is not one to rely on.
When each solve starts from the plan’s own prediction, the plan stays what it was: stand still. The tap is then a small departure from a good plan, which is exactly what the gain is for. Step 2 shows the other half of the bargain. A plan that does not look at the pendulum relies entirely on the inner loop to keep the pendulum near the plan.
The gain cannot do everything either. At the top, the motor can stop the rod only if it is moving slower than about 1.6 rad/s. A faster rod gains more energy from falling than the motor can take out before it has left the region where the motor can hold it. No controller with this motor catches a tap of 2.0 rad/s. The right response then is to accept that the plan no longer describes the pendulum, reset the solver from the measured state, and swing up again.
policy.cpp runs the same loop without a browser. It taps the rod half a second in, by an amount you give on the command line, and prints how far the rod got and when it was at rest again. These are the four loops with a tap of 1.0 rad/s.
tap 1.0 rad/s, plan's torque only, each solve from the measured state, every 1 stage(s):
furthest from inverted 4.364 rad; still again 2.81 s after the tap
tap 1.0 rad/s, plan's torque only, each solve from the predicted state, every 1 stage(s):
furthest from inverted 5.735 rad; not back at rest by the end of the run
tap 1.0 rad/s, plan with feedback, each solve from the measured state, every 1 stage(s):
furthest from inverted 4.366 rad; still again 2.80 s after the tap
tap 1.0 rad/s, plan with feedback, each solve from the predicted state, every 1 stage(s):
furthest from inverted 0.081 rad; still again 0.72 s after the tap
Since the inner loop does the catching, the solver can be slow. Run ./policy 1.0 feedback predicted 5 to solve only every fifth stage, 100 ms apart. The rod again gets 0.081 rad from upright.
Which state should a solve start from?
The experiment compared two answers. A real controller has a third consideration: a solve takes time. If the rod is moving at 6 rad/s, as it is at the bottom of the swing-up, it turns 0.06 rad during a solve that takes 10 ms. A plan computed from where the rod was when the solve began is a plan for a state that no longer exists when it comes into force.
So the general rule is to solve from the state expected at the moment the plan will take effect. How you form that expectation is a design choice.
| Start each solve from | Good when | Weakness |
|---|---|---|
| The latest estimate, predicted forward to the handoff under the policy in force | The system does not run away from its plan within the horizon. The plan then follows the real system closely. | On a system as unstable as the inverted pendulum, a disturbance makes the old plan’s rollout a poor starting point, as in step 3. |
| The plan’s own prediction for the handoff | An inner loop keeps the system close to the plan. Disturbances are left to the inner loop. | The plan cannot see an error the inner loop fails to remove. Watch the distance from the plan, and reset the solver from the estimate when it grows too large. |
In both cases the prediction should include the inner loop’s feedback, because the inner loop will be acting during that time. The example makes the second choice in one line.
if (tick > 0) solver.advance(pendulum, period);
const Pendulum::State start = from_measured ? x : predicted;
if (!solver.solve(pendulum, start, options).usable()) return false;
plan = solver.policy(); // a copy of every stage's state, torque and gain
plan.origin = tick;
plan.ticks_per_stage = ticks_per_stage;Hand each plan over at a known tick
solver.policy() refers to memory the solver will overwrite during its next solve. The inner loop needs a copy that stays still. The three lines after solve above make one: the whole policy is copied into storage the application owns, and two fields the solver never touches are filled in. origin is the tick at which stage 0 begins. ticks_per_stage is the number of inner-loop ticks in a stage. With an origin of 500 and 20 ticks per stage, plan.at(tick) returns stage 0 for ticks 500 to 519 and stage 1 from tick 520.
When the solver and the inner loop run as separate tasks, three more rules apply.
- Decide the handoff tick before the solve starts, and solve for the state expected at that tick. Stamp the copy with that tick as its
origin, and switch plans exactly then. - Switch between two complete copies. The inner loop must never read a policy that is half written.
- If a solve finishes after its handoff tick, discard it and keep the plan in force. Once a plan runs out,
at(tick)keeps returning its last stage. Your application decides how long that is acceptable.
Follow a moving reference
The pendulum’s target is one fixed angle. Many controllers follow a target that moves: a path, a schedule, a trajectory planned elsewhere. The cost of stage k then compares the predicted state with the reference at that stage’s time, which is what the stage index passed to stage_residual is for.
The library has a small table type for this. It holds rows at a fixed spacing in time and finds the two rows either side of any moment, with the fraction of the way between them.
// One column, a row every 0.25 s: hang, swing out to 0.2 rad, then on to 0.5 rad.
static const double angles[] = {0.0, 0.2, 0.5};
NMPC::PathTable<double, 1> reference;
reference.hold(angles, 3, 0.25); // the table borrows these rows; keep them aliveconst auto span = reference.span(time); // the rows either side of this time
const double angle = span.r0(0) + span.a * (span.r1(0) - span.r0(0));How to blend the two rows is left to you, because it depends on what the columns mean. An angle on a line can be interpolated as above. An attitude stored as a quaternion needs an interpolation that follows the rotation. Before the first row and after the last, the lookup holds the end value.
The table can also hold a window of a longer reference: set rows, first and held to the part in memory and count to the length of the whole. A lookup outside the window holds the nearest row it has and increments misses. Log that counter, so that a window moved too late is not mistaken for a tracking error.
A reference needs a clock. Adding a millisecond to a single-precision total thirty thousand times loses part of each addition to rounding, always in the same direction. NMPC::Clock keeps what each addition rounds off and puts it back.
// A single-precision clock that keeps what each addition rounds off.
NMPC::Clock<float> clock;
float plain = 0.0f;
clock.reset();
for (int tick = 0; tick < 30000; tick++) { // 30 s of 1 ms ticks
clock.advance(0.001f);
plain += 0.001f;
}t 0.000 s: 0% of the way from 0.0 to 0.2 rad -> 0.000 rad
t 0.125 s: 50% of the way from 0.0 to 0.2 rad -> 0.100 rad
t 0.375 s: 50% of the way from 0.2 to 0.5 rad -> 0.350 rad
t 0.500 s: 100% of the way from 0.2 to 0.5 rad -> 0.500 rad
t 0.800 s: 100% of the way from 0.2 to 0.5 rad -> 0.500 rad
after 30000 ticks of 1 ms: compensated 30.0000 s, plain sum 29.9951 s
The plain sum is 5 ms short after 30 s, a quarter of a stage for this controller. PathTable, Clock and the inner-loop helpers of the next chapter are marked experimental in this revision of the library, so their interfaces may change before version 2.0 is final.
Check your understanding
With the stored gain and the measured start, the rod still fell. Why did the gain not catch it?
The gain corrects departures from the plan in force, and within one stage the plan in force had become a fall. A gain about a falling motion does nothing to prevent the fall.
During the swing-up, most stages have a torque at the motor’s limit. What does the inner loop’s feedback do in those stages?
Nothing. A command held at a limit has no gain, so feedback returns the plan’s torque unchanged. The swing-up is flown open-loop between solves, which is where the next chapter starts.
A solve takes 8 ms and the inner loop ticks every millisecond. At which tick should the new plan’s origin be set?
At a tick you choose before the solve starts and can be sure of meeting, for example the start of the next stage. The solve must then start from the state expected at that tick. Setting the origin to “whenever the solve happens to finish” makes the plan’s first stage describe a moment that has already passed.
Reference
| Name | What it is |
|---|---|
NMPC::Policy<Problem> | A plan as a value you can copy: x[k], u[k], K[k], and the application’s origin and ticks_per_stage. |
at(tick) | The stage in force at a tick: its index, x, u and K. Holds the last stage once the plan has run out. |
feedback(k, state, planned) | u[k] + K[k] × difference(state, planned), before any limit. feedback(k, state) uses x[k] as the planned state, which is right only at the start of the stage. |
NMPC::clamp(u, lower, upper) | Each command within its limits. |
NMPC::PathTable<T, Columns> | A reference as rows at a fixed spacing. hold gives it the rows, and span(t) returns the rows either side of a time and the fraction between them. |
NMPC::Clock<T> | A running time that does not drift in single precision: reset, advance(step), value. |
Policy.h · Reference.h · The README’s rules for the handoff · Experimental interfaces