Skip to content
ImagineWorld

Encoder-Based Localisation with Python

node_idnode-book_learn-robotics-programming_chapter-12-encoder-based-localisation-with-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleEncoder-Based Localisation with Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Encoder-Based Localisation with Python

Section titled “Chapter 12 — Encoder-Based Localisation with Python”

A smart robot can use its sensors with intelligent algorithms to guess its position in a known space, improving its guess as it gathers more information about its movements within that space.

In this chapter, we will see how to build this simple kind of artificial intelligence, making many guesses about where it is with its own mental model. The robot will update these guesses about where it is when it moves, using each movement to make more informed guesses about its position.

For the robot to navigate a space, it needs a mathematical model. We will see how to build and display this model. Then we will look at how to model the robot moving in that space.

We will then see how to refine the guesses and predictions into better predictions.

In this chapter, you will learn about the following topics:

  • Representing and displaying the robot as poses
  • Modeling a test area
  • Moving poses with encoders
  • Localisation debugging tools
  • Refining pose probabilities
  • Controlling the rate of resampling

Before we get started, make sure you have the following parts:

  • The robot with the Raspberry Pi built in the previous chapters, along with the code from Chapter 11*,* Programming Encoders with Python.
  • Test area C, as built in Chapter 9*,* Avoiding Obstacles with Distance Sensors, in the Making a test area for your robot section
  • A computer with network access
  • A tape measure or ruler

You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.

This chapter’s code files are included in the downloadable code bundle.

Representing and displaying the robot as poses

Section titled “Representing and displaying the robot as poses”

We’ve seen with sensors that we represent the robot’s state as numbers. We store where the robot might be in a pose. A pose is a set of numbers that represent the robot’s location and orientation in a way code can manipulate, inspect, and visualize for us.

Our robot is a floor rover; it moves and rotates in a 2D flat space. The key way to represent this is as a Cartesian space. This uses an x and y coordinate, and a third parameter, theta, or θ to represent rotation. See the following diagram:

Figure 12.1 – Poses in a coordinate space

Figure 12.1 – Poses in a coordinate space

Figure 12.1 – Poses in a coordinate space

The diagram shows our world space. There are X and Y world axes, which start at x:0 and y:0. There’s also a world 0 theta for orientation.

There are two robots in different poses. The first robot pose A has some x A and y A with respect to the world axis. It also has a theta of 0 degrees with respect to the world theta, such that the robot’s own X axis is aligned with the world X axis. The front of the robot going forward is considered positive in the X direction in this system.

Theta is also known as yaw or heading.

The second pose, B, has different x B and y B coordinates, along with a positive θ B at around 30 degrees. The robot’s X axis no longer aligns with the world X axis, so driving forward along the robot X axis will be driving at 30 degrees from the world X axis.

The theta values represent rotations around a Z axis that would be pointing up from the robot.

Another way to think of these is what is known as the ENU convention:

  • East – X Axis
  • North – Y Axis
  • Up – Z Axis

However, this shortcut comes with the caveat that our robot operating space may not be well aligned with North, as not many walls are. We may simplify to X and Y axes aligning with the walls of our space (assuming those are at right angles to each other).

In the bottom right of the image is a pose data representation. As with the rest of the book, we use millimeters to measure distance, matching the encoder measurements. Theta θ is in terms of radians, because most manipulations of it will also be in radians.

We have a representation of a pose. Let’s try this in some code.

Our robot will need to handle many poses, so it can make many guesses and reason which are most likely. However, we’ll start working with just a few to get comfortable manipulating poses.

Let’s start by making a couple of poses. SSH into the robot, and start Python:

$ robotpython
Python 3.13.5 (main, Jun 25 2025, 18:55:22) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> prompt means you are interacting with Python on the robot. We can use that to test a pose. We are going to use numpy, so we can scale to many poses later:

>>> import numpy as np
>>> Pose = np.dtype([('x', np.float32), ('y', np.float32), ('theta', np.float32)])
>>> poses = np.array([(500, 500, 0), (150, 100, np.pi / 3)], dtype=Pose)
>>> poses[0]
np.void((500.0, 500.0, 0.0), dtype=[('x', '<f4'), ('y', '<f4'), ('theta', '<f4')])
>>> poses[1]
np.void((150.0, 100.0, 1.0471976), dtype=[('x', '<f4'), ('y', '<f4'), ('theta', '<f4')])

We’ve created a Pose NumPy datatype, with x, y, and theta. We then put two poses into np.array, a high-speed numpy array. The first pose has an x coordinate of 500, a y of 500, and theta of 0. The second pose has an x coordinate of 150, a y of 100, and a theta of Pi divided by 3, which is the radian equivalent of 60 degrees. Pi radians is equivalent to 180 degrees.

We retrieve the poses to print them, showing the values and their datatypes.

We can also ask for specific components by name:

>>> poses[0]['x']
np.float32(500.0)
>>> poses[0]['y']
np.float32(500.0)
>>> poses[0]['theta']
np.float32(0.0)
>>> poses['theta']
array([0. , 1.0471976], dtype=float32)

Here, we’ve asked for each component of the first pose. We can also do a NumPy trick where if we just ask for poses['theta'], we get back an array of all pose theta values. Press C trl + D to finish this. We can build a pose system with this.

Let’s turn what we’ve learned into a pose system to store and visualize poses by following these steps:

  1. Create the robot/common/poses.py file:
    import numpy as np
    class Poses(np.ndarray):
    Pose = np.dtype([('x', np.float32), ('y', np.float32), ('theta', np.float32)])
    def __new__(cls, input_array):
    return np.asarray(input_array, dtype=cls.Pose).view(cls)
  2. Now we can make use of this in a new file, robot/localisation.py:
    import numpy as np
    from common.mqtt_behavior import connect, publish_json
    from common.poses import Poses
    class Localisation:
    def __init__(self):
    self.poses = Poses([(500, 500, 0), (150, 100, np.pi / 3)])
    def publish_poses(self, client, poses):
    publish_json(client, "localisation/poses", poses.tolist())
    def start(self):
    client = connect()
    self.publish_poses(client, self.poses)
    client.loop_stop()
    service = Localisation()
    service.start()
    The publish_poses method lets us send poses as JSON over MQTT for a visualization tool. We pass this as a list of the current poses, but we may need to pass it a subset, so this is left as a parameter. For now, the start method connects to MQTT, publishes the poses, and stops.
  3. You’ll need to add this to deploy/deploy_services.py:
    code = files.put(
    name="Update localisation",
    src="robot/localisation.py",
    dest="robot/localisation.py")
    deploy_service("localisation",
    "robot/localisation.py",
    False, common.changed or code.changed)
  4. So we can see the poses, we will need an HTML page for localisation. We are going to ensure we have the chart libraries we need on the robot. Again, in deploy/deploy_services.py, add the following near the similar code for the mqtt library:
    files.download(
    name="Download chart js",
    src="https://cdn.jsdelivr.net/npm/chart.js",
    dest="robot_control/libs/chart.js"
    )
    files.download(
    name="Download chartjs datalabels plugin",
    src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2",
    dest="robot_control/libs/chartjs-plugin-datalabels.js"
    )
    We can load the chart from here in the future. We will be using the datalabels plugin to show the orientation of our poses as a data label.
  5. Create the robot_control/localisation.html file. Start with the following familiar code, and make a square canvas:
    {% extends "robot_control/page.html.j2" %}
    {% block title %}Localisation{% endblock %}
    {% block content %}
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <div style="height: 60vh; width: 60vh;">
    <canvas id="poses"></canvas>
    </div>
  6. We next need to load datalabels, which we’ll use to display our pose orientations. It must be loaded after chart.js:
    <script src="libs/chart.js"></script>
    <script src="libs/chartjs-plugin-datalabels.js"></script>
  7. Next, we start the JavaScript section with launcher buttons:
    <script type="module">
    import { connect, publish_when_clicked } from './mqtt_client.js';
    let mqttClient = connect();
    publish_when_clicked(mqttClient, "start", "launcher/start", "localisation");
    publish_when_clicked(mqttClient, "stop", "launcher/stop", "localisation");
  8. We now need to prepare some chart data and a way to load that JSON pose information:
    const data = {
    datasets: [{
    label: 'poses',
    data: [{x: 750, y: 750, theta: 0}],
    }],
    update_pose_data(json_data) {
    const pose_data = JSON.parse(json_data);
    this.datasets[0].data = pose_data.map(
    raw_pose => ({x: raw_pose[0], y: raw_pose[1], theta: -raw_pose[2] * 180 / Math.PI})
    );
    }
    };
    The chart data has a poses dataset, with a default pose in the middle of the chart. The update_pose_data method replaces the current poses with the pose data from json_data. This first parses the JSON into raw data, then maps each pose to a dictionary containing x, y, and theta named items. Chart.js requires these object names to work. We also convert theta to clockwise degrees for this layer.
  9. We will be using a scatter plot for the poses. The default scatter plot creates a dot, but it has no indication of orientation. So, we are going to use a data label on each dot that makes an arrow facing the direction of the pose theta. Add this to the module:
    const datalabels = {
    color: 'blue',
    font: {
    size: 24
    },
    padding: 0,
    formatter (value) {
    return '>'
    },
    rotation(ctx) {
    const index = ctx.dataIndex;
    return ctx.dataset.data[index].theta;
    }
    };
    This sets up a data label for each point; the color blue and font size are clear. The formatter usually allows us to format data points, but in this case, we ignore the value and return a greater-than sign, or an arrow to the east, aligning with an angle of 0. The rotation function uses the current context to find the data item being rendered and use its angle theta to rotate the arrow.
  10. Next, configure the chart:
    const pose_chart_config = {
    type: 'scatter',
    data: data,
    options: {
    animation: false,
    aspectRatio: 1,
    responsive: true,
    plugins: {
    datalabels
    },
    scales: {
    x: {
    suggestedMin: 0,
    suggestedMax: 1500,
    },
    y: {
    suggestedMin: 0,
    suggestedMax: 1500,
    }
    }
    },
    plugins: [ChartDataLabels]
    };
    const pose_ctx = document.getElementById('poses').getContext('2d');
    let pose_chart = new Chart(pose_ctx, pose_chart_config);
    This chart config uses the data and datalabels settings, and configures it as a scatter type. We’ve disabled animation, so poses draw immediately. The suggested x and y ranges account for the test area size; adjust both to the larger dimension for your arena size. This sets the canvas context for the chart.
  11. End the page with MQTT subscriptions for updating the data, and close the document:
    mqttClient.subscribe('localisation/#')
    mqttClient.on('message', (topic, message) => {
    switch (topic) {
    case 'localisation/poses':
    data.update_pose_data(message);
    pose_chart.update();
    break;
    }
    });
    </script>
    {% endblock %}
  12. Add a localisation menu item to robot_control/index.html.
  13. Then use the PyInfra deploy services script to send this. Use the web interface menu to enter localisation.

