Fundamentals / Physics / Electrodynamics / Numerical field laboratory

A converged field solver can still give the wrong voltage

Verify a two-dimensional electrostatic calculation with two independent charge patterns. Use symmetry to distinguish a transposed output, a coarse mesh and a poorly converged linear solve.

Choose a voltage before choosing a solver

A very long grounded tube has a square cross section \(0\le x,y\le L\), with \(L=1\) m. The contents are uniform along the axis. A model of its transverse charge density should predict what a voltage probe placed inside would measure. Three numerical statements that can sound similar are actually quite different: the discrete equations have a small residual, the grid solution approximates the continuous solution, and the physical source describes the tube. We can test the first two in a laboratory problem where the last is specified exactly.

Start by prescribing a voltage that satisfies all four walls. Introduce \(s_m(x)=\sin(m\pi x/L)\) and choose \(V_*(x,y)=[s_1(x)+g s_2(x)]s_1(y)\) volts. The parameter \(g\) is the signed amplitude of the second spatial pattern relative to the first. A probe at the centre sees exactly 1 V for every \(g\), since \(s_2(L/2)=0\). A calculation checked at that point alone could entirely lose the second pattern and still pass. At \(x=L/4\) on the centreline, \(V_*=1/\sqrt2+g\); at \(3L/4\) it is \(1/\sqrt2-g\). Their difference is \(2g\) volts. First write down all three expected readings for \(g=0.5\).

Manufacture the source by differentiating the field

The physical problem uses Gauss's law and the electrostatic relation \(\mathbf E=-\nabla V\). For uniform vacuum permittivity they yield

\[-\nabla^2V=\rho/\epsilon_0.\]

A product \(s_m(x)s_1(y)\) returns the factor \((m^2+1)\pi^2/L^2\) when acted on by the negative Laplacian. Applying this separately to the two patterns gives

\[\rho/\epsilon_0=(\pi/L)^2[2s_1(x)+5g s_2(x)]s_1(y)\ {\rm V}.\]

The right side has dimensions V/m² after including the factor \(L^{-2}\); multiplication by permittivity gives C/m³. When \(g\) becomes large enough, part of the imposed density changes sign. That is permissible for a manufactured source. The calculation represents a solution of the stated Poisson problem. Judging whether a particular apparatus could maintain that charge requires its own charge-transport model.

Uniqueness gives the reference solution special status. If there were a different voltage for the same walls and charge, their difference \(w\) would satisfy Laplace's equation with zero boundary value. Integrate \(w(-\nabla^2 w)\) over the square. Integration by parts leaves \(\int|\nabla w|^2\), because \(w\) is zero on the boundary. The integral must vanish; \(w\) is constant and its boundary makes that constant zero. This is why agreement with the manufactured voltage is a test of the solver and its input, rather than a choice between two physical solutions.

Background · How can the same source test a second boundary condition?

A smooth manufactured solution that vanishes on every edge tests a homogeneous Dirichlet solve. A code that incorrectly sets every requested boundary voltage to zero may still pass. Add a harmonic lift to the known field on a square of width \(L\). For a constant permittivity the charge depends on the Laplacian, so the exact source is unchanged.

\[\widetilde V(x,y)=V(x,y)+V_0\!\left(1+\frac{x}{L}\right),\]
\[-\epsilon\nabla^2\widetilde V=-\epsilon\nabla^2 V.\]

Prescribe the lifted values on all four sides and solve again using the same charge samples. The difference of the computed solutions should be the linear lift, which a centred second difference represents exactly on a uniform grid. A discrepancy points first to boundary-value handling or to the way known values enter the right-hand side. This comparison isolates that error from the truncation error on the original sine modes.

Solve the discrete problem on paper as a second reference

Let \(h=L/n\). The standard negative Laplacian has centre coefficient \(4/h^2\) and four neighbouring coefficients \(-1/h^2\). Substitute the samples of \(s_m(x)s_1(y)\). In the \(x\) direction the sum of forward and backward neighbours is twice the centre value times \(\cos(m\pi/n)\). Collect the corresponding \(y\) term. The resulting positive grid eigenvalue is

\[\lambda_{h,m}=\frac{4}{h^2}\left[\sin^2\!\frac{m\pi}{2n}+\sin^2\!\frac{\pi}{2n}\right].\]

The continuum eigenvalue is \(\lambda_m=(m^2+1)(\pi/L)^2\). If the source is the continuous source sampled at the nodes, the discrete voltage coefficient is multiplied by \(\lambda_m/\lambda_{h,m}\). Since \(\sin z<z\) for positive \(z\), each factor exceeds one on a resolving grid. The faster spatial oscillation has the larger relative bias. The resulting total pointwise error can still change sign because the spatial modes themselves have signs.

