Algorithm Search⌘K

Algorithmcore

Projected Gauss-Seidel

Also called PGS, sequential impulses, projected Gauss-Seidel solver.

Solve a contact problem by sweeping over constraints, solving each for its impulse alone and clamping it to its bounds, for a fixed number of sweeps.

Time
O(K z) matrixO(K n) matrix_free_pairwise
Space
O(n + z) matrixO(n + m) matrix_free
Where
K = the number of sweeps; m = the number of bodies; n = the number of constraint rows; z = the number of nonzero entries of A
Properties
deterministicin placeofflineiterative
Origin
Erin Catto, 2005

Projected Gauss-Seidel (PGS) computes contact and joint impulses for one time step of a rigid body simulation. It visits the constraint rows one at a time. For each row, it solves for the impulse that would make that row exactly satisfied if the other impulses stayed fixed, and then it clamps the impulse to its bounds: a normal impulse must not pull, and a friction impulse must stay inside its limit. It repeats these sweeps a fixed number of times. When it applies each change to the body velocities at once, it is called sequential impulses, and it is the usual contact solver of game physics engines.

In plain words

Several boxes touch each other and the floor. Each touching point needs a push that stops the boxes from moving into each other. The pushes depend on each other: a push at one point changes the motion at the points nearby.

The method takes the touching points one at a time. At each point, it asks what push would stop the boxes at that point, if all other pushes stayed as they are. If that push would pull instead of push, it uses no push. A friction push is limited in the same way. Then it goes to the next point. One pass over all points does not make every point correct, because later pushes change the earlier points. So it makes several passes. Each pass makes the answer better. A game stops after a fixed number of passes, so the cost of each frame is known.

The problem

There are nn constraint rows. Row ii has a Jacobian row JiJ_i, so that JivJ_i v is the relative velocity along that row for the body velocities vv; for a contact normal nn from BB to AA, Jiv=n⋅(vA(p)−vB(p))J_i v = n \cdot (v_A(p) - v_B(p)), which is positive when the bodies separate. An impulse λi\lambda_i on row ii changes the velocities by M−1JiTλiM^{-1} J_i^T \lambda_i. With the velocities v0v^0 before the solve,

w=Aλ+b,A=JM−1JT,b=Jv0+bias,w = A \lambda + b, \qquad A = J M^{-1} J^T, \qquad b = J v^0 + \text{bias},

is the vector of row velocities after the impulses. The bias carries restitution or position correction, for example Baumgarte stabilization. Each row has bounds loi≤λi≤hiilo_i \le \lambda_i \le hi_i: [0,∞)[0, \infty) for a contact normal, (−∞,∞)(-\infty, \infty) for a joint, and [−μλn,μλn][-\mu \lambda_n, \mu \lambda_n] for a friction row in the box model of Coulomb friction. The task is to find λ\lambda with

lo≤λ≤hi,wi=0 if loi<λi<hii,wi≥0 if λi=loi,wi≤0 if λi=hii.lo \le \lambda \le hi, \quad w_i = 0 \text{ if } lo_i < \lambda_i < hi_i, \quad w_i \ge 0 \text{ if } \lambda_i = lo_i, \quad w_i \le 0 \text{ if } \lambda_i = hi_i.

This is a box-constrained (mixed) linear complementarity problem (Catto, Section 7.3). For contact normals alone it is the LCP λ≥0\lambda \ge 0, w≥0w \ge 0, λTw=0\lambda^T w = 0 at the velocity level. AA is symmetric and positive semidefinite; it is singular when there are redundant contacts, such as four corners of a box on the floor.

The algorithm

  1. PGS(A, b, bounds, λ0, K)
  2. 1λ ← λ0 ▷ zero, or the impulses of the last step
  3. 2for k ← 1 to K
  4. 3for i ← 1 to n
  5. 4r ← b_i + Σ_j A_ij λ_j ▷ the current velocity of row i
  6. 5(lo, hi) ← BOUNDS(i, λ) ▷ fixed, or ±μ λ_normal for friction
  7. 6λ_i ← clamp(λ_i - r / A_ii, lo, hi) ▷ clamp the total, not the change
  8. 7return λ

Line L6 is one Gauss-Seidel step for row ii of Aλ=−bA \lambda = -b, followed by a projection onto the bounds of that row. It is the exact minimizer of q(λ)=12λTAλ+bTλq(\lambda) = \tfrac12 \lambda^T A \lambda + b^T \lambda over λi\lambda_i alone, so PGS is coordinate descent on qq over the box.

Sequential impulses. The matrix AA is never formed. Keep the body velocities vv, which always equal v0+M−1JTλv^0 + M^{-1} J^T \lambda. Then line L4 is r=Jiv+biasir = J_i v + \text{bias}_i, Aii=JiM−1JiTA_{ii} = J_i M^{-1} J_i^T is the effective mass of the row, and after line L6 the change (λinew−λiold)JiT(\lambda_i^{new} - \lambda_i^{old}) J_i^T is applied to the two bodies of the row as an impulse. Each row touches two bodies, so one update costs O(1)O(1). This is Catto's Algorithm 4, which keeps a=M−1JTλa = M^{-1} J^T \lambda and applies only "the actual increment" after the clamp; in exact arithmetic it gives the same iterates as the matrix version.

Example

A 2D box of mass 1 with sides 2 and 1 (I=5/12I = 5/12) falls flat onto the ground at 11 m/s and lands on its two bottom corners, at x=−1x = -1 and x=1x = 1. With e=0e = 0 and no friction, b=(−1,−1)b = (-1, -1) and