When you load it, you’ll see an initial pose. Click the S tart button and you should see this:

Figure 12.2 – Pose localisation display

Figure 12.2 – Pose localisation display

Figure 12.2 – Pose localisation display

The preceding figure shows the poses being displayed. At the top are the usual controls for going back to the menu. Click the S tart button if you see a pose in the middle.

There are two poses on display. One faces east, with 0 radians as its angle. The other faces Pi/3 or 60 degrees. The arrow shows their heading. Let’s ensure you see the same.

We have two components working here, both of which need slightly different strategies to debug:

  • If the web page isn’t working, use the developer (inspect) tools to see if there are any errors in the console. It’s not unusual to see an initial MQTT connection error, but you should not see any others.
  • The robot Python code is running with systemd, so use journalctl ‑u localisation.service to see any errors from it.
  • Use mosquitto sub or an MQTT client to look for the launcher/start message, followed by the localisation/poses message:
    $ mosquitto_sub -u robot -P robot -t 'launcher/#' -t 'localisation/#' -v
    launcher/start localisation
    localisation/poses [[500.0,500.0,0.0],[150.0,100.0,1.0471975511965976]]
    You should see both the messages. If you are updating only the code in the robot/ folder for fixes/changes, remember you can use deploy/update_code.py. This will not work for the HTML pages or systemd files, and will not restart running services.

We’ve built pose representation and visualization. Let’s see the building blocks to manipulate these poses.

We have two main kinds of movement or transformations to make in this space:

  • A translation changes x and y, moving the robot’s position in the space
  • A rotation changes θ (theta), but not x and y, orienting the robot in the space

These transformations are going to be common enough that we will want to put them in a common library.

A rotation is simple, by adding to theta. Let’s add a method for that in robot/common/poses.py, inside the Poses class:

def rotate(self, rotation) -> 'Poses':
result = self.copy()
result['theta'] += rotation
return result
def append(self, other) -> 'Poses':
return np.concatenate([self, other]).view(Poses)

This code copies the poses array, then adds the rotation to theta of every pose. There’s also a helper method to append lists of poses. These methods use ‑> 'Poses' to explicitly state they return another Poses object.

Then we can test this in robot/localisation.py with the highlighted change:

class Localisation:
def __init__(self):
self.poses = Poses([(500, 500, 0), (150, 100, np.pi / 3)])
self.poses = self.poses.append(self.poses.rotate(np.pi/2))

Rotations in radians are often in terms of multiples of Pi – this code rotates poses by pi/2 or 90 degrees. The code then appends them to our existing poses. When you sync this code to the robot and click the S tart button again, you should see poses at 90 degrees drawn over the original 2 poses.

Translation is a little more complex. Let’s see a translation:

Figure 12.3 – A translation

Figure 12.3 – A translation

Figure 12.3 – A translation

The preceding figure shows a pose being translated by distance L. Poses translate in the direction of theta. The starting coordinate x A, y A, θ A has a theta of 30 degrees, so the translation is at 30 degrees to the world X axis. This results in a movement in both the world x and y coordinates to the new coordinates x T, y T, θ T is still 30 degrees.

