Algorithm Search⌘K

Algorithmresearch

Gaussian process motion planning

Also called GPMP, GPMP2.

Represents a trajectory by a Gaussian process prior and solves planning as inference on a sparse factor graph.

Time
O(I N ((k + 1) m d + d^3)) worst
Space
O(N d^2) extra
Where
I = the number of iterations; N = the number of support states; d = the dimension of the configuration space; k = the number of interpolated check points per interval; m = the number of obstacles
Properties
deterministicnot exactofflinenot randomized

Gaussian process motion planning treats a trajectory as a continuous function of time with a Gaussian process prior, and turns planning into finding the most probable trajectory given that it should avoid obstacles. The prior used in GPMP2 is the constant-velocity process: white noise on the acceleration. Its states are positions and velocities, and its density is a product of factors that each connect two consecutive support states, so the problem is a sparse factor graph. Obstacle costs are further factors, and they can be checked between support states at no extra variables, because the Gaussian process gives the trajectory between support states as a fixed linear function of the two neighbors. The most probable trajectory is a nonlinear least squares problem with a block tridiagonal Hessian, solved by Gauss-Newton or Levenberg-Marquardt steps. Like the other methods for trajectory optimization, it is local.

In plain words

Describe a motion by a few snapshots of position and speed, and assume the motion between snapshots is as smooth as possible, which gives a fixed curve between each pair. Smoothness has a price, and so has coming close to an obstacle. Planning means finding the snapshots with the lowest total price. Because each price depends on at most two neighboring snapshots, the system to solve at each step is a short chain, and it can be solved quickly. Obstacles can also be checked on the curve between snapshots, so few snapshots are enough. Closeness to obstacles is only a price, not a hard rule, so the result can stay a little inside the safety distance. The method improves the motion near the start and does not search for the best one.

The problem

Input: a start state θ0\theta_0 and a goal state θN\theta_N (position and velocity), a total time TT, NN intervals of length Δt=T/N\Delta t = T/N, signed distance functions sdj\mathrm{sd}_j of the obstacles, a safety distance ε\varepsilon, an obstacle weight σ\sigma, and the spectral density QcQ_c of the prior. The unknowns are the support states θ1,…,θN−1\theta_1, \dots, \theta_{N-1} with θi=(pi,vi)\theta_i = (p_i, v_i). Minimize

F=12∑i=0N−1eiTQ−1ei+12σ2∑check points p∑jmax⁡(0, ε−sdj(p))2,F = \frac12 \sum_{i=0}^{N-1} e_i^{\mathsf T} Q^{-1} e_i + \frac{1}{2\sigma^2} \sum_{\text{check points } p} \sum_j \max\bigl(0,\ \varepsilon - \mathrm{sd}_j(p)\bigr)^2,

with the prior error ei=θi+1−Φθie_i = \theta_{i+1} - \Phi\theta_i, where

Φ=(IΔt I0I),Q=Qc(Δt33IΔt22IΔt22IΔt I).\Phi = \begin{pmatrix} I & \Delta t\, I \\ 0 & I \end{pmatrix}, \qquad Q = Q_c \begin{pmatrix} \tfrac{\Delta t^3}{3} I & \tfrac{\Delta t^2}{2} I \\ \tfrac{\Delta t^2}{2} I & \Delta t\, I \end{pmatrix}.

The check points are the support positions and kk points in each interval, at the positions given by the interpolation below. FF is minus the logarithm of the posterior density, up to a constant, so its minimizer is the most probable trajectory. This page uses a point robot in the plane; the paper also handles robot arms, where the check points are spheres on the links.

The algorithm

  1. GPMP(θ_0, θ_N, N, λ, I)
  2. 1θ_1, …, θ_{N-1} ← states on the segment, at constant velocity
  3. 2for it ← 1 to I do
  4. 3linearize all factors at θ; H ← Σ JᵀWJ; g ← Σ JᵀWr ▷ block tridiagonal
  5. 4solve (H + λI) δ = -g
  6. 5F′ ← F(θ + δ)
  7. 6if F′ < F(θ) then θ ← θ + δ; λ ← λ/10
  8. 7else λ ← 10λ and go back to L4
  9. 8if the decrease is small then stop
  10. 9return θ

Line L3 linearizes each factor. For a prior factor the error is linear in the two states it connects, with Jacobians −Φ-\Phi and II. For an obstacle factor at a check point pp, the residual is max⁡(0,ε−sd(p))/σ\max(0, \varepsilon - \mathrm{sd}(p))/\sigma with the Jacobian −∇sd(p)T/σ-\nabla\mathrm{sd}(p)^{\mathsf T}/\sigma times the derivative of pp with respect to the states, and zero where the point is farther than ε\varepsilon.

A check point at time ti+τt_i + \tau between two support states has the state

θ(ti+τ)=Λθi+Ψθi+1,Ψ=QτΦΔt−τTQΔt−1,Λ=Φτ−ΨΦΔt,\theta(t_i + \tau) = \Lambda\theta_i + \Psi\theta_{i+1}, \qquad \Psi = Q_\tau \Phi_{\Delta t - \tau}^{\mathsf T} Q_{\Delta t}^{-1}, \quad \Lambda = \Phi_\tau - \Psi\Phi_{\Delta t},

the mean of the process given the two support states. For the constant-velocity prior this is the cubic Hermite curve through the two states (proof, Theorem 1). The matrices depend only on τ\tau and Δt\Delta t, so they are computed once. Each check point involves only two neighboring support states, so the Hessian keeps its block tridiagonal form.

