Solving the Poisson Equation on a Square¶
The Poisson equation is one of the most fundamental partial differential equations in mathematical physics. It appears in electrostatics (relating charge density to electric potential), steady-state heat conduction (relating heat sources to temperature), fluid mechanics (pressure correction), and gravitational theory.
In two dimensions, the Poisson equation reads:
In this notebook, we solve the Poisson equation on the unit square \([0, 1] \times [0, 1]\) with homogeneous Dirichlet boundary conditions (\(u = 0\) on all four edges) and a source term chosen so that the analytical solution is known. This allows us to verify the accuracy of our numerical method.
We choose:
for which the exact solution is:
Setup: Imports and Grid Creation¶
We create a 2D grid from two equidistant axes with 51 points each on \([0, 1]\). Passing the axes as keyword arguments names them x and y.
[1]:
import numpy as np
import matplotlib.pyplot as plt
from numgrids import *
grid = Grid(x=equidistant(51, 0, 1), y=equidistant(51, 0, 1))
X, Y = grid.meshed_coords
print(grid)
print(f"Total unknowns: {grid.size}")
Grid(shape=(51, 51), ndims=2, axes=[
EquidistantAxis(num_points=51, low=0, high=1, periodic=False, name='x'),
EquidistantAxis(num_points=51, low=0, high=1, periodic=False, name='y')
])
Total unknowns: 2601
Source Term and Analytical Solution¶
grid.evaluate samples a function of the coordinates on all grid points.
[2]:
f = grid.evaluate(lambda x, y: -2 * np.pi**2 * np.sin(np.pi * x) * np.sin(np.pi * y))
u_exact = grid.evaluate(lambda x, y: np.sin(np.pi * x) * np.sin(np.pi * y))
Building the Operator and Solving¶
The discrete Laplacian \(L = D^{(2)}_x + D^{(2)}_y\) is available as a sparse Operator. Its solve method applies the boundary conditions and solves the linear system \(L\,u = f\) in one step; bcs=0 means \(u = 0\) on all four edges.
[3]:
L = grid.laplacian_operator()
print(L)
u = L.solve(f, bcs=0)
print(f"Solution range: [{u.min():.6f}, {u.max():.6f}]")
print(f"Expected max (analytical): {u_exact.max():.6f}")
Operator(grid=Grid(51, 51), nnz=23817)
Solution range: [-0.000000, 1.000000]
Expected max (analytical): 1.000000
Visualization¶
3D Surface Plot of the Numerical Solution¶
[4]:
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection="3d")
surf = ax.plot_surface(X, Y, u, cmap="viridis", edgecolor="none", alpha=0.9)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("u(x, y)")
ax.set_title("Numerical Solution of the 2D Poisson Equation")
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=10, label="u")
ax.view_init(elev=30, azim=225)
plt.tight_layout()
plt.show()
Color Plot¶
grid.plot(f) draws a color plot of any field on a 2D grid and returns the matplotlib axes for further customization.
[5]:
ax = grid.plot(u, cmap="RdYlBu_r")
ax.contour(X, Y, u, levels=10, colors="k", linewidths=0.4, alpha=0.5)
ax.set_aspect("equal")
ax.set_title("Numerical Solution")
plt.show()
Comparison with the Analytical Solution¶
[6]:
error = np.abs(u - u_exact)
print(f"Maximum absolute error: {error.max():.6e}")
print(f"Mean absolute error: {error.mean():.6e}")
print(f"RMS error: {np.sqrt(np.mean(error**2)):.6e}")
Maximum absolute error: 2.072502e-07
Mean absolute error: 9.678502e-08
RMS error: 1.126879e-07
[7]:
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
for ax, field, title, cmap in zip(axes, [u, u_exact, error],
["Numerical Solution", "Analytical Solution", "Absolute Error"],
["viridis", "viridis", "hot_r"]):
grid.plot(field, ax=ax, cmap=cmap)
ax.set_title(title)
ax.set_aspect("equal")
plt.suptitle("Numerical vs. Analytical Solution", fontsize=14, y=1.02)
plt.tight_layout()
plt.show()
Spectral Accuracy with Chebyshev Axes¶
The equidistant grid uses 4th-order finite differences. Switching to Chebyshev axes gives spectral accuracy: with far fewer points, the error drops to the level of round-off. Only the grid definition changes.
[8]:
cheb_grid = Grid(x=chebyshev(20, 0, 1), y=chebyshev(20, 0, 1))
source = lambda x, y: -2 * np.pi**2 * np.sin(np.pi * x) * np.sin(np.pi * y)
u_cheb = cheb_grid.laplacian_operator().solve(source, bcs=0)
err_cheb = np.max(np.abs(u_cheb - cheb_grid.evaluate(lambda x, y: np.sin(np.pi * x) * np.sin(np.pi * y))))
print(f"Equidistant {grid.shape}: max error = {error.max():.2e}")
print(f"Chebyshev {cheb_grid.shape}: max error = {err_cheb:.2e}")
Equidistant (51, 51): max error = 2.07e-07
Chebyshev (20, 20): max error = 4.09e-13
Mixed Boundary Conditions¶
Boundary conditions can be specified per face with a dictionary. Here we model a plate with a heat source, kept at temperature 0 on the left, at a sinusoidal temperature profile on the right, and insulated (Neumann, \(\partial u/\partial n = 0\)) at the top and bottom.
[9]:
u_mixed = cheb_grid.laplacian_operator().solve(-1.0, bcs={
"x_low": 0.0,
"x_high": lambda c: np.sin(np.pi * c[1]),
"y_low": Neumann(0.0),
"y_high": Neumann(0.0),
})
ax = cheb_grid.plot(u_mixed, cmap="inferno")
ax.set_aspect("equal")
ax.set_title("Mixed Dirichlet / Neumann conditions")
plt.show()
# The insulated edges indeed have zero normal derivative:
print("max |du/dn| on y_high:", np.abs(cheb_grid.faces["y_high"].normal_derivative(u_mixed)).max())
max |du/dn| on y_high: 2.11119553777339e-12
Conclusion¶
Solving the Poisson equation with numgrids takes three steps:
Define the grid – e.g.
Grid(x=equidistant(51, 0, 1), y=equidistant(51, 0, 1)).Get the operator –
L = grid.laplacian_operator().Solve –
u = L.solve(f, bcs=0), with boundary conditions given compactly, per face if needed.
Finite-difference grids converge algebraically, while Chebyshev grids reach machine precision with only a few points per direction for smooth problems like this one.