Skip to content

Geometry

Mesh sizing — one number, or a function of position

size= takes a float for a uniform mesh, or a callable for a graded one. A callable becomes a gmsh mesh-size callback and composes with every other size control by min, so it is the general "denser here" knob:

# THREE arguments, in 2-D as well as 3-D: gmsh calls a size function as f(x, y, z).
h_of = lambda x, y, z: H_FINE + (H_COARSE - H_FINE) * min(1.0, max(0.0, (LY - y) / BAND))
d = jno.shape.rect(0.0, 0.0, LX, LY, size=h_of).domain()

This is what makes a thin feature affordable. Measured on a 1.2 × 0.4 mm rectangle graded from 4 µm at the top surface to 30 µm below — the melt pool of the laser melt-pool tutorial, ~50 µm deep in a 400 µm domain:

mesh nodes through the 50 µm feature
uniform 16 µm 2,296 3 cells
uniform 4 µm 35,226 12 cells
graded 4 → 30 µm 2,035 12 cells

Same near-surface resolution as the uniform 4 µm mesh for 17× fewer nodes — and fewer nodes than the 16 µm mesh that resolved nothing.

f(x, y) is the natural thing to write in 2-D, and it is wrong

The callback passes three coordinates whatever the dimension. A two-argument function raises inside gmsh's C callback, where it surfaced as Wrong mesh element size lc = 0 (lcmin = 0, lcmax = 1e+22) — naming neither the callable, nor its signature, nor the shape it came from.

And whether it surfaced at all depended on gmsh's global state: the same wrong function raised in a fresh process and meshed silently in one that had already built other meshes. jNO now probes the callable once before registering it and refuses by name.

Meshing is lazy

.domain() does not build a mesh; the first thing that asks for one does. So a size callable is not called — and a wrong one not diagnosed — until then.

Curved (isoparametric) geometry — shape.curved()

By default jNO meshes straight-sided and synthesises higher-order nodes at the straight-edge midpoints, so the domain stays a polygon however high the element order goes. That approximation carries an O(h²) domain error at every basis order — it is what caps P2/P3 at second order on a round boundary, no matter how good the basis is. curved() asks the CAD kernel to place those nodes on the true surface instead:

d = jno.shape.disk(0, 0, 1, size=0.1).curved().domain()
u, v = d.fem_symbols(order=2)          # the basis order must MATCH the geometry order

Unit disk, -Δu = 1, exact u = (1−r²)/4 — RMS nodal error

Measured on -Δu = 1 on the unit disk (exact u = (1−r²)/4), RMS nodal error:

mesh size straight-sided curved
0.4 6.73e-03 7.63e-05
0.2 1.66e-03 7.67e-06
0.1 4.23e-04 7.36e-07
rate per halving ≈4× (O(h²)) ≈10× (O(h³))

Straight-sided is capped at second order by the geometry; curved recovers P2's own third order, and is 570× more accurate at the finest resolution.

Scope — what this does not cover. Order 2 and simplices only. An order mismatch is refused: isoparametric means geometry order == basis order, and a curved mesh under a P1 basis puts the midside DOF coordinates (on the arc) and the geometric map (from the chord) in disagreement.

Non-nodal families keep affine geometry — Nédélec, RT, Argyris and Morley need Piola/curvature push-forwards that are a separate change, so curved EM does not benefit yet — and a 4th-order form is refused on a curved cell, because the physical-Hessian transform is derived for an affine map and would gain a curvature term it does not carry. Facet normals are still straight-facet, so the O(h) normal error that affects radiation view factors, flux BCs and RCWA's field decomposition is unchanged by this.

Note also that a curved map makes the integrand rational, so no quadrature rule is exact any more. The default degree is raised by 2 on curved cells and jno.fem(quad_degree=...) still overrides (an explicit degree is used as written, also below the default 2 × order, and a degree below it is reported once with what it integrates inexactly); measured on the study above, refining the rule moves the answer by less than 0.01 %.


Parametric shapes — a parameter in the shape's coordinates

