bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Following a line with Monte Carlo tree search

bitsim's line_following_infrared_sonar example drives its differential drive robot around a track, a dark line on light paper with two boxes on it, with a controller written by hand: it follows the line with three infrared elements, and when its sonar sees a box close ahead, it turns away, drives an arc around the box and finds the line again. This example drives the same robot around the same track with no such rules. Every 0.2 s it plans with Monte Carlo tree search (MCTS) and drives with the command the plan starts with.

It needs bitsim built with Chrono, Irrlicht and OpenCV.

Planning in a model, acting in Chrono

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:

  • The model, TrackModel, is a kinematic robot: a point that moves with the commanded speed and turns with the commanded turn rate. It is on the same track, with the same boxes. In it the robot is a circle of 0.3 m radius around the centre of its chassis, which covers the chassis and the wheels, and it keeps 5 cm more from the boxes, for the error of the model.
  • The robot is bitsim's Chrono robot, with its motors, wheels and caster. It does not do exactly what the model predicts: for one, its motors take time to reach a new speed.

Every decision MCTS starts again from where Chrono says the robot is, so the errors of the model do not add up.

The decisions and the rewards

The robot chooses one of five commands, for the next 0.2 s:

Command Speed [m/s] Turn rate [rad/s]
straight 0.3 0
turn left 0.3 0.8
turn right 0.3 -0.8
turn hard left 0.2 1.6
turn hard right 0.2 -1.6

The model rewards every step with

  • the progress along the track, in metres: the change of the angle of the robot around the centre of the track, which goes once around the centre, times the length of the track per radian;
  • minus 0.5 for every square metre away from the line and second;
  • minus 10 for touching a box, which ends the episode.

The search

MCTSSolver runs 400 simulations for every decision, each looking up to 25 decisions, 5 s, ahead, with \(\gamma = 0.98\). Every simulation copies the model and

  1. walks down the tree of the sequences it tried, always to the child with the largest upper confidence bound, \(\bar{G} + c \sqrt{\ln N_{parent} / N}\), with \(c = 0.5\), until it reaches a node with a child it has not tried;
  2. tries that child;
  3. goes on with the rollout policy to the end of the 5 s;
  4. adds to every node it went through the reward of the step into the node and the discounted return after it.

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.

The results

The first 20 s at twice real speed, with the camera following the robot. Blue is the path of the robot. At every decision there is a path for each of the five commands: where the model expects the command to lead, along the most visited branch of the tree below it and then the rollout policy, to the end of the 5 s the search looks ahead. Green is the command MCTS chose; the other paths are orange, wider the more of the simulations started with their command.

One lap at twice real speed.

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:

./mcts_line_following

With --render it shows the run in a window, drawn as in the pictures above, with the share of the simulations that started with each command in the bar at the bottom; the star marks the command MCTS chose. --follow shows it with a camera that follows the robot. --record DIR also writes the window to DIR, ten frames a second of simulation, and --time-limit S stops after S seconds of simulation.

The driver code

