Skip to content

Moving meshes

A moving mesh is a term

A moving mesh is not a solve argument. Put coord.d(t) - velocity in the jno.fem([...]) list — a residual like any other equation — and the mesh moves as it says:

jax.config.update("jax_enable_x64", True)          # required; see the scope list below

xb, yb, tb = domain.variable("boundary", split=True)
fem = jno.fem([ui.t * vi + kappa * (ui.x * vi.x + ui.y * vi.y),   # the physics
               u(xb, yb) - 0.0, u(*ci) - 1.0,
               yb.d(tb) - 0.5 * yb])                              # dy/dt = y/2 — the mesh
traj = fem.solve()                                                # one frame per moved mesh
How a moving-mesh term is recognised

It is recognised structurally, by containing d(spatial coordinate)/d(temporal variable), so there is no new spelling: Variable.d and the term list already exist. Nothing about it is boundary-specific — an interior region, a boundary and a where= predicate all resolve the same way — and tagging is per-axis, so a term on yb alone moves the y column and holds x exactly.

The velocity is ordinary traced math, so an interface law may read the solved field (a Stefan front -(k/L)·∇T·n), the coordinates, the outward normals, the time, or a jno.np.parameter that then becomes a design variable. The march is differentiable in all of them, and in where the mesh started.

Each step: evaluate every geometry term's velocity, scatter it into the vertices and axes those terms name, extend harmonically over everything they do not, move, re-assemble on the moved vertices, and carry the state across.

The mesh velocity inside a weak form (ALE)

On a moving mesh a nodal value follows its vertex, so its rate is the ALE derivative

\[ \left.\frac{\partial u}{\partial t}\right|_{X} = \left.\frac{\partial u}{\partial t}\right|_{x} + w\cdot\nabla u , \]

with \(w\) the mesh velocity. Transport written on the moving mesh therefore carries \(w\), and you write it as what it is — the rate of a coordinate:

w0, w1 = xi.d(ti), yi.d(ti)                                        # the mesh velocity w
fem = jno.fem([ui.t * vi + ((c0 - w0) * ui.x + (c1 - w1) * ui.y) * vi   # u_t + (c - w)·∇u
               + nu * (ui.x * vi.x + ui.y * vi.y),
               xi.d(ti) - c0, yi.d(ti) - c1,                       # the mesh: it follows the flow
               u(*ci) - u0])

When a weak form reads coord.d(t), the nodal values ride with their vertices and nothing is transferred (transferring as well would count the mesh advection twice). Each step, w is the discrete motion of every vertex, \((X^{n+1} - X^n)/\Delta t\), harmonically extended vertices included, in volume and surface terms alike. This is the non-conservative ALE form, backward Euler, with mass and operator on the end-of-step configuration. Measured (tests/test_fem_ale_mesh_velocity.py):

  • a mesh translating rigidly with the material reproduces the fixed-mesh diffusion march to 1.1e-15;
  • a surface term (w·n) u v equals (c·n) u v on that mesh to 3.6e-16;
  • a Gaussian advected at c past a mesh moving at c/2 meets its closed form to 2.0 % (5.2 % on a fixed mesh with the same h and dt, since less relative motion means less numerical diffusion).

w lives on the mesh vertices and borrows a P1 Lagrange field's basis, so the problem needs one (a Taylor–Hood pressure qualifies). Refused by name: coord.d(t) with no geometry term (it would be identically zero), the rate of a normal or of cell_size, and the mesh acceleration xi.d(ti).d(ti).

The stabilised-flow tau works for a capillary drop as written

The SUPG/PSPG tau of the stabilised-flow tutorial needs no rescaling for a surface-tension driven drop. Measured on an ellipse released from rest (tests/test_fem_drop_oscillation.py), the recipe as written rings at ω within 0.4 % of Lamb's ω² = n(n²−1)σ/(ρR³), decays at 0.89× the viscous rate 2n(n−1)ν/R², and leaves the n = 4 mode at its initial amplitude. Scaling tau by 1e-4 changes none of these.

Earlier versions of this page warned the opposite: that this tau over-damps the drop tenfold (ω = 0.23) and feeds a spurious n = 4 mode (×9.7). That was an assembly defect, not physics. The stabilisation products contain u_t inside the strong residual, and the transient assembler routed each such product whole into the mass matrix. They are now split by temporal order. A spelling the assembler cannot split, such as tau * inner(a, u.t + (u.grad)u), is refused with instructions to write the u.t part as its own term.

Two further practicalities. Measure the shape as a Fourier mode of r(θ), not as a bounding-box aspect ratio, and fit a damped sinusoid — extremum counting returned +7.4/s and −1.6/s for the same run over different spans. And the capillary time step is tighter than √(ρh³/2πσ) suggests: at h = 0.03 that estimate gives 8e-4 while 5e-4 already tangles, so shrink dt as you refine.

