Docs › Examples › One model, five discretizations
One model, five discretizations
Keep the physics and the mesh fixed and change only the numerical method. For a problem with a known exact solution, every method can be graded.
The problem
A grounded unit cube filled with charge. The potential solves the Poisson equation \(-\nabla^2\varphi=\rho\) with \(\varphi=0\) on all six faces. The source is chosen so that the exact solution is
The peak is exactly 1 in the centre, so any deviation is discretization error.
The model, declared once
import numpy as np
from dataclasses import dataclass
from onesim.cad.d3 import Box
from onesim.meshing import StructuredHexahedralMesher
from onesim.numerics import Numerics
from onesim.numerics.linear import SparseDirect
from onesim.physics.electrostatics import FixedPotential, PoissonEquation
from onesim.simulation import Problem, Simulation
@dataclass(frozen=True)
class Permittivity:
unit = "F/m"
def evaluate(self, **state):
return 1.0
cube = Box(length=1, width=1, height=1)
exact = lambda x, y, z: np.sin(np.pi*x) * np.sin(np.pi*y) * np.sin(np.pi*z)
field = PoissonEquation(
domain=cube.volume, permittivity=Permittivity(),
charge_density=lambda x, y, z: 3 * np.pi**2 * exact(x, y, z))
problem = Problem(
name="Charge in a grounded box", geometry=cube, physics=(field,),
boundary_conditions=(
FixedPotential(physics=field, boundary=cube.boundaries.all, value=0.0),))
mesh = StructuredHexahedralMesher(cells=(16, 16, 16)).generate(cube)Nothing above mentions a numerical method. Geometry, physics, boundary condition and mesh are plain Python objects.
Five methods, one argument
from onesim.numerics.fem import FiniteElement, Lagrange
from onesim.numerics.fvm import FiniteVolume, LeastSquaresGradient, CentralDifference
from onesim.numerics.fdm import (FiniteDifference, CentralLaplacian,
PolynomialDifference, PolynomialLaplacian)
from onesim.numerics.fdm import CentralDifference as FDGradient
methods = {
"FEM, linear elements": FiniteElement(element=Lagrange(order=1)),
"FEM, quadratic elements": FiniteElement(element=Lagrange(order=2)),
"FVM": FiniteVolume(gradient=LeastSquaresGradient(),
diffusion=CentralDifference()),
"FDM, 2nd order": FiniteDifference(gradient=FDGradient(),
diffusion=CentralLaplacian()),
"FDM, 4th order": FiniteDifference(
gradient=PolynomialDifference(accuracy_order=4),
diffusion=PolynomialLaplacian(accuracy_order=4)),
}
centres = mesh.coordinates[mesh.cells].mean(axis=1)
for name, spatial in methods.items():
result = Simulation(
problem=problem, mesh=mesh,
numerics=Numerics(spatial=spatial, linear_solver=SparseDirect()),
).solve_stationary()
phi = result.field(field.potential).evaluate(centres)
error = np.sqrt(np.mean((phi - exact(*centres.T))**2))
print(f"{name:26s} {error:.1e}")What came out
Same mesh of 16 × 16 × 16 hexahedra, same solver, root-mean-square error at the cell centres against the exact solution, wall time on an Apple Silicon laptop.
| Method | RMS error | Time |
|---|---|---|
| FEM, linear elements | 2.8 × 10⁻³ | 14 s |
| FEM, quadratic elements | 6.3 × 10⁻⁷ | 86 s |
| FVM | 5.7 × 10⁻⁴ | 6 s |
| FDM, 2nd order | 1.1 × 10⁻³ | 6 s |
| FDM, 4th order | 1.7 × 10⁻⁸ | 7 s |
- The method matters more than the mesh. Five orders of magnitude lie between the worst and the best row on an identical mesh.
- High order is nearly free when the solution is smooth. The fourth-order stencil costs one second more than the second-order one.
- Accuracy has a price that differs by method. Quadratic elements gain almost four digits over linear ones and take six times as long. On a curved or unstructured geometry the finite-difference rows are not available, the finite-element rows are.
The solver is an argument too
On the linear finite-element model, three linear solvers give the same centre potential to five digits.
from onesim.numerics.linear import GMRES, ILU, ConjugateGradient
for solver in (SparseDirect(), GMRES(preconditioner=ILU()), ConjugateGradient()):
result = Simulation(problem=problem, mesh=mesh,
numerics=Numerics(spatial=methods["FEM, linear elements"],
linear_solver=solver)).solve_stationary()
print(result.field(field.potential).evaluate([[0.5, 0.5, 0.5]])) # 1.00645 each time