A box face, a rect corner, an extrusion height or a translation may be an expression in jno.np.parameters, written where the number would be:

y1 = jno.np.parameter((1,), name="y1")
y1.initialize(jax.nn.initializers.constant(8e-3))         # the reference the mesh is built at
heater = jno.shape.box(0, 4e-3, 0, 10e-3, y1, 1e-3, size=7e-4).name("heater").attach(k=1.0, q=1e6)
d = (base + heater).domain()
...
T = jno.fem([...]).solve()                               # differentiable in y1

The mesh is built once, at the parameters' initial values. A design then stretches it: along each axis, every face plane of every box in the plan is a breakpoint, a plane written with a parameter goes where the parameter puts it, a plane written with a number stays, and every vertex between two planes keeps its reference fraction of the gap.

So box faces land exactly where asked, cells stay valid as long as no two planes cross, and everything not between a moving plane and its fixed neighbours keeps its vertices. The stretch rides the .trainable() route below, so ∂(solve)/∂(parameter) is the exact derivative of the stretched discretisation (pinned against central differences and against meshes rebuilt at the moved design in tests/test_fem_parametric_shape.py). The same parameters move a jno.peec network on the same domain (its grid lines follow the same rule).

What it does not do, up front:

  • A large move distorts cells. It is a stretch, not a remesh. d.rebuild(when=...) rebuilds the shape at the current design whenever a condition over the design holds during jno.core.solve, and every jno.fem / jno.peec built on the domain follows; training continues from the same parameters (the optimizer state too, unless keep_opt_state=False):
d.rebuild(when=d.cell_aspect().max > 6)      # the FEM mesh
d.rebuild(when=em.cell_aspect().max > 4)     # a PEEC network's face grid

