bitsim built with Chrono; to see it, or to make the pictures of the GIF, with Irrlicht too. See Installing bitsim.
The figure of eight is \(x = 1.2 \sin\varphi\), \(y = 0.6 \sin 2\varphi\), once round in 11 s. Its velocity gives the heading and the speed along it, and its curvature the turning rate; with the axle of 0.4 m, the speeds of the two wheels that drive along it follow. Both robots start on the path and drive two laps.
Both controllers plan with the same model of the robot, over one control period of 0.05 s. Its state is the pose, \(x, y, \theta\), and the speeds the two wheels roll at; its inputs are the speeds the motors are told. The motors reach a new speed with a lag, and the model has it as a time constant \(\tau = 0.4\) s:
with \(c\) the command and \(w\) the speed of a wheel, and the robot drives with what its wheels do, \(v = (w_l + w_r) / 2\) and \(\omega = (w_r - w_l) / L\).
The model is not linear: the robot moves along \(\cos\theta\) and \(\sin\theta\). At every step the example linearises it along where the robot is expected to go, the model run from the pose now with the inputs the last plan had for the coming steps, and gives LinearMPC one linear model per step of the horizon, with its affine term. That is successive linearisation.
Both plan the next 20 steps, 1 s, and minimise how far the robot is from the path and how much the commands differ from those of the path, with the same weights. MPC also has the bound \(|c| \le 0.8\) m/s on each command:
Without the bound, MPC is a linear quadratic regulator along the path, over a finite horizon. Its commands can be more than 0.8 m/s, and the motors would not do them, so they are clipped, each wheel on its own.
The example exits with an error unless MPC stays within 0.15 m of the path, closer than the clipped LQR, so it runs as a test too, with one lap.
Where the path is too fast, the clipped LQR asks the outer wheel for more than it can do and gets 0.8 m/s, while the inner wheel gets what it asked for. The ratio of the two, which sets how sharply the robot turns, is no longer the one it planned, and the robot turns too little: it swings wide, 0.36 m off at worst, and cuts back across. MPC plans with the bound: it slows down where it has to and keeps turning, and stays within 0.07 m of the path.
Two things about the model mattered more than anything else here.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_CHRONO
#ifdef BITSIM_IRRLICHT
#include <chrono_irrlicht/ChVisualSystemIrrlicht.h>
#endif
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChContactMaterialNSC.h>
#include <chrono/physics/ChSystemNSC.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <limits>
#include <optional>
#include <string>
#include <thread>
#include <vector>
{
struct Path
{
{
return {
a * std::sin(
phi(t)),
b * std::sin(2.0 *
phi(t))};
}
{
return {
a * std::cos(
phi(t)) *
dphi(), 2.0 *
b * std::cos(2.0 *
phi(t)) *
dphi()};
}
{
return {-
a * std::sin(
phi(t)) * w * w, -4.0 *
b * std::sin(2.0 *
phi(t)) * w * w};
}
{
x << p[0], p[1], std::atan2(v[1], v[0]);
return x;
}
{
const real_t speed = std::hypot(v[0], v[1]);
const real_t omega = (v[0] * acc[1] - v[1] * acc[0]) / (speed * speed);
u << speed - 0.5 * axle * omega, speed + 0.5 * axle * omega;
return u;
}
};
{
return reference + std::remainder(angle - reference, 2.0 *
PI);
}
{
};
{
const real_t v = 0.5 * (x[3] + x[4]);
const real_t omega = (x[4] - x[3]) / axle;
f << x[0] + dt * v * std::cos(x[2]), x[1] + dt * v * std::sin(x[2]), x[2] + dt * omega,
x[3] + dt * (u[0] - x[3]) /
TAU, x[4] + dt * (u[1] - x[4]) /
TAU;
return f;
}
{
const real_t v = 0.5 * (x[3] + x[4]);
step.A(0, 2) = -dt * v * std::sin(th);
step.A(1, 2) = dt * v * std::cos(th);
step.A(0, 3) =
step.A(0, 4) = 0.5 * dt * std::cos(th);
step.A(1, 3) =
step.A(1, 4) = 0.5 * dt * std::sin(th);
step.A(2, 3) = -dt / axle;
step.A(2, 4) = dt / axle;
}
{
public:
{
q << 20.0, 20.0, 2.0, 0.1, 0.1;
mpc_.set_weights(q.asDiagonal().toDenseMatrix(), 0.5 * Matrix::Identity(2, 2));
if (limited_)
{
}
}
{
std::vector<Vector> u_nominal;
{
if (last_inputs_.size() ==
HORIZON)
{
u_nominal.push_back(last_inputs_[std::min<uint_t>(k + 1,
HORIZON - 1)]);
}
else
{
}
}
std::vector<Matrix> As;
std::vector<Matrix> Bs;
std::vector<Vector> cs;
std::vector<Vector> x_ref;
std::vector<Vector> u_ref;
{
x_nominal =
model_step(x_nominal, u_nominal[k], axle_);
next << pose[0], pose[1],
near(pose[2], x_nominal[2]), wheels[0], wheels[1];
x_ref.push_back(next);
u_ref.push_back(path.wheels(tk, axle_));
}
mpc_.set_model(As, Bs, cs);
mpc_.set_reference(x_ref, u_ref);
const Vector u = mpc_.solve(x);
last_inputs_ = mpc_.predicted_inputs();
plan_.clear();
for (const auto &xp : mpc_.predicted_states())
{
plan_.push_back({xp[0], xp[1]});
}
}
const std::vector<std::array<real_t, 2>> &
plan()
const {
return plan_; }
bool limited()
const {
return limited_; }
const LinearMPC &
mpc()
const {
return mpc_; }
private:
bool limited_;
LinearMPC mpc_;
std::vector<Vector> last_inputs_;
std::vector<std::array<real_t, 2>> plan_;
};
{
public:
{
system_.SetGravitationalAcceleration(
system_.SetCollisionSystemType(chrono::ChCollisionSystem::Type::BULLET);
system_.SetSolverType(chrono::ChSolver::Type::BARZILAIBORWEIN);
system_.GetSolver()->AsIterative()->SetMaxIterations(40);
auto material = chrono_types::make_shared<chrono::ChContactMaterialNSC>();
material->SetFriction(0.8f);
material->SetRestitution(0.1f);
auto ground = chrono_types::make_shared<chrono::ChBodyEasyBox>(12.0, 6.0, 0.1, 1000.0, true,
true, material);
ground->SetPos(chrono::ChVector3d(0.5 *
SEPARATION, 0.0, -0.05));
ground->SetFixed(true);
ground->GetVisualShape(0)->SetColor(chrono::ChColor(0.45f, 0.45f, 0.42f));
system_.Add(ground);
for (
uint_t i = 0; i < 2; ++i)
{
robots_[i].load(std::filesystem::path(
ROBOT_FILE));
}
}
{
robots_[i].set_world_pose(x +
offset(i), y, yaw);
}
{
for (
auto &
robot : robots_)
{
robot.add_to_sys(system_);
}
}
{
const auto c = robots_[i].axle_center();
x << c.x() -
offset(i), c.y(), robots_[i].heading();
return x;
}
{
const real_t r = robots_[i].get_data().wheel_radius;
return x;
}
{
const real_t r = robots_[i].get_data().wheel_radius;
}
{
for (
auto &
robot : robots_)
{
}
}
real_t time()
const {
return system_.GetChTime(); }
chrono::ChSystemNSC &
system() {
return system_; }
const CHRONO_DiffDriveRobot &
robot(
uint_t i)
const {
return robots_[i]; }
private:
chrono::ChSystemNSC system_;
std::array<CHRONO_DiffDriveRobot, 2> robots_;
};
{
real_t best = std::numeric_limits<real_t>::infinity();
for (int k = 0; k < 800; ++k)
{
const auto p = path.point(
LAP_TIME * k / 800.0);
best = std::min(best, std::hypot(x[0] - p[0], x[1] - p[1]));
}
return best;
}
#ifdef BITSIM_IRRLICHT
{
public:
Display(World &world,
const Path &path,
const std::string &record)
{
for (int k = 0; k <= 400; ++k)
{
const auto p = path.point(
LAP_TIME * k / 400.0);
figure_.push_back({p[0], p[1]});
}
vis_.AttachSystem(&world_.system());
vis_.SetWindowSize(1280, 720);
vis_.SetWindowTitle("Path following with model predictive control");
vis_.SetCameraVertical(chrono::CameraVerticalDir::Z);
vis_.Initialize();
vis_.AddCamera({0.5 * SEPARATION, -2.4, 2.6}, {0.5 * SEPARATION, 0.15, 0.0});
vis_.AddLightDirectional(60.0, 60.0, chrono::ChColor(0.45f, 0.45f, 0.45f),
chrono::ChColor(0.05f, 0.05f, 0.05f),
chrono::ChColor(0.55f, 0.55f, 0.55f));
}
bool show(
const std::array<Follower *, 2> &followers,
const Path &path,
const std::array<real_t, 2> &errors)
{
if (!vis_.Run())
{
return false;
}
for (
uint_t i = 0; i < 2; ++i)
{
const Vector x = world_.pose(i);
}
vis_.BeginScene();
vis_.Render();
const std::array<chrono::ChColor, 2> colours{chrono::ChColor(1.0f, 0.85f, 0.2f),
chrono::ChColor(0.3f, 0.7f, 1.0f)};
for (
uint_t i = 0; i < 2; ++i)
{
for (std::size_t k = 1; k < figure_.size(); ++k)
{
vis_, {figure_[k - 1][0] + dx, figure_[k - 1][1], 0.004},
{figure_[k][0] + dx, figure_[k][1], 0.004}, chrono::ChColor(0.8f, 0.8f, 0.8f),
2.0);
}
for (std::size_t k = 1; k < trails_[i].size(); ++k)
{
colours[i], 3.0);
}
const auto &plan = followers[i]->plan();
for (std::size_t k = 1; k < plan.size(); ++k)
{
vis_, {plan[k - 1][0] + dx, plan[k - 1][1], 0.02},
{plan[k][0] + dx, plan[k][1], 0.02}, chrono::ChColor(0.9f, 0.3f, 0.9f), 2.0);
}
const auto target = path.point(world_.time());
{target[0] + dx, target[1], 0.25},
chrono::ChColor(0.9f, 0.1f, 0.1f), 3.0);
}
char text[200];
std::snprintf(text, sizeof(text),
"t %5.1f s left: clipped LQR, %.2f m off the path right: MPC, %.2f m "
"off the path wheels at most %.1f m/s magenta: the plans",
vis_.EndScene();
recorder_.record(vis_, world_.time());
return true;
}
private:
World &world_;
chrono::irrlicht::ChVisualSystemIrrlicht vis_;
bitsim::utils::render::FrameRecorder recorder_;
std::vector<std::array<real_t, 2>> figure_;
std::array<std::vector<chrono::ChVector3d>, 2> trails_;
};
#endif
{
};
{
const real_t axle = world.robot(0).get_data().axle_length;
for (
uint_t i = 0; i < 2; ++i)
{
world.place(i, start[0], start[1], start[2]);
}
world.add_robots();
const std::array<Follower *, 2> followers{&clipped, &mpc};
const std::array<const char *, 2> names{"clipped LQR", "MPC"};
for (int k = 0; k < 1600; ++k)
{
peak = std::max(peak, u.cwiseAbs().maxCoeff());
}
std::printf("Robot: %s, axle %.2f m; along the path a wheel rolls at %.2f m/s at most, the "
"limit is %.1f m/s\n\n",
#ifdef BITSIM_IRRLICHT
std::optional<Display> display;
if (options.render || !options.record.empty())
{
display.emplace(world, path, options.record);
}
#else
if (options.render || !options.record.empty())
{
std::cerr << "--render and --record need bitsim built with Irrlicht\n";
return 1;
}
#endif
std::printf(" time [s] clipped LQR: off the path [m] MPC: off the path [m]\n");
std::array<real_t, 2> errors{0.0, 0.0};
std::array<real_t, 2> sum_sq{0.0, 0.0};
std::array<real_t, 2> worst_after{0.0, 0.0};
std::array<Vector, 2> wheels{Vector::Zero(2), Vector::Zero(2)};
const auto wall_start = std::chrono::steady_clock::now();
{
const real_t t = world.time();
if (t >= next_control - 1e-9)
{
for (
uint_t i = 0; i < 2; ++i)
{
const Vector x = world.pose(i);
wheels[i] = followers[i]->control(path, t, world.state(i));
world.set_wheels(i, wheels[i]);
sum_sq[i] += errors[i] * errors[i];
{
worst_after[i] = std::max(worst_after[i], errors[i]);
}
}
unsolved += mpc.mpc().status() == LinearMPC::QPStatus::SOLVED ? 0 : 1;
++n_samples;
}
if (t >= next_print - 1e-9)
{
std::printf(" %8.1f %29.3f %21.3f\n", t, errors[0], errors[1]);
}
world.step();
#ifdef BITSIM_IRRLICHT
if (display && world.time() >= next_frame - 1e-9)
{
if (!display->show(followers, path, errors))
{
return 0;
}
if (options.render)
{
world.time() -
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start)
.count();
if (ahead > 0.0)
{
std::this_thread::sleep_for(std::chrono::duration<real_t>(ahead));
}
}
}
#else
(void)next_frame;
(void)wall_start;
#endif
}
std::printf(
"\n%-12s RMS off the path [m] worst after the first %.0f s [m]\n",
"",
SETTLE);
for (
uint_t i = 0; i < 2; ++i)
{
std::printf("%-12s %20.3f %30.3f\n", names[i], std::sqrt(sum_sq[i] / n_samples),
worst_after[i]);
}
std::printf("\nMPC solved %u QPs, %u of them not to the tolerance\n",
static_cast<unsigned>(n_samples), static_cast<unsigned>(unsolved));
return (worst_after[1] < 0.15 && worst_after[1] < worst_after[0]) ? 0 : 1;
}
}
int main(
int argc,
char **argv)
{
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--render")
{
}
else if (arg == "--record" && i + 1 < argc)
{
}
else if (arg == "--laps" && i + 1 < argc)
{
options.
laps = std::max(1, std::atoi(argv[++i]));
}
else
{
std::cerr << "Usage: diff_drive_mpc [--render] [--record DIR] [--laps N]\n";
return 1;
}
}
}
#else
#include <iostream>
{
std::cout << "This example needs bitsim built with Chrono\n";
return 0;
}
#endif
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Model predictive control with a linear model, a quadratic cost and bounds on the inputs and the state...
Definition linear_mpc.h:46
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
@ LEFT
Definition diff_drive_robot.h:61
@ RIGHT
Definition diff_drive_robot.h:62
Definition diff_drive_mpc.cpp:361
Display(World &world, const Path &path, const std::string &record)
Definition diff_drive_mpc.cpp:363
bool show(const std::array< Follower *, 2 > &followers, const Path &path, const std::array< real_t, 2 > &errors)
Definition diff_drive_mpc.cpp:383
Definition diff_drive_mpc.cpp:173
Follower(bool limited, real_t axle)
Definition diff_drive_mpc.cpp:175
Vector control(const Path &path, real_t t, const Vector &x)
Definition diff_drive_mpc.cpp:189
bool limited() const
Definition diff_drive_mpc.cpp:247
const LinearMPC & mpc() const
Definition diff_drive_mpc.cpp:248
const std::vector< std::array< real_t, 2 > > & plan() const
Definition diff_drive_mpc.cpp:246
Definition diff_drive_mpc.cpp:260
real_t time() const
Definition diff_drive_mpc.cpp:338
void set_wheels(uint_t i, const Vector &u)
Definition diff_drive_mpc.cpp:322
Vector pose(uint_t i) const
Definition diff_drive_mpc.cpp:303
World()
Definition diff_drive_mpc.cpp:262
const CHRONO_DiffDriveRobot & robot(uint_t i) const
Definition diff_drive_mpc.cpp:340
static real_t offset(uint_t i)
Definition diff_drive_mpc.cpp:300
Vector state(uint_t i) const
Definition diff_drive_mpc.cpp:312
chrono::ChSystemNSC & system()
Definition diff_drive_mpc.cpp:339
void place(uint_t i, real_t x, real_t y, real_t yaw)
Definition diff_drive_mpc.cpp:287
void add_robots()
Definition diff_drive_mpc.cpp:292
void step()
Definition diff_drive_mpc.cpp:329
int main()
Definition discounted_returns.cpp:19
Pieces of an Irrlicht window for a robot simulation: a texture on the floor, a path drawn behind a ro...
const real_t G
Acceleration due to gravity m/secs.
Definition bitsim_consts.h:68
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
const std::string ROBOTS_DIR
Path to robots definitions.
Definition bitsim_consts.h:42
RealMat Matrix
The matrices of the linear models and the controllers.
Definition lqr.h:20
RealColVec Vector
The vectors of the linear models and the controllers: states, inputs.
Definition lqr.h:23
void irr_draw_line(chrono::irrlicht::ChVisualSystemIrrlicht &vis, const chrono::ChVector3d &start, const chrono::ChVector3d &end, const chrono::ChColor &color, real_t thickness)
Definition irrlicht_utils.cpp:19
void draw_status_bar(chrono::irrlicht::ChVisualSystemIrrlicht &vis, const std::string &text)
Write text on a light bar along the bottom of the window. Call this between Render() and EndScene().
Definition irrlicht_scene.cpp:151
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
Definition diff_drive_mpc.cpp:47
const real_t RECORD_RATE
Definition diff_drive_mpc.cpp:68
real_t distance_to_path(const Path &path, const Vector &x)
Definition diff_drive_mpc.cpp:348
LinearStep linearise(const Vector &x, const Vector &u, real_t axle)
Definition diff_drive_mpc.cpp:151
const real_t STEP_SIZE
Definition diff_drive_mpc.cpp:58
const real_t PRINT_PERIOD
Definition diff_drive_mpc.cpp:66
int run(const Options &options)
Definition diff_drive_mpc.cpp:456
const real_t RENDER_RATE
Definition diff_drive_mpc.cpp:67
const uint_t HORIZON
Definition diff_drive_mpc.cpp:60
const real_t LAP_TIME
Definition diff_drive_mpc.cpp:63
const real_t MAX_WHEEL_SPEED
Definition diff_drive_mpc.cpp:61
const real_t TAU
Definition diff_drive_mpc.cpp:62
const real_t PI
Definition diff_drive_mpc.cpp:56
Vector model_step(const Vector &x, const Vector &u, real_t axle)
Definition diff_drive_mpc.cpp:140
const real_t CONTROL_PERIOD
Definition diff_drive_mpc.cpp:59
const real_t SETTLE
Definition diff_drive_mpc.cpp:64
const real_t SEPARATION
Definition diff_drive_mpc.cpp:65
const std::string ROBOT_FILE
Definition diff_drive_mpc.cpp:57
real_t near(real_t angle, real_t reference)
Definition diff_drive_mpc.cpp:120
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Definition diff_drive_mpc.cpp:134
Matrix A
Definition diff_drive_mpc.cpp:135
Matrix B
Definition diff_drive_mpc.cpp:136
Vector c
Definition diff_drive_mpc.cpp:137
Definition diff_drive_mpc.cpp:450
bool render
Definition diff_drive_mpc.cpp:451
std::string record
Definition diff_drive_mpc.cpp:452
int laps
Definition diff_drive_mpc.cpp:453
Definition diff_drive_mpc.cpp:72
Vector state(real_t t) const
Definition diff_drive_mpc.cpp:96
real_t phi(real_t t) const
Definition diff_drive_mpc.cpp:76
std::array< real_t, 2 > acceleration(real_t t) const
Definition diff_drive_mpc.cpp:89
std::array< real_t, 2 > velocity(real_t t) const
Definition diff_drive_mpc.cpp:84
std::array< real_t, 2 > point(real_t t) const
Definition diff_drive_mpc.cpp:79
real_t a
Definition diff_drive_mpc.cpp:73
real_t b
Definition diff_drive_mpc.cpp:74
real_t dphi() const
Definition diff_drive_mpc.cpp:77
Vector wheels(real_t t, real_t axle) const
Definition diff_drive_mpc.cpp:107