bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
A simulation that keeps up with a real robot

A real robot cannot wait for a simulation, so a simulation with a real robot in it cannot run in lockstep. In wall-clock mode a participant keeps pace with the wall clock instead, and uses the newest state it has of every other participant, whenever it came. This example drives a simulated robot that follows a real one, 0.5 m behind it.

What the simulation believed, and the error

The black line is where the real robot was, except during the 1.5 s without reports, which it crosses in a straight line; the dots are where the simulation believed it was.

What you need

Nothing beyond bitsim itself in one process. For two processes, bitsim built with MQTT and a broker. See Installing bitsim.

The real robot

The real robot here is a thread that drives a circle of 1 m radius at 0.4 m/s, in real time, and reports its measured pose ten times a second, with 1 cm of noise. Its reports reach the simulation over a network, a LossyTransport, that delays them by 80 ms, give or take 20 ms, and loses one in ten. For 1.5 s in the middle the reports stop.

A report is a StateMessage, stamped with the wall-clock time it was measured. That is all a real robot has to send, and it needs nothing else of bitsim:

StateMessage m;
m.participant = "robot";
m.stamp = wall_time_now(); // seconds since the epoch of the system clock
m.bodies.push_back(BodyState::planar("chassis", x, y, theta, vx, vy, w, {0.4, 0.3, 0.1}));
transport.publish(m.encode()); // MQTT topic bitsim/world/<world>

The stamp is how the simulation tells how old a report is, so the clocks of the robot and of the simulation's machine must agree, to a few milliseconds. On a network that means NTP, or chrony.

The simulation

The simulation steps 50 times a second with a Synchroniser in SyncMode::WALL_CLOCK. At every step exchange() returns the newest report of the robot, with its age, and, with extrapolate set, the pose moved forward by the robot's velocities for that age. A report older than stale_after, 0.4 s, is stale: the simulated robot stops until a new one comes.

Running the example

./hardware_in_the_loop_sync # in one process, with and without moving the pose forward
./hardware_in_the_loop_sync --transport mqtt --role sim &
./hardware_in_the_loop_sync --transport mqtt --role robot

With MQTT, the robot's side is what a real robot replaces.

Output

1. Moving the pose forward by its age
extrapolated: error of the believed pose 0.013 m on average, at most 0.033 m; mean age 0.148 s
70 of 400 steps stale, the robot stopped for 1.40 s; closest to the real robot 0.50 m; 0 steps started late
2. Using the newest pose as it is
newest: error of the believed pose 0.061 m on average, at most 0.157 m; mean age 0.148 s
69 of 400 steps stale, the robot stopped for 1.38 s; closest to the real robot 0.50 m; 0 steps started late

A report is 0.15 s old on average when the simulation uses it: 80 ms of latency, half of the 0.1 s between reports, and the reports that were lost. In 0.15 s the robot drives 6 cm, and that is the error of the newest report used as it is. Moved forward with the robot's velocities, the error is 1.3 cm, about the noise of the measurement. The motion is a circle, and moving forward assumes constant velocities, which is why the error grows during the 0.4 s before a pose is stale.

When the reports stop, the simulated robot stops 0.4 s later, and goes on when they come back.

Things to try

  1. Set stale_after to 2 s. How far off is the believed pose at the end of the dropout?
  2. Make the robot report five times a second. Which error grows, and by how much?
  3. BodyState::extrapolated() turns the heading with the turn rate, but moves the position along a straight line. Move it along the arc instead: how much smaller is the error before a pose goes stale?

The code

