bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Balancing a cart-pole with LQR and MPC

A pole hinged on a cart falls over unless the cart moves under it. Balancing it is the classic test of a controller: the system is unstable, it has one input for two things to control, the pole and the cart, and the cart has a track that ends. This example balances CartPoleDynamics with two controllers designed from the same linear model and the same weights: a linear quadratic regulator (LQR), and model predictive control (MPC). They start near the end of the track, with the pole leaning towards it, and only MPC knows where the track ends.

The LQR, above, runs the cart off the end of the track; MPC, below, catches the pole within it

What you need

Nothing beyond bitsim itself. To make the pictures of the GIF, bitsim built with OpenCV. See Installing bitsim.

The cart-pole

The state is the position of the cart \(x\), its velocity, the angle of the pole from upright \(\theta\), positive when it leans towards \(+x\), and its rate. The input is a horizontal force on the cart, at most 10 N either way. The cart weighs 1 kg, the pole 0.1 kg, and the centre of the pole is 0.5 m from the pivot, as in the cart-pole of Barto, Sutton and Anderson that Gymnasium's CartPole also uses. The track runs from -2.4 m to 2.4 m.

Upright is an equilibrium, and linearise() gives the model about it, \(\dot x = A x + B F\), by central differences. discretise() turns it into the model of a controller that acts every 0.02 s, with the force held between, \(x_{k+1} = A_d x_k + B_d F_k\):

const CartPoleDynamics model;
const auto linear = model.linearise();
const auto discrete = bitsim::control::discretise(linear.A, linear.B, DT);
DiscreteLinearModel discretise(const Matrix &A, const Matrix &B, real_t dt)
Discretise for a step dt, with the input held over the step (zero-order hold): and ,...
Definition lqr.cpp:41

LQR

An LQR finds the state feedback \(F = -K x\) that minimises

\[J = \sum_{k=0}^{\infty} x_k^T Q x_k + F_k^T R F_k , \]

a sum of how far the state is from upright at the centre, and of how hard it pushes. Q weighs the angle of the pole most, 10, the position 1 and the two rates 0.1; R weighs the force 0.1. The gain comes from the discrete algebraic Riccati equation, which dlqr() solves:

const auto lqr = bitsim::control::dlqr(discrete.A, discrete.B, Q, R);
controller.set_input_bounds(Vector::Constant(1, -10.0), Vector::Constant(1, 10.0));
A linear state feedback about an operating point, , with optional bounds on each input.
Definition lqr.h:105
LQRSolution dlqr(const Matrix &A, const Matrix &B, const Matrix &Q, const Matrix &R)
The LQR of : with P from solve_dare().
Definition lqr.cpp:154
Matrix K
Definition lqr.h:75

\(K = [-2.83, -4.18, -39.57, -9.90]\): a pole leaning right, \(\theta > 0\), makes it push the cart right, under the pole, and the cart away from the centre makes it push it back. The LQR is optimal for the linear model, but it knows nothing about limits. Its force is clipped to 10 N, which it was not designed for, and the end of the track is not in its cost at all.

MPC

MPC plans instead. At every step it finds the forces \(F_0, \dots, F_{N-1}\) over the next \(N = 40\) steps, 0.8 s, that minimise the same cost, subject to the model and to the limits: \(|F_k| \le 10\) N, and the cart within \(\pm 2.3\) m, 0.1 m short of the ends. It uses the first force, and plans again at the next step from the state then. LinearMPC does it:

bitsim::control::LinearMPC mpc(4, 1, HORIZON);
mpc.set_model(discrete.A, discrete.B);
mpc.set_weights(Q, R);
mpc.set_input_bounds(Vector::Constant(1, -10.0), Vector::Constant(1, 10.0));
mpc.set_state_bounds(x_min, x_max, PENALTY);
const real_t force = mpc.solve(x)[0];
Model predictive control with a linear model, a quadratic cost and bounds on the inputs and the state...
Definition linear_mpc.h:46
  • The cost beyond the horizon is that of the LQR: the terminal weight is the solution P of the Riccati equation, so with no limit active, MPC gives the LQR's force.
  • The bound on the cart is soft: the plan may exceed it, at a cost of 1000 per metre and per step, plus a quadratic term. A hard bound can be impossible to keep after a large disturbance, and the planning problem would then have no solution at all. With the soft bound, MPC keeps to it whenever it can.
  • Every step solves a quadratic program, QPSolver, starting from the plan of the step before.

