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.
- Solves
- Rigid body simulation
- 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
- Model
- Real RAM
- Properties
- deterministicin placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 constraint rows. Row has a Jacobian row , so that is the relative velocity along that row for the body velocities ; for a contact normal from to , , which is positive when the bodies separate. An impulse on row changes the velocities by . With the velocities before the solve,
is the vector of row velocities after the impulses. The bias carries restitution or position correction, for example Baumgarte stabilization. Each row has bounds : for a contact normal, for a joint, and for a friction row in the box model of Coulomb friction. The task is to find with
This is a box-constrained (mixed) linear complementarity problem (Catto, Section 7.3). For contact normals alone it is the LCP , , at the velocity level. 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
PGS(A, b, bounds, λ0, K)- 1
λ ← λ0 ▷ zero, or the impulses of the last step - 2
for k ← 1 to K - 3
for i ← 1 to n - 4
r ← b_i + Σ_j A_ij λ_j ▷ the current velocity of row i - 5
(lo, hi) ← BOUNDS(i, λ) ▷ fixed, or ±μ λ_normal for friction - 6
λ_i ← clamp(λ_i - r / A_ii, lo, hi) ▷ clamp the total, not the change - 7
return λ
Line L6 is one Gauss-Seidel step for row of , followed by a projection onto the bounds of that row. It is the exact minimizer of over alone, so PGS is coordinate descent on over the box.
Sequential impulses. The matrix is never formed. Keep the body velocities , which always equal . Then line L4 is , is the effective mass of the row, and after line L6 the change is applied to the two bodies of the row as an impulse. Each row touches two bodies, so one update costs . This is Catto's Algorithm 4, which keeps 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 () falls flat onto the ground at m/s and lands on its two bottom corners, at and . With and no friction, and
The exact answer is : the box stops, without spin. A push at one corner turns the box and drives the other corner down ().
| sweep | error of | ||
|---|---|---|---|
| 1 | |||
| 2 | |||
After one sweep, the box still moves down at m/s and turns at rad/s, the order effect shown on the collision impulse page. Each further sweep multiplies the error of both impulses by exactly , so about 8 sweeps reduce it below .
Tall stacks converge slowly. A column of boxes of mass 1 rests on the ground. After the gravity step all boxes move down at with , so only the ground row has , and the exact impulses are for the row under box . Starting from zero, the number of sweeps until every impulse is within 1% of its exact value is a measurement:
| boxes | 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 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 updates, whatever the input.
- Each update is exact for its row. Line L6 minimizes over within its bounds, and the new satisfies the box condition of row . The KKT conditions of over the box are exactly the box conditions of all rows.
- Sufficient decrease. Each update lowers by at least , where is the change of .
- Convergence. For a symmetric positive definite 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 .
- Redundant contacts. For a positive semidefinite , all solutions have the same row velocities , although the impulses are not unique.
Not proved: convergence for a singular , convergence with friction bounds (the bounds move with , 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 matrix with , a vector , and bounds (with or allowed). Write for the box, , and
The target is a point with where , where , and where . 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 of sweeps over rows, and each update (lines L4 to L6) is a finite computation. So the algorithm stops after 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 . Line L6 sets to the minimizer of over . The new value satisfies the box condition for row .
Proof. As a function of alone, , with , where is the value of line L4. A convex parabola has its minimum over an interval at the projection of its vertex, which is . After the update, . If the clamp did not act, ; if , then ; if , then .
Lemma 2 (sufficient decrease). If before the update and is the change of , then decreases by at least .
Proof. Let be the old value, the new one. Since is the projection of onto the interval and is in the interval, . Hence . The decrease of is .
After the first update of row , stays in its interval, so Lemma 2 applies to every later update of that row. If , it applies to every update.
Lemma 3 (the box condition is the optimality condition). Let be symmetric positive semidefinite. A point satisfies the box condition if and only if it minimizes over .
Proof. is convex, and is a box, so is a minimizer exactly when no feasible direction decreases , that is, when for all . Since and is a product of intervals, this splits into one condition per coordinate: for all . This holds if and only if for an interior , at , and at . These are the KKT conditions of the box-constrained program.
Theorem 1 (convergence for a positive definite matrix). Let be symmetric positive definite, nonempty, and . Then the iterates of projected Gauss-Seidel converge to the unique point that satisfies the box condition.
Proof. is strictly convex and , where is the smallest eigenvalue of . So has a unique minimizer over the closed set , and its sublevel sets are bounded. By Lemma 3, is the only point with the box condition.
Let be the iterate after the update of row in sweep . By Lemma 2, never increases, so all iterates lie in the bounded set , and converges to a limit . Summing Lemma 2 over all updates gives , so the changes tend to zero. Take any limit point of the end-of-sweep iterates , along a subsequence . Since the changes in one sweep tend to zero, for every as well. The update of row is , and clamp and are continuous, so in the limit . By the argument of Lemma 1, this fixed point equation is the box condition for row . It holds for every , so . A bounded sequence whose only limit point is converges to .
For contact without friction, and , and the box condition is the linear complementarity problem , , . 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 and , where has one row per constraint and is the mass matrix. Run the matrix-free version: keep body velocities , start with , and for each row compute , set with , and apply the impulse change to . In exact arithmetic it produces the same sequence of as the matrix version, with the same bounds and the same row order.
Proof. The invariant is . It holds at the start by construction, and an update that changes by changes by , which keeps it. Under the invariant, , which is the of line L4, and . The bounds of line L5 depend only on , so they agree as well. By induction over the updates, both versions make the same change at every step.
The invariant needs the clamp on the total , as in line L6. A version that clamps each increment, for example for a normal row, keeps 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 is only positive semidefinite and for some (always true when the bias is zero or lies in the range of ), every point with the box condition gives the same , so the same constrained relative velocities. Proof. As in Theorem 3 of the proof for Baraff's algorithm: two minimizers of the convex over the convex set satisfy , so .
What is not proved. For a singular (redundant contacts) this note does not prove that the iterates converge; the velocities of all solutions agree, and the tests measure convergence of . For box friction, where the bounds 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 , and Theorem 1 holds for any .
Complexity
One update reads row of , so a sweep costs for nonzero entries of , and sweeps cost . In the matrix-free form, each row touches at most two bodies, so an update is and a sweep is , with memory for rows and bodies; Catto gives time per iteration and storage for constraints and 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 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 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, per contact (Section 4.3), which keeps the bounds fixed. Later engines use 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 , as in successive over-relaxation.
- Projected Jacobi. Update all rows from the same old . It is parallel, but it converges under stronger conditions on 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 m/s and spins clockwise at rad/s onto three contacts at , so . Correct PGS gives after one sweep and the exact 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 , where the middle contact pushes with while it separates at m/s.
- Read the effective mass from the right rows. must include the angular terms of both bodies. A wrong changes the fixed point.
- Few sweeps means soft contacts. With a fixed , tall stacks sink slowly and heavy bodies on light ones push through. Check the residual if accuracy matters.
- Bias adds energy. A position bias in 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 .
- Robotics conventions. Pages on Stewart-Trinkle time stepping use up; this page uses 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.
# 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
- 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)
- Erin Catto, Solver2D, Box2D blog, February 2024, the section on PGS, which reframes it as sequential impulses and clamps the accumulated impulse
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MA63NH Edit this page History Report an error Markdown