Linear solvers of the non-linear analyses#
Each iteration of a non-linear analysis of Analysis solves a linear system with the tangent stiffness matrix \(\boldsymbol{K}_T\), factorized with Analysis.linear_solver. This notebook runs the same non-linear analysis, whose tangent stiffness matrix is unsymmetric, with the default 'splu' (SuperLU), 'pardiso_lu' (the unsymmetric LU of PARDISO, oneMKL) and 'dense_lu' (the dense LU of LAPACK), checks that they take the same increments and iterations and
give the same solutions to round-off, and compares their times on a small and on a larger model. The choice of the solver is discussed in Linear solvers of the static analyses.
[1]:
import os
import time
import warnings
import numpy as np
import scipy.sparse as sp
from structsolve import Analysis
from structsolve.pardiso import available as pardiso_available
from structsolve.static import _factorize
print('PARDISO available:', pardiso_available())
print('threads: OMP_NUM_THREADS =', os.environ.get('OMP_NUM_THREADS'),
', MKL_NUM_THREADS =', os.environ.get('MKL_NUM_THREADS'))
PARDISO available: True
threads: OMP_NUM_THREADS = 1 , MKL_NUM_THREADS = 1
Model: a grid of hardening springs with a circulatory coupling#
An \(N \times N\) grid of nodes, each with one displacement \(u_i\), is connected to its neighbours by linear springs of stiffness \(k\) (the matrix \(\boldsymbol{K}\), a discrete Laplacian), and each node to the ground by a hardening spring, of force \(k_0 u_i + a u_i^3\). A circulatory coupling between the neighbours along \(x\), of stiffness \(g\), adds the antisymmetric matrix \(\boldsymbol{G}\), as a follower load would:
unsymmetric and sparse, with 5 terms per row. The load is a uniform force \(P\) at every node. The calls of calc_fint are counted, one per Newton-Raphson iteration.
[2]:
def grid_problem(N, k=100., k0=10., g=30., a=50., P=20.):
n = N*N
T = sp.diags([-np.ones(N - 1), 2*np.ones(N), -np.ones(N - 1)], [-1, 0, 1])
I = sp.identity(N)
K = k*(sp.kron(I, T) + sp.kron(T, I)) + k0*sp.identity(n)
# antisymmetric coupling along x
S = sp.diags([-np.ones(N - 1), np.ones(N - 1)], [-1, 1])
G = g*sp.kron(I, S)
K0 = sp.csr_matrix(K + G)
fext = P*np.ones(n)
calls = []
an = Analysis(
calc_fext=lambda inc=1., silent=True: inc*fext,
calc_fint=lambda c, silent=True: calls.append(1) or K0 @ c + a*c**3,
calc_kC=lambda c=None, NLgeom=False, silent=True: K0,
calc_kG=lambda c=None, NLgeom=False, silent=True: sp.diags(
3*a*(np.zeros(n) if c is None else c)**2).tocsr())
an.initialInc = 0.2
return an, calls
an, calls = grid_problem(4)
kT = an.calc_kC() + an.calc_kG(c=np.ones(16))
print('n =', kT.shape[0], ', terms =', kT.nnz,
', |kT - kT^T|max/|kT|max = %.2f' % (abs(kT - kT.T).max()/abs(kT).max()))
n = 16 , terms = 64 , |kT - kT^T|max/|kT|max = 0.11
Same increments, iterations and solutions#
The analysis is run with each solver ('pardiso_lu' only when oneMKL is found, see pardiso), here on a grid of \(10 \times 10\) nodes. The increments and the numbers of iterations are compared with those of 'splu', and the solutions by their largest relative difference. Warnings are turned into errors: no fallback of 'pardiso_lu' to SuperLU occurs.
[3]:
SOLVERS = ['splu', 'dense_lu'] + (['pardiso_lu'] if pardiso_available() else [])
def run(N, linear_solver, NL_method='NR'):
an, calls = grid_problem(N)
an.linear_solver = linear_solver
an.NL_method = NL_method
t0 = time.perf_counter()
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
increments, cs = an.static(NLgeom=True, silent=True)
t = time.perf_counter() - t0
return dict(increments=np.array(increments), cs=cs, iterations=len(calls), time=t)
def compare(N, NL_method='NR'):
res = {ls: run(N, ls, NL_method) for ls in SOLVERS}
ref = res['splu']
print('%-11s %10s %10s %14s %20s' % ('solver', 'increments', 'iterations',
'same loads', 'max rel. diff. of c'))
for ls, r in res.items():
same = (r['increments'].shape == ref['increments'].shape
and np.allclose(r['increments'], ref['increments'], rtol=1e-12))
diff = max(np.abs(c - c0).max()/np.abs(c0).max()
for c, c0 in zip(r['cs'], ref['cs']))
print('%-11s %10d %10d %14s %20.1e' % (ls, len(r['increments']),
r['iterations'], same, diff))
return res
res_nr = compare(10)
solver increments iterations same loads max rel. diff. of c
splu 5 19 True 0.0e+00
dense_lu 5 19 True 6.4e-16
pardiso_lu 5 19 True 4.5e-16
The same with the arc-length method of Riks, whose iterations solve two systems with each factorization:
[4]:
res_riks = compare(10, 'arc_length_riks')
solver increments iterations same loads max rel. diff. of c
splu 4 20 True 0.0e+00
dense_lu 4 20 True 5.9e-16
pardiso_lu 4 20 True 6.0e-16
Timing#
The time of each analysis and of one factorization of the tangent stiffness matrix at the end of the path, on the grid of \(10 \times 10\) nodes (100 degrees of freedom) and on a grid of \(50 \times 50\) nodes (2500). On the small model the dense LU is the fastest, its cost not depending on the sparsity; on the larger one the sparse factorizations are faster, and PARDISO, multithreaded and keeping the analysis of the pattern along the analysis, is the fastest. The times depend on the computer and on its number of threads, printed at the top (the stored outputs were computed on one thread, where PARDISO and the dense LU do not use their parallelism); they are the minimum of a few runs.
[5]:
def factorization_time(N, linear_solver, repeat=5):
an, calls = grid_problem(N)
kT = an.calc_kC() + an.calc_kG(c=0.3*np.ones(N*N))
times = []
for _ in range(repeat):
t0 = time.perf_counter()
f = _factorize(kT, linear_solver)
times.append(time.perf_counter() - t0)
del f
return min(times)
for N in (10, 50):
print('grid %d x %d, n = %d' % (N, N, N*N))
print(' %-11s %14s %18s %12s' % ('solver', 'analysis (s)', 'factorization (s)', 'iterations'))
for ls in SOLVERS:
t = min(run(N, ls)['time'] for _ in range(2))
print(' %-11s %14.3f %18.4f %12d' % (ls, t, factorization_time(N, ls), run(N, ls)['iterations']))
grid 10 x 10, n = 100
solver analysis (s) factorization (s) iterations
splu 0.008 0.0002 19
dense_lu 0.005 0.0001 19
pardiso_lu 0.007 0.0002 19
grid 50 x 50, n = 2500
solver analysis (s) factorization (s) iterations
splu 0.107 0.0051 22
dense_lu 5.783 0.3252 22
pardiso_lu 0.093 0.0081 22
The analysis creates a cache of the factorizations (_factorize) with which 'pardiso_lu' keeps the ordering and symbolic factorization of PARDISO for the next factorizations of the same sparsity pattern; the factorization times above, without the cache, include them. With inertia=True, 'dense_lu' records the sign of the determinant as 'splu' does, whereas 'pardiso_lu' raises a ValueError, PARDISO giving no inertia for unsymmetric matrices:
[6]:
an, calls = grid_problem(4)
an.linear_solver = 'pardiso_lu'
an.inertia = True
try:
an.static(NLgeom=True, silent=True)
except ValueError as e:
print('ValueError:', e)
ValueError: Analysis.inertia = True is not supported by Analysis.linear_solver = 'pardiso_lu'; use 'splu', 'dense_lu' or 'pardiso'