bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Chrono robots that see each other's ghosts

Robots simulated by separate participants split a simulation of kinematic robots into participants. Here every participant runs a full Chrono simulation of bitsim's differential drive robot, in a Chrono system of its own. Two robots start 4 m apart, facing each other, and drive forward until their front sonar hears something closer than 0.4 m.

The robot of the other participant is not in this participant's Chrono system: another process, maybe on another machine, simulates it. What this participant has is the state of the other's chassis, every 0.02 s. CHRONO_Ghosts turns that into a ghost: a fixed box the size of the chassis, moved to where the chassis is. Chrono does not move it, but it collides, so the sonar's rays hit it like any other body.

What you need

bitsim built with Chrono; with MQTT too, to run the robots as separate processes. See Installing bitsim.

A participant

Synchroniser sync(transport, "robot_0", config); // config.peers = {"robot_1"}
CHRONO_Ghosts ghosts(system);
for (uint_t s = 0; ...; ++s)
{
// send our chassis, and place the ghost of the other robot
ghosts.update(sync.exchange(s, {chrono_body_state("chassis", *robot.get_chassis(), size)}));
// two Chrono steps of 0.01 s, reading the sonar before each
}

Running the example

./distributed_chrono_robots # both robots, as two threads
./distributed_chrono_robots --no-ghosts # the same without ghosts
./distributed_chrono_robots --transport mqtt --participant 0 &
./distributed_chrono_robots --transport mqtt --participant 1

Output

Each robot sees the ghost of the other
robot_0: stopped after 7.700 s, its sonar reads 0.40 m, the front of its chassis is at x = -0.21 m
robot_1: stopped after 7.700 s, its sonar reads 0.40 m, the front of its chassis is at x = +0.21 m
the gap between the two fronts is 0.42 m
Without ghosts
robot_0: never stopped, its sonar reads 4.00 m, the front of its chassis is at x = +1.96 m
robot_1: never stopped, its sonar reads 4.00 m, the front of its chassis is at x = -1.96 m
the gap between the two fronts is -3.91 m: in one world they would have crashed into each other

With ghosts, each robot hears the other and stops 0.4 m from it: the gap between the fronts is 0.42 m, the two stopping distances less the little they rolled on. Without ghosts, each robot is alone in its world, its sonar hears nothing, and the two drive straight through each other. Run as two MQTT processes, in lockstep, the robots do exactly what the two threads do, to the last bit of every number in chrono_robot_0.csv and chrono_robot_1.csv.

What ghosts can and cannot do

A ghost shows where the other robot is, and nothing else: it does not push back. When two robots of different participants collide, each participant sees its own robot hit a wall that does not give. That is fine for robots that sense and avoid each other, as here. Robots that push each other, or push the same box, need the bodies they push in one participant.

The robots exchange their state every 0.02 s, so a ghost is up to 0.02 s behind its robot: at 0.3 m/s, 6 mm. In wall-clock mode the ghosts are moved forward by their age, see A simulation that keeps up with a real robot.

The example sets Chrono's solver as Following a line with infrared sensors and avoiding obstacles does, which drives the same robot. With Chrono's default solver, and a step of 0.002 s, the chassis tipped forward by about 3 degrees as it drove, and the sonar, which looks straight ahead along the chassis, heard the floor 3 to 4 m away.

Things to try

  1. Give the robots different speeds. Where do they stop?
  2. Exchange every 0.2 s instead of every 0.02 s. How much closer do they get?
  3. Add a third robot that crosses between them.

The code