Calculating this translation requires some trigonometry (e.g., that for a point on a circle with a radius of L:

X T = x A + cos(θ) × L

Y T = y A + sin (θ) × L

Let’s add this to our robot/common/poses.py code:

def translate(self, length) -> 'Poses':
result = self.copy()
result['x'] += np.cos(self['theta']) * length
result['y'] += np.sin(self['theta']) * length
return result

This method copies the poses, then adds the cosine of pose theta, multiplied by length, to the x component. We do similar with the sine of theta times length added to the y component. This is done for each pose, regardless of how many poses we have.

We can test this in robot/localisation.py, translating all the poses:

class Localisation:
def __init__(self):
self.poses = Poses([(500, 500, 0), (150, 100, np.pi / 3)])
self.poses = self.poses.append(self.poses.rotate(np.pi/2))
self.poses = self.poses.append(self.poses.translate(100))

When you send this to the robot and click the S tart button, the poses should each have moved 100 mm in their own theta direction.

Figure 12.4 – Transformed poses

Figure 12.4 – Transformed poses

Figure 12.4 – Transformed poses

You should see a screen like the preceding screenshot. The screenshot shows 4 poses. From the 2 initial poses, we have 2 further copies at 90 degrees to it, then each has been translated by 100 mm in their heading.

If things aren’t looking right, check journalctl, the browser developer tools, and MQTT messages for signs of problems. Try different rotation values and lengths.

We’ve modeled poses and how to move them. Next, we need to model our test area.

The walls will be modeled using the same X, Y coordinate system as the poses. We’ll start by making a drawing of test area C, but using coordinates:

Figure 12.5 – The walls represented as edges

Figure 12.5 – The walls represented as edges

Figure 12.5 – The walls represented as edges

The preceding figure shows the walls or boundaries of our test area. Each corner has a coordinate written in it, a vertex or plural vertices.

You may not have a space large enough or the right shape. You can use a smaller or different shape under these conditions:

The space is approximately the same L shape, a rectangle with a corner cut out of it. Non-right angles make things significantly more complicated, and without the corner feature, all sides look the same to the robot.

You will need to take measurements in mm of the space, all corners, and translate those numbers here, in the walls list, and the boundary-checking conditions.

In the diagram, a numbered list of vertices is shown in the middle of the arena, starting from the vertex at index 0. We will use a ring of these vertices to specify the wall.

We can store this as code in robot/common/arena.py:

from common.mqtt_behavior import publish_json
left = 0
bottom = 0
right = 1500
top = 1500
cutout_left = 1000
cutout_top = 500
walls = [
(left, top),
(right, top),
(right, cutout_top),
(cutout_left, cutout_top),
(cutout_left, bottom),
(left, bottom)
]
def publish_map(client):
publish_json(client, "localisation/map", {
"walls": walls
})

This defines the arena dimensions and has a function to serve up with MQTT. Let’s incorporate it into the localisation system. In the robot/localisation.py imports section, add the following:

from common import arena

We can serve this up via MQTT when the system starts with the highlighted change:

def start(self):
client = connect()
arena.publish_map(client)
self.publish_poses(client, self.poses)

We then need to show this on the web pages:

  1. Add the following code above pose_chart_config in robot_control/localisation.html:
    const mapPlotter = {
    id: 'mapPlotter',
    walls: [],
    scaledWallVertex(vertex, scales) {
    return [
    scales.x.getPixelForValue(vertex[0]),
    scales.y.getPixelForValue(vertex[1])
    ]
    },
    This makes mapPlotter, a plugin to translate the map data into a polygon on the chart. It has an id member, and an empty list of walls, which will come via MQTT. Our mapPlotter tool plots with JavaScript’s canvas system, a little more raw than Chart.js; however, we can ask the Chart.js scales (the x scale and y scale) where a plot value should be as a pixel on the canvas with getPixelForValue.
  2. We now need to draw it using these scaled vertices:
    drawWalls(ctx, scales) {
    ctx.save();
    ctx.strokeStyle = 'rgba(0, 0, 255, 1)';
    ctx.lineWidth = 2;
    ctx.beginPath();
    let scaledVertex = this.scaledWallVertex(this.walls[0], scales);
    ctx.moveTo(scaledVertex[0], scaledVertex[1]);
    for (const vertex of this.walls) {
    scaledVertex = this.scaledWallVertex(vertex, scales);
    ctx.lineTo(scaledVertex[0], scaledVertex[1]);
    }
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
    },
    This method draws the walls onto a JavaScript canvas context, the ctx parameter. The second parameter will be the scales for our chart. The drawing starts by saving the current context parameters so it can restore them after it’s complete. We then set strokeStyle and width for thick blue lines. We start a path (a chain of lines) with beginPath and move to the first scaled vertex to begin the drawing. We then loop over each vertex in the walls, scaling the vertex, then drawing a line to it. After drawing the lines, we close the path, adding a line back to the start. We then tell the context to stroke (draw the outline) of the path we just described. Finally, we restore the saved parameters so the chart can go back to whatever it was drawing before.
  3. We need to make a beforeDraw method, and close the mapPlotter object:
    beforeDraw(chart, args, options) {
    const { ctx, scales } = chart;
    if(this.walls.length==0) {
    return;
    }
    this.drawWalls(ctx, scales);
    }
    }
    The beforeDraw method is part of a Chart.js plugin specification, and is called as part of the render process before the other points on the chart are drawn. It starts by unpacking a chart canvas context, then checks to see if there are any walls yet. If there are walls, the method will draw them.
  4. Add it to the plugin list in pose_chart_config to register this plugin:
    const pose_chart_config = {
    type: 'scatter',
    data: data,
    options: {
    animation: false,
    responsive: true,
    plugins: {
    datalabels
    },
    scales: {
    x: {
    suggestedMin: 0,
    suggestedMax: 1500,
    },
    y: {
    suggestedMin: 0,
    suggestedMax: 1500,
    }
    }
    },
    plugins: [ChartDataLabels, mapPlotter]
    };
  5. Chart updates with poses can cause a logjam. This code allows it to redraw after handling any MQTT messages – add it after pose_chart:
    let awaiting_update = false;
    function triggerChartUpdate() {
    awaiting_update = true;
    setTimeout(() => {
    awaiting_update = false;
    pose_chart.update();
    }, 0);
    }
    The timer starts when other messages are completed, and the awaiting_update variable tracks if we’ve triggered a chart update yet to be drawn.
  6. Modify our subscription and topic handling to update the map and only update poses if we aren’t already waiting to update some:
    mqttClient.subscribe('localisation/#')
    mqttClient.on('message', (topic, message) => {
    switch (topic) {
    case 'localisation/poses':
    if (awaiting_update) {
    return;
    }
    data.update_pose_data(message);
    triggerChartUpdate();
    break;
    case 'localisation/map':
    const payload = JSON.parse(message);
    mapPlotter.walls = payload.walls;
    triggerChartUpdate();
    break;
    }
    });

You can now run deploy services again, reload the localisation page, then click S tart. This should draw the boundary around the poses.

Our robot localisation will work by trying a swarm of pose predictions, and then eliminating those that don’t work, or at least reducing the likelihood of incorrect guesses. We use many predicted poses, so we can calculate how likely they are.

The localisation method makes random predictions, moves them with the robot, then validates them against observations of the real world, refining them to more likely, less random predictions.

With more poses, we have more data to validate, which improves the probability of having poses close to the real pose of the robot. There’s a balance here between the number of poses and processing time.

We can set out the number of poses and where we want them in robot/localisation.py. After the imports, add the following:

population_size = 200

We then need to generate them, completely replacing the previous __init__ method:

class Localisation:
def __init__(self):
self.poses = Poses.generate(population_size, (arena.left, arena.right), (arena.bottom, arena.top), (0, 2 * np.pi))

In robot/common/poses.py, let’s implement this pose generation method, based on random selection. First, add a NumPy random number generator after the imports:

rng = np.random.default_rng()

Then, within the Poses class, add this method to generate random poses inside a range:

@classmethod
def generate(cls, count, x_range, y_range, theta_range) -> 'Poses':
poses = np.empty((count,), dtype=cls.Pose)
poses['x'] = rng.uniform(x_range[0], x_range[1], count)
poses['y'] = rng.uniform(y_range[0], y_range[1], count)
poses['theta'] = rng.uniform(theta_range[0], theta_range[1], count)
return poses.view(cls)

This generate method samples uniformly from the provided ranges: x between the arena’s left and right bounds (x_range), y between the top and bottom bounds (y_range), and theta between 0 and 2 pi.

This is where we introduce probability, using numbers to describe how likely an outcome is. A probability distribution is a way to discuss where guesses are, in the space of all guesses.

The following diagram shows two probability distributions we will be using:

Figure 12.6 – Probability distributions

Figure 12.6 – Probability distributions

Figure 12.6 – Probability distributions

The preceding diagram shows two probability distributions. The first is a U niform D istribution, taking a sample from any possible value inside the bounds, without being skewed to any particular space. The samples are just as likely to be right at a boundary as in the middle, or anywhere else.

On the right is a N ormal D istribution, with a bell-like curve. It’s also known as a Gaussian distribution, and has the property that values are more likely around a central mean, with values less likely as you go further from this mean.

Our pose generation algorithm uses the uniform distribution, so the samples are distributed right across the space. The following screenshot shows how this looks:

Figure 12.7 – Many poses

Figure 12.7 – Many poses

Figure 12.7 – Many poses

The preceding screenshot now shows 200 random poses, and the boundary drawn. Some poses, however, are outside of the cutout. The poses need refining, but let’s get them moving with the robot first.

Our robot’s encoders return data about the robot’s movements, which we can use to move the poses. We also need our control page to select a movement system for the robot.

Our localisation system needs a way to generate movement. While automatic movement systems are handy, we want to have a predictable source of movement. The joystick is suitable for driving from the phone, but for really predictable movement from a desktop browser, a keyboard system is more familiar.

We are going to build a movement system that can use the familiar gaming W, A, S, and D keys to move the robot. There’s a JavaScript helper library, keydrown.js, we can use to make this easy.

Create the file robot_control/keyboard_drive.js. We will use a setup function to wire this together. We start the setup with some parameters:

export function setup_keyboard_drive({
mqtt_client,
publish_interval_ms = 75,
throttle_scale = 0.7,
turn_scale = 0.45,
}) {

This starts a setup_keyboard_drive function. This sets up a dictionary of default parameters, which in JavaScript lets us override just the ones we need, similar to keyword parameters in Python. The option mqtt_client is a place to pass the MQTT connection, so we can send messages over MQTT in response to keypresses. We have publish_interval_ms, how often the keyboard will be checked in milliseconds. Then throttle_scale is how fast the robot will move forward or backward when W and S are pressed. Finally, turn_scale is how fast the robot will turn when the A or D buttons are held.

const kd = window.kd;
function update() {
const throttle = (kd.W.isDown() ? 1 : 0) - (kd.S.isDown() ? 1 : 0);
const turn = (kd.D.isDown() ? 1 : 0) - (kd.A.isDown() ? 1 : 0);
const left_motor = Math.max(-1, Math.min(1, throttle * throttle_scale + turn * turn_scale));
const right_motor = Math.max(-1, Math.min(1, throttle * throttle_scale - turn * turn_scale));
mqtt_client.publish('motors/wheels', JSON.stringify([left_motor, right_motor]));
}
setInterval(update, publish_interval_ms);
}

When keydrown is loaded, we will get a window.kd property referencing the library, we store a shortcut to it here in the constant kd.

The update function is embedded inside the setup function; it’s not exposed to the rest of the system. When called, this checks which keys are held down, and uses those to determine if the robot has a forward/reverse throttle, and a turn.

The update function then uses the throttle and turn values to control each motor according to the scale settings, ensuring the motor values do not go outside the -1 to 1 range.

The update function then publishes the left and right motor outputs to the motors/wheels topic.

Back in the surrounding setup_keyboard_drive function, we then use the JavaScript setInterval function to ensure this internal update function is called at every publish interval.

We now need a small change in robot_control/localisation.html to load this. In the script area, add the highlighted line:

<script src="libs/chart.js"></script>
<script src="libs/chartjs-plugin-datalabels.js"></script>
<script src="libs/keydrown.js"></script>

In the HTML file’s imports, we need to import our new keyboard drive system:

import { connect, publish_when_clicked } from './mqtt_client.js';
import { setup_keyboard_drive } from './keyboard_drive.js';

This makes our new setup function available to use. We also need to set this up after MQTT is connected:

let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "launcher/start", "localisation");
publish_when_clicked(mqttClient, "stop", "launcher/stop", "localisation");
setup_keyboard_drive({
mqtt_client: mqttClient,
});