This provides three independent calculations: a continuous closed-form field, an exact solution of the chosen difference equations and a numerical linear solve. Agreement of the latter two isolates assembly, indexing and algebraic errors. Comparing either with the continuous solution measures spatial discretisation error. Tightening an iterative tolerance indefinitely cannot remove a difference between \(\lambda_{h,m}\) and \(\lambda_m\).

Run the full field and compare genuinely different observations

The browser constructs the right-hand side over the two-dimensional interior and applies conjugate gradients to the five-point operator from an all-zero initial field. The two-mode right-hand side belongs to a two-dimensional invariant subspace, so exact-arithmetic convergence takes at most two iterations. In the special case \(g=0\), only one mode is excited. This unusually small iteration count is a property of the test and says very little about a rough source on the same grid.

Download the model and run the displayed case. Its CSV contains the midline \(y=L/2\), ordered by increasing \(x\). For \(n=16,\ g=2\) the value at \(x=0.1875\) m is about 2.42542 V on the grid and 2.40333 V analytically. If the centre is correct but the 0.1875 m reading is about 0.55736 V, check the orientation of the sampled data array. Keeping \(x\) fixed at its midpoint instead of \(y\) happens to annihilate the entire second mode.

A convergence report a second person can reproduce

Set \(g=0.5\). Record the centre voltage, the quarter-point voltage difference, the largest nodal error and the relative algebraic residual for \(n=8,16,32\). Use even grids divisible by four if reading exact quarter points. Estimate an order from two successive maximum errors using \(p=\log(E_n/E_{2n})/\log2\). For this smooth problem the leading difference between \(\sin^2 z\) and \(z^2\) is proportional to \(z^4\), giving a second-order spatial error at fixed physical modes. If \(g\) or the physical source profile changes during refinement, the ratio no longer tests that claim.

An experiment that quotes only the centre voltage has poor sensitivity to \(g\). An experiment quoting only the algebraic residual may perfectly solve the wrong mesh problem. An experiment that compares each plot to itself after smoothing lacks an independent reference. The three diagnostics above address these difficulties with quantities small enough to check by hand.

Extend the verification to a genuinely three-dimensional field

Ground all six faces of a cube with side length L=1 m. A potential that varies in every coordinate is

\[V_*(x,y,z)=A\sin(\pi x/L)\sin(\pi y/L)\sin(\pi z/L),\]
\[\rho=3\epsilon(\pi/L)^2 V_*.\]

Each second derivative contributes −(π/L)² times the potential. Adding the three derivatives gives the source above; every boundary vanishes because one sine is zero. This is a manufactured source for checking a numerical method. In the supplied calculation ε=1 F/m and A=1 V; scaling both charge and permittivity together leaves the voltage unchanged.

On a uniform nodal grid, the seven-point negative Laplacian has centre coefficient 6/h² and six neighbour coefficients −1/h². The same sine addition identity used in two dimensions gives

\[\lambda_h={12\over h^2}\sin^2\!\left({\pi h\over2L}\right),\]
\[V_h={3(\pi/L)^2\over\lambda_h}V_* .\]

The browser evaluates this discrete eigenmode directly. The spatial view places a coloured slice inside the cube; its height is the physical z coordinate. Moving that slice reveals the interior field while the companion line plot compares the grid values with the exact three-dimensional solution. The numerical potential is slightly too large because λh is smaller than its continuum limit.

Try it · Rotate a 3D field, move its slice and refine its mesh

Move the plane from the centre to a grounded face and predict the change. Then compare 8 and 16 cells per direction: the maximum nodal error should decrease by approximately four. Doubling A doubles the absolute error while leaving the relative error almost unchanged. Rotation changes the viewpoint only.

Download the 3D OneSimulation notebook · Download Python script

The notebook assembles and solves the full 3D OneSimulation finite-difference model. It reports an RMS error at cell centres; the browser reports a maximum error at nodes for its stated seven-point operator. These are different diagnostics. Compare each against its own continuous reference and repeat with a finer mesh.

