Algorithm Search⌘K

Techniqueadvanced

Optimization-based time integration

Also called variational implicit Euler.

Write a backward Euler step as the minimization of inertia plus potential energy and solve it with Newton's method, a descent test and a line search, so the objective never rises in a step.

Optimization time integration solves a backward Euler step as a minimization problem. The new positions are the minimizer of an objective EE, the sum of an inertia term and the potential energy, so a nonlinear solve becomes the search for a minimum. Gast and Schroeder (2014), and Gast, Schroeder, Stomakhin, Jiang and Teran (2015), solve it with Newton's method, a descent test and a line search. With these safeguards, EE cannot rise from one iteration to the next (proved), and in the tests below the solver reaches a lower EE at large time steps where plain Newton stalls or stops at a worse point (measured).

In plain words

An implicit step asks where the objects must be at the end of the step so that the forces and the change of velocity agree. You can turn this question into a landscape: one hill pulls each point toward where it would go if nothing pushed it, and the stored energy of the springs adds hills and valleys. The answer is the bottom of a valley. Plain Newton jumps toward a point where the ground is flat, which can be the top of a hill or a saddle. The safeguarded method checks that each jump goes downhill, and it shortens the jump until the ground is really lower. So it always walks down, even with large steps.

When it applies

  • Forces with a potential. The method needs a potential energy Φ\Phi with f=−∇Φf = -\nabla\Phi: elastic springs, hyperelastic finite elements, gravity and barrier contact. Damping and friction have no potential in general and need extra terms.
  • Large time steps. Backward Euler is stable for stiff systems, but each step is a nonlinear system. At large Δt\Delta t the start point is far from the solution, and plain Newton can fail (Section 2 of the 2014 paper shows this at Δt=1/24\Delta t = 1/24 s).
  • A bounded objective. The safeguards guarantee descent. They are useful when EE is bounded below, which is true for nonnegative elastic energies plus linear gravity (proved in proofs/correctness.md).
  • Inexact solves. The minimization form gives a measure of progress. A solve can stop after a few iterations and still have a lower EE than its start point.

The template

For a step from (xn,vn)(x_n, v_n) with mass matrix MM:

E(z)=12Δt2(z−x^)TM(z−x^)+Φ(z),x^=xn+Δt vn.E(z) = \frac{1}{2\Delta t^2}(z - \hat x)^T M (z - \hat x) + \Phi(z), \qquad \hat x = x_n + \Delta t\, v_n.

Its gradient is zero exactly at a backward Euler step M(vn+1−vn)=Δt f(xn+1)M(v_{n+1} - v_n) = \Delta t\, f(x_{n+1}) with vn+1=(xn+1−xn)/Δtv_{n+1} = (x_{n+1} - x_n)/\Delta t (proved).

  1. OTI-STEP(x, v, Δt)
  2. 1x̂ <- x + Δt v
  3. 2z <- x̂ + Δt² M⁻¹ f(x) ▷ the initial guess
  4. 3repeat up to max_iter times:
  5. 4g <- ∇E(z); H <- ∇²E(z)
  6. 5if |g| < τ: stop
  7. 6d <- the solution of H d = -g
  8. 7if d·g ≥ -κ |d| |g|: d <- -d; if still: d <- -g ▷ κ = 10⁻²
  9. 8if |d| > ℓ: d <- ℓ d / |d| ▷ ℓ = 10³
  10. 9t <- a step length with E(z + t d) ≤ E(z) + c t d·g
  11. 10z <- z + t d
  12. 11v <- (z - x) / Δt; x <- z

L7 to L9 are the safeguards of Section 3.1 of the 2014 paper. The paper solves L6 with conjugate gradients and uses a line search with the strong Wolfe conditions. The code solves L6 with a dense Gaussian elimination and uses Armijo backtracking with c=10−4c = 10^{-4}. It simulates a 2D chain of springs with gravity, with the first particle pinned. In floating point the code also stops when the predicted decrease −t d⋅g-t\, d \cdot g is below the rounding level of EE.

The proofs are in proofs/correctness.md. These are the claims:

  1. A point with ∇E=0\nabla E = 0 is a backward Euler step (proved).
  2. After L7 and L8 the direction goes downhill, d⋅g<0d \cdot g < 0 (proved).
  3. The line search ends, and EE does not rise from one iteration to the next (proved).
  4. For a quadratic Φ\Phi with a well conditioned HH, one iteration gives the exact step (proved). The test compares this with a direct linear solve.
  5. For a convex Φ\Phi, the exact step loses at least 12∣vn+1−vn∣M2\frac12 |v_{n+1} - v_n|_M^2 of total energy (proved). For a nonconvex Φ\Phi this is not guaranteed.
  6. With gravity only, the step is the symplectic Euler step (proved).