This now has the system connected in our page after the MQTT client has been connected.

This relies on a further library, which we need to install with PyInfra. Open deploy/deploy_services.py, and make the highlighted code change:

files.download(
name="Download chartjs datalabels plugin",
src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2",
dest="robot_control/libs/chartjs-plugin-datalabels.js"
) # https://v2_2_0--chartjs-plugin-datalabels.netlify.app/guide/
files.download(
name="Download keydrown",
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/keydrown.min.js",
dest="robot_control/libs/keydrown.js"
)

The highlighted section will download the keydrown library and place it in the robot_control/libs folder on the robot.

We can now install this with pyinfra inventory.py ‑y deploy/deploy_services.py.

If you reload the localisation page in the browser, you can now press W to drive forward, S to drive back, A to turn left, and D to turn right. You can combine the throttle keys with the turn keys to drive while turning.

The robot is now moving from the localisation page. However, nothing on the page is moving yet, only the robot.

In Chapter 11, Programming E ncoders with Python, we saw how we could use encoders to drive the robot in straight lines and curves. Now we need to reverse it, determine where the robot has driven, likely a curve with less-than-perfect wheels, and update our model from it.

The following diagram has some familiar and new elements to it:

Figure 12.8 – Calculating motion from encoders

Figure 12.8 – Calculating motion from encoders

Figure 12.8 – Calculating motion from encoders

The preceding figure shows a robot moving along an arc. Panel (a) builds on elements from Figure 11.14 in Chapter 11, Programming Encoders with Python. We use the same terminology and components here since each pose is a guess of the Robot origin! The encoders will send a Left distance, and a Right distance. The distance between the curve radius for right and left is the Wheel distance.

We can end up with negative values here; however, if we always subtract the left from the right, angles will be counterclockwise, in the same ENU convention as our poses.

Reversing what we found in Chapter 11, Programming E ncoders with Python, the distances we know are the arc lengths, as shown in Panel (b) for each wheel, and from those we can deduce the turn radius and arc length.

Panel (c) shows how, if you wrap a distance around an arc, you have the arc length. The arc length of the middle distance describes the arc the robot origin moved in and will be exactly between the left and right distances, their average. That is, mid_distance = (left_distance + right_distance) /2.

We can also calculate the angle theta from what we know about the robot and its wheel movement. If you consider the left arc and right arc to be circle sectors, it’s clear that one is a scaled version of the other. The ratio between an arc length and its radii will be theta. We know that the left and right radii are different by the wheel distance. Therefore, if we take the difference between the right distance and left distance and divide that by the wheel distance, we get theta. That is, theta = (right_distance – left_distance) / wheel_distance.

In Panel (d), we use theta and the arc length to transform each pose. Moving curves can be simplified into three simpler transformations. First, we rotate to face the endpoint of the curve, half of theta. Then we translate to the end of the curve, using mid_distance. Then we rotate again to face the outgoing direction of the curve by another half of theta. We can use our existing transformation code to apply these. This is an approximation for small curves, but we are treating the curve length the same as a straight line shortcut between its points, or its chord.

We’ll add an MQTT handler for encoder data and let it call some methods we’ll build later. In robot/localisation.py, add the following imports:

import ujson as json
import time

We’ll extend the __init__ method so it can hold the robot config and state:

def __init__(self):
self.poses = Poses.generate(population_size, (arena.left, arena.right), (arena.bottom, arena.top), (0, 2 * np.pi))
self.wheel_distance = 136
self.previous_left_distance = 0
self.previous_right_distance = 0

The new members are the wheel distance, and we also keep the previous distances for the left and right encoders, so we can work with differences (deltas). The value of wheel_distance should be based on at what points the wheel has contact with the floor – if the robot wheels are slightly angled up, then measure between the areas that make contact for this distance. I get 136 mm, smaller than the wheel-to-wheel measurement we took in Chapter 11, Programming E ncoders with Python. We now need a function for converting distance deltas (changes) into motion:

def convert_encoders_to_motion(self, left_distance_delta, right_distance_delta):
if left_distance_delta == right_distance_delta:
return left_distance_delta, 0
mid_distance = (left_distance_delta + right_distance_delta) / 2
theta = (right_distance_delta - left_distance_delta) / self.wheel_distance
return mid_distance, theta

This method implements the math we discussed in the preceding diagram. It takes the deltas for the left and right encoders, then returns a mid-distance and theta. There’s a special case for the two encoders being the same, either that we’ve not moved or the movement was a straight line. Otherwise, we calculate and return the two values.

We can use this to move poses with a new method in robot/common/poses.py:

def move(self, rotation, translation) -> 'Poses':
return self.rotate(rotation) \
.translate(translation) \
.rotate(rotation)

This function transforms the poses using the three transformations discussed previously. We connect these methods in robot/localisation.py with an on_encoders_data method:

def on_encoders_data(self, client, userdata, msg):
# Sense
distance_data = json.loads(msg.payload)
left_distance_delta = (distance_data['left_distance'] -
self.previous_left_distance)
right_distance_delta = (distance_data['right_distance'] -
self.previous_right_distance)
self.previous_left_distance = distance_data['left_distance']
self.previous_right_distance = distance_data['right_distance']
# Think
translation, theta = self.convert_encoders_to_motion(
left_distance_delta, right_distance_delta)
rotation = theta / 2
self.poses = self.poses.move(rotation, translation)
# Act
self.publish_poses(client, self.poses)

This function starts by loading the payload and then uses the new distance values to update the deltas. In the think section, we use the data to transform the poses. In the act section, we publish them.

The start method changes significantly to connect the encoders and run continuously until it is stopped. We also now only publish poses when there’s encoder data. Replace it with this:

def start(self):
client = connect()
arena.publish_map(client)
client.subscribe("sensors/encoders/data")
client.publish("sensors/encoders/control/reset")
client.message_callback_add("sensors/encoders/data",
self.on_encoders_data)
while True:
time.sleep(0.1)