"""Solve a grounded three-dimensional cube with OneSimulation and verify the field."""
import argparse
from dataclasses import dataclass
import numpy as np
import matplotlib.pyplot as plt
from onesim.cad.d3 import Box
from onesim.meshing import StructuredHexahedralMesher
from onesim.numerics import Numerics
from onesim.numerics.linear import SparseDirect
from onesim.numerics.fdm import FiniteDifference, CentralDifference, CentralLaplacian
from onesim.physics.electrostatics import FixedPotential, PoissonEquation
from onesim.simulation import Problem, Simulation

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--cells', type=int, default=16)
parser.add_argument('--amplitude', type=float, default=1.0, help='Reference potential amplitude in V')
parser.add_argument('--slice', type=float, default=50, help='Depth as a percentage of the cube')
args = parser.parse_args()
if not 8 <= args.cells <= 24 or not np.isfinite(args.amplitude) or args.amplitude <= 0 or not 0 <= args.slice <= 100:
    parser.error('Use 8–24 cells, a finite positive amplitude, and a slice between 0 and 100 percent')

@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: args.amplitude * 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='Three-dimensional manufactured potential', geometry=cube, physics=(field,),
                  boundary_conditions=(FixedPotential(physics=field, boundary=cube.boundaries.all, value=0.0),))
mesh = StructuredHexahedralMesher(cells=(args.cells,)*3).generate(cube)
simulation = Simulation(problem=problem, mesh=mesh, numerics=Numerics(
    spatial=FiniteDifference(gradient=CentralDifference(), diffusion=CentralLaplacian()),
    linear_solver=SparseDirect()))
simulation.validate().require_valid()
result = simulation.solve_stationary()
potential = result.field(field.potential)
centres = mesh.coordinates[mesh.cells].mean(axis=1)
computed = potential.evaluate(centres)
reference = exact(*centres.T)
error = np.sqrt(np.mean((computed-reference)**2))
z = round(args.cells*args.slice/100)/args.cells
print(f'{args.cells}³ cells; source amplitude {args.amplitude:g} V; slice z={z:.3f} m')
print(f'Cell-centre RMS error against the exact 3D solution: {error:.6e} V')

x = np.linspace(0,1,41)
X,Y = np.meshgrid(x,x)
points = np.column_stack([X.ravel(),Y.ravel(),np.full(X.size,z)])
V = potential.evaluate(points).reshape(X.shape)
line = np.column_stack([x,np.full_like(x,.5),np.full_like(x,z)])
fig = plt.figure(figsize=(10,4),layout='constrained')
ax = fig.add_subplot(121,projection='3d')
surface = ax.plot_surface(X,Y,V,cmap='viridis',linewidth=0)
ax.set(xlabel='x (m)',ylabel='y (m)',zlabel='Potential (V)',title=f'Computed slice at z={z:g} m')
ax = fig.add_subplot(122)
ax.plot(x,potential.evaluate(line),'o',markevery=2,label='OneSimulation FDM')
ax.plot(x,exact(x,.5,z),'--',label='Exact 3D solution')
ax.set(xlabel='x at y=0.5 m (m)',ylabel='Potential (V)')
ax.grid(alpha=.2); ax.legend()
fig.savefig('poisson-cube-3d.png',dpi=170)
assert np.isfinite(error) and error/args.amplitude < .02

Measured output at the default settings:

16³ cells; source amplitude 1 V; slice z=0.500 m
Cell-centre RMS error against the exact 3D solution: 1.138076e-03 V
OneSimulation potential on the midplane of a grounded three-dimensional cube, with a centreline comparison to the exact solution
Actual OneSimulation output. Here the left panel plots potential as height above the selected x–y plane; the right panel compares the same field along y=0.5 m.

Tutorial

A colleague sets \(g=-0.4\) and reports quarter-point voltages 1.107 V and 0.307 V on a very fine grid. Which change in the recorded setup would explain the observation?

Work through the solution

For the stated sign, the expected pair in increasing \(x\) is 0.3071 V then 1.1071 V. Reversing the \(x\) axis interchanges the pair while preserving the centre and the symmetric mode. Reversing the sign of the second source mode produces the same pair. A field measurement with a labelled coordinate direction distinguishes these possibilities.

You prescribe the discrete eigenvalue as the source amplitude during every refinement. The returned solution agrees with your analytic curve at all nodes to machine precision. Which part of the verification has disappeared?

Work through the solution

This tests the algebra of the discrete eigenmode and the linear solve. It changes the continuum source on every grid and cancels exactly the spatial discretisation error you intended to measure. Rerun with a wavelength and source amplitude specified in physical units independently of the grid.

A second probe has independent voltage noise of standard deviation 5 mV. Estimate the standard deviation of \(g\) inferred from the difference of the two quarter-point readings, if both probes have the same independent noise.

Work through the solution

The difference has variance \(2(0.005)^2\) V² and equals \(2g\) volts. Dividing by two gives standard deviation \(0.005/\sqrt2\simeq0.00354\) in the dimensionless amplitude. A shared additive offset cancels; a gain error common to both readings does not.