Classic examples

A falling chain (measured). A chain of 8 particles with spacing 0.1 m, stiffness 10410^4 and mass 0.1 starts horizontal at rest, hangs from its first particle and falls for 2 s, with τ=10−6\tau = 10^{-6}. The total energy 12vTMv+Φ\frac12 v^T M v + \Phi starts at 0.

1/Δt1/\Delta t energy at 1 s energy at 2 s steps where the energy rose largest iterations mean iterations
24 -2.000 -2.488 0 8 4.44
96 -1.010 -1.718 0 3 2.22
384 -0.402 -1.002 0 2 1.37

The energy falls more at larger Δt\Delta t, which is the numerical damping of backward Euler. The springs have a nonconvex energy, so claim 5 does not cover this chain; the decay here is measured. For linear springs (rest length zero, stiffness 100) at Δt=1/24\Delta t = 1/24 s, the smallest value of (En−En+1)−12∣vn+1−vn∣M2(\mathcal E_n - \mathcal E_{n+1}) - \frac12|v_{n+1} - v_n|_M^2 over 48 steps is 6.3×10−6≥06.3 \times 10^{-6} \ge 0, as claim 5 says.

Crumpled start points (measured). The same chain starts in a crumpled state: particle ii is at (0.02i+u,w)(0.02 i + u, w) with u,wu, w uniform in [−0.03,0.03][-0.03, 0.03], with seeds 0 to 5, and at rest. One step is solved with the safeguards and with plain Newton (full steps, no tests). The table gives the iterations and the final EE, and for plain Newton the number of iterations where EE rose.

Δt\Delta t seed start EE safeguarded plain Newton
1/24 0 3.6×1073.6 \times 10^7 15, 0.326 13, 0.326, 3 rises
1/24 1 2.3×1072.3 \times 10^7 34, 0.438 100, 0.603, 47 rises, no convergence
1/24 2 3.5×1073.5 \times 10^7 15, 0.219 69, 0.219, 32 rises
1/24 3 1.6×1071.6 \times 10^7 22, 0.517 71, 1.592, 32 rises
1/24 4 3.5×1073.5 \times 10^7 16, 0.272 15, 1.070, 7 rises
1/24 5 2.8×1072.8 \times 10^7 43, 0.414 19, 0.849, 7 rises
1 0 1.2×10131.2 \times 10^{13} 55, -2.679 5, 0.391, 2 rises
1 1 7.7×10127.7 \times 10^{12} 48, -1.362 5, 0.787, 2 rises
1 2 1.2×10131.2 \times 10^{13} 49, -0.977 5, 0.390, 2 rises
1 3 5.2×10125.2 \times 10^{12} 48, -1.349 6, 0.985, 3 rises
1 4 1.2×10131.2 \times 10^{13} 59, -2.684 7, -0.199, 3 rises
1 5 9.3×10129.3 \times 10^{12} 62, -2.496 6, 1.585, 3 rises

Plain Newton often converges to a stationary point with a higher EE, and in one case it does not converge in 100 iterations. The safeguarded solver never raises EE and always ends at an EE at most as high. Its end points are not always minima: the Hessian there is not always positive definite, so the method guarantees descent, not a minimum. For seed 1 at Δt=1/24\Delta t = 1/24 s it stopped at the rounding level with ∣∇E∣=1.6×10−6|\nabla E| = 1.6 \times 10^{-6}, just above τ\tau.

Methods that minimize the same objective. Fast mass springs and projective dynamics minimize EE with a local step and a global linear solve. Vertex block descent minimizes it one vertex at a time. Incremental potential contact adds a barrier on distances to EE and caps each step by a collision check, and affine body dynamics does the same for stiff bodies.

Variations

  • Krylov solves. For large systems L6 uses conjugate gradients with a tolerance tied to ∣∇E∣|\nabla E|, and on an indefinite HH it returns its last iterate (Section 3.1 of the 2014 paper).
  • Hessian projection. Many codes project the Hessian of each element to a positive semidefinite matrix. Then HH is positive definite and the Newton direction always goes downhill (proved as for claim 4), so only the angle test of L7 can still reject it.
  • Quasi-Newton solvers. L-BFGS needs only gradients and works with the same line search.
  • Other integrators. The implicit midpoint rule is also a minimization: its midpoint y=(xn+xn+1)/2y = (x_n + x_{n+1})/2 minimizes 2Δt2∣y−xn−Δt2vn∣M2+Φ(y)\frac{2}{\Delta t^2}|y - x_n - \frac{\Delta t}{2} v_n|_M^2 + \Phi(y) (proved by the same calculation as claim 1).
  • Constraints and contact. Contact can enter the minimization as constraints, as penalty terms or as barrier terms. IPC uses a barrier.

