Skip to content
Merged
17 changes: 17 additions & 0 deletions docs/api/function.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ Unwrap UWexpressions to their underlying SymPy expressions for compilation.
.. autofunction:: underworld3.function.unwrap
```

### diff_wrt_field

Differentiate with respect to a field value or gradient, keeping the field's realness.
Use it, not `sympy.diff`, for a hand-written tangent or `flux_jacobian`.

```{eval-rst}
.. autofunction:: underworld3.function.diff_wrt_field
```

### derive_by_array_wrt_field

`sympy.derive_by_array` through `diff_wrt_field`.

```{eval-rst}
.. autofunction:: underworld3.function.derive_by_array_wrt_field
```

## Quantities and Units

### UWQuantity
Expand Down
13 changes: 11 additions & 2 deletions docs/developer/guides/plasticity-solvers.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,25 @@ frozen and unwrapped flux by exactly the `∂η/∂(grad v)` term):

```python
import sympy
import underworld3 as uw
from underworld3.function.expressions import unwrap_expression
F1 = sympy.Array(stokes.F1.sym)
L = sympy.Array(stokes.Unknowns.L)
G_picard = sympy.derive_by_array(F1, L)
G_picard = uw.function.derive_by_array_wrt_field(F1, L)
F1_unwrapped = sympy.Array(
[unwrap_expression(e, mode="symbolic_keep_constants") for e in F1], F1.shape)
G_newton = sympy.derive_by_array(F1_unwrapped, L)
G_newton = uw.function.derive_by_array_wrt_field(F1_unwrapped, L)
# a nonzero difference == the Newton form is present
```

Differentiate with respect to fields the way the solvers do, with
`uw.function.derive_by_array_wrt_field` (or `uw.function.diff_wrt_field` for one
entry), never plain `sympy.diff` or `sympy.derive_by_array`, in this check and in a
hand-written tangent or `flux_jacobian`. Field values and gradients are declared
real, so a yield floor at softness 0 contains `Abs`, and SymPy differentiates with
respect to a field through a stand-in with no assumptions: it leaves
`Derivative(u, u)` unevaluated in the `Abs` term, which cannot be compiled (#823).

---

## δ smoothing — a modelling choice, not a convergence strategy (#475 substrate)
Expand Down
13 changes: 11 additions & 2 deletions docs/developer/subsystems/petsc-jacobian-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,16 @@ for fc in range(Nc):
for gc in range(Nc):
for df in range(dim):
for dg in range(dim):
G3[fc * Nc + gc, df * dim + dg] = sympy.diff(F1[fc, df], L[gc, dg])
G3[fc * Nc + gc, df * dim + dg] = uw.function.diff_wrt_field(
F1[fc, df], L[gc, dg])
```