// A simulated robot follows a real one, in wall-clock mode.
//
// The "real" robot drives a circle in real time and sends its measured pose ten times a second,
// as the code on a Raspberry Pi would: a StateMessage stamped with the wall-clock time. Its
// messages reach the simulation over a network that delays them by 80 ms, give or take 20 ms,
// and loses one in ten, and for 1.5 s in the middle they stop altogether, as when the Wi-Fi drops.
// The simulation runs at 50 steps a second in wall-clock mode and drives a simulated robot that
// keeps 0.5 m behind the real one. It does not wait for the real robot, which could not wait for
// it; it uses the newest pose it has, moved forward by its age, and stops its robot when the pose
// is too old to trust.
//
// Usage: hardware_in_the_loop_sync [--duration S]
// hardware_in_the_loop_sync --transport mqtt --role robot|sim [--duration S] [--broker URL]
//
// In-process (the default) the real robot is a thread, the example runs twice, with and without
// moving the pose forward, and compares what the simulation believed with where the robot was.
// With --transport mqtt the two sides are separate processes, and --role robot is the side a real
// robot replaces. Writes hil_extrapolated.csv and hil_newest.csv.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <thread>
{
using namespace bitsim::distributed;
using steady = std::chrono::steady_clock;
const real_t SPEED = 0.4; // [m/s], the real robot
const real_t TURN = 0.4; // [rad/s], so a circle of 1 m
const real_t REPORT_PERIOD = 0.1; // the real robot reports ten times a second
const real_t DROP_FROM = 0.45; // the reports stop for DROP_LENGTH from this share of the run
const real_t DROP_LENGTH = 1.5; // [s]
const real_t SIM_PERIOD = 0.02; // the simulation steps 50 times a second
const real_t BEHIND = 0.5; // [m], how far the simulated robot keeps behind
const real_t STALE_AFTER = 0.4; // [s]
struct Pose
{
};
// Where the real robot truly is, t seconds after it started
{
const real_t theta = TURN * t;
const real_t r = SPEED / TURN;
return {r * std::sin(theta), r * (1.0 - std::cos(theta)), theta};
}
// The real robot: drive, and every REPORT_PERIOD send the measured pose, except while the
// network is down. The pose is measured with 1 cm of noise
void real_robot(Transport &transport, real_t duration, steady::time_point start)
{
std::mt19937 rng(3);
std::normal_distribution<real_t> noise(0.0, 0.01);
const real_t drop_from = DROP_FROM * duration;
for (uint_t k = 0;; ++k)
{
const real_t t = k * REPORT_PERIOD;
if (t > duration)
{
break;
}
std::this_thread::sleep_until(
start + std::chrono::duration_cast<steady::duration>(std::chrono::duration<real_t>(t)));
if (t >= drop_from && t < drop_from + DROP_LENGTH)
{
continue; // the Wi-Fi is down
}
const Pose p = true_pose(t);
m.participant = "robot";
m.step = k;
m.time = t;
m.bodies.push_back(BodyState::planar("chassis", p.x + noise(rng), p.y + noise(rng), p.theta,
SPEED * std::cos(p.theta), SPEED * std::sin(p.theta),
TURN, {0.4, 0.3, 0.1}));
transport.publish(m.encode());
}
}
struct Statistics
{
real_t mean_error{0.0}, max_error{0.0}, mean_age{0.0};
};
// The simulation: a robot that keeps BEHIND behind the real one, with what the synchroniser
// says of it. With a known start, the true pose is known too, to measure the error
Statistics simulation(Transport &transport, real_t duration, bool extrapolate,
steady::time_point start, const std::string &csv)
{
config.mode = SyncMode::WALL_CLOCK;
config.extrapolate = extrapolate;
config.peers = {"robot"};
Synchroniser sync(transport, "sim", config);
std::ofstream out(csv);
out << "t,true_x,true_y,believed_x,believed_y,age,stale,sim_x,sim_y\n";
Pose me{-BEHIND, 0.0, 0.0};
real_t v = 0.0, w = 0.0;
const auto n = static_cast<uint_t>(duration / SIM_PERIOD);
for (uint_t k = 0; k < n; ++k)
{
const auto &peers = sync.exchange(
k, {BodyState::planar("chassis", me.x, me.y, me.theta, v * std::cos(me.theta),
v * std::sin(me.theta), w, {0.4, 0.3, 0.1})});
// the time since the real robot started, to look up where it truly is
const real_t t = std::chrono::duration<real_t>(steady::now() - start).count();
const auto &robot = peers.front();
++s.n_steps;
if (robot.stale || robot.bodies.empty())
{
// too old to trust: stop
++s.n_stale;
++s.n_stopped;
v = 0.0;
w = 0.0;
}
else
{
const auto &b = robot.bodies.front();
const Pose truth = true_pose(t);
const real_t error = std::hypot(b.position[0] - truth.x, b.position[1] - truth.y);
s.mean_error += error;
s.max_error = std::max(s.max_error, error);
s.mean_age += robot.age;
out << t << "," << truth.x << "," << truth.y << "," << b.position[0] << ","
<< b.position[1] << "," << robot.age << ",0," << me.x << "," << me.y << "\n";
// head for the point BEHIND behind where we believe the robot is
const real_t yaw = b.yaw();
const real_t gx = b.position[0] - BEHIND * std::cos(yaw);
const real_t gy = b.position[1] - BEHIND * std::sin(yaw);
const real_t d = std::hypot(gx - me.x, gy - me.y);
const real_t heading_error =
std::remainder(std::atan2(gy - me.y, gx - me.x) - me.theta, 2 * PI);
v = std::clamp(1.5 * d, 0.0, 0.8) * std::max(0.0, std::cos(heading_error));
w = std::clamp(4.0 * heading_error, -3.0, 3.0);
}
me.x += v * std::cos(me.theta) * SIM_PERIOD;
me.y += v * std::sin(me.theta) * SIM_PERIOD;
me.theta += w * SIM_PERIOD;
const Pose truth = true_pose(t);
s.closest = std::min(s.closest, std::hypot(truth.x - me.x, truth.y - me.y));
}
sync.leave();
const uint_t n_fresh = s.n_steps - s.n_stale;
if (n_fresh)
{
s.mean_error /= n_fresh;
s.mean_age /= n_fresh;
}
s.n_overruns = sync.n_overruns();
return s;
}
void report(const std::string &name, const Statistics &s)
{
std::cout << std::fixed << std::setprecision(3) << " " << name << ": error of the believed "
<< "pose " << s.mean_error << " m on average, at most " << s.max_error
<< " m; mean age " << s.mean_age << " s\n"
<< " " << s.n_stale << " of " << s.n_steps
<< " steps stale, the robot stopped for " << std::setprecision(2)
<< s.n_stopped * SIM_PERIOD << " s; closest to the real robot " << s.closest << " m; "
<< s.n_overruns << " steps started late\n";
}
Statistics run_in_process(real_t duration, bool extrapolate, const std::string &csv)
{
auto robot_side = bus.connect();
LossyTransport::Config network;
network.latency = 0.08;
network.jitter = 0.02;
network.loss = 0.1;
LossyTransport sim_side(bus.connect(), network);
const auto start = steady::now();
std::thread robot([&] { real_robot(*robot_side, duration, start); });
const auto s = simulation(sim_side, duration, extrapolate, start, csv);
robot.join();
return s;
}
int run(real_t duration, const std::string &transport, const std::string &role,
const std::string &broker)
{
if (transport == "mqtt")
{
#ifdef BITSIM_MQTT
MQTT_Transport t(broker, "hardware_in_the_loop_sync");
const auto start = steady::now();
if (role == "robot")
{
std::cout << " sending the robot's pose for " << duration << " s\n";
real_robot(t, duration, start);
return 0;
}
if (role == "sim")
{
// the start of the two processes differs, so the error against the true pose is off
// by that; the ages and the stale steps are not
report("over MQTT", simulation(t, duration, true, start, "hil_mqtt.csv"));
return 0;
}
std::cerr << "--role must be robot or sim\n";
return 1;
#else
std::cerr << "bitsim was built without MQTT\n";
return 1;
#endif
}
bitsim::utils::io::print_title("1. Moving the pose forward by its age");
report("extrapolated", run_in_process(duration, true, "hil_extrapolated.csv"));
std::cout << "\n";
bitsim::utils::io::print_title("2. Using the newest pose as it is");
report("newest", run_in_process(duration, false, "hil_newest.csv"));
return 0;
}
} // namespace hardware_in_the_loop_sync
int main(int argc, char **argv)
{
bitsim::real_t duration = 8.0;
std::string transport = "inprocess", role, broker = "tcp://localhost:1883";
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i], value = argv[i + 1];
if (flag == "--duration")
duration = std::strtod(value.c_str(), nullptr);
else if (flag == "--transport")
transport = value;
else if (flag == "--role")
role = value;
else if (flag == "--broker")
broker = value;
else
{
std::cerr << "unknown option " << flag << "\n";
return 1;
}
}
return hardware_in_the_loop_sync::run(duration, transport, role, broker);
}
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
A transport that delays and loses some of the messages of another, as a network would.
Definition transport.h:81
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
virtual void publish(const std::string &bytes)=0
Send bytes to every other participant.
int main()
Definition discounted_returns.cpp:19
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
Definition chrono_ghosts.cpp:12
real_t wall_time_now()
The wall-clock time now, in seconds since the epoch of std::chrono::system_clock.
Definition state_message.cpp:118
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
real_t error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
Definition hardware_in_the_loop_sync.cpp:44
const real_t TURN
Definition hardware_in_the_loop_sync.cpp:53
Pose true_pose(real_t t)
Definition hardware_in_the_loop_sync.cpp:67
std::chrono::steady_clock steady
Definition hardware_in_the_loop_sync.cpp:49
const real_t PI
Definition hardware_in_the_loop_sync.cpp:51
void report(const std::string &name, const Statistics &s)
Definition hardware_in_the_loop_sync.cpp:190
const real_t REPORT_PERIOD
Definition hardware_in_the_loop_sync.cpp:54
const real_t DROP_LENGTH
Definition hardware_in_the_loop_sync.cpp:56
const real_t BEHIND
Definition hardware_in_the_loop_sync.cpp:58
const real_t STALE_AFTER
Definition hardware_in_the_loop_sync.cpp:59
const real_t SIM_PERIOD
Definition hardware_in_the_loop_sync.cpp:57
Statistics run_in_process(real_t duration, bool extrapolate, const std::string &csv)
Definition hardware_in_the_loop_sync.cpp:201
const real_t DROP_FROM
Definition hardware_in_the_loop_sync.cpp:55
void real_robot(Transport &transport, real_t duration, steady::time_point start)
Definition hardware_in_the_loop_sync.cpp:76
Statistics simulation(Transport &transport, real_t duration, bool extrapolate, steady::time_point start, const std::string &csv)
Definition hardware_in_the_loop_sync.cpp:116
const real_t SPEED
Definition hardware_in_the_loop_sync.cpp:52
int run(real_t duration, const std::string &transport, const std::string &role, const std::string &broker)
Definition hardware_in_the_loop_sync.cpp:218
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 jitter
[s], the standard deviation of a delay added to latency
Definition transport.h:86
real_t loss
the probability that a message is lost
Definition transport.h:87
What a participant of a distributed simulation sends: the state of its bodies at one step,...
Definition state_message.h:64
real_t time
Definition state_message.h:74
uint_t step
Definition state_message.h:73
std::string participant
Definition state_message.h:72
std::string encode() const
The message in MessagePack, for a transport.
Definition state_message.cpp:58
real_t stamp
Definition state_message.h:75
std::vector< BodyState > bodies
Definition state_message.h:76
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
std::vector< std::string > peers
Definition synchroniser.h:54
real_t stale_after
wall-clock: a state older than this is stale [s]
Definition synchroniser.h:60
bool extrapolate
wall-clock: move the states forward by their age
Definition synchroniser.h:61
Definition hardware_in_the_loop_sync.cpp:62
real_t x
Definition hardware_in_the_loop_sync.cpp:63
real_t y
Definition hardware_in_the_loop_sync.cpp:63
real_t theta
Definition hardware_in_the_loop_sync.cpp:63
Definition hardware_in_the_loop_sync.cpp:108
real_t mean_error
Definition hardware_in_the_loop_sync.cpp:109
real_t worst_gap_error
Definition hardware_in_the_loop_sync.cpp:111
real_t max_error
Definition hardware_in_the_loop_sync.cpp:109
uint_t n_overruns
Definition hardware_in_the_loop_sync.cpp:110
uint_t n_stale
Definition hardware_in_the_loop_sync.cpp:110
real_t mean_age
Definition hardware_in_the_loop_sync.cpp:109
real_t closest
Definition hardware_in_the_loop_sync.cpp:111
uint_t n_stopped
Definition hardware_in_the_loop_sync.cpp:110
uint_t n_steps
Definition hardware_in_the_loop_sync.cpp:110