Bodies that merge — remesh(alpha=...)

Moving a mesh cannot change its topology: two droplets meshed as separate bodies in a void can approach forever and stay two meshes. alpha= re-decides which nodes form elements, instead of meshing the geometry afresh — a Delaunay triangulation of the nodes where the motion left them, keeping only the triangles whose circumradius is below alpha × the local mean edge length (the alpha shape, the remeshing step of the Particle Finite Element Method):

traj = fem.solve(adapt=jno.solve.remesh(alpha=1.2, every=1))   # re-triangulate the nodes every step

Every node stays put, so a P1 state carries across by identity — nothing is interpolated and nothing is lost. What changes is which nodes are neighbours, so a gap that closes gets bridged and the two bodies become one mesh.

Two disks (R = 0.5, h = 0.075, 357 nodes) driven together

gap 0.35 → 0.150 0.136
bodies 2 1

They merge at about 1.8 h, a little later than the flat-wall threshold 2·alpha·h = 0.18: two facing arcs put fewer nodes near the closest point than two straight walls do.

The node count is unchanged (357), the cell count goes 630 → 638, and the field — two flat plateaus at ∓1 — starts to diffuse across the new neck (minimum |u| there 0.479, against 0.972 when the bodies never merge). Only 2 of 12 steps actually rebuilt anything: the reconnection is skipped when it reproduces the elements already there. The march cost 5.0 s against 3.6 s without reconnection.

Merging is therefore a mesh-length contact model — bodies join when their gap is comparable to the element size — and not film drainage.

Scope: 2-D, P1 fields (a new edge bridging two bodies has its midpoint in the void, where a P2 value cannot be read), a geometry term must be present (nothing else moves the nodes), and alpha= does not combine with criterion= — they are different operations. A node left in no triangle (a free particle) is refused rather than dropped, because dropping it would renumber the rest and silently permute the state.

Scope — the rest raises rather than guessing:

  • Operator-split ALE, explicit in the velocity, hence first order in the step — measured, against a manufactured solution on a translating domain: observed rates 1.14 / 1.12 / 1.12 / 1.10 with the mesh moving, 0.99 / 1.01 / 1.04 / 1.10 with it still. The motion multiplies the error constant by ~3× (that is the state transfer) and leaves the order intact. Refining h converges too — 1.51 → 1.76 toward the expected 2 for P1 — and P2 is ~18× more accurate than P1 on the same moving mesh, so higher order still pays here.

If you repeat that measurement, compare against a fine-dt reference on the same mesh, not against the exact solution: the temporal and spatial errors have opposite signs, so the direct comparison shows rates of +1.4 then −0.4 as they cancel and separate again. That reads as a scheme that stops converging, and is only a contaminated measurement.

??? note "Why the mesh motion is explicit, not an implicit coupled equation" The term list reads like a coupled equation and this is not one: an implicit mesh would need the coordinates as unknowns in the monolithic system and the ALE convective term. * The state transfer is a conservative L2 projection onto the moved mesh, and it is still diffusive. On a rigid translation carrying a marginally-resolved bump the peak falls ~9 % (the pointwise re-interpolation this replaced fell ~33 %, and got worse as dt shrank). Conservation is algebraic — Σφ = 1 — so the residual is quadrature error on an integrand with kinks: ~2e-4 relative against the pointwise route's 3e-3 to 9e-3. Removing the diffusion entirely means not transferring at all (Lagrangian DOFs plus an ALE -w·∇u term), which is a different semidiscretisation — and what happens when a weak form reads the mesh velocity (above). * Requires jax_enable_x64. The transfer locates quadrature points in the previous mesh, and in float32 that carries ~4e-4 — enough for a mesh that never moves to drift 1.5e-3 over a march (2.6e-10 with x64). * Backward Euler only: θ comes from the block, and time=jno.solve.theta(...) is a solver slot, which a geometry term does not compose with. * Connectivity-preserving, unless told to remesh: a move that would invert an element raises. With fem.solve(adapt=jno.solve.remesh(criterion=lambda d: jno.le(d.cell_aspect(), 3.0), every=1)) the march checks the condition on the moved mesh every every steps and, where it breaks, rebuilds the mesh (mmg, at the starting DOF budget), re-assembles and carries the state across. Measured on a top edge bulging as y' = 2y sin(πx): worst cell aspect 6.27 → 3.19 with one remesh, the surface where the plain march puts it, a constant field exact to 4e-16. The laws may read only boundary and interior (any other region is found by a position that does not follow a moved surface), a remesh is not differentiable (refused under jax.grad), and each remesh drifts a curved boundary's enclosed area by ~6e-3 (mmg, measured on a disk). * A Dirichlet BC on the moving surface must be tied to a whole-boundary or held tag, not to a spatial sub-predicate — a predicate does not follow the motion. * Any nodal-Lagrange field(s), real, non-periodic, 2D or 3D — scalar or vector, P1 or higher, and mixed orders across a coupled system (a Taylor–Hood pair moves as one). Nonlinear problems work too. Complex, periodic, a non-nodal family (RT / Nédélec / Hermite / Argyris / Morley), a custom solve_fn and save_ts= each raise.

