bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Sensor fusion over MQTT with an extended Kalman filter

Extended Kalman filtering ran the filter on data it made itself. Here the data comes over MQTT, as it would from a robot: a Python program simulates a robot that drives a circle and publishes its noisy GPS position and its noisy inputs, and the C++ program fuses them with ExtendedKalmanFilter and publishes the estimate back. The filter is the same as in the other examples: MQTT only carries the readings in and the estimate out.

What you need

The model

The state is \((x, y, \psi, v)\): the position, the heading and the speed. The input is the speed and the rate of turn, \(u = (v, \omega)\), and the motion over a step \(\Delta t\) = 0.1 s is

\[x \mathrel{+}= v \cos\psi\, \Delta t, \qquad y \mathrel{+}= v \sin\psi\, \Delta t, \qquad \psi \mathrel{+}= \omega\, \Delta t \]

and \(v\) is the speed of the input. MotionModel in the code implements it, with its Jacobian \(F\) and \(L = I\), so that the noise \(Q\) adds to the state as it is; GPSModel says that the GPS measures \(x\) and \(y\). The covariances are those of the Python program: \(Q\) for the motion, \(R\) = I for the GPS.

The topics

Topic From What
GPS_TOPIC Python the noisy position, [x, y]
U_TOPIC Python the noisy input, [v, w]
STATE_TOPIC C++ the estimated state, as JSON

The Python program publishes a GPS reading and then the input of the same step. For each GPS reading the C++ program takes the input from its MqttSubscriber, predicts with it, corrects with the reading, and publishes the state with an MqttPublisher:

const auto z = parse(gps_topic.poll(timeout));
const auto u = parse(input_topic.poll(std::chrono::milliseconds(1000)));
ekf.predict(*u);
ekf.update(gps, *z, R);
state_topic.publish(motion.get_state().as_json());

It waits up to a minute for the first reading, and stops when none has come for 5 s.

Running the example

mosquitto # the broker, if none is running
./ekf_sensor_fusion_mqtt # in one terminal; or ./ekf_sensor_fusion_mqtt tcp://host:1883
python extended_kalman_filter.py # in another, from this example's directory

The Python program drives for 50 s, in real time. It also runs its own filter on the same data and prints its estimate next to the one it receives, which is a step behind.

Output

Listening on tcp://localhost:1883 for GPS_TOPIC and U_TOPIC; the estimate goes to STATE_TOPIC
Start extended_kalman_filter.py now
step gps x gps y est x [m] est y [m] yaw [deg] v [m/s]
1 0.344 0.188 0.174 0.095 0.4 0.026
2 0.368 0.037 0.213 0.075 -0.9 -0.421
3 0.318 0.249 0.359 0.120 -0.0 1.612
...
499 -9.312 6.880 -9.545 7.265 282.4 0.812
500 -9.584 7.064 -9.544 7.210 283.6 -0.078
No GPS reading for 5 s: 500 steps, 0 readings that could not be used

The readings are random, so each run differs. Over the 500 steps the C++ filter and the Python one agree to within the 1 mm the program prints. The GPS readings are scattered by about 0.5 m; the estimate is smoother. The speed in the state is the input's, which is noisy, as the model takes \(v\) from the input and does not filter it.

The code

