Skip to content
Projects

Graded axes

Download notebookView on GitHubRun when the site was built.

Patches refine by a fixed ratio, so the cell size jumps by two at every patch edge. Where the fine structure lies along a whole face of the domain (a sheath at a wall, the meniscus and the gaps of an extraction system along the beam axis), a mesh whose cells grow smoothly away from it does the same job with fewer cells and without the jumps. An axis of AMRHierarchy is graded by axis_nodes: the physical positions of its base nodes.

The map from the uniform logical coordinate (the one patches, levels and kernels work in) to the physical one is linear in every base cell. So every leaf cell, on any level, is a physical box: finer levels split the base cells evenly, and patches, the composite spaces and the solvers work on graded axes as on uniform ones, with the physical sizes in their metric.

import matplotlib.pyplot as plt
import numpy as np
from patchwork import AMRHierarchy, CellOperator, Dirichlet, NodalPoisson, plot_patches
def tanh_nodes(n: int, length: float, first: float) -> np.ndarray:
# n cells over [0, length], the first about `first` long, growing smoothly
s = np.linspace(0.0, 1.0, n + 1)
beta = 1.0
for _ in range(60): # the stretching that gives the first cell's size
x = 1.0 + np.tanh(beta * (s - 1.0)) / np.tanh(beta)
beta *= (x[1] * length / first) ** 0.2
return length * x
nodes = tanh_nodes(16, 1.0, 0.01)
mesh = AMRHierarchy((16, 8), axis_nodes=(nodes, None))
mesh.add_patch(level=1, box=((24, 32), (4, 12)))
print("first and last cell:", np.round(np.diff(nodes)[[0, -1]], 4))
print(
"largest ratio of neighbouring cells:",
np.round(np.max(np.diff(nodes)[1:] / np.diff(nodes)[:-1]), 3),
)
fig, ax = plt.subplots(figsize=(6, 3.2))
plot_patches(mesh, ax=ax)
ax.set_title("16 x 8 base cells, graded toward x = 0, and a patch")
fig.tight_layout()
first and last cell: [0.01 0.1303]
largest ratio of neighbouring cells: 1.274
Notebook output

−u′′+u/ε2=0-u'' + u/\varepsilon^2 = 0 on 0<x<10 < x < 1 with u(0)=1u(0) = 1 and u(1)=0u(1) = 0 has the layer u≈e−x/εu \approx e^{-x/\varepsilon} at the wall. With ε=0.01\varepsilon = 0.01, a uniform mesh needs hundreds of cells before it resolves it (its error even grows at first); a graded one whose first cell is a fraction of the layer (4ε/n4\varepsilon/n) converges at second order from a few dozen cells. CellOperator on a line, the same call on both:

EPS = 0.01
def exact(x):
return np.sinh((1.0 - x) / EPS) / np.sinh(1.0 / EPS)
def layer_error(n: int, graded: bool) -> float:
axis = tanh_nodes(n, 1.0, 4.0 * EPS / n) if graded else None
mesh = AMRHierarchy((n,), axis_nodes=(axis,))
solver = CellOperator(
mesh,
reaction=1.0 / EPS**2,
faces={"x_lower": Dirichlet(1.0), "x_upper": Dirichlet(0.0)},
)
u = solver.solve(0.0)
x = solver.cells.centers[:, 0]
return float(np.abs(u - exact(x)).max())
print(" cells uniform graded")
for n in (16, 32, 64, 128, 256):
print(f"{n:6d} {layer_error(n, False):.2e} {layer_error(n, True):.2e}")
cells uniform graded
16 3.64e-03 4.67e-03
32 5.19e-02 1.53e-03
64 7.35e-02 4.34e-04
128 4.05e-02 1.15e-04
256 1.43e-02 2.96e-05

Grading and patches combine: the potential of a charge cloud next to a wall at y=0y = 0 in a grounded box, with the axis normal to the wall graded and a patch over the cloud. The nodes, the control volumes and the Shortley–Weller rows of NodalPoisson use the physical spacings, and the solve converges at second order like on a uniform mesh.

def solve(n: int) -> tuple[NodalPoisson, np.ndarray]:
mesh = AMRHierarchy((n, n), axis_nodes=(None, tanh_nodes(n, 1.0, 0.1 / n)))
mesh.add_patch(level=1, box=((n // 2, 3 * n // 2), (0, n // 2)))
faces = {f: Dirichlet(0.0) for f in ("x_lower", "x_upper", "y_lower", "y_upper")}
solver = NodalPoisson(mesh, faces=faces)
x, y = solver.nodes.coordinates.T
exact = np.sin(np.pi * x) * np.sin(np.pi * y) * np.exp(-8.0 * y)
# -laplacian of the exact potential
source = (
np.sin(np.pi * x)
* np.exp(-8.0 * y)
* (
(2.0 * np.pi**2 - 64.0) * np.sin(np.pi * y)
+ 16.0 * np.pi * np.cos(np.pi * y)
)
)
difference = solver.solve(source, potential="phi") - exact
return solver, np.sqrt(np.sum(difference**2 * solver.volumes))
errors = [solve(n)[1] for n in (16, 32, 64)]
print(
"L2 errors:",
np.array(errors),
"orders:",
np.round(np.log2(np.array(errors[:-1]) / errors[1:]), 2),
)
solver, _ = solve(16)
fig, ax = plt.subplots(figsize=(5, 4.5))
plot_patches(solver.nodes.hierarchy, field="phi", ax=ax)
ax.set_title("graded toward y = 0, a patch over the layer")
fig.tight_layout()
L2 errors: [7.77508945e-04 1.88184539e-04 4.64096367e-05] orders: [2.05 2.02]
Notebook output
  • The bounds of a graded axis are its first and last node; a periodic graded axis keeps its period, and points beyond it map by whole periods.
  • Markers are located, deposited and gathered in logical coordinates (AMRHierarchy.to_logical, to_physical); CompositeNodes, CompositeEdges and AMRHierarchy.deposit and interpolate convert for you. A straight path is cut where it crosses a base plane of a graded axis, so the edge deposit keeps the charge to round-off.
  • The FFT backend needs uniform axes; the LU, PETSc and multigrid backends take graded ones.
  • graded_nodes(lower, upper, [(x, dx), ...], through=...) makes such nodes from the cell size wanted at a few positions, and puts nodes at the through positions (the faces of electrodes), so that surfaces fall on the mesh.
  • Grading belongs to the base level: keep neighbouring base cells within a few percent of each other for the second order, and let patches refine what moves.