Algorithm Search⌘K

Algorithmintro

Bayes filter

Also called recursive Bayesian estimation, recursive state estimation.

Updates a belief over the state by a prediction with the motion model and a correction by Bayes' rule with the measurement model.

Solves
Filtering
Time
O(T g^2) worst
Space
O(g) extra
Where
T = the number of time steps; g = the number of states of a finite state space
Properties
deterministicexactonlinerecursive
Origin
Yu Chi Ho, Robert C. K. Lee, 1964

The Bayes filter is the exact recursive solution of the filtering problem: at each time step it turns the belief bel(xt−1)\mathrm{bel}(x_{t-1}), a probability distribution over the state of a system, into bel(xt)\mathrm{bel}(x_t) by a prediction with the motion model and a correction with the measurement model by Bayes' theorem. It is correct when the state is Markov, so it is the filter of a hidden Markov model or of a state-space model with controls. As written, it is a recursion of distributions, not a program: the Kalman filter is its closed form in the linear Gaussian case, the particle filter is a Monte Carlo approximation, and the histogram filter runs it on a grid. This page gives the recursion, its proof and the exact version for a finite state space, where it costs O(g2)O(g^2) time per step for gg states.

In plain words

A robot does not know exactly where it is. It keeps a score for each place where it could be, and the scores add up to one. Two things happen again and again. First the robot moves. Its wheels slip, so the scores spread out: each place passes its score to the places the robot could reach from there. Then the robot looks at the world, for example it sees a door. Each place keeps its score times the chance of seeing a door from that place. Places with no door near them lose most of their score. At the end, the robot divides all scores by their total, so that they add up to one again. After a few moves and looks, most of the score sits on a few places, and often on one.

The problem

The state xtx_t of the robot (for example its pose (x,y,θ)(x, y, \theta), or a cell of a map) changes at each time step t=1,2,…t = 1, 2, \ldots under a control utu_t, and the robot gets a measurement ztz_t. The notation is the one of Thrun, Burgard and Fox (2005). The model has three parts:

  • the initial belief bel(x0)=p(x0)\mathrm{bel}(x_0) = p(x_0);
  • the motion model p(xt∣ut,xt−1)p(x_t \mid u_t, x_{t-1}), for example the odometry motion model or the velocity motion model;
  • the measurement model p(zt∣xt)p(z_t \mid x_t), for example the beam range finder model or the landmark measurement model. With a map mm it is p(zt∣xt,m)p(z_t \mid x_t, m); the map is fixed and known here.

Two conditional independence assumptions, together called the Markov assumption, make the state complete:

p(xt∣x0:t−1,z1:t−1,u1:t)=p(xt∣ut,xt−1),p(zt∣x0:t,z1:t−1,u1:t)=p(zt∣xt).p(x_t \mid x_{0:t-1}, z_{1:t-1}, u_{1:t}) = p(x_t \mid u_t, x_{t-1}), \qquad p(z_t \mid x_{0:t}, z_{1:t-1}, u_{1:t}) = p(z_t \mid x_t).

The output at each step is the posterior bel(xt)=p(xt∣z1:t,u1:t)\mathrm{bel}(x_t) = p(x_t \mid z_{1:t}, u_{1:t}). The prediction before the measurement is bel‾(xt)=p(xt∣z1:t−1,u1:t)\overline{\mathrm{bel}}(x_t) = p(x_t \mid z_{1:t-1}, u_{1:t}).

The algorithm

For a continuous state, read each sum as an integral.

  1. BAYES-FILTER(bel, u_t, z_t) ▷ bel(x) = bel(x_{t-1}) for each state x
  2. 1for each state x_t do
  3. 2bel_bar(x_t) ← Σ_{x_{t-1}} p(x_t | u_t, x_{t-1}) bel(x_{t-1}) ▷ prediction
  4. 3bel'(x_t) ← p(z_t | x_t) bel_bar(x_t) for each state x_t ▷ correction
  5. 4η ← 1 / Σ_{x_t} bel'(x_t)
  6. 5bel(x_t) ← η bel'(x_t) for each state x_t
  7. 6return bel

Line L2 is the law of total probability over the previous state. It is the Chapman-Kolmogorov equation of a Markov chain whose transition depends on the control. Line L3 is the numerator of Bayes' theorem, and lines L4 and L5 divide by the evidence p(zt∣z1:t−1,u1:t)=1/ηp(z_t \mid z_{1:t-1}, u_{1:t}) = 1/\eta. The sequence of one prediction and one correction per step is the form of Thrun et al., Table 2.1. A step with no measurement skips lines L3 to L5, and a step with no motion skips lines L1 and L2.

