capacitor-fem
A self-contained 2D finite-element electrostatics solver for real capacitor geometries — parallel plates, coaxial cables, and arbitrary shapes built from simple primitives — rather than closed-form formulas that exist only for a few idealized cases.
Pure NumPy / SciPy / Matplotlib. No mesh-generation library, no compiled extensions, no native dependencies. One file, runs anywhere:
python3 capacitor_fem_universal.py
capacitor_fem_universal.py is the single, platform-independent implementation.
All future work continues there.
This document covers the physics, mathematics, numerical method, software architecture, and usage of the code. It assumes familiarity with vector calculus, linear algebra, and Python, but not necessarily with finite elements; the derivation starts from Maxwell's equations and builds up from there.
Current status
- Structured triangular mesh with optional graded Cartesian refinement for the parallel-plate example.
- Independent bottom/top plate widths; optional rounded (filleted) plate edges via
edge_radius / RoundedRectangle.
- Constructor-time and post-snap_to_grid validation of geometry and material parameters.
- General two-run comparison tool (
compare_parallel_plate_runs) that plots any two ParallelPlateConfigs on a shared |E| colour scale.
- Runs unchanged on desktop, Jupyter / Carnets (static plots), and Pydroid 3 on Android.
- Core FEM numerics remain a direct sparse solve; safeguards added for under-determined systems and degenerate triangles.
Known limitations (summary)
- Structured (non-conforming) mesh: curved and non-axis-aligned boundaries are staircased (see §10.1–10.3).
- Direct sparse LU solve scales poorly in memory and time at very fine
h (see §4.6).
- Peak
|E| near any plate edge (sharp or rounded) is not mesh-converged at the shipped resolutions; only bulk fields and integrated quantities such as C are trustworthy (see §10.5).
- Domain-size truncation (
domain_margin) is a second, independent convergence axis (see §10.6).
- Intended use: practical engineering approximation for education, basic design comparison, and material selection — not a high-accuracy tool for geometries dominated by curved boundaries or sharp singularities.
Recent changes
- Graded Cartesian mesh support and independent plate widths.
- Robust validation of geometry/material fields (including post-snap checks).
- Optional rounded plate edges (
edge_radius, RoundedRectangle) with bit-for-bit compatibility at edge_radius=0.
- Shared-scale comparison tool (
compare_parallel_plate_runs).
- Android / Pydroid save-only plotting path and general robustness improvements.
- Conservative handling of under-determined solves and degenerate-triangle warnings.
Full discussion of each item, measured accuracy, and remaining limitations appears in the sections below.
Table of Contents
1. Overview
Given a set of conductors at fixed voltages and a (possibly spatially varying)
dielectric filling the space between them, the solver computes the electric
potential $V(x,y)$ everywhere, and from it:
$$
\mathbf{E} = -\nabla V \qquad \mathbf{D} = \varepsilon\mathbf{E} \qquad W = \frac{1}{2}\int_\Omega \mathbf{E}\cdot\mathbf{D}\,dA \qquad C = \frac{2W}{(\Delta V)^2}
$$
the electric field, displacement, stored energy, and two-conductor capacitance. The
same solver handles a parallel-plate capacitor, a coaxial cable, or any geometry built
from the shape primitives in the code, without changing a line of the physics.
Two design decisions shape everything below, and are worth stating up front because
they explain most of the trade-offs discussed later:
- A structured (Cartesian-derived) mesh, not an unstructured/conforming one.
This is what keeps the tool dependency-free — no
gmsh, no compiled mesh
libraries — at the cost of approximating curved or non-axis-aligned boundaries
with a staircase of grid cells. Section 10 quantifies exactly what this costs.
- Capacitance from stored energy, not from integrating charge along a boundary.
The energy method only needs a field that is already computed everywhere in the
domain; a charge-based method would need to differentiate a numerically noisy
field along a boundary, which amplifies error. See §3.7.
2. Physics: From Maxwell's Equations to the Governing PDE
Electrostatics is the time-independent limit of Maxwell's equations. Two of them
are relevant here. Gauss's law relates the electric displacement field to free
charge density $\rho_f$:
$$\nabla\cdot\mathbf{D} = \rho_f$$
and, because there is no time-varying magnetic field, Faraday's law reduces to
$\nabla\times\mathbf{E}=0$. A curl-free field is a gradient field, so it can always
be written in terms of a scalar potential:
$$\mathbf{E} = -\nabla V$$
For a linear, isotropic, non-dispersive dielectric, $\mathbf{D}$ and $\mathbf{E}$
are related by a scalar (position-dependent) permittivity:
$$\mathbf{D} = \varepsilon\,\mathbf{E}, \qquad \varepsilon(x,y) = \varepsilon_0\,\varepsilon_r(x,y)$$
Inside a capacitor's dielectric there is no free charge — all of it resides on the
conductor surfaces, which enter the problem as boundary conditions rather than a
volumetric source term — so $\rho_f = 0$ in the domain and Gauss's law reduces to
$$\nabla\cdot\mathbf{D} = 0$$
Substituting the previous two relations gives the equation the solver actually
solves:
$$\boxed{\ \nabla\cdot\big(\varepsilon\,\nabla V\big) = 0\ }$$
a generalized Poisson equation. When $\varepsilon$ is uniform this is the ordinary
Laplace equation $\nabla^2 V = 0$; allowing $\varepsilon$ to vary in space is what
lets one solver handle mixed dielectrics (glass and air, or a coax cable's
polyethylene fill) without any change to the governing equation.
A conductor in electrostatic equilibrium is an equipotential region: any
tangential field along its surface would drive current until it vanished. Each
conductor therefore contributes a Dirichlet boundary condition $V = V_k$ on its
surface, where $V_k$ is the applied voltage.
3. Mathematical Formulation
3.1 Weak (Variational) Form
The finite element method solves the PDE in weak (integral) form rather than
pointwise. Multiply the governing equation by an arbitrary test function $w$ and
integrate over the domain $\Omega$:
$$0 = \int_\Omega w\,\nabla\cdot(\varepsilon\nabla V)\,dA$$
Using the product rule $\nabla\cdot(w\,\varepsilon\nabla V) = w\,\nabla\cdot(\varepsilon\nabla V) + \varepsilon\nabla w\cdot\nabla V$
and the divergence theorem converts this to
$$0 = \oint_{\partial\Omega} w\,\varepsilon\,\frac{\partial V}{\partial n}\,ds \;-\; \int_\Omega \varepsilon\,\nabla w\cdot\nabla V\,dA$$
Restricting $w$ to functions that vanish on the Dirichlet (conductor) boundaries
eliminates that part of the boundary integral. No flux condition is imposed on the
remaining outer domain boundary — this is the weak form's natural boundary
condition, corresponding physically to zero prescribed normal component of $\mathbf{D}$ there.
What remains is the weak form the solver assembles:
$$\int_\Omega \varepsilon\,\nabla w\cdot\nabla V\,dA = 0 \qquad \text{for every admissible } w$$
This formulation only ever requires first derivatives of $V$, unlike the original
PDE which requires second derivatives — the reason piecewise-linear elements
(§3.3), whose second derivatives are zero everywhere, are already sufficient.
3.2 Galerkin Discretization
Approximate $V$ as a linear combination of a finite set of basis (nodal shape)
functions $N_j$:
$$V(x,y) \approx \sum_j V_j\,N_j(x,y)$$
The Galerkin method chooses the test functions from the same basis, $w = N_i$.
Substituting into the weak form for every $i$ turns the continuous PDE into a
finite linear system:
$$\sum_j K_{ij}\,V_j = 0, \qquad K_{ij} = \int_\Omega \varepsilon\,\nabla N_i\cdot\nabla N_j\,dA$$
$K$ is the global stiffness matrix — symmetric, sparse (since $N_i$ and $N_j$
overlap only for nodes sharing an element), and singular before boundary
conditions are applied (adding a constant to $V$ everywhere doesn't change the
energy — the classic "floating ground" gauge freedom of a pure-Neumann system).
3.3 Linear Triangular (P1) Elements
The domain is triangulated (§4.1), and on each triangle $V$ is approximated as
linear. For a triangle with vertices $(x_1,y_1),(x_2,y_2),(x_3,y_3)$, define
$$b_1=y_2-y_3,\quad b_2=y_3-y_1,\quad b_3=y_1-y_2$$
$$c_1=x_3-x_2,\quad c_2=x_1-x_3,\quad c_3=x_2-x_1$$
$$2A_{\text{signed}} = x_1(y_2-y_3) + x_2(y_3-y_1) + x_3(y_1-y_2)$$
The three linear ("hat") shape functions, each equal to 1 at their own node and 0
at the other two, are
$$N_i(x,y) = \frac{a_i + b_i x + c_i y}{2A_{\text{signed}}}$$
with gradients that are constant over the element (a direct consequence of
$N_i$ being linear):
$$\nabla N_i = \frac{1}{2A_{\text{signed}}}\,(b_i,\,c_i)$$
Using the signed area here is what makes this formula correct regardless of
whether a triangle's vertices happen to be listed clockwise or counterclockwise:
relabeling the vertices in the opposite order flips the sign of every $b_i,c_i$
and of $A_{\text{signed}}$ together, leaving $\nabla N_i$ unchanged — as it must
be, since a shape function's gradient is a geometric property of the triangle, not
an artifact of how its corners happened to be listed. _triangle_geometry in the
code computes exactly this.
3.4 The Element Stiffness Matrix
Because $\nabla N_i$ is constant per element, the local integral is just the
integrand times the element's area — but here the unsigned (physical) area
$|A|$ is needed, since this is a genuine area integral, not a gradient:
$$K^e_{ij} = \varepsilon_e \int_{\Omega_e} \nabla N_i\cdot\nabla N_j\,dA = \varepsilon_e\,\frac{b_i b_j + c_i c_j}{4\,|A|}$$
Assembly sums each element's $3\times 3$ local matrix into the global $K$ at the
corresponding global node indices — standard finite-element scatter-add,
detailed as an implementation matter in §4.4.
3.5 Dirichlet Boundary Conditions
Partition the nodes into fixed (Dirichlet, voltage known) and free
(unknown) sets. The assembled system $KV=0$ block-partitions as
$$\begin{pmatrix}K_{ff} & K_{fd}\\ K_{df} & K_{dd}\end{pmatrix}\begin{pmatrix}V_f\\ V_d\end{pmatrix} = \begin{pmatrix}0\\ \cdot\end{pmatrix}$$