A=(17/5−7/5−7/517/5).A = \begin{pmatrix} 17/5 & -7/5 \\ -7/5 & 17/5 \end{pmatrix}.

The exact answer is λ=(1/2,1/2)\lambda = (1/2, 1/2): the box stops, without spin. A push at one corner turns the box and drives the other corner down (A12<0A_{12} < 0).

sweep λ1\lambda_1 λ2\lambda_2 error of λ2\lambda_2
1 5/175/17 120/289120/289 −49/578-49/578
2 2285/49132285/4913 40560/8352140560/83521 −49/578⋅49/289-49/578 \cdot 49/289
kk −49/578⋅(49/289)k−1-49/578 \cdot (49/289)^{k-1}

After one sweep, the box still moves down at 84/28984/289 m/s and turns at 84/28984/289 rad/s, the order effect shown on the collision impulse page. Each further sweep multiplies the error of both impulses by exactly (A12/A11)2=49/289≈0.17(A_{12}/A_{11})^2 = 49/289 \approx 0.17, so about 8 sweeps reduce it below 10−610^{-6}.

Tall stacks converge slowly. A column of NN boxes of mass 1 rests on the ground. After the gravity step all boxes move down at gΔtg \Delta t with Δt=1/60\Delta t = 1/60, so only the ground row has b≠0b \ne 0, and the exact impulses are (N−k)gΔt(N - k) g \Delta t for the row under box kk. Starting from zero, the number of sweeps until every impulse is within 1% of its exact value is a measurement:

boxes NN 1 2 5 10 20
rows from the bottom up 1 7 47 192 776
rows from the top down 1 8 51 201 795

The count grows about as 2N22N^2 in this test, and the row order matters little. So with a budget of 10 sweeps from a cold start, the impulses of a tall stack stay too small, and the stack sinks. Warm starting and shock propagation are the usual remedies.

Correctness

The proof is in proofs/correctness.md. It shows:

  • Termination. The loops run KnK n updates, whatever the input.
  • Each update is exact for its row. Line L6 minimizes qq over λi\lambda_i within its bounds, and the new λi\lambda_i satisfies the box condition of row ii. The KKT conditions of min⁡q\min q over the box are exactly the box conditions of all rows.
  • Sufficient decrease. Each update lowers qq by at least 12Aiiδ2\tfrac12 A_{ii} \delta^2, where δ\delta is the change of λi\lambda_i.
  • Convergence. For a symmetric positive definite AA and fixed bounds, the iterates converge to the unique solution. Catto (Section 7.2) cites Cottle, Pang and Stone for this fact.
  • Sequential impulses compute the same iterates as the matrix version, by the invariant v=v0+M−1JTλv = v^0 + M^{-1} J^T \lambda.
  • Redundant contacts. For a positive semidefinite AA, all solutions have the same row velocities ww, although the impulses are not unique.

Not proved: convergence for a singular AA, convergence with friction bounds ±μλn\pm\mu\lambda_n (the bounds move with λn\lambda_n, so the argument of the proof does not apply), and any rate of convergence beyond the exact two-contact example.

Proof: Projected Gauss-Seidel converges for a symmetric positive definite matrix with fixed bounds, and sequential impulses compute the same iteratesfull

The input is a symmetric n×nn \times n matrix AA with Aii>0A_{ii} > 0, a vector bb, and bounds loi≤hiilo_i \le hi_i (with loi=−∞lo_i = -\infty or hii=+∞hi_i = +\infty allowed). Write B=∏i[loi,hii]B = \prod_i [lo_i, hi_i] for the box, w=Aλ+bw = A\lambda + b, and

q(λ)=12λTAλ+bTλ.q(\lambda) = \tfrac12 \lambda^T A \lambda + b^T \lambda.

The target is a point λ∈B\lambda \in B with wi≥0w_i \ge 0 where λi=loi<hii\lambda_i = lo_i < hi_i, wi≤0w_i \le 0 where λi=hii>loi\lambda_i = hi_i > lo_i, and wi=0w_i = 0 where loi<λi<hiilo_i < \lambda_i < hi_i. Call this the box condition. Line numbers refer to the pseudocode of the page.

Termination. The loops of lines L2 and L3 run a fixed number KK of sweeps over nn rows, and each update (lines L4 to L6) is a finite computation. So the algorithm stops after KnK n updates, whatever the input. The rest of this note is about what the iterates approach.

Lemma 1 (one update solves its row). Fix all coordinates except λi\lambda_i. Line L6 sets λi\lambda_i to the minimizer of qq over λi∈[loi,hii]\lambda_i \in [lo_i, hi_i]. The new value satisfies the box condition for row ii.

Proof. As a function of λi\lambda_i alone, q=12Aii(λi−x∗)2+constq = \tfrac12 A_{ii} (\lambda_i - x^*)^2 + \text{const}, with x∗=λi−r/Aiix^* = \lambda_i - r / A_{ii}, where r=wir = w_i is the value of line L4. A convex parabola has its minimum over an interval at the projection of its vertex, which is clamp(x∗,loi,hii)\text{clamp}(x^*, lo_i, hi_i). After the update, wi=Aii(λi−x∗)w_i = A_{ii}(\lambda_i - x^*). If the clamp did not act, wi=0w_i = 0; if λi=loi>x∗\lambda_i = lo_i > x^*, then wi>0w_i > 0; if λi=hii<x∗\lambda_i = hi_i < x^*, then wi<0w_i < 0. □\square

