Algorithm Search⌘K

Algorithmadvanced

Baraff's contact force algorithm

Also called Baraff fast contact force computation.

Compute nonnegative contact forces that prevent interpenetration of resting rigid bodies by a pivoting method on a linear complementarity problem.

Time
O(n) drivesO(n^3) per_pivot_fresh_solveO(n^2) per_pivot_incremental
Space
O(n^2) matrix
Where
n = the number of contact points
Properties
deterministicnot in placeofflineiterative
Origin
David Baraff, George B. Dantzig, Richard W. Cottle, 1994

Baraff's contact force algorithm computes the normal forces at the contact points of rigid bodies that rest on each other. The forces must push and never pull, the contacts must not accelerate into each other, and a contact that separates must carry no force. These conditions form a linear complementarity problem with a symmetric positive semidefinite matrix. The algorithm solves it by raising one force at a time until its contact stops accelerating inward, while it keeps all contacts handled so far consistent. It is Dantzig's principal pivoting method, which Baraff (1994) explained in physical terms and extended to friction.

In plain words

A book lies on a table, and a cup stands on the book. Gravity pulls everything down. At each touching point, the table or the book must push up just hard enough to stop things from sinking in. A point that is about to lift off must not pull.

The algorithm looks at the touching points one by one. For a point that would sink, it slowly turns up the push at that point. While it does that, the pushes at the points it has already handled change too, so that those points neither sink nor pull. If one of those old points would need to pull, it lets that point go and lifts it off instead. If a lifted point starts to sink again, it takes that point back. When the current point stops sinking, it moves on to the next.

The problem

Bodies are at rest relative to each other at nn contact points; colliding contacts are handled first with impulses. At contact ii, the normal nin_i points from BB to AA, fi≥0f_i \ge 0 is the size of the normal force, and aia_i is the normal relative acceleration: ai>0a_i > 0 means the contact separates. With the contact Jacobian JJ and the mass matrix MM, the accelerations depend linearly on the forces,

a=Af+b,A=JM−1JT,b=JM−1Fext+(velocity terms),a = A f + b, \qquad A = J M^{-1} J^T, \qquad b = J M^{-1} F_{ext} + (\text{velocity terms}),

by the Newton-Euler equations. The problem is: find ff with

f≥0,a=Af+b≥0,fiai=0 for all i.f \ge 0, \qquad a = A f + b \ge 0, \qquad f_i a_i = 0 \text{ for all } i.

AA is symmetric and positive semidefinite, and bb lies in the column space of AA (Baraff, Section 4.1). AA is singular whenever there are more contacts than independent directions, for example a box on four corners, or a 2D box on three points along its bottom edge. This model has no friction; it is the frictionless case of rigid contact complementarity.

The algorithm

  1. COMPUTE-FORCES(A, b)
  2. 1f ← 0; a ← b
  3. 2C ← ∅; NC ← ∅ ▷ C: clamped, a_i = 0; NC: not clamped, f_i = 0
  4. 3while some d has a_d < 0
  5. 4DRIVE-TO-ZERO(d)
  6. DRIVE-TO-ZERO(d)
  7. 5loop
  8. 6Δf ← FDIRECTION(d); Δa ← A Δf
  9. 7(s, j) ← MAXSTEP(f, a, Δf, Δa, d)
  10. 8f ← f + s Δf; a ← a + s Δa
  11. 9if j ∈ C then move j from C to NC
  12. 10else if j ∈ NC then move j from NC to C
  13. 11else add d to C; return ▷ j = d, and a_d = 0
  14. FDIRECTION(d)
  15. 12Δf ← 0; Δf_d ← 1
  16. 13solve A_CC x = -A_Cd ▷ keep a_i = 0 for i in C
  17. 14Δf_i ← x_i for i in C; return Δf
  18. MAXSTEP(f, a, Δf, Δa, d)
  19. 15s ← ∞; j ← none
  20. 16if Δa_d > 0 then s ← -a_d / Δa_d; j ← d
  21. 17for i in C with Δf_i < 0: if -f_i / Δf_i < s then s ← -f_i / Δf_i; j ← i
  22. 18for i in NC with Δa_i < 0: if -a_i / Δa_i < s then s ← -a_i / Δa_i; j ← i
  23. 19return (s, j)

FDIRECTION finds how all clamped forces must change, per unit increase of fdf_d, so that the clamped contacts keep ai=0a_i = 0. MAXSTEP finds the first event along that direction: ada_d reaches zero, a clamped force falls to zero, or a free contact starts to accelerate inward.

