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.
Nothing beyond bitsim itself. To make the pictures of the GIF, bitsim built with OpenCV. See Installing bitsim.
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.
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:
\(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 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:
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.
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.
#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>
{
struct Run
{
std::vector<CartPoleState>
states;
std::vector<std::vector<real_t>>
plans;
};
{
q << 1.0, 0.1, 10.0, 0.1;
return q.asDiagonal().toDenseMatrix();
}
{
return x;
}
template <
typename Controller>
Run simulate(
const std::string &name, Controller &&controller)
{
for (
uint_t k = 0; k <= steps; ++k)
{
run.forces.push_back(force);
run.off_track =
run.off_track || cart_pole.off_track();
cart_pole.step(force,
DT);
}
}
{
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(
" 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
{
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));
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 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;
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::Scalar(120, 120, 220), 1);
}
{
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);
}
}
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);
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",
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);
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++));
}
std::cout << "Wrote " << n << " pictures to " << directory << std::endl;
}
#endif
}
int main(
int argc,
char **argv)
{
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;
}
}
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),
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));
mpc.set_state_bounds(x_min, x_max,
PENALTY);
{ return lqr_controller.control(x)[0]; });
const Run mpc_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;
});
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
}
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