Lemma 2 (sufficient decrease). If λi∈[loi,hii]\lambda_i \in [lo_i, hi_i] before the update and δ\delta is the change of λi\lambda_i, then qq decreases by at least 12Aiiδ2\tfrac12 A_{ii} \delta^2.

Proof. Let xx be the old value, y=clamp(x∗)y = \text{clamp}(x^*) the new one. Since yy is the projection of x∗x^* onto the interval and xx is in the interval, (x−y)(x∗−y)≤0(x - y)(x^* - y) \le 0. Hence (x−x∗)2=(x−y)2+(y−x∗)2−2(x−y)(x∗−y)≥(x−y)2+(y−x∗)2(x - x^*)^2 = (x - y)^2 + (y - x^*)^2 - 2(x - y)(x^* - y) \ge (x - y)^2 + (y - x^*)^2. The decrease of qq is 12Aii[(x−x∗)2−(y−x∗)2]≥12Aii(x−y)2\tfrac12 A_{ii} [(x - x^*)^2 - (y - x^*)^2] \ge \tfrac12 A_{ii} (x - y)^2. □\square

After the first update of row ii, λi\lambda_i stays in its interval, so Lemma 2 applies to every later update of that row. If λ0∈B\lambda^0 \in B, it applies to every update.

Lemma 3 (the box condition is the optimality condition). Let AA be symmetric positive semidefinite. A point λ∈B\lambda \in B satisfies the box condition if and only if it minimizes qq over BB.

Proof. qq is convex, and BB is a box, so λ\lambda is a minimizer exactly when no feasible direction decreases qq, that is, when ∇q(λ)T(μ−λ)≥0\nabla q(\lambda)^T (\mu - \lambda) \ge 0 for all μ∈B\mu \in B. Since ∇q=w\nabla q = w and BB is a product of intervals, this splits into one condition per coordinate: wi(μi−λi)≥0w_i (\mu_i - \lambda_i) \ge 0 for all μi∈[loi,hii]\mu_i \in [lo_i, hi_i]. This holds if and only if wi=0w_i = 0 for an interior λi\lambda_i, wi≥0w_i \ge 0 at loilo_i, and wi≤0w_i \le 0 at hiihi_i. These are the KKT conditions of the box-constrained program. □\square

Theorem 1 (convergence for a positive definite matrix). Let AA be symmetric positive definite, BB nonempty, and λ0∈B\lambda^0 \in B. Then the iterates of projected Gauss-Seidel converge to the unique point λ∗\lambda^* that satisfies the box condition.

Proof. qq is strictly convex and q(λ)≥12σ∣λ∣2−∣b∣∣λ∣q(\lambda) \ge \tfrac12 \sigma |\lambda|^2 - |b| |\lambda|, where σ>0\sigma > 0 is the smallest eigenvalue of AA. So qq has a unique minimizer λ∗\lambda^* over the closed set BB, and its sublevel sets are bounded. By Lemma 3, λ∗\lambda^* is the only point with the box condition.

Let λk,i\lambda^{k,i} be the iterate after the update of row ii in sweep kk. By Lemma 2, qq never increases, so all iterates lie in the bounded set {q≤q(λ0)}\{q \le q(\lambda^0)\}, and qq converges to a limit qˉ\bar q. Summing Lemma 2 over all updates gives ∑12Aiiδ2≤q(λ0)−qˉ<∞\sum \tfrac12 A_{ii} \delta^2 \le q(\lambda^0) - \bar q < \infty, so the changes δ\delta tend to zero. Take any limit point λˉ\bar\lambda of the end-of-sweep iterates λk,n\lambda^{k,n}, along a subsequence kmk_m. Since the changes in one sweep tend to zero, λkm,i→λˉ\lambda^{k_m, i} \to \bar\lambda for every ii as well. The update of row ii is λik,i=clamp(λik,i−1−wi(λk,i−1)/Aii,loi,hii)\lambda^{k,i}_i = \text{clamp}(\lambda^{k,i-1}_i - w_i(\lambda^{k,i-1}) / A_{ii}, lo_i, hi_i), and clamp and ww are continuous, so in the limit λˉi=clamp(λˉi−wi(λˉ)/Aii,loi,hii)\bar\lambda_i = \text{clamp}(\bar\lambda_i - w_i(\bar\lambda)/A_{ii}, lo_i, hi_i). By the argument of Lemma 1, this fixed point equation is the box condition for row ii. It holds for every ii, so λˉ=λ∗\bar\lambda = \lambda^*. A bounded sequence whose only limit point is λ∗\lambda^* converges to λ∗\lambda^*. □\square

For contact without friction, loi=0lo_i = 0 and hii=+∞hi_i = +\infty, and the box condition is the linear complementarity problem λ≥0\lambda \ge 0, w≥0w \ge 0, λTw=0\lambda^T w = 0. Theorem 1 is the classical convergence result for projected iterative methods on symmetric LCPs (Cottle, Pang and Stone treat these methods; Catto 2005, Section 7.2, cites them for convergence when the matrix is positive definite).

Theorem 2 (sequential impulses compute the same iterates). Let A=JM−1JTA = J M^{-1} J^T and b=Jv0+biasb = J v^0 + \text{bias}, where JJ has one row per constraint and MM is the mass matrix. Run the matrix-free version: keep body velocities vv, start with v=v0+M−1JTλ0v = v^0 + M^{-1} J^T \lambda^0, and for each row compute r=Jiv+biasir = J_i v + \text{bias}_i, set λinew=clamp(λi−r/Kii)\lambda_i^{new} = \text{clamp}(\lambda_i - r / K_{ii}) with Kii=JiM−1JiTK_{ii} = J_i M^{-1} J_i^T, and apply the impulse change (λinew−λi)JiT(\lambda_i^{new} - \lambda_i) J_i^T to vv. In exact arithmetic it produces the same sequence of λ\lambda as the matrix version, with the same bounds and the same row order.

