Adaptivity: h, r and p on one problem
Where should a finite-element solution spend its unknowns? jNO adapts a discretisation three ways: h adds elements where the error is, r moves a fixed set of nodes, and p raises the local order of the approximation. All three run on one problem with two features of different character: the singularity at a re-entrant corner and a smooth, localised bump.

The meshes after each adaptation step, from the same coarse start: h refines (left), r moves the nodes (middle), p switches on higher-order covers at the marked nodes (right).

The problem
with \(f\) a compact \(C^3\) bump in the lower-right arm. Near the re-entrant corner the solution behaves like \(r^{2/3}\). The error is measured in energy, \(E_\text{ref}-E\) with \(E=\tfrac12\int|\nabla u_h|^2\), against a fully enriched reference with 11,805 unknowns.
The jNO code
The three methods are one argument, the adapt= slot of fem.solve; the weak form is untouched by the choice:
jno.solve.remesh()/refine(): h, Dörfler marking over cells;jno.solve.relocate(objective="energy"): r, descending the Ritz functional \(J(v)=\tfrac12a(v,v)-(f,v)\), which by Galerkin orthogonality lowers the energy error itself;jno.solve.enrich(): p, switching on interpolation covers (space="cover") at the marked nodes.
The energy is read off the assembled form, so P1, a relocated mesh and an enriched space are measured the same way:
Result
| method | error \(E_\text{ref}-E\) | active unknowns | |
|---|---|---|---|
| coarse start | 5.590e-03 | 147 | |
| h | 6.082e-04 | 614 | 9.2× lower |
| r (default arclength objective) | 7.996e-03 | 147 | worse than the start |
| p | 1.918e-04 | 357 (59 % enriched) | 29.1× lower |
| h then p | 1.202e-04 | 771 (62 %) | 46.5× lower |
The default relocation objective targets resolution, not this error; objective="energy" cuts the error to 0.70×
at fixed unknowns. p reaches 3.2× lower error than h with 58 % of the unknowns, and h then p beats both: refine
where the regularity is the limit, raise the order where smoothness pays. On a pure corner singularity, with
nothing smooth to enrich, h cuts the error by 72 % and p by 4 %.
| the solution is… | reach for |
|---|---|
| singular (corner, crack, shock) | h |
| smooth and resolved, the feature moves | r |
| smooth, localised, under-resolved | p |
Full script
The whole script, as it runs in the tests
r"""h, r and p adaptivity on one L-shape problem: same coarse mesh, same reference, same energy functional."""
import jax
import numpy as np
import jno
jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L_SHAPE = [(0, 0), (1, 0), (1, 0.5), (0.5, 0.5), (0.5, 1), (0, 1)] # re-entrant corner at (0.5, 0.5)
CORNER, BUMP = (
(0.5, 0.5),
(0.74, 0.22, 0.17, 60.0),
) # the bump: cx, cy, R, amplitude, compactly supported in the lower-right arm
H, MARGIN = 0.075, 0.04 # the common coarse mesh; the margin keeps relocated vertices off the boundary
LU = jno.solve.lu() # sparse-direct for every solve: the reference reaches ~12k DOFs
def source(x, y, xp): # a C^3 bump (1 - s)^4, s = |x - c|^2 / R^2
cx, cy, R, A = BUMP
s = ((x - cx) ** 2 + (y - cy) ** 2) / R**2
return A * xp.where(s < 1.0, 1.0 - s, 0.0) ** 4
def movable(x, y): # interior vertices: off the outer box and the two notch edges
in_arm = ~((x > 0.5) & (y > 0.5))
off_box = (x > MARGIN) & (x < 1 - MARGIN) & (y > MARGIN) & (y < 1 - MARGIN)
off_notch = ~(((np.abs(x - 0.5) < MARGIN) & (y > 0.5 - MARGIN)) | ((np.abs(y - 0.5) < MARGIN) & (x > 0.5 - MARGIN)))
return in_arm & off_box & off_notch
def build(size, space="Lagrange", relocate=False):
d = jno.shape.polygon(L_SHAPE, size=size).domain()
if relocate: # .trainable() on a coordinate makes the mesh vertices a design variable
xm, ym, _ = d.variable("mov", where=movable, split=True)
xm.trainable(name="ix"), ym.trainable(name="iy")
u = d.unknown.scalar(space=space) # space="cover": a p-enriched field
v = u.test()
x, y, _ = d.variable("interior", split=True)
boundary = d.variable("boundary", split=True)
stiff = jno.np.inner(jno.np.jacobian(u, [x, y]), jno.np.jacobian(v, [x, y])) # -lap u = f, u = 0 on the boundary
ui = u.bind(x=x, y=y)
return d, jno.fem([stiff - source(x, y, jno.np) * v, u(*boundary) - 0.0]), stiff, jno.np.sqrt(ui.x**2 + ui.y**2)
def energy(fem, stiff, sol): # E = 1/2 int |grad u_h|^2 = 1/2 u . (A u), read off the form: the same rule for every space
return 0.5 * float(np.dot(np.asarray(sol).reshape(-1), np.asarray(fem.eval(stiff, sol)).reshape(-1)))
def active_dofs(d, fem): # an unenriched cover node has its slots pinned: the padded size would hide the effect of p
return int(fem.dofs) - len({int(i) for i, _ in getattr(d, "_fem_native_dirichlet_pairs", None) or []})
def mesh_of(d):
return np.asarray(d.mesh.points)[:, :2], np.asarray(d.mesh.cells_dict["triangle"])
def min_angle(pts, cells): # smallest angle in degrees: the quality that relocation can quietly destroy
a, b, c = (np.linalg.norm(pts[cells[:, i]] - pts[cells[:, j]], axis=1) for i, j in ((1, 0), (2, 1), (0, 2)))
cos = np.stack(
[
(b * b + c * c - a * a) / (2 * b * c),
(a * a + c * c - b * b) / (2 * a * c),
(a * a + b * b - c * c) / (2 * a * b),
]
)
return float(np.degrees(np.arccos(np.clip(cos, -1, 1))).min())
# the reference must out-resolve every run: fully enriched (third order) at h = 0.015, whose drift from 0.020 is 4.8e-06
d_ref, fem_ref, stiff_ref, _ = build(0.015, space="cover")
E_REF = energy(fem_ref, stiff_ref, LU(fem_ref.A, fem_ref.b))
d0, fem0, stiff0, _ = build(H) # the coarse start
E0, n0 = energy(fem0, stiff0, LU(fem0.A, fem0.b)), active_dofs(d0, fem0)
pts0, tris0 = mesh_of(d0)
d_h, fem_h, stiff_h, _ = build(H) # h: add elements, solve -> ZZ estimate -> Dorfler mark -> local remesh
fem_h.solve(adapt=jno.solve.remesh(theta=0.6, max_iters=4, refine_factor=1.7), linear=LU)
E_h, n_h = energy(fem_h, stiff_h, LU(fem_h.A, fem_h.b)), active_dofs(d_h, fem_h)
pts_h, tris_h = mesh_of(d_h)
# r: relocate a fixed node set down a mesh functional, through the differentiable solve (the default
# objective equidistributes arclength, which targets resolution and not this error)
d_r, fem_r, stiff_r, _ = build(H, relocate=True)
pts_r0 = mesh_of(d_r)[0].copy()
sol_r = np.asarray(fem_r.solve(adapt=jno.solve.relocate(max_iters=30, lr=5e-4), linear=LU)).reshape(-1)
E_r, n_r = energy(fem_r, stiff_r, sol_r), active_dofs(d_r, fem_r)
pts_r, tris_r = mesh_of(d_r)
d_p, fem_p, stiff_p, grad_p = build(
H, space="cover"
) # p: raise the order on the same mesh, where the covers are switched on
fem_p.solve(
adapt=jno.solve.enrich(criterion=grad_p, theta=0.8, max_iters=5), linear=LU
) # returns the vertex view: re-solve on the final space
E_p, n_p = energy(fem_p, stiff_p, LU(fem_p.A, fem_p.b)), active_dofs(d_p, fem_p)
mask_p, pts_p = np.asarray(d_p._fem_enriched_nodes, dtype=bool), mesh_of(d_p)[0]
# hp: refine the mesh, then enrich on it (a fresh enrich starts from plain P1, so the active count goes down at that call)
d_hp, fem_hp, stiff_hp, grad_hp = build(H, space="cover")
fem_hp.solve(adapt=jno.solve.remesh(theta=0.6, max_iters=3, refine_factor=1.7), linear=LU)
fem_hp.solve(adapt=jno.solve.enrich(criterion=grad_hp, theta=0.8, max_iters=4), linear=LU)
E_hp, n_hp = energy(fem_hp, stiff_hp, LU(fem_hp.A, fem_hp.b)), active_dofs(d_hp, fem_hp)
mask_hp = np.asarray(d_hp._fem_enriched_nodes, dtype=bool)
err = lambda E: E_REF - E # the energy rises toward the truth, so the error E_ref - E is non-negative
print(f"E_ref = {E_REF:.6f} (cover, {active_dofs(d_ref, fem_ref)} dofs)")
print(f" coarse start : {err(E0):.3e} ({n0} dofs)")
print(f" h : {err(E_h):.3e} ({n_h} dofs) {err(E0) / err(E_h):5.1f}x lower")
print(f" r : {err(E_r):.3e} ({n_r} dofs, +0) {err(E0) / err(E_r):5.1f}x")
print(f" p : {err(E_p):.3e} ({n_p} dofs, {mask_p.mean():.0%} enriched) {err(E0) / err(E_p):5.1f}x lower")
print(f" h then p : {err(E_hp):.3e} ({n_hp} dofs, {mask_hp.mean():.0%} enriched) {err(E0) / err(E_hp):5.1f}x lower")
# where did each method spend its DOFs: at the corner, in the bump, elsewhere
near = lambda p, c, rad: np.hypot(p[:, 0] - c[0], p[:, 1] - c[1]) < rad
corner_p, bump_p = near(pts_p, CORNER, 0.22), near(pts_p, BUMP[:2], BUMP[2])
cent = pts_h[tris_h].mean(axis=1)
e1, e2 = pts_h[tris_h[:, 1]] - pts_h[tris_h[:, 0]], pts_h[tris_h[:, 2]] - pts_h[tris_h[:, 0]]
size_h = np.sqrt(0.5 * np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0]))
corner_h, bump_h = near(cent, CORNER, 0.22), near(cent, BUMP[:2], BUMP[2])
print(
f"p put its covers: corner {mask_p[corner_p].mean():4.0%} | bump {mask_p[bump_p].mean():4.0%} | elsewhere {mask_p[~(corner_p | bump_p)].mean():4.0%}"
)
print(
f"h put its elements: corner {size_h[corner_h].mean():.4f} | bump {size_h[bump_h].mean():.4f} | elsewhere {size_h[~(corner_h | bump_h)].mean():.4f} (mean cell size)"
)
print(f"smallest angle: start {min_angle(pts0, tris0):.1f} deg -> after relocation {min_angle(pts_r, tris_r):.1f} deg")
assert err(E0) > 0 and err(E_p) > 0 # the reference bounds every run
assert err(E_h) < 0.25 * err(E0) and err(E_p) < err(E_h) and err(E_hp) < err(E_p) and 0.0 < mask_p.mean() < 1.0
assert min_angle(pts_r, tris_r) > 0.6 * min_angle(pts0, tris0) # relocation does not wreck the mesh