Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions src/roboticstoolbox/mobile/ParticleFilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,15 @@ def run_animation(self, T=10, x0=None, format=None, file=None):
# # anim.add()
# # anim.close()

def _step(self):
def _step(self) -> None:
"""Advance the simulation and estimate the current particle cloud.

Heading uses the circular mean, with dispersion given by the root
mean square of wrapped angular residuals. The moments describe the
equally weighted cloud after resampling, when an observation is
available. A zero mean resultant does not define a unique heading;
in that case SciPy's circular mean selects a representative.
"""

# fprintf('---- step\n')
odo = self.robot.step(animate=self._animate) # move the robot
Expand All @@ -509,12 +517,11 @@ def _step(self):

# our estimate is simply the mean of the particles
x_est = self.x.mean(axis=0)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

computing the mean of column 2, and then overwriting it in next line is wasteful

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 13fa7a5: the linear mean is now computed only over self.x[:, :2], so the heading column is no longer averaged and overwritten.

x_est[2] = sp.stats.circmean(self.x[:, 2], low=-np.pi, high=np.pi)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use spatialmath angle_mean()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 13fa7a5 to use spatialmath.base.angle_mean(self.x[:, 2]). The wrap-boundary and particle-replication regressions pass in the current CI run.

std_est = self.x.std(axis=0)

# std is more complex for angles, need to account for 2pi wrap
std_est[2] = np.sqrt(np.sum(smb.angdiff(self.x[:, 2], x_est[2]) ** 2)) / (
self.nparticles - 1
)
std_est[2] = np.sqrt(np.mean(smb.angdiff(self.x[:, 2], x_est[2]) ** 2))

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use spatialmath angle_std()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 13fa7a5 to use spatialmath.base.angle_std() on the centred heading residuals. This avoids round-off for replicated identical headings; the tests also cover singleton and near-zero-resultant clouds. The docstring now describes circular standard deviation and its unbounded spread near a zero resultant.


# display the updated particles
# set(self.h, 'Xdata', self.x(:,1), 'Ydata', self.x(:,2), 'Zdata', self.x(:,3))
Expand Down Expand Up @@ -658,15 +665,18 @@ def get_xyt(self):
"""
return np.array([h.xest[:2] for h in self._history])

def get_std(self):
def get_std(self) -> np.ndarray:
r"""
Get standard deviation of particles

:return: standard deviation of vehicle position estimate
:rtype: ndarray(n,2)
:return: dispersion of position and heading estimates, shape (n, 3)
:rtype: ndarray(n,3)

Return the standard deviation :math:`(\sigma_x, \sigma_y)` of the
particle cloud at each time step.
Return the population standard deviation of position and the root
mean square wrapped heading residual
:math:`(\sigma_x, \sigma_y, \sigma_\theta)` of the equally weighted
particle cloud at each time step. Heading residuals are measured
from the circular mean in radians.

:seealso: :meth:`get_xyt`
"""
Expand Down
107 changes: 107 additions & 0 deletions tests/test_particle_heading_moments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Circular heading moments in native particle-filter simulation steps."""

import numpy as np
import pytest
from numpy.testing import assert_allclose
from scipy.stats import circmean
from spatialmath import base

import roboticstoolbox as rtb


def _particle_filter(
particles: np.ndarray, *, observations: bool = False, seed: int = 7
) -> rtb.ParticleFilter:
"""Build a stationary native vehicle, map, sensor and particle filter."""
robot = rtb.Bicycle(workspace=10)
robot.control = (0.0, 0.0)
landmarks = rtb.LandmarkMap(np.array([[3.0, 4.0], [-3.0, -2.0]]).T, workspace=10)
sensor = rtb.RangeBearingSensor(
robot,
landmarks,
covar=np.zeros((2, 2)),
fail=[] if observations else [(0, 100)],
seed=seed,
)
particle_filter = rtb.ParticleFilter(
robot,
sensor,
R=np.zeros((3, 3)),
L=np.diag([0.2, 0.2]),
nparticles=len(particles),
seed=seed,
animate=False,
)
particle_filter._init()
particle_filter.x = particles.copy()
return particle_filter


@pytest.mark.parametrize("centre", [0.0, np.pi - 0.02, -np.pi + 0.02])
@pytest.mark.parametrize("copies", [1, 3, 50])
def test_heading_moments_survive_wrap_and_particle_replication(
centre: float, copies: int
) -> None:
"""A tight heading cloud has the same centre/spread across the angle cut."""
offsets = np.array([-0.3, -0.1, 0.1, 0.3])
particles = np.c_[[0.0, 2.0, 4.0, 6.0], [0.0, 1.0, 2.0, 3.0], centre + offsets]
particles = np.tile(particles, (copies, 1))
particle_filter = _particle_filter(particles)

particle_filter._step()

step = particle_filter.history[-1]
assert_allclose(base.angdiff(step.xest[2], centre), 0.0, atol=1e-14)
assert_allclose(step.std[2], np.sqrt(0.05), atol=1e-14)
assert_allclose(step.xest[:2], [3.0, 1.5])
assert_allclose(step.std[:2], [np.sqrt(5.0), np.sqrt(1.25)])
assert_allclose(particle_filter.get_std()[-1], step.std)
np.testing.assert_equal(np.all(np.abs(particle_filter.x[:, 2]) <= np.pi), True)


def test_single_particle_has_zero_heading_spread() -> None:
"""A one-particle cloud has finite zero population dispersion."""
particle_filter = _particle_filter(np.array([[2.0, -1.0, 3.0]]))

particle_filter._step()

assert_allclose(particle_filter.history[-1].xest, [2.0, -1.0, 3.0])
assert_allclose(particle_filter.history[-1].std, np.zeros(3))


@pytest.mark.parametrize("observations", [False, True])
def test_heading_moments_use_the_current_resampled_cloud(
observations: bool,
) -> None:
"""Population moments describe the current cloud after native resampling."""
particles = np.c_[
np.linspace(-0.2, 0.2, 12),
np.linspace(0.1, -0.1, 12),
np.linspace(np.pi - 0.3, np.pi + 0.1, 12),
]
particle_filter = _particle_filter(particles, observations=observations)

particle_filter._step()

cloud = particle_filter.x
expected_heading = circmean(cloud[:, 2], low=-np.pi, high=np.pi)
residuals = np.angle(np.exp(1j * (cloud[:, 2] - expected_heading)))
step = particle_filter.history[-1]
assert_allclose(base.angdiff(step.xest[2], expected_heading), 0.0, atol=1e-14)
assert_allclose(step.std[2], np.sqrt(np.mean(residuals**2)))
assert_allclose(step.xest[:2], cloud[:, :2].mean(axis=0))
assert_allclose(step.std[:2], cloud[:, :2].std(axis=0))
if observations:
np.testing.assert_equal(np.any(step.weights != step.weights[0]), True)


def test_symmetric_resultant_has_finite_dispersion() -> None:
"""An undefined circular centre still uses the library's representative."""
particle_filter = _particle_filter(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, np.pi]]))

particle_filter._step()

step = particle_filter.history[-1]
np.testing.assert_equal(np.isfinite(step.xest).all(), True)
np.testing.assert_equal(np.isfinite(step.std).all(), True)
np.testing.assert_equal(0 <= step.std[2] <= np.pi, True)
Loading