Proof. The invariant is v=v0+M−1JTλv = v^0 + M^{-1} J^T \lambda. It holds at the start by construction, and an update that changes λi\lambda_i by δ\delta changes vv by M−1JiTδM^{-1} J_i^T \delta, which keeps it. Under the invariant, Jiv+biasi=Jiv0+biasi+(JM−1JTλ)i=bi+(Aλ)iJ_i v + \text{bias}_i = J_i v^0 + \text{bias}_i + (J M^{-1} J^T \lambda)_i = b_i + (A \lambda)_i, which is the rr of line L4, and Kii=AiiK_{ii} = A_{ii}. The bounds of line L5 depend only on λ\lambda, so they agree as well. By induction over the updates, both versions make the same change at every step. □\square

The invariant needs the clamp on the total λi\lambda_i, as in line L6. A version that clamps each increment, for example δ≥0\delta \ge 0 for a normal row, keeps v=v0+M−1JTλv = v^0 + M^{-1} J^T \lambda but solves a different problem: no impulse can ever decrease, and the limit may violate the box condition (the tipping box of the page).

Corollary (positive semidefinite matrices: the velocities agree). If AA is only positive semidefinite and b=Jv0+Jzb = J v^0 + J z for some zz (always true when the bias is zero or lies in the range of JJ), every point with the box condition gives the same w=Aλ+bw = A \lambda + b, so the same constrained relative velocities. Proof. As in Theorem 3 of the proof for Baraff's algorithm: two minimizers λ,μ\lambda, \mu of the convex qq over the convex set BB satisfy (λ−μ)TA(λ−μ)=0(\lambda - \mu)^T A (\lambda - \mu) = 0, so Aλ=AμA \lambda = A \mu. □\square

What is not proved. For a singular AA (redundant contacts) this note does not prove that the iterates converge; the velocities of all solutions agree, and the tests measure convergence of ww. For box friction, where the bounds ±μλn\pm \mu \lambda_n move with the normal impulse, the problem is not the optimality condition of a symmetric program, and convergence is not proved. No rate of convergence is proved here: the rate depends on the matrix, and on the page it is measured, not derived, except for the two-contact example, where it is computed exactly. Warm starting is a heuristic: it changes λ0\lambda^0, and Theorem 1 holds for any λ0∈B\lambda^0 \in B.

Complexity

One update reads row ii of AA, so a sweep costs O(z)O(z) for zz nonzero entries of AA, and KK sweeps cost O(Kz)O(K z). In the matrix-free form, each row touches at most two bodies, so an update is O(1)O(1) and a sweep is O(n)O(n), with O(n+m)O(n + m) memory for nn rows and mm bodies; Catto gives O(s)O(s) time per iteration and O(s+n)O(s + n) storage for ss constraints and nn bodies. The number of sweeps needed for a given accuracy depends on the matrix: it is small for loosely coupled contacts and grows with stack height and mass ratios, as the table above shows. In practice KK is fixed (Catto uses 10 iterations in his stacking test), so the cost per frame is predictable and the accuracy is not.

Properties

  • Simple: a few lines per constraint type, and joints, contacts, motors and limits all fit the same bounds scheme (Catto, Section 3.5).
  • Matrix-free and cache friendly in the sequential impulse form.
  • The result depends on the order of the rows after a finite number of sweeps.
  • Never pulls at a contact, at every iterate, because every update clamps.
  • Not exact after KK sweeps: the remaining error shows up as slow sinking or jitter.
  • Handles redundant contacts without special code; a pivoting method needs care there.

Variants and improvements

  • Warm starting. Start from the impulses of the previous step, matched by contact ids (Catto, Section 8). This is a heuristic: it helps when the contacts change little between frames. In Catto's tests, a stack of three boxes fell without caching, and a stack of ten boxes was stable with it (Section 9.1).
  • Friction models. Catto 2005 bounds the friction impulse by a constant, μmcg\mu m_c g per contact (Section 4.3), which keeps the bounds fixed. Later engines use ±μλn\pm \mu \lambda_n with the current normal impulse, which follows Coulomb's law more closely but loses the convergence proof.
  • Relaxation. Multiply the step of line L6 by a factor ω∈(0,2)\omega \in (0, 2), as in successive over-relaxation.
  • Projected Jacobi. Update all rows from the same old λ\lambda. It is parallel, but it converges under stronger conditions on AA than Gauss-Seidel, and it is often damped (see the Jacobi method).
  • Graph coloring. Rows that share no body do not affect each other's update, so a color class can be updated in parallel. The result is that of a sweep in the order of the colors.
  • Exact methods. Baraff's pivoting algorithm solves the frictionless problem exactly, at a higher cost per step.
  • Stacking. Shock propagation solves the levels of a stack from the ground up and freezes the lower levels.

When to use it

Use it for interactive simulations with many contacts and a fixed time budget per frame: games, virtual reality, and robotics simulators that value speed. It accepts joints and contacts in one loop, and warm starting makes it strong for scenes that change little between frames. Do not use it when you need accurate forces, very stiff chains, or large mass ratios: in Catto's test of two stacked boxes, the stack was stable until the density of the lower box was lowered to 3% of the upper one, and below that the top box bounced and slid off (Section 9.2). A direct or pivoting solver, or a reduced coordinate method for chains, is better there.