Lines L4 to L7 are a Levenberg-Marquardt step: a damped Gauss-Newton step, accepted only when the cost goes down. The system of line L4 has 4×44 \times 4 blocks on the diagonal and next to it, and the code solves it by block elimination in O(N)O(N) block operations. The paper solves the same sparse system with a factor graph library.

Example

A point moves from rest at (−1,0)(-1, 0) to rest at (1,0)(1, 0) in time T=1T = 1 with N=5N = 5 intervals, so there are four free support states. One disc of radius 0.50.5 has its center at (0,−0.15)(0, -0.15). The parameters are Qc=1Q_c = 1, ε=0.1\varepsilon = 0.1, σ=0.02\sigma = 0.02, and k=4k = 4 check points in each interval. The start is the straight line at constant velocity.

iteration FF prior part obstacle part clearance at check points clearance at support states
0 1660.597 80.000 1580.597 −0.345-0.345 −0.250-0.250
1 64.679 64.679 0.000 0.129 0.140
2 60.293 44.537 15.755 0.047 0.065
3 44.957 43.837 1.120 0.083 0.099
4 43.016 42.077 0.940 0.082 0.111
5 42.786 42.256 0.530 0.086 0.119
7 42.786 42.255 0.531 0.086 0.119

The method stops after seven iterations. The first step jumps clear of the disc, and the later steps trade smoothness against clearance. The final clearance, 0.0860.086 at the check points and 0.0840.084 on a fine sampling of the whole curve, is below ε\varepsilon: the obstacle term is a soft cost. Without obstacles, the optimum is the cubic p(t)=A+(B−A)(3t2−2t3)p(t) = A + (B - A)(3t^2 - 2t^3) with prior cost exactly 2424 (proof, Theorem 2); the obstacle raises it to 42.342.3.

The check points between support states matter. With k=0k = 0, only the four support states are checked. The result then has F=38.831F = 38.831 and a clearance of 0.0810.081 at the support states, but the curve between them comes as close as 0.0210.021 to the disc, because the middle of the trajectory falls between two support states.

Correctness

The proof shows three facts. First, the prior factor 12eTQ−1e\frac12 e^{\mathsf T} Q^{-1} e equals the smallest value of 12Qc∫∥p′′∥2\frac{1}{2Q_c}\int \|p''\|^2 over all paths that connect the two states in time Δt\Delta t, and the cubic Hermite curve attains it. This explains the prior: it charges acceleration energy. Second, the interpolation formula gives exactly the state of that cubic, so the check points lie on the curve that the prior describes; without obstacles the result is the cubic of least acceleration energy. Third, every accepted step of line L6 lowers FF, and as long as the gradient is not zero, line L7 increases λ\lambda only finitely often before a step is accepted. Nothing guarantees a global minimum or a collision-free result. The obstacle term is a penalty, and the method is local.

Proof: The prior factor is the minimum acceleration energy, the interpolation is the cubic Hermite curve, and every Levenberg-Marquardt step that is accepted lowers the costfull

We use the notation of the page and of the code. Each support state is θ=(p,v)∈R2×R2\theta = (p, v) \in \mathbb R^2 \times \mathbb R^2. For an interval of length ss,

Φs=(IsI0I),Qs=Qc(s33Is22Is22IsI).\Phi_s = \begin{pmatrix} I & sI \\ 0 & I \end{pmatrix}, \qquad Q_s = Q_c \begin{pmatrix} \tfrac{s^3}{3} I & \tfrac{s^2}{2} I \\ \tfrac{s^2}{2} I & s I \end{pmatrix}.

For a path pp on an interval [a,b][a, b] with square integrable second derivative, its energy is E(p)=12Qc∫ab∥p′′(t)∥2 dtE(p) = \frac{1}{2Q_c}\int_a^b \|p''(t)\|^2\,dt. For two states θ,θ′\theta, \theta' and a length ss, let Es(θ,θ′)E_s(\theta, \theta') be the smallest energy of a path of duration ss that starts in state θ\theta and ends in state θ′\theta' (position and velocity).

Lemma 1: the prior factor is the minimum energy