// Two of bitsim's Chrono robots drive towards each other, each simulated by its own participant,
// in a Chrono system of its own. A participant sees the other robot only as a ghost, a box that
// CHRONO_Ghosts moves to where the other participant says its chassis is; the front sonar of the
// robot hears the ghost like any other body, and the robot stops in front of it.
//
// Usage: distributed_chrono_robots [--no-ghosts] [--mode lockstep|wallclock]
// [--transport inprocess|mqtt] [--participant K] [--broker URL]
//
// With the in-process transport (the default) both robots are threads of this process. With
// --transport mqtt it simulates robot K only, and the other is another process on the broker:
//
// ./distributed_chrono_robots --transport mqtt --participant 0 &
// ./distributed_chrono_robots --transport mqtt --participant 1
//
// --no-ghosts leaves the ghosts out, to show what they are for. Writes chrono_robot_K.csv, the
// time, the position of the front of the chassis and the sonar reading of robot K.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#endif
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChContactMaterialNSC.h>
#include <chrono/physics/ChSystemNSC.h>
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
{
using namespace bitsim::distributed;
const std::string ROBOT_FILE = bitsim::consts::ROBOTS_DIR + "/bitsim_diff_drive_robot.json";
const std::array<real_t, 3> CHASSIS{0.5, 0.3, 0.1}; // the chassis of the robot file [m]
const real_t START = 2.0; // the axle centres start at x = -2 and 2 [m]
const real_t SPEED = 0.3; // [m/s]
const real_t STOP_AT = 0.4; // the sonar distance to stop at [m]
const real_t STEP = 0.01; // the step of Chrono [s]
const uint_t STEPS_PER_SYNC = 2; // exchange every 0.02 s
const real_t DURATION = 12.0; // [s]
struct Options
{
bool ghosts{true};
SyncMode mode{SyncMode::LOCKSTEP};
std::string transport{"inprocess"};
int participant{-1};
std::string broker{"tcp://localhost:1883"};
};
std::string name_of(uint_t k) { return "robot_" + std::to_string(k); }
struct Result
{
real_t stopped_at{-1.0}; // the time the robot stopped, -1 if it did not
real_t sonar{0.0}; // the last sonar reading [m]
real_t front{0.0}; // the x of the front of the chassis at the end [m]
};
// The world of one participant: the floor, its own robot, and the ghosts of the others
class World
{
public:
explicit World(uint_t k, bool with_ghosts) : ghosts_(system_), with_ghosts_(with_ghosts)
{
system_.SetGravitationalAcceleration(chrono::ChVector3d(0, 0, -bitsim::consts::maths::G));
system_.SetCollisionSystemType(chrono::ChCollisionSystem::Type::BULLET);
// as in line_following_infrared_sonar, which drives the same robot
system_.SetSolverType(chrono::ChSolver::Type::BARZILAIBORWEIN);
system_.GetSolver()->AsIterative()->SetMaxIterations(40);
auto material = chrono_types::make_shared<chrono::ChContactMaterialNSC>();
material->SetFriction(0.8f);
auto ground = chrono_types::make_shared<chrono::ChBodyEasyBox>(10.0, 4.0, 0.1, 1000.0, true,
true, material);
ground->SetPos(chrono::ChVector3d(0.0, 0.0, -0.05));
ground->SetFixed(true);
system_.AddBody(ground);
robot_.load(std::filesystem::path(ROBOT_FILE));
// robot 0 on the left facing right, robot 1 on the right facing left
robot_.set_world_pose(k == 0 ? -START : START, 0.0,
k == 0 ? 0.0 : bitsim::consts::maths::PI);
robot_.add_to_sys(system_);
direction_ = k == 0 ? 1.0 : -1.0;
}
// What the others need to know of this robot: its chassis
std::vector<BodyState> bodies() const
{
return {chrono_body_state("chassis", *robot_.get_chassis(), CHASSIS)};
}
void place_ghosts(const std::vector<PeerState> &peers)
{
if (with_ghosts_)
{
ghosts_.update(peers);
}
}
// Drive until the sonar hears something closer than STOP_AT, slowing down before it
void step(real_t &sonar)
{
auto sensor = robot_.get_sonar();
sonar = sensor->read_values().at(0);
const real_t v = SPEED * std::clamp((sonar - STOP_AT) / 0.5, 0.0, 1.0);
robot_.set_velocity(v, 0.0);
robot_.update(STEP);
system_.DoStepDynamics(STEP);
}
real_t time() const { return system_.GetChTime(); }
// the front of the chassis, along x
real_t front() const
{
return robot_.get_chassis()->GetPos().x() + direction_ * 0.5 * CHASSIS[0];
}
private:
chrono::ChSystemNSC system_;
CHRONO_DiffDriveRobot robot_;
CHRONO_Ghosts ghosts_;
bool with_ghosts_;
real_t direction_{1.0};
};
Result simulate(uint_t k, const Options &options, Transport &transport)
{
World world(k, options.ghosts);
config.mode = options.mode;
config.peers = {name_of(1 - k)};
config.timeout = 30.0;
config.resend_period = 0.02;
Synchroniser sync(transport, name_of(k), config);
Result result;
std::ofstream out("chrono_robot_" + std::to_string(k) + ".csv");
out << "t,front,sonar\n";
const auto n_syncs = static_cast<uint_t>(DURATION / config.sync_period);
real_t sonar = 0.0;
for (uint_t s = 0; s < n_syncs; ++s)
{
world.place_ghosts(sync.exchange(s, world.bodies()));
for (uint_t i = 0; i < STEPS_PER_SYNC; ++i)
{
world.step(sonar);
}
out << world.time() << "," << world.front() << "," << sonar << "\n";
if (result.stopped_at < 0.0 && sonar <= STOP_AT + 0.005)
{
result.stopped_at = world.time();
}
}
sync.leave();
result.sonar = sonar;
result.front = world.front();
return result;
}
// results[i] is the result of robot first + i
void report(const std::vector<Result> &results, uint_t first = 0)
{
for (uint_t i = 0; i < results.size(); ++i)
{
const auto &r = results[i];
std::cout << std::fixed << std::setprecision(2) << " " << name_of(first + i) << ": "
<< (r.stopped_at >= 0.0
? "stopped after " + std::to_string(r.stopped_at).substr(0, 5) + " s"
: std::string("never stopped"))
<< ", its sonar reads " << r.sonar
<< " m, the front of its chassis is at x = " << std::showpos << r.front
<< std::noshowpos << " m\n";
}
if (results.size() == 2)
{
const real_t gap = results[1].front - results[0].front;
std::cout << " the gap between the two fronts is " << std::setprecision(2) << gap << " m"
<< (gap < 0.0 ? ": in one world they would have crashed into each other" : "")
<< "\n";
}
}
std::vector<Result> run_in_process(const Options &options)
{
std::vector<std::unique_ptr<Transport>> transports;
transports.push_back(bus.connect());
transports.push_back(bus.connect());
std::vector<Result> results(2);
std::vector<std::thread> threads;
for (uint_t k = 0; k < 2; ++k)
{
threads.emplace_back([&, k] { results[k] = simulate(k, options, *transports[k]); });
}
for (auto &t : threads)
{
t.join();
}
return results;
}
int run(const Options &options)
{
if (options.transport == "mqtt")
{
#ifdef BITSIM_MQTT
if (options.participant != 0 && options.participant != 1)
{
std::cerr << "--transport mqtt needs --participant 0 or 1\n";
return 1;
}
MQTT_Transport transport(options.broker, "distributed_chrono_robots");
report({simulate(options.participant, options, transport)}, options.participant);
return 0;
#else
std::cerr << "bitsim was built without MQTT\n";
return 1;
#endif
}
bitsim::utils::io::print_title(options.ghosts ? "Each robot sees the ghost of the other"
: "Without ghosts");
return 0;
}
} // namespace distributed_chrono_robots
int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i)
{
const std::string flag = argv[i];
if (flag == "--no-ghosts")
{
options.ghosts = false;
continue;
}
if (i + 1 >= argc)
{
std::cerr << "option " << flag << " needs a value\n";
return 1;
}
const std::string value = argv[++i];
if (flag == "--mode")
options.mode = value == "wallclock" ? bitsim::distributed::SyncMode::WALL_CLOCK
else if (flag == "--transport")
options.transport = value;
else if (flag == "--participant")
options.participant = std::atoi(value.c_str());
else if (flag == "--broker")
options.broker = value;
else
{
std::cerr << "unknown option " << flag << "\n";
return 1;
}
}
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Participants that are threads of one process, joined by queues.
Definition transport.h:57
std::unique_ptr< Transport > connect()
A transport for a new participant.
Definition transport.cpp:37
Participants in several processes, on one machine or several, that meet on an MQTT broker.
Definition mqtt_transport.h:29
Keeps the participants of a distributed simulation in step.
Definition synchroniser.h:99
How the participants of a distributed simulation reach each other: everything one publishes,...
Definition transport.h:34
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
Definition distributed_chrono_robots.cpp:82
World(uint_t k, bool with_ghosts)
Definition distributed_chrono_robots.cpp:84
real_t front() const
Definition distributed_chrono_robots.cpp:135
real_t time() const
Definition distributed_chrono_robots.cpp:132
void place_ghosts(const std::vector< PeerState > &peers)
Definition distributed_chrono_robots.cpp:113
void step(real_t &sonar)
Definition distributed_chrono_robots.cpp:122
std::vector< BodyState > bodies() const
Definition distributed_chrono_robots.cpp:108
int main()
Definition discounted_returns.cpp:19
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
Definition chrono_ghosts.cpp:12
SyncMode
How the participants of a distributed simulation keep time.
Definition synchroniser.h:25
@ WALL_CLOCK
Definition synchroniser.h:38
@ LOCKSTEP
Definition synchroniser.h:31
BodyState chrono_body_state(const std::string &name, const chrono::ChBody &body, const std::array< real_t, 3 > &size)
The state of a Chrono body, to send to the other participants.
Definition chrono_ghosts.cpp:14
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Definition distributed_chrono_robots.cpp:46
const real_t STOP_AT
Definition distributed_chrono_robots.cpp:57
const uint_t STEPS_PER_SYNC
Definition distributed_chrono_robots.cpp:59
const real_t STEP
Definition distributed_chrono_robots.cpp:58
int run(const Options &options)
Definition distributed_chrono_robots.cpp:226
std::vector< Result > run_in_process(const Options &options)
Definition distributed_chrono_robots.cpp:207
void report(const std::vector< Result > &results, uint_t first=0)
Definition distributed_chrono_robots.cpp:185
const real_t START
Definition distributed_chrono_robots.cpp:55
const real_t DURATION
Definition distributed_chrono_robots.cpp:60
std::string name_of(uint_t k)
Definition distributed_chrono_robots.cpp:71
Result simulate(uint_t k, const Options &options, Transport &transport)
Definition distributed_chrono_robots.cpp:148
const std::string ROBOT_FILE
Definition distributed_chrono_robots.cpp:53
const real_t SPEED
Definition distributed_chrono_robots.cpp:56
const std::array< real_t, 3 > CHASSIS
Definition distributed_chrono_robots.cpp:54
void sensor(ConcurrentQueue< GyroReading > &queue)
Definition producer_consumer.cpp:45
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
The settings of Synchroniser.
Definition synchroniser.h:45
SyncMode mode
Definition synchroniser.h:46
real_t sync_period
the simulated time between two exchanges [s]
Definition synchroniser.h:47
real_t timeout
lockstep: the longest wait for a step [s]
Definition synchroniser.h:56
std::vector< std::string > peers
Definition synchroniser.h:54
real_t resend_period
lockstep: send the last steps again this often while waiting [s]
Definition synchroniser.h:57
Definition distributed_chrono_robots.cpp:63
std::string transport
Definition distributed_chrono_robots.cpp:66
SyncMode mode
Definition distributed_chrono_robots.cpp:65
bool ghosts
Definition distributed_chrono_robots.cpp:64
int participant
Definition distributed_chrono_robots.cpp:67
std::string broker
Definition distributed_chrono_robots.cpp:68
Definition distributed_chrono_robots.cpp:74
real_t front
Definition distributed_chrono_robots.cpp:77
real_t sonar
Definition distributed_chrono_robots.cpp:76
real_t stopped_at
Definition distributed_chrono_robots.cpp:75