Send this to the robot and reload the page. When you click S tart for the localisation, you shouldn’t see much of a change, but when you click Start moving, the poses should start moving while you drive the robot. You can also roll wheels gently to see movement. Let’s troubleshoot this behavior.

First, remember to use journalctl, the JavaScript console, and MQTT subs to see that there are no errors, and that messages are being sent for the poses and map when you click S tart. The commands in Appendix B*:* Command Cheat Sheet will help with troubleshooting.

Here are some common problems, solutions, and investigation tips:

  • Reduce the number from 200 to 2 if things look confusing, then increase it when things start to move correctly.
  • If the poses turn too much or too little, the wheel distance setting is not correct, and you should tune it more. You should have gotten something quite close to 90-degree turns in the preceding chapter.
  • Accidentally using the same side for both deltas will make the poses spin in amusing, uncontrollable ways.
  • We have multiple services running. Use journalctl to see multiple services with journalctl ‑u localisation.service distance‑sensor.service. You can show service names in the log by adding SyslogIdentifier={{ service_name }} to the [Service] section in deploy/service_template.j2 and running pyinfra inventory.py ‑r deploy/deploy_services.py.
  • If you don’t see problems or errors in the logs, add prints everywhere – with a small pose set or a sample of poses.
  • The poses are driving off the map – we expect this, we have no bounds checking yet. This will be built later.

By now, you should have a cloud of poses, moving in their own directions, but still roughly centered around the map, almost like blue bees doing synchronized dances.

These are very precise dances; however, they don’t quite reflect reality. We’ve made a grand assumption that the encoders are accurate, and that our wheels didn’t slip, bump, or are perfectly round. We need to model this.

When building a model like this, inaccuracies will accumulate over time. Therefore, we need to counter this by not entirely trusting the sensor data. One way to do that is to introduce noise to the sensor data, relating how much we do (or don’t) trust the data to the value of the change it represents. This is best represented by a diagram:

Figure 12.9 – Moving poses with an error

Figure 12.9 – Moving poses with an error

Figure 12.9 – Moving poses with an error

The diagram shows a number of poses as dots in a section of a test area. There’s a cluster of poses at the bottom left, representing a clumped starting point.

These poses move along a T ranslation, with some rotations as shown previously.

The faint gr a y lines show how the robot could have moved for the encoders to give these readings, since there’s noise from the encoder readings. The poses now end up anywhere in the banana-shaped cluster on the right. This is exaggerated, but the effect is that a tight clump becomes this banana. We counter this noise with controlled noise of our own based on the rotation and translations. That way, among a cluster of many poses, a few of them now land closer to the truth. This noise uses a normal distribution, favoring points closer to the middle of the banana.

It is conventional to call the level of noise in the system alpha or α. However, we can keep the intuitive term noise for this. We will have noise constants for each component of the movements. The rotation and translation components affect each other in that a larger rotation can introduce error to a translation, and vice versa.

Let’s see this in code. First, we are going to add some more configuration parameters to the Localisation.__init__ method in robot/localisation.py:

self.trans_noise_from_trans = 0.01/100
self.trans_noise_from_rot = 0.05/100
self.rot_noise_from_rot = 0.2/100
self.rot_noise_from_trans = 0.175/100

Each is a percentage, hence divided by 100, representing how much encoder movement introduces noise to an output component (e.g., noise to translation from translation). We need to add a random number generator to robot/localisation.py after the imports:

rng = np.random.default_rng()

Let’s make a method in the Localisation class to apply them:

def randomise_motion(self, translation, rotation):
trans_scale = self.trans_noise_from_trans * abs(translation) \
+ self.trans_noise_from_rot * abs(rotation)
rot_scale = self.rot_noise_from_rot * abs(rotation) \
+ self.rot_noise_from_trans * abs(translation)
trans_samples = rng.normal(translation, trans_scale, population_size)
rot_samples = rng.normal(rotation, rot_scale, population_size)
return trans_samples, rot_samples

This function is called with the translation and rotation. We use the abs function to get their value without any negative signs, and multiply them by the preceding alpha scaling factors. We then have scale factors to use with probability distributions.

The np.random.normal NumPy function generates random samples with a mean, scale, and sample count. We make rotation and translation noise using the normal distribution scaled by its factor, with the same number of noise samples as our population size.

Let’s use the noise to modify the movement. Go to the Think section of on_encoders_data and make the highlighted changes:

# Think
translation, theta = self.convert_encoders_to_motion(left_distance_delta, right_distance_delta)
rotation = theta / 2
trans_samples, rot_samples = self.randomise_motion(translation, rotation)
self.poses = self.poses.move(rot_samples, trans_samples)

Upload and start the localisation system, then use the keyboard to drive the robot around. If you spot a few poses that are close together, you should be able to see them gently form the banana shape now. Our mathematical model is simulating the likelihood of the poses being inaccurate.

If you are not getting poses moving while you drive the robot, the next section helps with tools to debug the system.

Localisation is complicated, combining probability and geometry for coordinate transformation in looping code, where effects can stack up into unexpected behavior. We are going to need some tools to help us debug this system.

In this section, we will build some debugging aids.

We don’t want to question if the encoder output is good while debugging localisation. So the first debugging aid will be a page to display simple encoder information.

At the end of Chapter 11, Programming Encoders with Python, the Inventor HAT service was publishing the right encoder distance and speed on the topic sensors/encoders/data. We can subscribe to a web page and display all the details.

Create the file robot_control/encoder_debug.html. We start with our usual block and title lead-in:

{% extends "robot_control/page.html.j2" %}
{% block title %}Encoder debug{% endblock %}
{% block content %}

Then we are going to create a table to display the debug information:

<table>
<tr>
<th></th>
<th>Left</th>
<th>Right</th>
</tr>
<tr>
<th>Distance (mm)</th>
<td><samp id="left_distance">0</samp></td>
<td><samp id="right_distance">0</samp></td>
</tr>
<tr>
<th>Speed (mm/s)</th>
<td><samp id="left_mm_per_sec">0</samp></td>
<td><samp id="right_mm_per_sec">0</samp></td>
</tr>
</table>

In between the table tags, we have three rows, using the tr (table row) tags. The first row is headings using th (table header) tags. The second row is the distances, and the third the speeds. Each cell that isn’t a heading has a td (table data) tag.

Inside these, our data is displayed in samp (sample) tags, meaning computer output data. We start these with a placeholder 0, and give them an id matching the field name in the topic.

Next, we add the JavaScript to connect this:

<script src="libs/keydrown.js"></script>
<script type="module">
import { connect } from './mqtt_client.js';
import { setup_keyboard_drive } from './keyboard_drive.js';
const mqttClient = connect();
setup_keyboard_drive({ mqtt_client: mqttClient });
mqttClient.subscribe('sensors/encoders/data');
mqttClient.on('message', (topic, message) => {
if (topic !== 'sensors/encoders/data') {
return;
}
const data = JSON.parse(message);
document.getElementById('left_distance').innerText = data.left_distance.toFixed(2);
document.getElementById('right_distance').innerText = data.right_distance.toFixed(2);
document.getElementById('left_mm_per_sec').innerText = data.left_mm_per_sec.toFixed(2);
document.getElementById('right_mm_per_sec').innerText = data.right_mm_per_sec.toFixed(2);
});
</script>
{% endblock %}

This connects to MQTT and subscribes to the sensors/encoders/data topic. It also sets up the keyboard driving as we did with the localisation page, using our tiny library.

Then, when each message is received, it’s decoded and displayed by setting the innerText of those samp tags. We have also clipped it to two decimal places with toFixed so it doesn’t run into many decimal places.

We then close the page’s content block.

This needs an item added in the menu list in robot_control/index.html:

<li><a href="encoder_debug.html">Encoder debug</a></li>

This can go anywhere among the list items there.

Use pyinfra inventory.py ‑y ‑‑ deploy/deploy_services.py to send this encoder debug tool to the robot. Then start this page from the menu and drive the robot around. This should show you that the encoders are producing sensible output.

This will make it much easier to rule out encoder problems for localisation.