Claim. Es(θ,θ′)=12eTQs−1eE_s(\theta, \theta') = \frac12 e^{\mathsf T} Q_s^{-1} e with e=θ′−Φsθe = \theta' - \Phi_s \theta, and the unique path that attains it is the cubic Hermite curve with the given end positions and velocities.

Proof. The coordinates separate, so take one coordinate, with states (p0,v0)(p_0, v_0) and (p1,v1)(p_1, v_1) on [0,s][0, s], and write u=p′′u = p''. By Taylor's formula with integral remainder, the end conditions are

∫0s(s−t) u(t) dt=p1−p0−v0s=ep,∫0su(t) dt=v1−v0=ev.\int_0^s (s - t)\,u(t)\,dt = p_1 - p_0 - v_0 s = e_p, \qquad \int_0^s u(t)\,dt = v_1 - v_0 = e_v.

Put k1(t)=s−tk_1(t) = s - t and k2(t)=1k_2(t) = 1. Their Gram matrix in L2(0,s)L^2(0, s) is G=(s3/3s2/2s2/2s)G = \begin{pmatrix} s^3/3 & s^2/2 \\ s^2/2 & s \end{pmatrix}, which is positive definite (its determinant is s4/12s^4/12). Let λ=G−1(ep,ev)T\lambda = G^{-1}(e_p, e_v)^{\mathsf T} and u∗=λ1k1+λ2k2u^* = \lambda_1 k_1 + \lambda_2 k_2; then u∗u^* meets both conditions. For every uu that meets them, u−u∗u - u^* is orthogonal to k1k_1 and k2k_2, so it is orthogonal to u∗u^*, and

∫0su2=∫0s(u∗)2+∫0s(u−u∗)2≥∫0s(u∗)2=λTGλ=(ep,ev) G−1(ep,ev)T,\int_0^s u^2 = \int_0^s (u^*)^2 + \int_0^s (u - u^*)^2 \ge \int_0^s (u^*)^2 = \lambda^{\mathsf T} G \lambda = (e_p, e_v)\, G^{-1} (e_p, e_v)^{\mathsf T},

with equality only for u=u∗u = u^*. Since u∗u^* is affine, the minimizing path is a cubic with the four given end values; the cubic Hermite curve is the only such cubic. Dividing by 2Qc2Q_c and adding the two coordinates gives 12eTQs−1e\frac12 e^{\mathsf T} Q_s^{-1} e. □\square

Lemma 2: splitting an interval

Claim. For 0<τ<s0 < \tau < s and states θ0,z,θ1\theta_0, z, \theta_1,

Eτ(θ0,z)+Es−τ(z,θ1)≥Es(θ0,θ1),E_\tau(\theta_0, z) + E_{s - \tau}(z, \theta_1) \ge E_s(\theta_0, \theta_1),

with equality if and only if zz is the state at time τ\tau of the cubic Hermite curve HH from θ0\theta_0 to θ1\theta_1.

Proof. Join the minimizing curve from θ0\theta_0 to zz with the minimizing curve from zz to θ1\theta_1. Position and velocity agree at τ\tau, so the joined path has a square integrable second derivative, starts in θ0\theta_0 and ends in θ1\theta_1; its energy is the left side, which is therefore at least Es(θ0,θ1)E_s(\theta_0, \theta_1). If z=H(τ)z = H(\tau), the two pieces of HH are admissible for the two short intervals, so the left side is at most E(H)=Es(θ0,θ1)E(H) = E_s(\theta_0, \theta_1), and equality holds. If equality holds, the joined path attains the minimum on [0,s][0, s], so by the uniqueness in Lemma 1 it is HH, and z=H(τ)z = H(\tau). □\square

Theorem 1: the interpolation of the code is the cubic Hermite curve

The code uses Ψ=QτΦs−τTQs−1\Psi = Q_\tau \Phi_{s-\tau}^{\mathsf T} Q_s^{-1} and Λ=Φτ−ΨΦs\Lambda = \Phi_\tau - \Psi \Phi_s and sets z∗=Λθ0+Ψθ1z^* = \Lambda\theta_0 + \Psi\theta_1.

Claim. z∗=H(τ)z^* = H(\tau), so the obstacle factors between support states are evaluated on the cubic Hermite curve through the support states.

Proof. By Lemma 1, the left side of Lemma 2 is the quadratic function

J(z)=12(z−Φτθ0)TQτ−1(z−Φτθ0)+12(θ1−Bz)TQs−τ−1(θ1−Bz),B=Φs−τ,J(z) = \tfrac12 (z - \Phi_\tau\theta_0)^{\mathsf T} Q_\tau^{-1} (z - \Phi_\tau\theta_0) + \tfrac12 (\theta_1 - B z)^{\mathsf T} Q_{s-\tau}^{-1} (\theta_1 - B z), \qquad B = \Phi_{s-\tau},

and by Lemma 2 its unique minimizer is H(τ)H(\tau). JJ is strictly convex, so it is enough to check that z∗z^* satisfies ∇J(z∗)=0\nabla J(z^*) = 0, that is, Qτ−1(z∗−Φτθ0)=BTQs−τ−1(θ1−Bz∗)Q_\tau^{-1}(z^* - \Phi_\tau\theta_0) = B^{\mathsf T} Q_{s-\tau}^{-1}(\theta_1 - B z^*).

Two identities are needed. First, BΦτ=ΦsB\Phi_\tau = \Phi_s. Second, BQτBT+Qs−τ=QsB Q_\tau B^{\mathsf T} + Q_{s-\tau} = Q_s: per coordinate, with a=τa = \tau and b=s−τb = s - \tau, the entries of BQτBTB Q_\tau B^{\mathsf T} are a3/3+a2b+ab2a^3/3 + a^2 b + a b^2, a2/2+aba^2/2 + ab and aa (times QcQ_c), and adding b3/3b^3/3, b2/2b^2/2 and bb gives (a+b)3/3(a+b)^3/3, (a+b)2/2(a+b)^2/2 and a+ba + b.

Put r=θ1−Φsθ0r = \theta_1 - \Phi_s\theta_0. Then z∗−Φτθ0=Ψr=QτBTQs−1rz^* - \Phi_\tau\theta_0 = \Psi r = Q_\tau B^{\mathsf T} Q_s^{-1} r, so the left side is BTQs−1rB^{\mathsf T} Q_s^{-1} r. For the right side, θ1−Bz∗=θ1−Φsθ0−BQτBTQs−1r=r−(Qs−Qs−τ)Qs−1r=Qs−τQs−1r\theta_1 - B z^* = \theta_1 - \Phi_s\theta_0 - B Q_\tau B^{\mathsf T} Q_s^{-1} r = r - (Q_s - Q_{s-\tau}) Q_s^{-1} r = Q_{s-\tau} Q_s^{-1} r, so the right side is BTQs−1rB^{\mathsf T} Q_s^{-1} r as well. □\square

In the language of Gaussian processes, JJ is minus the logarithm of the density of the state at τ\tau given the two support states, up to a constant, so z∗z^* is the conditional mean.

Theorem 2: without obstacles, the result is the minimum energy cubic

Claim. With no obstacle factors, the prior cost ∑i12eiTQ−1ei\sum_i \frac12 e_i^{\mathsf T} Q^{-1} e_i over the free support states θ1,…,θN−1\theta_1, \dots, \theta_{N-1} has the unique minimizer θi=P(ti)\theta_i = P(t_i), the states of the cubic PP of least energy from θ0\theta_0 to θN\theta_N, and the minimum is E(P)E(P). For θ0=(A,0)\theta_0 = (A, 0), θN=(B,0)\theta_N = (B, 0) and total time TT, P(t)=A+(B−A)(3(t/T)2−2(t/T)3)P(t) = A + (B - A)\bigl(3(t/T)^2 - 2(t/T)^3\bigr), and E(P)=6∥B−A∥2/(QcT3)E(P) = 6\|B - A\|^2/(Q_c T^3).

Proof. By Lemma 1 the prior cost is ∑iEΔt(θi,θi+1)\sum_i E_{\Delta t}(\theta_i, \theta_{i+1}). Joining the minimizing pieces gives an admissible path on [0,T][0, T], so the sum is at least ET(θ0,θN)E_T(\theta_0, \theta_N); for θi=P(ti)\theta_i = P(t_i) the pieces of PP show equality, and if equality holds the joined path is a minimizer, hence PP, by uniqueness. For the given ends, the Hermite cubic is the stated PP; P′′(t)=(B−A)(6−12t/T)/T2P''(t) = (B - A)(6 - 12t/T)/T^2 and ∫0T(6−12t/T)2 dt/T4=12/T3\int_0^T (6 - 12 t/T)^2\,dt/T^4 = 12/T^3, so E(P)=6∥B−A∥2/(QcT3)E(P) = 6\|B - A\|^2/(Q_c T^3). □\square

For the example on the page (A=(−1,0)A = (-1, 0), B=(1,0)B = (1, 0), T=1T = 1, Qc=1Q_c = 1) this is 2424.

Theorem 3: the Levenberg-Marquardt loop

Write F(x)=12∑frf(x)TWfrf(x)F(x) = \frac12 \sum_f r_f(x)^{\mathsf T} W_f r_f(x) for the total cost, with residuals rfr_f and weights WfW_f (the matrices Q−1Q^{-1} for the prior and 1/σ21/\sigma^2 for each obstacle term). Each obstacle term is 12σ2max⁡(0,ε−d)2\frac{1}{2\sigma^2}\max(0, \varepsilon - d)^2, which is continuously differentiable wherever dd is, because the square of a hinge has a continuous derivative; for a disc this holds everywhere except at its center. Line L3 forms H=∑fJfTWfJfH = \sum_f J_f^{\mathsf T} W_f J_f and g=∑fJfTWfrf=∇F(x)g = \sum_f J_f^{\mathsf T} W_f r_f = \nabla F(x).

Claim. Every step accepted by line L6 lowers FF. If FF is continuously differentiable near xx and g≠0g \ne 0, then after finitely many increases of λ\lambda in line L7 a step is accepted.

Proof. The first part is the test of line L6. For the second, HH is positive semidefinite, so H+λIH + \lambda I is positive definite for λ>0\lambda > 0, and the step δ=−(H+λI)−1g\delta = -(H + \lambda I)^{-1} g of line L4 satisfies ∥δ∥≤∥g∥/λ\|\delta\| \le \|g\|/\lambda and −gTδ≥∥g∥2/(∥H∥+λ)-g^{\mathsf T}\delta \ge \|g\|^2/(\|H\| + \lambda). Differentiability gives F(x+δ)=F(x)+gTδ+o(∥δ∥)F(x + \delta) = F(x) + g^{\mathsf T}\delta + o(\|\delta\|). So

F(x+δ)−F(x)≤−∥g∥2∥H∥+λ+o ⁣(∥g∥λ),F(x + \delta) - F(x) \le -\frac{\|g\|^2}{\|H\| + \lambda} + o\!\left(\frac{\|g\|}{\lambda}\right),

and the first term dominates as λ→∞\lambda \to \infty, because λ∥g∥2/(∥H∥+λ)→∥g∥2>0\lambda\|g\|^2/(\|H\| + \lambda) \to \|g\|^2 > 0. Line L7 multiplies λ\lambda by 10 at each rejection, so the right side becomes negative after finitely many rejections. ■\blacksquare

Structure of the system

A prior factor involves the support states ii and i+1i + 1, an obstacle factor at a support state involves one state, and an obstacle factor between support states ii and i+1i + 1 involves exactly those two (Theorem 1). So HH has nonzero 4×44 \times 4 blocks only on the diagonal and next to it, and line L4 solves the system by block elimination in O(N)O(N) block operations.

What is not proved

The cost values decrease, but nothing says that the limit is a global minimum or free of collision. The obstacle term is a soft cost: the result can stay inside the safety distance, as in the example, where the clearance ends below ε\varepsilon. The method is local, and a start on the other side of an obstacle leads to another answer.

Complexity

Line L3 evaluates the signed distance at N(k+1)N(k+1) check points for mm obstacles and adds small blocks, O(N(k+1)md)O(N(k+1)md) for a configuration space of dimension dd. Line L4 eliminates a block tridiagonal system with blocks of size 2d2d, O(Nd3)O(Nd^3). So one iteration costs O(N((k+1)md+d3))O(N((k+1)md + d^3)), and the memory is O(Nd2)O(Nd^2). Rejected steps repeat lines L4 and L5 only. The number of iterations has no useful bound; the seven of the example are a measurement.

Properties

  • Continuous time. The trajectory is defined at every time by the interpolation, and collisions can be checked at any time without new variables.
  • Sparse. Each factor touches at most two neighboring support states, so each iteration is linear in NN.
  • Few support states. With check points between them, a few support states describe a smooth motion.
  • Soft obstacles. The safety distance is a cost, so the result can stay inside it; a smaller σ\sigma pushes harder.
  • Local and deterministic. The same start gives the same result, which is a local minimum at best.

Variants and improvements

  • Incremental replanning. Keep the factor graph and update it with an incremental solver such as iSAM2 when the goal or the obstacles change, instead of solving from scratch. The paper uses this for replanning.
  • Other priors. Use a prior with more states, such as constant acceleration, for smoother motions; the blocks grow but stay tridiagonal.
  • Constraints as factors. Joint limits, velocity limits and goal regions become further factors with their own weights.
  • Smoothing view. With a linear prior and linear measurements, the same chain structure is solved by a Kalman smoother such as the Rauch-Tung-Striebel smoother; here the obstacle factors are nonlinear, hence the iterations.
  • Related methods. CHOMP uses a fixed finite-difference metric in place of the Gaussian process prior. TrajOpt treats collision as a hard constraint.

When to use it

Use it when the motion should be smooth in continuous time, collisions must be checked between waypoints, and planning must be fast or repeated, as in replanning when the scene changes. The factor graph form also makes it easy to add estimation and planning factors in one problem. For maze-like scenes use a sampling planner first. When a hard safety margin is required, check the result, or use a method with constraints.

Pitfalls

  • No check points between support states. If line L3 checks only the support states, the curve can cut through an obstacle between them, as in the example with k=0k = 0.
  • The safety distance is soft. Line L3 charges closeness, but the result can stay inside ε\varepsilon. Use a larger ε\varepsilon than the true margin, or a smaller σ\sigma, and check the result.
  • Weights. The balance of QcQ_c and σ\sigma decides how hard the obstacles push. A very small σ\sigma makes the system of line L4 badly scaled and the steps of line L6 small.
  • Gradients of the distance. At the center of a disc, or with a coarse distance field, the gradient in line L3 is zero or wrong, and the method can stall inside an obstacle.
  • Local minima. The start of line L1 decides on which side of an obstacle the result passes.

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.

gaussian_process_motion_planning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gaussian-process-motion-planning/. The authors are listed in prov/6FK8HV.jsonl.
"""GPMP2-style motion planning: a Gaussian process prior and obstacle factors.

A point robot in the plane has the state theta = (px, py, vx, vy). The
trajectory is represented by N + 1 support states at times t_i = i * dt.
The prior is the constant-velocity Gaussian process (white noise on the
acceleration, power spectral density Qc), whose factor between consecutive
support states has the error and covariance

    e_i = theta_(i+1) - Phi theta_i,   Phi = [[I, dt I], [0, I]],
    Q   = Qc [[dt^3/3 I, dt^2/2 I], [dt^2/2 I, dt I]].

Obstacle factors, one per obstacle, charge the hinge c(d) = max(0, eps - d)
of the signed distance d at each support state and at n_ip points between support states.
The position at an intermediate time tau is the Gaussian process
interpolation p(tau) = Lambda theta_i + Psi theta_(i+1) (position rows).

The cost is F = 1/2 sum e_i^T Q^-1 e_i + 1/2 sum c(d)^2 / sigma^2. It is a
nonlinear least squares problem whose Hessian is block tridiagonal with
4 x 4 blocks, minimized by Levenberg-Marquardt. Standard library only.
"""

import math


# ---------- small dense helpers ----------

def mat_mul(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def mat_vec(a, v):
    return [sum(a[i][k] * v[k] for k in range(len(v))) for i in range(len(a))]


def transpose(a):
    return [list(r) for r in zip(*a)]


def solve_dense(a, b):
    """Gaussian elimination with partial pivoting; b is a matrix (list of rows)."""
    n = len(a)
    m = [list(a[i]) + list(b[i]) for i in range(n)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for j in range(c, w):
            m[c][j] /= piv
        for r in range(n):
            if r != c and m[r][c] != 0.0:
                f = m[r][c]
                for j in range(c, w):
                    m[r][j] -= f * m[c][j]
    return [row[n:] for row in m]


def eye(n, s=1.0):
    return [[s if i == j else 0.0 for j in range(n)] for i in range(n)]


# ---------- the constant-velocity prior ----------

def phi(dt):
    return [[1.0, 0.0, dt, 0.0], [0.0, 1.0, 0.0, dt], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]


def q_cov(dt, qc):
    a, b, c = qc * dt ** 3 / 3.0, qc * dt ** 2 / 2.0, qc * dt
    return [[a, 0.0, b, 0.0], [0.0, a, 0.0, b], [b, 0.0, c, 0.0], [0.0, b, 0.0, c]]


def q_inv(dt, qc):
    a, b, c = 12.0 / dt ** 3, -6.0 / dt ** 2, 4.0 / dt
    return [[v / qc for v in row] for row in [[a, 0.0, b, 0.0], [0.0, a, 0.0, b], [b, 0.0, c, 0.0], [0.0, b, 0.0, c]]]


def interpolation(dt, tau, qc):
    """Lambda and Psi with theta(tau) = Lambda theta_i + Psi theta_(i+1)."""
    psi = mat_mul(mat_mul(q_cov(tau, qc), transpose(phi(dt - tau))), q_inv(dt, qc))
    lam = [[phi(tau)[i][j] - mat_mul(psi, phi(dt))[i][j] for j in range(4)] for i in range(4)]
    return lam, psi


# ---------- obstacles ----------

def disc_sd(ox, oy, r):
    def sd(p):
        dx, dy = p[0] - ox, p[1] - oy
        rho = math.hypot(dx, dy)
        if rho == 0.0:
            return -r, (0.0, 0.0)
        return rho - r, (dx / rho, dy / rho)
    return sd


def hinge(sd, p, eps):
    """The hinge c(d) = max(0, eps - d) of one signed distance, and its gradient in p."""
    d, g = sd(p)
    if d < eps:
        return eps - d, [-g[0], -g[1]]
    return 0.0, [0.0, 0.0]


# ---------- cost, linearization, and the solver ----------

class Problem:
    def __init__(self, q0, q1, total_time, n_int, sds, eps=0.1, sigma=0.05, qc=1.0, n_ip=0):
        self.dt = total_time / n_int
        self.n = n_int
        self.sds, self.eps, self.sigma, self.qc = sds, eps, sigma, qc
        self.start = [q0[0], q0[1], 0.0, 0.0]
        self.goal = [q1[0], q1[1], 0.0, 0.0]
        self.phi, self.qinv = phi(self.dt), q_inv(self.dt, qc)
        self.interp = [interpolation(self.dt, self.dt * j / (n_ip + 1), qc) for j in range(1, n_ip + 1)]

    def states(self, x):
        return [self.start] + x + [self.goal]

    def prior_cost(self, x):
        s = self.states(x)
        tot = 0.0
        for i in range(self.n):
            e = [s[i + 1][k] - v for k, v in enumerate(mat_vec(self.phi, s[i]))]
            tot += 0.5 * sum(e[a] * self.qinv[a][b] * e[b] for a in range(4) for b in range(4))
        return tot

    def obstacle_points(self, x):
        """(position, list of (state index, 2 x 4 matrix)) for every obstacle factor."""
        s = self.states(x)
        out = []
        for i in range(1, self.n):
            out.append((s[i][:2], [(i, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])]))
        for i in range(self.n):
            for lam, psi in self.interp:
                p = [sum(lam[r][k] * s[i][k] + psi[r][k] * s[i + 1][k] for k in range(4)) for r in range(2)]
                out.append((p, [(i, lam[:2]), (i + 1, psi[:2])]))
        return out

    def obstacle_cost(self, x):
        return sum(0.5 * (hinge(sd, p, self.eps)[0] / self.sigma) ** 2 for p, _ in self.obstacle_points(x) for sd in self.sds)

    def cost(self, x):
        return self.prior_cost(x) + self.obstacle_cost(x)

    def normal_equations(self, x):
        """Gauss-Newton blocks: diag[i], off[i] (block (i, i+1)), and gradient g[i], for i = 1..N-1."""
        m = self.n - 1
        diag = [[[0.0] * 4 for _ in range(4)] for _ in range(m)]
        off = [[[0.0] * 4 for _ in range(4)] for _ in range(max(m - 1, 0))]
        g = [[0.0] * 4 for _ in range(m)]
        s = self.states(x)

        def add_factor(jacs, r, w):
            # jacs: list of (state index, k x 4 Jacobian); r: k residual; w: k x k weight
            live = [(i - 1, j) for i, j in jacs if 1 <= i <= self.n - 1]
            for a, ja in live:
                wja = mat_mul(w, ja)
                jtw = transpose(wja)
                gr = mat_vec(jtw, r)
                for k in range(4):
                    g[a][k] += gr[k]
                for b, jb in live:
                    blk = mat_mul(jtw, jb)
                    if a == b:
                        tgt = diag[a]
                    elif b == a + 1:
                        tgt = off[a]
                    else:
                        continue
                    for p in range(4):
                        for q in range(4):
                            tgt[p][q] += blk[p][q]

        minus_phi = [[-v for v in row] for row in self.phi]
        for i in range(self.n):
            e = [s[i + 1][k] - v for k, v in enumerate(mat_vec(self.phi, s[i]))]
            add_factor([(i, minus_phi), (i + 1, eye(4))], e, self.qinv)
        w = [[1.0 / self.sigma ** 2]]
        for p, parts in self.obstacle_points(x):
            for sd in self.sds:
                val, grad = hinge(sd, p, self.eps)
                if val <= 0.0:
                    continue
                jacs = [(i, [[grad[0] * a[0][k] + grad[1] * a[1][k] for k in range(4)]]) for i, a in parts]
                add_factor(jacs, [val], w)
        return diag, off, g


def block_tridiag_solve(diag, off, rhs):
    """Solve the symmetric block tridiagonal system (4 x 4 blocks) by block elimination."""
    m = len(diag)
    d = [None] * m
    r = [None] * m
    d[0], r[0] = [row[:] for row in diag[0]], rhs[0][:]
    for i in range(1, m):
        # eliminate block (i, i-1) = off[i-1]^T using row i-1
        lower = transpose(off[i - 1])
        sol = solve_dense(d[i - 1], [list(off[i - 1][k]) + [r[i - 1][k]] for k in range(4)])
        x_off = [row[:4] for row in sol]  # d[i-1]^-1 off[i-1]
        x_r = [row[4] for row in sol]  # d[i-1]^-1 r[i-1]
        prod = mat_mul(lower, x_off)
        d[i] = [[diag[i][p][q] - prod[p][q] for q in range(4)] for p in range(4)]
        lr = mat_vec(lower, x_r)
        r[i] = [rhs[i][p] - lr[p] for p in range(4)]
    out = [None] * m
    out[m - 1] = [row[0] for row in solve_dense(d[m - 1], [[v] for v in r[m - 1]])]
    for i in range(m - 2, -1, -1):
        upd = mat_vec(off[i], out[i + 1])
        out[i] = [row[0] for row in solve_dense(d[i], [[r[i][p] - upd[p]] for p in range(4)])]
    return out


def straight_init(prob):
    """Support states on the segment at constant velocity (the usual start)."""
    a, b = prob.start, prob.goal
    t_total = prob.dt * prob.n
    v = [(b[0] - a[0]) / t_total, (b[1] - a[1]) / t_total]
    return [[a[0] + (b[0] - a[0]) * i / prob.n, a[1] + (b[1] - a[1]) * i / prob.n, v[0], v[1]] for i in range(1, prob.n)]


def gpmp(prob, x0=None, lam=1e-2, iters=100, tol=1e-9):
    """Levenberg-Marquardt on the factor graph. Returns (x, history of the cost)."""
    x = straight_init(prob) if x0 is None else [list(s) for s in x0]  # @line L1
    f = prob.cost(x)
    hist = [f]
    for _ in range(iters):  # @line L2
        diag, off, g = prob.normal_equations(x)  # @line L3
        while True:
            dmp = [[[diag[i][p][q] + (lam if p == q else 0.0) for q in range(4)] for p in range(4)] for i in range(len(diag))]
            step = block_tridiag_solve(dmp, off, [[-v for v in gi] for gi in g])  # @line L4
            trial = [[x[i][k] + step[i][k] for k in range(4)] for i in range(len(x))]
            ft = prob.cost(trial)  # @line L5
            if ft < f:  # @line L6
                lam = max(lam / 10.0, 1e-12)
                break
            lam *= 10.0  # @line L7
            if lam > 1e12:
                return x, hist
        done = f - ft <= tol * max(1.0, f)
        x, f = trial, ft
        hist.append(f)
        if done:  # @line L8
            break
    return x, hist  # @line L9


def min_clearance(prob, x):
    return min(sd(p)[0] for p, _ in prob.obstacle_points(x) for sd in prob.sds)


def support_clearance(prob, x):
    return min(sd(s[:2])[0] for s in x for sd in prob.sds)
test_gaussian_process_motion_planning.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gaussian-process-motion-planning/. The authors are listed in prov/6FK8HV.jsonl.
import random
import unittest

from gaussian_process_motion_planning import (
    Problem,
    block_tridiag_solve,
    disc_sd,
    gpmp,
    interpolation,
    min_clearance,
    phi,
    q_inv,
    solve_dense,
    straight_init,
    support_clearance,
)

Q0, Q1 = [-1.0, 0.0], [1.0, 0.0]
DISC = disc_sd(0.0, -0.15, 0.5)


def hermite(s0, s1, dt, tau):
    """Position and velocity of the cubic Hermite interpolant, one coordinate per call."""
    out = []
    for c in range(2):
        p0, v0, p1, v1 = s0[c], s0[c + 2], s1[c], s1[c + 2]
        u = tau / dt
        h00, h10, h01, h11 = 2 * u ** 3 - 3 * u ** 2 + 1, u ** 3 - 2 * u ** 2 + u, -2 * u ** 3 + 3 * u ** 2, u ** 3 - u ** 2
        d00, d10, d01, d11 = 6 * u ** 2 - 6 * u, 3 * u ** 2 - 4 * u + 1, -6 * u ** 2 + 6 * u, 3 * u ** 2 - 2 * u
        out.append((h00 * p0 + h10 * dt * v0 + h01 * p1 + h11 * dt * v1,
                    (d00 * p0 + d10 * dt * v0 + d01 * p1 + d11 * dt * v1) / dt))
    return out


def dense_clearance(prob, x, per=40):
    s = prob.states(x)
    best = float("inf")
    for i in range(prob.n):
        for j in range(per + 1):
            lam, psi = interpolation(prob.dt, prob.dt * j / per, prob.qc)
            p = [sum(lam[r][k] * s[i][k] + psi[r][k] * s[i + 1][k] for k in range(4)) for r in range(2)]
            best = min(best, DISC(p)[0])
    return best


class TestWorkedExample(unittest.TestCase):
    def test_disc_with_interpolation(self):
        prob = Problem(Q0, Q1, 1.0, 5, [DISC], eps=0.1, sigma=0.02, n_ip=4)
        x, hist = gpmp(prob)
        self.assertAlmostEqual(hist[0], 1660.597, places=2)
        self.assertAlmostEqual(hist[-1], 42.7862, places=3)
        self.assertEqual(len(hist) - 1, 7)
        self.assertTrue(all(b < a for a, b in zip(hist, hist[1:])))
        self.assertAlmostEqual(min_clearance(prob, x), 0.0857, places=3)
        self.assertGreater(dense_clearance(prob, x), 0.08)

    def test_without_interpolation_the_curve_cuts_closer(self):
        prob = Problem(Q0, Q1, 1.0, 5, [DISC], eps=0.1, sigma=0.02, n_ip=0)
        x, hist = gpmp(prob)
        self.assertAlmostEqual(support_clearance(prob, x), 0.0811, places=3)
        self.assertLess(dense_clearance(prob, x), 0.03)


class TestEdgeCases(unittest.TestCase):
    def test_free_space_gives_the_minimum_acceleration_cubic(self):
        prob = Problem(Q0, Q1, 1.0, 10, [])
        x, hist = gpmp(prob)
        self.assertAlmostEqual(hist[-1], 24.0, places=6)
        for i, s in enumerate(x, start=1):
            u = i / 10.0
            self.assertAlmostEqual(s[0], -1.0 + 2.0 * (3 * u * u - 2 * u ** 3), places=5)
            self.assertAlmostEqual(s[2], 2.0 * (6 * u - 6 * u * u), places=4)
            self.assertAlmostEqual(s[1], 0.0, places=9)

    def test_interpolation_is_cubic_hermite(self):
        rng = random.Random(3)
        for _ in range(5):
            dt = rng.uniform(0.1, 1.0)
            tau = rng.uniform(0.0, dt)
            s0 = [rng.uniform(-1, 1) for _ in range(4)]
            s1 = [rng.uniform(-1, 1) for _ in range(4)]
            lam, psi = interpolation(dt, tau, rng.uniform(0.5, 2.0))
            st = [sum(lam[r][k] * s0[k] + psi[r][k] * s1[k] for k in range(4)) for r in range(4)]
            h = hermite(s0, s1, dt, tau)
            for c in range(2):
                self.assertAlmostEqual(st[c], h[c][0], places=9)
                self.assertAlmostEqual(st[c + 2], h[c][1], places=9)

    def test_prior_factor_is_the_minimum_energy(self):
        rng = random.Random(8)
        dt, qc = 0.7, 1.3
        s0 = [rng.uniform(-1, 1) for _ in range(4)]
        s1 = [rng.uniform(-1, 1) for _ in range(4)]
        e = [s1[k] - sum(phi(dt)[k][j] * s0[j] for j in range(4)) for k in range(4)]
        w = q_inv(dt, qc)
        factor = 0.5 * sum(e[a] * w[a][b] * e[b] for a in range(4) for b in range(4))
        # the Hermite cubic has a linear second derivative, so Simpson's rule is exact
        energy = 0.0
        for c in range(2):
            p0, v0, p1, v1 = s0[c], s0[c + 2], s1[c], s1[c + 2]
            a2 = (3 * (p1 - p0) - (2 * v0 + v1) * dt) / dt ** 2
            a3 = (2 * (p0 - p1) + (v0 + v1) * dt) / dt ** 3
            acc = [2 * a2 + 6 * a3 * t for t in (0.0, dt / 2, dt)]
            energy += dt / 6 * (acc[0] ** 2 + 4 * acc[1] ** 2 + acc[2] ** 2)
        self.assertAlmostEqual(factor, 0.5 * energy / qc, places=9)

    def test_block_solve_matches_dense(self):
        rng = random.Random(11)
        m = 4
        diag = [[[rng.uniform(-0.2, 0.2) for _ in range(4)] for _ in range(4)] for _ in range(m)]
        for i in range(m):
            diag[i] = [[(diag[i][p][q] + diag[i][q][p]) / 2 + (5.0 if p == q else 0.0) for q in range(4)] for p in range(4)]
        off = [[[rng.uniform(-1, 1) for _ in range(4)] for _ in range(4)] for _ in range(m - 1)]
        rhs = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(m)]
        big = [[0.0] * (4 * m) for _ in range(4 * m)]
        for i in range(m):
            for p in range(4):
                for q in range(4):
                    big[4 * i + p][4 * i + q] = diag[i][p][q]
                    if i < m - 1:
                        big[4 * i + p][4 * i + 4 + q] = off[i][p][q]
                        big[4 * i + 4 + q][4 * i + p] = off[i][p][q]
        ref = solve_dense(big, [[v] for r in rhs for v in r])
        got = block_tridiag_solve(diag, off, rhs)
        for i in range(m):
            for p in range(4):
                self.assertAlmostEqual(got[i][p], ref[4 * i + p][0], places=9)

    def test_gradient_matches_finite_differences(self):
        prob = Problem(Q0, Q1, 1.0, 4, [DISC], eps=0.1, sigma=0.05, n_ip=2)
        x = straight_init(prob)
        x[1][1] += 0.03
        _, _, g = prob.normal_equations(x)
        h = 1e-6
        for i in range(len(x)):
            for k in range(4):
                xp = [list(s) for s in x]
                xm = [list(s) for s in x]
                xp[i][k] += h
                xm[i][k] -= h
                fd = (prob.cost(xp) - prob.cost(xm)) / (2 * h)
                self.assertAlmostEqual(g[i][k], fd, delta=1e-4 * max(1.0, abs(fd)))


class TestRandomized(unittest.TestCase):
    def test_cost_decreases_on_random_scenes(self):
        rng = random.Random(2018)
        for _ in range(3):
            sds = [disc_sd(rng.uniform(-0.4, 0.4), rng.uniform(-0.4, 0.2), rng.uniform(0.1, 0.3)) for _ in range(2)]
            prob = Problem(Q0, Q1, 1.0, 6, sds, eps=0.1, sigma=0.05, n_ip=2)
            x, hist = gpmp(prob, iters=30)
            self.assertTrue(all(b < a for a, b in zip(hist, hist[1:])))
            self.assertLessEqual(hist[-1], hist[0])


if __name__ == "__main__":
    unittest.main()

History

Mustafa Mukadam, Xinyan Yan and Byron Boots introduced Gaussian process motion planning in a conference paper. It used a Gaussian process prior of the kind developed for continuous-time state estimation, where the same sparse structure had been used to estimate trajectories. GPMP2, with Jing Dong and Frank Dellaert, followed in a conference paper and in the 2018 journal paper. It replaced the earlier optimizer with inference on a factor graph, which allowed incremental replanning with iSAM2.

References

  1. Mustafa Mukadam, Jing Dong, Xinyan Yan, Frank Dellaert and Byron Boots, Continuous-time Gaussian process motion planning via probabilistic inference, The International Journal of Robotics Research 37(11), 2018, 1319-1340, the whole paper (the Gaussian process prior, the obstacle factors with a hinge loss, the interpolation between support states, and the solution on a factor graph)

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
  • History with a source
  • at least three sources
  • a scene preset for the example