The algorithm in this form needs a sum or an integral over the whole state space. It can run exactly in two cases only: a finite state space (this page, and the forward algorithm for hidden Markov models) and the linear Gaussian case (the Kalman filter). All other filters of robotics approximate one of the two lines L2 or L3.

Example

The door. This is the example of Thrun et al. (Section 2.4). A robot faces a door that is open or closed. Its sensor says "open" with probability 0.60.6 if the door is open and 0.20.2 if it is closed. The robot can do nothing, or push. A push opens a closed door with probability 0.80.8, and an open door stays open. The prior is bel(open)=0.5\mathrm{bel}(\text{open}) = 0.5.

step control and measurement bel‾(open)\overline{\mathrm{bel}}(\text{open}) bel′(open),bel′(closed)\mathrm{bel}'(\text{open}), \mathrm{bel}'(\text{closed}) bel(open)\mathrm{bel}(\text{open})
1 nothing, "open" 1/21/2 3/10,1/103/10, 1/10 3/4=0.753/4 = 0.75
2 push, "open" 3/4+0.8⋅1/4=19/203/4 + 0.8 \cdot 1/4 = 19/20 57/100,1/10057/100, 1/100 57/58≈0.98357/58 \approx 0.983

After two steps the robot is quite sure that the door is open, but not sure: the closed state keeps the probability 1/581/58, because the sensor can be wrong.

A corridor. A robot moves in a ring of 6 cells, numbered 0 to 5. Cells 0, 1 and 3 have a door. The command "one cell forward" moves the robot by 0, 1 or 2 cells with probabilities 0.10.1, 0.80.8 and 0.10.1. The door detector says "door" with probability 0.750.75 at a door and 0.20.2 elsewhere. The prior is uniform, and the robot moves and then senses "door", "door", "wall".

after cell 0 cell 1 cell 2 cell 3 cell 4 cell 5
move, "door" 0.2632 0.2632 0.0702 0.2632 0.0702 0.0702
move, "door" 0.1514 0.4127 0.1101 0.1841 0.1013 0.0404
move, "wall" 0.0242 0.0699 0.4786 0.0620 0.2262 0.1391

The first belief is 5/195/19 at each door and 4/574/57 elsewhere. After the third step the most likely cell is 2, the only cell without a door that follows two cells with a door. The belief is exact: summing the joint probability over all 64=12966^4 = 1296 paths of states gives the same fractions.

Correctness

Under the Markov assumption, and if each control utu_t is chosen from the past data z1:t−1,u1:t−1z_{1:t-1}, u_{1:t-1} and randomness that is independent of the state, the output of each step is exactly p(xt∣z1:t,u1:t)p(x_t \mid z_{1:t}, u_{1:t}). The proof is by induction on tt. Line L2 is correct because the motion model does not depend on older states and older data, and because the new control carries no information about xt−1x_{t-1}. Line L3 is correct because the measurement depends only on xtx_t. The full proof is in the correctness proof. Without the Markov assumption, the same lines still run, but the output is no longer the posterior.

Proof: The Bayes filter computes the posterior p(x_t | z_1:t, u_1:t)full

Setting. The states x0,x1,…x_0, x_1, \ldots take values in a finite set XX with gg elements. For a continuous state with densities, replace each sum over XX by an integral; the steps are the same. The data at time t≥1t \ge 1 are a control utu_t and a measurement ztz_t. Write dt=(z1:t,u1:t)d_t = (z_{1:t}, u_{1:t}) for the data up to time tt, with d0d_0 empty. The model gives p(x0)p(x_0), the motion model p(xt∣ut,xt−1)p(x_t \mid u_t, x_{t-1}) and the measurement model p(zt∣xt)p(z_t \mid x_t).

Assumptions.

  • (M1) State completeness for motion: p(xt∣x0:t−1,z1:t−1,u1:t)=p(xt∣ut,xt−1)p(x_t \mid x_{0:t-1}, z_{1:t-1}, u_{1:t}) = p(x_t \mid u_t, x_{t-1}).
  • (M2) State completeness for measurement: p(zt∣x0:t,z1:t−1,u1:t)=p(zt∣xt)p(z_t \mid x_{0:t}, z_{1:t-1}, u_{1:t}) = p(z_t \mid x_t).
  • (C) The control carries no news about the past state: p(xt−1∣dt−1,ut)=p(xt−1∣dt−1)p(x_{t-1} \mid d_{t-1}, u_t) = p(x_{t-1} \mid d_{t-1}). This holds when utu_t is a function of dt−1d_{t-1} and of randomness that is independent of all states and measurements, because then, given dt−1d_{t-1}, the control is independent of xt−1x_{t-1}.
  • (P) Each measurement that occurs has positive probability: p(zt∣dt−1,ut)>0p(z_t \mid d_{t-1}, u_t) > 0.

