bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Two masses on a stiff spring, co-simulated

A co-simulation splits a system into subsystems, each simulated by its own solver, which meet only every macro step to exchange the variables that couple them: forces one way, motions the other. That lets a robot simulated in one tool drive a load simulated in another, or each part of a system run in a process or on a machine of its own. The price is that between two meetings each subsystem only guesses what the others do.

Here two masses joined by a stiff spring are split into two subsystems, the benchmark of co-simulation, and simulated with three ways of coupling them, against the whole system integrated by one solver.

x1 over time with a macro step of 0.02 s

What you need

Nothing beyond bitsim.

The system

Mass 1 hangs on a soft spring, mass 2 on a stiff one, and a stiff spring with a little damping joins them. The split is the usual force-displacement coupling:

Subsystem State Inputs Outputs
mass 1 \(x_1, v_1\) the force of the coupling spring on mass 1 \(x_1, v_1\)
mass 2 \(x_2, v_2\) \(x_1, v_1\) the force of the coupling spring on mass 1

The coupling spring belongs to mass 2, so its output, \(k_c (x_2 - x_1) + d_c (v_2 - v_1)\), depends on its inputs directly: a direct feedthrough. Each subsystem is an OdeSubsystem, given by its equations and integrated with 10 Runge-Kutta steps per macro step:

auto mass_1 = std::make_unique<OdeSubsystem>(
vec{1.0, 0.0}, 1, 2, // x0, 1 input, 2 outputs
[](real_t, const vec &x, const vec &u) { return vec{x[1], (-K1 * x[0] + u[0]) / M1}; },
[](const vec &x, const vec &) { return vec{x[0], x[1]}; });
CoSimulation cs(config);
cs.add("mass 1", *mass_1);
cs.add("mass 2", *mass_2);
cs.connect("mass 1", 0, "mass 2", 0); // x1
cs.connect("mass 1", 1, "mass 2", 1); // v1
cs.connect("mass 2", 0, "mass 1", 0); // the force on mass 1
cs.initialise(); // the inputs at t = 0, through the feedthrough
for (...)
cs.step(H);

Loose and strong coupling

CoSimulation is the master algorithm: it steps the subsystems and passes the outputs of each to the inputs of the others. Over a step from \(t_n\) to \(t_{n+1}\) a subsystem's inputs move in a straight line from those at \(t_n\) to a guess of those at \(t_{n+1}\). CouplingConfig decides how:

  • Loose coupling, inputs held (Jacobi): both subsystems step at the same time, the guess being the inputs at \(t_n\). Each sees the other frozen for the whole step.
  • Loose coupling, extrapolated: the guess is the straight line through the inputs at \(t_{n-1}\) and \(t_n\).
  • Gauss-Seidel: mass 1 steps first, with its inputs held; mass 2 then steps with the outputs of mass 1 at \(t_{n+1}\).
  • Strong coupling: Jacobi, repeated. After a try, the outputs give the inputs they imply; if those differ from the guess by more than a tolerance, every subsystem goes back to the state it saved and tries again, with the new inputs. When they agree, the two subsystems have stepped together, as one system would.

Output

1. The error of x1 at t = 2 s, against the whole system with one solver
macro step [s] loose, inputs held loose, extrapolated Gauss-Seidel strong tries per strong step
0.0400 8.47e+01 3.30e+00 2.47e+00 8.59e-02 18.9
0.0200 9.04e+00 4.94e-01 5.49e-01 2.21e-02 14.7
0.0100 1.30e+00 1.11e-01 1.90e-01 5.57e-03 11.2
0.0050 3.61e-01 2.74e-02 8.06e-02 1.40e-03 9.8
0.0025 1.39e-01 6.88e-03 3.73e-02 3.49e-04 9.0
2. A macro step of 0.05 s, for 5 s: the largest |x1|; it starts at 1
loose, inputs held 4.42e+05 unstable
loose, extrapolated 596 unstable
Gauss-Seidel 136 unstable
strong 0.973
3. The two subsystems on two threads
strong coupling gives the same x1 at every step, to the last bit: true

x1 starts at 1 m, so an error of 1 is as large as the motion itself. Held inputs give errors that shrink only slowly with the macro step, and wrong answers down to a few milliseconds. Extrapolating and Gauss-Seidel are better, but strong coupling is a different class: its error falls by 4 every time the macro step halves, second order, and it is 20 to 30 times smaller than the best loose scheme at the same step. With a macro step of 0.05 s, a quarter of the period of the stiff mode, every loose scheme feeds energy into the spring until it blows up; strong coupling stays stable.