??? note "Why higher order costs almost nothing here" Higher order costs almost nothing structurally, for two reasons worth knowing: the mesh geometry is P1 whatever the field order — a moved simplex stays straight-sided — so the quadrature map and the point location are shared by every field; and a topology-preserving move leaves the P{k} connectivity unchanged, so the seed assembly's tables stay valid for the whole march and the moved DOF coordinates are never needed at all. The quadrature degree follows the order (2k), because the mass ∫φᵢφⱼ must be integrated exactly or the solve is not a projection.

Reconnecting without recompiling — runtime connectivity

A Delaunay flip changes which nodes form a cell, but not how many cells there are, so no array changes shape. A march with a geometry term therefore assembles against a runtime connectivity: the cell array rides the same argument channel the moved vertices already use, and a reconnection that keeps every shape hands the compiled program a new triangulation instead of rebuilding it.

It is inferred: coord.d(t) - velocity already states that the mesh moves, and that is the only case in which the connectivity can change under a fixed node set. Domain.dynamic_topology() is the explicit spelling, and dynamic_topology(False) opts out.

Runtime connectivity, on a geometry-term march

baked connectivity runtime connectivity
one reconnection one XLA compilation, ~31 s 0.13 s
two-drop coalescence, whole march 1587 s 69.8 s (22.7×), trajectory identical to 1.1e-16
relocate, no reconnection at all (41 frames) 1.6 s 1.0 s
remesh(alpha=1.2, every=1) (41 frames) 3.5 s 0.9 s

It is faster even when nothing reconnects, which is why it is the default: the gather goes through the index array the moved vertices travel on anyway.

Only same-shape changes become free. A reconnection that changes the cell count (two bodies merging, node management inserting a node) still rebuilds. Affine simplices only: on a curved or tensor-product mesh an explicit dynamic_topology() raises, and the inferred one falls back to the baked connectivity.

When the node set does change, the state is carried by a conservative L2 projection onto the new mesh rather than by pointwise interpolation. On a laser-heated drop, whose hot layer is a few cells thick, one remesh used to cost 540 K of peak temperature and 6 % of the thermal energy; it now costs 6 K and +0.5 %.

Adapting a moving mesh — relocate, escalate=, anisotropic remesh

All three adaptivity kinds that move or add nodes compose with a geometry-term march.

r-adaptivity is nearly free here. Vertex positions ride the scan carry, so a relocation hands a new X to the same compiled program: no new nodes, no new connectivity, no rebuild.

traj = fem.solve(adapt=jno.solve.relocate(method="monge_ampere", every=20))

600 W melt ball (R = 150 µm, h = 40 µm), 800 steps

adaptivity nodes wall p90 interpolation error dent
remesh(alpha=1.2, every=1) 78 129 s 0.1720 −22.78 µm
relocate(every=20) 74 34 s 0.1722 −22.23 µm
relocate(every=20, escalate=0.5) 112 61 s 0.1124 −26.18 µm

