Robot Localisation and Sensor Fusion with Python
local graph
Chapter 17 — Robot Localisation and Sensor Fusion with Python
Section titled “Chapter 17 — Robot Localisation and Sensor Fusion with Python”Robot Localisation and Sensor Fusion with Python
Section titled “Robot Localisation and Sensor Fusion with Python”In the previous chapter, our robot got smarter with a voice agent system. Throughout the book, we’ve been building components to localise a robot. We want to ask the question, given what we know about our sensors, where is the robot? Can we get a good picture of where the robot is? Can we use this to achieve tasks?
We have a distance sensor system producing a lot of distance data for our robot. We can project distance readings in front of poses to find the points the sensor has detected and check those against a probability field to see how likely those distances are to be detecting a wall.
In this chapter, we’ll improve the Monte Carlo simulation we built in Chapter 12*,* Encoder -Based Localisation with Python. This is a probabilistic AI that predicts the robot’s position and validates those predictions against observations. We’ll fuse distance sensor observations with the encoder-based movement model and see how they change the localisation system’s accuracy and speed. We will build this in a way that is open to fusing further observation models from other sensors.
A single observation model, like the boundary model, is usually not great for localisation. Adding more provides more ways to determine the accuracy of the system. We’ll see how to make probability fields for an observation model and expand localisation with them.
In this chapter, you will learn about the following topics:
- Observation models
- Probability fields
- Modeling distance sensor array geometry
- Fusing distance sensor data
- Fusing IMU yaw data
Technical requirements
Section titled “Technical requirements”Before we get started, make sure you have the following parts:
- The robot platform and code from all previous chapters
- The arena built in Chapter 9, Avoiding Obstacles with Distance Sensors
- Tape measure or ruler
- A sheet of brightly colored card or paper
- Sticky tack, glue, or double-sided tape
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.
Observation models
Section titled “Observation models”In Chapter 12, Encoder -Based Localisation with Python, we built a localisation model. This model represents the position of the robot with many poses in 2D space. This localisation simulation starts by making random guesses about the robot’s pose.
Each pose was moved when the robot encoders recorded movement, allowing for the noise and accuracy problems of the encoders. The move poses then form a new set of predictions of where the robot may be.
Each pose is given a probability of that prediction being true, based on observations. An observation model is a system that compares the poses with an observed state. The current observation model checks if the robot has driven far enough to be outside the boundary of the arena. We then made a new generation of poses based on that probability. We also refer to the probability of a pose prediction being likely as a pose weight.
In this chapter, we are going to integrate a further observation model using the distance sensor array with the boundary.
The boundary observation model was binary — that is, a point was either inside the boundary or outside it. This approach will not work for modeling how well distance sensor readings align with real-world boundaries. As with the encoders, distance sensor readings have noise too; the real world is messy.
Adding further observation models will improve the capability of the localisation system, allowing it to use more observations to gather evidence for or against the predictions made by the movement model. However, it also comes with trade-offs.
The first trade-off is processing time. Adding more observation models will require more time to process all of those observations. There are ways to optimize and multithread to improve these, but that leads to the next trade-off: complexity. As you add more observation models, the complexity of the system will grow.
Because of the complexity of multiple observation models, you will sometimes need to isolate a particular observation model to debug problems, with the caveat that combining them will result in the best outcome.
After building an additional observation model, we will look at how it is combined with the existing observation model to improve localisation prediction accuracy.
Probability fields
Section titled “Probability fields”We’ve so far been looking at probability as mostly a single-dimensional graph of probability. However, if we are localising in 2D space, we should get comfortable with representing probabilities in a 2D space.
A probability field or likelihood field is a representation of the probability or weight of a particular event for all the locations in a space. This could be the likelihood that the robot would be in that location, or the probability that the sensors would detect a barrier in a location.
In this section, let’s explore how to model these boundaries with noise as probability fields, and build one for use in a distance array observation model.
Using a varying probability
Section titled “Using a varying probability”The following diagrams show how probability changes between observations:

Figure 17.1 – Probability change types
Figure 17.1 – Probability change types
There are many ways for probability to vary; however, the most important first distinction we must make is between a step change and any gradual change. Let’s examine each panel here:
- Step change (1): A step change is a change with a binary drop off. It’s all or nothing. We used a step change in our boundary observation model in Chapter 12, Encoder-Based Localisation with Python, where being inside the boundary is high probability and being outside is low probability. We slightly tamed it with the crosshair sampling.
- Gradual change (2): A gradual change is any change that does not have a single drop-off threshold.
- Boundary change (3): From distance sensor modeling, a wall boundary may resemble two step changes, one up and one down. A true value would mean that the distance detected aligns with a wall, and a false value means it aligns with empty space. This is intolerant to real-world noise.
- Gaussian ridge (4): To allow for real-world fuzziness, the probability of a sensor reading aligning with a wall should be calculated with a curve like a Gaussian ridge. It follows a normal (Gaussian) distribution, with a peak and a smooth curve away from the peak. An important part here is the S tandard D eviation, or SD. Most correct guesses are expected to lie in the range between the negative and positive standard deviation, so it is a way to specify how dispersed the Gaussian ridge would be. The standard deviation does not bound the Gaussian; guesses can be outside of this, but with a much lower probability. For the distance sensing, making a boundary line fuzzy allows the localisation system to “climb a slope” to more probable locations.
Sensor noise is likely to fall on either side of the real reading; however, we are assuming that this error is Gaussian too, around the real reading. We chose the Gaussian ridge both to estimate sensor noise and to help the model climb the possibility curves.
We will need to model this in 2D, but first we need to consider the coordinate space. Consider that our observation model would be like a person looking at landmarks, then checking with a map to see if their guessed location and observations match the map. Before building the map, we need to be clear on how map locations will relate to world locations.
Map coordinates
Section titled “Map coordinates”In Chapter 12, Encoder -Based Localisation with Python, we built a robot test area model and the robot origin. The coordinate space in the arena is between 0 and 1500 (or the size of your arena space). We also generate many poses. When we map the distance sensor reading onto the poses, those readings will fall outside the boundary. While there’s a point past which these will be simply a low probability, the Gaussian ridge has a slope on both sides.
If we model our image such that coordinate 0,0 maps directly to the image, there’s no room for the outside Gaussian slope. That means we need to have a map with margins for that. We’ll do this with two coordinate systems:
- A world coordinate: This models the robot position in relation to the arena
- A map coordinate: This models the robot position in relation to this observation model
It’s key to understand the coordinate system relationships to be able to create a map that accounts for sensor readings that may lie beyond the map. Although those far outside the map are likely to be predictions that should be rejected, those closer, on the slopes of the probability curve, may be real readings, but with some sensor inaccuracy and noise accounted for.
See the following diagram in Figure 17.2 to help you understand:

Figure 17.2 – Map coordinates vs. world coordinates
The preceding diagram shows our arena drawn on a map. The arena corners are labeled with their world coordinates (prefixed with a w).
The map has a frame that extends beyond the arena, the world we are modeling. An arrow in the bottom left of the diagram shows a mapping from the map (0,0) to the world (0,0) positions.
In code, we will use prefixes, e.g., wx and wy or mx and my, to be clear which we are talking about. All robot poses will be world coordinates, but we will transform them into map coordinates for use with the distance observation model. Let’s extend our robot arena code with a map frame.
Open robot/common/arena.py and insert a NumPy import at the top:
import numpy as npThen this code for a map frame to the end:
class MapFrame: def __init__(self, margin : int): self.w_left = -margin self.w_right = right + margin self.w_bottom = -margin self.w_top = top + margin self.margin = margin
@property def width(self) -> int: return self.w_right - self.w_left
@property def height(self) -> int: return self.w_top - self.w_bottom
def world_to_map(self, world_coordinates : np.ndarray) -> np.ndarray: return world_coordinates + (self.margin, self.margin)
def map_to_world(self, map_coordinates : np.ndarray) -> np.ndarray: return map_coordinates - (self.margin, self.margin)The map frame class sets up a map frame modeling the world coordinates within it. There are prefixed items for the left, right, top, and bottom world coordinates of this map frame.
It has properties for width and height. A Python property lets us retrieve a calculated value as if it were a variable. This map frame does not scale and remains 1 to 1; therefore, the width and height are in the same units as the world coordinates – always mm.
The variables left, right, top, and bottom were defined earlier in arena.py when the arena boundary was declared in Chapter 12, Encoder -Based Localisation with Python.
There are then functions to convert between the world coordinates and the map coordinates. These expect NumPy arrays of coordinates and will return more arrays of coordinates. This allows for mass transformations to and from the map frame coordinate system, adding and removing the margin. The additions operate on many items at once. Running an operation on every item in a multidimensional array like this is known as broadcasting.
Let’s use this frame to build our probability field.
Generating a distance probability field
Section titled “Generating a distance probability field”In Chapter 12, Encoder -Based Localisation with Python, we made robot/common/arena.py which models the robot arena corners. Let’s use that to build the fuzzy boundary map. We can do this by drawing the arena boundary with lines, then applying a blur algorithm.
In Chapter 15, L ine - Following with a Camera in Python, we used the Jupyter Notebook environment, which we can also use to experiment with the fuzzy boundaries.
If you have Jupyter still running, stop this first. In a terminal, in the root of the project, use poetry add ujson paho‑mqtt so we can use some of the robot code inside of Jupyter.
Run the command poetry run jupyter notebook. Click the token link shown in the terminal to see it in the browser, then navigate to the experiments folder.
VS Code has a Jupyter plugin, which lets you work with notebooks beside your other code. Choose one option, but don’t edit with both at the same time.
Create a new Python 3 notebook - experiments/distance_probabilities.ipynb.
In the first cell, we need some imports to start our experiments:
import sysimport numpy as npimport cv2from matplotlib import pyplot as pltsys.path.append('../robot')from common import arenaWe prepare NumPy for number manipulation, OpenCV for image manipulation, and matplotlib to draw it. We also modify the import path and load the robot arena too. If this fails to import the arena, ensure you have installed paho‑mqtt as shown above, and that you have started a fresh Jupyter Notebook from a terminal at the top folder of the project.
Run the cell and add the next. We then need a cell defining our map frame:
low_probability = 0.1map_frame = arena.MapFrame(100)We set a low probability value that is not quite 0, but quite close to it. It’s a bit higher than the boundary plan one, so this doesn’t make the differences too harsh. The variable map_frame creates a frame with a margin of 100 mm.
It will be helpful here to draw this map. Put this in a new cell and run it:
def plot_map(map_data, axs=None): if axs is None: plt.figure(figsize=(8, 8)) axs = plt axs.imshow( map_data, cmap='gray_r', origin='lower', extent=[map_frame.w_left, map_frame.w_right, map_frame.w_bottom, map_frame.w_top], aspect='equal' )This function takes map_data as its source. It can be given an axis to plot to; otherwise, it starts by setting the figure size to a large square figure and plots to that. We then plot our data in grayscale; the color map gray_r is darker for the higher values. It sets the extents of the image using the map frame.
Let’s draw our edges with OpenCV in a new cell:
walls_map = np.zeros((map_frame.height, map_frame.width), dtype=np.float32)cv2.polylines(walls_map, map_frame.world_to_map(np.array([arena.walls])), isClosed=True, color=1.0, thickness=1)
plot_map(walls_map)This starts by creating the variable walls_map, an empty map using the current frame. OpenCV stores images as a list of rows, with each row being a list of column data, so we define the height first.
The OpenCV polylines function will draw a polygon using point data. In this case, we must transform the arena walls list to map coordinates with the map_frame.world_to_map method.
We then use the above plot function. Run this, and you should see the map drawn:

Figure 17.3 – The walls map
Figure 17.3 – The walls map
This screenshot shows the map of the walls you should see. If you don’t see this, ensure you have the arena changes and run all prior cells.
As our arena is defined in mm, a map pixel is 1 mm by 1 mm.
This shows the extent of the frame, with the world coordinate system shown on the grid. I’ve thickened the lines for clarity, so you will see a thinner boundary line here. This maps the walls, but these walls are a step change. How can we make them more useful to the robot? Let’s explore this in the next section.
Smoothing the walls
Section titled “Smoothing the walls”We talked about blurring the walls to get a Gaussian ridge covering them. OpenCV has a GaussianBlur function that spreads probability values to nearby map locations, making a smooth probability gradient. Add this in a new cell:
distance_map = cv2.GaussianBlur(walls_map, (0, 0), 45)plot_map(distance_map)We’ve used 45 for the standard deviation of the Gaussian blur, effectively how dispersed the blur is. Making it larger will give a smoother slope for our probability. This value must be an odd number and must be no more than half the map margin. If it’s too wide, the model starts to be less effective. The VL53L5CX datasheet ranging accuracy is complicated, but a simplified version is that, in continuous mode (how we use it for our robot), the accuracy loss can be the greater of 15 mm and 8% of the distance. In the worst-case scenario, this can be 120 mm. The value 45 mm lies between them.
When you run this cell, it stores a distance map in the variable distance_map, and then plots it.
You should see the following screenshot:

Figure 17.4 – The Gaussian smoothed walls
Figure 17.4 – The Gaussian smoothed walls
The preceding screenshot shows the walls now smoothed into Gaussian ridges; let’s zoom in on a corner and take a closer look.
Add the following in a new cell and run it:
fig, (ax_map, ax_row) = plt.subplots( 2, 1, figsize=(8, 12), sharex=True, gridspec_kw={"height_ratios": [4, 2]} )
plot_map(distance_map, axs=ax_map)ax_map.set_xlim(-50, 150)ax_map.set_ylim(-50, 150)ax_map.axhline(y=100, color='r', linestyle='--')ax_map.tick_params(labelbottom=False)
map_y = 100 + map_frame.marginrow = distance_map[map_y, 50:250]ax_row.plot(np.linspace(-50, 150, 200), row)ax_row.set_title('Distance values along y = 100')ax_row.set_xlim(-50, 150)
fig.tight_layout()This creates a combined figure with multiple subplots, so we can align two different plots. The top plot, ax_map, uses set_xlim and set_ylim to manipulate the visible limits of the plot after drawing the map. We draw a red dashed line at map y 100.
The second plot, ax_row, is used to plot the data on the row we’ve highlighted.
This extracts a row of data, between map x 50 and map x 250. It plots the data using the world coordinates to make a linear space, then puts a title on it.
These are put in a tight layout so they align. The output of the zoomed map corner and row will show the following screenshot:

Figure 17.5 – Zooming in on the corner
Figure 17.5 – Zooming in on the corner
The screenshot shows the output of the zoomed cells. The first shows the smooth blurring on our boundary lines in distance_map as a 2D image. The lower image is a plot of the same data with the cell value plotted against the world x coordinate. One important thing to note here is that the peak value is only 0.032, which is going to be too low for us. Also, it’s impossible to tell if the base is 0 or just above. Let’s find the minimum and maximum by running this in a cell:
np.min(distance_map), np.max(distance_map)The result will be:
(np.float32(0.0), np.float32(0.032393876))We will need to shift this up and normalize it, ensuring that the lower bound is our low_probability value and the highest values are scaled up to 1:
normalized_map = cv2.normalize(distance_map, None, alpha=low_probability, beta=1.0, norm_type=cv2.NORM_MINMAX)plot_map(normalized_map)np.min(normalized_map), np.max(normalized_map)OpenCV likes to call the lower bound alpha and the upper bound beta in this case. This should now result in the minimum and maximum values we intend:
(np.float32(0.1), np.float32(1.0))We can now export this data for use in our robot. Add the following cell:
np.save('../robot/observation_models/distance_map.npy', normalized_map)And run it. A new file robot/observation_models/distance_map.npy will appear. We’ll be able to load this on the robot.
Probability field and likelihood field are equivalent terms here. Our specific implementation here is the distance_map, a precomputed probability field.
These files can be quite big, so I suggest adding *.npy to the file .gitignore. Now would be a good time to save your work and commit this to Git.
Troubleshooting
Section titled “Troubleshooting”If you run into problems, try these ideas:
- If you reload a Jupyter Notebook, you may need to start from the first cell again. An obvious sign you need to reload is if an imported symbol like
npis missing. - If you have other unrecognized symbol errors, ensure you have run each cell before adding a new one; you may need to restart the notebook and ensure you’ve run the cells in order.
- If you have import errors, ensure that you have installed Jupyter in Chapter 15, Line-Following with a Camera in Python.
We’ve created our distance map probability field. Now that we have generated the probability field, we can use it for localisation on the robot.
Making use of the probability field in robot code
Section titled “Making use of the probability field in robot code”Let’s load our distance sensor map, which we will use as part of our localisation. Add the file robot/observation_models/distance.py:
import numpy as np
from common import arenafrom common.poses import Poses
class DistanceObservationModel: def __init__(self, probability_field_path="robot/observation_models/distance_map.npy"): self.probability_field = np.load(probability_field_path) self.low_probability = np.min(self.probability_field) self.frame = arena.MapFrame(100)This first section imports NumPy, and declares a DistanceObservationModel class, along with the arena and pose information. When this is initialized, it loads the probability field we’d built with Jupyter. We also prepare a low probability value from the normalized map data.
Our model needs a method to consult it with a list of coordinates, returning a list of probabilities:
def get_probabilities(self, world_positions: np.ndarray) -> np.ndarray: map_positions = self.frame.world_to_map(world_positions).astype(int) mask = ((map_positions[:, 0] >= 0) & (map_positions[:, 0] < self.probability_field.shape[1]) & (map_positions[:, 1] >= 0) & (map_positions[:, 1] < self.probability_field.shape[0])) out = np.full(mask.shape, self.low_probability, dtype=float) out[mask] = self.probability_field[ map_positions[mask][:, 1], map_positions[mask][:, 0] ] return outThe get_probabilities function uses the probability field as a lookup table for boundary proximity probabilities. However, it must convert our world positions list into map frame positions first, then convert them to indexes using astype(int) as we cannot use floats for array lookups.
The function then creates a mask for positions inside our map. This will hold true/false values depending on the coordinate being inside the map frame.
We create a space to hold the same number of results as the input positions, but filled with the low probability default.
The mask now forms sets of array lookup keys. NumPy uses the mask to select the valid probability field coordinates efficiently from the underlying array. We then use the same mask to store the result, writing over the output array masked positions with that result – this stops it from trying to look up any values outside of the boundaries, in a fast way that can cope with large numbers of positions. The return is this output list of probabilities.
Images are stored [row, column] or [y, x]. We usually see coordinates in the order [x, y]. The map is an image, so map_positions[:, 1] holds y coordinates.
Let’s test this in the Jupyter Notebook we’ve been using. Open experiments/distance_probabilities.ipynb and extend the imports with this observation model and the poses:
import sysimport numpy as npimport cv2from matplotlib import pyplot as pltsys.path.append('../robot')from common import arenafrom common.poses import Posesfrom observation_models.distance import DistanceObservationModelI recommend using the Jupyter Restart button. In the menu, navigate to Kernel | Restart kernel and run all cells. This ensures it’s loaded the latest version of your code. You will need to do this any time you change imports or have closed down Jupyter.
Add the following cell to test some points for their probabilities:
model = DistanceObservationModel("../robot/observation_models/distance_map.npy")world_positions = np.array([[0, 0], [1705, 1500], [1500, 1200], [400, 400]])model.get_probabilities(world_positions)This creates an instance of the model we’ve started, which loads the map. We create an array of positions to look up, including 1705 and 1500, which are guaranteed to be outside, and then fetch the probabilities for them all. Jupyter will display those for us:
array([0.83666176, 0.1 , 0.83884484, 0.1 ])We can now look up probabilities for positions, but for them to make sense from a pose, we need to model some sensor geometry.
Modeling distance sensor array geometry
Section titled “Modeling distance sensor array geometry”Our robot has a distance sensor that covers an 8 by 8 grid. We will use only 1 row of 8 sensors, treating the space as two-dimensional. We can model the geometry of our distance sensor array as projecting 8 rays from its front surface. Modeling sensor and robot geometry is a key skill in fusing sensor data. Let’s explore some geometry components to make this work.
Making unit vectors
Section titled “Making unit vectors”When we manipulate geometry, rotation, or projecting a distance along an angle is a common operation. This uses the trigonometric sin and cos functions. We can capture this relationship as a unit vector: the x and y coordinates for a distance of 1.
Take a look at the following diagram:

Figure 17.6 – Building a unit vector with sine and cosine
Figure 17.6 – Building a unit vector with sine and cosine
This figure shows how to build a Unit vector. A unit vector always has a distance of 1 unit from its origin and represents an angle as the x and y components of a vector.
You build a unit vector within a Unit circle (radius 1), with its center at 0, 0. If you then make an angle theta, and draw a line from (0, 0) to the circle, the point where the line crosses the circle is the Unit vector.
For any given angle θ, the unit vector’s x component will be cos(theta). For the same angle, the unit vector’s y component will be sin(theta).
Using this unit vector to represent a direction means that we can multiply it by a length, so multiplying it by 50 would give the x and y coordinates of a point at angle theta, 50 units from the center. We can use unit vectors to store pre-calculated angles to save time.
Let’s use our geometry knowledge to build this code.
Distance sensor rays detecting a wall
Section titled “Distance sensor rays detecting a wall”If you recall in Chapter 12, Encoder -Based Localisation with Python, we performed the encoder movements relative to the Robot origin between the drive wheels of the robot. We must also model the sensors relative to this point.
The following diagram shows how the pose origin relates to the distance sensor rays detecting an obstacle:

Figure 17.7 – Robot sensor geometry
Figure 17.7 – Robot sensor geometry
The preceding figure shows the robot in the lower middle, facing an Obstacle in front. The robot pose X and Y axes are shown to make the pose orientation clear. Labeled near the middle of the image is the Distance sensor. Let’s use this to understand the sensor frame of reference relative to the robot.
One row from our Distance sensor is shown as 8 rays, dashed lines in the image. According to the VL53L5CX datasheet, these have a spread of 45 degrees, or Pi divided by 4 (an eighth of a circle). We’re calling this the Field of View or FoV.
The rays are spaced an eighth of the FoV apart. Each sensor in the row will have measured the distance, the length of the ray.
Let’s add this to robot/observation_models/distance.py in the __init__ constructor:
def __init__(self, probability_field_path="robot/observation_models/distance_map.npy"): self.probability_field = np.load(probability_field_path) self.frame = arena.MapFrame(100) self.sensor_forward_offset = 50.0 # mm sensor_fov = np.pi / 4 # 45 degrees sensor_angles = np.linspace(-sensor_fov/2, sensor_fov/2, 8) self.sensor_unit_vectors = np.array([ (np.cos(angle), np.sin(angle)) for angle in sensor_angles ]) self.relative_sensor_positions = np.empty((8, 2))The added code sets up a forward offset for the front of the sensor from the robot origin. We set sensor_fov (field of view) to match the datasheet. Then in sensor_angle s, we create a set of eight sensor angles, putting the field of view on either side of the 0 point. The rightmost sensor has a negative angle, while the leftmost has a positive angle. We won’t need to flip the sensor data here the way we did with the distance obstacle avoidance examples.
Since these angles don’t change, we can pre-calculate their cosine and sine and store them in self.sensor_unit_vectors.
When this model receives sensor readings, we want to get their position relative to the robot origin, so we’ve made an empty list self.relative_sensor_positions to store the x, y coordinates of these.
We need to transform those readings by the forward offset and the sensor angles to get their position relative to the robot origin. Add a handle_sensor_readings method to convert sensor data to relative positions:
def handle_sensor_readings(self, sensor_readings: np.ndarray): without_floor = sensor_readings[4::] row_reading = np.min(without_floor, axis=0) relative_to_sensor = self.sensor_unit_vectors * row_reading[:, np.newaxis] self.relative_sensor_positions = relative_to_sensor + np.array([self.sensor_forward_offset, 0])This method is passed the array of data from our distance sensor (see Chapter 8, Programming Distance Sensors with Python and Chapter 9, Avoiding Obstacles with Distance Sensors). We skip the first 4 rows, so we aren’t detecting the floor.
The first sensor fusion step we have in our distance observation model is to filter out misreads or sensor errors. Cells with an error return 3000, which is further than any distance in this arena. To do this, we take the minimum reading for each row using np.min. This leaves us with a single row of 8 readings in the variable row_reading, and naturally ignores the 3000 no-return values. This is a crude way to exclude anomalies, at least those further away than the other readings for that column.
We then multiply the unit vectors by these readings to get coordinates relative to the sensor and store them in relative_to_sensor. We use np.newaxis so NumPy can multiply each scalar reading by its corresponding 2D unit vector, resulting in a new coordinate for each.
The final part adds our forward offset to each of the coordinates, storing it in self.relative_sensor_positions. We expect this to be called by the distance sensor handling, so it needs to store this for when the robot position is being checked.
Let’s test this.
Testing distance handling in Jupyter
Section titled “Testing distance handling in Jupyter”We can load this in our Jupyter Notebook and verify what these look like as a plot relative to a robot. Open experiments/distance_probabilities.ipynb in Jupyter. In a new cell, let’s add some test readings:
distance_readings = np.array([[50]*8] * 4 + [[223,205,192,182,174,169,165,163]] * 4)distance_readings[5, 3] = 3000This set of test readings makes the floor (first 4) at a close 50 mm, then the rest are taken from the robot viewing a wall about 200 mm distance. We introduce one spurious reading of 3000 to test that these do not skew the results. We can ask the model to process them:
model.handle_sensor_readings(distance_readings)model.relative_sensor_positionsThis will have calculated and displayed a set of eight coordinates. However, drawing them will make it clearer what is going on:
plt.figure(figsize=(8, 8))plt.plot([0, model.sensor_forward_offset], [0, 0], 'r-')for sensor_pos in model.relative_sensor_positions: plt.plot([model.sensor_forward_offset, model.sensor_forward_offset + sensor_pos[0]], [0, sensor_pos[1]], 'b-')This code creates a plot and starts by drawing a red line (r‑) to the forward offset—using a plot with x data of 0 and the offset, and y data of 0s.
It then loops over model.relative_sensor_positions, plotting from the forward offset to the relative sensor coordinates for each sensor in blue (b‑). You should see something like this:

Figure 17.8 – Sensor readings plot
Figure 17.8 – Sensor readings plot
This screenshot shows the expected output of the above code. The blue lines are around 200 mm in front of the red line, as the code has ignored the floor readings of 50.
It has used the min function on each column, so it ignored the spurious 3000 mm as expected. This will account for any single sensor error; otherwise, one line would fly off into the distance. If you see one line longer, check the np.min line.
Now that we have the sensor geometry relative to the sensor surface, we need to map this to robot poses.
Making sensor endpoints from poses
Section titled “Making sensor endpoints from poses”We now have eight sensor coordinates relative to the robot. However, these need to be combined with each pose to get them into the pose’s frame of reference. The sensor beams are currently calculated relative to the world origin at 0,0 and facing right. However, the poses will be at other locations and orientations. Let’s see what we need to do:

Figure 17.9 – Sensor beam transformations
Figure 17.9 – Sensor beam transformations
The preceding figure shows how we will need to transform sensor beams to match our poses:
- The beams start with the sensor offset at the origin, facing right. A robot icon depicts a possible pose.
- First, we rotate the beams around the origin to align them with the pose orientation.
- Next, we translate (move) the beams to match the pose position.
- Finally, we combine the sensor beam positions with all poses. There are eight relative beam positions, each represented by a set of coordinates. The result is a data structure containing the number of poses × 8 points, each represented by an (x, y) coordinate pair.
We are going to be rotating coordinates. Rotations of coordinates might need some explanation if you’ve not seen it before. See the following diagram:

Figure 17.10 – Coordinate rotations
Figure 17.10 – Coordinate rotations
The figure shows a series of steps for rotating a coordinate. Let’s walk through them:
- The first part here shows what we mean in our operation. We start with a set of coordinates x, y – a vector of size 2. These will be rotated by the angle theta with respect to the origin. The goal image shows where the rotated coordinate will be.
- We take the x coordinate and use it to scale a unit vector at angle theta. This is equivalent to rotating the X-axis for this coordinate. This results in a rotated x vector with the calculated coordinates shown on the right.
- We then use a similar process with the y coordinate. We need to rotate the unit vector for theta by 90 degrees, so we can use it as a Y-axis rotation. One trick for this 90-degree rotation is to notice that the sin(theta) element now describes a line going from the Y-axis to the right, while the cos(theta) element now lies along the Y-axis. We scale this unit vector by the input y coordinate, resulting in the rotated y vector on the right.
- We can add these vectors, take the rotated x vector, and add the rotated y vector to where it ends. This results in the formulae on the right. We’ll see this in the code.
Let’s build the code. Add this method into robot/observation_models/distance.py:
def sensor_endpoints(self, poses: Poses) -> np.ndarray: cos_theta = np.cos(poses['theta'])[:, None] sin_theta = np.sin(poses['theta'])[:, None]
sensor_x = self.relative_sensor_positions[None:, 0] sensor_y = self.relative_sensor_positions[None:, 1]
sensor_rotated = np.stack( (sensor_x * cos_theta - sensor_y * sin_theta, sensor_x * sin_theta + sensor_y * cos_theta), axis=-1 )
return poses.positions[:, None] + sensor_rotatedThis code takes an array of poses, and returns an array of shape (N, 8, 2) with 8 coordinates for each sensor for each of the N poses.
We start by pre-calculating the unit vector cos_theta and sin _ theta elements for each pose. Pre-calculating them here will make later operations faster, as the sin and cos functions can be expensive to calculate.
We extract the sensor_x and sensor_y elements for all relative sensor coordinates.
We then create a sensor_rotated array, which will have (N, 8, 2) shape again, and has the rotation formulae we saw above applied to the sensor coordinates and pose theta. The function np.stack helps us stack elements back into an array of vectors, with the axis parameter instructing it to stack along the last axis, the 2 of the (N, 8, 2) shape.
We finally add the pose position to the rotated sensor coordinates.
It will be helpful to draw this in Jupyter to see what we’ve just done. Add the following in a cell (using the width and height of your arena if different):
poses = Poses.generate(20, (0, 1500), (0, 1500), (0, 2 * np.pi))This code will generate some random poses to test with, mostly on the boundary (some will be in the cut). Run this cell, then add a further one:
endpoints = model.sensor_endpoints(poses)plot_map(walls_map)for n, pose in enumerate(poses): x, y, theta = pose offset_x = x + model.sensor_forward_offset * np.cos(theta) offset_y = y + model.sensor_forward_offset * np.sin(theta) plt.plot([x, offset_x], [y, offset_y], 'g-', alpha=0.3) for sensor in range(8): plt.plot([offset_x, endpoints[n, sensor, 0]], [offset_y, endpoints[n, sensor, 1]], 'b-', alpha=0.3)This makes a visualisation of our endpoints. It starts by calling the sensor_endpoints method with the poses.
Then it plots a map of the walls as a background.
The code loops over the poses, using the variable i as an index for the poses. For each pose, it extracts its components and draws a small line for the forward offset (from the pose to the front of the robot). The style g‑ means a green solid line, and alpha=0.3 means 30% opaque, so you can see detail through these lines.
Then, within each pose, it loops over each of the sensor endpoints and draws a line from the offset to the endpoint. It uses the style b‑ for blue solid lines and the same opacity.
When you run this, you should see something like the following:

Figure 17.11 – Sensor endpoints transformed to match poses
Figure 17.11 – Sensor endpoints transformed to match poses
The screenshot shows the simple wall map, with a number of poses showing all the sensor beams radiating from them. Some are touching walls, most are not even near.
At this point, if you have any errors, check the code carefully. Because we are pulling apart arrays of coordinates, there are multiple bracket dereferences, so take extra care with the brackets.
This now means we can plot where each sensor beam has hit something for every pose. We are close to finding out which poses have a better probability.
Fusing distance sensor data
Section titled “Fusing distance sensor data”Armed with a model of the sensor geometry relative to all poses, we can use this to calculate probabilities for poses. We then need to integrate this into the localisation loop and fuse that with the existing observation model there.
Getting pose probabilities from sensor endpoints
Section titled “Getting pose probabilities from sensor endpoints”We now need to look up all the transformed poses in the probability field. We can do this by flattening the array of n by 8 coordinates into just an array of coordinates, for a lookup of all the probabilities. Add this in robot/observation_models/distance.py:
def calculate_weights(self, poses: Poses) -> np.ndarray: endpoints = self.sensor_endpoints(poses) flat = endpoints.reshape(-1, 2) flat_probs = self.get_probabilities(flat) probs = flat_probs.reshape(len(poses), 8)
return np.mean(probs, axis=1)This code starts by using the endpoint method we made above. It then flattens that output and uses the flat coordinates list to look up all the probabilities. The NumPy reshape method allows code to interact with data either in flatter or deeper dimensions without making a copy, so it is very efficient.
We then reshape the result back into groups of 8 so each pose has a probability.
We then fuse these eight sensor readings into a single probability. Calling np.mean calculates the average for all eight sensor-based probabilities for each pose. Using axis=1 selects averaging across the sensor axis, keeping the poses axis, so each pose is still separate. We use the mathematical mean (average) here, so a small pose miss doesn’t totally flatten the probabilities. A multiplication here means a miss would be too impactful; the mean makes it less so, while a pose with more close wall hits will still have a higher weight. The mean also damps out noise that can come from the sensor. It is important to be mindful of noise when fusing data from multiple sensor elements or multiple sensor sources.
We can test this in our Jupyter Notebook, experiments/distance_probabilities.ipynb. Modify the last cell to include the probabilities:
endpoints = model.sensor_endpoints(poses)weights = model.calculate_weights(poses)plot_map(walls_map)for n, pose in enumerate(poses): x, y, theta = pose offset_x = x + model.sensor_forward_offset * np.cos(theta) offset_y = y + model.sensor_forward_offset * np.sin(theta) plt.plot([x, offset_x], [y, offset_y], 'g-', alpha=0.3) for sensor in range(8): plt.plot([offset_x, endpoints[n, sensor, 0]], [offset_y, endpoints[n, sensor, 1]], 'b-', alpha=0.3) plt.text(x + 16, y + 16, str(n), color='red', fontsize=12)plt.scatter(poses['x'], poses['y'], c=np.log(weights), cmap='Greys', s=100, alpha=0.7)This adds a line to calculate the weights for all poses, and the last line of the cell makes a scatter plot, such that the higher the probability, the darker the color with a color map – cmap. We’ve used the log function to make the display a bit easier to read. There’s also a pose number to help with debugging. Run the cell to see something like this:

Figure 17.12 – Probabilities plotted for poses using sensor endpoints
Figure 17.12 – Probabilities plotted for poses using sensor endpoints
The screenshot now shows gray circles showing how relatively likely some poses are. The darker ones have more endpoints that are close to boundaries. Due to these samples being unlucky this time, none are particularly good fits yet. But those marked darker are certainly a better fit than those with no endpoints close to a boundary. Because there are some near misses, with a weight between the total misses and hits, the algorithm can “climb” the Gaussian curve, favoring closer and closer guesses. The boundary observation model would make no distinction between poses 6 and 14, as both are inside the boundary. The distance observation model accounts for pose 6 observations touching the wall, while pose 14 observations are nowhere near.
This distance observation model makes no distinction between poses being inside or outside the boundary. This means that poses 0 and 2 have higher weight (darker circles) than poses 18 and 11 here, despite clearly being outside the boundary. This is because poses 0 and 2 have endpoints that better align with walls than 11 and 18. For more accurate observations, we need to combine the distance observation model with the boundary observation model, since each brings different observations to the system.
We have now built and tested the components we need to add this observation model to our localisation system. Let’s incorporate it!
Incorporating the distance observation model
Section titled “Incorporating the distance observation model”Our current localisation loop runs every time the encoder data is received. This makes sense because we want to update our poses, move them, and recalculate their probabilities at this moment.
The distance sensor has a different timing model and will deliver data at other times. We will set up our localisation to handle distance sensor messages by updating the relative sensor positions (calling handle_sensor_readings in the observation model), and then consult the module when checking observations when handling the encoder updates.
Start by adding the distance observation model into the imports in robot/localisation.py:
from common import arenafrom common.mqtt_behavior import connect, publish_jsonfrom common.poses import Posesfrom observation_models.boundary import BoundaryObservationModelfrom observation_models.distance import DistanceObservationModelWe need some constants to express how much influence each observation model will have over our system. Lower values soften influence, higher values sharpen it:
boundary_model_influence = 0.5distance_model_influence = 0.5We then set up the distance model in the localisation init method:
self.boundary_model = BoundaryObservationModel()self.distance_model = DistanceObservationModel()Now we can use it in our code. We need an MQTT handler to send data to the distance observation model. Add this method:
def on_distance_readings(self, client, userdata, msg): sensor_data = np.array(json.loads(msg.payload)) sensor_readings = sensor_data.reshape((8, 8)) self.distance_model.handle_sensor_readings(sensor_readings)The method receives a distance message, decodes it, reshapes the sensor data, and then passes it to the observation model. We need to subscribe this method to the right topic in the start method. Make the highlighted changes:
client.subscribe("sensors/encoders/data")client.publish("sensors/encoders/control/reset")client.message_callback_add("sensors/encoders/data", self.on_encoders_data)client.subscribe("sensors/distance_mm")client.message_callback_add("sensors/distance_mm", self.on_distance_readings)client.publish("sensors/distance/control/start_ranging", "")
while True: time.sleep(0.1)This will now mean our model is receiving readings from the distance sensor. One final change will combine this with our existing boundary observation model in the apply_observational_models method:
def apply_observational_models(self): boundary_weights = self.boundary_model.calculate_weights(self.poses) ** boundary_model_influence distance_weights = self.distance_model.calculate_weights(self.poses) ** distance_model_influence return boundary_weights * distance_weightsThe changes here store the boundary model weights in the variable boundary_weights and then store the distance model calculated weight in distance_weights. That means it has calculated both observation models for our poses. Each is combined with an influence factor, using the exponent (power of) operator **, so that they can have a greater or lesser influence on the outcome. We can use the influence factor to damp noisy models or favor more reliable observation models.
We then multiply them together. Each set of weights is a weight-per-pose in NumPy arrays. By multiplying them like this, the operation is broadcast across them; that is, each boundary weight is multiplied by its corresponding distance weight for each pose, so the result is a set of weights for each pose, combining the model weights. Multiplying the probabilities fuses the data such that each weight now represents the probability of the pose prediction being true according to both sets of observation data.
Why use multiplication instead of mean?
Inside the observation models, data is strongly correlated, so a mean of the strongly correlated data stops the weight from collapsing under one sensor reading. However, when combining observation models, we want each independent piece of evidence from other observations to support the prediction or not. This is so that a strong disagreement, like the boundary model detecting a pose that is now outside the boundaries, would be reflected in the pose weight.
This is still compatible with the overall filter, and since we’ve extended the existing robot/observation_models folder, it is still compatible with deploy/deploy_services.py.
Let’s deploy it with pyinfra inventory.py ‑y ‑‑ deploy/deploy_services.py.
Reload the localisation page and use the start button on its own. You should see the field of poses immediately resolve to those matching distances in front of the robot. Test initially by rolling the motors by hand, to ensure the code doesn’t trip on something small.
If the poses freeze, use journalctl ‑u localisation to look for errors.
Then when you are happy with this result, put the robot (on battery) into the arena, stop the current localisation run, then start it again and use the Start motors button. The robot should start to group into sensible possible locations faster than the boundary model alone does.
Troubleshooting
Section titled “Troubleshooting”This code is complicated and can fail in multiple ways:
- Initially, use
journalctl ‑u localisationto look for errors. The distance service may also have errors. - If things are in no location, your distance sensor offset may be different from my 50 mm model; ensure that number reflects the real geometry of your robot.
- Ensure that your robot wheel diameters (modeled in Chapter 12, Encoder-Based Localisation with Python) are accurate to where the wheel is touching the floor, along with the wheel base (width), and encoder configuration.
- Ensure that the modeled boundary map is accurate – your arena should be rectilinear, and the numbers you use in the
robot/common/arena.pyshould be to the nearest mm. - Use the distance plot to observe what the distance sensors are detecting; if not, revisit the distance sensor chapter to check these.
This should get you to a system that can model the robot’s movement and find its position quickly. My testing shows this can create a dominant location group in 20 seconds, compared with the previous boundary-only system taking a few minutes. Start the robot in a few locations, and it should be really clear how the cut adds enough of a landmark to eliminate many of the poor guesses quickly.
The robot is now able to quickly guess its location. There are further ways we can fuse sensors into our localisation. While we could add further observation models, we can also add further motion data sources.
Fusing IMU yaw data
Section titled “Fusing IMU yaw data”Our IMU (Inertial Measurement Unit) provides robot orientation data based on gyroscope, accelerometer, and magnetic sensor data. We covered this in Chapter 13, IMU-Based Robot Navigation with Python.
We can combine IMU data with our encoder data to improve the odometry and motion model. The current motion model can over- or understeer and is subject to motor or wheel imbalances, along with wheels slipping on the surface. A minor inaccuracy in the wheelbase or wheel diameter settings can have a strong influence on the motion predictions.
The IMU would produce a yaw independent of the encoder data and not subject to the same limitations. It has its own limitations, needing to be calibrated, being influenced by magnetic fields (including the motors), and possible gyroscope drift.
Fusing the data from both sensor sources would allow each to compensate for the other’s limitations, reducing the noise in the data and improving its accuracy.
Preparation for fusing the motion data
Section titled “Preparation for fusing the motion data”Currently, the encoder data code is totally embedded into the localisation class. We’ll need to separate that out, creating a small decoupling. Also, as we found with the Distance Sensor observation model, different sensor data arrives at different times, so we will also need to decouple receiving data from consuming it.
We would create this class for the encoder system. Add this in robot/localisation.py above the Localisation class:
class EncoderMotionData: def __init__(self): self.wheel_distance = 136 self.previous_left_distance = 0 self.previous_right_distance = 0 self.pending_theta = 0.0 self.pending_distance = 0.0Since the wheel_distance is needed for encoder motion data, it is stored in this class, along with the previous distances that were in the Localisation class. The members pending_theta and pending_distance store data that hasn’t yet been consumed. If we receive further updates before the data is consumed, we add this to the data so the deltas (differences) account for all updates. Let’s see how:
def on_encoders_data(self, client, userdata, msg): encoder_data = json.loads(msg.payload) left_distance_delta = (encoder_data['left_distance'] - self.previous_left_distance) right_distance_delta = (encoder_data['right_distance'] - self.previous_right_distance) self.previous_left_distance = encoder_data['left_distance'] self.previous_right_distance = encoder_data['right_distance']
# Special case, straight line if left_distance_delta == right_distance_delta: self.pending_distance += left_distance_delta return
self.pending_distance += (left_distance_delta + right_distance_delta) / 2 self.pending_theta += (right_distance_delta - left_distance_delta) / self.wheel_distanceThis on_encoders_data method will be subscribed to the MQTT topic, and will update the pending members with new data, calculating them from the incoming encoder data using code extracted from Localisation.on_encoders_data and Localisation.convert_encoders_to_motion. We then need a method to consume it:
def consume_data(self): translation = self.pending_distance theta = self.pending_theta self.pending_distance = 0.0 self.pending_theta = 0.0 return translation, thetaThis method makes a temporary store of the pending members, then resets them to 0, returning the accumulated translation and theta values for the Localisation class to use.
We can then simplify the Localisation class. The initializer created this EncoderMotionData class and no longer needs to set up the previous left and right distance members:
def __init__(self): self.poses = Poses.generate(population_size, (arena.left, arena.right), (arena.bottom, arena.top), (0, 2 * np.pi))
self.trans_noise_from_trans = 0.2/100 self.trans_noise_from_rot = 0.1/100 self.rot_noise_from_rot = 0.2/100 self.rot_noise_from_trans = 0.01/100
self.boundary_model = BoundaryObservationModel() self.distance_model = DistanceObservationModel() self.encoder_data = EncoderMotionData()The highlighted code creates an instance of the EncoderMotionData class. Otherwise, this initializer mostly removes previously defined members.
Since we moved their logic to EncoderMotionData, you can remove the convert_encoders_to_motion method from Localisation and rename the Localisation.on_encoders_data method to update and make the highlighted changes:
def update(self, client): # Sense translation, theta = self.encoder_data.consume_data()
# Think rotation = theta / 2 trans_samples, rot_samples = self.randomise_motion( translation, rotation)Along with the name change, the Sense section now consumes data from the sensor data source. The Think section now has the line calling convert_encoders_to_motion removed. The rest of the Think section and the Act section have not changed since the prior Localisation.on_encoders_data method. This update method takes a client parameter for the MQTT client so it can publish poses there.
We require some small changes to the Localisation.start method too, connecting the data source handler method and making the update calls:
def start(self): client = connect(start_loop=False) arena.publish_map(client)
client.subscribe("sensors/encoders/data") client.publish("sensors/encoders/control/reset") client.message_callback_add("sensors/encoders/data", self.encoder_data.on_encoders_data) client.subscribe("sensors/distance_mm") client.message_callback_add("sensors/distance_mm", self.on_distance_readings) client.publish("sensors/distance/control/start_ranging", "")
while True: client.loop(0.1) self.update(client)Only the highlighted changes are needed. We have decoupled our updates from the encoder data arriving. This means that updates are outside the MQTT thread. This could have problems if we try to consume data at the same time as the handler methods for any sensor data (encoders and distance sensor) try to update it. So we’ve altered the way the MQTT thread runs. When we connect, we set start_loop to False, which allows us to take control of the MQTT client processing thread.
In the main while true loop, instead of sleeping, we now ask the MQTT client to loop for 0.1 seconds, which will process queued messages and send pending messages as required for that time. After this, we call self.update to process and consume data.
This refactor serves two purposes. First, it decouples the encoder data from localisation, making it easier to add in further motion data sources. Secondly, if encoder data is being queued faster than our full pose update and resampling cycle can process it, instead of queuing up, it can now update the pending motion variables and be consumed when the update cycle is ready.
Sending this to the robot with PyInfra should not result in a noticeable change, and localisation should still work.
Creating the IMU motion data system
Section titled “Creating the IMU motion data system”We can now complement the encoder motion data system with an IMU data system. The code for sampling and storing pending data is similar to the encoder motion data system, but also much simpler. In robot/localisation.py, add the following below EncoderMotionData:
class ImuMotionData: def __init__(self): self.previous_yaw = None self.pending_theta = 0.0This ImuMotionData class starts with an init method that sets up two members:
- The member
previous_yawwill store the previous IMU reading so we can calculate deltas - The member
pending_thetawill let us accumulate theta updates so they can be consumed when needed
We will be accumulating angle data into pending_theta. When we add or subtract angle information, we must be wary of updates that cross the 0 line, which would take us to adding a full rotation instead of subtracting a small delta. We need the normalise_angle method to ensure that theta changes result in the smallest rotation:
def normalize_angle(self, angle): return (angle + np.pi) % (2 * np.pi) - np.piNext, we require an MQTT handler to consume data published by the IMU service:
def on_imu_data(self, client, userdata, msg): imu_data = json.loads(msg.payload) yaw = imu_data['yaw'] if self.previous_yaw is not None: delta_yaw = self.normalize_angle(yaw - self.previous_yaw) self.pending_theta += delta_yaw self.previous_yaw = yawThe method on_imu_data extracts the current yaw from the IMU data and extracts the delta_yaw, or difference in yaw since the last update. One special case is the first time it runs, in which case there is no previous yaw, so we need to store that and leave the pending theta at 0.
We have some MQTT/IMU housekeeping to do – we only want to start updating data when the sensor is calibrated:
def on_status_update(self, client, userdata, message): status = json.loads(message.payload) if status['sys'] == 3: # Fully calibrated client.subscribe("sensors/imu/euler") client.message_callback_add("sensors/imu/euler", self.on_imu_data)This method is a copy of the one used in the robot/face_direction.py code. Only when the IMU system status is 3, e.g., fully calibrated, will we subscribe to the Euler IMU topic, with roll, pitch, and yaw updates.
The last method in this class returns the accumulated theta value:
def consume_data(self): delta_theta = self.pending_theta self.pending_theta = 0.0 return delta_thetaThis consume_data method stores the accumulated pending_theta value, then resets it to 0 for the next update, and returns the stored value.
When dealing with sensor data like this, sometimes a further low-pass filter is added to only accept a percentage of an update; however, there are a few reasons we won’t need to:
- The BNO055 has onboard fusion algorithms that apply low-pass filters to the noisier sensors
- Our delta will be read at the lower frequency of our update loop
- And in the next section, we are fusing with another data source, also reducing the influence of noise
For this reason, we don’t need to add a further low-pass filter to this sensor class.
Fusing the IMU data
Section titled “Fusing the IMU data”We now need to connect this data system with the localisation system and fuse it with the encoder motion data. As with the observation models, we want to be able to control how much each influences the motion. At the top of robot/localisation.py, add the highlighted change with the other influence settings:
boundary_model_influence = 0.5distance_model_influence = 0.5imu_rotation_influence = 0.7We are only expressing IMU, as this time we will allow the IMU to influence the rotation 70% and assume that encoders influence it the remaining 30%. This value can be tuned based on how much we trust each source for rotation.
In the Localisation.__init__ method, we need to create an instance of the ImuMotionData system:
self.boundary_model = BoundaryObservationModel()self.distance_model = DistanceObservationModel()self.encoder_data = EncoderMotionData()self.imu_data = ImuMotionData()We can then modify our update method to account for it:
# Sensetranslation, encoder_theta = self.encoder_data.consume_data()imu_theta = self.imu_data.consume_data()
# Thinktheta = (1 - imu_rotation_influence) * encoder_theta + imu_rotation_influence * imu_thetarotation = theta / 2trans_samples, rot_samples = self.randomise_motion( translation, rotation)Only the Sense and part of the Think sections have changed here. We’ve clarified the encoder return values with the variable encoder_theta, so it can be distinct from the imu_theta we get by consuming from imu_data.
In the think section, we calculate a unified theta. The IMU rotation influence is distributed such that the IMU data is multiplied by this influence, and the encoder theta is multiplied by what is left. This is known as a c omp le mentary filter – combining the sources and assuming they have complementary sources of noise and error.
We then need to hook this up in the Localisation.start method:
def start(self): client = connect(start_loop=False) arena.publish_map(client)
client.subscribe("sensors/encoders/data") client.publish("sensors/encoders/control/reset") client.message_callback_add("sensors/encoders/data", self.encoder_data.on_encoders_data) client.subscribe("sensors/distance_mm") client.message_callback_add("sensors/distance_mm", self.on_distance_readings) client.publish("sensors/distance/control/start_ranging", "")
client.subscribe("sensors/imu/status") client.message_callback_add("sensors/imu/status", self.imu_data.on_status_update) client.publish("launcher/start", "imu_service")
try: while True: client.loop(0.1) self.update(client) finally: client.publish("launcher/stop", "imu_service")Here, we’ve ensured we are subscribed to the Euler status topic to indicate when the IMU is calibrated. We hook that up to trigger the self.imu_data.on_status update handler. We then publish a message to the launcher to start the imu_service, which will start its calibration cycle.
We’ve wrapped the main loop in a try / finally block to ensure that the IMU service is stopped when this code stops.
We need our Localisation page to show us the calibration status; otherwise, we cannot tell when the system is ready.
Adding IMU calibration status
Section titled “Adding IMU calibration status”The IMU service is already publishing its status, and we have written code to show this on a page before. We now need to copy over the relevant components into the robot_control/localisation.html code. Open this file, and locate the buttons section, then insert the highlighted code:
<button id="start">Start</button><button id="stop">Stop</button><button id="start_moving">Start moving</button><button id="stop_moving">Stop moving</button>IMU Status: <samp id="status"></samp><div style="height: 60vh; width: 60vh;"> <canvas id="poses"></canvas></div>This creates a status element where we can render the status update.
Find the mqttClient.subscribe calls near the bottom of robot_control/localisation.html and make the highlighted change:
mqttClient.subscribe('localisation/#')mqttClient.subscribe('sensors/imu/status');mqttClient.on('message', (topic, message) => { switch (topic) { case 'sensors/imu/status': document.getElementById('status').innerText = message; break; case 'localisation/poses': if (awaiting_update) { return; }The first highlighted change subscribes our control page to the sensors/imu/status MQTT topic.
When we receive a message on the sensors/imu/status topic, we set the status element’s data to the message content.
We now have all the components to deploy and test fusing IMU data.
Deploying and testing IMU fusion
Section titled “Deploying and testing IMU fusion”Deploy the IMU fusion code using pyinfra inventory.py ‑y ‑‑ deploy/deploy_services.py.
Ensure you stop any current localisation run, then navigate from the menu to the Localisation page or reload it in your browser if you are already there.
When you press Start, you will need to follow the IMU calibration procedures from Chapter 13, IMU-Based Robot Navigation with Python, and the IMU system status must hit 3 before localisation starts consuming IMU data.
Test the robot driving around in the arena and observe whether the orientation is more accurate than with encoders alone.
Let’s see what we’ve learned.
Summary
Section titled “Summary”We’ve learned about probability fields, a way to pre-calculate probabilities like the wall distances, and how a Gaussian curve lets an algorithm climb to better weighted options.
You’ve seen how a world map and a map frame relate to each other, so we can model the possibility of hits being slightly off the map. We looked at how we can look up in the maps we created.
We then looked at how unit vectors worked, and how scaling them can be used to model distance sensor beams hitting objects in front of the robot. This led us into the geometry of rotating and moving coordinates, so we could map all the modeled sensor hit coordinates to all the poses.
We used geometrically mapped poses to look up the weights in the probability field and combined them to make a distance observation weight for every pose, then saw how to combine that with our boundary observation model.
We then saw how the combination of fusing these two observation models made the localisation algorithm faster and smarter.
We’ve then looked at how to separate the motion data from the localisation system and fuse IMU sensor data with our encoder-based motion detection to create a smarter motion detection system, with each compensating for the flaws of the other.
In the next chapter, we are going to see how we will continue our robotics journey and what you could build next!
Challenges
Section titled “Challenges”The following challenges will let you build a better localisation system and practice more of the techniques in this chapter:
- Consider the geometry of the robot camera when facing forward. How would you model this? Can you use the camera datasheet to determine its field of view in degrees and consider how horizontal positions would map to relative angles?
- Place a colored card target (circle) matching the color range in the colored object detector in the middle of a long wall on the arena. How could you model this position as a probability field, considering that the real world might be noisy?
- If you know the size of this circle, and the camera field of view, consider how the distance and angle of this target could be calculated relative to a pose from the object detector messages?
- Could you use the modeling of colored targets to build a colored target observation model?
- The system has converged on clustering: a good area of research is clustering algorithms, so the robot could detect how well localisation is locked in. Could you add that ability?
- With clustering locked in, and a location (with a probability), could the robot be made to drive to a target zone and orientation?
Further reading
Section titled “Further reading”Please refer to the following for more information:
- A simpler model using two distance sensors for localisation can be found in Robotics at Home with Raspberry Pi Pico by Danny Staple.
- For more on robotics localisation, I recommend the playlist of robotics videos from Bonn University delivered by Cyrill Stachniss at https://www.youtube.com/playlist?list=PLgnQpQtFTOGQEn33QDVGJpiZLi-SlL7vA.
- Probabilistic Robotics by Sebastian Thrun, Dieter Fox, Wolfram Burgard from MIT Press is fundamental in the Monte Carlo localisation and observation models field.
- Further reading on Monte Carlo localisation and other advanced robotics algorithms can be found in Robotics, Vision and Control: Fundamental Algorithms in Python – Springer Tracts in Advanced Robotics 146 by Peter Corke.
- Scientific Computing with Python: High-performance scientific computing with NumPy, SciPy, and pandas by Claus Fuhrer, Jan Erik Solem*,*and Olivier Verdier presents information on using Python’s tools for numerical manipulation with large datasets more effectively.