A strong step costs 9 to 19 tries with this tolerance, \(10^{-12}\). A looser tolerance takes fewer, and a strong step with a long macro step can still be cheaper than loose coupling with the macro step that its accuracy would need.

The subsystems of a try do not depend on each other, so set_pool() steps them on threads; the result is the same to the last bit. A robot and its trailer, co-simulated in two processes puts each subsystem in a process of its own.

Running the example

./two_mass_oscillator [--csv oscillator.csv]
python examples/13_co_simulation/two_mass_oscillator/plot.py oscillator.csv two_mass_oscillator.png

Things to try

  1. Set the tolerance of the strong scheme to \(10^{-6}\). How many tries does a step take, and how much does the error grow?
  2. Give mass 1 the coupling spring instead, so that mass 1 outputs the force and mass 2 its motion. Which loose scheme suffers most?
  3. Set relaxation to 0.5. Does the strong scheme take more tries, or fewer?

The code

// Two masses joined by a stiff spring, simulated as two subsystems that meet only every macro
// step: the benchmark of co-simulation. It compares loose coupling, Gauss-Seidel and strong
// coupling with the whole system integrated by one solver.
//
// Usage: two_mass_oscillator [--csv oscillator.csv]
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
namespace
{
using namespace bitsim::cosim;
// mass 1 on a soft spring, mass 2 on a stiff one, joined by a stiff spring with a little damping
const real_t M1 = 1.0, K1 = 10.0;
const real_t M2 = 1.0, K2 = 1000.0, D2 = 0.1;
const real_t KC = 100.0, DC = 0.1;
const uint_t SUBSTEPS = 10; // Runge-Kutta steps of each subsystem per macro step
using vec = std::vector<real_t>;
// the force of the coupling spring on mass 1, from the state of mass 2 and that of mass 1
real_t coupling_force(const vec &x2, const vec &x1)
{
return KC * (x2[0] - x1[0]) + DC * (x2[1] - x1[1]);
}
// A: mass 1. State (x1, v1); input the force of the coupling on it; outputs (x1, v1)
std::unique_ptr<OdeSubsystem> mass_1()
{
return std::make_unique<OdeSubsystem>(
vec{1.0, 0.0}, 1, 2,
[](real_t, const vec &x, const vec &u) {
return vec{x[1], (-K1 * x[0] + u[0]) / M1};
},
[](const vec &x, const vec &) {
return vec{x[0], x[1]};
},
SUBSTEPS);
}
// B: mass 2 and the coupling spring. State (x2, v2); inputs (x1, v1); output the force on mass 1,
// which depends on the inputs directly
std::unique_ptr<OdeSubsystem> mass_2()
{
return std::make_unique<OdeSubsystem>(
vec{0.0, 0.0}, 2, 1,
[](real_t, const vec &x, const vec &u) {
return vec{x[1], (-K2 * x[0] - D2 * x[1] - coupling_force(x, u)) / M2};
},
[](const vec &x, const vec &u) { return vec{coupling_force(x, u)}; }, SUBSTEPS);
}
// the whole system, with one solver: (x1, v1, x2, v2)
OdeSubsystem whole_system(uint_t substeps)
{
return OdeSubsystem(
{1.0, 0.0, 0.0, 0.0}, 0, 1,
[](real_t, const vec &x, const vec &)
{
const real_t f = coupling_force({x[2], x[3]}, {x[0], x[1]});
return vec{x[1], (-K1 * x[0] + f) / M1, x[3], (-K2 * x[2] - D2 * x[3] - f) / M2};
},
[](const vec &x, const vec &) { return vec{x[0]}; }, substeps);
}
struct Scheme
{
std::string name;
CouplingConfig config;
};
std::vector<Scheme> schemes()
{
CouplingConfig extrapolated;
extrapolated.extrapolate = true;
strong.max_iterations = 50;
strong.tolerance = 1e-12;
return {{"loose, inputs held", loose},
{"loose, extrapolated", extrapolated},
{"Gauss-Seidel", seidel},
{"strong", strong}};
}
struct Run
{
std::vector<real_t> x1; // at every macro step, the start included
real_t max_abs_x1{0.0};
real_t tries_per_step{0.0};
};
Run cosimulate(const CouplingConfig &config, real_t H, real_t T,
{
auto a = mass_1();
auto b = mass_2();
CoSimulation cs(config);
cs.add("mass 1", *a);
cs.add("mass 2", *b);
cs.connect("mass 1", 0, "mass 2", 0); // x1
cs.connect("mass 1", 1, "mass 2", 1); // v1
cs.connect("mass 2", 0, "mass 1", 0); // the force on mass 1
cs.set_pool(pool);
cs.initialise();
Run run;
run.x1.push_back(a->state()[0]);
const auto n = static_cast<uint_t>(std::llround(T / H));
for (uint_t s = 0; s < n; ++s)
{
cs.step(H);
run.x1.push_back(a->state()[0]);
run.max_abs_x1 = std::max(run.max_abs_x1, std::abs(a->state()[0]));
}
run.tries_per_step = static_cast<real_t>(cs.total_iterations()) / n;
return run;
}
std::vector<real_t> reference(real_t H, real_t T)
{
// Runge-Kutta steps of 10 microseconds
auto whole = whole_system(static_cast<uint_t>(std::llround(H / 1e-5)));
std::vector<real_t> x1{whole.state()[0]};
const auto n = static_cast<uint_t>(std::llround(T / H));
for (uint_t s = 0; s < n; ++s)
{
whole.do_step(s * H, H, {}, {});
x1.push_back(whole.state()[0]);
}
return x1;
}
} // namespace
int main(int argc, char **argv)
{
std::string csv_path = "oscillator.csv";
for (int i = 1; i + 1 < argc; i += 2)
{
if (std::string(argv[i]) == "--csv")
{
csv_path = argv[i + 1];
}
}
const real_t T = 2.0;
const auto all = schemes();
std::printf("1. The error of x1 at t = %.0f s, against the whole system with one solver\n\n",
T);
std::printf(" macro step [s]");
for (const auto &s : all)
{
std::printf(" %20s", s.name.c_str());
}
std::printf(" tries per strong step\n");
for (const real_t H : {0.04, 0.02, 0.01, 0.005, 0.0025})
{
const real_t ref = reference(H, T).back();
std::printf(" %14.4f", H);
real_t tries = 0.0;
for (const auto &s : all)
{
const auto run = cosimulate(s.config, H, T);
std::printf(" %20.2e", std::abs(run.x1.back() - ref));
tries = run.tries_per_step;
}
std::printf(" %21.1f\n", tries);
}
const real_t H_long = 0.05;
std::printf("\n2. A macro step of %.2f s, for 5 s: the largest |x1|; it starts at 1\n", H_long);
for (const auto &s : all)
{
const auto run = cosimulate(s.config, H_long, 5.0);
std::printf(" %20s %10.3g%s\n", s.name.c_str(), run.max_abs_x1,
run.max_abs_x1 > 2.0 ? " unstable" : "");
}
std::printf("\n3. The two subsystems on two threads\n");
const auto alone = cosimulate(all.back().config, 0.01, T);
const auto threads = cosimulate(all.back().config, 0.01, T, &pool);
std::printf(" strong coupling gives the same x1 at every step, to the last bit: %s\n",
alone.x1 == threads.x1 ? "true" : "false");
// x1 over time with a macro step of 0.02 s, for the plot
const real_t H = 0.02;
const auto ref = reference(H, T);
std::vector<Run> runs;
for (const auto &s : all)
{
runs.push_back(cosimulate(s.config, H, T));
}
std::ofstream csv(csv_path);
csv << "t,whole system";
for (const auto &s : all)
{
csv << ",\"" << s.name << "\"";
}
csv << "\n";
for (std::size_t k = 0; k < ref.size(); ++k)
{
csv << k * H << "," << ref[k];
for (const auto &r : runs)
{
csv << "," << r.x1[k];
}
csv << "\n";
}
std::printf("\nx1 over time with a macro step of %.2f s is in %s\n", H, csv_path.c_str());
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A co-simulation in one process: the master algorithm that steps coupled subsystems,...
Definition co_simulation.h:37
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
A fixed number of threads that run the tasks given to them, in the order given.
Definition thread_pool.h:33
int main()
Definition discounted_returns.cpp:19
Definition co_simulation.cpp:9
@ GAUSS_SEIDEL
Definition coupling.h:95
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
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
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
CouplingScheme scheme
Definition coupling.h:103
real_t tolerance
JACOBI: done when no input moves by more than this.
Definition coupling.h:105
bool extrapolate
Definition coupling.h:111