Pitfalls

  • Clamp the total, not the increment. A 2D box of mass 1 and sides 2 and 1 falls at 1010 m/s and spins clockwise at 3636 rad/s onto three contacts at x=−1,0,1x = -1, 0, 1, so b=(26,−10,−46)b = (26, -10, -46). Correct PGS gives (0,10,180/17)(0, 10, 180/17) after one sweep and the exact (0,0,230/17)(0, 0, 230/17) after the second: the middle impulse must fall back to zero. A solver that clamps each change at zero can never lower an impulse. It stops at (0,10,180/17)(0, 10, 180/17), where the middle contact pushes with 1010 while it separates at 180/17180/17 m/s.
  • Read the effective mass from the right rows. Aii=JiM−1JiTA_{ii} = J_i M^{-1} J_i^T must include the angular terms of both bodies. A wrong AiiA_{ii} changes the fixed point.
  • Few sweeps means soft contacts. With a fixed KK, tall stacks sink slowly and heavy bodies on light ones push through. Check the residual ww if accuracy matters.
  • Bias adds energy. A position bias in bb makes the contacts push bodies apart faster than they met. See Baumgarte stabilization for split impulses.
  • Restitution in the bias. Compute the restitution target from the velocity before the solve, not from the current iterate, or the bounce changes with KK.
  • Robotics conventions. Pages on Stewart-Trinkle time stepping use zz up; this page uses yy up.

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.

projected_gauss_seidel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projected-gauss-seidel/. The authors are listed in prov/MA63NH.jsonl.

"""Projected Gauss-Seidel for contact impulses, in matrix form and as sequential impulses.

The problem: given A (n x n, A_ii > 0), b and bounds lo_i <= hi_i, find lam with

    lo <= lam <= hi,  w = A lam + b,
    w_i >= 0 where lam_i = lo_i,  w_i <= 0 where lam_i = hi_i,  w_i = 0 in between.

For a contact, lam_i is an impulse, w_i the relative velocity along the
constraint row after the impulse, A = J M^-1 J^T and b = J v0 + bias.

A bound entry is either a pair (lo, hi) or a triple ("friction", k, mu), which
means the box [-mu lam_k, mu lam_k] around the current normal impulse lam_k.

The matrix-free version (sequential impulses) keeps body velocities instead of
A. In exact arithmetic it produces the same lam as the matrix version.
"""

INF = float("inf")


def clamp(x, lo, hi):
    return lo if x < lo else hi if x > hi else x


def row_bounds(entry, lam):
    if len(entry) == 3 and entry[0] == "friction":
        _, k, mu = entry
        return -mu * lam[k], mu * lam[k]
    return entry


def pgs(A, b, bounds, sweeps, lam0=None, trace=None):
    """Run a fixed number of projected Gauss-Seidel sweeps and return lam."""
    n = len(b)
    lam = list(lam0) if lam0 is not None else [0 * b[i] for i in range(n)]  # @line L1
    for _ in range(sweeps):  # @line L2
        for i in range(n):  # @line L3
            r = b[i] + sum(A[i][j] * lam[j] for j in range(n))  # @line L4
            lo, hi = row_bounds(bounds[i], lam)  # @line L5
            lam[i] = clamp(lam[i] - r / A[i][i], lo, hi)  # @line L6
        if trace is not None:
            trace.append(list(lam))
    return lam  # @line L7


def residual(A, b, lam):
    return [b[i] + sum(A[i][j] * lam[j] for j in range(len(b))) for i in range(len(b))]


def violation(A, b, bounds, lam):
    """The largest violation of the box complementarity conditions (0 for an exact solution)."""
    w = residual(A, b, lam)
    worst = 0
    for i, wi in enumerate(w):
        lo, hi = row_bounds(bounds[i], lam)
        x = lam[i]
        worst = max(worst, lo - x, x - hi)
        # the projected residual: zero exactly when the row update would not move lam_i
        worst = max(worst, abs(clamp(x - wi, lo, hi) - x))
    return worst


def objective(A, b, lam):
    n = len(b)
    return sum(lam[i] * A[i][j] * lam[j] for i in range(n) for j in range(n)) / 2 + sum(b[i] * lam[i] for i in range(n))


# ---------------------------------------------------------------- sequential impulses


class Body:
    """A 2D rigid body: mass m, moment of inertia I, velocity v, angular velocity w."""

    def __init__(self, m, I, v, w):
        self.inv_m = 0 if m is None else 1 / m
        self.inv_I = 0 if I is None else 1 / I
        self.v = list(v)
        self.w = w


def ground():
    return Body(None, None, (0, 0), 0)


def cross2(r, d):
    return r[0] * d[1] - r[1] * d[0]


class Row:
    """One constraint row: the impulse lam * d acts on body a at r_a, and -lam * d on body b at r_b."""

    def __init__(self, a, b, r_a, r_b, d):
        self.a, self.b, self.r_a, self.r_b, self.d = a, b, r_a, r_b, d
        self.ca, self.cb = cross2(r_a, d), cross2(r_b, d)

    def jacobian(self, nbodies):
        """The row of J, three entries (v_x, v_y, w) per body."""
        J = [0] * (3 * nbodies)
        J[3 * self.a:3 * self.a + 3] = [self.d[0], self.d[1], self.ca]
        J[3 * self.b:3 * self.b + 3] = [-self.d[0], -self.d[1], -self.cb]
        return J


