Adaptive Mesh Refinement in Action

When solving problems on numerical grids, one of the hardest practical questions is: how many grid points do I need along each axis? Too few points and the solution is inaccurate; too many and you waste memory and compute time. The problem is especially acute for anisotropic functions – functions that vary rapidly in one direction but smoothly in another.

In this notebook we demonstrate how numgrids can automatically determine the resolution needed along each axis using adaptive mesh refinement (AMR). The core idea is Richardson-extrapolation-style error estimation: for each axis, refine that axis alone, re-evaluate the function, interpolate back, and measure the difference. The axis whose refinement changes the answer the most is the resolution bottleneck and gets refined first.

Because numgrids uses tensor-product grids, refinement is performed per-axis rather than per-cell. This keeps all existing operators (differentiation, integration, interpolation) working unchanged while still allowing anisotropic resolution – on Cartesian and curvilinear grids alike.

[1]:
import numpy as np
import matplotlib.pyplot as plt
from numgrids import *

Defining the Test Function

We use a 2D function with deliberately anisotropic complexity:

\[f(x, y) = \tanh\bigl(20\,(x - 0.5)\bigr) \cdot \cos(2\pi y)\]
  • Along x, \(\tanh(20(x - 0.5))\) has a steep transition layer near \(x = 0.5\) with a width of roughly \(1/20 = 0.05\), so many grid points are needed to resolve it.

  • Along y, \(\cos(2\pi y)\) is smooth and slowly varying and requires far fewer points.

The adaptation routines take a function grid -> array, so the quantity of interest can be re-evaluated on any refined grid. grid.evaluate samples a function of the coordinates.

[2]:
def my_func(grid):
    return grid.evaluate(lambda x, y: np.tanh(20 * (x - 0.5)) * np.cos(2 * np.pi * y))

One-Shot Error Estimation

Before running the full adaptation loop, estimate_error gives a snapshot of the discretization error on a coarse grid: the global error and the per-axis contributions.

[3]:
coarse_grid = Grid(x=equidistant(15, 0, 1), y=equidistant(15, 0, 1))

error_report = estimate_error(coarse_grid, my_func)
print(f"Global error estimate: {error_report['global']:.6f}")
for axis_idx, err in error_report["per_axis"].items():
    print(f"  axis {coarse_grid.axes[axis_idx].name}: {err:.6f}")
Global error estimate: 0.027817
  axis x: 0.022725
  axis y: 0.005862

As expected, the error along x (the sharp \(\tanh\) transition) is much larger than along y: x is the resolution bottleneck.

Full Adaptive Refinement

adapt iteratively identifies the worst-resolved axis and refines it until the global error drops below a prescribed tolerance.

[4]:
result = adapt(coarse_grid, my_func, tol=1e-4, norm="max")

print(f"Converged:   {result.converged}")
print(f"Final shape: {result.grid.shape}")
print(f"Final error: {result.global_error:.2e}")
print(f"Iterations:  {result.iterations}")
Converged:   True
Final shape: (480, 240)
Final error: 5.46e-05
Iterations:  10

The x axis is refined first and ends up with twice as many points as y, reflecting the anisotropy of the function. Refinement keeps the axis names, so the result can be used just like the original grid:

[5]:
ax = result.grid.plot(result.f, cmap="RdBu_r")
ax.set_aspect("equal")
ax.set_title(f"Target function on adapted grid {result.grid.shape}")
plt.show()
../_images/examples_adaptive-refinement-demo_9_0.png

Adaptation History

result.history contains diagnostics for each iteration: the grid shape, global error, per-axis errors and which axis was refined.

[6]:
print(f"{'Iter':>4}  {'Shape':>14}  {'Global Error':>12}  {'x error':>12}  {'y error':>12}  Refined")
print("-" * 78)
names = [ax.name for ax in coarse_grid.axes]
for record in result.history:
    refined = [names[int(k.replace("refined_axis_", ""))] for k in record if k.startswith("refined_axis_")]
    errs = record["axis_errors"]
    print(f"{record['iteration']:>4}  {str(record['shape']):>14}  {record['global_error']:>12.4e}"
          f"  {errs[0]:>12.4e}  {errs[1]:>12.4e}  {', '.join(refined) or '-'}")
Iter           Shape  Global Error       x error       y error  Refined
------------------------------------------------------------------------------
   0        (15, 15)    2.7817e-02    2.2725e-02    5.8620e-03  x
   1        (30, 15)    1.3362e-02    8.8671e-03    5.8620e-03  x
   2        (60, 15)    6.6690e-03    2.5626e-03    5.8620e-03  y
   3        (60, 30)    3.4914e-03    2.5626e-03    1.4075e-03  x
   4       (120, 30)    1.6226e-03    6.6374e-04    1.4075e-03  y
   5       (120, 60)    8.7943e-04    6.6374e-04    3.4787e-04  x
   6       (240, 60)    4.0297e-04    1.6672e-04    3.4787e-04  y
   7      (240, 120)    2.1876e-04    1.6672e-04    8.6355e-05  x
   8      (480, 120)    1.0023e-04    4.1663e-05    8.6355e-05  y
   9      (480, 240)    5.4627e-05    4.1663e-05    2.1506e-05  -
[7]:
iterations = [r["iteration"] for r in result.history]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))