How often it relocates is free once the Monge–Ampère round is compiled: every=100/50/20/10 all cost 34–35 s.

  • Area is conserved; perimeter is not. A boundary vertex slides only along the chord joining its two boundary neighbours, which leaves the enclosed area unchanged to first order, and an iterated normal correction removes the rest (4.7e-3 → 4.2e-11 relative). A free surface stretches, so its perimeter is left free.
  • A sliver is a connectivity defect. Moving nodes cannot repair it, so relocate().remesh(alpha=...) reconnects first, at a fixed node set, and then relocates.
  • A relocation that would invert a cell is rejected, not applied. Relocation optimises the discretisation, never the physics, so skipping a round is harmless and visible in the trajectory's records (relocate_skipped, relocate_would_invert). JNO_RELOCATE_STRICT=1 raises instead. Before this guard, a 600 W run reported 10,201 plausible frames while 98 % of its cells had inverted, and its temperatures stayed in range throughout. Only the area and the orientation revealed it.
  • escalate=tol adds nodes only when moving them was not enough. After each relocation the march measures the interpolation error, and above tol (relative to the field's range) it adds vertices along the anisotropic mmg path. The error indicator pairs each curvature with the element's extent in its own direction (Alauzet & Loseille, J. Comput. Phys. 229 (2010) §2.2). An isotropic shape measure is deliberately not the trigger: on an anisotropically adapted mesh it flags the stretched cells that are doing their job. The loop is self-limiting. Above, it fired once, at the error peak.

Anisotropic h-adaptivity is remesh(anisotropic=True) with a criterion that says when to remesh, and a Hessian metric that says how. On a squeezed disk carrying a sharp front, it produced elements with aspect ratio 9.04 lying along the level sets (|long axis · ∇u| = 0.046, against 0.330 for an isotropic remesh).

Not wired, and the reasons are substantive:

  • p-adaptivity (enrich()) needs a space="cover" field, whose degrees of freedom are not nodal values. Plain P2 does march on a moving mesh.
  • r-adaptivity on two separate bodies still fails. On a two-ball problem, 399 of 400 relocation rounds would invert cells and are rejected. Use alpha, which is also the only adaptivity that can merge bodies.

A graded mesh reconnects on its own length scale

The alpha filter keeps a triangle when its circumradius is below alpha × a length scale, and that scale is now each node's own mean edge length, not one number for the whole mesh.

On a graded mesh a single value fails at both ends: coarse cells all exceed it, and their nodes become free particles; in the fine region, the coarse value fuses surfaces that are really apart. Two rod tips graded 50 → 500 µm: the scalar mean (98 µm) stranded 50 of 363 nodes; the per-node scale triangulates all of them and keeps the rods apart. An inserted midpoint inherits the mean of the two nodes it splits.

A march that survives being killed — checkpoint=

A march holds every frame and returns them only when solve() returns, so a run killed by an OOM, a signal or a reboot used to return nothing, however far it had got. checkpoint= writes frames to disk as they are produced:

traj = fem.solve(
    nonlinear=jno.solve.newton(direct=True),
    adapt=jno.solve.remesh(alpha=1.2, every=1),
    checkpoint=jno.solve.checkpoint("runs/ball", every=500),
)
  • every is the number of steps between writes. A write also happens at every rebuild, because that is where a restart has to begin anyway.
  • keep="last" (the default) drops each written chunk from memory, and the returned trajectory loads its frames from disk on demand, so a march no longer has to fit in RAM. keep="all" keeps everything resident and checkpoints only for crash safety.
  • resume=True continues an unfinished run in path. A run marked complete is never resumed; delete the directory to redo it.

The restart state is the one a rebuild already re-enters the march with, plus the domain the next segment starts on. Trajectories are bit-identical with and without checkpointing, including across rebuilds (600 and 1,400 steps on a melt ball; max |Δstate| = max |Δpoints| = 0).

The same checkpoint= writes down the fixed-mesh marches too: a transient (u.t) march with a built-in scheme, and a load-path march (.i(k) with domain(tau=...)).

u = fem.solve(checkpoint=jno.solve.checkpoint("runs/heat", every=200)).fn()   # u.t march
u = fem.solve(checkpoint=jno.solve.checkpoint("runs/plate", every=50))         # tau load path

Those marches are compiled loops, and checkpointing runs them as a host loop of chunks of every steps, writing the frames to one frames.npy memory map and the loop carry to latest.npz after each chunk.

The transient trajectory is bit-identical to the unchecked march on CPU and within 1 ulp on GPU (the chunks compile to other shapes than the single scan); the load path agrees to round-off (2.8e-17). With keep="last" the result is a numpy.memmap of the frames on disk. A store records what identifies its march (grid, sizes, scheme, initial state, parameters, operators), so resuming a different problem into it raises instead of splicing the two.

A checkpointed march is not differentiable

A chain of scans is not the single scan whose adjoint jNO builds, so checkpoint= raises under jit / grad / jno.core. Checkpoint the forward run at named values (fem.solve(k=2.0, checkpoint=...)) and differentiate without it.

Every solve that cannot write itself down refuses checkpoint= rather than run and leave the directory empty: a steady solve, an adaptive time step, a sharded or solve_fn= integrator, adaptive / arc-length / contact load stepping, and a moving mesh without adapt= (one compiled scan, with no boundary to write at).

Two memory leaks in the rebuild path were fixed with it:

  • a closure kept each segment's sampled point pools alive;
  • re-sampling a region wrote to a fresh alias instead of the region's own name, which also left the constraints reading the old points.

Per-rebuild memory growth fell from 0.361 GB to 0.027 GB, and device memory now stays flat. JNO_MARCH_MEMDEBUG=1 prints the per-rebuild breakdown (RSS, live JAX buffers by shape, Python heap, domain.context) that found both leaks.