def row_velocity(row, bodies):
    A, B = bodies[row.a], bodies[row.b]
    return (row.d[0] * (A.v[0] - B.v[0]) + row.d[1] * (A.v[1] - B.v[1])
            + A.w * row.ca - B.w * row.cb)


def row_mass(row, bodies):
    """K_ii = J_i M^-1 J_i^T."""
    A, B = bodies[row.a], bodies[row.b]
    dd = row.d[0] * row.d[0] + row.d[1] * row.d[1]
    return (A.inv_m + B.inv_m) * dd + A.inv_I * row.ca * row.ca + B.inv_I * row.cb * row.cb


def apply_row(row, bodies, dlam):
    A, B = bodies[row.a], bodies[row.b]
    for k in range(2):
        A.v[k] += A.inv_m * dlam * row.d[k]
        B.v[k] -= B.inv_m * dlam * row.d[k]
    A.w += A.inv_I * dlam * row.ca
    B.w -= B.inv_I * dlam * row.cb


def sequential_impulses(bodies, rows, bias, bounds, sweeps, lam0=None):
    """Matrix-free PGS: update body velocities in place and return the accumulated impulses."""
    n = len(rows)
    lam = list(lam0) if lam0 is not None else [0] * n  # @line L1
    for i in range(n):  # warm start: apply the initial impulses once
        if lam[i]:
            apply_row(rows[i], bodies, lam[i])
    K = [row_mass(r, bodies) for r in rows]
    for _ in range(sweeps):  # @line L2
        for i in range(n):  # @line L3
            r = row_velocity(rows[i], bodies) + bias[i]  # @line L4
            lo, hi = row_bounds(bounds[i], lam)  # @line L5
            new = clamp(lam[i] - r / K[i], lo, hi)  # @line L6
            apply_row(rows[i], bodies, new - lam[i])  # clamp the total, apply the change
            lam[i] = new  # @line L6
    return lam  # @line L7


def assemble(bodies, rows, bias):
    """A = J M^-1 J^T and b = J v + bias for the current body velocities."""
    nb = len(bodies)
    J = [r.jacobian(nb) for r in rows]
    inv = []
    for body in bodies:
        inv += [body.inv_m, body.inv_m, body.inv_I]
    v = []
    for body in bodies:
        v += [body.v[0], body.v[1], body.w]
    A = [[sum(Ji[k] * inv[k] * Jj[k] for k in range(3 * nb)) for Jj in J] for Ji in J]
    b = [sum(Ji[k] * v[k] for k in range(3 * nb)) + bias[i] for i, Ji in enumerate(J)]
    return A, b
test_projected_gauss_seidel.py 238 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projected-gauss-seidel/. The authors are listed in prov/MA63NH.jsonl.

import itertools
import random
from fractions import Fraction as F

from projected_gauss_seidel import (INF, Body, Row, assemble, clamp, ground, objective, pgs, residual,
                                    row_velocity, sequential_impulses, violation)


def box_scene(v, w, xs):
    """A 2D box (mass 1, sides 2 and 1, I = 5/12) on the ground, with contacts at the bottom offsets xs."""
    bodies = [Body(F(1), F(5, 12), v, w), ground()]
    rows = [Row(0, 1, (F(x), F(-1, 2)), (0, 0), (0, 1)) for x in xs]
    return bodies, rows


def solve(M, rhs):
    n = len(rhs)
    aug = [list(M[i]) + [rhs[i]] for i in range(n)]
    for c in range(n):
        p = next((r for r in range(c, n) if aug[r][c] != 0), None)
        if p is None:
            return None
        aug[c], aug[p] = aug[p], aug[c]
        for r in range(n):
            if r != c and aug[r][c] != 0:
                fac = aug[r][c] / aug[c][c]
                aug[r] = [x - fac * y for x, y in zip(aug[r], aug[c])]
    return [aug[i][n] / aug[i][i] for i in range(n)]


def brute_force(A, b, bounds):
    """All solutions of the box problem with fixed bounds, over the 3^n choices lo / hi / free."""
    n = len(b)
    out = []
    for pattern in itertools.product(("lo", "hi", "free"), repeat=n):
        if any((p == "lo" and bounds[i][0] == -INF) or (p == "hi" and bounds[i][1] == INF)
               for i, p in enumerate(pattern)):
            continue
        lam = [F(0)] * n
        for i, p in enumerate(pattern):
            if p != "free":
                lam[i] = F(bounds[i][0] if p == "lo" else bounds[i][1])
        free = [i for i, p in enumerate(pattern) if p == "free"]
        if free:
            x = solve([[A[i][j] for j in free] for i in free],
                      [-b[i] - sum(A[i][j] * lam[j] for j in range(n) if j not in free) for i in free])
            if x is None:
                continue
            for i, xi in zip(free, x):
                lam[i] = xi
        if violation(A, b, bounds, lam) == 0:
            out.append(lam)
    return out


def test_page_example_two_corners_error_factor():
    bodies, rows = box_scene((0, -1), 0, [-1, 1])
    A, b = assemble(bodies, rows, [0, 0])
    assert A == [[F(17, 5), F(-7, 5)], [F(-7, 5), F(17, 5)]] and b == [-1, -1]
    trace = []
    pgs(A, b, [(0, INF)] * 2, 6, trace=trace)
    assert trace[0] == [F(5, 17), F(120, 289)]
    assert trace[1] == [F(2285, 4913), F(40560, 83521)]
    err = [[x - F(1, 2) for x in lam] for lam in trace]
    assert err[0] == [F(-7, 34), F(-49, 578)]
    for k in range(1, 6):
        assert err[k] == [F(49, 289) * x for x in err[k - 1]]
    # the box after one sweep: v_y and the angular velocity of the collision-impulse page
    lam = trace[0]
    assert sum(lam) - 1 == F(-84, 289)
    assert (lam[1] - lam[0]) * F(12, 5) == F(84, 289)