ax1.semilogy(iterations, [r["global_error"] for r in result.history], "o-", color="#c0392b")
ax1.axhline(1e-4, color="gray", linestyle="--", linewidth=1, label="tolerance = $10^{-4}$")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Global Error (max norm)")
ax1.set_title("Convergence of Global Error")
ax1.legend()
ax1.grid(True, alpha=0.3)

ax2.plot(iterations, [r["shape"][0] for r in result.history], "s-", color="#2980b9", label="x")
ax2.plot(iterations, [r["shape"][1] for r in result.history], "^-", color="#27ae60", label="y")
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Number of Grid Points")
ax2.set_title("Grid Resolution per Axis")
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.suptitle("Adaptation History", fontsize=14, y=1.02)
plt.tight_layout()
plt.show()
../_images/examples_adaptive-refinement-demo_12_0.png

Comparison: Uniform Grid vs Adapted Grid

We compare the adapted grid with a uniform grid that uses the same total number of points. Both have roughly the same computational cost, but the adapted grid distributes its points according to the needs of each direction and therefore reaches a smaller error.

[8]:
N0, N1 = result.grid.shape
N_uniform = int(np.sqrt(N0 * N1))
uniform_grid = Grid(x=equidistant(N_uniform, 0, 1), y=equidistant(N_uniform, 0, 1))

uniform_error = estimate_error(uniform_grid, my_func)["global"]
adapted_error = estimate_error(result.grid, my_func)["global"]

print(f"Adapted grid {result.grid.shape}: {result.grid.size} points, error {adapted_error:.2e}")
print(f"Uniform grid {uniform_grid.shape}: {uniform_grid.size} points, error {uniform_error:.2e}")
print(f"Error ratio (uniform / adapted): {uniform_error / adapted_error:.1f}x")
Adapted grid (480, 240): 115200 points, error 5.46e-05
Uniform grid (339, 339): 114921 points, error 8.98e-05
Error ratio (uniform / adapted): 1.6x
[9]:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5))
for ax, grid, f, err in [(ax1, uniform_grid, my_func(uniform_grid), uniform_error),
                         (ax2, result.grid, result.f, adapted_error)]:
    grid.plot(f, ax=ax, cmap="RdBu_r")
    ax.set_aspect("equal")
    ax.set_title(f"{'Adapted' if grid is result.grid else 'Uniform'} grid {grid.shape}\nError: {err:.2e}")
plt.suptitle("Uniform vs Adapted Grid (same total points)", fontsize=14, y=1.02)
plt.tight_layout()
plt.show()
../_images/examples_adaptive-refinement-demo_15_0.png

Adapting a PDE Solution on a Curvilinear Grid

The function passed to adapt can be anything that maps a grid to an array – including a full PDE solve. Here we solve the Poisson equation on an annulus with a source concentrated in a thin ring at \(r = 0.75\):

\[\nabla^2 u = e^{-\left((r - 0.75)/0.05\right)^2} \cos\varphi, \qquad u = 0 \text{ at } r = 0.5 \text{ and } r = 1.\]

The source is sharp in \(r\) but smooth in \(\varphi\). Refinement preserves the grid type, so every refined grid is again a PolarGrid with its Laplacian.

[10]:
def solve_ring_source(grid):
    source = lambda r, phi: np.exp(-((r - 0.75) / 0.05)**2) * np.cos(phi)
    return grid.laplacian_operator().solve(source, bcs=0)

polar_start = PolarGrid(chebyshev(10, 0.5, 1.0), periodic(8))
polar_result = adapt(polar_start, solve_ring_source, tol=1e-6)

print(f"Converged:   {polar_result.converged}")
print(f"Grid type:   {type(polar_result.grid).__name__}")
print(f"Final shape: {polar_result.grid.shape}  (r, phi)")
print(f"Final error: {polar_result.global_error:.2e}")

# With only 8 angular points, a direct color plot would look polygonal. Spectral interpolation
# onto a finer grid gives a smooth picture without loss of accuracy.
fine = PolarGrid(chebyshev(160, 0.5, 1.0), periodic(64))
u_fine = polar_result.grid.interpolate(polar_result.f, fine, method="spectral")

ax = fine.plot(u_fine, cmap="RdBu_r")
ax.set_title(f"Solution on adapted grid {polar_result.grid.shape} (interpolated for display)")
plt.show()
Converged:   True
Grid type:   PolarGrid
Final shape: (160, 8)  (r, phi)
Final error: 7.40e-07
../_images/examples_adaptive-refinement-demo_17_1.png

The radial axis is refined heavily to resolve the thin ring, while the angular axis needs only a handful of points for the single \(\cos\varphi\) mode.

Summary

  1. ``estimate_error`` provides a quick diagnostic that reveals which axis is under-resolved.

  2. ``adapt`` automates the refinement loop: starting from a coarse grid, it refines the worst-resolved axis until a target tolerance is met, producing an anisotropic grid that is fine where needed and coarse where possible.

  3. Anisotropic refinement beats uniform refinement: for the same number of points, the adapted grid is more accurate. The more anisotropic the problem, the larger the gain – the PDE example needed 160 radial but only 8 angular points.

  4. The quantity of interest can be a PDE solution, and adaptation works on curvilinear grids too.