The solver knows nothing about pendulums. It works on any system you can describe with four things: a model that says what a command does, the model’s derivatives, a cost that says what you want, and limits on the commands. This chapter writes those four for the pendulum. Together they are the file pendulum.h that every program in this guide includes.
The state, the command and the stage
The state is what you must know about the system now in order to predict its future. For the pendulum that is two numbers: the angle of the rod, measured in radians from hanging straight down, and the rate at which the angle is changing. The command is what the controller decides: one number, the motor’s torque in newton metres. A stage is the stretch of time over which one command is held, here 20 ms.
using Scalar = double;
enum { NX = 2, NU = 1, NR = 3, NT = 2, Stages = 100 };
using State = Eigen::Matrix<double, 2, 1>; // angle from hanging down (rad), rate (rad/s)
using Control = Eigen::Matrix<double, 1, 1>; // motor torque (N m)
double dt = 0.02; // length of one stage, s; 100 stages look 2 s ahead
int substeps = 2; // steps of the model within one stage
double g = 9.80665; // m/s^2
Tuning tuning;The sizes are part of the type, so every matrix in the solver has a size the compiler knows and nothing is allocated at run time. NX and NU count the entries of the state and the command. NR and NT count the terms of the cost, which come later in this chapter. Stages is the length of the plan: 100 stages of 20 ms look two seconds ahead.
The physical numbers and the weights of the cost sit together in one small structure, with their units.
// Everything you would measure or tune, with its units.
struct Tuning {
double length = 0.5; // m
double mass = 0.2; // kg, at the end of a massless rod
double damping = 0.005; // N m s/rad
double torque_limit = 0.35; // N m, about a third of the 0.98 N m that holds the rod level
double angle_weight = 3.0; // per rad from inverted
double rate_weight = 0.3; // per rad/s
double torque_weight = 0.5; // per unit of the torque limit
double terminal_weight = 4.0; // per rad and per rad/s, at the end of the plan
};The model: one stage of motion
Three torques act on the rod. The motor supplies the command. Friction in the bearing opposes the motion, in proportion to the rate. Gravity pulls the weight straight down, which turns the rod with a torque equal to the weight times its lever arm: the sideways distance from the shaft to the weight, length × sin(angle). Gravity’s torque is zero when the rod hangs or stands on end, and largest, 0.98 N m, when the rod is level.
The sum of the three torques, divided by the rod’s inertia, is its angular acceleration. The model takes two small steps of time within a stage. In each it first changes the rate by the acceleration, then changes the angle by the new rate.
// Angular acceleration: the motor, less friction, less the pull of gravity.
double acceleration(const State& x, double torque) const {
const double friction = tuning.damping * x(1);
const double gravity = weight_torque() * std::sin(x(0)); // weight times its lever arm
return (torque - friction - gravity) / inertia();
}
// One substep: the rate first, then the angle from the new rate.
State substep(const State& x, double torque, double h) const {
const double rate = x(1) + h * acceleration(x, torque);
return State(x(0) + h * rate, rate);
}
// One stage of the plan holds the torque for dt seconds.
State step(int, const State& x, const Control& u) const {
const double h = dt / substeps;
State next = x;
for (int i = 0; i < substeps; i++) {
next = substep(next, u(0), h);
}
return next;
}The solver calls step to predict the motion a plan would cause. The simulations in this guide call the same function to move the simulated pendulum, which is why the model is exact in every chapter but the last.
The figure shows what step does. Its plot is the phase plane: each point is one state, with the angle across and the rate up. The grey arrows show where the model sends every state for the chosen torque. The green dots follow one state through 100 calls of step, two seconds of motion.
Pendulum pendulum;
const Pendulum::State x(0.00, 0.00); // angle (rad), rate (rad/s)
const Pendulum::Control u = Pendulum::Control::Constant(0.35); // torque (N m)
const Pendulum::State next = pendulum.step(0, x, u); // (0.0021, 0.1398)Pendulum pendulum;
const Pendulum::State x(0.00, 0.00); // angle (rad), rate (rad/s)
const Pendulum::Control u = Pendulum::Control::Constant(0.35); // torque (N m)
const Pendulum::State next = pendulum.step(0, x, u); // (0.0021, 0.1398)
x is the same state in the phase plane, and each green dot is the state one stage later than the one before. Grey arrows show the direction in which the model moves each state, longer where the motion is faster. Shaded bands and wedges mark the angles at which the motor’s full torque can balance the weight. You can drag the dark dot.Try it
- Start as the figure opens: hanging at rest with the full +0.35 N m. The green loop is the whole motion: the rod swings out to 0.73 rad and back, for ever. Full torque in one direction never gets the weight above 42°.
- Now pump the swing by hand. Set the rate to +2 rad/s and look at where the loop goes. Then move the angle to the far end of that loop, set the rate to zero and the torque to −0.35 N m. Each reversal at the end of a swing makes the next loop larger. This is the plan the solver finds for itself.
- Set the torque to zero and drag the state to 3.0 rad at rest, just short of inverted. The rod falls away, slowly at first. Near the top a small error grows quickly, which is why holding the rod there needs feedback.
- Still near the top, set the torque to +0.35 N m and move the angle through 2.7, 2.8 and 2.9 rad. Inside the shaded wedge the motor wins and the rod rises. Outside it, gravity wins.
The limit on the command
The motor’s limit is the smallest part of the problem and the reason the pendulum is hard.
// What the motor can deliver at stage k. The solver never plans outside it.
void control_bounds(int, Control& lower, Control& upper) const {
lower(0) = -tuning.torque_limit;
upper(0) = tuning.torque_limit;
}The solver reads these bounds once per solve, for every stage, and no plan it returns goes outside them. The shaded regions in the figure follow from this one number. The motor can hold the rod still only where gravity’s torque is no more than 0.35 N m, which is within 0.365 rad (21°) of hanging or of inverted.
Because the bounds are read at every solve, they can change while the controller runs: lower them when a motor overheats, or by the share that another part of the control loop needs, as the last chapter does. Use an infinity for a command with no limit on one side. Equal lower and upper bounds fix a command at that value.
Derivatives: how a small change carries forward
To improve a plan, the solver must know how a small change early in the plan alters everything after it. You supply that as two matrices for each stage. a says how the next state moves when the present state changes a little. b says how the next state moves when the torque changes a little. They are the Jacobians of step.
For the pendulum only one entry is interesting. A small change in angle changes the lever arm, so it changes gravity’s torque, so it changes the next rate. How much depends on where the rod is: the lever arm grows fastest when the rod hangs, does not change at all when the rod is level, and shrinks when the rod is above level. That is the cosine in the code below.
// How the next state moves when the state (a) or the torque (b) changes a little.
template <class A, class B>
void step_jacobian(int, const State& x, const Control& u, A& a, B& b) const {
const double h = dt / substeps;
a.setIdentity();
b.setZero();
State s = x;
for (int i = 0; i < substeps; i++) {
// The slope of the acceleration at this substep's state.
const double da_dangle = -weight_torque() * std::cos(s(0)) / inertia();
const double da_drate = -tuning.damping / inertia();
Eigen::Matrix<double, 2, 2> m; // the substep's own Jacobian
m(1, 0) = h * da_dangle;
m(1, 1) = 1.0 + h * da_drate;
m(0, 0) = 1.0 + h * m(1, 0);
m(0, 1) = h * m(1, 1);
Eigen::Matrix<double, 2, 1> n; // and its response to torque
n(1) = h / inertia();
n(0) = h * n(1);
a = (m * a).eval(); // chain it onto the substeps before
b = (m * b + n).eval();
s = substep(s, u(0), h);
}
}The solver never differentiates numerically. It trusts these matrices, so a mistake in them makes plans worse without any error message. The library provides a checker for use in tests. It nudges each entry of the state and the command a little each way, runs step, and compares the change it sees with the matrix you wrote.
const NMPC::CheckResult<double> step = NMPC::check_step_jacobian(problem, 0, x, u, 1e-7);
const NMPC::CheckResult<double> cost = NMPC::check_residual_jacobians(problem, 0, x, u, 1e-7);
const NMPC::CheckResult<double> end = NMPC::check_terminal_jacobian(problem, x, 1e-7);The figure shows the entry a(1, 0), the change in the next rate per radian of change in the angle. The green curve is the model itself: the rate after one stage, starting from rest at each angle. The dashed line is what the Jacobian claims the curve’s slope to be at the chosen angle. A correct Jacobian lies along the curve.
const Pendulum::State probe(2.00, 0.0); // angle (rad), at rest
const auto check = NMPC::check_step_jacobian(
pendulum, 0, probe, Pendulum::Control::Zero(), 1e-7);
// passed, worst error 1.3e-11const Pendulum::State probe(2.00, 0.0); // angle (rad), at rest
const auto check = NMPC::check_step_jacobian(
pendulum, 0, probe, Pendulum::Control::Zero(), 1e-7);
// passed, worst error 1.3e-11
step_jacobian returns in a(1, 0). The curve and the check results were recorded from check.cpp.Try it
- Move the angle from −3.1 to 3.1 rad. With the Jacobian from
pendulum.hthe dashed line stays tangent to the curve, and the check passes with an error near a hundred-billionth. - Switch to the Small-angle shortcut. This Jacobian was written as if gravity’s pull were proportional to the angle, which is nearly true for small swings. Set the angle to 0: the line is still tangent and the check still passes.
- Move the angle to 2.0 rad. The claimed slope now has the wrong sign. The check fails at row 1, column 0 with an error of 0.55, and tells you which entry to look at.
The lesson of the last two steps is to check derivatives at states the system will really visit, away from any point where a simplification happens to hold. check.cpp runs the checks at 2.0 rad and −1.5 rad/s with a torque applied, so that every term of the model takes part.
pendulum.h at angle 2.00 rad:
step_jacobian passed worst error 4.4e-11 at row 1, column 2
residual_jacobians passed worst error 4.6e-12
terminal_jacobian passed worst error 5.2e-12
small-angle Jacobian at angle 2.00 rad:
step_jacobian FAILED worst error 0.55 at row 1, column 0
residual_jacobians passed worst error 4.6e-12
terminal_jacobian passed worst error 5.2e-12
A reported column below NX is an entry of the state. Later columns are commands, so “column 2” above is the torque. Each error is the difference between the two derivatives, divided by the size of the numerical one when that is larger than one.
The cost: what the plan is asked to care about
The cost turns “swing up and stay there” into a number. You write it as a list of residuals: quantities that should each be small. The pendulum has three per stage: the angle’s distance from inverted, the rate, and the torque. The cost of a stage is half the sum of their squares, so a residual twice as large costs four times as much.
// The cost of a stage is half the sum of these three numbers squared.
template <class R>
void stage_residual(int, const State& x, const Control& u, R& r) const {
const double s = std::sqrt(dt); // so that the weights are per second
r << s * tuning.angle_weight * (x(0) - kPi),
s * tuning.rate_weight * x(1),
s * tuning.torque_weight * u(0) / tuning.torque_limit;
}
// The end of the plan is scored once, on where the pendulum is left.
template <class R>
void terminal_residual(const State& x, R& r) const {
r << tuning.terminal_weight * (x(0) - kPi), tuning.terminal_weight * x(1);
}Each residual is multiplied by a weight, which sets its price. An angle weight of 3 and a rate weight of 0.3 say that one radian of angle error costs as much as ten radians per second of rate. The torque is divided by its limit first, so its weight prices the share of the motor in use. The factor sqrt(dt) makes the prices per second: the cost of a second of error then stays the same if you later divide that second into more stages.
At the end of the plan the terminal residuals score the last predicted state once more, with a larger weight. They stand in for everything beyond the horizon: a plan that ends close to upright and nearly at rest is one from which the next plan can finish the job.
Writing the cost as squared residuals lets the solver build what it needs from first derivatives alone. Those derivatives are the residuals’ own Jacobians, which for the pendulum are constants.
template <class JX, class JU>
void residual_jacobians(int, const State&, const Control&, JX& jx, JU& ju) const {
const double s = std::sqrt(dt);
jx.setZero();
ju.setZero();
jx(0, 0) = s * tuning.angle_weight;
jx(1, 1) = s * tuning.rate_weight;
ju(2, 0) = s * tuning.torque_weight / tuning.torque_limit;
}
template <class JX>
void terminal_jacobian(const State&, JX& jx) const {
jx = tuning.terminal_weight * JX::Identity();
}Weights decide the motion, and a bad choice can decide that there is none. The figure draws the cost over the phase plane. States inside the outlined region cost less per second than hanging at rest. The path is the simulated swing-up that tune.cpp recorded with the selected weights.
pendulum.tuning.rate_weight = 0.3;
pendulum.tuning.torque_weight = 0.5;pendulum.tuning.rate_weight = 0.3;
pendulum.tuning.torque_weight = 0.5;
Try it
- With a rate weight of 0.3 the outline is tall: speed is cheap. The path leaves the outlined region on its swing to the left, pays for a moment, and comes back in on the way up. The rod is held inverted from 3.28 s.
- Choose a rate weight of 1.0. The outline is flatter and the route over the top passes further outside it. The swing-up still succeeds, at 3.48 s.
- Choose 2.0. Passing the bottom at 6.5 rad/s would now cost about three times as much per second as hanging there. The cheapest two seconds are spent near the bottom, and the rod never gets far from it.
- Choose a rate weight of 0.3 with a torque weight of 5.0. Torque is now ten times dearer. The controller uses less of it, 0.24 against 0.34 when torque squared is summed over time, and still holds the rod inverted from 3.02 s.
The third step is the usual way a predictive controller disappoints. It did exactly what the cost asked for. When a controller refuses to do the obvious thing, work out the cost of the obvious thing by hand before you look for a bug.
Parts you may not need
The pendulum uses two optional parts of a problem. The rest are for larger systems.
| Member | When to supply it |
|---|---|
state_scale, control_scale | The typical size of each state and command. Supply them when the sizes differ widely, above all in single precision. The solver works in units of these. The pendulum gives 1 rad, 5 rad/s and the torque limit. |
retract, difference | Always required, and trivial for the pendulum: add a change to a state, and subtract one state from another. A state that holds an attitude quaternion has four numbers but only three ways to change, and these two functions say how. NX counts the ways to change. Types.h has attitude_retract and attitude_difference. |
linear_cost, linear_cost_gradient | A cost term that is not a squared residual, such as a reward for progress along a path. |
cost_expansion, terminal_expansion | Your own, faster way to form the cost’s derivatives when you know their structure. |
tail_control | The command for the new stage that enters at the far end when the plan is advanced. Without it the last command is repeated. |
finite | Required only when the state is not an Eigen type, so that the solver can test a predicted state. |
Anything else the model depends on, such as a measured wind or a changing weight in the cost, is an ordinary member of your problem that your program sets between solves.
Check your understanding
At what angles is a(1, 0) zero, and what does that mean physically?
Close to ±π/2, where the rod is level. There gravity’s torque is at its largest, so a small change in angle does not change it, and the next rate is the same either way.
The check passed at an angle of zero even with the wrong Jacobian. Why?
The shortcut takes the slope at hanging, and at hanging that is the right slope. A check proves the derivatives only at the states where you run it.
You want the rod to arrive at the top more gently. Which number would you change first?
The rate weight, upward, but by a little. It prices speed everywhere, including the speed the swing needs at the bottom, and by 2.0 the swing-up no longer happens. A rate weight that grows near the top would be a better tool. A weight can depend on the state, because the residual is your own function.
Reference
| A problem provides | Meaning |
|---|---|
Scalar, State, Control, NX, NU, NR, NT, Stages | The number type, the state and command types, and the sizes. |
step(k, x, u) | The state one stage after x when the command u is held. k is the stage’s index in the plan. |
step_jacobian(k, x, u, a, b) | The derivatives of step with respect to the state and the command. |
stage_residual, terminal_residual | The quantities whose squares, halved and summed, are the cost. |
residual_jacobians, terminal_jacobian | The derivatives of the residuals. |
control_bounds(k, lower, upper) | The limits on the command at stage k. |
NMPC::check_step_jacobian, check_residual_jacobians, check_terminal_jacobian | Compare your derivatives with central differences. Each returns passed, the worst error and its row and column. |