It needs bitsim built with Chrono, Irrlicht and OpenCV.
MCTS finds a good action by trying many sequences of actions ahead. It needs an environment that it can copy and step quickly, from the state the agent is in. The Chrono simulation is neither: one 10 ms step of the robot takes about 7 ms, and its motors, wheels and sensors keep state that Chrono cannot save and restore. A plan of a few hundred sequences, each a few seconds long, would take minutes for every decision.
So MCTS plans in a model of the world, and the robot acts in Chrono, the usual way to use MCTS on a robot:
Every decision MCTS starts again from where Chrono says the robot is, so the errors of the model do not add up.
The robot then drives with the command of the child of the root that the simulations visited most.
The rollout policy matters. With random commands, the rollouts wander, and the returns they give say little about the node they started from. Worse, a rollout that follows the line drives straight into the next box, so staying on the line looks worse than driving away from it: in a first version the robot circled at the start. The rollout policy here, TowardsTheLine, does what a simple controller would. It heads along the track and back to the line, the further from it the more sharply, and when it is within 1 m of a box it heads for a path 0.6 m outside the line instead, to go around it. A fifth of its commands are random, so that the rollouts try other ways too. The policy only guides the rollouts: the tree is free to choose other commands where its simulations rate them better.
On one run the robot went once around the track in 47.7 s of simulation, without touching a box, and was never more than 0.82 m from the line, around the boxes. bitsim's hand written controller takes 59.3 s for the same lap, at the same top speed. Each decision took about 4 ms of planning on a laptop, so the example runs faster than real time without a window:
#include "bitsim/bitsim_config.h"
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChContactMaterialNSC.h>
#include <chrono/physics/ChSystemNSC.h>
#include <chrono_irrlicht/ChVisualSystemIrrlicht.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <optional>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
{
using Point = std::array<real_t, 2>;
const std::string
WINDOW_TITLE =
"Line following with Monte Carlo tree search";
{{0.3, 0.0}, {0.3, 0.8}, {0.3, -0.8}, {0.2, 1.6}, {0.2, -1.6}}};
0.98, 42};
{
const real_t dx = std::max(std::abs(x - box[0]) - h, 0.0);
const real_t dy = std::max(std::abs(y - box[1]) - h, 0.0);
return std::hypot(dx, dy);
}
{
};
{
public:
{
};
const Pose &
pose() const noexcept {
return pose_; }
{
{
pose_.x +=
command.v * std::cos(pose_.heading) * dt;
pose_.y +=
command.v * std::sin(pose_.heading) * dt;
pose_.heading +=
command.omega * dt;
time_step.reward_ -=
LINE_COST * off_line * off_line * dt;
{
time_step.done_ = true;
break;
}
}
return time_step;
}
{
{ return distance_to_box(box, cx, cy) < ROBOT_RADIUS + CLEARANCE; });
}
private:
};
{
const real_t nx = (
TRACK.signed_distance(x + h, y) -
TRACK.signed_distance(x - h, y)) / (2 *
h);
const real_t ny = (
TRACK.signed_distance(x, y + h) -
TRACK.signed_distance(x, y - h)) / (2 *
h);
return std::atan2(nx, -ny);
}
{
{
std::uniform_int_distribution<uint_t> random_command(0,
COMMANDS.size() - 1);
if (std::uniform_real_distribution<real_t>(0.0, 1.0)(generator) <
ROLLOUT_RANDOM)
{
return random_command(generator);
}
}
{
const auto &pose = model.pose();
{ return distance_to_box(box, cx, cy) < DETOUR_NEAR; });
{
if (std::abs(
COMMANDS[c].omega - omega) < std::abs(
COMMANDS[best].omega - omega))
{
best = c;
}
}
return best;
}
};
const std::array<const char *, 5>
COMMAND_NAMES{
"straight",
"left",
"right",
"hard left",
"hard right"};
{
};
template <typename Solver>
{
std::vector<Candidate> result;
const auto root = solver.root();
if (!root || root->total_visits() == 0)
{
return result;
}
for (
uint_t c = 0; c < root->n_children(); ++c)
{
std::shared_ptr<const typename Solver::node_type> node = root->get_child(c);
static_cast<real_t>(node->total_visits()) / root->total_visits(),
{model.pose()}};
while (node && node->total_visits() > 0 && !done)
{
done = ahead.step(node->get_action()).done();
candidate.path.push_back(ahead.pose());
std::shared_ptr<const typename Solver::node_type> next;
for (
uint_t k = 0; k < node->n_children(); ++k)
{
auto child = node->get_child(k);
if (child->total_visits() > 0 &&
(!next || child->total_visits() > next->total_visits()))
{
next = child;
}
}
node = next;
}
while (!done && candidate.path.size() <=
SEARCH.max_depth)
{
candidate.path.push_back(ahead.pose());
}
result.push_back(std::move(candidate));
}
return result;
}
{
}
{
public:
explicit World(
const FloorImage &floor)
{
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);
ground_ = chrono_types::make_shared<chrono::ChBodyEasyBox>(20.0, 20.0, 0.1, 1000.0, true,
true, material);
ground_->SetPos(chrono::ChVector3d(0.0, 0.0, -0.05));
ground_->SetFixed(true);
ground_->GetVisualShape(0)->SetColor(chrono::ChColor(0.45f, 0.45f, 0.42f));
system_.Add(ground_);
{
auto box = chrono_types::make_shared<chrono::ChBodyEasyBox>(
box->SetFixed(true);
box->GetVisualShape(0)->SetColor(chrono::ChColor(0.85f, 0.45f, 0.1f));
system_.Add(box);
obstacles_.push_back(box);
}
contacts_ = std::make_shared<ContactCounter>(obstacles_);
robot_.load(std::filesystem::path(
robot_.set_floor([&floor](
real_t x,
real_t y) {
return floor.reflectance(x, y); });
robot_.add_to_sys(system_);
}
{
touching_ = contacts_->count(system_) > 0;
}
{
texture);
}
real_t time()
const {
return system_.GetChTime(); }
{
const auto axle = robot_.axle_center();
return {axle.x(), axle.y(), robot_.heading()};
}
chrono::ChSystemNSC &
system() {
return system_; }
private:
chrono::ChSystemNSC system_;
std::shared_ptr<chrono::ChBodyEasyBox> ground_;
std::vector<std::shared_ptr<chrono::ChBody>> obstacles_;
std::shared_ptr<ContactCounter> contacts_;
CHRONO_DiffDriveRobot robot_;
bool touching_{false};
};
{
public:
Display(World &world,
const FloorImage &floor,
const std::string &record,
bool follow)
{
const auto texture =
(std::filesystem::temp_directory_path() / "bitrl_mcts_line_following_floor.png")
.string();
floor.write_texture(texture);
world_.show_floor(texture);
vis_.AttachSystem(&world_.system());
vis_.SetWindowSize(1280, 720);
vis_.SetCameraVertical(chrono::CameraVerticalDir::Z);
vis_.Initialize();
vis_.AddCamera({0.0, -3.4, 3.0}, {0.0, -0.1, 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));
}
{
if (!vis_.Run())
{
return false;
}
const auto pose = world_.pose();
trail_.add(pose.x, pose.y);
if (follow_)
{
follow_robot_(pose);
}
vis_.BeginScene();
vis_.Render();
trail_.draw(vis_, chrono::ChColor(0.1f, 0.4f, 0.9f), 3.0);
for (int pass = 0; pass < 2; ++pass)
{
{
const bool is_chosen = c.action == chosen;
if (is_chosen != (pass == 1))
{
continue;
}
const auto colour = is_chosen ? chrono::ChColor(0.1f, 0.85f, 0.2f)
: chrono::ChColor(1.0f, 0.55f, 0.1f);
const real_t thickness = is_chosen ? 4.0 : 1.0 + 3.0 * c.share;
for (std::size_t i = 1; i < c.path.size(); ++i)
{
vis_, chrono::ChVector3d(c.path[i - 1].x, c.path[i - 1].y, 0.06),
chrono::ChVector3d(c.path[i].x, c.path[i].y, 0.06), colour, thickness);
}
}
}
std::ostringstream text;
text << std::fixed << std::setprecision(1) << "t " << world_.time() << " s lap "
<< 100.0 *
lap <<
" % simulations:";
{
text <<
" " <<
COMMAND_NAMES[c.action] <<
" " << std::setprecision(0)
<< 100.0 * c.share << "%" << (c.action == chosen ? "*" : "");
}
vis_.EndScene();
recorder_.record(vis_, world_.time());
return true;
}
private:
void follow_robot_(const Pose &pose)
{
if (!camera_heading_)
{
camera_heading_ = pose.heading;
}
*camera_heading_ += 0.05 * std::remainder(pose.heading - *camera_heading_, 2.0 *
PI);
const real_t c = std::cos(*camera_heading_);
const real_t s = std::sin(*camera_heading_);
vis_.UpdateCamera(
}
World &world_;
chrono::irrlicht::ChVisualSystemIrrlicht vis_;
FrameRecorder recorder_;
Trail trail_;
bool follow_;
std::optional<real_t> camera_heading_;
};
{
};
{
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--render")
{
options.render = true;
}
else if (arg == "--record" && i + 1 < argc)
{
options.record = argv[++i];
options.render = true;
}
else if (arg == "--follow")
{
options.follow = true;
options.render = true;
}
else if (arg == "--time-limit" && i + 1 < argc)
{
options.time_limit = std::stod(argv[++i]);
}
else
{
std::cout << "Usage: mcts_line_following [--render] [--record DIR] [--time-limit S]\n"
<< " --render show the simulation in a window, in real time\n"
<< " --follow show it with a camera that follows the robot\n"
<<
" --record DIR also write the window to DIR, " <<
RECORD_RATE
<< " frames a second\n"
<<
" --time-limit S stop after S seconds of simulation, " <<
TIME_LIMIT
<< " by default" << std::endl;
std::exit(arg == "--help" || arg == "-h" ? 0 : 1);
}
}
return options;
}
{
std::optional<Display> display;
if (options.render)
{
display.emplace(world, floor, options.record, options.follow);
}
std::cout << std::fixed << std::setprecision(2) <<
"Track " <<
TRACK.perimeter()
<<
" m around, " <<
OBSTACLES.size() <<
" boxes on it. MCTS: " <<
SEARCH.n_simulations
<<
" simulations of up to " <<
SEARCH.max_depth <<
" decisions, "
<< " t [s] x [m] y [m] head [deg] line [m] v [m/s] w [rad/s]\n";
std::vector<Candidate> weighed;
bool was_touching = false;
bool completed = false;
const auto wall_start = std::chrono::steady_clock::now();
while (world.time() < options.time_limit)
{
if (world.time() + 1e-9 >= next_decision)
{
const auto start = std::chrono::steady_clock::now();
const auto action = solver.plan(model);
planning_time +=
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - start).count();
n_decisions += 1;
if (display)
{
}
}
world.step(command);
const auto pose = world.pose();
travelled += std::remainder(angle - last_angle, 2.0 *
PI);
last_angle = angle;
max_off_line = std::max(max_off_line,
TRACK.distance(pose.x, pose.y));
if (world.is_touching_a_box() && !was_touching)
{
n_hits += 1;
}
was_touching = world.is_touching_a_box();
if (world.time() + 1e-9 >= next_print)
{
std::cout << std::setw(9) << world.time() << std::setw(8) << pose.x << std::setw(8)
<< pose.y << std::setw(12) << pose.heading * 180.0 /
PI << std::setw(10)
<<
TRACK.distance(pose.x, pose.y) << std::setw(9) <<
command.v
<< std::setw(11) <<
command.omega <<
"\n";
}
if (display && world.time() + 1e-9 >= next_frame)
{
if (!display->show(weighed, chosen, travelled / (2.0 *
PI)))
{
break;
}
const auto wall = std::chrono::steady_clock::now() - wall_start;
const auto ahead = std::chrono::duration<real_t>(world.time()) - wall;
if (ahead.count() > 0.0)
{
std::this_thread::sleep_for(ahead);
}
}
if (travelled >= 2.0 *
PI)
{
completed = true;
break;
}
}
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start).count();
std::cout << "\n";
if (completed)
{
std::cout << "The robot went once around the track in " << world.time()
<< " s of simulation, " << wall << " s of wall time\n";
}
else
{
std::cout <<
"The robot went " << 100.0 * travelled / (2.0 *
PI)
<< " % around the track in " << world.time() << " s of simulation\n";
}
std::cout << "Times it touched a box: " << n_hits
<< ", furthest from the line: " << max_off_line << " m\n"
<< "Decisions: " << n_decisions << ", " << 1000.0 * planning_time / n_decisions
<< " ms of planning each" << std::endl;
return n_hits == 0 ? 0 : 1;
}
}
int main(
int argc,
char **argv)
{
try
{
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
Monte Carlo tree search, with UCB to pick the children (UCT).
Definition mc_tree_search_solver.h:115
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
An image of the floor, centred on the world origin.
Definition downward_camera.h:31
A closed track in the plane: a rectangle centred on the origin with its sides along x and y,...
Definition rounded_rectangle.h:20
real_t signed_distance(real_t x, real_t y) const
The signed distance from (x, y) to the track [m]: negative inside the shape, positive outside....
Definition rounded_rectangle.cpp:24
real_t distance(real_t x, real_t y) const
The distance from (x, y) to the track [m], from inside or outside.
Definition rounded_rectangle.cpp:35
Writes the window to dir/frame_00000.png, frame_00001.png, ..., rate times a second of simulation,...
Definition irrlicht_scene.h:121
A path drawn as a line: in the plane, just above the floor, where a robot has been or where it thinks...
Definition irrlicht_scene.h:48
Definition mcts_line_following.cpp:434
Display(World &world, const FloorImage &floor, const std::string &record, bool follow)
Definition mcts_line_following.cpp:436
bool show(const std::vector< Candidate > &candidates, uint_t chosen, real_t lap)
Definition mcts_line_following.cpp:459
static FloorImage draw(real_t width, real_t height, real_t metres_per_pixel, const std::function< bool(real_t, real_t)> &is_ink, uchar paper=235, uchar ink=25)
Draw a floor: a grey picture of width x height metres of paper, with ink wherever is_ink(x,...
Definition downward_camera.cpp:32
Definition mcts_line_following.cpp:159
uint_t n_actions() const noexcept
Definition mcts_line_following.cpp:174
TimeStep step(action_type action)
Definition mcts_line_following.cpp:178
bool touches_a_box() const
Definition mcts_line_following.cpp:207
TrackModel(const Pose &pose)
Definition mcts_line_following.cpp:172
const Pose & pose() const noexcept
Definition mcts_line_following.cpp:175
Pose state_type
Definition mcts_line_following.cpp:162
uint_t action_type
Definition mcts_line_following.cpp:161
Definition mcts_line_following.cpp:358
real_t time() const
Definition mcts_line_following.cpp:411
chrono::ChSystemNSC & system()
Definition mcts_line_following.cpp:418
bool is_touching_a_box() const
Definition mcts_line_following.cpp:417
World(const FloorImage &floor)
Definition mcts_line_following.cpp:360
Pose pose() const
Definition mcts_line_following.cpp:412
void step(const Command &command)
Definition mcts_line_following.cpp:397
void show_floor(const std::string &texture)
Definition mcts_line_following.cpp:405
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
std::filesystem::path build_robot_file_path(const std::string filename)
Definition bitsim_consts.h:52
void add_floor_texture(chrono::ChBody &ground, real_t width, real_t height, real_t z, const std::string &texture)
Put a picture on the ground: a rectangle of width x height [m] centred on the origin of the world,...
Definition irrlicht_scene.cpp:22
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
std::map< std::string, std::any > command(real_t v, real_t w)
Definition diff_drive_kinematics.cpp:29
EKFSlam::Pose Pose
Definition ekf_slam.cpp:57
real_t h(real_t x)
Definition importance_sampling.cpp:39
Definition mcts_line_following.cpp:56
std::array< real_t, 2 > Point
Definition mcts_line_following.cpp:69
const real_t HIT_COST
Definition mcts_line_following.cpp:114
const std::vector< Point > OBSTACLES
Definition mcts_line_following.cpp:95
const real_t ROLLOUT_GAIN
Definition mcts_line_following.cpp:117
const Point START
Definition mcts_line_following.cpp:98
const real_t OBSTACLE_SIZE
Definition mcts_line_following.cpp:96
const real_t LINE_COST
Definition mcts_line_following.cpp:113
const real_t METRES_PER_PIXEL
Definition mcts_line_following.cpp:94
const real_t METRES_PER_RADIAN
Definition mcts_line_following.cpp:130
const real_t TRACK_HALF_LENGTH
Definition mcts_line_following.cpp:88
const real_t PRINT_PERIOD
Definition mcts_line_following.cpp:78
const real_t FLOOR_WIDTH
Definition mcts_line_following.cpp:92
const real_t FOLLOW_AHEAD
Definition mcts_line_following.cpp:85
const real_t FOLLOW_HEIGHT
Definition mcts_line_following.cpp:84
const real_t ROBOT_RADIUS
Definition mcts_line_following.cpp:104
const real_t FLOOR_HEIGHT
Definition mcts_line_following.cpp:93
const RoundedRectangle TRACK(TRACK_HALF_LENGTH, TRACK_HALF_WIDTH, TRACK_CORNER_RADIUS)
const uint_t MODEL_SUBSTEPS
Definition mcts_line_following.cpp:106
std::vector< Candidate > candidates(const Solver &solver, const TrackModel &model)
Definition mcts_line_following.cpp:298
bitsim::control::DiffDriveCommand Command
Definition mcts_line_following.cpp:68
const real_t CHASSIS_AHEAD
Definition mcts_line_following.cpp:103
const real_t CLEARANCE
Definition mcts_line_following.cpp:105
const std::array< Command, 5 > COMMANDS
Definition mcts_line_following.cpp:109
const real_t PI
Definition mcts_line_following.cpp:72
FloorImage draw_floor()
Definition mcts_line_following.cpp:350
const real_t TIME_LIMIT
Definition mcts_line_following.cpp:77
real_t distance_to_box(const Point &box, real_t x, real_t y)
Definition mcts_line_following.cpp:135
const real_t STEP_SIZE
Definition mcts_line_following.cpp:75
int run(const Options &options)
Definition mcts_line_following.cpp:592
const std::array< const char *, 5 > COMMAND_NAMES
Definition mcts_line_following.cpp:280
real_t angle_around_track(real_t x, real_t y)
Definition mcts_line_following.cpp:132
const real_t DECISION_PERIOD
Definition mcts_line_following.cpp:76
const real_t ROLLOUT_APPROACH
Definition mcts_line_following.cpp:118
const real_t RECORD_RATE
Definition mcts_line_following.cpp:80
const real_t FOLLOW_BEHIND
Definition mcts_line_following.cpp:83
const real_t DETOUR_OFFSET
Definition mcts_line_following.cpp:121
const real_t RENDER_RATE
Definition mcts_line_following.cpp:79
const real_t ROLLOUT_RANDOM
Definition mcts_line_following.cpp:119
const std::string WINDOW_TITLE
Definition mcts_line_following.cpp:71
const real_t DETOUR_NEAR
Definition mcts_line_following.cpp:120
const MCTSConfig SEARCH
Definition mcts_line_following.cpp:124
const real_t LINE_WIDTH
Definition mcts_line_following.cpp:91
const real_t OBSTACLE_HEIGHT
Definition mcts_line_following.cpp:97
const real_t TRACK_CORNER_RADIUS
Definition mcts_line_following.cpp:90
Options parse(int argc, char **argv)
Definition mcts_line_following.cpp:553
const real_t TRACK_HALF_WIDTH
Definition mcts_line_following.cpp:89
real_t track_direction(real_t x, real_t y)
Definition mcts_line_following.cpp:222
End lap(uint_t run)
Definition parallel_monte_carlo.cpp:57
dict action
Definition play.py:46
bool done
Definition play.py:40
The configuration of MCTSSolver.
Definition mc_tree_search_solver.h:61
What a differential drive robot is told to do: drive at v [m/s] and turn at omega [rad/s],...
Definition infrared_line_follower.h:22
Definition mcts_line_following.cpp:291
std::vector< Pose > path
Definition mcts_line_following.cpp:294
uint_t action
Definition mcts_line_following.cpp:292
real_t share
Definition mcts_line_following.cpp:293
Definition mcts_line_following.cpp:546
std::string record
Definition mcts_line_following.cpp:548
bool follow
Definition mcts_line_following.cpp:550
real_t time_limit
Definition mcts_line_following.cpp:549
bool render
Definition mcts_line_following.cpp:547
Definition mcts_line_following.cpp:148
real_t heading
Definition mcts_line_following.cpp:151
real_t x
Definition mcts_line_following.cpp:149
real_t y
Definition mcts_line_following.cpp:150
Definition mcts_line_following.cpp:238
static uint_t steer(const TrackModel &model)
Definition mcts_line_following.cpp:250
uint_t operator()(const TrackModel &model, std::mt19937 &generator) const
Definition mcts_line_following.cpp:239
Definition mcts_line_following.cpp:165
bool done_
Definition mcts_line_following.cpp:167
real_t reward_
Definition mcts_line_following.cpp:166
bool done() const noexcept
Definition mcts_line_following.cpp:169
real_t reward() const noexcept
Definition mcts_line_following.cpp:168