Differentiate with `uw.function.diff_wrt_field`, never plain `sympy.diff`. Field
values and gradients are declared real, so SymPy writes $\sqrt{g^2}$ as $|g|$;
`sympy.diff` differentiates with respect to a field through a stand-in with no
assumptions and leaves `sign(g)*Derivative(u, u)` unevaluated, which cannot be
compiled (#823).

Row index `fc * Nc + gc`, col index `df * dim + dg`. Row-major flatten
gives `((fc * Nc + gc) * dim + df) * dim + dg` — PETSc's expected index.

Expand Down Expand Up @@ -210,7 +217,9 @@ consumers.

When writing a new class that registers a `PetscDSSetJacobian` callback:

1. **Use the explicit-index pattern from `SNES_MultiComponent` — always.**
1. **Use the explicit-index pattern from `SNES_MultiComponent` — always,** with
every entry differentiated by `uw.function.diff_wrt_field` (or
`uw.function.derive_by_array_wrt_field` for a whole array), not `sympy.diff`.
It reads like the PETSc documentation and is robust against sympy
convention drift. There is no remaining in-repo
`derive_by_array + permutedims` Jacobian path to copy from, by design:
Expand Down
100 changes: 100 additions & 0 deletions docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# JIT setup cost (#823): adversarial review record

Branch `bugfix/jit-setup-cost-823`, stacked on `bugfix/jit-petsc-include-dirs` (#828).
Three adversarial rounds, each run against the installed build of the commits it
reviewed, plus an independent measurement session (the tier-2 codegen work) that
profiled the notch and confirmed generated-C identity by header hash.

## What the branch does

| Change | Cost removed (Spiegelman notch, Newton) | Output |
|---|---|---|
| Memoised complete unwrap (`_unwrap_expression_complete`) | 563 s → 0.11 s for the viscosity | srepr-identical to the fixed-point `subs` loop, except two cases where the loop was wrong (below) |
| Identity-walk symbol scan (`_unique_symbols`), memoised sqrt guard, debug text only when debugging | 35 s, 16 s, 23 s | identical |
| Field values, gradients, coordinates, constant slots and unit-carrying parameters declared real | complex-plane evaluation in `Pow` | solutions bit-identical on 18 models; C differs (`fabs` for `sqrt(x**2)`) |
| Every Jacobian derivative through `uw.function.diff_wrt_field` (a real stand-in) | 131 s → 3.5 s for `uu_G3` | C byte-identical to plain `sympy.diff` where both compile |
| Power-mean sharpness `s` held as its own constant | 40 s → 0.05 s Newton source | solutions to 6.8e-13, same iterations |
| Shared-graph constants substitution, printer `re()` pass only when needed | 4.3 s, 2.9 s | identical |

Notch setup on `development`: 616 s (sqrt law) and 1,352 s (power mean). On the
branch: 10 s and 13 s; 18 s and 25 s including the C build. The whole generated header
of the notch, VEP and TI fixtures is byte-identical across the last two commits
(md5 checked by the tier-2 session). Full serial suite 3,014 passed; parallel np=2
passes except #826; five reference solutions bit-identical to the build without the
realness declarations, except the power mean (6.8e-13, same 18 iterations).

## Findings and their state

Round 1 (on the memoised unwrap and the first realness commit):

- **Field realness broke the Newton Jacobian** (found by the tier-2 session first):
`sqrt(g**2)` becomes `Abs(g)`, and `sympy.diff` with respect to a field goes through
an assumption-free `Dummy`, leaving `Derivative(u, u)` unprintable. Drucker-Prager
with a yield floor at softness 0 failed to compile. Fixed by differentiating through
a real stand-in (`diff_wrt_field`), which also fixed an explicit `Abs` of the unknown
in any Jacobian, broken on `development`.
- **Coordinate realness turns a twice-differentiated kink into a `DiracDelta`**,
which C cannot print. Fixed: one rule (`_without_dirac_deltas`) for the JIT printer
and every evaluate path, dropping the term (its value away from the zero) with a
warning.
- Tests that could not fail (the unwrap equivalence passed on the old algorithm; the
include test passed wherever the headers were on the default path): replaced by a
constancy-call count (25 vs 103) and a check of the generated `setup.py`.
- Smaller: a guard around a hard dependency (Charter §5), the process-global
coordinate patch documented, the identity claim corrected (the old loop returned
`Subs(...)` for a held `Derivative` and a meaningless result for a cycle).

Round 2 (on the stand-in):

- `uw.function.evaluate` raised `NameError` on a `DiracDelta` the JIT compiled.
Fixed by the shared rule, applied at each evaluator's entry so constants keep their
broadcast shape.
- The governing Jacobian-layout doc and the plasticity guide taught plain
`sympy.diff`, and pointed at private helpers. The helpers are public
(`uw.function.diff_wrt_field`, `derive_by_array_wrt_field`) and both docs teach them.
- `UWQuantity` realness raised on a `Fraction` and said "real" for NaN; fixed.
- The helper mis-handled a held `Derivative` and a plain number; fixed.
- Tests: a loose accuracy gate (1e-4 for a 1.3e-9 error) tightened to 1e-7; a
"compiles" test that never compiled now solves against the viscous answer; a source
census fails if a solver differentiates with `sympy.diff`.

Round 3 (on the sharpness atom and the round-2 fixes):

- The Clement evaluation path still raised on a `DiracDelta`; fixed.
- The warning was attributed to library frames and repeated in a loop when the delta's
argument changed; it now points at the user's call and warns once per call site, on
every rank for a (rank-local) evaluation and on rank 0 for the (collective) JIT.
- A field `Abs` beside a held `Derivative` lost its derivative; fixed.
- The census test's exact count was a drift detector; dropped, and the scan covers
`systems/`. The sharpness test now asserts a δ change does not recompile.
- `Float(0.001)` for an exact constant (Charter §6); now `Rational(1, 1000)`.

## Attacks that failed

- Memoised unwrap vs the fixed point: Piecewise, Subs, matrix-valued `.sym`, `None`
sym, a diamond DAG (no false cycle), units with scaling on and off, `.sym` changed
between calls, all four modes.
- `_unique_symbols` vs `atoms(Symbol)` on 18 awkward types; the sqrt guard vs
`.replace(simultaneous=True)` on 161 cases.
- Determinism: generated C byte-identical across `PYTHONHASHSEED` 1, 2, 3 for 13
models; no `Dummy` name reaches C.
- The sharpness atom tracks δ through the property, the homotopy control and the
anchor reset; two models get distinct atoms; the JIT key is unchanged by a δ change.
- No spurious `DiracDelta` warning in any VP or VEP Newton solve at softness 0.

## Known and accepted

- For VEP and TI power-mean models δ no longer appears in the constants manifest
(only `s` does), so the step transcript records `{s_{y}}`, from which δ follows.
- The `BaseScalar` realness patch applies to every `sympy.vector` coordinate system
in the process (documented at the patch).
- Plain `sympy.diff` with respect to a field in user code now leaves
`Derivative(u, u)` beside a field `Abs`; the guides direct users to
`diff_wrt_field`.

## Out of scope, filed

- #826: `test_1063` [ti] topography 1.8 % off its anchor on the anchor's own mesh,
identical on `development` and with every change here switched off.
- #827: every viscoelastic Stokes solve prints a PETSc error banner from
`_check_velocity_preconditioner`.
1 change: 1 addition & 0 deletions docs/reviews/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ docs/reviews/

| Review | Component | Tests | Pass Rate | Date | Status |
|--------|-----------|-------|-----------|------|--------|
| JIT setup cost ([2026-10](2026-10/jit-setup-cost-823-adversarial-review.md), #823) | JIT/Solvers | adversarial, 3 rounds | Passing | 2026-10-07 | Fixes on branch |
| Units System (2026-02) | Units/Scaling | 60+ | Passing | 2026-02-01 | Approved (2026-03-10) |
| Data Access (2026-02) | Array/Math Interface | 75+ | Passing | 2026-02-01 | Approved (2026-03-10) |
| Reduction Operations | Mesh/Swarm Arrays | 5 | ✅ 100% | 2025-10-25 | ✅ Approved |
Expand Down
26 changes: 22 additions & 4 deletions src/underworld3/constitutive_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,18 @@ def _get_yield_softness(self):
self._yield_offset_for_anchor(),
"Yield soft-min offset; tracks δ so the chosen anchor is exact",
)
# The power mean's sharpness, held as its own atom like the offset. δ is
# floored SMOOTHLY (+0.001, not Max()) so 1/δ stays finite as δ → 0 (a Max
# on the δ atom triggers an unsupported symbolic numeric comparison).
# Written inline, the exponent -1/(δ + 0.001) has a sum in its
# denominator, and SymPy then evaluates im() of the whole base each time
# it builds a**(-s) (its test for a power of E): 40 s of the notch Newton
# source, 0.1 s with the atom (#823).
self._yield_sharpness_expr = expression(
R"{s_{y}}",
1 / (self._yield_softness_expr + sympy.Rational(1, 1000)),
"Power-mean soft-min sharpness s = 1/(δ + 0.001); tracks δ",
)
else:
self._yield_softness_expr.sym = sympy.Float(delta_value)
return self._yield_softness_expr
Expand All @@ -1085,6 +1097,11 @@ def _get_yield_offset(self):
self._get_yield_softness()
return self._yield_offset_expr

def _get_yield_sharpness(self):
"""The power-mean sharpness atom ``s = 1/(δ + 0.001)`` (created alongside δ)."""
self._get_yield_softness()
return self._yield_sharpness_expr

@property
def yield_anchor(self):
r"""Which point of the ``"softmin"`` yield law is pinned to the exact ``Min``.
Expand Down Expand Up @@ -1146,6 +1163,7 @@ def yield_anchor(self, value):
# (#490).
self._yield_offset_expr = None
self._yield_softness_expr = None
self._yield_sharpness_expr = None
self._reset()

def _combine_yield(self, eta_ve, eta_pl):
Expand Down Expand Up @@ -1183,10 +1201,8 @@ def _combine_yield(self, eta_ve, eta_pl):
delta = self._get_yield_softness()
f = eta_ve / eta_pl
if smoother == "powermean":
# Soft-min of order -s in an overflow-safe harmonic-normalised form. δ is
# floored SMOOTHLY (+ε, not Max()) so 1/δ stays finite as δ→0 (a Max on
# the δ atom triggers an unsupported symbolic numeric comparison).
s = 1 / (delta + sympy.Float(0.001))
# Soft-min of order -s in an overflow-safe harmonic-normalised form.
s = self._get_yield_sharpness()
a = 1 + f
b = 1 + 1 / f
# Harmonic mean written as eta_ve/(1+f), NOT eta_ve*eta_pl/(eta_ve+eta_pl).
Expand Down Expand Up @@ -1512,6 +1528,7 @@ def __init__(self, unknowns, material_name: str = None):
self._yield_smoother = "sqrt" # smooth-min family: "sqrt" | "powermean"
self._yield_softness_expr = None # constants[] δ atom (created lazily)
self._yield_offset_expr = None # onset-offset atom (created lazily)
self._yield_sharpness_expr = None # power-mean sharpness atom (created lazily)

class _Parameters(_ParameterBase, _ViscousParameterAlias):
"""Any material properties that are defined by a constitutive relationship are
Expand Down Expand Up @@ -1817,6 +1834,7 @@ def __init__(self, unknowns, order=1, integrator: str = "bdf",
self._yield_smoother = "sqrt" # smooth-min family: "sqrt" | "powermean"
self._yield_softness_expr = None # constants[] δ atom (created lazily)
self._yield_offset_expr = None # onset-offset atom (created lazily)
self._yield_sharpness_expr = None # power-mean sharpness atom (created lazily)

# Timestep — set by the solver before each solve(). Not a user parameter.
# Initialised to oo (viscous limit). The solver overwrites this with the
Expand Down
21 changes: 21 additions & 0 deletions src/underworld3/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,27 @@
from sympy.vector.scalar import BaseScalar


# Coordinates are real and finite. sympy.vector does not say so (BaseScalar.is_real is
# None), so every unwrapped kernel, which holds the plain BaseScalars of mesh.N, was
# complex as far as SymPy's simplification knew (#823). Stated on the class, so it
# covers mesh.N, mesh.Gamma and every UWCoordinate, and, because it is the class,
# every sympy.vector coordinate system created after underworld3 is imported (a
# BaseScalar whose realness was asked before the import keeps its cached None).
def _coordinate_is_real_and_finite(self):
return True


BaseScalar._eval_is_real = _coordinate_is_real_and_finite
BaseScalar._eval_is_extended_real = _coordinate_is_real_and_finite
BaseScalar._eval_is_finite = _coordinate_is_real_and_finite
# SymPy collects a class's _eval_is_* handlers into _prop_handler when the class is
# CREATED, so a handler added afterwards is never consulted: register it there too.
# _prop_handler is SymPy-private; test_0022 fails if a SymPy release changes it.
BaseScalar._prop_handler["real"] = _coordinate_is_real_and_finite
BaseScalar._prop_handler["extended_real"] = _coordinate_is_real_and_finite
BaseScalar._prop_handler["finite"] = _coordinate_is_real_and_finite


class UWCoordinate(BaseScalar):
"""
A Cartesian coordinate variable (x, y, or z).
Expand Down
Loading
Loading