Soft p-enrichment: where to raise the order, by gradient
FEM soft_enrichment_l_shape.py
Where should a finite-element solution raise its order? The greedy answer marks the nodes with the largest error estimate, round by round. Here every node gets a continuous weight instead, so the energy is a smooth function of where the order is raised, and a gradient method optimises the choice under a budget. The problem is the L-shape of the adaptivity tutorial.

Left: the weights \(w_i\) during the optimisation for a budget of 52 nodes. Right: the nodes the greedy loop chose (orange) and the thresholded optimum (rings).
The problem
\(-\Delta u=f\) on the L-shape, \(u=0\) on the boundary. Each node's cover coefficients get a diagonal penalty
so \(w_i=1\) is the full cover space and \(w_i\to0\) plain P1 at that node. The Ritz energy \(\Pi(w)=\tfrac12u^\top Au-b^\top u\) with \(u=u(w)\), whose excess over the exact value is half the squared energy error, is then minimised under the budget
At \(w=0\) its gradient is the diagonal hierarchical estimate of Bank & Smith (SIAM J. Numer. Anal. 30, 1993), \(\partial\Pi/\partial w_i=-(1-w_{\min})\sum_{k\in i}r_k^2/A_{kk}\), which the script checks.
The jNO code
The weights enter the assembled system on one sparsity pattern, so one compiled solve serves every \(w\), and
jax.grad of \(\Pi\) goes through the linear solve. The optimiser is projected gradient onto the budget.
Result
Energy error \(\Pi-\Pi_\text{ref}\) on the 203-node mesh, at the enriched-node counts of the greedy loop's rounds:
| enriched nodes \(k\) | greedy enrich |
budgeted optimum | uniform P1, same unknowns |
|---|---|---|---|
| 20 | 1.84e-3 | 1.62e-3 | 4.63e-3 |
| 38 | 1.07e-3 | 8.56e-4 | 4.03e-3 |
| 52 | 5.78e-4 | 4.97e-4 | 3.70e-3 |
| 63 | 3.80e-4 | 3.42e-4 | 3.46e-3 |
| 74 | 2.80e-4 | 2.47e-4 | 3.22e-3 |
The optimum beats greedy marking by 10–20 % at every budget, and from three random starts it lands within 0.3 % of the same value. A one-shot ranking by the gradient at \(w=0\) is worse than greedy: the gain comes from the coupling between neighbouring covers, which the gradient at \(w=0\) cannot see.
Full script
The whole script, as it runs in the tests
r"""Soft p-enrichment on the L-shape: the order distribution as a differentiable variable, against greedy marking."""
import jax
import jax.numpy as jnp
import numpy as np
import jno
from jno.utils.solver.fem_soft_cover import (
cover_dof_index,
hierarchical_indicator,
operator_diagonal,
ritz_energy,
soft_solve,
)
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)]
BUMP = (0.74, 0.22, 0.17, 60.0) # cx, cy, R, amplitude
H, H_REF = 0.075, 0.015 # the coarse mesh and the fully enriched (third-order) reference, as in the adaptivity tutorial
STEPS, CHUNK, SIMP_P = 300, 5, 3.0 # projected-gradient steps per budget, snapshot every CHUNK steps
LU = jno.solve.lu()
def source(x, y, xp):
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 build(size): # -lap u = f on the L-shape, u = 0 on the boundary, one scalar space="cover" field
d = jno.shape.polygon(L_SHAPE, size=size).domain()
u = d.unknown.scalar(space="cover")
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]))
return d, jno.fem([stiff - source(x, y, jno.np) * v, u(*boundary) - 0.0]), u.bind(x=x, y=y)
compiles = [0] # XLA compilations, to compare the greedy loop with the whole soft optimisation
jax.monitoring.register_event_duration_secs_listener(
lambda name, *_a, **_k: compiles.__setitem__(0, compiles[0] + ("backend_compile" in name))
)
d_ref, fem_ref, _ = build(H_REF)
A_ref, b_ref = fem_ref.operator
PI_REF = float(ritz_energy(A_ref, b_ref, LU(A_ref, b_ref)))
d0, fem0, _ = build(H)
A, b = fem0.operator
b = jnp.asarray(b).reshape(-1)
pts, tris = np.asarray(d0.mesh.points)[:, :2], np.asarray(d0.mesh.cells_dict["triangle"])
N = len(pts)
IDX = cover_dof_index(N, 2)
C = operator_diagonal(A, IDX)
pi = lambda w: ritz_energy(A, b, soft_solve(A, b, IDX, C, w)) # Pi(w) = 1/2 u.Au - b.u, 2 (Pi - Pi_exact) = |u - u_exact|^2
err = lambda w: float(pi(jnp.asarray(w, dtype=float))) - PI_REF # energy error of the softly enriched solution
pinned = {int(i) for i, _ in d0._fem_native_dirichlet_pairs}
free_cover = np.array(
[[int(k) not in pinned for k in row] for row in IDX]
) # a boundary node's covers are partly pinned already
active_dofs = lambda mask: (
sum(int(IDX[i, 0] - 1) not in pinned for i in range(N)) + int(free_cover[np.asarray(mask, bool)].sum())
)
def top_k(score, k):
m = np.zeros(N, dtype=bool)
m[np.argsort(-np.asarray(score))[:k]] = True
return m
# the greedy loop: jno.solve.enrich, whose rounds fix the budgets every comparison uses
d_g, fem_g, ui_g = build(H)
c0 = compiles[0]
fem_g.solve(adapt=jno.solve.enrich(criterion=jno.np.sqrt(ui_g.x**2 + ui_g.y**2), theta=0.5, max_iters=6), linear=LU)
compiles_greedy = compiles[0] - c0
masks = [np.asarray(r["enriched"], bool) for r in fem_g.adapt_history] + [np.asarray(d_g._fem_enriched_nodes, bool)]
masks = [m for i, m in enumerate(masks) if m.sum() > 0 and (i == 0 or m.sum() != masks[i - 1].sum())]
budgets = [int(m.sum()) for m in masks]
A_m, b_m = fem_g.operator # the loop leaves fem_g bound to its final mask: the hard-mask energy checks the soft one
E_hard, E_soft = float(ritz_energy(A, b, LU(A_m, b_m))) - PI_REF, err(masks[-1].astype(float))
# the AD indicator -dPi/dw at w = 0 against its closed form, sum r^2 / A_kk (Bank & Smith 1993)
g0 = np.asarray(jax.jit(jax.grad(pi))(jnp.zeros(N)))
h0 = np.asarray(hierarchical_indicator(A, b, IDX, C, soft_solve(A, b, IDX, C, jnp.zeros(N))))
live = np.abs(h0) > 1e-10 * np.abs(h0).max()
def project(v_, k): # Euclidean projection onto {0 <= w <= 1, sum w = k}: bisection on the shift
lo, hi = jnp.min(v_) - 1.0, jnp.max(v_)
def body(_, lh):
mid = 0.5 * (lh[0] + lh[1])
up = jnp.sum(jnp.clip(v_ - mid, 0.0, 1.0)) > k
return jnp.where(up, mid, lh[0]), jnp.where(up, lh[1], mid)
lo, hi = jax.lax.fori_loop(0, 60, body, (lo, hi))
return jnp.clip(v_ - 0.5 * (lo + hi), 0.0, 1.0)
def optimiser(p): # CHUNK projected-gradient steps from step i0, the gate w -> w^p
vg = jax.value_and_grad((lambda w: pi(w**p)) if p != 1.0 else pi)
@jax.jit
def chunk(w, k, i0):
def step(i, w):
g = vg(w)[1]
return project(w - (0.3 * (1.0 - (i0 + i) / STEPS) + 0.01) * g / (jnp.max(jnp.abs(g)) + 1e-300), k)
return jax.lax.fori_loop(0, CHUNK, step, w)
def run(w, k, record=None):
for i0 in range(0, STEPS, CHUNK):
w = chunk(w, float(k), i0)
if record is not None:
record.append(np.asarray(w))
return np.asarray(w)
return run
opt_lin, opt_simp = optimiser(1.0), optimiser(SIMP_P)
c0, rows, frames = compiles[0], [], []
k_show = budgets[len(budgets) // 2]
for m_g, k in zip(masks, budgets):
w0 = jnp.full(N, k / N)
w_lin, w_simp = opt_lin(w0, k, frames if k == k_show else None), opt_simp(w0, k)
rows.append(
dict(
k=k,
dofs=active_dofs(top_k(w_lin, k)),
greedy=err(m_g.astype(float)),
ad=err(top_k(-g0, k).astype(float)),
lin=err(top_k(w_lin, k).astype(float)),
simp=err(top_k(w_simp, k).astype(float)),
)
)
rng = np.random.default_rng(0)
starts = [project(jnp.asarray(rng.random(N)), float(k_show)) for _ in range(3)] # random starts at the middle budget
spread = {
n: [err(top_k(opt(w, k_show), k_show).astype(float)) for w in starts]
for n, opt in (("lin", opt_lin), ("SIMP", opt_simp))
}
compiles_soft = compiles[0] - c0
# uniform P1 on finer meshes at the same active DOFs: P1 is the cover space with every weight 0
p1 = []
for f in (1.0, 0.85, 0.75, 0.65, 0.55):
d_f, fem_f, _ = build(H * f)
A_f, b_f = fem_f.operator
n_f, idx_f = len(np.asarray(d_f.mesh.points)), cover_dof_index(len(np.asarray(d_f.mesh.points)), 2)
pin_f = {int(i) for i, _ in d_f._fem_native_dirichlet_pairs}
sol = soft_solve(A_f, jnp.asarray(b_f).reshape(-1), idx_f, operator_diagonal(A_f, idx_f), jnp.zeros(n_f))
p1.append(
(sum(3 * i not in pin_f for i in range(n_f)), float(ritz_energy(A_f, jnp.asarray(b_f).reshape(-1), sol)) - PI_REF)
)
p1_dofs, p1_err = (np.array(a) for a in zip(*sorted(p1)))
uniform = lambda t: float(np.exp(np.interp(np.log(t), np.log(p1_dofs), np.log(p1_err))))
print(
f"L-shape, H={H}: {N} nodes, {A.shape[0]} padded DOFs; Pi_ref={PI_REF:.8f}; errors P1 {err(np.zeros(N)):.4e}, full cover {err(np.ones(N)):.4e}"
)
print(
f"hard mask vs soft w in {{0,1}}: {E_hard:.6e} vs {E_soft:.6e}; AD gradient vs closed form: {np.max(np.abs(g0 - h0)[live] / np.abs(h0[live])):.1e}"
)
print(f"{'k':>4} {'DOFs':>5} {'greedy':>11} {'AD 1x':>11} {'opt lin':>11} {'opt SIMP':>11} {'uniform P1':>11}")
for r in rows:
print(
f"{r['k']:>4} {r['dofs']:>5} {r['greedy']:>11.4e} {r['ad']:>11.4e} {r['lin']:>11.4e} {r['simp']:>11.4e} {uniform(r['dofs']):>11.4e}"
)
print(
f"random starts at k={k_show}: opt lin {min(spread['lin']):.4e}..{max(spread['lin']):.4e}, "
f"opt SIMP {min(spread['SIMP']):.4e}..{max(spread['SIMP']):.4e}; "
f"XLA compilations: greedy loop {compiles_greedy}, soft optimisation {compiles_soft}"
)
assert abs(E_hard - E_soft) <= 1e-5 * abs(E_hard) # soft weights in {0, 1} reproduce the hard mask
assert np.max(np.abs(g0 - h0)[live] / np.abs(h0[live])) < 1e-3 # the AD indicator is its closed form
assert all(
r["lin"] <= r["greedy"] and r["lin"] < uniform(r["dofs"]) for r in rows
) # the optimum beats greedy marking and uniform P1
assert compiles_soft < compiles_greedy # and compiles fewer programs