// Sensor fusion over MQTT with ExtendedKalmanFilter. A Python program, extended_kalman_filter.py,
// simulates a robot that drives a circle and publishes its noisy GPS position and its noisy
// inputs. This program reads them from the broker, predicts with each input, corrects with each
// GPS reading, and publishes the estimate back. The filter is the one of the other examples; MQTT
// only carries the readings in and the estimate out.
//
// Usage: ekf_sensor_fusion_mqtt [BROKER] (default tcp://localhost:1883)
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
{
const std::string GPS_TOPIC = "GPS_TOPIC";
const std::string INPUT_TOPIC = "U_TOPIC";
const std::string STATE_TOPIC = "STATE_TOPIC";
const real_t DT = 0.1; // [s] between two readings, as in the Python program
// Wait this long for the Python program to start, and stop when it has sent nothing for
// QUIET_TIME
const std::chrono::milliseconds START_TIME(60000);
const std::chrono::milliseconds QUIET_TIME(5000);
// The state is (x, y, yaw, v); the input u = (v, omega). Each step
// x += v cos(yaw) dt, y += v sin(yaw) dt, yaw += omega dt, v = u_v
// as in the Python program, whose Jacobian this one copies
class MotionModel
{
public:
: state_({"X", "Y", "YAW", "V"}, 0.0), F_(matrix_type::Identity(4, 4)),
L_(matrix_type::Identity(4, 4))
{
}
{
const real_t yaw = state_[2];
const real_t v = u[0];
// The Jacobian at the state before the step
F_.setIdentity();
F_(0, 2) = -DT * v * std::sin(yaw);
F_(0, 3) = DT * std::cos(yaw);
F_(1, 2) = DT * v * std::cos(yaw);
F_(1, 3) = DT * std::sin(yaw);
state_[0] += DT * v * std::cos(yaw);
state_[1] += DT * v * std::sin(yaw);
state_[2] += DT * u[1];
state_[3] = v;
return state_;
}
// F, and L = I: the noise Q is added to the state as it is
const matrix_type &get_matrix(const std::string &name) const
{
if (name == "F")
{
return F_;
}
if (name == "L")
{
return L_;
}
throw std::invalid_argument("MotionModel has no matrix " + name);
}
const state_type &get_state() const { return state_; }
state_type &get_state() { return state_; }
private:
state_type state_;
};
// The GPS measures x and y
class GPSModel
{
public:
GPSModel() : H_(DynMat<real_t>::Zero(2, 4))
{
H_(0, 0) = 1.0;
H_(1, 1) = 1.0;
}
{
z << x[0], x[1];
return z;
}
const DynMat<real_t> &get_matrix(const std::string &name) const
{
if (name != "H")
{
throw std::invalid_argument("GPSModel has no matrix " + name);
}
return H_;
}
private:
};
std::optional<DynVec<real_t>> parse(const std::optional<std::string> &message)
{
if (!message)
{
return std::nullopt;
}
if (!vector)
{
return std::nullopt;
}
return vector->message;
}
int run(const std::string &broker)
{
MotionModel motion;
const GPSModel gps;
bitsim::estimation::ExtendedKalmanFilter<MotionModel> ekf(motion);
// The matrices of the Python program
Q(0, 0) = 0.1 * 0.1; // x [m^2]
Q(1, 1) = 0.1 * 0.1; // y [m^2]
Q(2, 2) = degrees_to_rad(1.0) * degrees_to_rad(1.0); // yaw [rad^2]
Q(3, 3) = 1.0; // v [m^2/s^2]
ekf.with_matrix("P", DynMat<real_t>::Identity(4, 4)).with_matrix("Q", Q);
bitsim::network::MqttSubscriber gps_topic(broker, GPS_TOPIC);
bitsim::network::MqttSubscriber input_topic(broker, INPUT_TOPIC);
bitsim::network::MqttPublisher state_topic(broker, STATE_TOPIC);
gps_topic.connect();
input_topic.connect();
state_topic.connect();
std::cout << "Listening on " << broker << " for " << GPS_TOPIC << " and " << INPUT_TOPIC
<< "; the estimate goes to " << STATE_TOPIC << "\n"
<< "Start extended_kalman_filter.py now\n\n"
<< " step gps x gps y est x [m] est y [m] yaw [deg] v [m/s]\n";
uint_t n_steps = 0;
uint_t n_bad = 0;
while (true)
{
// The Python program publishes a GPS reading, then the input of the same step
const auto z = parse(gps_topic.poll(n_steps + n_bad == 0 ? START_TIME : QUIET_TIME));
if (!z)
{
break;
}
const auto u = parse(input_topic.poll(std::chrono::milliseconds(1000)));
if (!u || u->size() != 2 || z->size() != 2)
{
++n_bad;
continue;
}
ekf.predict(*u);
ekf.update(gps, *z, R);
++n_steps;
const auto &state = motion.get_state();
state_topic.publish(state.as_json());
std::cout << std::fixed << std::setprecision(3) << std::setw(6) << n_steps << std::setw(9)
<< (*z)[0] << std::setw(9) << (*z)[1] << std::setw(12) << state[0]
<< std::setw(11) << state[1] << std::setprecision(1) << std::setw(11)
<< state[2] * 180.0 / bitsim::consts::maths::PI << std::setprecision(3)
<< std::setw(9) << state[3] << std::endl;
}
std::cout << "\nNo GPS reading for " << QUIET_TIME.count() / 1000 << " s: " << n_steps
<< " steps, " << n_bad << " readings that could not be used" << std::endl;
return n_steps > 0 ? 0 : 1;
}
} // namespace ekf_sensor_fusion_mqtt
int main(int argc, char **argv)
{
const std::string broker = argc > 1 ? argv[1] : "tcp://localhost:1883";
try
{
}
catch (const std::exception &e)
{
std::cerr << "ekf_sensor_fusion_mqtt: " << e.what() << std::endl;
return 1;
}
}
#else
#include <iostream>
int main()
{
std::cerr << "This example requires MQTT to be enable. Reconfigure bitsim with ENABLE_MQTT=ON"
<< std::endl;
return 1;
}
#endif
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
SysState utility class describing the state of a system.
Definition system_state.h:25
Definition ekf_sensor_fusion_mqtt.cpp:107
DynVec< real_t > evaluate(const DynVec< real_t > &x) const
Definition ekf_sensor_fusion_mqtt.cpp:115
GPSModel()
Definition ekf_sensor_fusion_mqtt.cpp:109
const DynMat< real_t > & get_matrix(const std::string &name) const
Definition ekf_sensor_fusion_mqtt.cpp:122
Definition ekf_sensor_fusion_mqtt.cpp:51
const state_type & get_state() const
Definition ekf_sensor_fusion_mqtt.cpp:96
state_type & evaluate(const input_type &u)
Definition ekf_sensor_fusion_mqtt.cpp:63
DynVec< real_t > input_type
Definition ekf_sensor_fusion_mqtt.cpp:55
const matrix_type & get_matrix(const std::string &name) const
Definition ekf_sensor_fusion_mqtt.cpp:83
DynMat< real_t > matrix_type
Definition ekf_sensor_fusion_mqtt.cpp:54
MotionModel()
Definition ekf_sensor_fusion_mqtt.cpp:57
bitsim::dynamics::SysState< 4 > state_type
Definition ekf_sensor_fusion_mqtt.cpp:53
int main()
Definition discounted_returns.cpp:19
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
@ Q
Definition fixed_wing_dynamics.h:38
@ R
Definition fixed_wing_dynamics.h:39
real_t degrees_to_rad(real_t degs)
Definition unit_converter.h:42
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
Eigen::MatrixX< T > DynMat
Dynamically sized matrix to use around the library.
Definition bitsim_types.h:51
double real_t
real_t
Definition bitsim_types.h:20
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
Definition ekf_sensor_fusion_mqtt.cpp:31
const std::chrono::milliseconds START_TIME(60000)
const std::chrono::milliseconds QUIET_TIME(5000)
const std::string GPS_TOPIC
Definition ekf_sensor_fusion_mqtt.cpp:37
const std::string INPUT_TOPIC
Definition ekf_sensor_fusion_mqtt.cpp:38
const real_t DT
Definition ekf_sensor_fusion_mqtt.cpp:40
int run(const std::string &broker)
Definition ekf_sensor_fusion_mqtt.cpp:149
std::optional< DynVec< real_t > > parse(const std::optional< std::string > &message)
Definition ekf_sensor_fusion_mqtt.cpp:135
const std::string STATE_TOPIC
Definition ekf_sensor_fusion_mqtt.cpp:39
state
Definition play.py:39
static std::optional< EigenVectorMessage< T > > parse(const std::string &msg)
Definition vector_message.h:26
Various unit conversion utilities.