A robot tows a trailer on a stiff tow bar. The robot, with its speed controller, is one subsystem; the trailer and the bar are another. Each runs in a participant of its own, a thread or a process on any machine that reaches an MQTT broker, and every macro step they exchange the motion of the hitch and the force of the bar, repeating the step until the two agree. The result is that of the same co-simulation in one process, to the last bit.
Nothing beyond bitsim for the threads of one process. For two processes, bitsim built with MQTT and a broker such as mosquitto; see Installing bitsim.
The robot's PI controller pushes with at most 150 N to follow a speed that rises to 1 m/s, holds, and falls back to 0. The bar is 0.5 m long, with a stiffness of 20 kN/m: it barely stretches, and that is what makes the coupling hard.
Every try of a macro step, a participant steps its own subsystem, sends its outputs, and waits for those of the other, with bitsim's Synchroniser in lockstep. Then each participant has the outputs of both. From the layout, which both share, each works out the inputs of both subsystems, how far they moved, and whether to try again, so the two decide alike without another message. Both run the same jacobi_step() as CoSimulation does in one process, with the same numbers, so they get its result to the last bit.
The processes took the same 9663 tries as the threads, and saw the same forces.
Loosely coupled, the bar force is wrong by up to 130 N, more than twice the largest true force, and while the robot cruises it is wrong all the time. That is not noise: with its inputs held, the trailer sees the hitch where it was at the start of the step, 1 cm behind where it is at 1 m/s and 0.01 s, and the bar turns 1 cm into 200 N. The stiffer the coupling and the faster the robot, the larger the error. The speeds look almost right, since the error is a force that the robot's controller mostly cancels, which is why such errors go unnoticed. Strongly coupled, the force is within 0.2 N of the whole system everywhere, for 12 tries per step.
Every try costs a round trip: 62 microseconds between threads, and 131 through mosquitto with set_tcp_nodelay true. Without it mosquitto delays small messages by about 40 ms, and a strong step would take half a second. Strong coupling across processes pays off for subsystems whose steps cost more than a round trip: a physics engine, a detailed model of a motor, or a tool of its own.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
namespace
{
using vec = std::vector<real_t>;
const real_t M_TRAILER = 50.0;
const real_t KP = 400.0, KI = 200.0, F_MAX = 150.0;
{
if (t < 1.0)
return 0.0;
if (t < 2.0)
return t - 1.0;
if (t < 5.0)
return 1.0;
if (t < 6.0)
return 6.0 - t;
return 0.0;
}
{
const real_t e = target_speed(t) - v;
return std::clamp(KP * e + KI * integral, -F_MAX, F_MAX);
}
real_t bar_force_on_robot(
const vec &robot,
const vec &trailer)
{
const real_t stretch = robot[0] - trailer[0] - L_BAR;
return -K_BAR * stretch - D_BAR * (robot[1] - trailer[1]);
}
std::unique_ptr<OdeSubsystem> robot()
{
return std::make_unique<OdeSubsystem>(
vec{0.0, 0.0, 0.0}, 1, 2,
[](
real_t t,
const vec &x,
const vec &u)
{
const real_t f = motor_force(t, x[1], x[2]);
return vec{x[1], (f + u[0]) / M_ROBOT, target_speed(t) - x[1]};
},
[](const vec &x, const vec &) {
return vec{x[0], x[1]};
},
SUBSTEPS);
}
std::unique_ptr<OdeSubsystem> trailer()
{
return std::make_unique<OdeSubsystem>(
vec{-L_BAR, 0.0}, 2, 1,
[](
real_t,
const vec &x,
const vec &u) {
return vec{x[1], (-bar_force_on_robot(u, x) - ROLLING * x[1]) / M_TRAILER};
},
[](const vec &x, const vec &u) { return vec{bar_force_on_robot(u, x)}; }, SUBSTEPS);
}
{
l.
connect(
"robot", 0,
"trailer", 0);
l.
connect(
"robot", 1,
"trailer", 1);
l.
connect(
"trailer", 0,
"robot", 0);
return l;
}
{
return c;
}
struct Run
{
vec force;
vec robot_v;
vec trailer_v;
double seconds{0.0};
};
{
auto r = robot();
auto t = trailer();
cs.add("robot", *r);
cs.add("trailer", *t);
const auto wiring = layout();
for (const auto &c : wiring.connections())
{
cs.connect(c.from, c.output, c.to, c.input);
}
cs.initialise();
const auto n =
static_cast<uint_t>(std::llround(DURATION / H));
for (
uint_t k = 0; k < n; ++k)
{
cs.step(H);
run.force.push_back(cs.inputs(
"robot")[0]);
run.robot_v.push_back(r->state()[1]);
run.trailer_v.push_back(t->state()[1]);
}
run.tries = cs.total_iterations();
run.not_converged = cs.n_not_converged();
}
{
const auto substeps =
static_cast<uint_t>(std::llround(H / 1e-5));
{0.0, 0.0, 0.0, -L_BAR, 0.0}, 0, 1,
[](
real_t t,
const vec &x,
const vec &)
{
const real_t bar = bar_force_on_robot({x[0], x[1]}, {x[3], x[4]});
const real_t f = motor_force(t, x[1], x[2]);
return vec{x[1], (f + bar) / M_ROBOT, target_speed(t) - x[1], x[4],
(-bar - ROLLING * x[4]) / M_TRAILER};
},
[](const vec &x, const vec &) {
return vec{bar_force_on_robot({x[0], x[1]}, {x[3], x[4]})};
},
substeps);
vec force;
const auto n =
static_cast<uint_t>(std::llround(DURATION / H));
for (
uint_t k = 0; k < n; ++k)
{
whole.do_step(k * H, H, {}, {});
force.push_back(whole.outputs({})[0]);
}
return force;
}
{
return *std::max_element(v.begin(), v.end(),
[](
real_t a,
real_t b) { return std::abs(a) < std::abs(b); });
}
real_t max_error(
const vec &a,
const vec &b)
{
for (std::size_t k = 0; k < a.size(); ++k)
{
e = std::max(e, std::abs(a[k] - b[k]));
}
return e;
}
{
mine = name == "robot" ? robot() : trailer();
const auto start = std::chrono::steady_clock::now();
p.initialise();
const auto n =
static_cast<uint_t>(std::llround(DURATION / H));
for (
uint_t k = 0; k < n; ++k)
{
p.step(H);
run.force.push_back(p.inputs(
"robot")[0]);
}
run.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
run.tries = p.total_iterations();
run.not_converged = p.n_not_converged();
p.leave();
}
}
int main(
int argc,
char **argv)
{
std::string csv_path =
"towing.csv", transport =
"inprocess",
participant,
broker = "tcp://localhost:1883";
bool use_loose = false;
for (int i = 1; i < argc; ++i)
{
const std::string a = argv[i];
auto next = [&]() -> std::string
{
if (i + 1 >= argc)
{
std::cerr << a << " needs a value\n";
std::exit(1);
}
return argv[++i];
};
if (a == "--macro-step")
else if (a == "--csv")
csv_path = next();
else if (a == "--transport")
transport = next();
else if (a == "--participant")
else if (a == "--broker")
broker = next();
else if (a == "--loose")
use_loose = true;
else
{
std::cerr << "unknown option " << a << "\n";
return 1;
}
}
if (transport == "mqtt")
{
#ifdef BITSIM_MQTT
if (participant != "robot" && participant != "trailer")
{
std::cerr << "--transport mqtt needs --participant robot or trailer\n";
return 1;
}
std::unique_ptr<OdeSubsystem> mine;
const auto run = participate(participant, mqtt, use_loose ? loose() : strong(), H, mine);
std::printf("%s: %zu macro steps, %u tries, in %.2f s, %.0f microseconds a try; the "
"largest bar force %.9f N\n",
run.seconds, 1e6 *
run.seconds /
run.tries, peak);
return 0;
#else
std::cerr << "this bitsim was built without MQTT\n";
return 1;
#endif
}
if (transport != "inprocess")
{
std::cerr << "--transport is inprocess or mqtt\n";
return 1;
}
std::printf("A robot tows a trailer on a stiff bar for %.0f s, macro step %.3f s\n\n", DURATION,
H);
const auto ref = reference_force(H);
const auto l = in_one_process(loose(), H);
const auto s = in_one_process(strong(), H);
const auto n = ref.size();
auto peak = [](const vec &v)
{
p = std::max(p, std::abs(f));
return p;
};
std::printf("1. In one process: the force of the bar [N]\n");
std::printf(" largest force largest error tries per step\n");
std::printf(" whole system, one solver %12.1f\n", peak(ref));
std::printf(" loose coupling %12.4g %12.4g %14.1f\n", peak(l.force),
max_error(l.force, ref),
static_cast<real_t>(l.tries) / n);
std::printf(" strong coupling %12.1f %12.4g %14.1f\n", peak(s.force),
max_error(s.force, ref),
static_cast<real_t>(s.tries) / n);
std::printf(" strong steps that did not converge: %u\n\n",
static_cast<unsigned>(s.not_converged));
std::printf("2. The robot and the trailer in participants of their own, threads on a bus\n");
Run on_robot, on_trailer;
std::unique_ptr<OdeSubsystem> robot_sub, trailer_sub;
std::thread a([&] { on_robot = participate("robot", *tr, strong(), H, robot_sub); });
std::thread b([&] { on_trailer = participate("trailer", *tt, strong(), H, trailer_sub); });
a.join();
b.join();
std::printf(" %u tries in %.3f s: %.0f microseconds a try for the exchange and the step\n",
static_cast<unsigned>(on_robot.tries), on_robot.seconds,
1e6 * on_robot.seconds / on_robot.tries);
std::printf(
" the largest bar force %.9f N\n",
largest(on_robot.force));
std::printf(" both saw the bar force of the one process at every step, to the last bit: "
"%s\n",
on_robot.force == s.force && on_trailer.force == s.force ? "true" : "false");
std::ofstream csv(csv_path);
csv << "t,target,robot,trailer,force whole system,force strong,force loose\n";
for (std::size_t k = 0; k < n; ++k)
{
csv << t << "," << target_speed(t) << "," << s.robot_v[k] << "," << s.trailer_v[k] << ","
<< ref[k] << "," << s.force[k] << "," << l.force[k] << "\n";
}
std::printf("\nthe speeds and the bar force are in %s\n", csv_path.c_str());
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
One subsystem of a co-simulation, in a process or on a machine of its own.
Definition cosim_participant.h:44
A co-simulation in one process: the master algorithm that steps coupled subsystems,...
Definition co_simulation.h:37
The subsystems of a co-simulation, their sizes, and which output feeds which input.
Definition coupling.h:35
uint_t add(const std::string &name, uint_t n_inputs, uint_t n_outputs)
Add a subsystem; its index is the number of subsystems before it.
Definition coupling.cpp:12
void connect(const std::string &from, uint_t output, const std::string &to, uint_t input)
Definition coupling.cpp:36
A subsystem given by its equations: the state x moves with dx/dt = f(t, x, u), and the outputs are y ...
Definition cosim_subsystem.h:70
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
How the participants of a distributed simulation reach each other: everything one publishes,...
Definition transport.h:34
int main()
Definition discounted_returns.cpp:19
Definition co_simulation.cpp:9
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
Outcome participant(uint_t agent, Transport &transport, uint_t n_episodes)
Definition distributed_independent_learners.cpp:85
H
Definition extended_kalman_filter.py:42
json run(const Config &c, real_t learning_rate, const fs::path &dir, bitrl::network::TensorboardServer *tensorboard)
Definition log_experiment.cpp:106
real_t largest(const std::vector< real_t > &v)
Definition point_to_point.cpp:46
How a co-simulation couples its subsystems.
Definition coupling.h:102
uint_t max_iterations
JACOBI: the most tries of a macro step; 1 couples loosely.
Definition coupling.h:104
real_t tolerance
JACOBI: done when no input moves by more than this.
Definition coupling.h:105
bool extrapolate
Definition coupling.h:111