OneSimulation docs Website Free books Plans on Gumroad

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

\[\varphi(x,y,z)=\sin(\pi x)\,\sin(\pi y)\,\sin(\pi z).\]

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.

MethodRMS errorTime
FEM, linear elements2.8 × 10⁻³14 s
FEM, quadratic elements6.3 × 10⁻⁷86 s
FVM5.7 × 10⁻⁴6 s
FDM, 2nd order1.1 × 10⁻³6 s
FDM, 4th order1.7 × 10⁻⁸7 s

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