Running the example

./cart_pole_lqr_mpc # print both runs
./cart_pole_lqr_mpc --record frames # and write a picture every 0.04 s to frames/

The GIF above is made from the pictures with

ffmpeg -framerate 25 -i frames/frame_%04d.png \
-vf "split[a][b];[a]palettegen=max_colors=64[p];[b][p]paletteuse" cart_pole_lqr_mpc.gif

The example exits with an error if MPC lets the cart off the track or does not balance the pole, so it runs as a test too.

Output

Both start at 1.5 m, with the pole leaning 0.4 rad towards the end at 2.4 m:

LQR
time [s] cart [m] pole [rad] force [N]
0.00 1.500 0.400 10.00
0.50 2.267 -0.220 -6.00
1.00 2.283 -0.247 -3.11
1.50 1.543 -0.017 0.29
...
6.00 -0.006 -0.002 -0.02
furthest the cart went: 2.436 m, off the end of the track
MPC
time [s] cart [m] pole [rad] force [N]
0.00 1.500 0.400 10.00
0.50 2.269 -0.244 -10.00
1.00 2.284 -0.182 -2.72
1.50 1.853 -0.100 -1.08
...
6.00 -0.011 -0.002 -0.02
furthest the cart went: 2.301 m, on the track
MPC solved 301 QPs, 0 of them not to the tolerance, with 168 iterations on average

Both push right as hard as they can at first, to get the cart under the falling pole. The LQR keeps pushing until the pole is caught, and only then brakes: by then the cart is past the end of the track, at 2.436 m. MPC sees, 0.8 s ahead, that the cart would cross its bound, and brakes earlier and at full force, -10 N at 0.5 s where the LQR uses -6 N, tilting the pole back with less travel: the cart stops at 2.301 m. Both then bring the cart back to the centre, the LQR slightly faster, since it did not have to give anything up to keep to the track. The blue dots under MPC's cart in the GIF are its plan: where it expects the cart to be over the next 0.8 s.

One MPC step, a QP with 240 variables, the 160 planned states, 40 forces and 40 slacks of the soft bound, takes about 1 ms here, 170 iterations of the solver on average.

Things to try

  • Start at 1.8 m, or with the pole at 0.5 rad. MPC can no longer keep the cart within 2.3 m: it goes past its bound, to 2.66 m from 1.8 m, and still balances the pole. Then make the bound hard, with a penalty of 0. From 1.8 m the planning problem has no solution any more, the solver stops at its limit of iterations at almost every step, and MPC loses the pole.
  • Shorten the horizon. With 20 steps, 0.4 s, MPC still stops the cart at its bound, with half the work per step. With 10 steps, 0.2 s, it sees the end of the track too late, gives up the pole and the cart drives away: a short horizon with a constraint that becomes active is no longer stable, even with the LQR's cost at its end.

The code