Claim. Let bel0(x)=p(x0=x)\mathrm{bel}_0(x) = p(x_0 = x), and let belt\mathrm{bel}_t be the output of BAYES-FILTER(belt−1,ut,zt)(\mathrm{bel}_{t-1}, u_t, z_t). Then for every t≥0t \ge 0 and every x∈Xx \in X,

belt(x)=p(xt=x∣dt).\mathrm{bel}_t(x) = p(x_t = x \mid d_t).

Proof. By induction on tt. For t=0t = 0 the claim is the definition of bel0\mathrm{bel}_0.

Let t≥1t \ge 1 and assume belt−1(x′)=p(xt−1=x′∣dt−1)\mathrm{bel}_{t-1}(x') = p(x_{t-1} = x' \mid d_{t-1}) for all x′x'.

Prediction (lines L1 and L2). By the law of total probability over xt−1x_{t-1}, and then by the product rule,

p(xt∣dt−1,ut)=∑x′∈Xp(xt∣xt−1=x′,dt−1,ut) p(xt−1=x′∣dt−1,ut).p(x_t \mid d_{t-1}, u_t) = \sum_{x' \in X} p(x_t \mid x_{t-1} = x', d_{t-1}, u_t)\, p(x_{t-1} = x' \mid d_{t-1}, u_t).

In the first factor, (M1) removes the older states and data. Summing (M1) over x0:t−2x_{0:t-2} shows that p(xt∣xt−1,dt−1,ut)=p(xt∣ut,xt−1)p(x_t \mid x_{t-1}, d_{t-1}, u_t) = p(x_t \mid u_t, x_{t-1}). In the second factor, (C) removes utu_t, and the induction hypothesis gives belt−1(x′)\mathrm{bel}_{t-1}(x'). So

p(xt∣dt−1,ut)=∑x′∈Xp(xt∣ut,xt−1=x′) belt−1(x′),p(x_t \mid d_{t-1}, u_t) = \sum_{x' \in X} p(x_t \mid u_t, x_{t-1} = x')\, \mathrm{bel}_{t-1}(x'),

which is the value bel‾(xt)\overline{\mathrm{bel}}(x_t) that line L2 computes.

Correction (lines L3 to L5). Bayes' theorem with the data dt−1,utd_{t-1}, u_t held fixed gives

p(xt∣zt,dt−1,ut)=p(zt∣xt,dt−1,ut) p(xt∣dt−1,ut)p(zt∣dt−1,ut).p(x_t \mid z_t, d_{t-1}, u_t) = \frac{p(z_t \mid x_t, d_{t-1}, u_t)\, p(x_t \mid d_{t-1}, u_t)}{p(z_t \mid d_{t-1}, u_t)}.

The left side is p(xt∣dt)p(x_t \mid d_t). In the numerator, (M2) summed over x0:t−1x_{0:t-1} gives p(zt∣xt,dt−1,ut)=p(zt∣xt)p(z_t \mid x_t, d_{t-1}, u_t) = p(z_t \mid x_t), and the second factor is bel‾(xt)\overline{\mathrm{bel}}(x_t). So the numerator is the value bel′(xt)\mathrm{bel}'(x_t) of line L3. The denominator does not depend on xtx_t. It equals ∑xp(zt∣xt=x) bel‾(x)=∑xbel′(x)\sum_{x} p(z_t \mid x_t = x)\, \overline{\mathrm{bel}}(x) = \sum_x \mathrm{bel}'(x) by the law of total probability, and it is positive by (P). So η\eta of line L4 is 1/p(zt∣dt−1,ut)1 / p(z_t \mid d_{t-1}, u_t), and line L5 gives belt(x)=p(xt=x∣dt)\mathrm{bel}_t(x) = p(x_t = x \mid d_t). This completes the induction. □\square

The steps with missing data. If no control is applied at time tt, the state does not change, so p(xt∣dt−1)=belt−1p(x_t \mid d_{t-1}) = \mathrm{bel}_{t-1} and skipping lines L1 and L2 is correct. If no measurement arrives, dtd_t adds only utu_t, and the prediction bel‾\overline{\mathrm{bel}} is already p(xt∣dt)p(x_t \mid d_t), so skipping lines L3 to L5 is correct. The same induction covers both cases.

The likelihood. Let the controls be fixed in advance, so that they are not random. Then p(zt∣dt−1,ut)=p(zt∣z1:t−1;u1:T)p(z_t \mid d_{t-1}, u_t) = p(z_t \mid z_{1:t-1}; u_{1:T}), and the chain rule gives ∏t=1Tp(zt∣dt−1,ut)=p(z1:T;u1:T)\prod_{t=1}^{T} p(z_t \mid d_{t-1}, u_t) = p(z_{1:T}; u_{1:T}). So the product of the values 1/η1/\eta is the likelihood of the measurements under the given controls. If a control depends on earlier measurements, a later control carries information about those measurements, and the product is the likelihood of the measurements only in the sense of the sequential decisions that were made.

Termination and exactness. Each call does gg sums of gg terms, gg products and one division, so it ends after O(g2)O(g^2) operations. With exact rational arithmetic (the Python implementation accepts fractions) every operation is exact, and the output equals the posterior with no error.

What fails without the assumptions. If (M2) fails, for example when two measurements share a noise term, the factor p(zt∣xt,dt−1,ut)p(z_t \mid x_t, d_{t-1}, u_t) differs from p(zt∣xt)p(z_t \mid x_t), and line L3 uses the wrong likelihood. The output is then still a probability distribution but not the posterior. If (P) fails, line L4 divides by zero.

Complexity

Let gg be the number of states of a finite state space. These bounds are in the real RAM model, with one operation per arithmetic step on a real number.

  • Line L2 costs O(g)O(g) for each of the gg states, so the prediction costs O(g2)O(g^2). If from each state only bb next states have a nonzero probability, it costs O(gb)O(g b). On a grid of poses, bb is the number of cells that one step of motion can reach, so a short time step keeps the prediction cheap.
  • Lines L3 to L5 cost O(g)O(g) plus gg evaluations of the measurement model.
  • Over TT steps, the time is O(Tg2)O(T g^2) in the worst case, and the memory is O(g)O(g): the filter keeps only the current belief.

For a continuous state, the exact filter is not finite. The Kalman filter keeps a mean and a covariance and costs O(d3)O(d^3) per step for a state of dimension dd. A grid with a fixed resolution has a number of cells that grows exponentially with the dimension of the state, which is why grids are used for planar poses (3 dimensions) and rarely above.

Properties

  • Exact for a finite state space. With exact arithmetic, the output equals the posterior. The implementation below uses Python fractions for the tests.
  • Online and recursive. Each step uses only the last belief, the new control and the new measurement. The past data are not stored.
  • Multimodal. The belief can have several peaks, as in the corridor example. A Gaussian filter cannot represent this.
  • Normalization is optional until the end. The unnormalized belief bel′\mathrm{bel}' gives the same posterior after one division at any later time; normalizing at each step only keeps the numbers in range.
  • Its normalizer is the likelihood. For controls fixed in advance, the product of the evidences 1/η1/\eta over all steps is the probability of the measurements z1:Tz_{1:T} under the controls u1:Tu_{1:T}. This number can compare two models of the same data.

Variants and improvements

  • Kalman filter. Linear motion and measurement models with Gaussian noise keep the belief Gaussian, so the filter tracks only a mean μ\mu and a covariance Σ\Sigma. The extended and unscented Kalman filters approximate a nonlinear model.
  • Histogram filter. It splits a continuous state space into cells and runs this algorithm on the cells. For robot pose estimation with a map, this is grid Markov localization.
  • Particle filter. It represents the belief by samples, draws line L2 from the motion model, weights by line L3, and resamples. For localization it is Monte Carlo localization.
  • Binary Bayes filter with a static state. When the state does not change, the prediction is the identity, and the update of one binary variable is a sum of log odds. This is the cell update of occupancy grid mapping.
  • Smoothing. A backward pass after the filter gives p(xt∣z1:T,u1:T)p(x_t \mid z_{1:T}, u_{1:T}) for t<Tt < T; see smoothing.

When to use it

Use the exact algorithm when the state space is small and finite: the position of a robot in a topological map, a door that is open or closed, or a fault mode of a machine. Use it as the template for every other estimator of the area: mobile robot localization and SLAM methods are Bayes filters with a chosen representation of the belief, and the choice decides what they can represent and what they cost.

Pitfalls

  • Zero probabilities. If the measurement model gives probability zero to the true state once, that state never comes back, because line L3 multiplies by zero. A wrong reading can then make the belief wrong forever, or empty it, in which case line L4 divides by zero. Real models add a small floor, such as the random term of the beam range finder model.
  • Underflow. Many sharp measurements make the products too small for floating point numbers. Normalize at each step, or work with logarithms.
  • Measurements that are not independent. The Markov assumption says that the noise of two measurements is independent given the state. Neighboring beams of a laser scanner and repeated readings of the same object are not. The filter then counts the same evidence many times and becomes too confident. A common rule of thumb is to use only a subset of the beams, or to raise the likelihood to a power less than one; this is a heuristic, not a correction derived from the model.
  • An incomplete state. People who walk near the robot, or a map that is out of date, break the Markov assumption, because they are part of the world but not of the state. Fox, Burgard and Thrun (1999) filter out readings that such effects explain.
  • The order of the two lines. Some texts and programs correct first and predict second, so the belief at the end of a step is a prediction. Both orders are correct, but the result at time tt means a different thing.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bayes_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayes-filter/. The authors are listed in prov/V7B1QT.jsonl.

"""The Bayes filter on a finite state space (Thrun, Burgard and Fox 2005, Table 2.1).

The states are 0, 1, ..., n - 1. A belief is a list of n probabilities.
The caller gives two functions:
  motion(x, u, x_prev)   returns p(x_t = x | u_t = u, x_(t-1) = x_prev),
  measurement(z, x)      returns p(z_t = z | x_t = x).
The arithmetic is generic: with fractions.Fraction inputs the result is exact.
"""


def bayes_filter(bel, u, z, motion, measurement):
    """Return bel(x_t) from bel(x_(t-1)), the control u and the measurement z.

    If u is None the prediction is skipped (the state does not move).
    If z is None the correction is skipped (no measurement at time t).
    """
    n = len(bel)
    if u is None:
        bel_bar = list(bel)
    else:
        bel_bar = []
        for x in range(n):  # @line L1
            bel_bar.append(sum(motion(x, u, xp) * bel[xp] for xp in range(n)))  # @line L2
    if z is None:
        return bel_bar
    unnorm = [measurement(z, x) * bel_bar[x] for x in range(n)]  # @line L3
    total = sum(unnorm)
    if total == 0:
        raise ValueError("the measurement has probability zero under the predicted belief")
    eta = 1 / total  # @line L4
    new_bel = [eta * b for b in unnorm]  # @line L5
    return new_bel  # @line L6


def run_bayes_filter(bel0, controls, measurements, motion, measurement):
    """Apply bayes_filter for t = 1..T and return [bel_1, ..., bel_T]."""
    if len(controls) != len(measurements):
        raise ValueError("one control and one measurement per step")
    out, bel = [], list(bel0)
    for u, z in zip(controls, measurements):
        bel = bayes_filter(bel, u, z, motion, measurement)
        out.append(bel)
    return out
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small estimation helpers for the localization and SLAM pages.

Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).

  wrap_angle(a)                       a wrapped to [-pi, pi)
  gauss_sample(rng, mean, cov)        one draw of N(mean, cov), by a Cholesky factor
  gauss_pdf(x, mean, cov)             the density of N(mean, cov) at x
  mahalanobis2(x, mean, cov)          (x - mean)^T cov^(-1) (x - mean)
  low_variance_resample(rng, w)       indices of a systematic (low variance) resample
  logodds(p), prob_from_logodds(l)    l = log(p / (1 - p)) and its inverse
  CHI2[(dof, level)]                  chi-square quantiles for gates, dof 1 to 3

gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""

import math

import rbm

CHI2 = {
    (1, 0.95): 3.841,
    (1, 0.99): 6.635,
    (2, 0.95): 5.991,
    (2, 0.99): 9.210,
    (3, 0.95): 7.815,
    (3, 0.99): 11.345,
}

_TWO_PI = 2.0 * math.pi


def wrap_angle(a):
    """Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.

    An angle that is already in [-pi, pi) comes back unchanged, so that
    small angles keep all their digits.
    """
    if -math.pi <= a < math.pi:
        return float(a)
    w = math.fmod(a + math.pi, _TWO_PI)
    if w < 0.0:
        w += _TWO_PI
    w -= math.pi
    if w >= math.pi:  # rounding can give exactly pi
        w -= _TWO_PI
    return w


def _as_vector(x):
    if isinstance(x, (int, float)):
        return [float(x)], True
    return [float(v) for v in x], False


def _as_matrix(cov, scalar):
    if scalar:
        if isinstance(cov, (int, float)):
            return [[float(cov)]]
        return [[float(cov[0][0])]]
    return [[float(v) for v in row] for row in cov]


def gauss_sample(rng, mean, cov):
    """Draw x = mean + L z, with cov = L L^T and z standard normal.

    rng is a random.Random. cov must be symmetric positive definite.
    A number for mean (with a variance for cov) gives a number.
    """
    mu, scalar = _as_vector(mean)
    if scalar:
        var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
        if var < 0.0:
            raise ValueError("negative variance")
        return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
    L = rbm.cholesky(_as_matrix(cov, False))
    z = [rng.gauss(0.0, 1.0) for _ in mu]
    return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]


def mahalanobis2(x, mean, cov):
    """Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
    xv, scalar = _as_vector(x)
    mv, _ = _as_vector(mean)
    if len(xv) != len(mv):
        raise ValueError("x and mean differ in size")
    d = [a - b for a, b in zip(xv, mv)]
    S = _as_matrix(cov, scalar)
    if len(d) == 1:
        return d[0] * d[0] / S[0][0]
    y = rbm.solve(S, d)
    return sum(a * b for a, b in zip(d, y))


def gauss_pdf(x, mean, cov):
    """Return the density of N(mean, cov) at x."""
    xv, scalar = _as_vector(x)
    S = _as_matrix(cov, scalar)
    k = len(xv)
    det = S[0][0] if k == 1 else rbm.det(S)
    if det <= 0.0:
        raise ValueError("covariance is not positive definite")
    m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
    return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)


def low_variance_resample(rng, weights):
    """Return len(weights) indices drawn by the low variance sampler.

    This is systematic resampling (Thrun et al. 2005, Table 4.4): one
    uniform offset r in [0, 1/N), and the N points r + m / N select the
    indices through the cumulative weights. The weights need not sum to 1.
    """
    n = len(weights)
    if n == 0:
        return []
    total = float(sum(weights))
    if total <= 0.0 or any(w < 0.0 for w in weights):
        raise ValueError("weights must be nonnegative with a positive sum")
    r = rng.random() / n
    c = weights[0] / total
    i = 0
    out = []
    for m in range(n):
        u = r + m / n
        while u > c and i < n - 1:
            i += 1
            c += weights[i] / total
        out.append(i)
    return out


def logodds(p):
    """Return log(p / (1 - p)) for p in (0, 1)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return math.log(p / (1.0 - p))


def prob_from_logodds(l):
    """Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
    if l >= 0.0:
        return 1.0 / (1.0 + math.exp(-l))
    e = math.exp(l)
    return e / (1.0 + e)
test_bayes_filter.py 223 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayes-filter/. The authors are listed in prov/V7B1QT.jsonl.
# The tests of the shared helper robest.py are in this file too.

import itertools
import math
import random
from fractions import Fraction as F

import pytest

import robest
from bayes_filter import bayes_filter, run_bayes_filter

# ---------------------------------------------------------------------------
# The door example of Thrun, Burgard and Fox (2005), Section 2.4.2.
# State 0 is "open", state 1 is "closed".

SENSE = {("open", 0): F(3, 5), ("closed", 0): F(2, 5), ("open", 1): F(1, 5), ("closed", 1): F(4, 5)}


def door_motion(x, u, xp):
    if u == "nothing":
        return F(1) if x == xp else F(0)
    # u == "push": an open door stays open, a closed door opens with 0.8
    if xp == 0:
        return F(1) if x == 0 else F(0)
    return F(4, 5) if x == 0 else F(1, 5)


def door_sense(z, x):
    return SENSE[(z, x)]


def test_door_example_exact():
    bels = run_bayes_filter([F(1, 2), F(1, 2)], ["nothing", "push"], ["open", "open"], door_motion, door_sense)
    assert bels[0] == [F(3, 4), F(1, 4)]
    assert bels[1] == [F(57, 58), F(1, 58)]
    assert abs(float(bels[1][0]) - 0.98276) < 1e-5


# ---------------------------------------------------------------------------
# A cyclic corridor of 6 cells with doors at cells 0, 1 and 3.

N_CELLS = 6
DOORS = {0, 1, 3}
STEP = {0: F(1, 10), 1: F(4, 5), 2: F(1, 10)}  # move by 0, 1 or 2 cells


def corridor_motion(x, u, xp):
    """The command u = 1 asks for one cell forward; the robot moves 0, 1 or 2 cells."""
    return STEP.get((x - xp) % N_CELLS, F(0))


def corridor_sense(z, x):
    hit = F(3, 4) if x in DOORS else F(1, 5)
    return hit if z == "door" else 1 - hit


def brute_force_posterior(bel0, controls, measurements):
    """p(x_T | z_1:T, u_1:T) by summing the joint over all state paths."""
    T = len(controls)
    post = [F(0)] * N_CELLS
    for path in itertools.product(range(N_CELLS), repeat=T + 1):
        p = bel0[path[0]]
        for t in range(1, T + 1):
            u, z = controls[t - 1], measurements[t - 1]
            if u is not None:
                p *= corridor_motion(path[t], u, path[t - 1])
            elif path[t] != path[t - 1]:
                p = F(0)
            if z is not None:
                p *= corridor_sense(z, path[t])
            if p == 0:
                break
        post[path[T]] += p
    total = sum(post)
    return [v / total for v in post]


def test_corridor_motion_is_a_distribution():
    for xp in range(N_CELLS):
        assert sum(corridor_motion(x, 1, xp) for x in range(N_CELLS)) == 1


@pytest.mark.parametrize(
    "controls, measurements",
    [
        ([1, 1, 1, 1], ["door", "door", "wall", "door"]),
        ([None, 1, 1, 1], ["door", None, "wall", "door"]),
        ([1, 1, None, 1], ["wall", "wall", "door", None]),
    ],
)
def test_matches_brute_force_over_paths(controls, measurements):
    bel0 = [F(1, N_CELLS)] * N_CELLS
    bels = run_bayes_filter(bel0, controls, measurements, corridor_motion, corridor_sense)
    assert bels[-1] == brute_force_posterior(bel0, controls, measurements)
    for b in bels:
        assert sum(b) == 1 and all(v >= 0 for v in b)


def test_zero_probability_measurement_raises():
    def never(z, x):
        return F(0)

    with pytest.raises(ValueError):
        bayes_filter([F(1, 2), F(1, 2)], None, "z", door_motion, never)


def test_particle_filter_agrees_with_exact_filter():
    """A particle version with the low variance sampler of robest is close to the exact belief."""
    rng = random.Random(11)
    controls = [1, 1, 1, 1, 1]
    measurements = ["door", "door", "wall", "door", "wall"]
    exact = run_bayes_filter([F(1, N_CELLS)] * N_CELLS, controls, measurements, corridor_motion, corridor_sense)[-1]
    n = 1000
    particles = [rng.randrange(N_CELLS) for _ in range(n)]
    weights = None
    for u, z in zip(controls, measurements):
        if weights is not None:
            idx = robest.low_variance_resample(rng, weights)
            particles = [particles[i] for i in idx]
        moved = []
        for xp in particles:
            r = rng.random()
            moved.append((xp + (0 if r < 0.1 else 1 if r < 0.9 else 2)) % N_CELLS)
        particles = moved
        weights = [float(corridor_sense(z, x)) for x in particles]
    total = sum(weights)
    est = [0.0] * N_CELLS
    for x, w in zip(particles, weights):
        est[x] += w / total
    assert max(abs(a - float(b)) for a, b in zip(est, exact)) < 0.05


# ---------------------------------------------------------------------------
# The shared helper robest.py.


def test_logodds_check_values():
    assert abs(robest.logodds(0.7) - 0.84730) < 1e-5
    assert abs(robest.logodds(0.6) - 0.40547) < 1e-5
    assert robest.logodds(0.5) == 0.0
    for p in (1e-9, 0.1, 0.3, 0.5, 0.7, 0.999999):
        assert abs(robest.prob_from_logodds(robest.logodds(p)) - p) < 1e-12
    assert robest.prob_from_logodds(1000.0) == 1.0
    assert robest.prob_from_logodds(-1000.0) == 0.0
    with pytest.raises(ValueError):
        robest.logodds(1.0)


def test_wrap_angle():
    pi = math.pi
    assert robest.wrap_angle(pi) == -pi
    assert robest.wrap_angle(-pi) == -pi
    assert abs(robest.wrap_angle(3 * pi / 2) + pi / 2) < 1e-12
    assert abs(robest.wrap_angle(-7.0) - (-7.0 + 2 * pi)) < 1e-12
    assert robest.wrap_angle(-1e-17) == -1e-17
    rng = random.Random(3)
    for _ in range(1000):
        a = rng.uniform(-50.0, 50.0)
        w = robest.wrap_angle(a)
        assert -pi <= w < pi
        k = (a - w) / (2 * pi)
        assert abs(k - round(k)) < 1e-9


def test_gauss_sample_mean_and_covariance():
    rng = random.Random(5)
    mean = [1.0, -2.0]
    cov = [[2.0, 0.6], [0.6, 1.0]]
    n = 2000
    xs = [robest.gauss_sample(rng, mean, cov) for _ in range(n)]
    m = [sum(x[i] for x in xs) / n for i in range(2)]
    c = [[sum((x[i] - m[i]) * (x[j] - m[j]) for x in xs) / (n - 1) for j in range(2)] for i in range(2)]
    # standard errors are about 0.03 for the mean and 0.06 for the covariance
    assert all(abs(m[i] - mean[i]) < 0.1 for i in range(2))
    assert all(abs(c[i][j] - cov[i][j]) < 0.2 for i in range(2) for j in range(2))
    s = [robest.gauss_sample(rng, 3.0, 0.25) for _ in range(n)]
    assert abs(sum(s) / n - 3.0) < 0.05


def test_gauss_pdf_and_mahalanobis():
    cov = [[4.0, 0.0], [0.0, 1.0]]
    assert abs(robest.mahalanobis2([2.0, 1.0], [0.0, 0.0], cov) - 2.0) < 1e-12
    assert abs(robest.mahalanobis2(3.0, 1.0, 4.0) - 1.0) < 1e-12
    p = robest.gauss_pdf([2.0, 1.0], [0.0, 0.0], cov)
    assert abs(p - robest.gauss_pdf(2.0, 0.0, 4.0) * robest.gauss_pdf(1.0, 0.0, 1.0)) < 1e-15
    assert abs(robest.gauss_pdf(0.0, 0.0, 1.0) - 1 / math.sqrt(2 * math.pi)) < 1e-15
    h = 0.01
    area = sum(robest.gauss_pdf(-8.0 + h * (k + 0.5), 0.0, 2.0) * h for k in range(1600))
    assert abs(area - 1.0) < 1e-6
    full = [[2.0, 0.6], [0.6, 1.0]]
    assert abs(robest.mahalanobis2([1.0, 1.0], [0.0, 0.0], full) - (1.0 - 1.2 + 2.0) / 1.64) < 1e-12


def test_low_variance_resample():
    rng = random.Random(9)
    w = [0.1, 0.0, 0.25, 0.65]
    for _ in range(200):
        idx = robest.low_variance_resample(rng, w)
        assert len(idx) == 4 and idx == sorted(idx)
        counts = [idx.count(i) for i in range(4)]
        assert counts[1] == 0
        for i in range(4):
            assert math.floor(4 * w[i]) <= counts[i] <= math.ceil(4 * w[i])
    assert robest.low_variance_resample(rng, [5.0]) == [0]
    with pytest.raises(ValueError):
        robest.low_variance_resample(rng, [0.0, 0.0])


def _chi2_cdf(x, k):
    if k == 1:
        return math.erf(math.sqrt(x / 2))
    if k == 2:
        return 1 - math.exp(-x / 2)
    return math.erf(math.sqrt(x / 2)) - math.sqrt(2 * x / math.pi) * math.exp(-x / 2)


def test_chi2_table():
    assert len(robest.CHI2) == 6
    for (k, level), q in robest.CHI2.items():
        assert abs(_chi2_cdf(q, k) - level) < 2e-4

History

Ho and Lee (1964) wrote estimation as the update of the conditional density of the state, step by step, with Bayes' rule, and derived the Kalman filter as the case of linear models with Gaussian noise. The name "Bayes filter" and the form with a control in each step are those of the robotics literature, in particular of Thrun, Burgard and Fox (2005), who build the whole book on it. Grid versions of the filter were used for robot localization in the 1990s, for example by Fox, Burgard and Thrun (1999).

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 2, Section 2.4 (the Bayes filter algorithm of Table 2.1, the door example, the derivation and the Markov assumption)
  2. Simo Särkkä, Bayesian Filtering and Smoothing, Cambridge University Press, 2013, Chapter 4 (probabilistic state space models and the Bayesian filtering equations)
  3. Yu-Chi Ho and Robert C. K. Lee, A Bayesian approach to problems in stochastic estimation and control, IEEE Transactions on Automatic Control 9(4), 1964, pages 333 to 339, the recursive Bayesian update of the conditional density, and the Kalman filter derived from it
  4. Dieter Fox, Wolfram Burgard and Sebastian Thrun, Markov localization for mobile robots in dynamic environments, Journal of Artificial Intelligence Research 11, 1999, pages 391 to 427, the Bayes filter over a grid of robot poses for localization, and the Markov assumption in environments with people

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example