Example

A 2D box of mass m=1m = 1 and width 2, with I=5/12I = 5/12, rests on the ground on three contacts, numbered 1, 2, 3 from left to right, at the horizontal offsets x=−1,0,1x = -1, 0, 1 from its center. Take g=10g = 10 and an applied torque of −15-15 (clockwise). For a contact at offset xx, a=y¨+αxa = \ddot y + \alpha x, so Aij=1/m+xixj/IA_{ij} = 1/m + x_i x_j / I and bi=−10+xi⋅(−15/I)b_i = -10 + x_i \cdot (-15/I):

A=(17/51−7/5111−7/5117/5),b=(26,−10,−46).A = \begin{pmatrix} 17/5 & 1 & -7/5 \\ 1 & 1 & 1 \\ -7/5 & 1 & 17/5 \end{pmatrix}, \qquad b = (26, -10, -46).

AA has rank 2, since three collinear contacts in 2D give only two independent rows.

pass driven dd CC before Δf\Delta f limit jj step ss ff after aa after
1 2 (middle) {}\{\} (0,1,0)(0, 1, 0) dd 10 (0,10,0)(0, 10, 0) (36,0,−36)(36, 0, -36)
2 3 (right) {2}\{2\} (0,−1,1)(0, -1, 1) 2 leaves CC 10 (0,0,10)(0, 0, 10) (12,0,−12)(12, 0, -12)
3 3 (right) {}\{\} (0,0,1)(0, 0, 1) dd 60/1760/17 (0,0,230/17)(0, 0, 230/17) (120/17,60/17,0)(120/17, 60/17, 0)

Contact 1 starts with a1=26>0a_1 = 26 > 0 and is never driven. In pass 2, pushing at the right corner while keeping the middle clamped needs less force in the middle, and the middle force reaches zero: the middle contact moves to NCNC. The result is the tipping box: only the right corner pushes, with 230/17230/17, and the left and middle contacts lift off with a=120/17a = 120/17 and 60/1760/17. Check: y¨=−10+230/17=60/17\ddot y = -10 + 230/17 = 60/17 and α=−36+(230/17)(12/5)=−60/17\alpha = -36 + (230/17)(12/5) = -60/17, so the right corner has y¨+α=0\ddot y + \alpha = 0.

Correctness