Pitfalls

  • A stationary point is not a minimum. Plain Newton finds any point with ∇E=0\nabla E = 0, and at large steps this can be a saddle (the table). Do not take ∇E=0\nabla E = 0 as a proof that the state is good.
  • Rounding limits the tolerance. When ∣∇E∣|\nabla E| is small, the change of EE in a step can be below the rounding level of EE, and the line search then cannot see a decrease. Choose τ\tau relative to the scale of the forces, and stop when the predicted decrease is below rounding.
  • Nonsmooth energies. A spring with a positive rest length has no gradient at length zero. A line search near such a point can stall.
  • Numerical damping. Backward Euler removes energy, more at larger Δt\Delta t (the first table). The minimization form does not change this.
  • Forces without a potential. Damping, friction and some follower forces have no potential. They need a separate treatment, often with lagged terms.

Code

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.

optimization_time_integration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimization-time-integration/. The authors are listed in prov/VE7FP8.jsonl.

"""Optimization time integration (Gast, Schroeder, Stomakhin, Jiang and Teran 2015) on a 2D spring chain.

The backward Euler step x_{n+1} = x_n + dt v_{n+1}, M (v_{n+1} - v_n) = dt f(x_{n+1})
is the minimizer of

    E(x) = 1/(2 dt^2) (x - xh)^T M (x - xh) + Phi(x),  xh = x_n + dt v_n,

where Phi is the potential energy, here springs plus gravity. The solver is
Newton's method with the safeguards of Section 3.1 of Gast and Schroeder
(2014): stop when |grad E| < tau; if the Newton direction d is not clearly
downhill (d . g >= -kappa |d| |g|, kappa = 1e-2), try -d, and else use -g;
clamp the length of d; then do a line search. The paper uses conjugate
gradients and a strong Wolfe line search; this code uses a dense solve and a
backtracking Armijo line search.
"""

import math

GRAVITY = (0.0, -9.81)