// Following a line and going around boxes with Monte Carlo tree search
//
// The differential drive robot of bitsim drives around the track of bitsim's
// line_following_infrared_sonar example: a dark line on light paper, with two
// boxes on it. There it follows the line with a hand written controller. Here
// it plans: every DECISION_PERIOD seconds, Monte Carlo tree search tries
// thousands of sequences of commands in a fast model of the track, and the
// robot drives with the first command of the best one.
//
// The model is a kinematic robot, a point that moves with the commanded speed
// and turn rate, on the same track with the same boxes. It rewards progress
// around the track, costs a little for every metre away from the line, and a
// lot for touching a box. The robot itself is the Chrono robot, with its motors
// and wheels, so it does not do exactly what the model says. MCTS plans again
// from where Chrono says the robot is, at every decision.
//
// Usage: mcts_line_following [--render] [--follow] [--record DIR] [--time-limit SECONDS]
#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";
// The simulation
const real_t STEP_SIZE = 0.01; // [s] of Chrono
const real_t DECISION_PERIOD = 0.2; // [s] between two plans
const real_t TIME_LIMIT = 150.0; // [s]
const real_t PRINT_PERIOD = 2.0; // [s]
const real_t RENDER_RATE = 30.0; // [frames/s] of simulation in the window
const real_t RECORD_RATE = 10.0; // [frames/s] of simulation written by --record
// --follow: where the camera is, from the robot
const real_t FOLLOW_BEHIND = 2.6; // [m]
const real_t FOLLOW_HEIGHT = 2.4; // [m]
const real_t FOLLOW_AHEAD = 1.5; // [m] where it looks
// The track and the boxes, as in bitsim's line_following_infrared_sonar
const real_t TRACK_HALF_LENGTH = 2.2; // [m] along x, to the centre of the line
const real_t TRACK_HALF_WIDTH = 1.4; // [m] along y
const real_t TRACK_CORNER_RADIUS = 0.7; // [m]
const real_t LINE_WIDTH = 0.05; // [m]
const real_t FLOOR_WIDTH = 5.6; // [m] the paper, along x
const real_t FLOOR_HEIGHT = 4.6; // [m] along y
const real_t METRES_PER_PIXEL = 0.005; // of the picture of the paper
const std::vector<Point> OBSTACLES{{0.0, -TRACK_HALF_WIDTH}, {-0.2, TRACK_HALF_WIDTH}};
const real_t OBSTACLE_SIZE = 0.3; // [m] each side of its base
const real_t OBSTACLE_HEIGHT = 0.4; // [m]
// The robot in the model: a circle around the centre of the chassis, which is
// CHASSIS_AHEAD in front of the axle. It covers the chassis and the wheels
const real_t CHASSIS_AHEAD = 0.1; // [m]
const real_t ROBOT_RADIUS = 0.3; // [m]
const real_t CLEARANCE = 0.05; // [m] the model keeps from a box, for the error of the model
const uint_t MODEL_SUBSTEPS = 4; // per decision
// What the robot can do: drive straight, turn gently or turn hard, both ways
const std::array<Command, 5> COMMANDS{
{{0.3, 0.0}, {0.3, 0.8}, {0.3, -0.8}, {0.2, 1.6}, {0.2, -1.6}}};
// The rewards of the model
const real_t LINE_COST = 0.5; // per square metre from the line and second
const real_t HIT_COST = 10.0; // for touching a box, which ends the episode
// The rollouts steer towards the line, and take a random command now and then
const real_t ROLLOUT_GAIN = 2.0; // [rad/s per rad] of heading error
const real_t ROLLOUT_APPROACH = 2.0; // [1/m] how sharply to head back to the line
const real_t ROLLOUT_RANDOM = 0.2; // the share of random commands
const real_t DETOUR_NEAR = 1.0; // [m] closer than this to a box, go around it
const real_t DETOUR_OFFSET = 0.6; // [m] outside the line, while going around
// The search
const MCTSConfig SEARCH{/*n_simulations*/ 400, /*max_depth*/ 25, /*temperature*/ 0.5,
/*gamma*/ 0.98, /*seed*/ 42};
// The track goes around its centre, so the angle of the robot around it
// measures how far along the track it is; one lap is 2 pi. This turns it into
// metres along the line
const real_t METRES_PER_RADIAN = TRACK.perimeter() / (2.0 * PI);
real_t angle_around_track(real_t x, real_t y) { return std::atan2(y, x); }
// The distance from a point to the base of a box
{
const real_t h = 0.5 * OBSTACLE_SIZE;
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);
}
// ---------------------------------------------------------------------------
// The model MCTS plans in
// ---------------------------------------------------------------------------
struct Pose
{
real_t x{0.0};
real_t y{0.0};
};
{
public:
typedef Pose state_type;
struct TimeStep
{
bool done_{false};
real_t reward() const noexcept { return reward_; }
bool done() const noexcept { return done_; }
};
explicit TrackModel(const Pose &pose) : pose_(pose) {}
uint_t n_actions() const noexcept { return COMMANDS.size(); }
const Pose &pose() const noexcept { return pose_; }
// Drive with COMMANDS[action] for DECISION_PERIOD
{
const auto &command = COMMANDS[action];
TimeStep time_step;
for (uint_t i = 0; i < MODEL_SUBSTEPS; ++i)
{
const real_t before = angle_around_track(pose_.x, pose_.y);
pose_.x += command.v * std::cos(pose_.heading) * dt;
pose_.y += command.v * std::sin(pose_.heading) * dt;
pose_.heading += command.omega * dt;
const real_t after = angle_around_track(pose_.x, pose_.y);
// progress along the track, in metres, and the cost of being away
// from the line
const real_t off_line = TRACK.distance(pose_.x, pose_.y);
time_step.reward_ += METRES_PER_RADIAN * std::remainder(after - before, 2.0 * PI);
time_step.reward_ -= LINE_COST * off_line * off_line * dt;
{
time_step.reward_ -= HIT_COST;
time_step.done_ = true;
break;
}
}
return time_step;
}
bool touches_a_box() const
{
const real_t cx = pose_.x + CHASSIS_AHEAD * std::cos(pose_.heading);
const real_t cy = pose_.y + CHASSIS_AHEAD * std::sin(pose_.heading);
return std::any_of(OBSTACLES.begin(), OBSTACLES.end(),
[&](const Point &box)
{ return distance_to_box(box, cx, cy) < ROBOT_RADIUS + CLEARANCE; });
}
private:
Pose pose_;
};
// The direction of travel along the track at (x, y): the outward normal, the
// gradient of the signed distance, turned a quarter to the left
{
const real_t h = 1e-4;
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);
}
{
uint_t operator()(const TrackModel &model, std::mt19937 &generator) const
{
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);
}
return steer(model);
}
// The command the policy takes when it does not take a random one
static uint_t steer(const TrackModel &model)
{
const auto &pose = model.pose();
const real_t cx = pose.x + CHASSIS_AHEAD * std::cos(pose.heading);
const real_t cy = pose.y + CHASSIS_AHEAD * std::sin(pose.heading);
const bool near_a_box = std::any_of(OBSTACLES.begin(), OBSTACLES.end(),
[&](const Point &box)
{ return distance_to_box(box, cx, cy) < DETOUR_NEAR; });
const real_t target = near_a_box ? DETOUR_OFFSET : 0.0;
// signed_distance is positive outside the track: further out than the
// target, turn left, towards the inside
const real_t offset = TRACK.signed_distance(pose.x, pose.y) - target;
const real_t heading =
track_direction(pose.x, pose.y) + std::atan(ROLLOUT_APPROACH * offset);
const real_t omega = ROLLOUT_GAIN * std::remainder(heading - pose.heading, 2.0 * PI);
uint_t best = 0;
for (uint_t c = 1; c < COMMANDS.size(); ++c)
{
if (std::abs(COMMANDS[c].omega - omega) < std::abs(COMMANDS[best].omega - omega))
{
best = c;
}
}
return best;
}
};
// The names of the commands, for the window
const std::array<const char *, 5> COMMAND_NAMES{"straight", "left", "right", "hard left",
"hard right"};
struct Candidate
{
std::vector<Pose> path;
};
template <typename Solver>
std::vector<Candidate> candidates(const Solver &solver, const TrackModel &model)
{
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);
Candidate candidate{node->get_action(),
static_cast<real_t>(node->total_visits()) / root->total_visits(),
{model.pose()}};
// down the tree, the most visited child each time
TrackModel ahead(model);
bool done = false;
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;
}
// then the rollout policy, to the end of the look ahead
while (!done && candidate.path.size() <= SEARCH.max_depth)
{
done = ahead.step(TowardsTheLine::steer(ahead)).done();
candidate.path.push_back(ahead.pose());
}
result.push_back(std::move(candidate));
}
return result;
}
// ---------------------------------------------------------------------------
// The world the robot drives in
// ---------------------------------------------------------------------------
{
[](real_t x, real_t y)
{ return TRACK.distance(x, y) < 0.5 * LINE_WIDTH; });
}
class World
{
public:
explicit World(const FloorImage &floor)
{
system_.SetGravitationalAcceleration(
chrono::ChVector3d(0.0, 0.0, -bitsim::consts::maths::G));
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_);
for (const auto &p : OBSTACLES)
{
auto box = chrono_types::make_shared<chrono::ChBodyEasyBox>(
OBSTACLE_SIZE, OBSTACLE_SIZE, OBSTACLE_HEIGHT, 500.0, true, true, material);
box->SetPos(chrono::ChVector3d(p[0], p[1], 0.5 * OBSTACLE_HEIGHT));
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(
bitsim::consts::build_robot_file_path("bitsim_diff_drive_robot.json")));
robot_.set_floor([&floor](real_t x, real_t y) { return floor.reflectance(x, y); });
robot_.set_world_pose(START[0], START[1], 0.0);
robot_.add_to_sys(system_);
}
void step(const Command &command)
{
robot_.set_velocity(command.v, command.omega);
robot_.update(STEP_SIZE);
system_.DoStepDynamics(STEP_SIZE);
touching_ = contacts_->count(system_) > 0;
}
void show_floor(const std::string &texture)
{
texture);
}
real_t time() const { return system_.GetChTime(); }
Pose pose() const
{
const auto axle = robot_.axle_center();
return {axle.x(), axle.y(), robot_.heading()};
}
bool is_touching_a_box() const { return touching_; }
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};
};
// ---------------------------------------------------------------------------
// The window
// ---------------------------------------------------------------------------
class Display
{
public:
Display(World &world, const FloorImage &floor, const std::string &record, bool follow)
: world_(world), recorder_(record, RECORD_RATE), follow_(follow)
{
// The paper on the ground goes on before the visual system starts
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_.SetWindowTitle(WINDOW_TITLE);
vis_.SetCameraVertical(chrono::CameraVerticalDir::Z);
vis_.Initialize();
vis_.AddCamera({0.0, -3.4, 3.0}, {0.0, -0.1, 0.0});
// A soft light: the typical lights wash the white paper out
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));
}
// Returns false once the window is closed
bool show(const std::vector<Candidate> &candidates, uint_t chosen, real_t lap)
{
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);
// the paths MCTS weighed: the more simulations started with a command,
// the wider its path; the command it chose in green, on top
for (int pass = 0; pass < 2; ++pass)
{
for (const auto &c : candidates)
{
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:";
for (const auto &c : candidates)
{
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:
// Behind and above the robot, looking ahead of it. The camera turns
// with a smoothed heading, so that the small turns of the robot do not
// shake the picture
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(
chrono::ChVector3d(pose.x - FOLLOW_BEHIND * c, pose.y - FOLLOW_BEHIND * s,
chrono::ChVector3d(pose.x + FOLLOW_AHEAD * c, pose.y + FOLLOW_AHEAD * s, 0.0));
}
World &world_;
chrono::irrlicht::ChVisualSystemIrrlicht vis_;
FrameRecorder recorder_;
Trail trail_;
bool follow_;
std::optional<real_t> camera_heading_;
};
// ---------------------------------------------------------------------------
// The run
// ---------------------------------------------------------------------------
struct Options
{
bool render{false};
std::string record;
bool follow{false};
};
Options parse(int argc, char **argv)
{
Options options;
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;
}
int run(const Options &options)
{
const FloorImage floor = draw_floor();
World world(floor);
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, "
<< SEARCH.max_depth * DECISION_PERIOD << " s, every " << DECISION_PERIOD << " s\n\n"
<< " t [s] x [m] y [m] head [deg] line [m] v [m/s] w [rad/s]\n";
uint_t chosen = 0;
std::vector<Candidate> weighed;
real_t next_decision = 0.0;
real_t next_print = 0.0;
real_t next_frame = 0.0;
real_t last_angle = angle_around_track(START[0], START[1]);
real_t travelled = 0.0;
real_t max_off_line = 0.0;
real_t planning_time = 0.0;
uint_t n_decisions = 0;
uint_t n_hits = 0;
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)
{
next_decision += DECISION_PERIOD;
const TrackModel model(world.pose());
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;
chosen = action;
if (display)
{
weighed = candidates(solver, model);
}
}
world.step(command);
const auto pose = world.pose();
const real_t angle = angle_around_track(pose.x, pose.y);
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)
{
next_print += PRINT_PERIOD;
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)
{
next_frame += 1.0 / RENDER_RATE;
if (!display->show(weighed, chosen, travelled / (2.0 * PI)))
{
break;
}
// Keep to real time, so that the window shows the robot at its speed
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;
}
}
const real_t wall =
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;
}
} // namespace mcts_line_following
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
Counts the contacts that touch any of a set of bodies, such as the obstacles a robot should not hit.
Definition contact_counter.h:32
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