The proof is in proofs/correctness.md. The steps:

  • Invariants. Clamped contacts have ai=0a_i = 0 and fi≥0f_i \ge 0, free contacts have fi=0f_i = 0 and ai≥0a_i \ge 0, and contacts not yet handled have fi=0f_i = 0. MAXSTEP takes the largest step that keeps them, so when no ada_d is negative, ff solves the LCP.
  • The driven contact moves. Δad=ΔfTAΔf\Delta a_d = \Delta f^T A \Delta f, the Schur complement of ACCA_{CC}; it is positive for positive definite AA (Baraff's Theorem 2).
  • Each drive is finite. For positive definite AA, the state is the unique solution of a smaller LCP that depends on fdf_d alone. Each set CC is valid on an interval of fdf_d, and fdf_d only grows, so no set CC repeats in one drive (Baraff's Theorem 3), if no step has length zero.
  • At most nn drives. Each drive adds the driven contact to CC for good, and no drive removes a handled contact.
  • Uniqueness. For positive definite AA the forces are unique. For positive semidefinite AA with bb in its column space, all solutions have the same accelerations aa, because the LCP is the optimality condition of the convex quadratic program min⁡12fTAf+bTf\min \tfrac12 f^T A f + b^T f over f≥0f \ge 0 (see KKT conditions).

Termination for singular AA and for degenerate steps is proved by Baraff in Appendix A, not on this page.

Proof: Baraff's pivoting algorithm returns a solution of the contact LCP, and it terminates for a positive definite matrixfull

The input is a symmetric positive semidefinite n×nn \times n matrix AA and a vector bb. The goal is ff with f≥0f \ge 0, a=Af+b≥0a = A f + b \ge 0 and fiai=0f_i a_i = 0 for all ii. The algorithm keeps ff, aa and two disjoint index sets CC (clamped) and NCNC (not clamped). Call P=C∪NCP = C \cup NC the processed indices. Line numbers refer to the pseudocode of the page.

Invariants. At line L3 and at the start of every pass of the loop in DRIVE-TO-ZERO(dd):

  • (I0) a=Af+ba = A f + b.
  • (I1) f≥0f \ge 0.
  • (I2) ai=0a_i = 0 for i∈Ci \in C.
  • (I3) fi=0f_i = 0 and ai≥0a_i \ge 0 for i∈NCi \in NC.
  • (I4) fi=0f_i = 0 for i∉Pi \notin P, except fd≥0f_d \ge 0 inside DRIVE-TO-ZERO(dd).
  • (I5) inside DRIVE-TO-ZERO(dd): d∉Pd \notin P and ad<0a_d < 0.

At line L1, f=0f = 0, a=ba = b and P=∅P = \emptyset, so (I0) to (I4) hold. The outer loop picks dd with ad<0a_d < 0; by (I2) and (I3), d∉Pd \notin P, so (I5) holds at the first pass.

Lemma 1 (the direction). Let Δf\Delta f be the result of FDIRECTION(dd) and Δa=AΔf\Delta a = A \Delta f. Then Δfd=1\Delta f_d = 1, Δfi=0\Delta f_i = 0 for i∉C∪{d}i \notin C \cup \{d\}, Δai=0\Delta a_i = 0 for i∈Ci \in C, and Δad=ΔfTAΔf≥0\Delta a_d = \Delta f^T A \Delta f \ge 0. If AA is positive definite, Δad>0\Delta a_d > 0.

Proof. The first two facts are lines L12 to L14. For i∈Ci \in C, Δai=∑j∈CAijxj+Aid=(ACCx+ACd)i=0\Delta a_i = \sum_{j \in C} A_{ij} x_j + A_{id} = (A_{CC} x + A_{Cd})_i = 0 by line L13. Since Δf\Delta f is supported on C∪{d}C \cup \{d\}, ΔfTAΔf=∑i∈CΔfiΔai+ΔfdΔad=Δad\Delta f^T A \Delta f = \sum_{i \in C} \Delta f_i \Delta a_i + \Delta f_d \Delta a_d = \Delta a_d. It is ≥0\ge 0 because AA is positive semidefinite, and >0> 0 for positive definite AA because Δf≠0\Delta f \ne 0. □\square

So Δad\Delta a_d is the Schur complement Add−AdCACC−1ACdA_{dd} - A_{dC} A_{CC}^{-1} A_{Cd}; this is Theorem 2 of Baraff's Appendix A.

Lemma 2 (the step keeps the invariants). Let (s,j)(s, j) be the result of MAXSTEP. Then s≥0s \ge 0, and after line L8 and the set update of lines L9 to L11, the invariants hold again, with fdf_d increased by ss.

Proof. Each candidate step is nonnegative: −ad/Δad>0-a_d / \Delta a_d > 0 by (I5), −fi/Δfi≥0-f_i / \Delta f_i \ge 0 for i∈Ci \in C by (I1), and −ai/Δai≥0-a_i / \Delta a_i \ge 0 for i∈NCi \in NC by (I3). (I0) holds because aa and ff change by sΔa=A(sΔf)s \Delta a = A (s \Delta f). By Lemma 1, aCa_C does not change, ff does not change outside C∪{d}C \cup \{d\}, and fdf_d grows by ss. The step is the smallest of the candidates, so no fif_i with i∈Ci \in C becomes negative, no aia_i with i∈NCi \in NC becomes negative, and ada_d does not pass zero. The index jj that limits the step is tight: if j∈Cj \in C, then fj=0f_j = 0, and moving jj to NCNC keeps (I3) because aj=0a_j = 0; if j∈NCj \in NC, then aj=0a_j = 0, and moving jj to CC keeps (I2) and (I1); if j=dj = d, then ad=0a_d = 0, and adding dd to CC keeps (I2) and ends the call. □\square

Theorem 1 (the output solves the LCP). If COMPUTE-FORCES returns, then f≥0f \ge 0, a=Af+b≥0a = A f + b \ge 0 and fiai=0f_i a_i = 0 for all ii.

Proof. It returns only when no aia_i is negative. By (I1), f≥0f \ge 0. For i∈Ci \in C, ai=0a_i = 0; for i∈NCi \in NC and for i∉Pi \notin P, fi=0f_i = 0 by (I3) and (I4). □\square

Lemma 3 (each call adds one processed index). Every call DRIVE-TO-ZERO(dd) that returns adds dd to PP and does not remove any index from PP. So there are at most nn calls.

Proof. Lines L9 and L10 move indices between CC and NCNC; line L11 adds dd, which is not in PP by (I5). The outer loop only calls DRIVE-TO-ZERO on an index d∉Pd \notin P, so each call is on a new index. □\square

Lemma 4 (uniqueness for positive definite matrices). If MM is positive definite, the LCP g≥0g \ge 0, w=Mg+q≥0w = M g + q \ge 0, g⋅w=0g \cdot w = 0 has at most one solution.

Proof. Let (g,w)(g, w) and (h,z)(h, z) be solutions. Then (g−h)TM(g−h)=(g−h)⋅(w−z)=g⋅w−g⋅z−h⋅w+h⋅z=−g⋅z−h⋅w≤0(g - h)^T M (g - h) = (g - h) \cdot (w - z) = g \cdot w - g \cdot z - h \cdot w + h \cdot z = -g \cdot z - h \cdot w \le 0. Positive definiteness forces g=hg = h. □\square

Theorem 2 (termination for positive definite AA). Let AA be positive definite, and assume that no step of MAXSTEP has s=0s = 0 (nondegeneracy). Then every call DRIVE-TO-ZERO(dd) ends after at most 2∣P∣2^{|P|} passes, and COMPUTE-FORCES ends after at most nn calls. The result is the unique solution of the LCP.

Proof. Fix one call, with the processed set PP at its start; PP does not change during the call until the last pass. For τ≥0\tau \ge 0, let L(τ)L(\tau) be the LCP on the indices PP with the matrix APPA_{PP} and the vector bP+APdτb_P + A_{Pd} \tau. By the invariants, at the start of each pass fPf_P solves L(fd)L(f_d). APPA_{PP} is positive definite, so by Lemma 4 this solution is the only one.

For a split (C,NC)(C, NC) of PP, let T(C)T(C) be the set of τ\tau for which fC=−ACC−1(bC+ACdτ)f_C = -A_{CC}^{-1}(b_C + A_{Cd} \tau), fNC=0f_{NC} = 0 solves L(τ)L(\tau). The conditions are fC≥0f_C \ge 0 and aNC≥0a_{NC} \ge 0, which are finitely many linear inequalities in τ\tau, so T(C)T(C) is a closed interval. A pass with the set CC starts at some τ0∈T(C)\tau_0 \in T(C), moves the state along exactly this affine family (Lemma 1: fCf_C changes by sxs x, aNCa_{NC} by sΔaNCs \Delta a_{NC}), and MAXSTEP stops at the right end of T(C)T(C), unless ada_d reaches zero first. With s>0s > 0 for every step, fdf_d strictly increases from pass to pass. So if the set CC were used again in a later pass, at a value τ1\tau_1 larger than the right end of T(C)T(C), then τ1∈T(C)\tau_1 \in T(C), which is a contradiction. The passes therefore use distinct subsets CC of PP, so there are at most 2∣P∣2^{|P|} of them, and since Δad>0\Delta a_d > 0 (Lemma 1) every pass has a finite step, so the call ends at j=dj = d. By Lemma 3 there are at most nn calls. The result solves the LCP by Theorem 1, and it is the unique solution by Lemma 4. □\square

Baraff's Theorem 3 states the same fact, that no set CC repeats in one call, and his Theorems 4 and 5 rule out zero steps. This proof assumes nondegeneracy instead.

Lemma 5 (the index that just moved does not block the next step). Let AA be positive definite. If jj moved from CC to NCNC, the next direction has Δaj>0\Delta a_j > 0. If jj moved from NCNC to CC, the next direction has Δfj>0\Delta f_j > 0.

Proof. Let Δf\Delta f be the old direction and Δf′\Delta f' the new one, and δ=Δf′−Δf\delta = \Delta f' - \Delta f. Then δd=0\delta_d = 0. In the first case, δ\delta is supported on CC (the old set), (Aδ)i=0(A \delta)_i = 0 for i∈C∖{j}i \in C \setminus \{j\}, and δj=−Δfj>0\delta_j = -\Delta f_j > 0, since jj left CC because Δfj<0\Delta f_j < 0. So 0<δTAδ=δj(Aδ)j=−Δfj Δaj′0 < \delta^T A \delta = \delta_j (A\delta)_j = -\Delta f_j\, \Delta a'_j, where (Aδ)j=Δaj′−0(A \delta)_j = \Delta a'_j - 0. Hence Δaj′>0\Delta a'_j > 0. In the second case, δ\delta is supported on C∪{j}C \cup \{j\}, (Aδ)i=0(A\delta)_i = 0 for i∈Ci \in C, (Aδ)j=0−Δaj>0(A \delta)_j = 0 - \Delta a_j > 0, and δj=Δfj′\delta_j = \Delta f'_j. So 0<δTAδ=Δfj′(−Δaj)0 < \delta^T A \delta = \Delta f'_j (-\Delta a_j), and Δfj′>0\Delta f'_j > 0. □\square

So a zero step can only come from a second index that becomes tight at the same value of fdf_d, which is the degenerate case.

Theorem 3 (positive semidefinite AA: the accelerations are unique). Let AA be symmetric positive semidefinite and b=Azb = A z for some zz. Then the LCP has a solution, and all solutions have the same a=Af+ba = A f + b.

Proof. The solutions of the LCP are exactly the points that satisfy the KKT conditions of the convex program: minimize q(f)=12fTAf+bTfq(f) = \tfrac12 f^T A f + b^T f subject to f≥0f \ge 0 (the multiplier of f≥0f \ge 0 is aa). For a convex program the KKT conditions are necessary and sufficient, so the solutions are the minimizers. A minimizer exists: q(f)=12(f+z)TA(f+z)−12zTAzq(f) = \tfrac12 (f + z)^T A (f + z) - \tfrac12 z^T A z is bounded below, and a quadratic function that is bounded below on a polyhedron attains its minimum there (the Frank-Wolfe theorem). If ff and gg are minimizers with value q∗q^*, then q(12(f+g))=12q(f)+12q(g)−18(f−g)TA(f−g)≥q∗q(\tfrac12 (f + g)) = \tfrac12 q(f) + \tfrac12 q(g) - \tfrac18 (f - g)^T A (f - g) \ge q^*, so (f−g)TA(f−g)≤0(f - g)^T A (f - g) \le 0, hence =0= 0, and A(f−g)=0A (f - g) = 0 for a positive semidefinite AA. □\square

In contact terms, b=Jwb = J w for the matrix JJ of the contact normals and the unconstrained accelerations ww, and A=JM−1JTA = J M^{-1} J^T has the same column space as JJ, so the condition holds. The forces of a box on three collinear contacts are not unique, but the accelerations are.

What is not proved. Termination for a singular AA and for degenerate steps is not proved here; Baraff proves it in his Appendix A for bb in the column space of AA, and the sets ACCA_{CC} are then nonsingular (his footnote 2). The bound of 2∣P∣2^{|P|} passes per call is not a bound that is reached in practice; Baraff reports about three times the work of one Gaussian elimination of size nn in his simulations, which is a measurement. Friction is not covered: Baraff's extension to static friction is not proved to terminate, and the frictional problem is NP-hard in general (Baraff 1991).

Complexity

There are at most nn calls of DRIVE-TO-ZERO. Each pass solves one linear system with ACCA_{CC}: O(n3)O(n^3) with a fresh Gaussian elimination, as in Baraff's first implementation, or O(n2)O(n^2) with a factorization that is updated by one row and column per pass, since consecutive sets CC differ in one index. The proof bounds the passes of one call only by the number of subsets of the handled contacts, so no polynomial bound on the total is given here. Baraff reports about three times the work of one Gaussian elimination of size nn on his frictionless examples, which is a measurement. Storing AA takes O(n2)O(n^2) space; it is sparse when each body touches few others.

Properties

  • Exact in exact arithmetic: the result satisfies the complementarity conditions exactly, not to a tolerance.
  • No pulling forces, and no inward acceleration at any contact.
  • Works for singular AA, which is the normal case with redundant contacts.
  • The result depends on the order of the contacts when AA is singular, but the accelerations do not.
  • Finite: it ends after a finite number of pivots, while an iterative method such as projected Gauss-Seidel gives a sequence of approximations.

Variants and improvements

  • Bilateral constraints. Joints have ai=0a_i = 0 with forces of either sign. Baraff keeps them in CC for the whole run, so that MAXSTEP never removes them.
  • Friction. Later sections of Baraff's paper add static and dynamic Coulomb friction. The matrix is then no longer symmetric, and the static friction version is not proved to terminate. With friction, a consistent set of forces may not exist (the Painlevé paradox), and deciding whether one exists is NP-hard (Baraff 1991).
  • Impulse level. The same LCP with b=Jvb = J v and impulses in place of forces gives inelastic contact impulses for one time step, as in Stewart-Trinkle time stepping.
  • Lemke's method. Lemke's algorithm is a complementary pivoting method that applies to wider classes of LCPs, at the cost of an extra artificial variable.
  • Iterative solvers. Projected Gauss-Seidel trades exactness for a fixed cost per iteration and is the usual choice in game engines.

When to use it

Use it when you need accurate resting contact forces for a moderate number of contacts: robotics and engineering simulation, grasping, offline animation. It handles redundant contacts, and its result is exact up to rounding. For thousands of contacts per frame at interactive rates, an iterative solver with a fixed number of sweeps is cheaper. With friction, the pivoting extensions lose their termination guarantees, and a time-stepping formulation at the impulse level is more robust.

Pitfalls

  • Rounding and singular ACCA_{CC}. In exact arithmetic the matrices ACCA_{CC} that the algorithm forms are nonsingular when bb is in the column space of AA (Baraff, Section 4.4). In floating point, rounding can let an index enter CC that makes ACCA_{CC} singular or nearly singular. Use a solver that detects this, and do not trust a pivot on a tiny value.
  • bb not in the column space. If the data are inconsistent, MAXSTEP may find no limit, and the driven force grows without bound. Check for this and stop.
  • Forces are not unique. With redundant contacts, the force split between contacts can jump between frames even though the motion is the same. Do not read individual forces as measured loads.
  • Collisions first. The acceleration LCP assumes that no contact approaches with a nonzero velocity. Resolve colliding contacts with impulses before calling it, and correct the slow drift of positions, for example with Baumgarte stabilization.
  • Tolerances. In floating point, use a small tolerance in the tests ad<0a_d < 0, Δfi<0\Delta f_i < 0 and Δai<0\Delta a_i < 0, or the method can pivot on rounding noise.

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.

baraff_contact_force_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-contact-force-algorithm/. The authors are listed in prov/APAZTF.jsonl.

"""Baraff's frictionless contact force algorithm (Dantzig's pivoting method for the LCP).

Given a symmetric positive semidefinite matrix A and a vector b, find f with

    f >= 0,  a = A f + b >= 0,  f_i a_i = 0 for every i.

In contact mechanics, f_i is the normal force at contact i and a_i the normal
relative acceleration there (Baraff, SIGGRAPH 94, Section 4). The algorithm
keeps a set C of clamped contacts (a_i = 0) and a set NC of contacts that do
not push (f_i = 0), and raises one force f_d at a time until a_d = 0.

All arithmetic is exact if the input is given as Fraction values. The linear
systems are solved by Gaussian elimination, as in Baraff's first
implementation.
"""

from fractions import Fraction


def solve(M, rhs):
    """Solve M x = rhs by Gaussian elimination with partial pivoting. Raise on a singular M."""
    n = len(rhs)
    aug = [list(M[i]) + [rhs[i]] for i in range(n)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(aug[r][col]))
        if aug[piv][col] == 0:
            raise ZeroDivisionError("singular submatrix A_CC")
        aug[col], aug[piv] = aug[piv], aug[col]
        for r in range(col + 1, n):
            factor = aug[r][col] / aug[col][col]
            if factor:
                for c in range(col, n + 1):
                    aug[r][c] -= factor * aug[col][c]
    x = [0] * n
    for r in range(n - 1, -1, -1):
        s = aug[r][n] - sum(aug[r][c] * x[c] for c in range(r + 1, n))
        x[r] = s / aug[r][r]
    return x


def matvec(A, x):
    return [sum(A[i][j] * x[j] for j in range(len(x))) for i in range(len(A))]


def fdirection(A, C, d):
    """The force change df with df_d = 1, df_i = 0 outside C + {d}, and (A df)_i = 0 for i in C."""
    n = len(A)
    df = [0] * n  # @line L12
    df[d] = 1  # @line L12
    idx = sorted(C)
    if idx:
        x = solve([[A[i][j] for j in idx] for i in idx], [-A[i][d] for i in idx])  # @line L13
        for i, xi in zip(idx, x):  # @line L14
            df[i] = xi  # @line L14
    return df  # @line L14


def maxstep(f, a, df, da, C, NC, d):
    """The largest step s along df that keeps the invariants, and the index j that limits it."""
    s, j = None, None  # @line L15
    if da[d] > 0:  # @line L16
        s, j = -a[d] / da[d], d  # @line L16
    for i in sorted(C):  # @line L17
        if df[i] < 0:  # @line L17
            s1 = -f[i] / df[i]  # @line L17
            if s is None or s1 < s:  # @line L17
                s, j = s1, i  # @line L17
    for i in sorted(NC):  # @line L18
        if da[i] < 0:  # @line L18
            s1 = -a[i] / da[i]  # @line L18
            if s is None or s1 < s:  # @line L18
                s, j = s1, i  # @line L18
    return s, j  # @line L19


def drive_to_zero(A, f, a, C, NC, d, trace=None, max_pivots=10000):
    for _ in range(max_pivots):  # @line L5
        df = fdirection(A, C, d)  # @line L6
        da = matvec(A, df)  # @line L6
        s, j = maxstep(f, a, df, da, C, NC, d)  # @line L7
        if j is None:
            raise ArithmeticError("no step limit: the LCP has no solution")
        for i in range(len(f)):  # @line L8
            f[i] += s * df[i]  # @line L8
            a[i] += s * da[i]  # @line L8
        if j in C:  # @line L9
            C.remove(j)  # @line L9
            NC.add(j)  # @line L9
            f[j] = 0 * f[j]
            move = "C to NC"
        elif j in NC:  # @line L10
            NC.remove(j)  # @line L10
            C.add(j)  # @line L10
            a[j] = 0 * a[j]
            move = "NC to C"
        else:  # @line L11
            C.add(j)  # @line L11
            a[j] = 0 * a[j]
            move = "d to C"
        if trace is not None:
            trace.append((d, j, move, s))
        if move == "d to C":
            return  # @line L11
    raise RuntimeError("too many pivots")


def compute_forces(A, b, trace=None):
    """Return (f, a, C) with f >= 0, a = A f + b >= 0 and f . a = 0."""
    n = len(b)
    f = [0 * b[i] for i in range(n)]  # @line L1
    a = list(b)  # @line L1
    C, NC = set(), set()  # @line L2
    while True:  # @line L3
        neg = [i for i in range(n) if a[i] < 0]  # @line L3
        if not neg:  # @line L3
            return f, a, C
        drive_to_zero(A, f, a, C, NC, neg[0], trace)  # @line L4


def is_solution(A, b, f, a):
    """Check the LCP conditions exactly."""
    return (all(x >= 0 for x in f) and all(y >= 0 for y in a) and all(x * y == 0 for x, y in zip(f, a))
            and a == [p + q for p, q in zip(matvec(A, f), b)])


def box_contact_matrix(m, I, xs):
    """A and the map from external accelerations to b for a 2D body on contacts below it.

    The contacts are at the horizontal offsets xs from the center of mass, the
    normal is +y, and the body is at rest, so a_i = acc_y + alpha * x_i."""
    A = [[1 / Fraction(m) + Fraction(xi) * xj / Fraction(I) for xj in xs] for xi in xs]
    return A
test_baraff_contact_force_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-contact-force-algorithm/. The authors are listed in prov/APAZTF.jsonl.

import itertools
import random
from fractions import Fraction as F

from baraff_contact_force_algorithm import box_contact_matrix, compute_forces, is_solution, matvec, solve


def random_matrix(rng, rows, cols):
    return [[F(rng.randint(-6, 6), rng.randint(1, 3)) for _ in range(cols)] for _ in range(rows)]


def gram(J):
    """J J^T: symmetric positive semidefinite, of rank rank(J)."""
    return [[sum(x * y for x, y in zip(ri, rj)) for rj in J] for ri in J]


def brute_force(A, b):
    """All solutions of the LCP over the 2^n choices of the support of f, for a nonsingular A."""
    n = len(b)
    out = []
    for size in range(n + 1):
        for S in itertools.combinations(range(n), size):
            f = [F(0)] * n
            if S:
                try:
                    x = solve([[A[i][j] for j in S] for i in S], [-b[i] for i in S])
                except ZeroDivisionError:
                    continue
                for i, xi in zip(S, x):
                    f[i] = xi
            a = [p + q for p, q in zip(matvec(A, f), b)]
            if is_solution(A, b, f, a):
                out.append(f)
    return out


def test_page_example_box_tips():
    A = box_contact_matrix(1, F(5, 12), [-1, 0, 1])
    alpha = F(-15) / F(5, 12)
    b = [F(-10) + alpha * x for x in (-1, 0, 1)]
    assert b == [26, -10, -46]
    trace = []
    f, a, C = compute_forces(A, b, trace)
    assert trace == [(1, 1, "d to C", 10), (2, 1, "C to NC", 10), (2, 2, "d to C", F(60, 17))]
    assert f == [0, 0, F(230, 17)]
    assert a == [F(120, 17), F(60, 17), 0]
    assert C == {2}


def test_positive_definite_matches_brute_force():
    rng = random.Random(1)
    for _ in range(80):
        n = rng.randint(1, 5)
        A = gram(random_matrix(rng, n, n + 1))
        b = [F(rng.randint(-12, 12), rng.randint(1, 3)) for _ in range(n)]
        try:
            solve(A, [F(1)] * n)
        except ZeroDivisionError:
            continue
        sols = {tuple(s) for s in brute_force(A, b)}
        f, a, _ = compute_forces(A, b)
        assert is_solution(A, b, f, a)
        assert sols == {tuple(f)}


def test_semidefinite_resting_box_has_zero_acceleration():
    rng = random.Random(3)
    for _ in range(40):
        m, I = F(rng.randint(1, 4)), F(rng.randint(1, 6), 4)
        xs = sorted({F(rng.randint(-8, 8), 4) for _ in range(rng.randint(3, 5))})
        if len(xs) < 3 or xs[0] >= 0 or xs[-1] <= 0:
            continue
        torque = F(rng.randint(-10, 10), 4)
        if not xs[0] * m * 10 < torque < xs[-1] * m * 10:
            torque = 0
        acc_y, alpha = F(-10), torque / I
        A = box_contact_matrix(m, I, xs)
        b = [acc_y + alpha * x for x in xs]
        f, a, _ = compute_forces(A, b)
        assert is_solution(A, b, f, a)
        assert acc_y + sum(f) / m == 0
        assert alpha + sum(fi * x for fi, x in zip(f, xs)) / I == 0


def test_semidefinite_all_solutions_share_the_accelerations():
    rng = random.Random(5)
    for _ in range(60):
        n = rng.randint(2, 6)
        J = random_matrix(rng, n, rng.randint(1, n - 1))
        A = gram(J)
        w = [F(rng.randint(-6, 6), 2) for _ in range(len(J[0]))]
        b = [sum(x * y for x, y in zip(row, w)) for row in J]  # b = J w lies in the column space of A
        f, a, _ = compute_forces(A, b)
        assert is_solution(A, b, f, a)
        perm = list(range(n))
        rng.shuffle(perm)
        Ap = [[A[i][j] for j in perm] for i in perm]
        bp = [b[i] for i in perm]
        fp, ap, _ = compute_forces(Ap, bp)
        assert is_solution(Ap, bp, fp, ap)
        assert [ap[perm.index(i)] for i in range(n)] == a


def test_each_drive_adds_one_processed_index():
    rng = random.Random(7)
    for _ in range(60):
        n = rng.randint(2, 7)
        A = gram(random_matrix(rng, n, n))
        b = [F(rng.randint(-12, 12), rng.randint(1, 3)) for _ in range(n)]
        trace = []
        try:
            f, a, _ = compute_forces(A, b, trace)
        except ZeroDivisionError:
            continue
        driven = [d for d, j, move, _ in trace if move == "d to C"]
        assert len(driven) == len(set(driven)) <= n
        assert all(s >= 0 for *_, s in trace)


def test_nonnegative_b_needs_no_force():
    A = box_contact_matrix(2, F(1, 3), [F(-1, 2), F(1, 2)])
    f, a, C = compute_forces(A, [F(3), F(0)])
    assert f == [0, 0] and a == [3, 0] and C == set()

History

Baraff (1989) posed the computation of resting contact forces between rigid bodies as a quadratic program, which needed a general optimization package. In 1991 he showed that the problem with Coulomb friction is NP-hard. His 1994 paper used Dantzig's algorithm for the frictionless LCP, described by Cottle and Dantzig and attributed to Dantzig, gave it a physical reading as "drive one contact to zero acceleration at a time", and extended it to static and dynamic friction. Cottle, Pang and Stone treat pivoting methods for the LCP in general.

References

  1. David Baraff, Fast contact force computation for nonpenetrating rigid bodies, SIGGRAPH 94, 23-34, Section 4 (4.3 the procedures compute-forces, drive-to-zero, fdirection and maxstep; 4.4 termination; 4.5 implementation) and Appendix A (Theorems 2 to 5)
  2. David Baraff, Analytical methods for dynamic simulation of non-penetrating rigid bodies, SIGGRAPH 89, 223-232, the contact force problem for resting contact
  3. David Baraff, Coping with friction for non-penetrating rigid body simulation, Computer Graphics 25(4), 31-41, 1991, the NP-hardness of consistent contact forces with Coulomb friction
  4. Richard W. Cottle, Jong-Shi Pang and Richard E. Stone, The Linear Complementarity Problem, SIAM Classics in Applied Mathematics, 2009, the chapters on pivoting methods and on the existence and uniqueness of LCP solutions

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.drives
  • a full proof of time.per_pivot_fresh_solve
  • a full proof of time.per_pivot_incremental
  • a full proof of space.matrix
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