Sometimes, because so many poses are visible, it is hard to see what is happening. Reducing the population size can make it far easier to debug movement issues.

Motion tracking like this has lots of noise, and we are adding noise, so you will not dial it in perfectly, but if there are patterns of inconsistency, you can use a single pose to fix it.

The extreme example is to set the population size to 1, and drive the robot around, to see that the pose drawn is following the robot motion, even if the starting orientation and position are far off. However, 10 or 20 poses usually also mean you aren’t just seeing noise as bias.

If you see the pose turning too much, it’s likely the wheel_distance setting in robot/localisation.py is a little short; if you see the pose turning too little, it’s likely the wheel base setting is a little high.

Similarly, if the robot and pose distances don’t match, check your wheel diameter settings in robot/inventor_hat_service.py. It’s stored as a radius, for example, wheel_radius = 67 / 2.

If you see asymmetry that doesn’t match between the robot movement and pose movement, it’s possible that there may be wheel diameter differences. Measure each tire with a set of calipers, and if so, you may need to introduce left_wheel_radius and right_wheel_radius variables to compensate. You will likely need to update services and restart localisation a few times to tune this.

When you are reasonably happy that systematic problems have been dealt with, reset population_size to 200. If you run into systematic movement biases, you can use this tool again to check the motion.

With our system modeling pose movement pretty well, we still need to model the idea of boundaries, and poses that really don’t sound correct, since they’ve strayed outside of those boundaries. In the next section, let’s see how to deal with that.

We will generate new populations by resampling, choosing based on probability, and creating a particle filter, where our system is more likely to sample from poses that are more probable than others.

How do we make probabilities for poses? We incorporate observation models**.** An observation model compares predictions with an observation (e.g., a sensor) to see how likely the pose is. As the robot moves and our poses move, these weights will change.

This cycle of making many guesses, making updates, making observations, then making new guesses is the heart of Mont e Carlo simulation.

In this section, we’ll create and incorporate the boundary observation model, based on how close our robot is to the boundary using encoder motion only. Although being outside the barrier is a clear boundary, we’ll later incorporate more sensor data that is fuzzier. This can then update poses’ weights, so we can consider how likely they are, and resample a new generation from them. We’ll see how to have larger populations while keeping the display reasonable.

The boundary observation model detects whether the robot has gone outside the boundaries of our arena. Create the robot/observation_models folder.

Start the robot/observation_models/boundary.py file with imports and constants:

import numpy as np
from common import arena
low_probability = 0.1

We start by creating a concept of low probability. This should be a very small fraction, but not zero. We are building a single observational model, but we will later be adding further observational models. We combine such models by multiplying probabilities. A probability of 0 results in the system discarding too many predictions, as other observation models cannot increase that probability and recover. A low number, though, can still allow other models to affect the prediction probability.

Let’s make a class for this observation model; this one isn’t tracking internal state, but we will add further models that do:

class BoundaryObservationModel:
def in_boundary(self, poses):
inside_walls = np.logical_and(
np.logical_and(poses['x'] > arena.left, poses['x'] < arena.right),
np.logical_and(poses['y'] > arena.bottom, poses['y'] < arena.top)
)
not_in_cutouts = np.logical_not(
np.logical_and(poses['x'] > arena.cutout_left, poses['y'] < arena.cutout_top)
)
return np.logical_and(inside_walls, not_in_cutouts)

We test whether items are inside the boundary by checking that the point is between the lowest value (0) and the highest (1,500) for each of the boundaries, then checking for the special case of the cutout in the bottom-right corner.

We use the fast NumPy logical operators, which result in lists of true/false values. If we printed the output of this, we’d see an entry for every pose, something like this:

[False True True False True ...]

Where a value of True means the pose is inside the boundary. This can be used to weight our poses, in the observation model, which we can add as a method:

def calculate_weights(self, poses):
return np.where(self.in_boundary(poses), 1.0, low_probability)

The np.where function uses the output of the in_boundary function as a set of conditions, and generates another list. For each True, it will use 1.0, and where it’s False, it will use our low_probability number. If we print this, we see the probabilities:

[0.1 1.0 1.0 0.1 1.0 ...]

This is subtle, but False has become 0.1, a small number. True has become 1.0, which is just 1.

We need to then incorporate this into our localisation code. In robot/localisation.py, add the following import:

from observation_models.boundary import BoundaryObservationModel

In the Localisation class __init__ method, add the following:

self.boundary_model = BoundaryObservationModel()

Then add the following method:

def apply_observational_models(self):
return self.boundary_model.calculate_weights(self.poses)

This indirection here is intended for us to add further observation models later in the book.

Let’s update our display to filter the poses we see:

# Act
self.publish_poses(client, self.poses[weights > 0.5])

Run this, and the poses should no longer be visible in the cutout. However to improve our system, we can use the weights to choose better pose predictions for a new generation of poses.

Resampling lets us pick poses for a new generation, but also allows us to make larger or smaller datasets from the original set. A sample count determines how many samples to take.

Our poses are in a weighted sample space, with weights representing how well the observations match the prediction. We will use a method known as low-variance resampling, which allows for efficient random selection from a population while preserving the pose probability distribution. Predictions with higher weights are more likely to be selected multiple times than those with lower weights.

We are sampling poses, so for this system, the term sample references a pose. See the following diagram to see how resampling works:

Figure 12.10 – Low-variance resampling

Figure 12.10 – Low-variance resampling

Figure 12.10 – Low-variance resampling

The preceding figure starts with the Original sample space, now weighted – a weighted sample space shown as a number line from 0 to the sum of all weights. The bar below the number line represents 10 samples (named a to j) in the sample space. The weight of each is represented by its width in this bar. Shading is used to show the different samples. In our system, the poses are the samples.

The diagram then shows a R esampling, with an example resampled size of five samples. The sample size could be the size of the original sample space (for making a new generation of poses) or smaller (for display or debug purposes). It could even be a larger space for interpolating.

Resampling the original set starts by dividing the total sum by the number of samples to generate, making an interval size. This size is in terms of the sample weights. We can generate a random offset between 0 and this interval for the starting sample, and then take samples at intervals along the total sum of weights.

We find the weight that matches the start of each interval, and use the index of that weight to retrieve a sample, producing a N ew sample space. Note that sample c, which has the highest weight, gets sampled multiple times. The new samples do not yet have weights, so are all equally weighted, but some samples from the original set appear multiple times to represent their weights. This is a quick and efficient method to pick the more likely samples.

Let’s build this in the Poses class in robot/common/poses.py:

def resample(self, weights, sample_count) -> 'Poses':
cumulative_sum = np.cumsum(weights)
total_weight = cumulative_sum[-1]
interval = total_weight / sample_count
start = rng.uniform(0, interval)
sample_points = start + np.arange(sample_count) * interval
indices = np.searchsorted(cumulative_sum, sample_points)
return self[indices]

We start by using NumPy to efficiently calculate the cumulative sum of all samples. The total_weight variable holds the last item of the cumulative sum, so we don’t need to recalculate it. We then get the interval by dividing the total weight by the sample count.

We generate start as a uniform random number up to the interval. We can then generate the sample points – from start, using NumPy’s arange method (the single r is intentional – think of the name as array range). The arange method makes a list of numbers from 0 to the sample count, and then each is multiplied by the interval.

The NumPy searchsorted method then lets us find where in the sorted set (the cumulative sum), a set of new values (the sample points) would need to be added, and returns a set of array indexes. This would be the index of each corresponding weight.

We can now use this to look up the poses by the list of indexes, returning the new resampled set of poses.

NumPy has an rng.choice method to choose random samples based on a list of probabilities. However, it is both slower and less stable than the low-variance resampling method.

Let’s add resampling to the on_encoders_data method in robot/localisation.py:

def on_encoders_data(self, client, userdata, msg):
# Sense
distance_data = json.loads(msg.payload)
left_distance_delta = distance_data['left_distance'] - self.previous_left_distance
right_distance_delta = distance_data['right_distance'] - self.previous_right_distance
self.previous_left_distance = distance_data['left_distance']
self.previous_right_distance = distance_data['right_distance']
# Think
translation, theta = self.convert_encoders_to_motion(left_distance_delta, right_distance_delta)
rotation = theta / 2
trans_samples, rot_samples = self.randomise_motion(translation, rotation)
self.poses = self.poses.move(rot_samples, trans_samples)
weights = self.apply_observational_models()
# Act
publish_sample = self.poses.resample(weights, 200)
self.poses = self.poses.resample(weights, population_size)
self.publish_poses(client, publish_sample)

