bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Dead reckoning drift, on all the cores

Odometry from the wheel encoders showed that odometry drifts. How far? The errors are random, so the answer is a distribution, and the simplest way to get it is Monte Carlo: simulate many laps, each with its own random errors, and look at where they end. The laps are independent, so they can run on all the cores at once.

Where 20000 laps ended

What you need

Nothing beyond bitsim itself. See Installing bitsim.

One lap

A differential drive robot drives a square of 2 m sides at 0.5 m/s and turns on the spot at the corners, a quarter turn a second, integrated every 10 ms with DiffDriveDynamics. Without errors it ends where it started. With errors:

  • every step its speed is 5 % off at random, as its wheels slip;
  • every step its turn rate is off by a random 0.05 rad/s;
  • for the whole lap its turn rate has a bias, drawn once per lap with a standard deviation of 0.01 rad/s, as a gyroscope or a wheel a little larger than the other would give.

Many laps, in parallel

End lap(uint_t run)
{
std::mt19937 rng(task_seed(SEED, run)); // every lap its own errors
...
}
const auto ends = parallel_map(n_runs, lap); // ends[i] = lap(i), on every core

Each lap has its own generator, seeded from its index with task_seed(), and writes only its own result, so the laps need no lock. parallel_map returns the results in the order of the laps, so they are the same however many threads ran them: the example runs the laps once in a plain loop and once on the default pool, and compares every end.

Running the example

./parallel_monte_carlo [--runs 20000]

It writes final_positions.csv, the end of every lap, the points of the picture above.

Output

1. One lap without errors
the robot ends 3.96019e-14 m from where it started: back at the start, but for rounding
2. 20000 laps with errors
on one thread: 2.60 s; on 8 threads of the pool and this one: 0.69 s, a speed-up of 3.74
every run ended in the same place on both: true
3. Where the robot ends up
runs mean error [m] rms error [m] 95 % within [m] mean end [m]
100 0.194 0.250 0.507 (0.021, 0.012)
1000 0.220 0.278 0.540 (0.017, 0.020)
10000 0.231 0.288 0.564 (0.014, 0.025)
20000 0.230 0.286 0.561 (0.012, 0.026)

The laps took 3.7 times less time on a laptop with four cores and two threads per core; the times change from run to run, the ends do not. With BITSIM_NUM_THREADS set to 2, 4 and 8 the speed-up was about 2.4, 3.0 and 3.9: the pool's threads and the calling thread together, on four cores whose second threads add less than a core.

After one lap the robot is 23 cm from its start on average, and within 56 cm in 95 % of the laps. The picture shows why the spread is an arc and not a disc: the bias of the turn rate turns the whole square a little, and the robot ends on an arc around the middle of the square. The speed errors of the steps mostly average out over the 2000 steps of a lap. A hundred laps already give the error to within a few centimetres; the 95 % bound needs more, since few laps fall that far.

Things to try

  1. Set the bias to 0. How much smaller is the error, and what shape is the cloud now?
  2. Drive the square twice. Does the error double?
  3. Run with BITSIM_NUM_THREADS=1, 2 and 4, and plot the time against the threads.

The code

