OneSimulation docs Website Free books Plans on Gumroad

Docs › Worked numerical comparisons › Finite-element lab

9.4 Finite-element lab

9.4.1 Compare finite-element orders on a manufactured harmonic field

Prescribe a harmonic quadratic potential on the box boundary. Its representation distinguishes first- and second-order spaces. Use physical evaluation and a logarithmic error panel for the comparison.

import numpy as np
import matplotlib.pyplot as plt
import onesimulation_plot_theme as theme
from onesim.cad.d3 import Box
from onesim.materials import VacuumPermittivity
from onesim.meshing import StructuredTetrahedralMesher
from onesim.numerics import Numerics
from onesim.numerics.fem import FiniteElement, Lagrange
from onesim.numerics.linear import SparseDirect
from onesim.physics.electrostatics import FixedPotential, PoissonEquation
from onesim.simulation import Problem, Simulation

box = Box(length=1, width=1, height=1)
model = PoissonEquation(domain=box.volume, permittivity=VacuumPermittivity())


def exact(x, y):
    return x * x - y * y


problem = Problem(
    name="Harmonic potential",
    geometry=box,
    physics=(model,),
    boundary_conditions=(
        FixedPotential(physics=model, boundary=box.boundaries.all, value=exact),
    ),
)
mesh = StructuredTetrahedralMesher(cells=(3, 3, 3)).generate(box)
x = np.linspace(0.01, 0.99, 101)
points = np.column_stack((x, np.full_like(x, 0.3), np.full_like(x, 0.55)))
reference = exact(points[:, 0], points[:, 1])
theme.use_theme()
fig, (a, b) = plt.subplots(
    2, 1, sharex=True, figsize=(7.2, 4.1), layout="constrained"
)
errors = {}
for p in (1, 2):
    sim = Simulation(
        problem=problem,
        mesh=mesh,
        numerics=Numerics(
            spatial=FiniteElement(element=Lagrange(order=p)),
            linear_solver=SparseDirect(),
        ),
    )
    result = sim.solve_stationary()
    potential = result.field(model.potential).evaluate(points)
    errors[p] = np.max(np.abs(potential - reference))
    a.plot(x, potential, label=f"P{p}")
    b.semilogy(x, np.maximum(np.abs(potential - reference), 1e-16), label=f"P{p}")
assert errors[2] < 1e-10 < errors[1]
a.set_ylabel("Potential [V]")
a.legend(frameon=False)
b.set(xlabel="World x [m]", ylabel="Absolute error [V]")
plt.show()
Figure computed with OneSimulation: recipe finite element orders

9.4.2 Mixed normal-flux elements for the Poisson balance

Pair each H(div) flux family with its compatible discontinuous scalar order. Solve a manufactured quadratic potential whose gradient is linear and compare the physical potential and electric field along the same line.

import numpy as np
import matplotlib.pyplot as plt
import onesimulation_plot_theme as theme
from onesim.cad.d3 import Box
from onesim.meshing import StructuredTetrahedralMesher
from onesim.numerics import Numerics
from onesim.numerics.fem import (
    BrezziDouglasMarini,
    DiscontinuousLagrange,
    FiniteElement,
    MixedDiffusionElement,
    RaviartThomas,
)
from onesim.numerics.linear import SparseDirect
from onesim.physics.electrostatics import FixedPotential, PoissonEquation
from onesim.simulation import Problem, Simulation


class ConstantPermittivity:
    unit = "F/m"

    def evaluate(self, **state):
        return 2.0


box = Box(length=1, width=1, height=1)
model = PoissonEquation(
    domain=box.volume, permittivity=ConstantPermittivity(), charge_density=-12.0
)


def exact(x, y, z):
    return x * x + y * y + z * z


problem = Problem(
    name="Mixed potential and flux",
    geometry=box,
    physics=(model,),
    boundary_conditions=(
        FixedPotential(physics=model, boundary=box.boundaries.all, value=exact),
    ),
)
mesh = StructuredTetrahedralMesher(cells=(2, 2, 2)).generate(box)
x = np.linspace(0.02, 0.98, 91)
p = np.column_stack((x, np.full_like(x, 0.27), np.full_like(x, 0.56)))
theme.use_theme()
fig, (a, b) = plt.subplots(
    2, 1, sharex=True, figsize=(7.2, 4.1), layout="constrained"
)
for flux, degree, label in (
    (RaviartThomas(2), 2, "RT2 / P2"),
    (BrezziDouglasMarini(3), 2, "BDM3 / P2"),
):
    spatial = FiniteElement(
        element=MixedDiffusionElement(flux=flux, scalar=DiscontinuousLagrange(degree))
    )
    result = Simulation(
        problem=problem,
        mesh=mesh,
        numerics=Numerics(spatial=spatial, linear_solver=SparseDirect()),
    ).solve_stationary()
    phi = result.field(model.potential).evaluate(p)
    ex = result.field(model.electric_field).evaluate(p)[:, 0]
    np.testing.assert_allclose(phi, exact(*p.T), atol=1e-8)
    np.testing.assert_allclose(ex, -2 * x, atol=1e-8)
    a.plot(x, phi, label=label)
    b.plot(x, ex, label=label)
a.set_ylabel("Potential [V]")
a.legend(frameon=False)
b.set(xlabel="World x [m]", ylabel="Electric field x [V/m]")
plt.show()
Figure computed with OneSimulation: recipe mixed hdiv