Algorithmresearch
Stewart-Trinkle time stepping
Also called Anitescu-Potra time stepping, velocity-impulse time stepping.
A time-stepping method for rigid bodies with contact and Coulomb friction that solves one linear complementarity problem in impulses and velocities per step.
- Time
- O(n^3 + n^2 m + n m^2 + m^3 2^m) worstΘ(m^2) per_pivot
- Space
- Θ(n^2 + m^2) extra
- Where
- m = the number of LCP unknowns, c (k + 2) for c active contacts with k friction edges each; n = the number of generalized velocities
- Model
- Real RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David E. Stewart, Jeffrey C. Trinkle, 1996
Stewart-Trinkle time stepping simulates rigid bodies that touch each other or the ground with Coulomb friction. It does not compute contact forces and accelerations. Over each time step it computes contact impulses and the new velocity together, as the solution of one linear complementarity problem (LCP), and then it moves the bodies with the new velocity. Because impulses can be as large as needed, a step has a solution even in the cases of the Painlevé paradox, where the force and acceleration form of the rigid contact model has none.
In plain words
Think of a film of a box that slides on a floor, taken at a fixed number of frames per second. Between two frames, the program does not ask how hard the floor pushes at each instant. It asks a simpler question: how much total push did the floor give during this short time? The answer must obey three rules. The floor can only push, never pull. The floor pushes only where the box touches it, and only enough to stop the box from going into it. The sideways push from friction can be at most a fixed part of the upward push, and it acts against the sliding. The program finds the pushes that obey all three rules at once, updates the speed of the box, and moves it to the next frame. A short hard push is always allowed, so the program never gets stuck.
The problem
The system has the generalized coordinates , the generalized velocities , the mass matrix and the manipulator equation . All forces except the contact forces, that is the actuator forces, gravity and the velocity product terms, are collected in . Contact has a gap function , the distance between the two bodies along the contact normal, with when they do not overlap. The normal points into the body that receives the contact force.
The friction cone of contact is replaced by a polyhedral cone with edges. In generalized coordinates, is the row written as a column, and map to the tangential velocity of the contact point along the edge directions. The edges come in opposite pairs, so is even; in the plane . The matrices and have the and the as columns. is block diagonal with one column of ones of length per contact, and holds the friction coefficients.
An LCP with a square matrix and a vector asks for a vector with and for every . In words: each pair is nonnegative, and at least one member of the pair is 0.
Input: , , the step , the forces and the contact data. Output: and after one step, and the impulses (normal) and (friction, one per edge) that act in the step.
The algorithm
STEWART-TRINKLE-STEP(q, v, h)- 1
f ← τ - C(q, v) v - g(q) ▷ all forces but contact - 2
v* ← v + h M^-1 f ▷ the velocity without contact - 3
for each contact i with φ_i(q) ≤ ε do collect φ_i, n_i and d_i1, ..., d_ik - 4
A_GG ← G^T M^-1 G with G = [N D] - 5
A ← [A_GG, (0; E); (U, -E^T), 0] - 6
b ← (N^T v* + φ / h, D^T v*, 0) - 7
z = (c_n, β, λ) ← LEMKE(A, b) - 8
v+ ← v* + M^-1 (N c_n + D β) - 9
q+ ← q + h v+ SIMULATE(q, v, h, steps)- 10
repeat STEWART-TRINKLE-STEP steps times LEMKE(A, b)- 11
if b ≥ 0 then return z = 0 - 12
tableau [I | -A | -e | b] with the w variables in the basis - 13
r ← row of the smallest b_r (the last such row on ties); z0 enters - 14
loop - 15
pivot on row r and the entering column - 16
if the leaving variable is z0 then exit the loop - 17
entering ← the complement of the leaving variable - 18
r ← lexicographic minimum ratio row of the entering column - 19
if there is no such row then return RAY - 20
return z read from the basis
The matrix of line L5 written out is
The three block rows of are, by line L8, , and . So the three complementarity conditions say:
- , , and one of them is 0: the contact can only push, the gap at the end of the step is not negative to first order, and a contact that separates has no impulse.
- , , and one of them is 0: friction acts only along the edges against which the contact slides fastest, and is the slip speed.
- , , and one of them is 0: friction stays in the linearized cone, and it is on the boundary of the cone when the contact slides.
The term in line L6 is the position part. It lets a contact with a small positive gap close without an impulse, and it pushes out a contact that already overlaps. Without it, the LCP is the velocity form of Anitescu and Potra (1997). Line L3 takes every contact that is closer than a distance , so that a contact can become active within the step.
Lines L11 to L20 are Lemke's method for the LCP: line L12 adds an artificial variable with the covering vector of ones, which gives a first basis that is not negative, and the pivots of lines L15 to L18 move from one almost complementary basis to the next until leaves the basis. This page does not depend on Lemke's method; any LCP solver can replace line L7.
Example
A particle of mass 1 kg rests on the floor with , m/s and s. A horizontal force of 7 N pushes it. With one contact and the two friction edges , the LCP has the four unknowns . Line L2 gives m/s, and
Lemke's method takes four pivots:
| Pivot | Enters | Leaves | Basic values after the pivot |
|---|---|---|---|
| 1 | , , , | ||
| 2 | , , , | ||
| 3 | , , , | ||
| 4 | , , , |
So N s, which is the weight times , and N s : friction acts in the direction at its limit. Line L8 gives m/s, so the particle slides with the acceleration m/s, and m/s is its slip speed. With a push of 3 N in place of 7 N, the same LCP gives N s and : the particle sticks.
For a planar block of 2 kg, 0.4 m wide, sliding at 1 m/s on its two lower corners with and s, one step gives the normal impulses 0.07848 N s at the rear corner and 0.11772 N s at the front corner. Their sum is the weight times . The friction impulse is N s, and the speed falls to 0.96076 m/s.
Correctness
Every solution of the LCP satisfies discrete forms of the contact laws: the gap at the end of the step is not negative to first order, the impulse lies in the linearized friction cone, and friction maximizes the dissipation over that cone (it is the solution of a small linear program whose KKT conditions are the second and third complementarity conditions). If all active gaps are at least 0 at the start of the step, the contact impulses do not add kinetic energy: . Lemke's method with the lexicographic rule stops after a finite number of pivots, and when leaves the basis, the result solves the LCP. These are theorems; the proofs are in the correctness proof of this page.
Lemke's method can also stop on a ray, without a solution. For the velocity form without , Anitescu and Potra (1997) proved that a solution always exists and that Lemke's method finds it. With the gap term, Trinkle, Berard and Pang (2005) call the LCP nearly always solvable. As , the scheme converges, in the sense of measures, to a solution of the measure differential inclusion of rigid body motion with Coulomb friction (Stewart 1998); this is how the scheme resolves the Painlevé paradox.
Proof: A Stewart-Trinkle step obeys the discrete contact laws and does not add energyfull
We use the notation of the page. The system has the mass matrix , symmetric and positive definite, and the contacts with are active. Contact has the normal row , the friction edge directions , the impulses and , and the slack . and have these as columns, is the block diagonal matrix with one column of ones of length per contact, and . Let and, for a vector ,
The LCP of line L7 asks for with and , with and from lines L4 to L6.
Lemma 1 (the parts of ). For every ,
Proof. By lines L4 and L6, . In the same way, . The last row is line L5.
Theorem 1 (discrete contact laws). Let solve the LCP. Then for each active contact :
- (no penetration to first order) , and only if ;
- (friction cone) and , so the contact impulse lies in the linearized friction cone;
- (maximal dissipation) minimizes the power over all with ;
- (slip) if for some , then and .
Proof. Part 1 is and with Lemma 1, multiplied by . Part 2 is and .
For part 3, fix and write . The problem in part 3 is a linear program in . Its KKT conditions, with the multiplier of the constraint , are
By Lemma 1, these are exactly the rows of and for contact , with their complementarity. For a linear program the KKT conditions are sufficient for optimality, so is a minimizer.
For part 4, the first condition gives , and then the last condition gives . If , some , and for it ; with for all this is the maximum. If , all , and can be any value at least ; the claim about holds only up to this case.
Theorem 2 (no energy from the contacts). Let solve the LCP and assume that for every active contact. Then .
Proof. From ,
The last term is at least 0, so it is enough to show . Now . By Theorem 1, part 1, . By the complementarity of and and of and ,
The sum of these terms is .
The assumption is necessary. If a contact has at the start of the step, the term asks for a separating velocity, and the normal impulse then does positive work. This is the price of the gap term in line L6: it removes the drift into the ground but it can add energy.
Lemma 2 (Lemke's method ends). With the lexicographic ratio test of line L18, Lemke's method of lines L11 to L20 stops after a finite number of pivots, either with leaving the basis or on a ray.
Proof. If , line L11 returns , which solves the LCP. Otherwise the tableau of line L12 holds . After the pivot of line L13, and every basic variable is at least 0. Every later basis is almost complementary: it contains and, for every index but one, exactly one of and . The lexicographic ratio test keeps every row of the matrix lexicographically positive, and with it the leaving row of each pivot is unique (Cottle, Pang and Stone, Chapter 4). An almost complementary basis therefore has at most two neighbours on the path: the two pivots in which one member of the missing pair enters. The path enters through one and leaves through the other. The start has only one neighbour on the path, because the other direction from it is the primary ray. Suppose that a basis repeats, and take the first one that does. It is not the start, so it would have three different neighbours on the path: the one before its first visit, the one after it, and the one before its second visit. This is not possible, so no basis repeats. There are at most almost complementary bases, so the path is finite. It stops when line L19 finds no positive entry in the entering column, which is a ray, or when leaves at line L16.
Lemma 3 (the output solves the LCP). If leaves at line L16, the vector of line L20 solves the LCP.
Proof. After leaves, and the basis is complementary: for each exactly one of and is basic, and the nonbasic one is 0. All basic values are at least 0, because every pivot of the method keeps the right side nonnegative. So , and for every .
Existence. Lemke's method can end on a ray, and then it gives no solution. For the velocity form of the step, where has no term , Anitescu and Potra (1997) proved that the LCP always has a solution and that Lemke's method finds it. With the gap term of line L6, Trinkle, Berard and Pang (2005) describe the LCP as nearly always solvable, not always. The implementation raises an error on a ray.
Line L9. The new configuration is , a semi-implicit Euler step: the position update uses the new velocity. For a body that moves in a plane with this is exact for the coordinates. For a body in space, must be formed with the exponential map of the rotation; see the pitfalls on the page.
Cost. Lines L2 to L6 cost for velocities and unknowns, with a Cholesky factor of . Each pivot of Lemke's method updates a tableau of rows and columns in operations. By the proof of Lemma 2, the number of pivots is at most . Murty (1978) gave LCPs on which Lemke's method needs a number of pivots exponential in .
Complexity
In the real RAM, with velocities and active contacts with edges, the LCP has unknowns. Lines L2 to L6 cost with a Cholesky factor of , or when the bodies are free so that is block diagonal. Each pivot of Lemke's method costs . The number of pivots is at most , the number of almost complementary bases plus one, and it is exponential in for some LCPs (Murty 1978). In practice it is a small multiple of for the matrices of contact problems; this is an observation, not a bound. The extra space is .
Properties
- Impulses, not forces. The unknowns are impulses over the step. A step can stop a sliding body at once, which the force form cannot do.
- First order. The velocity update is a semi-implicit Euler step, so the global error is for smooth motion. Each impact is perfectly inelastic: the normal velocity after the impact is 0.
- Not unique. The LCP can have many solutions. For the block of the example at rest on two corners, the two friction impulses can push against each other by any amount that stays in the cones; the LCP for one step then has 17 basic solutions, but they all give the same . Uniqueness of is not a general property of the scheme.
- Linearized cone. The cone with edges is inside or outside the true circular cone, depending on how the edges are placed; in the plane with it is exact.
- The gap term can add energy. With an overlap , the term pushes the bodies apart with a velocity , and that adds kinetic energy.
Variants and improvements
- Anitescu and Potra (1997). The velocity form without in . Its LCP always has a solution and Lemke's method finds it. When the LCP with the gap term has no solution, a simulator can drop the gap term for that step and solve this one (Trinkle, Berard and Pang 2005).
- Nonlinear cone. A second-order cone in place of the polyhedral cone gives a nonlinear complementarity problem. Anitescu (2006) relaxed it to a convex cone program, which is solved by second-order cone programming.
- Iterative solvers. Physics engines often solve the LCP of a step approximately by projected Gauss-Seidel: they sweep over the contacts and solve one contact at a time. This is fast and robust but gives an approximate answer.
- Contact-implicit planning. Contact-implicit trajectory optimization uses the same complementarity constraints over a whole trajectory, as constraints of a nonlinear program.
When to use it
Use it to simulate robots, grasps and parts with many contacts and with friction, when the bodies may stick, slide, separate and collide, and when a fixed step is acceptable. It is a sound choice where the force and acceleration form has no solution or several, as in the Painlevé examples. If the contact set does not change, a smooth model with known constraint forces, for example the manipulator equation with fixed contacts, is cheaper and more accurate. For soft contacts, a penalty model with springs avoids the LCP, at the cost of stiff equations.
Pitfalls
- The sign of the edge directions. The friction edges must come in opposite pairs, so that friction can act in every tangent direction. With only , the contact can only be pushed one way.
- A large . Contacts far from touching enter the LCP. With the term , they stay free, but the LCP grows.
- Penetration drift without the gap term. The velocity form keeps only, so small overlaps add up over many steps. The term removes them, but it can add energy; some codes use a fraction of .
- Rotations in space. Line L9 is correct for coordinates such as in the plane. For a body in space, the orientation must be updated with the exponential map, not by adding to angles.
- Degenerate pivots. Contact LCPs are often degenerate, for example a block with four corners on the floor. Lemke's method without the lexicographic rule can then cycle.
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/stewart-trinkle-time-stepping/. The authors are listed in prov/EWJYN8.jsonl.
"""Stewart-Trinkle time stepping for one planar rigid body above the ground line y = 0.
The body has the generalized coordinates q = (x, y, theta): the position of its
center of mass in meters and its angle in radians. Its velocity is
v = (x', y', theta'). Contact points are given in body coordinates. Each contact
has a normal impulse c_n, two friction impulses beta (along +x and -x, so the
planar friction cone has k = 2 edges) and a slack lambda. One step solves one
linear complementarity problem (LCP) in these impulses with Lemke's method.
"""
import math
from itertools import product
PIVOT_TOL = 1e-12
def lemke(A, b, max_pivots=500):
"""Solve the LCP: find z >= 0 with w = A z + b >= 0 and z . w = 0.
Lemke's complementary pivoting method with the covering vector of ones and
the lexicographic ratio test. Returns z, or None when the method ends on a
secondary ray (then it gives no solution).
"""
m = len(b)
if all(bi >= 0.0 for bi in b): # @line L11
return [0.0] * m
# Tableau of w - A z - e z0 = b. Columns: w_0..w_(m-1), z_0..z_(m-1), z0, rhs.
cols = 2 * m + 2
T = []
for i in range(m): # @line L12
row = [0.0] * cols
row[i] = 1.0
for j in range(m):
row[m + j] = -A[i][j]
row[2 * m] = -1.0
row[2 * m + 1] = float(b[i])
T.append(row)
basis = list(range(m)) # basic variable of each row: index into the columns
z0 = 2 * m
# The first pivot: z0 enters, the row with the smallest b leaves.
# Among ties, the largest index keeps the tableau lexicographically positive.
r = 0
for i in range(m): # @line L13
if b[i] <= b[r]:
r = i
entering = z0
for _ in range(max_pivots): # @line L14
_pivot(T, r, entering) # @line L15
leaving = basis[r]
basis[r] = entering
if leaving == z0: # @line L16
break
entering = leaving + m if leaving < m else leaving - m # @line L17
r = _lex_ratio_row(T, entering, m) # @line L18
if r is None: # @line L19
return None
else:
return None
z = [0.0] * m
for i, var in enumerate(basis): # @line L20
if m <= var < 2 * m:
z[var - m] = max(T[i][-1], 0.0)
if z0 in basis and T[basis.index(z0)][-1] > 1e-9:
return None
return z
def _pivot(T, r, c):
"""Make column c a unit column with its 1 in row r."""
p = T[r][c]
T[r] = [t / p for t in T[r]]
for i in range(len(T)):
if i != r:
f = T[i][c]
if f != 0.0:
Ti, Tr = T[i], T[r]
T[i] = [a - f * bb for a, bb in zip(Ti, Tr)]
def _lex_ratio_row(T, c, m):
"""The leaving row for the entering column c, by the lexicographic minimum ratio test.
The rows compete on (rhs, B^-1 row) / T[i][c]; the columns of the w variables
hold B^-1. Returns None when no entry of column c is positive (a ray).
"""
best, best_key = None, None
for i in range(len(T)):
a = T[i][c]
if a > PIVOT_TOL:
key = [T[i][-1] / a] + [T[i][j] / a for j in range(m)]
if best is None or _lex_less(key, best_key):
best, best_key = i, key
return best
def _lex_less(u, v, tol=1e-11):
for a, bb in zip(u, v):
if a < bb - tol * (1.0 + abs(bb)):
return True
if a > bb + tol * (1.0 + abs(bb)):
return False
return False
class PlanarBody:
"""A rigid body in the plane: mass m (kg), inertia I about the center of mass
(kg m^2), friction coefficient mu, and contact points in body coordinates (m)."""
def __init__(self, m, I, mu, points):
self.m, self.I, self.mu = m, I, mu
self.points = [tuple(p) for p in points]
def minv(self):
return [1.0 / self.m, 1.0 / self.m, 1.0 / self.I]
def contact_data(q, p):
"""Gap phi, normal row n and tangent row d of the body point p at the configuration q.
phi = y + r_y is the height of the point. n = d phi / dq = (0, 1, r_x).
d = (1, 0, -r_y) maps v to the x velocity of the point.
"""
c, s = math.cos(q[2]), math.sin(q[2])
rx = c * p[0] - s * p[1]
ry = s * p[0] + c * p[1]
return q[1] + ry, [0.0, 1.0, rx], [1.0, 0.0, -ry]
def build_lcp(body, q, v, h, f_ext, eps):
"""Form the LCP of one step. Returns (A, b, v_star, cols, phis) where cols holds
the generalized directions of the impulse variables (normals, then friction edges)."""
minv = body.minv()
v_star = [v[i] + h * minv[i] * f_ext[i] for i in range(3)] # @line L2
N, D, phis = [], [], []
for p in body.points: # @line L3
phi, n, d = contact_data(q, p)
if phi <= eps:
N.append(n)
phis.append(phi)
D.append(d)
D.append([-x for x in d])
c = len(N)
if c == 0:
return None, None, v_star, [], []
G = N + D # the 3c directions of c_n and beta, as rows
def ip(a, bb): # a^T M^-1 b with a diagonal M
return sum(a[i] * minv[i] * bb[i] for i in range(3))
size = 4 * c
A = [[0.0] * size for _ in range(size)]
for i in range(3 * c): # @line L4
for j in range(3 * c):
A[i][j] = ip(G[i], G[j])
for i in range(c): # @line L5
A[c + 2 * i][3 * c + i] = 1.0 # E
A[c + 2 * i + 1][3 * c + i] = 1.0
A[3 * c + i][i] = body.mu # U
A[3 * c + i][c + 2 * i] = -1.0 # -E^T
A[3 * c + i][c + 2 * i + 1] = -1.0
b = [0.0] * size
for i in range(c): # @line L6
b[i] = sum(N[i][k] * v_star[k] for k in range(3)) + phis[i] / h
for j in range(2 * c):
b[c + j] = sum(D[j][k] * v_star[k] for k in range(3))
return A, b, v_star, G, phis
def velocity_from_impulses(body, v_star, G, z):
"""v+ = v* + M^-1 (N c_n + D beta)."""
minv = body.minv()
P = [0.0, 0.0, 0.0]
for i, g in enumerate(G):
for k in range(3):
P[k] += g[k] * z[i]
return [v_star[k] + minv[k] * P[k] for k in range(3)], P
def step(body, q, v, h, g=9.81, f_ext=None, eps=0.01):
"""One step of length h. f_ext is the applied generalized force (F_x, F_y, torque)
besides gravity. Returns (q_next, v_next, z) where z = (c_n, beta, lambda)."""
f = [0.0, -body.m * g, 0.0] # @line L1
if f_ext is not None:
f = [f[i] + f_ext[i] for i in range(3)]
A, b, v_star, G, _ = build_lcp(body, q, v, h, f, eps)
if A is None:
v_next, z = v_star, []
else:
z = lemke(A, b) # @line L7
if z is None:
raise ArithmeticError("Lemke's method ended on a ray")
v_next, _ = velocity_from_impulses(body, v_star, G, z) # @line L8
q_next = [q[k] + h * v_next[k] for k in range(3)] # @line L9
return q_next, v_next, z
def simulate(body, q, v, h, steps, g=9.81, f_ext=None, eps=0.01):
for _ in range(steps): # @line L10
q, v, _ = step(body, q, v, h, g, f_ext, eps)
return q, v
def lcp_residual(A, b, z):
"""The largest violation of z >= 0, w >= 0 and z_i w_i = 0."""
w = [sum(A[i][j] * z[j] for j in range(len(z))) + b[i] for i in range(len(b))]
r = 0.0
for zi, wi in zip(z, w):
r = max(r, -zi, -wi, abs(zi * wi))
return r
def solve_dense(A, rhs):
"""Gaussian elimination with partial pivoting. Returns None for a singular matrix."""
n = len(rhs)
M = [list(A[i]) + [rhs[i]] for i in range(n)]
for col in range(n):
p = max(range(col, n), key=lambda i: abs(M[i][col]))
if abs(M[p][col]) < 1e-12:
return None
M[col], M[p] = M[p], M[col]
for i in range(col + 1, n):
f = M[i][col] / M[col][col]
if f != 0.0:
for j in range(col, n + 1):
M[i][j] -= f * M[col][j]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
return x
def lcp_enumerate(A, b, tol=1e-9):
"""All solutions of the LCP with a nonsingular basis, by trying each of the 2^m
complementary cases: for each index, either z_i = 0 or w_i = 0."""
m = len(b)
sols = []
for pattern in product((0, 1), repeat=m):
S = [i for i in range(m) if pattern[i]]
z = [0.0] * m
if S:
zs = solve_dense([[A[i][j] for j in S] for i in S], [-b[i] for i in S])
if zs is None:
continue
for k, i in enumerate(S):
z[i] = zs[k]
if lcp_residual(A, b, z) <= tol:
sols.append(z)
return sols
test_stewart_trinkle_time_stepping.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stewart-trinkle-time-stepping/. The authors are listed in prov/EWJYN8.jsonl.
"""Tests of Stewart-Trinkle time stepping. Units are SI, g = 9.81 m/s^2.
The integration is the one of the scheme itself (a semi-implicit Euler step on
the velocity, then q+ = q + h v+), with the step h given in each test.
"""
import math
import random
from stewart_trinkle_time_stepping import (
PlanarBody,
build_lcp,
contact_data,
lcp_enumerate,
lcp_residual,
lemke,
simulate,
step,
velocity_from_impulses,
)
G = 9.81
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def random_lcp(rng, m, psd_only=False):
"""A = B B^T + 0.1 I plus a skew part: positive definite, so the LCP has one solution."""
B = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
S = [[0.0 if psd_only else rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
A = [[sum(B[i][k] * B[j][k] for k in range(m)) + (0.1 if i == j else 0.0) + S[i][j] - S[j][i]
for j in range(m)] for i in range(m)]
b = [rng.uniform(-1, 1) for _ in range(m)]
return A, b
def test_lemke_matches_enumeration_on_positive_definite_matrices():
rng = random.Random(7)
for _ in range(150):
A, b = random_lcp(rng, rng.randint(1, 5))
z = lemke(A, b)
sols = lcp_enumerate(A, b)
assert z is not None and len(sols) == 1
assert close(z, sols[0], 1e-8)
assert lcp_residual(A, b, z) < 1e-9
def test_lemke_trivial_and_ray_cases():
assert lemke([[2.0, 1.0], [1.0, 2.0]], [1.0, 0.0]) == [0.0, 0.0]
# w = -z - 1 >= 0 has no solution with z >= 0, so the method ends on a ray.
assert lemke([[-1.0]], [-1.0]) is None
# A degenerate case with equal entries of b: the lexicographic rule must not cycle.
z = lemke([[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [-1.0, -1.0, -1.0])
assert z is not None and lcp_residual([[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [-1.0, -1.0, -1.0], z) < 1e-12
def particle(mu=0.5, m=1.0):
return PlanarBody(m, 1.0, mu, [(0.0, 0.0)])
def test_particle_at_rest_gets_weight_impulse():
h = 0.01
q, v, z = step(particle(), [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], h)
assert close(v, [0.0, 0.0, 0.0], 1e-14)
assert abs(z[0] - G * h) < 1e-14 and abs(z[1]) < 1e-14 and abs(z[2]) < 1e-14
def test_stick_below_and_slip_above_the_friction_limit():
h, mu = 0.01, 0.5
# 3 N < mu m g = 4.905 N: the particle sticks, friction impulse 3 h opposes the push.
_, v, z = step(particle(mu), [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], h, f_ext=[3.0, 0.0, 0.0])
assert close(v, [0.0, 0.0, 0.0], 1e-14)
assert abs(z[2] - 3.0 * h) < 1e-14 and z[1] < 1e-14
# 7 N > 4.905 N: it slides with acceleration 7 - 4.905 = 2.095 m/s^2.
_, v, z = step(particle(mu), [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], h, f_ext=[7.0, 0.0, 0.0])
assert abs(v[0] - (7.0 - mu * G) * h) < 1e-12
assert abs(z[2] - mu * G * h) < 1e-12 and abs(z[3] - v[0]) < 1e-12
def test_sliding_particle_stops_at_the_closed_form_distance():
h, mu, v0 = 0.001, 0.5, 2.0
q, v = [0.0, 0.0, 0.0], [v0, 0.0, 0.0]
n = 0
while v[0] > 0.0:
q, v, _ = step(particle(mu), q, v, h)
n += 1
assert n == math.ceil(v0 / (mu * G * h))
# The exact stopping distance is v0^2 / (2 mu g) = 0.40775 m; the scheme is first order.
assert abs(q[0] - v0 * v0 / (2 * mu * G)) < v0 * h
assert abs(q[1]) < 1e-15
def test_falling_particle_lands_without_penetration_or_bounce():
p = particle()
q, v = [0.0, 0.1, 0.0], [0.3, 0.0, 0.0]
lowest = q[1]
for _ in range(300):
q, v, _ = step(p, q, v, 0.001)
lowest = min(lowest, q[1])
assert lowest > -1e-12
assert abs(v[1]) < 1e-12
def block(mu=0.4):
a, b = 0.2, 0.1 # half width and half height in m
m = 2.0
I = m * ((2 * a) ** 2 + (2 * b) ** 2) / 12.0
return PlanarBody(m, I, mu, [(-a, -b), (a, -b), (a, b), (-a, b)])
def test_block_at_rest_splits_its_weight():
h = 0.01
blk = block()
_, v, z = step(blk, [0.0, 0.1, 0.0], [0.0, 0.0, 0.0], h)
assert close(v, [0.0, 0.0, 0.0], 1e-13)
assert abs(z[0] - G * h) < 1e-12 and abs(z[1] - G * h) < 1e-12
def test_block_step_matches_enumeration_of_all_complementarity_cases():
rng = random.Random(3)
blk = block()
h = 0.01
for _ in range(25):
q = [0.0, 0.1, 0.0]
v = [rng.uniform(-1, 1), rng.uniform(-0.5, 0.0), rng.uniform(-1, 1)]
f = [rng.uniform(-10, 10), -blk.m * G, rng.uniform(-1, 1)]
A, b, v_star, cols, _ = build_lcp(blk, q, v, h, f, 0.01)
z = lemke(A, b)
assert z is not None and lcp_residual(A, b, z) < 1e-10
sols = lcp_enumerate(A, b)
assert any(close(z, s, 1e-8) for s in sols)
v_lemke, _ = velocity_from_impulses(blk, v_star, cols, z)
for s in sols:
assert close(velocity_from_impulses(blk, v_star, cols, s)[0], v_lemke, 1e-8)
def kinetic(body, v):
return 0.5 * (body.m * (v[0] ** 2 + v[1] ** 2) + body.I * v[2] ** 2)
def test_contact_impulses_lie_in_the_cone_and_remove_energy():
rng = random.Random(11)
blk = block()
h = 0.005
for _ in range(40):
# Every gap is at least 0 at the start of the step; the lemma needs this.
q = [0.0, 0.0, rng.uniform(-0.02, 0.02)]
lowest = min(contact_data(q, p)[0] for p in blk.points)
q[1] = -lowest + rng.uniform(0.0, 0.004)
v = [rng.uniform(-2, 2), rng.uniform(-2, 0.5), rng.uniform(-3, 3)]
f = [0.0, -blk.m * G, 0.0]
A, b, v_star, cols, phis = build_lcp(blk, q, v, h, f, 0.01)
if A is None:
continue
z = lemke(A, b)
c = len(phis)
for i in range(c):
assert z[i] >= 0.0
assert z[c + 2 * i] + z[c + 2 * i + 1] <= blk.mu * z[i] + 1e-12
v_next, _ = velocity_from_impulses(blk, v_star, cols, z)
assert kinetic(blk, v_next) <= kinetic(blk, v_star) + 1e-12
def test_painleve_rod_gets_an_impulsive_stop():
# A rod of length 1 m and mass 1 kg leans at theta = atan 2 with mu = 1.5 > 4/3.
# Its lower end slides away from the center at 1 m/s. The acceleration form has
# no solution here; the impulse form stops the end with an impulse near (0.4, 0.3) N s.
l, th = 0.5, math.atan(2.0)
rod = PlanarBody(1.0, (2 * l) ** 2 / 12.0, 1.5, [(-l, 0.0)])
q = [l * math.cos(th), l * math.sin(th), th]
v = [-1.0, 0.0, 0.0]
for h, tol in ((1e-3, 0.02), (1e-4, 0.002)):
A, b, v_star, cols, _ = build_lcp(rod, q, v, h, [0.0, -G, 0.0], 0.01)
z = lemke(A, b)
assert z is not None and lcp_residual(A, b, z) < 1e-12
v_next, _ = velocity_from_impulses(rod, v_star, cols, z)
_, n, d = contact_data(q, (-l, 0.0))
slip = sum(d[k] * v_next[k] for k in range(3))
assert abs(slip) < 1e-12
assert abs(z[0] - 0.3) < tol and abs(z[1] - z[2] - 0.4) < tol
def test_sliding_block_keeps_both_corners_down_and_stops():
blk = block(mu=0.3)
q, v = simulate(blk, [0.0, 0.1, 0.0], [1.5, 0.0, 0.0], 0.002, 400)
assert close(v, [0.0, 0.0, 0.0], 1e-9)
assert abs(q[2]) < 1e-9 and abs(q[1] - 0.1) < 1e-9
assert abs(q[0] - 1.5 ** 2 / (2 * 0.3 * G)) < 1.5 * 0.002
History
Stewart and Trinkle (1996) formulated rigid body dynamics with inelastic collisions and Coulomb friction as a time-stepping scheme in which each step solves a complementarity problem in impulses and velocities, and they showed that it has a solution where the force form does not. Anitescu and Potra (1997) gave the velocity form, and proved that its LCP is always solvable and that Lemke's method solves it. Stewart (1998) proved convergence of the time-stepping scheme as the step goes to 0, which resolved Painlevé's problem in the measure sense, and Stewart (2000) surveyed the field in SIAM Review. Lemke's method (1965) comes from the computation of equilibria of bimatrix games.
References
- David E. Stewart and Jeffrey C. Trinkle, An implicit time-stepping scheme for rigid body dynamics with inelastic collisions and Coulomb friction, International Journal for Numerical Methods in Engineering 39(15), 1996, pages 2673 to 2691
- Mihai Anitescu and Florian A. Potra, Formulating dynamic multi-rigid-body contact problems with friction as solvable linear complementarity problems, Nonlinear Dynamics 14(3), 1997, pages 231 to 247
- David E. Stewart, Rigid-body dynamics with friction and impact, SIAM Review 42(1), 2000, pages 3 to 39
- David E. Stewart and Jeffrey C. Trinkle, An implicit time-stepping scheme for rigid body dynamics with Coulomb friction, IEEE International Conference on Robotics and Automation, 2000, pages 162 to 169
- Carlton E. Lemke, Bimatrix equilibrium points and mathematical programming, Management Science 11(7), 1965, pages 681 to 689
- Richard W. Cottle, Jong-Shi Pang and Richard E. Stone, The Linear Complementarity Problem, SIAM Classics in Applied Mathematics 60, 2009, Chapter 4 (pivoting methods, Lemke's method and the lexicographic rule)
- David E. Stewart, Convergence of a time-stepping scheme for rigid-body dynamics and resolution of Painlevé's problem, Archive for Rational Mechanics and Analysis 145(3), 1998, pages 215 to 260
- Jeffrey C. Trinkle, Stephen Berard and Jong-Shi Pang, A time-stepping scheme for quasistatic multibody systems, IEEE International Symposium on Assembly and Task Planning, 2005, pages 174 to 181; Section 1.1 on the solvability of the Stewart-Trinkle and Anitescu-Potra LCPs
- Katta G. Murty, Computational complexity of complementary pivot methods, Mathematical Programming Study 7, 1978, pages 61 to 73
- Mihai Anitescu, Optimization-based simulation of nonsmooth rigid multibody dynamics, Mathematical Programming 105(1), 2006, pages 113 to 143
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 EWJYN8 Edit this page History Report an error Markdown