The objective can jump at a rebuild, by as much as the two discretisations disagree. A condition that still holds on the freshly rebuilt cells is refused (it would rebuild every epoch). - Two faces on one plane move together. They are one plane of a conforming mesh: write them with the same expression, or start them apart. A fixed face and a moving one on one plane are refused by name. - Curved primitives cannot carry a parameter (disk, cylinder, sphere, polygon, rotate, revolve, fillet): refused at the constructor. A fixed curved body between moving planes is stretched with them. - A parametric line is not followed by the mesh. Its vertices move a PEEC filament, not a meshed tube, so jno.fem refuses a domain whose meshed line has parametric vertices. - What follows the moving mesh, and what refuses. The assembly, coefficients written in x, surface terms, normals, point loads, functionals and .evolves state readouts follow it; so do an essential value u(wall) - g(x) and an initial condition u(initial) - u0(x) on a P1 field (re-evaluated at the moved nodes). Every other place a position-dependent value is read at nodes (an obstacle bound u.bounds(psi(x)), a time- AND position-dependent essential value, a higher-order field's value, the 1-D assembler, u.tt forms, the VPINN context) refuses by name rather than read the reference positions. fem.points stays the reference coordinates. - Only jno.fem and jno.peec follow yet. jno.fdm, jno.rcwa and a jno.core loss that samples the domain's points (collocation) refuse a parametric domain by name.

Another solver's scalar readout -- a PEEC loss, an RCWA power, an expr.integrate(fem) -- may be a coefficient here (d.attach(region, q=em.solve().dissipation()[region])): it is one value per solve, resolved once and handed to the kernel, so a design parameter reaches this solve through it too (tests/test_peec_fem_parametric_chain.py, tests/test_fem_global_scalar_coefficient.py).

Differentiable mesh geometry — trainable coordinates (.trainable())

Any placeholder promotes to a jno.np.parameter seeded at its current values with .trainable() — an existing coefficient / data tag becomes an inverse unknown in one call:

k = domain.variable("kappa", sample=k0).trainable()   # trainable coefficient, seeded at k0

Called on a spatial coordinate (domain.variable(region)), .trainable() makes that region's mesh vertices a design variable — the map from node positions to the solution is differentiable, so a solve can be optimized with respect to the mesh itself (mesh relocation / r-adaptivity / shape optimization), all in one JAX graph:

xi, yi, _ = domain.variable("core", split=True)   # a where= / predicate sub-region
Xx = xi.trainable()                                # ONLY the x-positions of the core vertices move
#   differentiating a solve now yields the shape derivative ∂(solve)/∂X

.trainable() is per component — call it on every axis you want to move

The spelling is literal, per component (x.trainable() moves only x; call it per axis for full motion — which also gives constrained relocation for free, e.g. promote only the tangential component on a slip plane).

Under the hood the coordinate parameter scatters into the assembly's P1 geometry before the element Jacobian is formed, so J, JxW, the physical gradients, the quadrature-point coordinates and the boundary-facet normals all become differentiable in the node positions. Scope: nodal-Lagrange volume + Neumann/Robin terms, 2D triangle / 3D tet, steady. The mesh connectivity is fixed — this is relocation, not remeshing (h-remeshing stays the non-differentiable outer AFEM loop); it is differentiable on valid meshes, with element inversion (tangling) the boundary of that regime.

Moving a slip surface (n·u = 0) with runtime coordinates

The exact slip elimination carries u = P ũ with P built from the surface's per-node normals N_i = ∫ φ_i n ds. When the slip surface's own vertices are trainable, those normals move, so P is rebuilt for each solve from the coordinates it is given: same sparsity (the build-time pivots and facets), new values, pure JAX, differentiable in the coordinates.

Checked against a fresh build of the moved mesh (1e-16 on a tilted 2-D surface, 2e-11 m/s on a 3-D rolling model) and against the flux Σ u_i·N_i through the moved surface, which stays at round-off. Scope: the steady nonlinear solve (fem.solve(param=...), continuation=); a linear or transient form with a moving slip surface raises at build. Before this, the build-time normals were used silently (3e-4 relative error on the rolling model) — the reason one build could not serve a sequence of remeshed geometries.

Entries of P that the allowed motion cannot make nonzero (the z-part of a normal on a surface y = f(x) when only z is trainable) are left out of its pattern — detected at build by evaluating P at random perturbations of the trainable axes, and re-checked after every eager solve, which raises if one is nonzero after all.

Keeping them quadrupled the reduced tangent on the rolling model (the sparse reduction expands each triplet over the square of P's entries per row) and made each factorization 5.5x slower; pruned, a moved-mesh solve costs what a fresh build's does (23.6 s vs 22.5 s for its 137-step continuation) and a re-solve after the mesh moves takes 1.1 s instead of a 7.6 s rebuild.

r-adaptivity in one call. Tagging coordinates .trainable() and driving the relocation yourself is the low-level path; the packaged form reuses the same adapt= slot as h-refinement:

xm, ym, _ = domain.variable("core", where=interior, split=True)
xm.trainable(); ym.trainable()                              # BEFORE jno.fem(...)
u = fem.solve(adapt=jno.solve.relocate(max_iters=60))
How the descent works

jno.solve.relocate() descends the equidistribution defect of an arclength monitor through the differentiable solve, with a backtracking det J line search — so the fixed node set concentrates at solution features and the mesh never tangles (the validity constraint lives in the step control; a stock optimiser or an energy barrier alone cannot guarantee it on a stiff problem — see run_adaptive_relocate).

It mutates the domain to the relocated mesh, returns the solution there, and raises if no coordinate was tagged. Works across linear, nonlinear (Newton), transient (relocates for the whole trajectory via a time-averaged objective), periodic, and complex problems, scalar or vector — the objective sums over every solution block, so a complex field's real and imaginary parts both contribute. Only complex-transient is not wired yet.

The nonlinear=/linear=/precond= slots configure the solve on the final mesh, the one returned (linear=jno.solve.lu() on a saddle problem, say); the descent itself keeps its own differentiable solves. x0= and time= are refused: a warm start and a time scheme do not survive the change of mesh.

A mesh objective that names the physics — objective=<expression>

The three built-in objectives ("equidistribution", "energy", "huang") are mesh-quality measures: they read the solution only through a monitor, so they can ask for resolution but cannot state a goal about the physics. objective= also accepts a weak-form expression, assembled exactly as criterion= is and summed to a scalar, over a volume or a boundary region:

xs, ys, nx, ny = domain.variable("side", normals=True, split=True)
ys.trainable()                                   # the wall may move along y only
us, vs = u.bind(x=xs, y=ys), v.bind(x=xs, y=ys)
fem.solve(adapt=jno.solve.relocate(objective=(us[0]*nx + us[1]*ny)**2 * vs[0]))

That is a free surface: the wall moves until the flow through it vanishes. The facet normals are rebuilt from the moving vertices, so n is the current mesh's normal. The gradient runs through the solve — matched to central differences at 7.5e-09 — and the through-flow falls 11.4x over 60 rounds (12.5x at 120, so this is a descent, not a root-find).

Why the obvious benchmark measures nothing

The benchmark deserves a word, because the obvious version of it measures nothing. In a channel with a symmetry bottom, uniform flow u = (1,0), p = 0 satisfies every equation and boundary condition for any shape of the traction-free top: measured, the solution stayed uniform to 2.3e-14 and moved by 9.8e-14 when the wall was displaced by 0.1.

The objective is then purely geometric — it exercises the normals and the facet measure but never the solve. A no-slip bottom couples them (max|du| = 7.2e-02 for the same displacement), and only then is d(objective)/d(vertex) a statement about the physics rather than about the mesh.

Three things to know:

  • The objective is a scalar, so it needs a scalar test function; on a velocity/pressure saddle the pressure test is chosen automatically.
  • When the expression reaches its region only through a bound view — u.bind(x=xs, y=ys) absorbs its coordinates — the test function cannot be auto-bound. Carry it yourself, as above (* vs[0]). That case raises with this instruction rather than a trace-level binding error.
  • A surface objective needs the form to carry a surface term, because the facet quadrature tables are tabulated at build time only then. A traction-free wall (0.0 * vs[0]) in the term list is enough.

A mesh condition, as an inequality. criterion= also takes a jno.le / jno.ge constraint, and then it is its own trigger — there is no cadence or threshold argument, because the condition already says both where and whether:

fem.solve(adapt=jno.solve.remesh(criterion=lambda d: jno.le(d.cell_aspect(), 2.0), max_iters=6))

Every cell whose margin is positive is marked — all of them, not a Dörfler fraction — and the march stops when none is. Measured on a deliberately stretched mesh: worst aspect 2.87 → 1.57 in one round, 0 marked on the next. theta is refused with a constraint (there is no bulk fraction to choose), and a bare comparison (q > 2.0) is refused too: it records which cells are bad but not by how much, so marking would take a fraction of them and quietly leave the rest.

On a march the same condition is a trigger. With remesh(criterion=jno.le(...), every=k) on a transient problem it is checked on the current mesh every k steps, and the mesh is rebuilt only when some cell breaks it; fem.adapt_history records remeshed: False for the rounds it held, so a condition that never breaks never remeshes.

A ranking criterion (1 - phi**2, |grad u|) is evaluated on the live state at each remesh -- and at that remesh's time, so it may read t (a moving source) -- and the DOF budget (max_dofs, else the starting count) is held on both the isotropic and the anisotropic path.

max_dofs counts DOFs — every unknown of the assembled system (fem.dofs), so a vector field counts each component, a Taylor–Hood P2/P1 pair about nine per vertex in 2-D, and a complex field its real and imaginary halves — not vertices.

The mesher is steered by a vertex count and only approximates it, so each remesh is counted before it is applied and redone with a corrected target if it misses: the DOF count stays within 20 % of max_dofs, and a remesh that cannot be brought under 1.2 × max_dofs (an hmax too small to coarsen that far, say) raises.

On a steady loop the budget caps each round's growth and stops the loop once reached. (It used to be handed to the mesher as a vertex count: a Taylor–Hood march asked for max_dofs=4000 produced 23,793 DOFs.)

Two things to know. Set a threshold the mesher can actually reach — an unstructured 2-D mesh bottoms out around 1.2–1.5, and a constraint below that never settles, so the march refines until it runs out of rounds. And pass a callable for a geometry criterion: a geometry node captures the cell table when it is constructed, so a single node keeps answering for the mesh it was born on and is refused by name once the topology changes.

When moving nodes is not enough: relocate(...).remesh(...). Relocation moves a fixed node set, so once the mesh has to stretch further than its elements allow it can do nothing — quality_floor is a line search that rejects the step, and rejecting a step never adds a node. Chain an h-step onto it and say what "too far" means:

fem.solve(adapt=jno.solve.relocate(objective=through, max_iters=200)
                         .remesh(criterion=lambda d: jno.le(d.cell_aspect(), 2.0), max_iters=4))
Where the quality floor is enforced

The condition is checked inside the relocation line search, on each candidate step, so an inadmissible mesh is never accepted — the march honours the bound exactly rather than reporting a breach after the fact.

When no admissible step exists, relocation has run out of room and the cells blocking it are refined; the movable vertices are then re-derived from the region each was tagged on, since indices do not survive a remesh. Measured on a Poisson peak, bound 1.7: 44 → 80 vertices over 3 remeshes, final worst aspect exactly 1.700, objective still falling 8.4e-02 → 2.0e-02.

The nested spec's max_iters caps how many remeshes the march may spend and max_dofs caps the size. If the budget runs out while the mesh still breaks the condition, that is raised, not returned quietly — refining does not repair every shape, and a bound below what the mesher can deliver would otherwise refine without end (measured, before this: 44 → … → 15709 vertices and an out-of-memory failure inside the solver).

Scope: the interleaved criterion must be a mesh-geometry condition (cell_aspect, cell_volume, cell_angles), because it is evaluated on the moving vertices with no solve, and the bound must sit directly on one node so it can be evaluated once per round rather than re-traced. A solution criterion belongs on a standalone jno.solve.remesh(...).

Mesh quality as a term you can write. domain.cell_aspect() is the longest edge over the inradius, scaled so a regular simplex reads exactly 1.0 and a stretched one reads more — per cell, 2-D and 3-D, and differentiable in the vertex positions (checked against central differences at 2.7e-10).

It is the companion to domain.cell_size, which is |det J|^(1/dim) — an isotropic size that cannot see stretch at all, since a sliver and a regular element of the same area share it. domain.cell_angles() also measures distortion but is 2-D only. Reference: Shewchuk, What Is a Good Linear Finite Element? (2002), §2.

Tagging is literal and per-axis: xm.trainable() frees only the x column. On a boundary that is the lever for sliding — free an edge's along-edge axis and its nodes redistribute within the wall, leave the normal axis untagged and the domain shape is preserved exactly.

method="monge_ampere" — the alternative

method="monge_ampere" swaps the descent for a Monge–Ampère mesh solve, m·det(I + H(φ)) = θ with x = ξ + ∇φ (McRae, Cotter & Budd, SIAM J. Sci. Comput. 40(2) 2018, arXiv:1612.08077 §3.1).

The displacement is a gradient, so the whole map cannot fold and no line search is needed, and it converges in 3–6 rounds against descent's 30. It is not the default, because on the Allen–Cahn front the suite measures (h=0.06, eps=0.03, error on a common fine grid so the metric does not depend on where each mesh puts its nodes) it loses on the answer:

mesh rel-L2 vs uniform min element quality
uniform 1.096e-01 1.000 0.834
relocate() (descent) 3.951e-02 0.361 0.503
relocate(method="monge_ampere") 8.879e-02 0.811 0.160

The cause is structural rather than a tuning miss: with one global θ, concentrating elements at the front forces the rest of the domain to stretch, which is why element quality collapses far from the feature. The control is under-relaxation — relax_step=0.02 recovers quality to 0.318 and the ratio to 0.633.