This code uses resampling twice – once to publish the poses, then again to resample the poses for the next generation. Note, we need to populate the variable publish_sample before we replace the poses so we represent the pre-resample weights. We are also now going to increase our population size. I suggest 2,000 to get things working, then 20,000 (20k) to improve the pool of predictions.

We need to send all this to the robot to run it. In deploy/deploy_services.py, find the code for Update localisation and add the highlighted code:

code = files.put(
name="Update localisation",
src="robot/localisation.py",
dest="robot/localisation.py")
observation_models = files.sync(
name="Update observation models",
src="robot/observation_models", dest="robot/observation_models",
exclude=("*.pyc", "__pycache__"))
deploy_service("localisation",
"robot/localisation.py",
False, common_changed or code.changed or observation_models.changed)

Send this with deploy services, then place the robot in the test area and click R un. The first thing you should see is that the poses are no longer in the cutout:

Figure 12.11 – Resampled poses

Figure 12.11 – Resampled poses

Figure 12.11 – Resampled poses

The poses have been resampled based on their weights for staying within the lines, since those in the cutout would have had a lower probability. The other thing is that we are constantly resampling, first between pose generations, and secondly for the display. The poses will be jumping around like ants! This is the random factors at work.

If you move the robot with the keyboard, the poses will move with the robot, but those that go out of bounds will have their probability reduced, so those remaining will be within the bounds.

Left long enough, you should see something like the following:

Figure 12.12 – Poses converged on likely locations and directions

Figure 12.12 – Poses converged on likely locations and directions

Figure 12.12 – Poses converged on likely locations and directions

The poses in this figure are starting to converge on roughly where the robot is. It still gets confused sometimes about the corners, and the parameters could do with tuning. It also still looks like a small moving swarm in that location.

As the robot moves, the out-of-bounds cloud around the robot will reduce to likely places the robot can be without having gone outside the boundary. The more it moves, the more the poses will converge on locations and headings. The cutout acts as a landmark, which a plain rectangle wouldn’t have, so the robot can distinguish different sides of the space.

Our distance sensors are keeping the robot movement within the bounds, while encoders are tracking that movement. It takes a lot of luck to get a cluster as well placed as the preceding figure; you may have 3 or 4 swarms, and it can end with a single swarm in the wrong place. We’ll see in a later chapter how we can improve this using the distance sensors in a further observational model.

There’s some tricky areas here. First, ensure to check the browser console for any problems, along with journalctl and expected messages.

  • If things fail to start at all, check for any errors in the preceding locations. If the poses are moving incorrectly, check the Tracing curves section again.
  • If poses are moving out of bounds, and not being picked off, ensure the bounds checking function matches the preceding code, and that you’ve set the correct low probability. It’s a common mistake to miss the double asterisk ** operator there.

Poses will naturally take time to converge, and will lose tracking and reconverge as you watch; this is expected. However, you can improve this by ensuring the width, height, and cutout sizes match your test area well. You should see some clusters that make sense, sometimes, but not always.

The boundary model we have here is on or off, which means poses can get close to the edge and simply drop off. A smoother probability change will help guide the choice of poses more than the very steep changes.

One simple way to do this is, instead of checking our boundary condition at a single dot, check at crosshair points, and take the mean of those samples.

Let’s draw what we mean:

Figure 12.13 – Crosshair sample

Figure 12.13 – Crosshair sample

Figure 12.13 – Crosshair sample

The preceding diagram shows how a crosshair sample will work. The large dark circle is the pose. Arranged around it are crosshair points for cardinal directions – above, below, to the left, and to the right of the pose, at which we take 4 more samples.

We then take 5 samples per pose, and then take the mean (average) of them, by adding all the weights found at those locations and dividing by the number of sample items.

Let’s write the code for this. Open up robot/observation_models/boundary.py and add some constants (after the low_probability setting) to set up the crosshair shape and size:

crosshair_radius = 50.0
crosshair_points = np.array(
[
[0.0, 0.0],
[crosshair_radius, 0.0],
[-crosshair_radius, 0.0],
[0.0, crosshair_radius],
[0.0, -crosshair_radius],
],
dtype=np.float32,
)

We are going to need a type for a 2D point without a rotation for this crosshair system, to assist NumPy in declaring and shaping the output. Add this near the top of this file:

Point2D = np.dtype([('x', np.float32), ('y', np.float32)])

The crosshair_radius variable expresses how far in mm the 4 satellite sample points should be from each pose. We then use this to set up the crosshair points in a convenient array we can reuse when we need to calculate these.

Next, add the following method:

def observe_crosshair(self, poses):
crosshair_positions = (
poses.positions[:, np.newaxis:] + crosshair_points[np.newaxis::]
)
flat_positions = crosshair_positions.reshape(-1, 2)
samples = np.empty(flat_positions.shape[0], dtype=Point2D)
samples['x'] = flat_positions[:, 0]
samples['y'] = flat_positions[:, 1]
flat_weights = np.where(self.in_boundary(samples), 1.0, low_probability)
all_weights = flat_weights.reshape(-1, crosshair_points.shape[0])
return np.mean(all_weights, axis=1)

This method starts by combining all poses with the set of crosshair positions, which will create a new array (crosshair_positions) with the number of poses multiplied by 5 of 2 coordinates – all the positions for each pose.

We then reshape this into a flat array, since we can use that flat array with our existing in_boundary method. Reshaping is handy since, if the underlying datatype doesn’t change, the system can just look up numbers in it using a different structure, but without making a copy. The shape (-1, 2) means lookup as n structures of 2 items, where -1 represents the unknown n. We can use that to get flat_weights.

We need to unpack the data stored in flat_weights to use them, so we reshape again, this time with the number of points in the crosshair points. This will now give us 5 weights per pose.

Finally, we get the mean of each set of 5 weights on the latter axis, which will be the mean of all crosshair samples for each pose.

We can wire this in with a small change in the boundary model:

def calculate_weights(self, poses):
return self.observe_crosshair(poses)

The changed line here uses the crosshair observation instead of simply the in_boundary observation.

If you send this to the robot, you will see a few effects. First, poses will be less frequently right up against the edge of the arena, but also, the system is now able to favor those slightly further from the edge than others closer to it.

Our system has a problem, though; it can sometimes eliminate many poses, such that only a small cluster, maybe entirely wrong, remains. Let’s see why.

Our system is resampling every time there is encoder data. However, if the poses have not moved much, their probability might not have changed much. Worse still, if most or all are away from the boundaries, their probabilities will all be the same. A resample at this moment will needlessly eliminate poses or allow very small probability variations to have a very large effect.

The poses start off distributed uniformly, so there can be no information, or very little. The first sample will show those that are inside the boundary, but what is less clear are those near it. However, after some movement, it would become clearer which are now close to a boundary, and those that are still in the middle.

If we want to control resampling, we must first measure how many particles are contributing meaningful information to the system.

This is done with E ffective S ample S ize (ESS). This is a rough measure of the count of particles that are contributing to the system, versus them all being equally weighted.

Let’s use a plot to show different groups of particle weights:

Figure 12.14 – Particle weight distributions

Figure 12.14 – Particle weight distributions

Figure 12.14 – Particle weight distributions

The preceding diagram shows two different particle distributions. Both contain 100 particles, so the ESS will always be some portion of 100 in this example.

Although each weight appears small, they add up to 1.0. This is a normalized distribution. Each normalized weight represents its share of the total probability of 1. The result here is now relative to 1 instead of to the whole weight scale.

The top distribution has a low ESS. Here, the filter estimates that only about 23.0 particles are contributing meaningfully to the system. This small number of particles stands out from the rest, forming visible clumps of higher probability. The probabilities are at 0.06 or higher here.