def test_warm_start_at_the_solution_is_a_fixed_point():
    bodies, rows = box_scene((0, -1), 0, [-1, 1])
    A, b = assemble(bodies, rows, [0, 0])
    assert pgs(A, b, [(0, INF)] * 2, 1, lam0=[F(1, 2), F(1, 2)]) == [F(1, 2), F(1, 2)]


def test_tipping_box_clamp_the_total_not_the_increment():
    bodies, rows = box_scene((0, -10), -36, [-1, 0, 1])
    A, b = assemble(bodies, rows, [0, 0, 0])
    assert b == [26, -10, -46]
    trace = []
    lam = pgs(A, b, [(0, INF)] * 3, 3, trace=trace)
    assert trace == [[0, 10, F(180, 17)], [0, 0, F(230, 17)], [0, 0, F(230, 17)]]
    assert residual(A, b, lam) == [F(120, 17), F(60, 17), 0]
    # the wrong variant: clamp each increment at zero, so an impulse can never decrease
    bad = [F(0)] * 3
    for _ in range(50):
        for i in range(3):
            r = residual(A, b, bad)[i]
            bad[i] += max(-r / A[i][i], 0)
    assert bad == [0, 10, F(180, 17)]
    w = residual(A, b, bad)
    assert w == [F(360, 17), F(180, 17), 0]
    assert bad[1] * w[1] > 0  # the middle contact pushes while it separates


def test_spd_fixed_bounds_matches_brute_force():
    rng = random.Random(11)
    for _ in range(60):
        n = rng.randint(1, 4)
        G = [[F(rng.randint(-4, 4), rng.randint(1, 2)) for _ in range(n + 1)] for _ in range(n)]
        A = [[sum(x * y for x, y in zip(G[i], G[j])) + (1 if i == j else 0) for j in range(n)] for i in range(n)]
        b = [F(rng.randint(-8, 8), rng.randint(1, 3)) for _ in range(n)]
        bounds = []
        for _ in range(n):
            kind = rng.randint(0, 2)
            if kind == 0:
                bounds.append((0, INF))
            elif kind == 1:
                bounds.append((-INF, INF))
            else:
                lo = F(rng.randint(-3, 1))
                bounds.append((lo, lo + rng.randint(1, 3)))
        sols = sorted({tuple(s) for s in brute_force(A, b, bounds)})
        assert len(sols) == 1  # one solution, found by several patterns when it is degenerate
        Af = [[float(x) for x in row] for row in A]
        lam = pgs(Af, [float(x) for x in b], bounds, 400)
        assert max(abs(x - float(y)) for x, y in zip(lam, sols[0])) < 1e-9


def test_each_sweep_lowers_the_objective_by_the_proved_amount():
    rng = random.Random(13)
    for _ in range(40):
        n = rng.randint(1, 5)
        G = [[F(rng.randint(-4, 4), rng.randint(1, 2)) for _ in range(n)] for _ in range(n)]
        A = [[sum(x * y for x, y in zip(G[i], G[j])) + F(1, 4) * (i == j) for j in range(n)] for i in range(n)]
        b = [F(rng.randint(-8, 8), rng.randint(1, 3)) for _ in range(n)]
        bounds = [(F(rng.randint(-2, 0)), F(rng.randint(1, 3))) for _ in range(n)]
        lam = [clamp(F(rng.randint(-3, 3)), lo, hi) for lo, hi in bounds]
        for _ in range(4):
            new = pgs(A, b, bounds, 1, lam0=lam)
            drop = objective(A, b, lam) - objective(A, b, new)
            assert drop >= sum(A[i][i] * (new[i] - lam[i]) ** 2 for i in range(n)) / 2
            lam = new


def test_redundant_contacts_give_unique_velocities():
    rng = random.Random(17)
    xs = [-1, F(-1, 3), F(1, 3), 1]
    for _ in range(10):
        v, w = (0, F(rng.randint(-20, -1), 4)), F(rng.randint(-8, 8), 4)
        bodies, rows = box_scene(v, w, xs)
        A, b = assemble(bodies, rows, [0] * 4)
        Af, bf = [[float(x) for x in r] for r in A], [float(x) for x in b]
        bounds = [(0, INF)] * 4
        lam = pgs(Af, bf, bounds, 3000)
        assert violation(Af, bf, bounds, lam) < 1e-9
        perm = [3, 1, 0, 2]
        lam_p = pgs([[Af[i][j] for j in perm] for i in perm], [bf[i] for i in perm], bounds, 3000)
        w1 = residual(Af, bf, lam)
        w2 = residual([[Af[i][j] for j in perm] for i in perm], [bf[i] for i in perm], lam_p)
        assert max(abs(w1[perm[k]] - w2[k]) for k in range(4)) < 1e-8