// How far off is dead reckoning after a lap? A Monte Carlo study on all the cores.
//
// A differential drive robot drives a 2 m square by odometry alone: its wheels slip a little,
// so the speed it moves at is not quite the one it commanded, and its turn rate has a small
// error too. Each run simulates one lap with its own random errors, and many runs give the
// distribution of where the robot ends up. The runs are independent, so the example runs them
// with parallel_map, first on one thread and then on all of them, and checks that the results
// are the same.
//
// Usage: parallel_monte_carlo [--runs N]
//
// Writes final_positions.csv, the end of every run, to the working directory.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <vector>
{
const real_t SIDE = 2.0; // [m]
const real_t V = 0.5; // [m/s]
const real_t W = PI / 2.0; // [rad/s], a quarter turn in 1 s
const real_t DT = 0.01; // [s]
const real_t SPEED_NOISE = 0.05; // relative error of the speed, per step
const real_t RATE_NOISE = 0.05; // error of the turn rate, per step [rad/s]
const real_t RATE_BIAS_STD = 0.01; // a bias of the turn rate for the whole lap [rad/s]
const uint_t SEED = 42;
struct End
{
};
// One lap of the square by odometry, with the errors of run `run`
{
std::mt19937 rng(static_cast<std::mt19937::result_type>(task_seed(SEED, run)));
std::normal_distribution<real_t> speed_error(0.0, SPEED_NOISE);
std::normal_distribution<real_t> rate_error(0.0, RATE_NOISE);
const real_t bias = std::normal_distribution<real_t>(0.0, RATE_BIAS_STD)(rng);
SysState<3> state(
{std::make_pair("X", 0.0), std::make_pair("Y", 0.0), std::make_pair("Theta", 0.0)});
const auto n_straight = static_cast<uint_t>(std::lround(SIDE / (V * DT)));
const auto n_turn = static_cast<uint_t>(std::lround((PI / 2.0) / (W * DT)));
for (uint_t side = 0; side < 4; ++side)
{
for (uint_t k = 0; k < n_straight; ++k)
{
const real_t v = V * (1.0 + speed_error(rng));
state = DiffDriveDynamics::integrate_state_v2(state, DT, v, bias + rate_error(rng),
{0.0, 0.0});
}
for (uint_t k = 0; k < n_turn; ++k)
{
W + bias + rate_error(rng), {0.0, 0.0});
}
}
return {state[0], state[1], std::remainder(state[2], 2.0 * PI)};
}
struct Statistics
{
real_t mean_error{0.0}, rms_error{0.0}, p95_error{0.0}, mean_x{0.0}, mean_y{0.0};
};
// Without errors the robot ends where it started, so the error is the distance from the start
Statistics statistics(const std::vector<End> &ends, std::size_t n)
{
std::vector<real_t> errors(n);
for (std::size_t i = 0; i < n; ++i)
{
errors[i] = std::hypot(ends[i].x, ends[i].y);
s.mean_error += errors[i];
s.rms_error += errors[i] * errors[i];
s.mean_x += ends[i].x;
s.mean_y += ends[i].y;
}
s.mean_error /= n;
s.rms_error = std::sqrt(s.rms_error / n);
s.mean_x /= n;
s.mean_y /= n;
std::sort(errors.begin(), errors.end());
s.p95_error = errors[static_cast<std::size_t>(0.95 * (n - 1))];
return s;
}
void run(uint_t n_runs)
{
bitsim::utils::io::print_title("1. One lap without errors");
{
{std::make_pair("X", 0.0), std::make_pair("Y", 0.0), std::make_pair("Theta", 0.0)});
for (uint_t side = 0; side < 4; ++side)
{
for (uint_t k = 0; k < 400; ++k)
{
state = DiffDriveDynamics::integrate_state_v2(state, DT, V, 0.0, {0.0, 0.0});
}
for (uint_t k = 0; k < 100; ++k)
{
state = DiffDriveDynamics::integrate_state_v2(state, DT, 0.0, W, {0.0, 0.0});
}
}
std::cout << " the robot ends " << std::hypot(state[0], state[1])
<< " m from where it started: back at the start, but for rounding\n\n";
}
bitsim::utils::io::print_title("2. " + std::to_string(n_runs) + " laps with errors");
using clock = std::chrono::steady_clock;
// a plain loop, for the time of one thread
auto start = clock::now();
std::vector<End> serial;
serial.reserve(n_runs);
for (uint_t i = 0; i < n_runs; ++i)
{
serial.push_back(lap(i));
}
const std::chrono::duration<real_t> t_serial = clock::now() - start;
start = clock::now();
const auto parallel = parallel_map(n_runs, lap); // the default pool, every core
const std::chrono::duration<real_t> t_parallel = clock::now() - start;
bool same = true;
for (std::size_t i = 0; i < n_runs; ++i)
{
same = same && serial[i].x == parallel[i].x && serial[i].y == parallel[i].y;
}
std::cout << std::fixed << std::setprecision(2) << " on one thread: " << t_serial.count()
<< " s; on " << default_thread_pool().size()
<< " threads of the pool and this one: " << t_parallel.count() << " s, a speed-up of "
<< t_serial.count() / t_parallel.count() << "\n"
<< " every run ended in the same place on both: " << std::boolalpha << same
<< "\n\n";
bitsim::utils::io::print_title("3. Where the robot ends up");
std::cout << " runs mean error [m] rms error [m] 95 % within [m] mean end [m]\n";
// more runs, a better estimate: the error of a mean shrinks with the square root of the runs
std::vector<std::size_t> sizes;
for (std::size_t n = 100; n < n_runs; n *= 10)
{
sizes.push_back(n);
}
sizes.push_back(n_runs);
for (const std::size_t n : sizes)
{
const auto s = statistics(parallel, n);
std::cout << std::setw(10) << n << std::setprecision(3) << std::setw(17) << s.mean_error
<< std::setw(16) << s.rms_error << std::setw(18) << s.p95_error << " ("
<< s.mean_x << ", " << s.mean_y << ")\n";
}
std::ofstream out("final_positions.csv");
out << "x,y,theta\n";
for (const auto &e : parallel)
{
out << e.x << "," << e.y << "," << e.theta << "\n";
}
std::cout << "\n The ends of the runs are in final_positions.csv\n";
}
} // namespace parallel_monte_carlo
int main(int argc, char **argv)
{
bitsim::uint_t n_runs = 20000;
for (int i = 1; i + 1 < argc; i += 2)
{
if (std::string(argv[i]) == "--runs")
{
n_runs = std::strtoul(argv[i + 1], nullptr, 10);
}
}
parallel_monte_carlo::run(std::max<bitsim::uint_t>(n_runs, 100));
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
DiffDriveDynamics class. Describes the motion of a differential drive robot in the plane: the centre ...
Definition diff_drive_dynamics.h:39
SysState utility class describing the state of a system.
Definition system_state.h:25
uint_t size() const noexcept
The number of threads.
Definition thread_pool.h:54
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 concurrent_queue.h:15
uint_t task_seed(uint_t base_seed, uint_t task) noexcept
A seed for task task, made from base_seed.
Definition parallel.h:148
auto parallel_map(std::size_t n, F &&f, ThreadPool &pool=default_thread_pool()) -> std::vector< std::invoke_result_t< F &, std::size_t > >
Compute f(0), f(1), ..., f(n - 1) on the threads of pool.
Definition parallel.h:119
ThreadPool & default_thread_pool()
The pool that parallel_for() and parallel_map() use when given none. It starts ThreadPool::default_n_...
Definition thread_pool.cpp:77
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
Definition parallel_monte_carlo.cpp:33
const real_t PI
Definition parallel_monte_carlo.cpp:41
End lap(uint_t run)
Definition parallel_monte_carlo.cpp:57
const uint_t SEED
Definition parallel_monte_carlo.cpp:49
const real_t SIDE
Definition parallel_monte_carlo.cpp:42
Statistics statistics(const std::vector< End > &ends, std::size_t n)
Definition parallel_monte_carlo.cpp:91
const real_t DT
Definition parallel_monte_carlo.cpp:45
const real_t V
Definition parallel_monte_carlo.cpp:43
const real_t W
Definition parallel_monte_carlo.cpp:44
const real_t RATE_BIAS_STD
Definition parallel_monte_carlo.cpp:48
void run(uint_t n_runs)
Definition parallel_monte_carlo.cpp:112
const real_t RATE_NOISE
Definition parallel_monte_carlo.cpp:47
const real_t SPEED_NOISE
Definition parallel_monte_carlo.cpp:46
state
Definition play.py:39
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
real_t y
Definition parallel_monte_carlo.cpp:53
real_t x
Definition parallel_monte_carlo.cpp:53
real_t theta
Definition parallel_monte_carlo.cpp:53
Definition parallel_monte_carlo.cpp:86
real_t mean_error
Definition parallel_monte_carlo.cpp:87
real_t mean_y
Definition parallel_monte_carlo.cpp:87
real_t rms_error
Definition parallel_monte_carlo.cpp:87
real_t p95_error
Definition parallel_monte_carlo.cpp:87
real_t mean_x
Definition parallel_monte_carlo.cpp:87