Algorithmcore
Newmark-beta method
Also called Newmark method.
Steps M a + C v + K d = F in time with parameters beta and gamma. beta = 1/4, gamma = 1/2 is second order and unconditionally stable for linear problems only.
- Time
- Θ(n b^2 + m n b) worst
- Space
- Θ(n b) extra
- Where
- b = the half bandwidth of the effective matrix; m = the number of time steps; n = the number of unknowns
- Model
- Real RAM
- Properties
- deterministicone step
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nathan M. Newmark, 1959
The Newmark-beta method is a one-step time integrator for the second order equations of structural dynamics , which come from a finite element discretization in space. It advances displacement , velocity and acceleration with two parameters and : gives second order accuracy, gives the explicit central difference method, and , gives the implicit average acceleration rule, which is unconditionally stable and conserves the energy exactly for linear undamped problems. Unconditional stability is a property of linear problems: for nonlinear problems the same rule can let the energy grow. Graphics simulators of cloth and soft bodies often step with backward Euler, which is stable but damps every motion strongly, and Newmark with adds second order accuracy and no artificial damping at the price of the same one linear solve per step.
In plain words
A vibrating structure moves, so its position, its speed and its rate of change of speed change at every instant. A computer can only look at the structure at separate moments, a small time apart. The Newmark method gets the next position and speed from the current ones and from a guess about how the speed changes during the step. One setting assumes that the rate of change of speed is the average of its values at the start and the end of the step. This setting never blows up for a linear structure, whatever the size of the step, and it keeps the energy of a free vibration exactly. Another setting uses only the start values. That one is cheap, but it fails when the step is too long compared with the fastest vibration.
The problem
Input. A symmetric positive definite mass matrix , a damping matrix and a stiffness matrix , all , a load , initial values and , a time step and a number of steps . On finite element pages is the mesh size, so the time step is here.
Output. Approximations , and at for , such that holds at every step and
The algorithm
The step first forms predictors and from the old values, then solves one linear system for the new acceleration, then corrects.
NEWMARK(M, C, K, F, d_0, v_0, dt, m, beta, gamma)- 1
a_0 <- solve M a = F(0) - C v_0 - K d_0 - 2
for k <- 0 to m - 1 do - 3
dp <- d_k + dt v_k + (dt^2 / 2)(1 - 2 beta) a_k ▷ displacement predictor - 4
vp <- v_k + (1 - gamma) dt a_k ▷ velocity predictor - 5
a_{k+1} <- solve (M + gamma dt C + beta dt^2 K) a = F(t_{k+1}) - C vp - K dp - 6
d_{k+1} <- dp + beta dt^2 a_{k+1} - 7
v_{k+1} <- vp + gamma dt a_{k+1} - 8
return (d_k, v_k, a_k) for k = 0 .. m
The matrix of line L5 does not change when is fixed, so a code factors it once. With , and a diagonal (lumped) , line L5 is a division per unknown and the method is explicit.
Nonlinear problems. For an internal force in place of , line L5 becomes the nonlinear equation . A Newton iteration solves it with the matrix , where is the tangent stiffness at the current iterate. The reference code does this in newmark_nonlinear.
Common members of the family.
| name | type | order | stable for (undamped) | ||
|---|---|---|---|---|---|
| central difference | explicit with lumped | 2 | |||
| Fox-Goodwin | implicit | 2 | |||
| linear acceleration | implicit | 2 | |||
| average acceleration (trapezoidal rule) | implicit | 2 | all | ||
| damped Newmark | implicit | 1 | all |
Here is the highest natural frequency of the mesh, the square root of the largest eigenvalue of . The table holds for . The limit for and is .
Example
One step by hand. Take (so ), no damping, no load, , , , and the average acceleration rule. Line L1 gives . Line L3 gives and line L4 gives . Line L5 solves , so . Then and . The energy is the initial energy. The exact values are and .
| exact | exact | |||
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 1 | 15/17 = 0.88235 | -8/17 = -0.47059 | 0.87758 | -0.47943 |
| 2 | 161/289 = 0.55709 | -240/289 = -0.83045 | 0.54030 | -0.84147 |
| 3 | 495/4913 = 0.10075 | -4888/4913 = -0.99491 | 0.07074 | -0.99749 |
| 4 | -0.37929 | -0.92528 | -0.41615 | -0.90930 |
The discrete solution is , with per step in place of . The amplitude is exact and the phase lags: the period grows by the factor , which is for , for and for . For small steps the relative period error is about .
Other members on the same problem. After 4 steps of (at , exact ) the central difference method gives , Fox-Goodwin and linear acceleration . Fox-Goodwin is the most accurate of the four here, but it is only conditionally stable.
Correctness
The full proofs are in the correctness proof. Three facts carry the method.
- Consistency and order. Insert the exact solution into the two update formulas. The velocity formula has a residual and the displacement formula . So the local truncation error per unit time is unless , and when . For the average acceleration rule the proof bounds the global error in the energy norm by directly. For the other stable members the global error has the order of the local one by the usual stability argument (Hughes 2000, Chapter 9), and the reference tests measure orders 2 and 1.
- Stability for linear problems. For one mode , the displacements satisfy the three-term recurrence with . For the steps stay bounded exactly when and either or , with strict inequality when . The modes of with decouple, so the same holds for the full system.
- Energy. For , , and , the quantity is the same at every step, for any , by a two-line identity.
Proof: Order, linear stability and energy of the Newmark-beta methodpartial
Setting. is symmetric positive definite, is symmetric and , so that is invertible for the problems below. Lines L1 to L7 give, for every ,
and . Indeed line L6 gives with from line L3, and line L7 gives with from line L4. The system of line L5 is written with these two expressions. Line L1 gives the equation at . The status is partial because Theorem 9 cites, and does not prove, the convergence of the members other than the average acceleration rule.
Lemma 1 (two-step form). For every , whatever the equation of motion,
Proof. Subtract (U1) for the step from to from (U1) for the step from to . This gives . By (U2), . Collect the terms: has the coefficient , has , and has .
Corollary (central difference). For and , Lemma 1 reads . With and this is the central difference method , also for a nonlinear .
Lemma 2 (modal reduction). Let and , and let be positive semidefinite. Let be the matrix of generalized eigenvectors, with . Write , and . Then each component is the Newmark sequence of the scalar problem with the same , and .
Proof. is invertible, and (U1) and (U2) are linear with scalar coefficients, so they hold for , and in place of , and . Multiply by : . So , which is the scalar equation of motion.
So the sequence is bounded for all initial data exactly when each scalar mode is bounded for all initial data.
Lemma 3 (scalar step and its eigenvalues). For put and . The step is a linear map of . Its eigenvalues are the roots of
Proof. With , Lemma 1 becomes , that is for . Put . Then for all , where is the companion matrix of , with rows and . By (U1) with , , so with lower triangular with diagonal entries and , so is invertible. Since every is a possible initial value, for all , and has the same eigenvalues as , the roots of .
Lemma 4 (roots in the unit disk). Let and be real. Both roots of have modulus at most 1 exactly when and .
Proof. If the roots are not real, they are conjugate, , and . Then and , so the condition holds exactly when , which is exactly when . If the roots are real, then , and . If both roots are in , all three facts give and , and is . Conversely let and . If , then forces , and , a contradiction. If , then forces and again .
Theorem 5 (linear stability). Let . The scalar sequence is bounded for all initial data exactly when and either , or with strict inequality when .
Proof. A direct computation from Lemma 3 gives
The powers stay bounded exactly when the roots of are in the closed unit disk and a root of modulus 1 is not a double root, because a matrix with a double eigenvalue is either or similar to a Jordan block, and is not (the companion matrix has the entry off the diagonal).
By Lemma 4 the roots are in the closed disk exactly when , and . Here always. The condition is . The condition is or . It implies by the last identity.
Double roots on the circle: a double root needs , which is impossible for . A double root needs and . If , then , and means . With this is , that is . Non-real roots are distinct. So the only bad case inside the closed disk is with .
Corollaries. For , by Lemma 2 the full system is stable for every when , and otherwise (for ) when . This limit is for , for and for , all with . For and we have , so the damped member is unconditionally stable. For a rigid body mode, , and , which is the exact free motion.
Phase of the average acceleration rule. For and , and . With this is , so the roots are : modulus 1 and the angle per step in place of the exact .
Lemma 6 (consistency). Let be a smooth exact solution with . Define the defects and . Then
Proof. Insert the Taylor expansions , and . In the terms in cancel and remains. In the terms in and cancel and remains.
So the defect per unit time, , is for (its leading term is not zero when ) and for . For , is the error of the trapezoidal rule for , so for each component, and for .
Theorem 7 (energy of the average acceleration rule). Let , , , and symmetric. Then is the same for all , for every .
Proof. (U2) gives , and (U1) then gives . The equation of motion gives . For a symmetric matrix , . So
because is symmetric.
The two relations of the proof are the trapezoidal rule for and . With a load and damping the same steps give the trapezoidal rule for , . For a nonlinear the last step fails, because is not a gradient difference, and the energy is not conserved (the reference test test_nonlinear_energy_is_not_exact measures a change of more than ).
Remark (conserved quadratic form for ). For the scalar recurrence of Lemma 3 has , so it reads with . Then satisfies . So every member with conserves a quadratic form for linear undamped problems, and by Lemma 2 this holds mode by mode.
Theorem 8 (second order convergence of the average acceleration rule). Let , , , symmetric positive definite, and let the exact solution have a bounded fourth derivative on . Start from the exact and . Let and . Then for ,
where depends on , and the bounds of the third and fourth derivatives of .
Proof. The exact solution satisfies (U1) and (U2) with the defects and added, and . Subtract the numerical scheme. The errors satisfy the scheme for with the defects added: and , with . As in Theorem 7, with , and . The same computation as in Theorem 7 gives, for ,
Write , and . By the Cauchy-Schwarz inequality in these inner products, and , so with . Divide by (if it is the claim is trivial) to get . With , . By Lemma 6, , and there are terms.
Theorem 9 (convergence of the other members, cited). For fixed and in the stable set of Theorem 5, with the inequality strict, a linear problem and a smooth solution, the global error on is for and for . This follows from Lemma 6 and a bound on the powers of the step matrix that is uniform in (Hughes 2000, Chapter 9). We do not repeat that bound here. The reference tests measure the orders 2 for and 1 for .
Complexity
In the real-RAM model, for a linear problem with fixed , the effective matrix is factored once. For a banded matrix with half bandwidth , as from a finite element mesh with a good node order, the Cholesky factorization costs and each step costs for the matrix-vector products and the two triangular solves. The total for steps is , and the memory is for the factor. The explicit case (, lumped , diagonal or zero) needs no factorization, and a step costs one product with , , but must stay below , and grows like for a mesh of size . A nonlinear step costs one tangent assembly and one factorization per Newton iteration. Newton converges locally and quadratically when the tangent is exact and the predictor is close enough; the number of iterations is a measurement (at most 2 corrections per step to a residual of for the Duffing test of the reference code, with 50 to 200 steps). The reference code uses dense Gaussian elimination from scimat, so it costs per step and is meant only for small systems.
Properties
- Second order exactly when . Any adds numerical damping and drops the order to 1.
- No amplitude error for the trapezoidal rule. Both roots have modulus 1 for every , so the method neither damps nor amplifies a linear mode. The price is that high, unresolved modes of a coarse mesh also keep their full amplitude.
- Equivalent forms. With , the method is the trapezoidal rule applied to the first order system , . With , the displacements satisfy when , the central difference method, which for is the position form of Verlet integration.
- Not L-stable. The trapezoidal rule has spectral radius 1 as , so it is A-stable but does not damp stiff modes, in contrast with backward Euler.
- Symplectic members. For the method conserves a modified quadratic energy for linear problems. For it is the symplectic Stormer-Verlet scheme also for nonlinear forces.
Variants and improvements
- Generalized-alpha method. Evaluate the equation of motion at shifted times inside the step. This keeps second order and gives a chosen amount of damping of the high modes, which Newmark can only get with and first order.
- HHT-alpha and WBZ-alpha. The two special cases of the generalized-alpha family, which shift only the stiffness and damping terms (Hilber, Hughes and Taylor) or only the inertia term (Wood, Bossak and Zienkiewicz).
- d-form and v-form. Solve for or in place of . The three forms give the same values in exact arithmetic. The d-form is common in nonlinear codes, because the tangent acts on the displacement.
- Explicit predictor-corrector. Use the predictors as the new values and the old acceleration in the force evaluation. This is explicit for any but has a step limit.
- Energy-momentum methods. For nonlinear elastodynamics, replace the trapezoidal force average by a discrete gradient so that energy, linear momentum and angular momentum are all conserved (Simo and Tarnow 1992).
When to use it
Use the average acceleration rule for linear and mildly nonlinear structural dynamics where the response of interest is in the low modes and you want no artificial damping, for example the response of a building to an earthquake record. Use the central difference member with a lumped mass matrix for short events such as impact, crash and wave propagation, where the step must be small anyway to resolve the physics. When the mesh has spurious high modes that must be damped, or when a nonlinear problem shows energy growth, use the generalized-alpha method in place of .
Pitfalls
- Unconditional stability is only for linear problems. For nonlinear problems the energy of the trapezoidal rule can grow without bound for large steps (Hughes 1976, Simo and Tarnow 1992). A large step that works for the linearized problem can fail on the nonlinear one.
- Damping by . It damps the high modes, but it also loses second order for all modes. The error then grows linearly in .
- The explicit limit uses the highest frequency. The limit comes from the stiffest element of the mesh, not from the physics. One small or very stiff element limits the whole model. The consistent mass matrix gives a larger than the lumped one, so it gives a smaller stable step.
- Initial acceleration. Line L1 must solve the equation of motion for . Setting for a loaded or displaced start gives a first order error that persists.
- Undamped high modes with the trapezoidal rule. A sudden load excites mesh modes that the trapezoidal rule never damps, so the computed velocities and stresses show noise of high frequency that a finer step does not remove.
- Period error. The method has no amplitude error but has a phase error. Over many periods the phase error dominates. For the trapezoidal rule the period error is about , so to keep it below 1 percent, use at least about 20 steps per period of the highest mode of interest.
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/newmark-beta-method/. The authors are listed in prov/DKETH0.jsonl.
"""Newmark-beta time stepping for M a + C v + K d = F(t) and its nonlinear form.
Matrices are lists of rows and vectors are lists, as in scimat. The step is dt.
With Fraction data and Fraction parameters the linear steps are exact.
"""
import math
import scimat
def newmark(M, C, K, F, d0, v0, dt, nsteps, beta=0.25, gamma=0.5):
"""Integrate M a + C v + K d = F(t) with the Newmark-beta method.
F is a function of t that returns the load vector. Return the lists of
displacements, velocities and accelerations at t = 0, dt, ..., nsteps dt.
"""
n = len(d0)
d, v = list(d0), list(v0)
rhs0 = scimat.sub(scimat.sub(F(0 * dt), scimat.matvec(C, v)), scimat.matvec(K, d))
a = scimat.solve(M, rhs0) # @line L1
lhs = [[M[i][j] + gamma * dt * C[i][j] + beta * dt * dt * K[i][j] for j in range(n)] for i in range(n)]
ds, vs, accs = [list(d)], [list(v)], [list(a)]
for k in range(nsteps): # @line L2
t1 = (k + 1) * dt
dp = [d[i] + dt * v[i] + dt * dt / 2 * (1 - 2 * beta) * a[i] for i in range(n)] # @line L3
vp = [v[i] + (1 - gamma) * dt * a[i] for i in range(n)] # @line L4
r = scimat.sub(scimat.sub(F(t1), scimat.matvec(C, vp)), scimat.matvec(K, dp))
a = scimat.solve(lhs, r) # @line L5
d = [dp[i] + beta * dt * dt * a[i] for i in range(n)] # @line L6
v = [vp[i] + gamma * dt * a[i] for i in range(n)] # @line L7
ds.append(d)
vs.append(v)
accs.append(a)
return ds, vs, accs # @line L8
def newmark_nonlinear(M, C, fint, tangent, F, d0, v0, dt, nsteps, beta=0.25, gamma=0.5, tol=1e-12, maxit=30):
"""Integrate M a + C v + fint(d) = F(t) with Newmark-beta and Newton iterations.
tangent(d) returns the stiffness matrix d fint / d d. Each step solves the
residual equation for a_(n+1) by Newton's method with the effective
tangent M + gamma dt C + beta dt^2 K_T. Return (ds, vs, accs, iterations).
"""
n = len(d0)
d, v = list(d0), list(v0)
a = scimat.solve(M, scimat.sub(scimat.sub(F(0 * dt), scimat.matvec(C, v)), fint(d)))
ds, vs, accs, its = [list(d)], [list(v)], [list(a)], []
for k in range(nsteps):
t1 = (k + 1) * dt
dp = [d[i] + dt * v[i] + dt * dt / 2 * (1 - 2 * beta) * a[i] for i in range(n)]
vp = [v[i] + (1 - gamma) * dt * a[i] for i in range(n)]
anew = list(a)
for it in range(maxit):
dn = [dp[i] + beta * dt * dt * anew[i] for i in range(n)]
vn = [vp[i] + gamma * dt * anew[i] for i in range(n)]
res = scimat.sub(scimat.add(scimat.add(scimat.matvec(M, anew), scimat.matvec(C, vn)), fint(dn)), F(t1))
if scimat.norm2(res) <= tol * (1 + scimat.norm2(F(t1))):
break
kt = tangent(dn)
jac = [[M[i][j] + gamma * dt * C[i][j] + beta * dt * dt * kt[i][j] for j in range(n)] for i in range(n)]
da = scimat.solve(jac, res)
anew = [anew[i] - da[i] for i in range(n)]
else:
raise RuntimeError("Newton iteration did not converge")
a = anew
d = [dp[i] + beta * dt * dt * a[i] for i in range(n)]
v = [vp[i] + gamma * dt * a[i] for i in range(n)]
ds.append(d)
vs.append(v)
accs.append(a)
its.append(it)
return ds, vs, accs, its
def amplification_matrix(omega_dt, beta, gamma, xi=0.0):
"""Return the 2 by 2 matrix A with (d, dt v)_(n+1) = A (d, dt v)_n.
It is for the free single degree of freedom oscillator a + 2 xi omega v +
omega^2 d = 0 with dt = 1 and omega = omega_dt, so it depends only on
omega dt, xi and the parameters.
"""
m, c, k = [[1.0]], [[2 * xi * omega_dt]], [[omega_dt * omega_dt]]
cols = []
for d0, v0 in ((1.0, 0.0), (0.0, 1.0)):
ds, vs, _ = newmark(m, c, k, lambda t: [0.0], [d0], [v0], 1.0, 1, beta, gamma)
cols.append((ds[1][0], vs[1][0]))
return [[cols[0][0], cols[1][0]], [cols[0][1], cols[1][1]]]
def spectral_radius_2x2(a):
"""Return the largest modulus of the eigenvalues of a real 2 by 2 matrix."""
tr = a[0][0] + a[1][1]
det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
disc = tr * tr / 4 - det
if disc >= 0:
s = math.sqrt(disc)
return max(abs(tr / 2 + s), abs(tr / 2 - s))
return math.sqrt(det)
def critical_omega_dt(beta, gamma):
"""Return the stability limit of omega dt for an undamped linear oscillator.
Valid for gamma >= 1/2. Return math.inf when 2 beta >= gamma (unconditional).
"""
if 2 * beta >= gamma:
return math.inf
return 1 / math.sqrt(gamma / 2 - beta)
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_newmark_beta_method.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newmark-beta-method/. The authors are listed in prov/DKETH0.jsonl.
import math
from fractions import Fraction as Fr
import scimat
from newmark_beta_method import (
amplification_matrix,
critical_omega_dt,
newmark,
newmark_nonlinear,
spectral_radius_2x2,
)
def free_sdof(omega, dt, nsteps, beta, gamma, d0=1.0, v0=0.0):
return newmark([[1.0]], [[0.0]], [[omega * omega]], lambda t: [0.0], [d0], [v0], dt, nsteps, beta, gamma)
def test_first_step_exact_fractions():
# m = k = 1, d0 = 1, v0 = 0, dt = 1/2, average acceleration: d1 = 15/17, v1 = -8/17.
ds, vs, accs = newmark([[Fr(1)]], [[Fr(0)]], [[Fr(1)]], lambda t: [Fr(0)], [Fr(1)], [Fr(0)], Fr(1, 2), 1, Fr(1, 4), Fr(1, 2))
assert accs[0] == [Fr(-1)]
assert ds[1] == [Fr(15, 17)]
assert vs[1] == [Fr(-8, 17)]
assert accs[1] == [Fr(-15, 17)]
def test_average_acceleration_conserves_energy_exactly():
# For an undamped linear system, (1/2)(v.Mv + d.Kd) is the same at every step, for any dt.
M = [[Fr(2), Fr(0)], [Fr(0), Fr(1)]]
K = [[Fr(6), Fr(-2)], [Fr(-2), Fr(4)]]
C = [[Fr(0)] * 2 for _ in range(2)]
ds, vs, _ = newmark(M, C, K, lambda t: [Fr(0), Fr(0)], [Fr(1), Fr(0)], [Fr(0), Fr(1)], Fr(3), 12, Fr(1, 4), Fr(1, 2))
def energy(d, v):
return (scimat.dot(v, scimat.matvec(M, v)) + scimat.dot(d, scimat.matvec(K, d))) / 2
e0 = energy(ds[0], vs[0])
assert all(energy(d, v) == e0 for d, v in zip(ds, vs))
def test_trapezoidal_phase_is_two_arctan():
# The eigenvalues of the average acceleration step have modulus 1 and argument 2 atan(omega dt / 2).
for w in (0.1, 0.7, 2.0, 10.0, 100.0):
a = amplification_matrix(w, 0.25, 0.5)
det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
tr = a[0][0] + a[1][1]
assert abs(det - 1) < 1e-12
assert abs(tr / 2 - math.cos(2 * math.atan(w / 2))) < 1e-12
def errors_at_T(beta, gamma, steps_list, T=2.0):
errs = []
for ns in steps_list:
ds, vs, _ = free_sdof(1.0, T / ns, ns, beta, gamma)
errs.append(math.hypot(ds[-1][0] - math.cos(T), vs[-1][0] + math.sin(T)))
return errs
def test_second_order_for_gamma_half():
for beta in (0.25, 1 / 6, 1 / 12, 0.0):
p = scimat.observed_order(errors_at_T(beta, 0.5, [40, 80, 160, 320]))
assert all(abs(q - 2) < 0.2 for q in p), (beta, p)
def test_first_order_for_gamma_above_half():
gamma = 0.6
beta = (gamma + 0.5) ** 2 / 4
p = scimat.observed_order(errors_at_T(beta, gamma, [80, 160, 320, 640]))
assert all(abs(q - 1) < 0.2 for q in p), p
def test_central_difference_limit_two():
assert critical_omega_dt(0.0, 0.5) == 2
assert spectral_radius_2x2(amplification_matrix(1.99, 0.0, 0.5)) <= 1 + 1e-12
assert spectral_radius_2x2(amplification_matrix(2.01, 0.0, 0.5)) > 1.05
def test_linear_acceleration_limit():
wc = critical_omega_dt(1 / 6, 0.5)
assert abs(wc - math.sqrt(12)) < 1e-12
assert spectral_radius_2x2(amplification_matrix(wc * 0.999, 1 / 6, 0.5)) <= 1 + 1e-9
assert spectral_radius_2x2(amplification_matrix(wc * 1.01, 1 / 6, 0.5)) > 1
def test_unconditional_stability_region():
for gamma in (0.5, 0.55, 0.7, 1.0):
beta = gamma / 2
for w in (0.5, 5.0, 50.0, 5e3):
# near omega dt = infinity the step matrix is close to a Jordan block, so allow rounding
assert spectral_radius_2x2(amplification_matrix(w, beta, gamma)) <= 1 + 1e-9
assert critical_omega_dt(0.25, 0.5) == math.inf
def test_dissipation_with_gamma_above_half():
gamma = 0.6
beta = (gamma + 0.5) ** 2 / 4
rho = spectral_radius_2x2(amplification_matrix(1e6, beta, gamma))
assert rho < 0.9
assert spectral_radius_2x2(amplification_matrix(1e6, 0.25, 0.5)) > 1 - 1e-9
def test_two_dof_against_modal_solution():
# M = I, K = [[2, -1], [-1, 2]]: modes (1, 1) with omega = 1 and (1, -1) with omega = sqrt(3).
K = [[2.0, -1.0], [-1.0, 2.0]]
I2 = [[1.0, 0.0], [0.0, 1.0]]
Z = [[0.0, 0.0], [0.0, 0.0]]
T = 3.0
w2 = math.sqrt(3.0)
def exact(t):
q1, q2 = math.cos(t), 0.5 * math.cos(w2 * t)
return [q1 + q2, q1 - q2]
errs = []
for ns in (60, 120, 240):
ds, _, _ = newmark(I2, Z, K, lambda t: [0.0, 0.0], exact(0.0), [0.0, 0.0], T / ns, ns)
errs.append(max(abs(x - y) for x, y in zip(ds[-1], exact(T))))
p = scimat.observed_order(errs)
assert all(abs(q - 2) < 0.2 for q in p), p
def test_forced_damped_oscillator():
# a + 0.2 v + d = cos(t) from rest; compare with the exact solution.
xi, T = 0.1, 4.0
def exact(t):
# particular solution (0.2 sin t) / 0.04 = 5 sin t; homogeneous part fixes d(0) = 0, v(0) = 0.
wd = math.sqrt(1 - xi * xi)
A = 0.0
B = -5.0 / wd
return 5 * math.sin(t) + math.exp(-xi * t) * (A * math.cos(wd * t) + B * math.sin(wd * t))
errs = []
for ns in (50, 100, 200):
ds, _, _ = newmark([[1.0]], [[0.2]], [[1.0]], lambda t: [math.cos(t)], [0.0], [0.0], T / ns, ns)
errs.append(abs(ds[-1][0] - exact(T)))
p = scimat.observed_order(errs)
assert all(abs(q - 2) < 0.2 for q in p), p
def rk4_duffing(d, v, T, ns):
h = T / ns
def f(x, y):
return y, -x - x ** 3
for _ in range(ns):
k1 = f(d, v)
k2 = f(d + h / 2 * k1[0], v + h / 2 * k1[1])
k3 = f(d + h / 2 * k2[0], v + h / 2 * k2[1])
k4 = f(d + h * k3[0], v + h * k3[1])
d += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
v += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
return d, v
def test_nonlinear_duffing_against_rk4():
# a + d + d^3 = 0, d(0) = 1, v(0) = 0; RK4 with 4000 steps is the reference.
T = 3.0
dref, _ = rk4_duffing(1.0, 0.0, T, 4000)
errs = []
for ns in (50, 100, 200):
ds, _, _, its = newmark_nonlinear(
[[1.0]], [[0.0]], lambda d: [d[0] + d[0] ** 3], lambda d: [[1 + 3 * d[0] ** 2]], lambda t: [0.0], [1.0], [0.0], T / ns, ns
)
assert max(its) <= 8
errs.append(abs(ds[-1][0] - dref))
p = scimat.observed_order(errs)
assert all(abs(q - 2) < 0.2 for q in p), p
def test_nonlinear_energy_is_not_exact():
# The trapezoidal rule does not conserve the energy of a nonlinear spring exactly.
ds, vs, _, _ = newmark_nonlinear(
[[1.0]], [[0.0]], lambda d: [d[0] + d[0] ** 3], lambda d: [[1 + 3 * d[0] ** 2]], lambda t: [0.0], [1.0], [0.0], 0.5, 40
)
e = [v[0] ** 2 / 2 + d[0] ** 2 / 2 + d[0] ** 4 / 4 for d, v in zip(ds, vs)]
assert max(abs(x - e[0]) for x in e) > 1e-4
History
Nathan Newmark published the method in 1959, in a paper on computing the response of structures to blast and earthquake loads, and gave the two parameters, the choice for no artificial damping and the stability limits for the linear oscillator. The finite element community made it the standard integrator for structural dynamics in the 1970s. Hughes showed in 1976 that the energy argument for the average acceleration rule fails for nonlinear problems. Hilber, Hughes and Taylor in 1977 and Chung and Hulbert in 1993 added controlled numerical damping without the loss of order. Simo and Tarnow in 1992 gave schemes that conserve energy and momentum for nonlinear elastodynamics.
References
- N. M. Newmark, A method of computation for structural dynamics, Journal of the Engineering Mechanics Division (ASCE) 85(3) (1959) 67-94, the two-parameter step for displacement and velocity, with the stability limits
- Thomas J. R. Hughes, The Finite Element Method, Linear Static and Dynamic Finite Element Analysis, Dover, 2000, Chapter 9 (the Newmark method, its stability and accuracy analysis, numerical dissipation and dispersion)
- T. J. R. Hughes, Stability, convergence and growth and decay of energy of the average acceleration method in nonlinear structural dynamics, Computers and Structures 6(4-5) (1976) 313-324, energy of the average acceleration method for nonlinear problems
- J. C. Simo and N. Tarnow, The discrete energy-momentum method. Conserving algorithms for nonlinear elastodynamics, Zeitschrift fur angewandte Mathematik und Physik 43(5) (1992) 757-792, loss of stability of the trapezoidal rule in nonlinear elastodynamics, and energy-momentum conserving schemes
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 DKETH0 Edit this page History Report an error Markdown