// Balancing a cart-pole near the end of its track, with an LQR and with model predictive control.
//
// Usage: cart_pole_lqr_mpc [--record DIR]
//
// Both controllers start with the pole leaning 0.4 rad towards the near end of the track, 0.9 m
// from it, and can push the cart with at most 10 N. The LQR is designed without the limits, and
// its force is clipped to them. MPC plans with the limits of the force and of the track. --record
// DIR writes a picture of both every 0.04 s of simulated time to DIR, which needs bitsim built
// with OpenCV.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_OPENCV
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#endif
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
{
const real_t DT = 0.02; // the control period [s]
const real_t DURATION = 6.0; // [s]
const real_t X0 = 1.5; // where the cart starts [m]
const real_t THETA0 = 0.4; // how far the pole leans, towards +x [rad]
const real_t TRACK_BOUND = 2.3; // what MPC keeps the cart within, 0.1 m short of the end [m]
const uint_t HORIZON = 40; // the steps MPC plans, 0.8 s
const real_t PENALTY = 1000.0; // of a cart beyond TRACK_BOUND
const real_t RECORD_RATE = 25.0; // [pictures/s]
// One run: the state at every step, and the force
struct Run
{
std::string name;
std::vector<CartPoleState> states;
std::vector<real_t> forces;
std::vector<std::vector<real_t>> plans; // MPC's planned cart positions, at every step
real_t max_x{0.0};
bool off_track{false};
};
// The weights of both controllers: the angle of the pole matters most, then the position
{
q << 1.0, 0.1, 10.0, 0.1;
return q.asDiagonal().toDenseMatrix();
}
Matrix input_weights() { return 0.1 * Matrix::Identity(1, 1); }
{
CartPoleState x = CartPoleState::Zero();
x[cp::X] = X0;
return x;
}
// Run a controller, a function from the state to the force, and record what happens
template <typename Controller> Run simulate(const std::string &name, Controller &&controller)
{
run.name = name;
const auto steps = static_cast<uint_t>(std::lround(DURATION / DT));
for (uint_t k = 0; k <= steps; ++k)
{
const CartPoleState x = cart_pole.state();
const real_t force = cart_pole.limit(controller(x, run));
run.states.push_back(x);
run.forces.push_back(force);
run.max_x = std::max(run.max_x, x[cp::X]);
run.off_track = run.off_track || cart_pole.off_track();
cart_pole.step(force, DT);
}
return run;
}
void print(const Run &run)
{
std::printf("\n%s\n time [s] cart [m] pole [rad] force [N]\n", run.name.c_str());
for (uint_t k = 0; k < run.states.size(); k += 25)
{
const auto &x = run.states[k];
std::printf(" %8.2f %8.3f %10.3f %9.2f\n", k * DT, x[cp::X], x[cp::THETA],
run.forces[k]);
}
std::printf(" furthest the cart went: %.3f m, %s\n", run.max_x,
run.off_track ? "off the end of the track" : "on the track");
}
#ifdef BITSIM_OPENCV
// Draw both runs, one above the other, at step k
cv::Mat draw(const std::vector<Run> &runs, uint_t k, const CartPoleParameters &p)
{
const int width = 640;
const int panel = 250;
cv::Mat picture(panel * static_cast<int>(runs.size()), width, CV_8UC3,
cv::Scalar(250, 250, 250));
// the part of the track where it happens, from -0.5 m to 2.9 m
const real_t view_min = -0.5;
const real_t view_max = 2.9;
const real_t scale = width / (view_max - view_min); // pixels per metre
const auto px = [&](real_t x) { return static_cast<int>(std::lround((x - view_min) * scale)); };
for (uint_t r = 0; r < runs.size(); ++r)
{
const Run &run = runs[r];
const auto &x = run.states[std::min<uint_t>(k, run.states.size() - 1)];
const int top = static_cast<int>(r) * panel;
const int ground = top + panel - 40;
// the track and MPC's bound; the end of the track is drawn over the cart
cv::line(picture, {0, ground}, {px(p.track_half_length), ground}, cv::Scalar(90, 90, 90),
2);
for (int y = ground - 200; y < ground; y += 8)
{
cv::line(picture, {px(TRACK_BOUND), y}, {px(TRACK_BOUND), y + 4},
cv::Scalar(120, 120, 220), 1);
}
// MPC's planned cart positions
if (!run.plans.empty())
{
for (const real_t xp : run.plans[std::min<uint_t>(k, run.plans.size() - 1)])
{
cv::circle(picture, {px(xp), ground + 14}, 2, cv::Scalar(200, 150, 60), -1);
}
}
// the cart, the pole and the force
const int cart_x = px(x[cp::X]);
const int cart_y = ground - 14;
const cv::Scalar cart_colour = std::abs(x[cp::X]) > p.track_half_length
? cv::Scalar(60, 60, 220)
: cv::Scalar(70, 70, 70);
const int half = static_cast<int>(0.25 * scale); // a cart 0.5 m long
cv::rectangle(picture, {cart_x - half, cart_y - 14}, {cart_x + half, cart_y + 14},
cart_colour, -1);
const real_t length = 2.0 * p.pole_half_length * scale;
const cv::Point tip(cart_x + static_cast<int>(length * std::sin(x[cp::THETA])),
cart_y - static_cast<int>(length * std::cos(x[cp::THETA])));
cv::line(picture, {cart_x, cart_y}, tip, cv::Scalar(30, 140, 230), 6, cv::LINE_AA);
cv::line(picture, {px(p.track_half_length), ground - 40},
{px(p.track_half_length), ground + 8}, cv::Scalar(40, 40, 200), 4);
cv::putText(picture, "end", {px(p.track_half_length) + 6, ground - 30},
cv::FONT_HERSHEY_SIMPLEX, 0.45, cv::Scalar(40, 40, 200), 1, cv::LINE_AA);
cv::putText(picture, "bound", {px(TRACK_BOUND) + 6, ground - 120}, cv::FONT_HERSHEY_SIMPLEX,
0.45, cv::Scalar(120, 120, 220), 1, cv::LINE_AA);
const real_t force = run.forces[std::min<uint_t>(k, run.forces.size() - 1)];
if (std::abs(force) > 0.2)
{
const int arrow = static_cast<int>(force * 6.0);
cv::arrowedLine(picture, {cart_x, cart_y + 26}, {cart_x + arrow, cart_y + 26},
cv::Scalar(60, 160, 60), 2, cv::LINE_AA, 0, 0.3);
}
char text[120];
std::snprintf(text, sizeof(text), "%s t %.2f s cart %.2f m force %+.1f N",
run.name.c_str(), k * DT, x[cp::X], force);
cv::putText(picture, text, {12, top + 24}, cv::FONT_HERSHEY_SIMPLEX, 0.55,
cv::Scalar(20, 20, 20), 1, cv::LINE_AA);
if (r > 0)
{
cv::line(picture, {0, top}, {width, top}, cv::Scalar(200, 200, 200), 1);
}
}
return picture;
}
void record(const std::vector<Run> &runs, const std::string &directory)
{
std::filesystem::create_directories(directory);
const auto every = static_cast<uint_t>(std::lround(1.0 / (RECORD_RATE * DT)));
uint_t n = 0;
for (uint_t k = 0; k < runs.front().states.size(); k += every)
{
char name[32];
std::snprintf(name, sizeof(name), "/frame_%04u.png", static_cast<unsigned>(n++));
cv::imwrite(directory + name, draw(runs, k, CartPoleParameters()));
}
std::cout << "Wrote " << n << " pictures to " << directory << std::endl;
}
#endif
} // namespace cart_pole_lqr_mpc
int main(int argc, char **argv)
{
using namespace cart_pole_lqr_mpc;
std::string record_dir;
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--record" && i + 1 < argc)
{
record_dir = argv[++i];
}
else
{
std::cerr << "Usage: cart_pole_lqr_mpc [--record DIR]\n";
return 1;
}
}
// the model, linearised about upright and discretised for the control period
const CartPoleDynamics model;
const auto linear = model.linearise();
const auto discrete = bitsim::control::discretise(linear.A, linear.B, DT);
const Matrix Q = state_weights();
const Matrix R = input_weights();
const real_t max_force = model.parameters().max_force;
// the LQR, with its force clipped to the limit
const auto lqr = bitsim::control::dlqr(discrete.A, discrete.B, Q, R);
lqr_controller.set_input_bounds(Vector::Constant(1, -max_force),
Vector::Constant(1, max_force));
std::printf("LQR gain K = [%.2f %.2f %.2f %.2f]\n", lqr.K(0, 0), lqr.K(0, 1), lqr.K(0, 2),
lqr.K(0, 3));
// MPC, with the same weights, the limit of the force, and the track, softly
const real_t inf = std::numeric_limits<real_t>::infinity();
mpc.set_model(discrete.A, discrete.B);
mpc.set_weights(Q, R);
mpc.set_input_bounds(Vector::Constant(1, -max_force), Vector::Constant(1, max_force));
Vector x_min(4);
x_min << -TRACK_BOUND, -inf, -inf, -inf;
Vector x_max(4);
x_max << TRACK_BOUND, inf, inf, inf;
mpc.set_state_bounds(x_min, x_max, PENALTY);
const Run lqr_run = simulate("LQR", [&](const CartPoleState &x, Run &)
{ return lqr_controller.control(x)[0]; });
uint_t unsolved = 0;
uint_t iterations = 0;
const Run mpc_run =
simulate("MPC",
[&](const CartPoleState &x, Run &run)
{
const real_t force = mpc.solve(x)[0];
unsolved +=
mpc.status() == bitsim::control::LinearMPC::QPStatus::SOLVED ? 0 : 1;
iterations += mpc.iterations();
std::vector<real_t> plan;
for (const auto &xp : mpc.predicted_states())
{
plan.push_back(xp[cp::X]);
}
run.plans.push_back(plan);
return force;
});
print(lqr_run);
print(mpc_run);
std::printf("\nMPC solved %zu QPs, %u of them not to the tolerance, with %.0f iterations on "
"average\n",
mpc_run.states.size(), static_cast<unsigned>(unsolved),
static_cast<double>(iterations) / mpc_run.states.size());
if (!record_dir.empty())
{
#ifdef BITSIM_OPENCV
record({lqr_run, mpc_run}, record_dir);
#else
std::cerr << "--record needs bitsim built with OpenCV\n";
return 1;
#endif
}
// what the example shows: MPC keeps the cart on the track and balances the pole
const auto &last = mpc_run.states.back();
const bool balanced = std::abs(last[cp::THETA]) < 0.01 && std::abs(last[cp::X]) < 0.1;
return (!mpc_run.off_track && balanced) ? 0 : 1;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A cart on a straight track, pushed by a horizontal force F, with a pole hinged on it.
Definition cart_pole_dynamics.h:70
const CartPoleParameters & parameters() const noexcept
Definition cart_pole_dynamics.h:108
CartPoleLinearModel linearise(const CartPoleState &x=CartPoleState::Zero(), real_t force=0.0) const
Definition cart_pole_dynamics.cpp:59
int main()
Definition discounted_returns.cpp:19
Linear quadratic regulators: the Riccati equations, the discretisation of a linear model,...
RealMat Matrix
The matrices of the linear models and the controllers.
Definition lqr.h:20
LQRSolution lqr(const Matrix &A, const Matrix &B, const Matrix &Q, const Matrix &R)
The LQR of : with P from solve_care().
Definition lqr.cpp:161
RealColVec Vector
The vectors of the linear models and the controllers: states, inputs.
Definition lqr.h:23
Where each value is in a CartPoleState.
Definition cart_pole_dynamics.h:33
constexpr int THETA
Definition cart_pole_dynamics.h:36
constexpr int X
Definition cart_pole_dynamics.h:34
@ Q
Definition fixed_wing_dynamics.h:38
@ R
Definition fixed_wing_dynamics.h:39
RealColVec4d CartPoleState
The state: the position of the cart [m], its velocity [m/s], the angle of the pole from upright [rad]...
Definition cart_pole_dynamics.h:29
const GeomPoint< spacedim, T > scale(const GeomPoint< spacedim, T > &t, T factor)
scale the given point by facto and returns a copyr. This function does not change the entries of t.
Definition geom_point.h:421
Eigen::Vector4d RealColVec4d
4D column vector
Definition bitsim_types.h:142
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Definition cart_pole_lqr_mpc.cpp:31
const real_t DT
Definition cart_pole_lqr_mpc.cpp:43
const real_t THETA0
Definition cart_pole_lqr_mpc.cpp:46
Matrix state_weights()
Definition cart_pole_lqr_mpc.cpp:64
const real_t TRACK_BOUND
Definition cart_pole_lqr_mpc.cpp:47
Run simulate(const std::string &name, Controller &&controller)
Definition cart_pole_lqr_mpc.cpp:82
const uint_t HORIZON
Definition cart_pole_lqr_mpc.cpp:48
Matrix input_weights()
Definition cart_pole_lqr_mpc.cpp:71
const real_t X0
Definition cart_pole_lqr_mpc.cpp:45
void print(const Run &run)
Definition cart_pole_lqr_mpc.cpp:101
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
const real_t DURATION
Definition cart_pole_lqr_mpc.cpp:44
cv::Mat draw(const std::vector< Run > &runs, uint_t k, const CartPoleParameters &p)
Definition cart_pole_lqr_mpc.cpp:116
const real_t RECORD_RATE
Definition cart_pole_lqr_mpc.cpp:50
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
const real_t PENALTY
Definition cart_pole_lqr_mpc.cpp:49
Controller controller(const MultiRobotNavigation &env, uint_t robot)
Definition distributed_robot_navigation.cpp:113
json run(const Config &c, real_t learning_rate, const fs::path &dir, bitrl::network::TensorboardServer *tensorboard)
Definition log_experiment.cpp:106
The cart and the pole. The defaults are those of the classic cart-pole of Barto, Sutton and Anderson ...
Definition cart_pole_dynamics.h:18
real_t max_force
the largest push on the cart, either way [N]
Definition cart_pole_dynamics.h:23
Definition cart_pole_lqr_mpc.cpp:54
std::vector< CartPoleState > states
Definition cart_pole_lqr_mpc.cpp:56
real_t max_x
Definition cart_pole_lqr_mpc.cpp:59
bool off_track
Definition cart_pole_lqr_mpc.cpp:60
std::vector< real_t > forces
Definition cart_pole_lqr_mpc.cpp:57
std::string name
Definition cart_pole_lqr_mpc.cpp:55
std::vector< std::vector< real_t > > plans
Definition cart_pole_lqr_mpc.cpp:58