A simulation of many robots can outgrow one process, or one machine, or it can mix simulated robots with real ones. bitsim's bitsim/distributed splits it up: every participant simulates its own robots, and the participants tell each other, every so often, where their robots are. Here four differential drive robots cross a circle to the opposite point, each simulated by a participant of its own with bitsim's diff-drive kinematics, and each steers around the robots it hears of.
Nothing beyond bitsim itself for the threads of one process. For processes, bitsim built with MQTT and a broker such as mosquitto. See Installing bitsim.
The second line runs every robot in a process of its own, meeting on the broker at tcp://localhost:1883 (--broker for another). They can be on different machines.
In lockstep the paths are the same every time, and the same when a tenth of the messages are lost: the losses only cost time. Run as four MQTT processes, the paths are the same to the last bit as the paths of the threads. In wall-clock mode the robots see each other a little late, and the crossing takes a little longer.
With mosquitto's default settings, the 200 steps of the four processes took 7.9 s; with set_tcp_nodelay true in mosquitto.conf they took 0.09 s. By default the broker waits a few milliseconds to bundle small TCP packets (Nagle's algorithm), and a lockstep that waits for every message pays that wait at every step. Turn it off on a broker that serves a distributed simulation.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
{
struct Options
{
std::string
broker{
"tcp://localhost:1883"};
};
std::string
name_of(
uint_t k) {
return "robot_" + std::to_string(k); }
std::array<real_t, 2>
steer(
const bitsim::dynamics::SysState<3> &s,
const std::array<real_t, 2> &goal, const std::vector<PeerState> &peers)
{
const real_t x = s[0], y = s[1], theta = s[2];
const real_t distance = std::hypot(goal[0] - x, goal[1] - y);
real_t dx = (goal[0] - x) / std::max(distance, 1e-9);
real_t dy = (goal[1] - y) / std::max(distance, 1e-9);
for (const auto &peer : peers)
{
for (const auto &b : peer.bodies)
{
const real_t rx = b.position[0] - x, ry = b.position[1] - y;
const real_t r = std::hypot(rx, ry);
if (r > 1.0 || r < 1e-9)
{
continue;
}
const real_t push = 0.3 * (1.0 / std::max(r - 2.0 *
RADIUS, 0.05) - 1.0);
dx += push * (ry - rx) / r;
dy -= push * (rx + ry) / r;
if ((rx * std::cos(theta) + ry * std::sin(theta)) / r > 0.0)
{
slow = std::min(slow, std::clamp((r - 2.0 *
RADIUS) / 0.5, 0.2, 1.0));
}
}
}
return {std::min(
MAX_V, distance) * std::max(0.0, std::cos(error)) * slow,
}
{
std::vector<std::array<real_t, 3>>
path;
};
{
const real_t angle = 2.0 *
PI * k / options.n_robots;
bitsim::dynamics::SysState<3>
state({std::make_pair(
"X",
CIRCLE * std::cos(angle)),
std::make_pair(
"Y",
CIRCLE * std::sin(angle)),
std::make_pair(
"Theta",
wrap(angle +
PI))});
const std::array<real_t, 2> goal{-
CIRCLE * std::cos(angle), -
CIRCLE * std::sin(angle)};
config.
mode = options.mode;
for (
uint_t j = 0; j < options.n_robots; ++j)
{
if (j != k)
{
}
}
std::array<real_t, 2>
command{0.0, 0.0};
{
const real_t t = sync.time_of(step);
const auto &peers =
sync.exchange(step, {
BodyState::planar(
"chassis", state[0], state[1], state[2], vx, vy,
if (std::hypot(goal[0] - state[0], goal[1] - state[1]) < 0.1)
{
result.arrived = true;
result.time = t;
break;
}
{
command[1], {0.0, 0.0});
}
}
sync.leave();
result.n_resent = sync.n_resent();
result.n_overruns = sync.n_overruns();
result.max_wait = sync.max_wait();
if (options.write_paths)
{
std::ofstream out(result.name + ".csv");
out << std::setprecision(17) << "t,x,y\n";
for (const auto &p : result.path)
{
out << p[0] << "," << p[1] << "," << p[2] << "\n";
}
}
return result;
}
{
for (std::size_t a = 0; a < results.size(); ++a)
{
for (std::size_t b = a + 1; b < results.size(); ++b)
{
const auto &pa = results[a].path, &pb = results[b].path;
for (std::size_t i = 0; i < std::max(pa.size(), pb.size()); ++i)
{
const auto &qa = pa[std::min(i, pa.size() - 1)];
const auto &qb = pb[std::min(i, pb.size() - 1)];
best = std::min(best, std::hypot(qa[1] - qb[1], qa[2] - qb[2]));
}
}
}
return best;
}
{
uint_t arrived = 0, resent = 0, overruns = 0;
for (const auto &r : results)
{
arrived += r.arrived ? 1 : 0;
last = std::max(last, r.time);
resent += r.n_resent;
overruns += r.n_overruns;
max_wait = std::max(max_wait, r.max_wait);
}
std::cout << std::fixed << std::setprecision(2) << " " << arrived << " of " << results.size()
<< " robots arrived, the last after " << last << " s of simulated time, in "
<< wall_seconds <<
" s; closest centres " <<
closest(results) <<
" m\n"
<< std::setprecision(3);
if (mode == SyncMode::LOCKSTEP)
{
std::cout << " " << resent << " times a robot sent its last steps again; the longest "
<< "wait for the others " << max_wait << " s\n";
}
else
{
std::cout << " " << overruns << " steps started more than a period late; the latest "
<< max_wait << " s\n";
}
}
{
std::vector<std::unique_ptr<Transport>> transports;
for (
uint_t k = 0; k < options.n_robots; ++k)
{
if (options.network.latency > 0.0 || options.network.loss > 0.0)
{
auto network = options.network;
network.seed += k;
t = std::make_unique<LossyTransport>(std::move(t), network);
}
transports.push_back(std::move(t));
}
std::vector<Result> results(options.n_robots);
std::vector<std::thread> threads;
for (
uint_t k = 0; k < options.n_robots; ++k)
{
threads.emplace_back([&, k] { results[k] =
simulate(k, options, *transports[k]); });
}
for (auto &t : threads)
{
t.join();
}
return results;
}
{
const auto start = std::chrono::steady_clock::now();
f();
return std::chrono::duration<real_t>(std::chrono::steady_clock::now() - start).count();
}
{
if (options.transport == "mqtt")
{
#ifdef BITSIM_MQTT
if (options.participant < 0 ||
static_cast<uint_t>(options.participant) >= options.n_robots)
{
std::cerr << "--transport mqtt needs --participant K, 0 <= K < " << options.n_robots
<< "\n";
return 1;
}
timed([&] { result =
simulate(options.participant, options, transport); });
std::cout << result.name << (result.arrived ? " arrived after " : " gave up after ")
<< std::fixed << std::setprecision(2) << result.time << " s, in " << wall
<< " s; " << result.n_resent << " resends\n";
return 0;
#else
std::cerr << "bitsim was built without MQTT\n";
return 1;
#endif
}
if (options.participant >= 0)
{
std::cerr << "--participant is for --transport mqtt\n";
return 1;
}
lockstep.mode = SyncMode::LOCKSTEP;
lockstep.network = {};
std::vector<Result> first, again;
report(first, wall, SyncMode::LOCKSTEP);
lockstep.write_paths = false;
bool same = true;
for (
uint_t k = 0; k < first.size(); ++k)
{
same = same && first[k].path == again[k].path;
}
std::cout << " a second run gives the same paths: " << std::boolalpha << same << "\n\n";
lossy.network = options.network;
if (lossy.network.latency == 0.0 && lossy.network.loss == 0.0)
{
lossy.network.latency = 0.005;
lossy.network.jitter = 0.002;
lossy.network.loss = 0.1;
}
std::vector<Result> over_network;
report(over_network, wall, SyncMode::LOCKSTEP);
same = true;
for (
uint_t k = 0; k < first.size(); ++k)
{
same = same && first[k].path == over_network[k].path;
}
std::cout << " " << std::setprecision(0) << 100 * lossy.network.loss << " % of the messages "
<< "lost, " << 1000 * lossy.network.latency << " ms of latency; the paths are "
<< (same ? "the same as in 1" : "NOT the same as in 1") << "\n\n";
wall_clock.mode = SyncMode::WALL_CLOCK;
wall_clock.speed = options.speed;
std::vector<Result> real_time;
report(real_time, wall, SyncMode::WALL_CLOCK);
std::cout << " at " << std::setprecision(1) << wall_clock.speed
<< " times real time; the paths differ from run to run\n";
return 0;
}
}
int main(
int argc,
char **argv)
{
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i], value = argv[i + 1];
if (flag == "--robots")
options.
n_robots = std::strtoul(value.c_str(),
nullptr, 10);
else if (flag == "--mode")
else if (flag == "--speed")
options.
speed = std::strtod(value.c_str(),
nullptr);
else if (flag == "--latency")
else if (flag == "--loss")
options.
network.
loss = std::strtod(value.c_str(),
nullptr);
else if (flag == "--transport")
else if (flag == "--participant")
else if (flag == "--broker")
else if (flag == "--resend")
options.
resend = std::strtod(value.c_str(),
nullptr);
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
static SysState< 3 > integrate_state_v2(const SysState< 3 > &state, real_t dt, real_t v, real_t w, const std::array< real_t, 2 > &errors)
integrate_state_v2
Definition diff_drive_dynamics.cpp:57
int main()
Definition discounted_returns.cpp:19
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
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
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
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
std::map< std::string, std::any > command(real_t v, real_t w)
Definition diff_drive_kinematics.cpp:29
Definition distributed_robots.cpp:47
const real_t RADIUS
Definition distributed_robots.cpp:55
const real_t TIME_LIMIT
Definition distributed_robots.cpp:60
const real_t MAX_W
Definition distributed_robots.cpp:57
real_t timed(F &&f)
Definition distributed_robots.cpp:270
const real_t CIRCLE
Definition distributed_robots.cpp:54
void report(const std::vector< Result > &results, real_t wall_seconds, SyncMode mode)
Definition distributed_robots.cpp:212
std::array< real_t, 2 > steer(const bitsim::dynamics::SysState< 3 > &s, const std::array< real_t, 2 > &goal, const std::vector< PeerState > &peers)
Definition distributed_robots.cpp:80
const real_t MAX_V
Definition distributed_robots.cpp:56
const uint_t STEPS_PER_SYNC
Definition distributed_robots.cpp:59
std::vector< Result > run_in_process(const Options &options)
Definition distributed_robots.cpp:242
int run(const Options &options)
Definition distributed_robots.cpp:277
std::string name_of(uint_t k)
Definition distributed_robots.cpp:75
Result simulate(uint_t k, const Options &options, Transport &transport)
Definition distributed_robots.cpp:123
const real_t PI
Definition distributed_robots.cpp:53
real_t wrap(real_t a)
Definition distributed_robots.cpp:77
const real_t DT
Definition distributed_robots.cpp:58
real_t closest(const std::vector< Result > &results)
Definition distributed_robots.cpp:193
real_t error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
state
Definition play.py:39
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
static BodyState planar(const std::string &name, real_t x, real_t y, real_t yaw, real_t vx=0.0, real_t vy=0.0, real_t wz=0.0, const std::array< real_t, 3 > &size={0.0, 0.0, 0.0})
A body that moves in the plane: at (x, y), turned yaw about z, moving with (vx, vy) and turning at wz...
Definition state_message.cpp:14
real_t latency
[s]
Definition transport.h:85
real_t loss
the probability that a message is lost
Definition transport.h:87
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 real_time_factor
wall-clock: simulated seconds per wall-clock second
Definition synchroniser.h:59
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
real_t stale_after
wall-clock: a state older than this is stale [s]
Definition synchroniser.h:60
Definition distributed_robots.cpp:63
SyncMode mode
Definition distributed_robots.cpp:65
bool write_paths
Definition distributed_robots.cpp:72
std::string broker
Definition distributed_robots.cpp:70
uint_t n_robots
Definition distributed_robots.cpp:64
LossyTransport::Config network
Definition distributed_robots.cpp:67
int participant
Definition distributed_robots.cpp:69
real_t speed
Definition distributed_robots.cpp:66
std::string transport
Definition distributed_robots.cpp:68
real_t resend
Definition distributed_robots.cpp:71
Definition distributed_robots.cpp:113
real_t time
Definition distributed_robots.cpp:116
std::vector< std::array< real_t, 3 > > path
Definition distributed_robots.cpp:117
real_t max_wait
Definition distributed_robots.cpp:119
bool arrived
Definition distributed_robots.cpp:115
std::string name
Definition distributed_robots.cpp:114
uint_t n_overruns
Definition distributed_robots.cpp:118
uint_t n_resent
Definition distributed_robots.cpp:118