def random_scene(rng):
    dirs = [(F(3, 5), F(4, 5)), (F(0), F(1)), (F(1), F(0)), (F(-4, 5), F(3, 5)), (F(5, 13), F(12, 13))]
    nb = rng.randint(1, 3)
    params = [(F(rng.randint(1, 4)), F(rng.randint(1, 6), 3),
               (F(rng.randint(-4, 4), 2), F(rng.randint(-4, 4), 2)), F(rng.randint(-4, 4), 3)) for _ in range(nb)]
    contacts = []
    for _ in range(rng.randint(1, 3)):
        a = rng.randrange(nb)
        b = rng.choice([x for x in range(nb + 1) if x != a])
        n = rng.choice(dirs)
        t = (n[1], -n[0])
        ra = (F(rng.randint(-3, 3), 2), F(rng.randint(-3, 3), 2))
        rb = (F(rng.randint(-3, 3), 2), F(rng.randint(-3, 3), 2))
        contacts.append((a, b, ra, rb, n, t, F(rng.randint(1, 8), 8)))
    return params, contacts


def build(params, contacts):
    bodies = [Body(m, I, v, w) for m, I, v, w in params] + [ground()]
    rows, bounds = [], []
    for a, b, ra, rb, n, t, mu in contacts:
        k = len(rows)
        rows.append(Row(a, b, ra, rb, n))
        bounds.append((0, INF))
        rows.append(Row(a, b, ra, rb, t))
        bounds.append(("friction", k, mu))
    return bodies, rows, bounds


def test_sequential_impulses_equal_matrix_pgs_exactly():
    rng = random.Random(19)
    for trial in range(40):
        params, contacts = random_scene(rng)
        bodies, rows, bounds = build(params, contacts)
        bias = [F(rng.randint(-2, 2), 4) if k % 2 == 0 else 0 for k in range(len(rows))]
        A, b = assemble(bodies, rows, bias)
        lam0 = None if trial % 2 == 0 else [F(rng.randint(0, 3), 4) if k % 2 == 0 else 0 for k in range(len(rows))]
        lam_matrix = pgs(A, b, bounds, 3, lam0=lam0)
        lam_free = sequential_impulses(bodies, rows, bias, bounds, 3, lam0=lam0)
        assert lam_free == lam_matrix
        # the body velocities of the matrix-free route give w = A lam + b
        assert [row_velocity(rows[i], bodies) + bias[i] for i in range(len(rows))] == residual(A, b, lam_matrix)


def test_sequential_impulses_float_route_agrees():
    rng = random.Random(23)
    for _ in range(20):
        params, contacts = random_scene(rng)
        fparams = [(float(m), float(I), (float(v[0]), float(v[1])), float(w)) for m, I, v, w in params]
        fcontacts = [(a, b, tuple(map(float, ra)), tuple(map(float, rb)), tuple(map(float, n)), tuple(map(float, t)),
                      float(mu)) for a, b, ra, rb, n, t, mu in contacts]
        bodies, rows, bounds = build(fparams, fcontacts)
        bias = [0.0] * len(rows)
        A, b = assemble(bodies, rows, bias)
        lam_matrix = pgs(A, b, bounds, 40)
        lam_free = sequential_impulses(bodies, rows, bias, bounds, 40)
        assert max(abs(x - y) for x, y in zip(lam_matrix, lam_free)) < 1e-12


def test_sliding_and_sticking_box():
    for mu, sticks in ((F(2), True), (F(1, 10), False)):
        bodies = [Body(F(1), F(5, 12), (1.0, -1.0), 0.0), ground()]
        rows, bounds = [], []
        for x in (-1.0, 1.0):
            k = len(rows)
            rows.append(Row(0, 1, (x, -0.5), (0, 0), (0, 1)))
            bounds.append((0, INF))
            rows.append(Row(0, 1, (x, -0.5), (0, 0), (1, 0)))
            bounds.append(("friction", k, float(mu)))
        A, b = assemble(bodies, rows, [0.0] * 4)
        lam = pgs(A, b, bounds, 500)
        assert violation(A, b, bounds, lam) < 1e-10
        w = residual(A, b, lam)
        if sticks:
            assert abs(w[1]) < 1e-10 and abs(w[3]) < 1e-10
        else:
            assert abs(lam[1] + float(mu) * lam[0]) < 1e-10 and abs(lam[3] + float(mu) * lam[2]) < 1e-10
            assert w[1] > 0 and w[3] > 0

History

Projected iterative methods such as projected Gauss-Seidel and projected SOR for symmetric linear complementarity problems are classical in mathematical programming; Cottle, Pang and Stone (1992) treat them. Catto (2005) used projected Gauss-Seidel with contact caching as the solver of a velocity-level time stepping scheme for games, and later reframed the same loop as sequential impulses, which apply one row impulse at a time to the bodies. Erleben (2007) studied velocity-based iterative complementarity solvers for stacking, together with shock propagation.

References

  1. Erin Catto, Iterative Dynamics with Temporal Coherence, Game Developers Conference, 2005, Section 3.5 (bounds on each multiplier), Section 4.3 (friction bounded by a constant), Section 7 (Algorithms 3 and 4, the mixed LCP in 7.3), Section 8 (contact caching) and Section 9 (box stacking and mass ratios)
  2. Erin Catto, Solver2D, Box2D blog, February 2024, the section on PGS, which reframes it as sequential impulses and clamps the accumulated impulse
  3. Richard W. Cottle, Jong-Shi Pang and Richard E. Stone, The Linear Complementarity Problem, SIAM Classics in Applied Mathematics, 2009 (first edition Academic Press, 1992), the chapter on iterative methods for the LCP
  4. Kenny Erleben, Velocity-based shock propagation for multibody dynamics animation, ACM Transactions on Graphics 26(2), article 12, 2007, the iterative complementarity solver for velocity-based multibody dynamics

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.matrix
  • a full proof of time.matrix_free_pairwise
  • a full proof of space.matrix
  • a full proof of space.matrix_free
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