Every simulation so far has flattered the controller. The simulated pendulum obeyed exactly the equations the controller planned with. A real rod will not. Its weight will be a few percent off the drawing, its bearing will drag more on a cold day, and a cable will tug at it. This chapter gives the controller a pendulum that differs from its model, watches the swing-up fail, and then closes the loop in a way that survives the difference.
A pendulum that is not the model
track.cpp swings up a simulated pendulum whose weight is a chosen fraction of the weight in the controller’s model. Its direct loop is the one from the quickstart: every 20 ms, solve from the measured state and apply the plan’s first torque. The figure replays it. It opens on a weight 5% lighter than the model’s.
real.tuning.mass = 0.95 * model.tuning.mass; // the weight really on the rod
const double reserve = 0.0; // N m kept back from the plan
model.tuning.torque_limit = motor_limit - reserve;
solver.solve(model, x, options); // where each plan startsreal.tuning.mass = 0.95 * model.tuning.mass; // the weight really on the rod
const double reserve = 0.0; // N m kept back from the plan
model.tuning.torque_limit = motor_limit - reserve;
solver.solve(model, x, options); // where each plan starts
track.cpp.Try it
- Play the opening run from the start. The swing looks like the one you know until 2.4 s. There the rod reaches the top moving at 2.2 rad/s with the motor still pushing it on. It goes over, falls down the far side and swings back. In the 10 s of the run it is never held inverted.
- Set the weight to +5%. Now the rod is heavier than planned for. It rises to 2.2 rad, stops short of the top and falls back.
- Set the weight to 0%. With a perfect model the direct loop is the fastest in this chapter: inverted from 3.27 s.
- Go back to −5% and switch the loop to Plan and track. The rod follows the pale green rod up and stays. The next section explains what changed.
A 5% error is not a large one, and the controller measured the true state at every solve. The trouble is the kind of plan it was flying. The swing-up runs the motor at its limit nearly all the way, and reaches the top with almost no speed to spare. That leaves no margin in two senses.
There is no margin in energy. Lifting a weight that is 5% lighter takes about 0.1 J less. The previous chapter found that the motor can stop the rod at the top only below about 1.6 rad/s, which is 0.06 J of motion. The surplus alone is more than the motor can absorb once the rod has arrived.
And there is no margin in torque. Dealing with the surplus early would mean easing off on the way up. But each solve only improves the plan a little, and the plan it starts from is at the limit for a second ahead, a pattern that was right for the heavier weight. By the time the measurements have pulled the plan far enough, the rod is at the top and moving too fast.
Leave room to correct, and follow the plan
The remedy has two parts, and the library has the pieces for both. First, do not let the plan use the whole motor. Second, add an inner loop whose only job is to keep the real system on the plan, and give it the torque that was held back.
Holding torque back is a change to the bounds the solver sees. The motor’s limit stays what it is.
const double motor_limit = 0.35; // what the motor can deliver, N m
const double reserve = tracking ? 0.05 : 0.0; // kept back for the inner loop
Pendulum model;
model.substeps = 20;
model.tuning.torque_limit = motor_limit - reserve; // control_bounds gives the plan the restThe plan now starts each solve from its own prediction, as in the previous chapter, so it describes the motion of the model. That motion is one the real pendulum can follow, because the plan asks for at most 0.30 N m and the motor has 0.35.
The inner loop needs a law that turns “the rod is behind the plan” into torque. The stored gains of the previous chapter cannot do it here: during the swing-up the planned torque sits at the plan’s limit, and a command at a limit has no gain. The library offers a second error law for exactly this case, an attitude and rate cascade. It turns the error in angle into a wanted rate, compares that with the measured rate, and turns the difference into a torque. An integral term slowly adds torque against an error that persists.
NMPC::AttitudeCascade<double> cascade;
cascade.k_attitude = Vector3::Constant(6.0); // rad/s of rate asked per rad of angle error
cascade.kp = Vector3::Constant(18.0); // rad/s^2 per rad/s of rate error
cascade.ki = Vector3::Constant(40.0);
cascade.kd = Vector3::Zero();
cascade.integral_limit = Vector3::Constant(reserve);
cascade.design(0.001); // the inner loop's tick, s
const Vector3 inertia = Vector3::Constant(model.inertia());AttitudeCascade was written for vehicles, whose attitude is a rotation in three dimensions, so it takes the attitude as a quaternion and returns a moment about three axes. The pendulum turns about one axis, its shaft. The example describes the rod’s angle as a rotation about that axis and uses the one component of the moment that acts on the shaft. On a vehicle the same call handles roll, pitch and yaw, and takes care that a planned rate is expressed in the axes of the vehicle’s own attitude before it is compared with the gyroscope.
Every millisecond the inner loop adds the cascade’s torque to the plan’s and clips the sum to the real limit of the motor.
double torque = plan_torque;
bool clipped = false;
if (tracking) {
const Vector3 moment = cascade.moment(about_shaft(x(0)), Vector3(0.0, 0.0, x(1)),
about_shaft(planned(0)), Vector3(0.0, 0.0, planned(1)), inertia);
const double wanted = plan_torque + moment.z();
torque = std::clamp(wanted, -motor_limit, motor_limit);
clipped = torque != wanted;
cascade.integrate(clipped, inertia); // the integral waits while the motor is at its limit
}The last call matters. An integral that keeps growing while the motor is already at its limit stores up a correction that cannot be delivered, and releases it later as an overshoot. integrate(clipped, …) holds the integral still whenever the command was clipped.
Run track for a range of weights and the difference between the two loops is plain.
| Real weight | Direct: held inverted | Plan and track: held inverted | Furthest from the plan |
|---|---|---|---|
| −20% | not within 10 s | from 4.67 s | 0.011 rad |
| −10% | not within 10 s | from 4.66 s | 0.006 rad |
| −5% | not within 10 s | from 4.66 s | 0.003 rad |
| as modelled | from 3.27 s | from 4.65 s | 0.000 rad |
| +5% | not within 10 s | from 4.64 s | 0.003 rad |
| +10% | not within 10 s | from 4.64 s | 0.006 rad |
| +20% | not within 10 s | from 4.73 s | 0.215 rad |
Two things in the table deserve a second look. The reserve has a price: with a perfect model, the plan that may use only 0.30 N m takes 4.65 s to do what the full motor did in 3.27 s. And the reserve has an end. A weight 20% heavier needs up to 0.2 N m more than the model expects when the rod is level, four times the 0.05 N m in reserve. The rod falls 0.22 rad behind the plan before it catches up. Much beyond that it would not catch up, and the plan would be describing a motion that is no longer happening.
So the size of the reserve is a judgement about how wrong the model may be, and the inner loop’s distance from the plan is the number to watch. When it grows past what the reserve can recover, stop following: reset the solver from the measured state and plan again.
A torque the model leaves out
An inner loop with an integral removes a steady error slowly, by letting the error build up first. There is a faster way when you can measure acceleration. The model predicts how the rod should accelerate under the torque just applied. If the rod accelerates differently, something is pushing that the model does not know about, and the size of the surprise is the size of the push.
The library calls this an incremental correction. Each tick, you give it the measured value minus the model’s expectation. It filters that difference, multiplies it by a gain that converts it into the units of the actuator, and holds the result as an addition to the command.
NMPC::Incremental<double, 1, 1> correction; // one measured quantity, one actuator
correction.design(cutoff, 1000.0); // low-pass cutoff and inner-loop rate, Hz
correction.gain(0) = -pendulum.inertia(); // rad/s^2 of surprise to N m against it
correction.allocation(0, 0) = 1.0; // all of it goes to the one motor
correction.limit(0) = 0.1; // the most it may hold, N mFor the pendulum the measured quantity is angular acceleration, taken from two successive gyroscope readings. The gain is minus the rod’s inertia, because an unexplained acceleration of 1 rad/s² means an unknown torque of one inertia’s worth, and the correction should oppose it. The low-pass filter is there because differencing a gyroscope amplifies its noise.
// What the gyroscope shows of the last millisecond, against what the model expected of it.
const double rate = x(1) + gyro_sigma * noise();
const double measured = (rate - last_rate) / 0.001; // rad/s^2
const double expected = pendulum.acceleration(x, applied); // from the model
NMPC::Vector<double, 1> surprise;
surprise(0) = measured - expected;
if (correcting && tick > 0) correction.update(surprise);
last_rate = rate;
// The three terms of the inner loop: the plan, its error law, and the correction.
const double nominal = plan.feedback(stage.index, x, predicted)(0);
applied = std::clamp(nominal + correction.held(0), -motor_limit, motor_limit);The expectation uses the torque that was actually applied, including the correction’s own share. That is what makes the scheme settle: once the correction cancels the push, measured and expected accelerations differ by exactly the push again, and the held value stays where it is.
In correction.cpp the rod is held inverted by the plan and its stored gain. From 0.5 s a steady 0.03 N m pushes on it, as an off-centre load would.
correction.design(3.0, 1000.0); // low-pass cutoff and inner-loop rate, Hz
surprise(0) = measured - expected; // angular acceleration, rad/s^2
correction.update(surprise);
applied = std::clamp(nominal + correction.held(0), -motor_limit, motor_limit);correction.design(3.0, 1000.0); // low-pass cutoff and inner-loop rate, Hz
surprise(0) = measured - expected; // angular acceleration, rad/s^2
correction.update(surprise);
applied = std::clamp(nominal + correction.held(0), -motor_limit, motor_limit);
correction.cpp, with simulated gyroscope noise of 0.001 rad/s.Try it
- Select Off. The stored gain stops the rod, but only by letting it lean: it settles 14.6 mrad from inverted, where the gain’s torque balances the push. The plan knows nothing of this.
- Select On, 3 Hz. The blue estimate rises to the push within a few tenths of a second. The rod moves 2.9 mrad and comes back to inverted.
- Select On, 1 Hz. A slower filter finds the push later, and the rod moves 6.9 mrad first.
- Select On, 10 Hz. The estimate arrives sooner and the rod moves less than a milliradian. The cost is on the blue line: more of the gyroscope’s noise now reaches the motor.
NMPC::Butterworth2, the filter inside the correction, can be used alone. design(cutoff, rate) takes both in hertz, with the cutoff below half the rate. Calling the filter with a sample, as in y = filter(x), advances it by one step and returns the filtered value. When a loop has no correction, NMPC::NoCorrection supplies a held of zero so that the rest of the code need not change.
One motor, three claims on it
The inner loop is now a sum of three terms: the plan’s command, an error law on the distance from the plan, and the correction. All three want the same motor, and the motor has one limit. Three rules keep the sum honest.
- Tell the solver what is left. Whatever the correction is holding, and whatever you reserve for the error law, comes out of the bounds the solver plans within. The solver reads the bounds at every solve, so a problem can report them from a member the application updates.
// The pendulum problem, with the correction's share of the motor taken out of the plan's range.
struct Corrected : Pendulum {
double held = 0.0; // torque the correction is applying, N m
void control_bounds(int, Control& lower, Control& upper) const {
lower(0) = -tuning.torque_limit - held;
upper(0) = tuning.torque_limit - held;
}
};- Clip the sum, once. Add the three terms and clamp the total to the physical limit.
NMPC::clampdoes this for a vector of actuators, andNMPC::on_boundreports whether any is at a limit. - Stop integrating while clipped. Pass that report to
integrate, and give the correction alimitof its own, so that neither can store up a demand the motor cannot meet.
With more than one actuator there is a further step, allocation: turning a wanted force or moment into commands for individual actuators. The correction’s allocation matrix does this for its own increments. Two motors that lift together would each take half of a wanted force, and take opposite shares of a wanted moment.
What the controller knows
One flattery remains in these simulations. The controller and the inner loop were given the pendulum’s true angle and rate, apart from the noisy gyroscope of the last example. A real controller has an estimate, made from sensors by a filter, and the estimate is late, noisy and sometimes wrong.
That affects the choices of this chapter. Gains multiply noise: a rate gain of 0.9 N m per rad/s turns a rate error of 0.05 rad/s into 0.045 N m of motor torque, nearly the whole reserve. A correction built on measured acceleration needs its filter. And the state from which a plan starts, discussed in the previous chapter, is always a prediction from an estimate.
The companion guide builds the estimator for this same pendulum: the SFWA UKF guide tracks its angle and rate from a camera, and reports how uncertain each is. That uncertainty is the right thing to compare with your reserve.
Check your understanding
The direct loop re-solved from the true state every 20 ms. Why was that not enough to cope with a 5% error?
Because the plan left no room to act on what the measurements showed. It ran the motor at its limit and aimed to arrive with no speed to spare, so the lighter rod’s extra energy could neither be taken out on the way up nor absorbed at the top.
With Plan and track, which part of the controller knows that the weight is wrong?
None of it knows. The plan describes the model’s motion, and the inner loop sees only that the rod keeps drifting from the plan and pushes it back. The integral ends up holding the torque that the wrong weight requires. To learn the weight itself you would estimate it, which is a job for a filter.
Why must the expected acceleration include the correction’s own torque?
If it did not, the correction would see its own effect as another surprise. Having cancelled the push, it would measure no unexplained acceleration, let go, feel the push again, and so on. Including it makes the difference equal to the unknown push and nothing else.
Reference
| Name | What it is |
|---|---|
NMPC::AttitudeCascade<T> | An error law for a rigid body. moment(q, w, q_plan, w_plan, inertia) returns the moment about each body axis that pulls the attitude q and rate w toward the plan’s. Gains per axis: k_attitude (1/s), kp (1/s), ki (1/s²), kd (s), and integral_limit (N m). The defaults are for a small quadrotor: set your own. |
design(tick, cutoff) | The inner loop’s tick in seconds and the cutoff of the derivative’s filter in hertz. Clears the cascade’s state. |
integrate(clipped, inertia) | Advance the integral, unless the command was clipped. |
NMPC::Incremental<T, NY, NA> | A correction from NY measured-minus-expected quantities to NA actuator increments, with a gain per quantity, an allocation matrix and a limit per actuator. update(residual) filters and stores the increments in held. |
NMPC::Butterworth2<T> | A second-order low-pass filter. design(cutoff, rate) in hertz, then call it with each sample. |
NMPC::clamp, NMPC::on_bound | Limit a vector of commands, and report whether any is at a limit. |
NMPC::NoCorrection<T, NA> | A correction that holds nothing. |
These helpers are experimental in this revision of the library. Their source states the units, the conventions for frames and what each reset clears.
InnerLoop.h · Inner-loop checks · The README on the inner loop · Experimental interfaces