def gauss_solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting. Return None if a is singular."""
    n = len(b)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) < 1e-300:
            return None
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                for k in range(c, n + 1):
                    m[r][k] -= f * m[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))) / m[r][r]
    return x


class Chain:
    def __init__(self, rest, springs, masses, pinned=(), gravity=GRAVITY):
        """springs are tuples (a, b, rest_length, stiffness). rest_length 0 gives a linear spring."""
        self.rest = [tuple(p) for p in rest]
        self.springs = [tuple(s) for s in springs]
        self.mass = list(masses)
        self.pinned = set(pinned)
        self.free = [i for i in range(len(rest)) if i not in self.pinned]
        self.col = {v: k for k, v in enumerate(self.free)}
        self.g = gravity


def potential(ch, x):
    e = 0.0
    for a, b, r, k in ch.springs:
        e += 0.5 * k * (math.dist(x[a], x[b]) - r) ** 2
    for i in ch.free:
        e -= ch.mass[i] * (ch.g[0] * x[i][0] + ch.g[1] * x[i][1])
    return e


def potential_grad_hess(ch, x):
    """The gradient and Hessian of Phi on the free coordinates (no projection)."""
    nf = 2 * len(ch.free)
    g = [0.0] * nf
    h = [[0.0] * nf for _ in range(nf)]
    for i in ch.free:
        g[2 * ch.col[i]] -= ch.mass[i] * ch.g[0]
        g[2 * ch.col[i] + 1] -= ch.mass[i] * ch.g[1]
    for a, b, r, k in ch.springs:
        dx, dy = x[a][0] - x[b][0], x[a][1] - x[b][1]
        ln = math.hypot(dx, dy)
        if r == 0.0:
            gs = (k * dx, k * dy)
            blk = [[k, 0.0], [0.0, k]]
        else:
            n = (dx / ln, dy / ln)
            gs = (k * (ln - r) * n[0], k * (ln - r) * n[1])
            s = 1.0 - r / ln
            blk = [[k * (n[p] * n[q] + s * ((1.0 if p == q else 0.0) - n[p] * n[q])) for q in range(2)] for p in range(2)]
        for v, sv in ((a, 1.0), (b, -1.0)):
            if v not in ch.col:
                continue
            for p in range(2):
                g[2 * ch.col[v] + p] += sv * gs[p]
            for u, su in ((a, 1.0), (b, -1.0)):
                if u in ch.col:
                    for p in range(2):
                        for q in range(2):
                            h[2 * ch.col[v] + p][2 * ch.col[u] + q] += sv * su * blk[p][q]
    return g, h


def objective(ch, x, xh, dt):
    e = potential(ch, x)
    for i in ch.free:
        e += ch.mass[i] / (2.0 * dt * dt) * ((x[i][0] - xh[i][0]) ** 2 + (x[i][1] - xh[i][1]) ** 2)
    return e


def objective_grad_hess(ch, x, xh, dt):
    g, h = potential_grad_hess(ch, x)
    for i in ch.free:
        c = ch.mass[i] / (dt * dt)
        for d in range(2):
            r = 2 * ch.col[i] + d
            g[r] += c * (x[i][d] - xh[i][d])
            h[r][r] += c
    return g, h


def moved(ch, x, d, t):
    y = list(x)
    for i in ch.free:
        c = ch.col[i]
        y[i] = (x[i][0] + t * d[2 * c], x[i][1] + t * d[2 * c + 1])
    return y


def oti_step(ch, x, v, dt, tau=1e-6, kappa=1e-2, max_len=1e3, max_iter=100, safeguards=True, history=None):
    """One backward Euler step by minimizing E with safeguarded Newton. Return (x, v, iterations)."""
    xh = [(p[0] + dt * u[0], p[1] + dt * u[1]) if i in ch.col else tuple(p)
          for i, (p, u) in enumerate(zip(x, v))]  # @line L1
    g0, _ = potential_grad_hess(ch, x)
    z = moved(ch, xh, [-dt * dt * gi / ch.mass[ch.free[k // 2]] for k, gi in enumerate(g0)], 1.0)  # @line L2
    e = objective(ch, z, xh, dt)
    if history is not None:
        history.append(e)
    it = 0
    while it < max_iter:  # @line L3
        g, h = objective_grad_hess(ch, z, xh, dt)  # @line L4
        gn = math.sqrt(sum(c * c for c in g))
        if gn < tau:  # @line L5
            break
        d = gauss_solve(h, [-c for c in g])  # @line L6
        if safeguards:
            if d is None:
                d = [-c for c in g]
            dn = math.sqrt(sum(c * c for c in d))
            if sum(a * b for a, b in zip(d, g)) >= -kappa * dn * gn:  # @line L7
                d = [-c for c in d]
                if sum(a * b for a, b in zip(d, g)) >= -kappa * dn * gn:
                    d = [-c for c in g]
            dn = math.sqrt(sum(c * c for c in d))
            if dn > max_len:  # @line L8
                d = [c * max_len / dn for c in d]
            slope = sum(a * b for a, b in zip(d, g))
            if -slope <= 1e-15 * (1.0 + abs(e)):
                break  # the predicted decrease is below the rounding level of E
            t = 1.0
            while True:  # @line L9
                trial = moved(ch, z, d, t)
                et = objective(ch, trial, xh, dt)
                if et <= e + 1e-4 * t * slope or t < 1e-14:
                    break
                t *= 0.5
            if t < 1e-14:
                break  # no sufficient decrease is possible at the level of rounding: keep z
        else:
            if d is None:
                break
            trial = moved(ch, z, d, 1.0)
            et = objective(ch, trial, xh, dt)
        z, e = trial, et  # @line L10
        if history is not None:
            history.append(e)
        it += 1
    v_new = [((a[0] - b[0]) / dt, (a[1] - b[1]) / dt) for a, b in zip(z, x)]  # @line L11
    return z, v_new, it


def total_energy(ch, x, v):
    return potential(ch, x) + sum(0.5 * ch.mass[i] * (v[i][0] ** 2 + v[i][1] ** 2) for i in ch.free)


def hanging_chain(count, spacing, stiffness, mass, rest_zero=False):
    """A horizontal chain pinned at particle 0. rest_zero gives linear springs (a convex potential)."""
    rest = [(i * spacing, 0.0) for i in range(count)]
    r = 0.0 if rest_zero else spacing
    springs = [(i, i + 1, r, stiffness) for i in range(count - 1)]
    return Chain(rest, springs, [mass] * count, pinned=[0])
test_optimization_time_integration.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimization-time-integration/. The authors are listed in prov/VE7FP8.jsonl.

"""Tests of optimization time integration: derivatives, a linear reference, monotone Newton and energy behaviour."""

import random

import optimization_time_integration as ot


def central_grad(f, x, h=1e-6):
    out = []
    for i in range(len(x)):
        a, b = list(x), list(x)
        a[i] += h
        b[i] -= h
        out.append((f(a) - f(b)) / (2 * h))
    return out


def flat(ch, x):
    return [c for i in ch.free for c in x[i]]


def unflat(ch, z, x):
    y = list(x)
    for k, i in enumerate(ch.free):
        y[i] = (z[2 * k], z[2 * k + 1])
    return y


def crumpled(seed):
    rng = random.Random(seed)
    ch = ot.hanging_chain(8, 0.1, 1e4, 0.1)
    x0 = [(0.0, 0.0)] + [(0.02 * i + rng.uniform(-0.03, 0.03), rng.uniform(-0.03, 0.03)) for i in range(1, 8)]
    return ch, x0


def test_example_one_spring_is_backward_euler():
    m, k, r, dt = 1.0, 100.0, 1.0, 0.1
    ch = ot.Chain([(0.0, 0.0), (1.5, 0.0)], [(0, 1, r, k)], [m, m], pinned=[0], gravity=(0.0, 0.0))
    x1, v1, _ = ot.oti_step(ch, [(0.0, 0.0), (1.5, 0.0)], [(0.0, 0.0)] * 2, dt, tau=1e-12)
    assert abs(x1[1][0] - 1.25) < 1e-12 and abs(x1[1][1]) < 1e-14 and abs(v1[1][0] + 2.5) < 1e-10


def test_gradient_and_hessian_against_central_differences():
    ch, x = crumpled(9)
    dt = 1.0 / 24.0
    xh = [(p[0] + 0.01, p[1] - 0.02) for p in x]
    g, h = ot.objective_grad_hess(ch, x, xh, dt)
    z0 = flat(ch, x)
    ng = central_grad(lambda z: ot.objective(ch, unflat(ch, z, x), xh, dt), z0)
    assert max(abs(a - b) for a, b in zip(g, ng)) < 1e-5 * max(abs(c) for c in g)
    for r in range(len(z0)):
        col = central_grad(lambda z, r=r: ot.objective_grad_hess(ch, unflat(ch, z, x), xh, dt)[0][r], z0)
        assert max(abs(col[c] - h[r][c]) for c in range(len(z0))) < 1e-4 * max(1.0, max(map(abs, h[r])))


def test_linear_springs_match_a_direct_linear_solve():
    """With zero rest lengths the step solves (M / dt^2 + K) x = M / dt^2 xh + f; the reference builds K by hand."""
    n, k, m, dt = 6, 50.0, 0.2, 0.05
    ch = ot.hanging_chain(n, 0.1, k, m, rest_zero=True)
    rng = random.Random(3)
    x0 = [(0.0, 0.0)] + [(0.1 * i + rng.uniform(-0.02, 0.02), rng.uniform(-0.02, 0.02)) for i in range(1, n)]
    v0 = [(0.0, 0.0)] + [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(1, n)]
    x1, _, _ = ot.oti_step(ch, x0, v0, dt, tau=1e-12)
    f = n - 1
    lap = [[0.0] * f for _ in range(f)]
    for i in range(1, n):
        lap[i - 1][i - 1] += k * (1 if i == n - 1 else 2)
        if i + 1 < n:
            lap[i - 1][i] -= k
            lap[i][i - 1] -= k
    for d, gd in ((0, 0.0), (1, -9.81)):
        a = [[lap[r][c] + (m / dt ** 2 if r == c else 0.0) for c in range(f)] for r in range(f)]
        rhs = [m / dt ** 2 * (x0[i][d] + dt * v0[i][d]) + m * gd for i in range(1, n)]
        rhs[0] += k * x0[0][d]
        sol = ot.gauss_solve(a, rhs)
        assert max(abs(sol[i - 1] - x1[i][d]) for i in range(1, n)) < 1e-12


def test_safeguarded_newton_never_increases_the_objective():
    for seed in range(4):
        for dt in (1.0 / 24.0, 1.0):
            ch, x0 = crumpled(seed)
            hist = []
            ot.oti_step(ch, x0, [(0.0, 0.0)] * 8, dt, history=hist)
            assert all(b <= a for a, b in zip(hist, hist[1:]))


def test_plain_newton_can_increase_the_objective_and_stop_higher():
    """Measured: from a crumpled start, unguarded Newton raises E and ends at a higher stationary value."""
    ch, x0 = crumpled(0)
    h1, h2 = [], []
    ot.oti_step(ch, x0, [(0.0, 0.0)] * 8, 1.0, history=h1)
    ot.oti_step(ch, x0, [(0.0, 0.0)] * 8, 1.0, safeguards=False, history=h2)
    assert any(b > a for a, b in zip(h2, h2[1:]))
    assert h1[-1] < h2[-1] - 1.0


def test_convex_potential_energy_inequality():
    """For a convex potential, the exact step satisfies E_n - E_(n+1) >= 1/2 |v_(n+1) - v_n|_M^2."""
    ch = ot.hanging_chain(8, 0.1, 100.0, 0.1, rest_zero=True)
    x, v = list(ch.rest), [(0.0, 0.0)] * 8
    for _ in range(48):
        e0 = ot.total_energy(ch, x, v)
        x1, v1, _ = ot.oti_step(ch, x, v, 1.0 / 24.0, tau=1e-10)
        dv = 0.5 * sum(ch.mass[i] * ((v1[i][0] - v[i][0]) ** 2 + (v1[i][1] - v[i][1]) ** 2) for i in ch.free)
        assert e0 - ot.total_energy(ch, x1, v1) >= dv - 1e-9
        x, v = x1, v1


def test_nonconvex_chain_energy_does_not_rise_here():
    """Measured: a falling chain with rest lengths loses energy at every step at dt = 1/24 s."""
    ch = ot.hanging_chain(8, 0.1, 1e4, 0.1)
    x, v = list(ch.rest), [(0.0, 0.0)] * 8
    prev = ot.total_energy(ch, x, v)
    for _ in range(48):
        x, v, _ = ot.oti_step(ch, x, v, 1.0 / 24.0)
        e = ot.total_energy(ch, x, v)
        assert e <= prev + 1e-9
        prev = e


def test_free_fall_is_symplectic_euler():
    ch = ot.Chain([(0.0, 0.0)], [], [1.0])
    x, v = [(0.0, 0.0)], [(0.0, 0.0)]
    for _ in range(10):
        x, v, _ = ot.oti_step(ch, x, v, 0.1)
    assert abs(x[0][1] + 5.3955) < 1e-12

Exercises

  1. Show that ∇E(z)=0\nabla E(z) = 0 is the same as M(vn+1−vn)=Δt f(xn+1)M(v_{n+1} - v_n) = \Delta t\, f(x_{n+1}) with vn+1=(z−xn)/Δtv_{n+1} = (z - x_n)/\Delta t.
  2. For one particle of mass mm on a spring of stiffness kk and rest length rr to a pinned point, compute the step from xn>rx_n > r at rest. Check with m=1m = 1, k=100k = 100, r=1r = 1, xn=1.5x_n = 1.5 and Δt=0.1\Delta t = 0.1 that xn+1=1.25x_{n+1} = 1.25.
  3. Show that the direction −g-g at L7 passes the test of L7 for every κ<1\kappa < 1.
  4. Show that a Newton direction with a positive definite HH passes the test of L7 when the condition number of HH is smaller than 1/κ1/\kappa.
  5. Find a 1D potential Φ\Phi and a start point where a full Newton step raises EE.
  6. Prove that for a convex Φ\Phi the total energy does not rise in an exact backward Euler step.
Proof: Correctness of optimization time integrationfull

Let MM be the diagonal mass matrix of the free coordinates, Φ\Phi the potential energy (springs plus gravity), x^=xn+Δt vn\hat x = x_n + \Delta t\, v_n, and

E(z)=12Δt2(z−x^)TM(z−x^)+Φ(z).E(z) = \frac{1}{2\Delta t^2}(z - \hat x)^T M (z - \hat x) + \Phi(z).

The step returns xn+1=zx_{n+1} = z and vn+1=(z−xn)/Δtv_{n+1} = (z - x_n)/\Delta t. Lines L1 to L11 refer to the template on the page. We assume that Φ\Phi is differentiable at every iterate (for springs with a positive rest length this means that no spring has length zero).

Lemma 1 (stationary points are backward Euler steps). ∇E(z)=0\nabla E(z) = 0 if and only if (xn+1,vn+1)=(z,(z−xn)/Δt)(x_{n+1}, v_{n+1}) = (z, (z - x_n)/\Delta t) satisfies xn+1=xn+Δt vn+1x_{n+1} = x_n + \Delta t\, v_{n+1} and M(vn+1−vn)=−Δt ∇Φ(xn+1)M(v_{n+1} - v_n) = -\Delta t\, \nabla\Phi(x_{n+1}).

Proof. The first equation holds by the definition of vn+1v_{n+1}. Then z−x^=Δt(vn+1−vn)z - \hat x = \Delta t(v_{n+1} - v_n), so ∇E(z)=M(vn+1−vn)/Δt+∇Φ(z)\nabla E(z) = M(v_{n+1} - v_n)/\Delta t + \nabla\Phi(z). This is zero exactly when the second equation holds. □\square

Lemma 2 (E is bounded below). If every spring energy is nonnegative and gravity is linear, EE is bounded below on the free coordinates.

Proof. The spring terms are at least 00. The rest is 12Δt2(z−x^)TM(z−x^)−∑imi g⋅zi\frac{1}{2\Delta t^2}(z - \hat x)^T M (z - \hat x) - \sum_i m_i\, g \cdot z_i, a strictly convex quadratic because MM is positive definite, and a strictly convex quadratic has a finite minimum. □\square

Lemma 3 (the direction is downhill). Let g=∇E(z)≠0g = \nabla E(z) \neq 0 and 0<κ<10 < \kappa < 1. After L7 and L8, the direction dd satisfies d⋅g<0d \cdot g < 0.

Proof. If the Newton direction passes the test d⋅g<−κ∣d∣∣g∣d \cdot g < -\kappa |d||g|, then d⋅g<0d \cdot g < 0. Otherwise L7 tries −d-d, and if it passes, the same bound holds for −d-d. If both fail, or if HH is singular, L7 uses d=−gd = -g, and d⋅g=−∣g∣2<0d \cdot g = -|g|^2 < 0. L8 multiplies dd by a positive number, which keeps the sign of d⋅gd \cdot g. □\square

Lemma 4 (the line search ends). If d⋅g<0d \cdot g < 0 and EE is differentiable at zz, then for each c∈(0,1)c \in (0, 1) there is t0>0t_0 > 0 with E(z+td)≤E(z)+c t d⋅gE(z + t d) \le E(z) + c\, t\, d \cdot g for all t∈(0,t0]t \in (0, t_0]. So backtracking by halves from t=1t = 1 stops after a finite number of halvings.

Proof. By differentiability, E(z+td)=E(z)+t d⋅g+o(t)E(z + t d) = E(z) + t\, d \cdot g + o(t). Since (1−c) d⋅g<0(1 - c)\, d \cdot g < 0, the term o(t)o(t) is smaller than −(1−c) t d⋅g-(1 - c)\, t\, d \cdot g for all small tt, which gives the inequality. □\square

In floating point the code also stops the search at t<10−14t < 10^{-14} and then keeps zz without an update.

Theorem 5 (the objective never rises). With the safeguards, the values of EE at the accepted iterates do not increase.

Proof. An iterate is accepted at L10 only after the Armijo test E(z+td)≤E(z)+10−4 t d⋅gE(z + t d) \le E(z) + 10^{-4}\, t\, d \cdot g with t>0t > 0. By Lemma 3, d⋅g<0d \cdot g < 0, so E(z+td)<E(z)E(z + t d) < E(z). When the test is not met, the code stops and keeps zz, so no step raises EE. □\square

Corollary 6. By Lemma 2 and Theorem 5, the values of EE at the iterates converge. This does not prove that ∇E\nabla E goes to zero: the spring energy with a positive rest length is not differentiable at length zero, so the usual global convergence theorems for line search methods do not apply without more assumptions.

Theorem 7 (one Newton step solves a quadratic step). Let Φ\Phi be a quadratic with a positive semidefinite Hessian KK (springs with rest length zero plus gravity), and let H=M/Δt2+KH = M/\Delta t^2 + K have the condition number λmax⁡/λmin⁡<1/κ\lambda_{\max}/\lambda_{\min} < 1/\kappa. Then the first iteration takes the full Newton step and ends at the exact minimizer of EE.

Proof. HH is positive definite, so d=−H−1gd = -H^{-1} g exists. Then −d⋅g=gTH−1g≥∣g∣2/λmax⁡-d \cdot g = g^T H^{-1} g \ge |g|^2/\lambda_{\max} and ∣d∣≤∣g∣/λmin⁡|d| \le |g|/\lambda_{\min}, so −d⋅g≥(λmin⁡/λmax⁡)∣d∣∣g∣>κ∣d∣∣g∣-d \cdot g \ge (\lambda_{\min}/\lambda_{\max}) |d||g| > \kappa |d||g| and L7 keeps dd. Since EE is quadratic, E(z+d)=E(z)+d⋅g+12dTHd=E(z)+12d⋅gE(z + d) = E(z) + d \cdot g + \frac12 d^T H d = E(z) + \frac12 d \cdot g, which meets the Armijo test with c=10−4≤12c = 10^{-4} \le \frac12, so t=1t = 1. The point z+dz + d has ∇E=g+Hd=0\nabla E = g + H d = 0, and it is the unique minimizer because HH is positive definite. (L8 can shorten dd only if ∣d∣>ℓ|d| > \ell; with ℓ=103\ell = 10^3 this does not occur in the tests.) □\square

Corollary 8 (free fall is symplectic Euler). If Φ\Phi is only gravity, the initial guess at L2 is z=x^+Δt2gz = \hat x + \Delta t^2 g, and ∇E(z)=M(z−x^)/Δt2−Mg=0\nabla E(z) = M(z - \hat x)/\Delta t^2 - M g = 0, so L5 stops at once. Then vn+1=vn+Δt gv_{n+1} = v_n + \Delta t\, g and xn+1=xn+Δt vn+1x_{n+1} = x_n + \Delta t\, v_{n+1}, which is the symplectic Euler step. After 10 steps of 0.10.1 from rest, y=−9.81⋅0.01⋅(1+2+⋯+10)=−5.3955y = -9.81 \cdot 0.01 \cdot (1 + 2 + \cdots + 10) = -5.3955. □\square

Theorem 9 (energy decay for a convex potential). Let Φ\Phi be convex and differentiable and let (xn+1,vn+1)(x_{n+1}, v_{n+1}) be an exact backward Euler step. With E=12vTMv+Φ(x)\mathcal E = \frac12 v^T M v + \Phi(x),

En−En+1≥12(vn+1−vn)TM(vn+1−vn).\mathcal E_n - \mathcal E_{n+1} \ge \tfrac12 (v_{n+1} - v_n)^T M (v_{n+1} - v_n).

Proof. Write v0=vnv_0 = v_n, v1=vn+1v_1 = v_{n+1}, x0=xnx_0 = x_n, x1=xn+1x_1 = x_{n+1}. By Lemma 1, M(v1−v0)=−Δt ∇Φ(x1)M(v_1 - v_0) = -\Delta t\, \nabla\Phi(x_1). The identity 12v1TMv1−12v0TMv0=v1TM(v1−v0)−12(v1−v0)TM(v1−v0)\frac12 v_1^T M v_1 - \frac12 v_0^T M v_0 = v_1^T M (v_1 - v_0) - \frac12 (v_1 - v_0)^T M (v_1 - v_0) and Δt v1=x1−x0\Delta t\, v_1 = x_1 - x_0 give

K1−K0=−∇Φ(x1)⋅(x1−x0)−12(v1−v0)TM(v1−v0).K_1 - K_0 = -\nabla\Phi(x_1) \cdot (x_1 - x_0) - \tfrac12 (v_1 - v_0)^T M (v_1 - v_0).

Convexity gives Φ(x0)≥Φ(x1)+∇Φ(x1)⋅(x0−x1)\Phi(x_0) \ge \Phi(x_1) + \nabla\Phi(x_1) \cdot (x_0 - x_1), that is −∇Φ(x1)⋅(x1−x0)≤Φ(x0)−Φ(x1)-\nabla\Phi(x_1) \cdot (x_1 - x_0) \le \Phi(x_0) - \Phi(x_1). Adding Φ(x1)−Φ(x0)\Phi(x_1) - \Phi(x_0) to both sides of the identity gives the claim. □\square

The theorem needs convexity. Springs with a positive rest length have a nonconvex energy (the energy of a spring is not convex when it is compressed), so for them the decay of E\mathcal E is only measured, not proved. The code stops at ∣∇E∣<τ|\nabla E| < \tau, so it satisfies the inequality only up to a term of order τ\tau; the test allows 10−910^{-9}.

References

  1. Theodore Gast, Craig Schroeder, Alexey Stomakhin, Chenfanfu Jiang and Joseph Teran, Optimization integrator for large time steps, IEEE Transactions on Visualization and Computer Graphics 21(10), 2015, 1103 to 1115, the minimization form of backward Euler and the safeguarded Newton method, extended to the material point method for snow (general locator)
  2. Theodore Gast and Craig Schroeder, Optimization integrator for large time steps, Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2014), 31 to 40, Section 2 (backward Euler and the failure of plain Newton at large steps, Figures 3, 4 and 7), Section 2.1 (the objective E), Section 3.1 (the Newton steps, the descent test with kappa = 10^-2, the length clamp and the line search)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/VE7FP8/proof-correctness.yaml
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
  • three classic examples