The lower distribution is nearly uniform, more like grains of sand spread across a beach. Most of the particles have very similar weights, so the ESS is high at about 99.7. This means that almost the whole population is contributing, so the filter has not yet found enough evidence to prefer one set of particles over any others. Notice also that because the shares are more evenly distributed, each has a lower probability. The highest here is around the 0.0100 mark.

We do not want to resample while everything is like loose sand. At that point, resampling mostly duplicates noise and may discard particles before enough evidence has built up to judge them. Instead, we want to wait until probabilities begin to stand out and gather into clumps. This is a sign that the filter is finally seeing structure worth reinforcing.

When particles start to stand out, the ESS drops, making this a good moment to resample.

How do we calculate this ESS? Let’s find out in the next section.

The following diagram shows how we will convert pose weights to the effective sample size:

Figure 12.15 – Calculating the effective sample size

Figure 12.15 – Calculating the effective sample size

Figure 12.15 – Calculating the effective sample size

The preceding diagram shows how we convert the pose weights to an effective sample size.

We start with the pose weights as they have come from our boundary observation model. Before these model weights can be used for ESS, we must N ormalize them. We can do that by calculating the sum of the weights and dividing each individual weight by its sum.

We can then S quare the normalized weights. Squaring them means that the differences between the probability shares are more exaggerated. Small weights, with low probability, become even smaller, and large weights stay influential.

We S um them to see how many large weights now dominate. The Sum of squares gets bigger quickly when weights are large, compared with many small weights. This is where we can start to see the difference, with a large value showing how concentrated the weights are.

We then Invert, that is, divide 1 by the sum of squares. This converts from concentration to how many samples have a standout share of the distribution, resulting in the ESS.

ESS tells us how concentrated the particle weights are, not whether the filter is correct. That is, has our distribution become selective enough to justify resampling? It will not answer if we are selecting the right hypothesis.

When we have calculated this ESS, we can test it against a threshold, so when fewer than this number of samples are contributing to most of the weight distribution, our code will resample. We can build this code.

We will need to modify our localisation code first. Open robot/localisation.py and in the constants section, let’s add a threshold. Initially, a tenth of the population size. Add the highlighted code:

population_size = 20000
ess_threshold = population_size // 10

We’ve used the // operator, so that the result of this division remains stored as a whole number.

In the localisation constructor (__init__ method) add the highlighted line:

class Localisation:
def __init__(self):
self.poses = Poses.generate(population_size, (arena.left, arena.right), (arena.bottom, arena.top), (0, 2 * np.pi))
self.weights = np.ones(population_size) / population_size

We are now keeping track of weights between localisation updates, starting with an initial value of 1 divided by the population size. This is normalized already, but all are completely equal.

We can then add a method to calculate the ESS. Add this as a new method in the Localisation class:

def calculate_ess(self):
return 1 / np.sum(self.weights ** 2)

This applies the calculation we saw above to the normalized weights.

We can now apply this to our system in the on_encoders_data method. First, we make the highlighted changes to the Think section to update our weights and calculate the ESS:

# Think
translation, theta = self.convert_encoders_to_motion(
left_distance_delta, right_distance_delta)
rotation = theta / 2
trans_samples, rot_samples = self.randomise_motion(
translation, rotation)
self.poses = self.poses.move(rot_samples, trans_samples)
self.weights *= self.apply_observational_models()
weight_sum = np.sum(self.weights)
self.weights /= weight_sum
ess = self.calculate_ess()

The highlighted lines now multiply the stored weights by the result of applying the observational models. That means our system can gather evidence, building up differences in the weights. Repeated updates will make some weights grow relative to the others, making them more plausible than other pose guesses.

We sum the weights, so we can normalize them again. The stored self.weights will be normalized every time our code passes these lines.

We can then use the normalized weights to calculate the ESS.

Let’s now account for the ESS in the Act section with the highlighted changes:

# Act
publish_sample = self.poses.resample(self.weights, 200)
if ess < ess_threshold:
self.poses = self.poses.resample(self.weights, population_size)
self.weights = np.ones(population_size) / population_size
self.publish_poses(client, publish_sample)
publish_json(client, "localisation/ess", {"ess": ess})

We now check if the ess is below the threshold, signaling that 10% of the particles now dominate the sample set. If so, it is time to resample.

We resample as before and must reset the weights to 1 over the population size, as the old weights no longer relate to the new resampled set.

We also publish the value of ess so we can debug how this value changes.

A useful distinction:

  • The robot receives observations over time.
  • The particle filter expresses the observation effects through changing particle weights.

So, in our system:

  • Observations arrive.
  • Weights are updated reflecting the combined effect of observations.
  • ESS measures how concentrated that has become.

Our system is now measuring the ESS and accounting for it. You could send this to the robot now, and it will work, but it would be useful to be able to see how the ESS changes over time. Let’s extend our control page to show this.

We are logging the ESS data via MQTT already. We can use Chart.js to extend the localisation page and display ESS as a plot versus time. Open robot_control/localisation.html and add the highlighted div tag to hold the plot:

<div style="height: 60vh; width: 60vh;">
<canvas id="poses"></canvas>
</div>
<div class="line_chart">
<canvas id="ess_plot"></canvas>
</div>
<script src="libs/chart.js"></script>

This prepares a line chart, with the id ess_plot.

We are going to need to import the timeseries chart helper for this. Add the highlighted import:

import { connect, publish_when_clicked } from './mqtt_client.js';
import { create_timeseries_chart } from './chart_helper.js';
import { setup_keyboard_drive } from './keyboard_drive.js';

We can now use create_timeseries_chart to connect a chart. Let’s set this chart up when we also connect the pose chart by inserting the highlighted line:

const pose_ctx = document.getElementById('poses').getContext('2d');
let pose_chart = new Chart(pose_ctx, pose_chart_config);
const ess_chart = create_timeseries_chart('ess_plot', ['ess']);

This has now linked our div tag with id ess_plot to a chart, with the data element ess expected. The last thing we’ll need is to handle this in the MQTT topics after handling the map:

case 'localisation/map':
const payload = JSON.parse(message);
mapPlotter.walls = payload.walls;
triggerChartUpdate();
break;
case 'localisation/ess':
const ess_data = JSON.parse(message);
ess_chart.update_data({
time: Date.now() / 1000,
ess: ess_data.ess,
});
break;

The highlighted code checks for the localisation/ess topic and parses the message. Because JavaScript times are in milliseconds, we divide the current time by 1000 to get seconds for the chart and update the chart with the received data.

You are ready to test the localisation with ESS-based resampling.

You can send the updated localisation behavior and web page to the robot using the deploy services script.

When you run this, press Start on the localisation screen and move the robot with the keyboard. You should see the ESS graph start to change as you move the robot around. It will start to drop off as you move more, and you should see it then shoot back up, almost like a sawtooth. This is when the model has resampled.

This should improve the localisation in that it is now less likely to dismiss poses before it has enough evidence.

Now, let’s see what we’ve learned.

In this chapter, we used the encoder data along with a model of our robot poses and an arena to create a dynamic probabilistic mathematical model of the robot’s location. We learned how to mathematically represent the world the robot is occupying, and also represented possible poses the robot could be at.

We saw how encoder readings can infer where the robot has moved or turned, accounting for noise in the sensors, and then fused that with a model to observe whether the prediction is still within the arena boundaries. The robot has gone from simply reacting to sensors to making dynamic predictions and testing hypotheses about where it is.

We took a trip through probability, making random selections, weighting poses based on their properties versus the world, and saw how to display this on a browser while it runs. We saw how probability distribution concentration can be measured and used to control how often we resample from a population. These are powerful tools we can extend and work with.

In the next chapter, we will add another sensor, the inertial measurement unit.

The following challenges will let you build a better robot and learn more from the techniques in this chapter:

  • You can modify the population size. How do higher numbers affect performance? Do lower numbers change the convergence?
  • What happens when you start and stop motion while leaving the localisation running?
  • Try playing with the alpha factors, and see how they affect the scattering and randomization of the poses. This might be a good place to enhance this code with the configuration system. We can also configure the wheel distance from here.
  • We are sending a subset of poses to the browser. Can you try higher or lower pose counts?
  • Consider other test areas and how to model their conditions and boundary lines. How would you model them and check for out-of-bounds conditions?

Please refer to the following for more information: