diff --git a/docs/api/function.md b/docs/api/function.md index 9ac50e271..ff58372f7 100644 --- a/docs/api/function.md +++ b/docs/api/function.md @@ -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 diff --git a/docs/developer/guides/plasticity-solvers.md b/docs/developer/guides/plasticity-solvers.md index 6d0e3c56c..8f03f37c4 100644 --- a/docs/developer/guides/plasticity-solvers.md +++ b/docs/developer/guides/plasticity-solvers.md @@ -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) diff --git a/docs/developer/subsystems/petsc-jacobian-layout.md b/docs/developer/subsystems/petsc-jacobian-layout.md index 09cd9a539..d778ebebb 100644 --- a/docs/developer/subsystems/petsc-jacobian-layout.md +++ b/docs/developer/subsystems/petsc-jacobian-layout.md @@ -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. @@ -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: diff --git a/docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md b/docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md new file mode 100644 index 000000000..345fc65d3 --- /dev/null +++ b/docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md @@ -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`. diff --git a/docs/reviews/README.md b/docs/reviews/README.md index 530a47470..e47f7cfe8 100644 --- a/docs/reviews/README.md +++ b/docs/reviews/README.md @@ -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 | diff --git a/src/underworld3/constitutive_models.py b/src/underworld3/constitutive_models.py index 44424922a..a35bd823d 100644 --- a/src/underworld3/constitutive_models.py +++ b/src/underworld3/constitutive_models.py @@ -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 @@ -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``. @@ -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): @@ -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). @@ -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 @@ -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 diff --git a/src/underworld3/coordinates.py b/src/underworld3/coordinates.py index a8a0b71a7..47bb74984 100644 --- a/src/underworld3/coordinates.py +++ b/src/underworld3/coordinates.py @@ -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). diff --git a/src/underworld3/cython/petsc_generic_snes_solvers.pyx b/src/underworld3/cython/petsc_generic_snes_solvers.pyx index 5bc95bb59..0e73b97b9 100644 --- a/src/underworld3/cython/petsc_generic_snes_solvers.pyx +++ b/src/underworld3/cython/petsc_generic_snes_solvers.pyx @@ -51,6 +51,7 @@ from underworld3.function import expression as public_expression expression = lambda *x, **X: public_expression(*x, _unique_name_generation=True, **X) from underworld3.function.expressions import unwrap_expression as _unwrap_expression +from underworld3.function._function import diff_wrt_field, derive_by_array_wrt_field def _public_names(cls): @@ -103,11 +104,35 @@ def _jacobian_unwrap(expr): # every HALF-INTEGER power: +1/2 (the invariant itself), -1/2 # (its reciprocal in eta_pl = tau_y/(2 edot_II)), -3/2 (their # derivatives), ... — all singular in value or derivative at a - # zero-argument state - return e.replace( - lambda n: (n.is_Pow and n.exp.is_Rational - and n.exp.q == 2 and n.args[0].free_symbols), - lambda n: sympy.Pow(n.args[0] + eps2, n.exp)) + # zero-argument state. + # The same bottom-up rebuild as `e.replace(query, value)`, memoised on node + # identity: the unwrapped flux repeats its shared sub-expressions as the same + # object, and `replace` walked every occurrence (measured 16 s of a 108 s + # notch compile, #823). + memo = {} + + def guard(n): + hit = memo.get(id(n)) + if hit is not None: + return hit[1] + out = n + args = getattr(n, "args", None) + if args: + new_args = tuple(guard(a) for a in args) + if any(a is not b for a, b in zip(args, new_args)) and args != new_args: + out = n.func(*new_args) + # replace(simultaneous=True): a rebuild that collapses to one of + # the changed arguments is not matched again + if any(out == a and a != b for a, b in zip(args, new_args)): + memo[id(n)] = (n, out) + return out + if (out.is_Pow and out.exp.is_Rational and out.exp.q == 2 + and out.args[0].free_symbols): + out = sympy.Pow(out.args[0] + eps2, out.exp) + memo[id(n)] = (n, out) + return out + + return guard(e) f = lambda e: _guard_sqrts( _unwrap_expression(e, mode="symbolic_keep_constants")) @@ -4214,23 +4239,23 @@ class SNES_Scalar(SolverBaseClass): # Only G3's index order moves. Uc = U[0] G0 = sympy.zeros(1, 1) - G0[0, 0] = sympy.diff(f0_jac[0], Uc) + G0[0, 0] = diff_wrt_field(f0_jac[0], Uc) # G1[df, 0] = d f0 / d L[df] G1 = sympy.zeros(cdim, 1) for df in range(cdim): - G1[df, 0] = sympy.diff(f0_jac[0], L[df]) + G1[df, 0] = diff_wrt_field(f0_jac[0], L[df]) # G2[0, df] = d F1[df] / d U G2 = sympy.zeros(1, cdim) for df in range(cdim): - G2[0, df] = sympy.diff(F1_jac[df], Uc) + G2[0, df] = diff_wrt_field(F1_jac[df], Uc) # G3[df, dg] = d F1[df] / d L[dg] G3 = sympy.zeros(cdim, cdim) for df in range(cdim): for dg in range(cdim): - G3[df, dg] = sympy.diff(F1_jac[df], L[dg]) + G3[df, dg] = diff_wrt_field(F1_jac[df], L[dg]) self._G0 = sympy.ImmutableMatrix(G0) self._G1 = sympy.ImmutableMatrix(G1) @@ -4260,8 +4285,8 @@ class SNES_Scalar(SolverBaseClass): bd_F0 = sympy.Array(bc.fn_f) bc.fns["u_f0"] = sympy.ImmutableDenseMatrix(bd_F0) - G0 = sympy.derive_by_array(bd_F0, U) - G1 = sympy.derive_by_array(bd_F0, L) + G0 = derive_by_array_wrt_field(bd_F0, U) + G1 = derive_by_array_wrt_field(bd_F0, L) bc.fns["uu_G0"] = sympy.ImmutableMatrix(G0.reshape(1, 1)) bc.fns["uu_G1"] = sympy.ImmutableMatrix(G1.reshape(dim, 1)) @@ -5188,21 +5213,21 @@ class SNES_Vector(SolverBaseClass): G0 = sympy.zeros(Nc, Nc) for fc in range(Nc): for gc in range(Nc): - G0[fc, gc] = sympy.diff(f0_jac_list[fc], U_list[gc]) + G0[fc, gc] = diff_wrt_field(f0_jac_list[fc], U_list[gc]) # G1[fc*Nc + gc, df] = ∂f0[fc] / ∂L[gc, df] G1 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - G1[fc * Nc + gc, df] = sympy.diff(f0_jac_list[fc], L[gc, df]) + G1[fc * Nc + gc, df] = diff_wrt_field(f0_jac_list[fc], L[gc, df]) # G2[fc*Nc + gc, df] = ∂F1[fc, df] / ∂U[gc] G2 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - G2[fc * Nc + gc, df] = sympy.diff(F1_jac[fc, df], U_list[gc]) + G2[fc * Nc + gc, df] = diff_wrt_field(F1_jac[fc, df], U_list[gc]) # G3[fc*Nc + gc, df*cdim + dg] = ∂F1[fc, df] / ∂L[gc, dg] G3 = sympy.zeros(Nc * Nc, cdim * cdim) @@ -5210,7 +5235,7 @@ class SNES_Vector(SolverBaseClass): for gc in range(Nc): for df in range(cdim): for dg in range(cdim): - G3[fc * Nc + gc, df * cdim + dg] = sympy.diff(F1_jac[fc, df], L[gc, dg]) + G3[fc * Nc + gc, df * cdim + dg] = diff_wrt_field(F1_jac[fc, df], L[gc, dg]) self._G0 = sympy.ImmutableMatrix(G0) self._G1 = sympy.ImmutableMatrix(G1) @@ -5253,9 +5278,9 @@ class SNES_Vector(SolverBaseClass): bd_G1 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): - bd_G0[fc, gc] = sympy.diff(bd_f0_list[fc], U_list[gc]) + bd_G0[fc, gc] = diff_wrt_field(bd_f0_list[fc], U_list[gc]) for df in range(cdim): - bd_G1[fc * Nc + gc, df] = sympy.diff(bd_f0_list[fc], L[gc, df]) + bd_G1[fc * Nc + gc, df] = diff_wrt_field(bd_f0_list[fc], L[gc, df]) bc.fns["uu_G0"] = sympy.ImmutableMatrix(bd_G0) bc.fns["uu_G1"] = sympy.ImmutableMatrix(bd_G1) @@ -5285,9 +5310,9 @@ class SNES_Vector(SolverBaseClass): for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - bd_G2[fc * Nc + gc, df] = sympy.diff(bd_F1_jac[fc, df], U_list[gc]) + bd_G2[fc * Nc + gc, df] = diff_wrt_field(bd_F1_jac[fc, df], U_list[gc]) for dg in range(cdim): - bd_G3[fc * Nc + gc, df * cdim + dg] = sympy.diff(bd_F1_jac[fc, df], L[gc, dg]) + bd_G3[fc * Nc + gc, df * cdim + dg] = diff_wrt_field(bd_F1_jac[fc, df], L[gc, dg]) bc.fns["uu_G2"] = sympy.ImmutableMatrix(bd_G2) bc.fns["uu_G3"] = sympy.ImmutableMatrix(bd_G3) @@ -5944,21 +5969,21 @@ class SNES_MultiComponent(SolverBaseClass): G0 = sympy.zeros(Nc, Nc) for fc in range(Nc): for gc in range(Nc): - G0[fc, gc] = sympy.diff(f0_jac_list[fc], U_list[gc]) + G0[fc, gc] = diff_wrt_field(f0_jac_list[fc], U_list[gc]) # G1[fc*Nc + gc, df] = ∂f0[fc] / ∂L[gc, df] G1 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - G1[fc * Nc + gc, df] = sympy.diff(f0_jac_list[fc], L[gc, df]) + G1[fc * Nc + gc, df] = diff_wrt_field(f0_jac_list[fc], L[gc, df]) # G2[fc*Nc + gc, df] = ∂F1[fc, df] / ∂U[gc] G2 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - G2[fc * Nc + gc, df] = sympy.diff(F1_jac[fc, df], U_list[gc]) + G2[fc * Nc + gc, df] = diff_wrt_field(F1_jac[fc, df], U_list[gc]) # G3[fc*Nc + gc, df*cdim + dg] = ∂F1[fc, df] / ∂L[gc, dg] G3 = sympy.zeros(Nc * Nc, cdim * cdim) @@ -5966,7 +5991,7 @@ class SNES_MultiComponent(SolverBaseClass): for gc in range(Nc): for df in range(cdim): for dg in range(cdim): - G3[fc * Nc + gc, df * cdim + dg] = sympy.diff(F1_jac[fc, df], L[gc, dg]) + G3[fc * Nc + gc, df * cdim + dg] = diff_wrt_field(F1_jac[fc, df], L[gc, dg]) self._G0 = sympy.ImmutableMatrix(G0) self._G1 = sympy.ImmutableMatrix(G1) @@ -6002,9 +6027,9 @@ class SNES_MultiComponent(SolverBaseClass): bd_G1 = sympy.zeros(Nc * Nc, cdim) for fc in range(Nc): for gc in range(Nc): - bd_G0[fc, gc] = sympy.diff(bd_f0_list[fc], U_list[gc]) + bd_G0[fc, gc] = diff_wrt_field(bd_f0_list[fc], U_list[gc]) for df in range(cdim): - bd_G1[fc * Nc + gc, df] = sympy.diff(bd_f0_list[fc], L[gc, df]) + bd_G1[fc * Nc + gc, df] = diff_wrt_field(bd_f0_list[fc], L[gc, df]) bc.fns["uu_G0"] = sympy.ImmutableMatrix(bd_G0) bc.fns["uu_G1"] = sympy.ImmutableMatrix(bd_G1) @@ -6030,9 +6055,9 @@ class SNES_MultiComponent(SolverBaseClass): for fc in range(Nc): for gc in range(Nc): for df in range(cdim): - bd_G2[fc * Nc + gc, df] = sympy.diff(bd_F1_jac[fc, df], U_list[gc]) + bd_G2[fc * Nc + gc, df] = diff_wrt_field(bd_F1_jac[fc, df], U_list[gc]) for dg in range(cdim): - bd_G3[fc * Nc + gc, df * cdim + dg] = sympy.diff(bd_F1_jac[fc, df], L[gc, dg]) + bd_G3[fc * Nc + gc, df * cdim + dg] = diff_wrt_field(bd_F1_jac[fc, df], L[gc, dg]) bc.fns["uu_G2"] = sympy.ImmutableMatrix(bd_G2) bc.fns["uu_G3"] = sympy.ImmutableMatrix(bd_G3) @@ -8282,18 +8307,19 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): _f0_flat = sympy.Array(F0_jac).reshape(dim) # Jacobian blocks are built with MATRIX-LEVEL diffs: one - # ``sympy.diff(, var)`` call per derivative - # variable instead of per-entry ``diff`` loops. Measured ~1.7x faster - # on large (monster-viscosity) fluxes — the batched elementwise diff - # reuses the derivative work across the block's shared subexpressions — - # and produces bit-identical entries (verified against the loop form). + # ``diff_wrt_field(, var)`` call per derivative + # variable instead of per-entry loops. Measured with ``sympy.diff`` ~1.7x + # faster on large (monster-viscosity) fluxes — the batched elementwise + # diff reuses the derivative work across the block's shared + # subexpressions — and bit-identical to the loop form. (#823 routed it + # through diff_wrt_field, measured no slower.) # The flat PETSc [fc, gc, df, dg] layout is preserved by assigning each # variable's matrix derivative into its slots below. # uu_G0[fc, gc] = dF0[fc] / dU[gc] G0 = sympy.zeros(Nc, Nc) for gc in range(Nc): - dF0_dU = sympy.diff(_f0_flat, U_list[gc]) + dF0_dU = diff_wrt_field(_f0_flat, U_list[gc]) for fc in range(Nc): G0[fc, gc] = dF0_dU[fc] @@ -8301,14 +8327,14 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): G1 = sympy.zeros(Nc * Nc, dim) for gc in range(Nc): for dg in range(dim): - dF0_dL = sympy.diff(_f0_flat, L[gc, dg]) + dF0_dL = diff_wrt_field(_f0_flat, L[gc, dg]) for fc in range(Nc): G1[fc * Nc + gc, dg] = dF0_dL[fc] # uu_G2[fc*Nc + gc, df] = dF1[fc, df] / dU[gc] G2 = sympy.zeros(Nc * Nc, dim) for gc in range(Nc): - dF1_dU = sympy.diff(F1_for_jac, U_list[gc]) + dF1_dU = diff_wrt_field(F1_for_jac, U_list[gc]) for fc in range(Nc): for df in range(dim): G2[fc * Nc + gc, df] = dF1_dU[fc, df] @@ -8317,7 +8343,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): G3 = sympy.zeros(Nc * Nc, dim * dim) for gc in range(Nc): for dg in range(dim): - dF1_dL = sympy.diff(F1_for_jac, L[gc, dg]) + dF1_dL = diff_wrt_field(F1_for_jac, L[gc, dg]) for fc in range(Nc): for df in range(dim): G3[fc * Nc + gc, df * dim + dg] = dF1_dL[fc, df] @@ -8336,20 +8362,20 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): # up_G0[fc, 0] = dF0[fc] / dp G0 = sympy.zeros(dim, 1) - dF0_dp = sympy.diff(_f0_flat, p_scalar) + dF0_dp = diff_wrt_field(_f0_flat, p_scalar) for fc in range(dim): G0[fc, 0] = dF0_dp[fc] # up_G1[fc, dg] = dF0[fc] / d(dp/dx_dg) G1 = sympy.zeros(dim, dim) for dg in range(dim): - dF0_dGp = sympy.diff(_f0_flat, Gp[0, dg]) + dF0_dGp = diff_wrt_field(_f0_flat, Gp[0, dg]) for fc in range(dim): G1[fc, dg] = dF0_dGp[fc] # up_G2[fc, df] = dF1[fc, df] / dp G2 = sympy.zeros(dim, dim) - dF1_dp = sympy.diff(F1_for_jac, p_scalar) + dF1_dp = diff_wrt_field(F1_for_jac, p_scalar) for fc in range(dim): for df in range(dim): G2[fc, df] = dF1_dp[fc, df] @@ -8357,7 +8383,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): # up_G3[fc*dim + df, dg] = dF1[fc, df] / d(dp/dx_dg) G3 = sympy.zeros(dim * dim, dim) for dg in range(dim): - dF1_dGp = sympy.diff(F1_for_jac, Gp[0, dg]) + dF1_dGp = diff_wrt_field(F1_for_jac, Gp[0, dg]) for fc in range(dim): for df in range(dim): G3[fc * dim + df, dg] = dF1_dGp[fc, df] @@ -8371,8 +8397,8 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): # P/U block (check permutations) - G0 = sympy.derive_by_array(PF0_jac, self.u.sym) - G1 = sympy.derive_by_array(PF0_jac, self.Unknowns.L) + G0 = derive_by_array_wrt_field(PF0_jac, self.u.sym) + G1 = derive_by_array_wrt_field(PF0_jac, self.Unknowns.L) # (there is no FP1 flux term, so the pu_G2 / pu_G3 blocks are empty) self._pu_G0 = sympy.ImmutableMatrix(G0.reshape(dim)) # non zero @@ -8400,7 +8426,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): for mvar, eps in zip(self._multipliers, self._multiplier_screening): h_F0 = sympy.ImmutableDenseMatrix(sympy.Array([eps * mvar.sym[0]]).reshape(1)) hh_G0 = sympy.ImmutableMatrix( - sympy.derive_by_array(sympy.Array([eps * mvar.sym[0]]), mvar.sym).reshape(1, 1) + derive_by_array_wrt_field(sympy.Array([eps * mvar.sym[0]]), mvar.sym).reshape(1, 1) ) self._h_F0.append(h_F0) self._hh_G0.append(hh_G0) @@ -8433,14 +8459,14 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): G0 = sympy.zeros(dim, dim) for fc in range(dim): for gc in range(dim): - G0[fc, gc] = sympy.diff(bd_f0_list[fc], U_list[gc]) + G0[fc, gc] = diff_wrt_field(bd_f0_list[fc], U_list[gc]) # uu_G1[fc*dim + gc, dg] = d bd_F0[fc] / dL[gc, dg] G1 = sympy.zeros(dim * dim, dim) for fc in range(dim): for gc in range(dim): for dg in range(dim): - G1[fc * dim + gc, dg] = sympy.diff(bd_f0_list[fc], L[gc, dg]) + G1[fc * dim + gc, dg] = diff_wrt_field(bd_f0_list[fc], L[gc, dg]) bc.fns["uu_G0"] = sympy.ImmutableMatrix(G0) bc.fns["uu_G1"] = sympy.ImmutableMatrix(G1) @@ -8449,13 +8475,13 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): # up_G0[fc, 0] = d bd_F0[fc] / dp G0 = sympy.zeros(dim, 1) for fc in range(dim): - G0[fc, 0] = sympy.diff(bd_f0_list[fc], p_scalar) + G0[fc, 0] = diff_wrt_field(bd_f0_list[fc], p_scalar) # up_G1[fc, dg] = d bd_F0[fc] / d(dp/dx_dg) G1 = sympy.zeros(dim, dim) for fc in range(dim): for dg in range(dim): - G1[fc, dg] = sympy.diff(bd_f0_list[fc], Gp[0, dg]) + G1[fc, dg] = diff_wrt_field(bd_f0_list[fc], Gp[0, dg]) bc.fns["up_G0"] = sympy.ImmutableMatrix(G0) bc.fns["up_G1"] = sympy.ImmutableMatrix(G1) @@ -8478,7 +8504,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): for fc in range(dim): for gc in range(dim): for df in range(dim): - G2[fc * dim + gc, df] = sympy.diff( + G2[fc * dim + gc, df] = diff_wrt_field( bd_F1_jac[fc, df], U_list[gc] ) @@ -8488,7 +8514,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): for gc in range(dim): for df in range(dim): for dg in range(dim): - G3[fc * dim + gc, df * dim + dg] = sympy.diff( + G3[fc * dim + gc, df * dim + dg] = diff_wrt_field( bd_F1_jac[fc, df], L[gc, dg] ) @@ -8500,14 +8526,14 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): G2 = sympy.zeros(dim, dim) for fc in range(dim): for df in range(dim): - G2[fc, df] = sympy.diff(bd_F1[fc, df], p_scalar) + G2[fc, df] = diff_wrt_field(bd_F1[fc, df], p_scalar) # up_G3[fc*dim + df, dg] = d bd_F1[fc, df] / d(dp/dx_dg) G3 = sympy.zeros(dim * dim, dim) for fc in range(dim): for df in range(dim): for dg in range(dim): - G3[fc * dim + df, dg] = sympy.diff( + G3[fc * dim + df, dg] = diff_wrt_field( bd_F1[fc, df], Gp[0, dg] ) @@ -8523,8 +8549,8 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): bc.fns["p_f0"] = sympy.ImmutableDenseMatrix(bd_PF0) fns_bd_residual += [bc.fns["p_f0"]] - G0 = sympy.derive_by_array(bd_PF0, self.Unknowns.u.sym) - G1 = sympy.derive_by_array(bd_PF0, self.Unknowns.L) + G0 = derive_by_array_wrt_field(bd_PF0, self.Unknowns.u.sym) + G1 = derive_by_array_wrt_field(bd_PF0, self.Unknowns.L) bc.fns["pu_G0"] = sympy.ImmutableMatrix(G0.reshape(dim)) bc.fns["pu_G1"] = sympy.ImmutableMatrix(G1.reshape(dim*dim)) fns_bd_jacobian += [bc.fns["pu_G0"], bc.fns["pu_G1"]] @@ -8580,17 +8606,17 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): G0 = sympy.zeros(dim, dim) for fc in range(dim): for gc in range(dim): - G0[fc, gc] = sympy.diff(fn_f[fc], U_list[gc]) + G0[fc, gc] = diff_wrt_field(fn_f[fc], U_list[gc]) cbc.fns["uu_G0"] = sympy.ImmutableMatrix(G0) fns_bd_jacobian += [cbc.fns["uu_G0"]] # uh (0, h): ∂fn_f/∂h = n — mirror the up_G0 (velocity,scalar) shape - G0 = sympy.derive_by_array(sympy.Array(fn_f), H) + G0 = derive_by_array_wrt_field(sympy.Array(fn_f), H) cbc.fns["uh_G0"] = sympy.ImmutableMatrix(G0.reshape(dim)) fns_bd_jacobian += [cbc.fns["uh_G0"]] # hu (h, 0): ∂fn_h/∂u = n — mirror the pu_G0 (scalar,velocity) shape - G0 = sympy.derive_by_array(fn_h, self.Unknowns.u.sym) + G0 = derive_by_array_wrt_field(fn_h, self.Unknowns.u.sym) cbc.fns["hu_G0"] = sympy.ImmutableMatrix(G0.reshape(dim)) fns_bd_jacobian += [cbc.fns["hu_G0"]] diff --git a/src/underworld3/function/__init__.py b/src/underworld3/function/__init__.py index 59252026a..eacf0f356 100644 --- a/src/underworld3/function/__init__.py +++ b/src/underworld3/function/__init__.py @@ -28,6 +28,8 @@ from . import _function from ._function import ( UnderworldFunction, + diff_wrt_field, + derive_by_array_wrt_field, global_evaluate_nd as _global_evaluate_nd, evaluate_nd as _evaluate_nd, dm_swarm_get_migrate_type, @@ -193,11 +195,7 @@ def derivative(expression, variable, evaluate=True): return_self=False, ) - derivative = sympy.diff( - subbed_expr, - variable, - evaluate=True, - ) + derivative = diff_wrt_field(subbed_expr, variable) else: # Use the new natural syntax internally for deferred derivatives diff --git a/src/underworld3/function/_function.pyx b/src/underworld3/function/_function.pyx index 96540e25f..8ced00522 100644 --- a/src/underworld3/function/_function.pyx +++ b/src/underworld3/function/_function.pyx @@ -188,6 +188,12 @@ class UnderworldFunction(sympy.Function): # even if they have the same display name, solving the "funny whitespace" problem mesh = meshvar.mesh uw_id = mesh.instance_number if mesh.instance_number > 1 else None + # A mesh-variable value (and its derivative) is a real, finite number at every + # point. An undefined function is complex to SymPy by default, so every power + # with a symbolic exponent made it work out real and imaginary parts before + # combining powers (#823). Differentiate WITH RESPECT TO these through + # diff_wrt_field: sympy.diff swaps them for an assumption-free Dummy. + options.setdefault("real", True) ourcls = sympy.core.function.UndefinedFunction(fname,*args, bases=(UnderworldAppliedFunction,), _uw_id=uw_id, **options) # Grab weakref to meshvar. import weakref @@ -215,6 +221,101 @@ class UnderworldFunction(sympy.Function): return ourcls +def diff_wrt_field(expr, wrt): + r"""Partial derivative :math:`\partial f / \partial u` of ``expr`` with respect + to a field value or a field gradient component ``wrt``. + + Use this, not ``sympy.diff``, to differentiate with respect to a mesh variable + (writing a Newton tangent or a ``flux_jacobian``). Field values are declared + real, so SymPy writes :math:`\sqrt{g^2}` as :math:`|g|`. ``sympy.diff`` + differentiates with respect to anything that is not a Symbol by swapping it for + a stand-in ``Dummy`` with no assumptions, differentiating and substituting back, + so the field is complex while it is differentiated: :math:`|u - c|` gives + :math:`\mathrm{sign}(u - c)\,\partial u/\partial u` with the last factor left + unevaluated, which cannot be compiled. Here the stand-in carries the field's + realness; otherwise it is the same swap. + + ``wrt`` that is a Symbol (a coordinate, a parameter) goes to ``sympy.diff`` + unchanged. So does an ``expr`` holding an unevaluated ``Derivative``, which the + swap would hide from the variable it differentiates by; the + :math:`\partial u/\partial u` that SymPy then leaves beside a ``sign`` is set + to 1. + + Parameters + ---------- + expr : sympy.Expr or sympy.Matrix + The expression to differentiate. + wrt : sympy.Expr + A mesh-variable value such as ``T.sym[0]``, a gradient component such as + ``T.sym[0].diff(mesh.N.x)``, or any SymPy variable. + + Returns + ------- + sympy.Expr or sympy.Matrix + The derivative, the same shape as ``expr``. + + Examples + -------- + >>> mesh = uw.meshing.UnstructuredSimplexBox(cellSize=0.25) + >>> T = uw.discretisation.MeshVariable("T", mesh, 1, degree=1) + >>> c = sympy.Symbol("c", real=True) + >>> uw.function.diff_wrt_field(sympy.Abs(T.sym[0] - c), T.sym[0]) + sign(-c + T(N.x, N.y)) + """ + if not isinstance(expr, (sympy.Basic, sympy.MatrixBase)): + expr = sympy.sympify(expr) + from underworld3.utilities._jitextension import _holds_instance + + if not isinstance(wrt, sympy.core.function.AppliedUndef): + return sympy.diff(expr, wrt) + if _holds_instance(expr, sympy.Derivative): + # SymPy's own path, so the held Derivative still sees what it differentiates + # by; the d(u)/d(u) it then leaves next to an Abs or sign of u is 1 + return sympy.diff(expr, wrt).xreplace( + {sympy.Derivative(wrt, wrt, evaluate=False): sympy.S.One}) + stand_in = sympy.Dummy("xi", real=True) if wrt.is_real else sympy.Dummy("xi") + return sympy.diff(expr.xreplace({wrt: stand_in}), stand_in).subs(stand_in, wrt) + + +def derive_by_array_wrt_field(expr, dx): + r"""``sympy.derive_by_array(expr, dx)`` through :func:`diff_wrt_field`: every + derivative of ``expr`` with respect to every entry of ``dx``, keeping the + fields' realness. + + Parameters + ---------- + expr : sympy.Expr, sympy.Matrix, sympy.Array or list + The expression or array of expressions to differentiate. + dx : sympy.Matrix, sympy.Array or list + The variables: field values, gradient components (``solver.Unknowns.L``) + or SymPy symbols. + + Returns + ------- + sympy.Array + Entry ``[i..., j...]`` is + :math:`\partial\, \mathrm{expr}[j...] / \partial\, dx[i...]`, the layout + of ``sympy.derive_by_array``; its shape is ``dx.shape + expr.shape``. + + Examples + -------- + >>> F1 = sympy.Array(stokes.F1.sym) + >>> G = uw.function.derive_by_array_wrt_field(F1, stokes.Unknowns.L) + """ + from sympy.tensor.array import ImmutableDenseNDimArray, NDimArray + from sympy.tensor.array.arrayop import Flatten + + dx = ImmutableDenseNDimArray(dx) + if isinstance(expr, (list, tuple, sympy.MatrixBase, NDimArray)): + expr = (expr.as_immutable() if isinstance(expr, NDimArray) + else ImmutableDenseNDimArray(expr)) + return type(expr)([[diff_wrt_field(y, x) for y in Flatten(expr)] + for x in Flatten(dx)], dx.shape + expr.shape) + expr = sympy.sympify(expr) + return ImmutableDenseNDimArray([diff_wrt_field(expr, x) for x in Flatten(dx)], + dx.shape) + + # ============================================================================= # Shared helper functions for evaluation paths # ============================================================================= @@ -271,6 +372,9 @@ def _lambdify_and_evaluate(expr, coords, interpolated_results, coord_sys=None, m import random from sympy import lambdify from sympy.vector import CoordSys3D + from underworld3.utilities._jitextension import _without_dirac_deltas + + expr = _without_dirac_deltas(expr, "evaluate") # 1. Replace mesh variables with random symbol placeholders varfns_symbols = {} @@ -897,6 +1001,9 @@ def _clement_to_work_variable(expr, mesh, derivfns): import underworld3 as uw import sympy from underworld3.function.gradient_evaluation import compute_clement_gradient_at_nodes + from underworld3.utilities._jitextension import _without_dirac_deltas + + expr = _without_dirac_deltas(expr, "evaluate") # Get work variable (scalar, P1) if not hasattr(mesh, '_clement_work_scalar'): diff --git a/src/underworld3/function/expressions.py b/src/underworld3/function/expressions.py index 6ca0c29c1..05bde6184 100644 --- a/src/underworld3/function/expressions.py +++ b/src/underworld3/function/expressions.py @@ -199,6 +199,83 @@ def _unwrap_expression_once(expr, mode='nondimensional'): return expr +def _unwrap_expression_complete(expr, mode): + r"""Complete expansion of every UW atom in ``expr`` (the ``depth=None`` case). + + Each UW atom is expanded ONCE, memoised by identity, with the same rule as + :func:`_unwrap_atom`, including the same truly-constant predicate for + ``'symbolic_keep_constants'``, also memoised. Each expression is then rebuilt in + ONE ``xreplace`` pass. The result is the fixed point that repeated + :func:`_unwrap_expression_once` passes reach, structurally identical, with two + exceptions where the passes were wrong. An unevaluated ``Derivative`` of a UW + atom whose content depends on the differentiation variable: ``subs`` returned + ``Subs(Derivative(a*T, x), a, x**2)``, i.e. :math:`x^2\,\partial T/\partial x`, + where this returns ``Derivative(x**2*T, x)``, the derivative of the content, as + ``uw.function.derivative`` does. And a cyclic expression: the passes stopped + after 100 with a meaningless result, where this raises ``ValueError``. + + Why not repeated ``subs`` passes (#823): each pass traverses and re-canonicalises + the whole growing tree, and in keep-constants mode every atom on every pass ran + ``_is_truly_constant``, itself a full unwrap. On the Spiegelman notch viscosity, a + 130-node graph with 18 named sub-expressions that expands to a 9,913-node tree, + that took 563 s; this takes 0.11 s. Repeated sub-expressions in the result are the + same Python object, which identity-memoised walks downstream exploit. + """ + from underworld3.coordinates import UWCoordinate + + uw_types = (UWexpression, UWQuantity, UWCoordinate) + expanded = {} # id(atom) -> (atom, expansion); the atom is held so its id stays valid + constant = {} # id(atom) -> (atom, bool) + in_progress = set() + + def is_truly_constant(atom): + hit = constant.get(id(atom)) + if hit is None: + from underworld3.utilities._jitextension import _is_truly_constant + hit = constant[id(atom)] = (atom, _is_truly_constant(atom, UWexpression)) + return hit[1] + + def expand_atom(atom): + hit = expanded.get(id(atom)) + if hit is not None: + return hit[1] + if id(atom) in in_progress: + raise ValueError(f"cyclic expression: {atom} contains itself") + in_progress.add(id(atom)) + try: + if (mode == 'symbolic_keep_constants' and isinstance(atom, UWexpression) + and not isinstance(atom, UWCoordinate)): + # _unwrap_atom's keep-constants rule, with the predicate memoised + result = atom if is_truly_constant(atom) else expand(atom.sym) + else: + one_level = _unwrap_atom(atom, mode) + result = atom if one_level is atom else expand(one_level) + finally: + in_progress.discard(id(atom)) + expanded[id(atom)] = (atom, result) + return result + + def expand(e): + if isinstance(e, UWQuantity) and not isinstance(e, UWexpression): + return _unwrap_atom(e, mode) + if isinstance(e, uw_types): + return expand_atom(e) + if not hasattr(e, 'free_symbols'): + return e + mapping = {} + for sym in e.free_symbols: + if isinstance(sym, uw_types): + replacement = expand_atom(sym) + if replacement is not sym: + # as subs() did: a value that cannot be sympified (a units + # quantity in 'symbolic' mode) raises SympifyError here; a sympy + # object comes back as the same object, so sharing is kept + mapping[sym] = sympy.sympify(replacement) + return e.xreplace(mapping) if mapping else e + + return expand(expr) + + def unwrap_expression(expr, mode='nondimensional', depth=None): """ Unified unwrapping of UW expressions. @@ -228,17 +305,8 @@ def unwrap_expression(expr, mode='nondimensional', depth=None): else: return sympy.sympify(expr) - # Fixed-point iteration (or depth-limited) if depth is None: - result = working - result_next = _unwrap_expression_once(result, mode) - iteration = 0 - max_iterations = 100 # Safety limit - while result is not result_next and iteration < max_iterations: - result = result_next - result_next = _unwrap_expression_once(result, mode) - iteration += 1 - return result + return _unwrap_expression_complete(working, mode) else: result = working for _ in range(depth): diff --git a/src/underworld3/function/pure_sympy_evaluator.py b/src/underworld3/function/pure_sympy_evaluator.py index fa7764412..61ac33521 100644 --- a/src/underworld3/function/pure_sympy_evaluator.py +++ b/src/underworld3/function/pure_sympy_evaluator.py @@ -255,6 +255,10 @@ def evaluate_pure_sympy(expr, coords, coord_symbols=None): - Caches lambdified functions for repeated evaluations - ~10,000x faster than sympy.subs() for many points """ + from underworld3.utilities._jitextension import _without_dirac_deltas + + expr = _without_dirac_deltas(expr, "evaluate") + # Ensure coords is 2D numpy array coords_array = np.asarray(coords, dtype=np.float64) if coords_array.ndim == 1: diff --git a/src/underworld3/function/quantities.py b/src/underworld3/function/quantities.py index 8affa432f..bf29a1f78 100644 --- a/src/underworld3/function/quantities.py +++ b/src/underworld3/function/quantities.py @@ -793,6 +793,44 @@ def _sympy_(self): except (TypeError, ValueError): return sympy.sympify(self._value) + def _numeric_value(self): + """The value as a numpy array, or None for one numpy cannot read as a number.""" + try: + value = np.asarray(self._value) + return value if np.iscomplexobj(value) else value.astype(float) + except (TypeError, ValueError): + # Sanctioned: a value that is not a number (a string, an object); the + # realness questions below then answer "unknown", as SymPy would + return None + + @property + def is_extended_real(self): + """True when the value is real (or :math:`\\pm\\infty`), as SymPy's assumption; + None (unknown) for NaN or a value that is not a number. + + A UW expression holding this quantity reports its realness from here. Without + it every constitutive parameter given with units was "not known real", and + SymPy evaluated each power over a sum containing one in the complex plane + (#823). + """ + if isinstance(self._value, sympy.Basic): + return self._value.is_extended_real + value = self._numeric_value() + if value is None or np.any(np.isnan(value)): + return None + return bool(np.all(np.imag(value) == 0)) + + @property + def is_finite(self): + """True when the value is finite, as SymPy's assumption (``yield_stress = oo`` + is real but not finite); None for NaN or a value that is not a number.""" + if isinstance(self._value, sympy.Basic): + return self._value.is_finite + value = self._numeric_value() + if value is None or np.any(np.isnan(value)): + return None + return bool(np.all(np.isfinite(value))) + def __float__(self): """Convert to float.""" return float(self._value) diff --git a/src/underworld3/systems/free_surface.py b/src/underworld3/systems/free_surface.py index e913e2c6c..ededaae64 100644 --- a/src/underworld3/systems/free_surface.py +++ b/src/underworld3/systems/free_surface.py @@ -20,6 +20,7 @@ import underworld3 as uw from underworld3 import function +from underworld3.function._function import diff_wrt_field from underworld3.coordinates import CoordinateSystemType @@ -821,7 +822,7 @@ def _build_composition_transport(self): self._comp_adv.tolerance = 1.0e-4 if self._conserve_integrand is not None: self._conserve_area = uw.maths.Integral(self.mesh, self._conserve_integrand) - shift_rate = sympy.diff(self._conserve_integrand, self.composition.sym[0]) + shift_rate = diff_wrt_field(self._conserve_integrand, self.composition.sym[0]) self._conserve_rate = uw.maths.Integral(self.mesh, shift_rate) self._conserve_target = float(self._conserve_area.evaluate()) diff --git a/src/underworld3/utilities/_jitextension.py b/src/underworld3/utilities/_jitextension.py index 019b4326d..1fd8d7788 100644 --- a/src/underworld3/utilities/_jitextension.py +++ b/src/underworld3/utilities/_jitextension.py @@ -328,7 +328,7 @@ def prepare_for_cache_key(fn, constants_subs_map): if constants_subs_map and fn_structural is not None: try: if hasattr(fn_structural, "xreplace"): - fn_structural = fn_structural.xreplace(constants_subs_map) + fn_structural = _xreplace_shared(fn_structural, constants_subs_map) except Exception: pass @@ -376,6 +376,12 @@ class _JITConstant(sympy.Symbol): Identity without ordering is a parallel abort; ordering without identity is a silently wrong answer. Keep both. ``tests/test_0103_jit_rampable_constants.py`` pins each one separately. + + A slot holds a C double, so it is built ``real`` (real and finite) for SymPy's + simplification (#823). Declared at construction, not by a class handler: SymPy + shares one assumptions knowledge base between Symbols with the same declared + assumptions, so a handler's answer could be pre-empted by a plain Symbol's cached + ``None``. """ __slots__ = ("_const_index", "_ccodestr") @@ -385,7 +391,7 @@ def __new__(cls, index, name=None): # slot; see the class docstring on why the name alone is not enough # and _hashable_content alone is not either. suffix = "" if name is None else f"_{name}" - obj = sympy.Symbol.__xnew__(cls, f"_jit_const_{index}{suffix}") + obj = sympy.Symbol.__xnew__(cls, f"_jit_const_{index}{suffix}", real=True) obj._const_index = index obj._ccodestr = f"constants[{index}]" return obj @@ -473,6 +479,130 @@ def _extract_constants(all_fns, mesh): return manifest, subs_map +def _xreplace_shared(expr, rule): + """``expr.xreplace(rule)`` (a sympy expression or Matrix), visiting each node + OBJECT once. + + A compiled kernel repeats its shared sub-expressions as the same object (the + memoised unwrap inserts one object wherever an atom occurs, #823), and + ``xreplace`` rebuilds every occurrence: 4.3 s of the notch C generation for the + constants[] substitution alone. The result is the same expression. + """ + memo = {} + + def walk(e): + hit = memo.get(id(e)) + if hit is not None: + return hit[1] + if e in rule: + out = rule[e] + elif isinstance(e, sympy.Basic) and e.args: + new_args = tuple(walk(a) if isinstance(a, sympy.Basic) else a for a in e.args) + changed = any(n is not a for n, a in zip(new_args, e.args)) + out = e.func(*new_args) if changed else e + else: + out = e + memo[id(e)] = (e, out) + return out + + if isinstance(expr, sympy.MatrixBase): + return expr.applyfunc(walk) + return walk(expr) + + +def _holds_instance(expr, types): + """Whether ``expr`` holds a node of ``types``, visiting each node object once.""" + from sympy.tensor.array import NDimArray + + seen = {} + stack = [expr] + while stack: + e = stack.pop() + if id(e) in seen: + continue + seen[id(e)] = e + if isinstance(e, types): + return True + if isinstance(e, (sympy.MatrixBase, NDimArray)): + stack.extend(e) + elif isinstance(e, sympy.Basic): + stack.extend(e.args) + return False + + +def _warn_dirac_deltas_dropped(deltas, where, collective=False): + """Say that ``deltas`` were evaluated as 0 by ``where``, at the user's own call. + + The message names the count, not the delta, so a time loop warns once per call + site. A ``collective`` caller (the JIT, which every rank runs) warns on rank 0 + only; an evaluation is rank-local and warns wherever it runs. + """ + if not deltas or (collective and underworld3.mpi.rank != 0): + return + import sys + import warnings + + # the first frame outside the underworld3 package: the user's call + package = os.path.dirname(underworld3.__file__) + os.sep + frame, level = sys._getframe(1), 2 # stacklevel 2 is the frame that called this + while frame is not None and frame.f_code.co_filename.startswith(package): + frame, level = frame.f_back, level + 1 + warnings.warn( + f"{where}: {len(deltas)} DiracDelta term(s) taken as 0, their value away from " + f"the zero of the argument. A DiracDelta comes from differentiating a step " + f"once (a Heaviside or sign of the unknown in a Newton tangent, which then " + f"leaves out the jump) or a kink twice (Abs(x - a) in a manufactured source). " + f"A point source has to be applied as a point load.", + stacklevel=level, + ) + + +def _without_dirac_deltas(expr, where): + """``expr`` with every DiracDelta replaced by 0, warning if there were any. + + The rule for every path that turns an expression into numbers: the JIT (through + its printer), ``uw.function.evaluate`` and the field evaluator (through lambdify). + A pointwise evaluation cannot carry a distribution. + """ + if not hasattr(expr, "atoms"): + return expr + deltas = sorted(expr.atoms(sympy.DiracDelta), key=sympy.default_sort_key) + if not deltas: + return expr + _warn_dirac_deltas_dropped(deltas, where) + return expr.xreplace({d: sympy.S.Zero for d in deltas}) + + +def _unique_symbols(expr): + """The Symbol atoms of ``expr`` (a sympy expression, Matrix or Array): the same set + as ``expr.atoms(sympy.Symbol)``, found by visiting each node OBJECT once. + + ``atoms`` walks every occurrence of every node. An unwrapped constitutive law + repeats its shared sub-expressions as the SAME Python object (the memoised unwrap + inserts one object wherever an atom occurs, #823), so an identity walk is + proportional to the shared graph rather than the expanded tree: measured on the + Spiegelman notch kernels, ``atoms`` was 35 s of a 108 s compile. + """ + # keyed by id, holding the object so that no id is reused while the walk runs + seen = {} + found = set() + stack = [expr] + while stack: + e = stack.pop() + if id(e) in seen: + continue + seen[id(e)] = e + if isinstance(e, (sympy.MatrixBase, sympy.NDimArray)): + stack.extend(e) + continue + if isinstance(e, sympy.Symbol): + found.add(e) + continue + if isinstance(e, sympy.Basic): + stack.extend(e.args) + return found + + def _is_truly_constant(expr, UWexpression): """Check if a UWexpression resolves to a pure constant (no spatial deps). @@ -535,7 +665,7 @@ def _collect_constant_atoms(expr, result_set, is_constant_expr, UWexpression): return # Check all UWexpression atoms - for atom in _stable_sorted(expr.atoms(sympy.Symbol)): + for atom in _stable_sorted(_unique_symbols(expr)): if isinstance(atom, UWexpression) and _is_truly_constant(atom, UWexpression): result_set.add(atom) elif isinstance(atom, UWexpression): @@ -1186,6 +1316,28 @@ def _basescalar_ccode(self, printer): printer = c_code_printers["c99"]({"user_functions": custom_functions}) + # A DiracDelta is printed as 0, its value away from the zero of its argument, by + # the rule every evaluation path shares (_without_dirac_deltas). Done in the + # printer so that one made while lowering (cse, temporaries) is caught too. + dropped_deltas = [] + + def _print_DiracDelta(expr, **kwargs): + dropped_deltas.append(expr) + return "0.0" + + printer._print_DiracDelta = _print_DiracDelta + + # SymPy's code printer rewrites re(UnevaluatedExpr()) with a whole-tree + # replace on every kernel it prints (2.9 s of the notch C generation). Field values + # and coordinates are real (#823), so a kernel seldom holds any re() at all; the + # rewrite runs only when one is there. + handle_unevaluated = printer._handle_UnevaluatedExpr + + def _handle_UnevaluatedExpr(expr): + return handle_unevaluated(expr) if _holds_instance(expr, sympy.re) else expr + + printer._handle_UnevaluatedExpr = _handle_UnevaluatedExpr + # Purge libary/header dictionaries. These will be repopulated # when `doprint` is called below. This ensures that we only link # in libraries where needed. @@ -1237,7 +1389,7 @@ def _basescalar_ccode(self, printer): # C source must never disagree (issue #302). if constants_subs_map is not None and hasattr(fn, 'atoms'): unmanifested = [ - a.name for a in _stable_sorted(fn.atoms(sympy.Symbol)) + a.name for a in _stable_sorted(_unique_symbols(fn)) if isinstance(a, _UWexpr) and _is_truly_constant(a, _UWexpr) and a not in constants_subs_map @@ -1253,7 +1405,7 @@ def _basescalar_ccode(self, printer): # These survive into C code as constants[i] if constants_subs_map and fn is not None: try: - fn = fn.xreplace(constants_subs_map) if hasattr(fn, 'xreplace') else fn + fn = _xreplace_shared(fn, constants_subs_map) if hasattr(fn, 'xreplace') else fn except Exception: pass @@ -1264,7 +1416,7 @@ def _basescalar_ccode(self, printer): # slot and is about to be baked — refuse rather than freeze the # parameter silently (issue #302). if constants_subs_map and hasattr(fn, 'atoms'): - baked = [a.name for a in _stable_sorted(fn.atoms(sympy.Symbol)) + baked = [a.name for a in _stable_sorted(_unique_symbols(fn)) if a in constants_subs_map] if baked: raise RuntimeError( @@ -1414,6 +1566,8 @@ def _patch_coords(expr): ) eqns.append(eqn) + _warn_dirac_deltas_dropped(dropped_deltas, "JIT", collective=True) + MODNAME = "fn_ptr_ext_" + str(name) # JIT compile flags for the generated kernels. Default keeps -O3 (kernel @@ -1524,9 +1678,9 @@ def _patch_coords(expr): fn_counter = 0 for eqn in eqns[eqn_index_0:eqn_index_1]: - debug_str = debugging_text(randstr, fns[fn_counter], " res", fn_counter) + debug_str = debugging_text(randstr, fns[fn_counter], " res", fn_counter) if debug else "" h_str += "void {}_petsc_{}{}\n{{\n{}\n{}\n}}\n\n".format( - randstr, eqn[0], residual_sig, eqn[1], debug_str if debug else "" + randstr, eqn[0], residual_sig, eqn[1], debug_str ) pyx_str += " void {}_petsc_{}{}\n".format(randstr, eqn[0], residual_sig) fn_counter += 1 @@ -1538,9 +1692,9 @@ def _patch_coords(expr): # but we leave this separate in case it changes in later PETSc implementations for eqn in eqns[eqn_index_0:eqn_index_1]: - debug_str = debugging_text(randstr, fns[fn_counter], " ebc", fn_counter) + debug_str = debugging_text(randstr, fns[fn_counter], " ebc", fn_counter) if debug else "" h_str += "void {}_petsc_{}{}\n{{\n{}\n{}\n}}\n\n".format( - randstr, eqn[0], residual_sig, eqn[1], debug_str if debug else "" + randstr, eqn[0], residual_sig, eqn[1], debug_str ) pyx_str += " void {}_petsc_{}{}\n".format(randstr, eqn[0], residual_sig) fn_counter += 1 @@ -1549,10 +1703,10 @@ def _patch_coords(expr): eqn_index_1 = eqn_index_1 + count_jacobian_sig for eqn in eqns[eqn_index_0:eqn_index_1]: - debug_str = debugging_text(randstr, fns[fn_counter], " jac", fn_counter) + debug_str = debugging_text(randstr, fns[fn_counter], " jac", fn_counter) if debug else "" h_str += "void {}_petsc_{}{}\n{{\n{}\n{}\n}}\n\n".format( - randstr, eqn[0], jacobian_sig, eqn[1], debug_str if debug else "" + randstr, eqn[0], jacobian_sig, eqn[1], debug_str ) pyx_str += " void {}_petsc_{}{}\n".format(randstr, eqn[0], jacobian_sig) fn_counter += 1 @@ -1560,9 +1714,9 @@ def _patch_coords(expr): eqn_index_0 = eqn_index_1 eqn_index_1 = eqn_index_1 + count_bd_residual_sig for eqn in eqns[eqn_index_0:eqn_index_1]: - debug_str = debugging_text_bd(randstr, fns[fn_counter], "bdres", fn_counter) + debug_str = debugging_text_bd(randstr, fns[fn_counter], "bdres", fn_counter) if debug else "" h_str += "void {}_petsc_{}{}\n{{\n{}\n{}\n}}\n\n".format( - randstr, eqn[0], bd_residual_sig, eqn[1], debug_str if debug else "" + randstr, eqn[0], bd_residual_sig, eqn[1], debug_str ) pyx_str += " void {}_petsc_{}{}\n".format(randstr, eqn[0], bd_residual_sig) fn_counter += 1 @@ -1570,9 +1724,9 @@ def _patch_coords(expr): eqn_index_0 = eqn_index_1 eqn_index_1 = eqn_index_1 + count_bd_jacobian_sig for eqn in eqns[eqn_index_0:eqn_index_1]: - debug_str = debugging_text_bd(randstr, fns[fn_counter], "bdjac", fn_counter) + debug_str = debugging_text_bd(randstr, fns[fn_counter], "bdjac", fn_counter) if debug else "" h_str += "void {}_petsc_{}{}\n{{\n{}\n{}\n}}\n\n".format( - randstr, eqn[0], bd_jacobian_sig, eqn[1], debug_str if debug else "" + randstr, eqn[0], bd_jacobian_sig, eqn[1], debug_str ) pyx_str += " void {}_petsc_{}{}\n".format(randstr, eqn[0], bd_jacobian_sig) fn_counter += 1 diff --git a/tests/test_0022_unwrap_memoised_matches_fixed_point.py b/tests/test_0022_unwrap_memoised_matches_fixed_point.py new file mode 100644 index 000000000..573f84302 --- /dev/null +++ b/tests/test_0022_unwrap_memoised_matches_fixed_point.py @@ -0,0 +1,184 @@ +"""The memoised unwrap, the memoised sqrt guard and the identity-walk symbol scan (#823) +give exactly what the algorithms they replace gave. + +The old ``unwrap_expression`` iterated ``subs`` passes to a fixed point, and in +``symbolic_keep_constants`` mode ran ``_is_truly_constant`` (itself a full unwrap) for every +atom on every pass. On the Spiegelman notch viscosity that took 563 s; the memoised +version takes 0.11 s. These tests hold the replacement to STRUCTURAL identity (``srepr``) +with a copy of the old algorithm, on the constitutive laws the solvers compile, in every +mode. Identical expressions mean identical generated C and identical JIT cache keys. +""" +import pytest +import sympy + +import underworld3 as uw +import underworld3.function.expressions as ex + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + +MODES = ("nondimensional", "symbolic", "symbolic_keep_constants", "dimensional") + + +def _fixed_point_unwrap(expr, mode): + """The algorithm #823 replaced, kept here as the reference.""" + if isinstance(expr, ex.UWQuantity) and not isinstance(expr, ex.UWexpression): + return ex._unwrap_atom(expr, mode) + result = expr + nxt = ex._unwrap_expression_once(result, mode) + it = 0 + while result is not nxt and it < 100: + result = nxt + nxt = ex._unwrap_expression_once(result, mode) + it += 1 + return result + + +def _laws(): + """(name, expression) for the laws the solvers compile, built on a small box.""" + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.5) + x, y = mesh.X + v = uw.discretisation.MeshVariable("V0022", mesh, mesh.dim, degree=2) + p = uw.discretisation.MeshVariable("P0022", mesh, 1, degree=1) + f = uw.discretisation.MeshVariable("F0022", mesh, 1, degree=0, continuous=False) + out = [] + for law in ("min", "sqrt", "powermean"): + s = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + s.constitutive_model = uw.constitutive_models.ViscoPlasticFlowModel + cm = s.constitutive_model + cm.Parameters.shear_viscosity_0 = 1.0 + f.sym[0] + C = uw.expression(rf"C_{{{law}}}", 0.5, "cohesion") + cm.Parameters.yield_stress = C + 0.3 * p.sym[0] + cm.Parameters.yield_stress_min = 0.02 * C + cm.Parameters.shear_viscosity_min = 1.0e-3 * (1.0 + x) + if law != "min": + cm.yield_mode = "softmin" + cm.yield_smoother = law + cm.yield_softness = 0.1 + cm.viscosity_min_rounding = 1.0e-4 + out.append((f"viscoplastic_{law}", cm.viscosity)) + out.append((f"viscoplastic_{law}_flux", s.F1.sym)) + s = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + s.constitutive_model = uw.constitutive_models.ViscoElasticPlasticFlowModel(s.Unknowns, order=1) + cm = s.constitutive_model + cm.Parameters.shear_viscosity_0 = 1.0 + cm.Parameters.shear_modulus = 1.0 + cm.Parameters.dt_elastic = sympy.Rational(1, 10) + cm.Parameters.yield_stress = 0.3 + out.append(("viscoelastic_plastic_flux", s.F1.sym)) + u = uw.discretisation.MeshVariable("U0022", mesh, 1, degree=1) + pois = uw.systems.Poisson(mesh, u_Field=u) + pois.constitutive_model = uw.constitutive_models.DiffusionModel + pois.constitutive_model.Parameters.diffusivity = 1.0 + u.sym[0] ** 2 + out.append(("poisson_k_of_u_flux", pois.F1.sym)) + return out + + +@pytest.fixture(scope="module") +def laws(): + uw.reset_default_model() + return _laws() + + +def _unwrap_each(expr, fn): + if isinstance(expr, sympy.MatrixBase): + return expr.applyfunc(fn) + return fn(expr) + + +@pytest.mark.parametrize("mode", MODES) +def test_memoised_unwrap_is_the_fixed_point(laws, mode): + for name, expr in laws: + try: + old = _unwrap_each(expr, lambda e: _fixed_point_unwrap(e, mode)) + except Exception as failure: + # e.g. 'symbolic' mode on a parameter holding a units quantity: subs() + # could not sympify it. The replacement must fail the same way. + with pytest.raises(type(failure)): + _unwrap_each(expr, lambda e: ex.unwrap_expression(e, mode=mode)) + continue + new = _unwrap_each(expr, lambda e: ex.unwrap_expression(e, mode=mode)) + assert sympy.srepr(new) == sympy.srepr(old), (name, mode) + + +def test_the_jacobian_sqrt_guard_matches_replace(laws): + from underworld3.cython.generic_solvers import _jacobian_unwrap + + eps2 = sympy.Float(1.0e-36) + + def old_guard(e): + return e.replace( + lambda n: (n.is_Pow and n.exp.is_Rational and n.exp.q == 2 + and n.args[0].free_symbols), + lambda n: sympy.Pow(n.args[0] + eps2, n.exp)) + + for name, expr in laws: + new = _jacobian_unwrap(expr) + old = _unwrap_each(expr, lambda e: old_guard( + _fixed_point_unwrap(e, "symbolic_keep_constants"))) + assert sympy.srepr(new) == sympy.srepr(old), name + + +def test_the_identity_walk_finds_the_same_symbols(laws): + from underworld3.utilities._jitextension import _unique_symbols + + for name, expr in laws: + for e in (expr, ex.unwrap_expression(expr, mode="nondimensional") + if not isinstance(expr, sympy.MatrixBase) + else expr.applyfunc(lambda a: ex.unwrap_expression(a, mode="nondimensional"))): + assert _unique_symbols(e) == set(e.atoms(sympy.Symbol)), name + + +def test_the_shared_xreplace_matches_xreplace(laws): + """The constants[] substitution in the JIT lowering visits each node object once; + it must build exactly what xreplace builds, the generated C and the cache key + both depend on it.""" + from underworld3.utilities._jitextension import _xreplace_shared, _unique_symbols + + swapped = 0 + for name, expr in laws: + unwrapped = _unwrap_each(expr, lambda e: ex.unwrap_expression( + e, mode="symbolic_keep_constants")) + held = sorted((a for a in _unique_symbols(unwrapped) + if isinstance(a, ex.UWexpression)), key=str) + if not held: + continue # k(u) = 1 + u**2 has no parameter to swap + rule = {a: sympy.Symbol(f"slot_{k}") for k, a in enumerate(held)} + assert sympy.srepr(_xreplace_shared(unwrapped, rule)) == \ + sympy.srepr(unwrapped.xreplace(rule)), name + swapped += 1 + assert swapped >= 7 # the VP (three laws, viscosity and flux) and VEP + + +def test_each_atom_is_tested_for_constancy_once(monkeypatch): + """The cost that #823 removed: the fixed-point passes asked whether each atom was + a constant on every pass, and each answer was itself a full unwrap. On a chain of + 12 nested expressions with 25 distinct UW atoms the passes asked 103 times; the + memoised unwrap asks once per distinct atom.""" + import underworld3.utilities._jitextension as jx + + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.5) + T = uw.discretisation.MeshVariable("T0022c", mesh, 1, degree=1) + levels = 12 + e = uw.expression(r"e_{0022c,0}", T.sym[0], "base") + for k in range(1, levels + 1): + c = uw.expression(rf"c_{{0022c,{k}}}", 0.1 * k, "constant") + e = uw.expression(rf"e_{{0022c,{k}}}", e + c * T.sym[0] + e * c, "level") + calls = [] + is_truly_constant = jx._is_truly_constant + + def counted(atom, uw_type): + calls.append(atom) + return is_truly_constant(atom, uw_type) + + monkeypatch.setattr(jx, "_is_truly_constant", counted) + ex.unwrap_expression(e, mode="symbolic_keep_constants") + assert len(calls) == 2 * levels + 1, len(calls) + + +def test_a_cyclic_expression_is_refused(): + a = uw.expression(r"a_{cyc}", 1.0, "cyclic test") + a.sym = a + 1 + with pytest.raises(ValueError, match="cyclic"): + ex.unwrap_expression(a, mode="symbolic") diff --git a/tests/test_0023_field_realness_and_derivatives.py b/tests/test_0023_field_realness_and_derivatives.py new file mode 100644 index 000000000..7626f20ee --- /dev/null +++ b/tests/test_0023_field_realness_and_derivatives.py @@ -0,0 +1,332 @@ +"""Field values, coordinates and parameters are declared real, and every derivative +with respect to a field keeps that realness (#823). + +SymPy treats an undefined function, a sympy.vector coordinate and a plain Symbol as +possibly complex, so it worked out real and imaginary parts all through the +constitutive laws. Declaring them real changes what SymPy builds (sqrt(g**2) is +Abs(g)), and sympy.diff differentiates with respect to a field through a stand-in +with no assumptions. These tests hold both halves: the declarations, and the +solvers' differentiation through uw.function.diff_wrt_field. +""" +import pathlib +from fractions import Fraction + +import numpy as np +import pytest +import sympy + +import underworld3 as uw + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + + +def test_field_values_coordinates_and_constant_slots_are_declared_real(): + """SymPy treats an undefined function, a sympy.vector coordinate and a plain Symbol + as possibly complex, so a power with a symbolic exponent made it work out real and + imaginary parts before combining powers (#823). Field values, their gradients and + coordinates are real and finite. A UW expression reads its realness from its + content, so one built on them is real too.""" + from underworld3.utilities._jitextension import _JITConstant + + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.5) + v = uw.discretisation.MeshVariable("V0022r", mesh, mesh.dim, degree=2) + x = mesh.N.x + for atom in (v.sym[0], v.sym[0].diff(x), x, mesh.N.y, mesh.X[0]): + assert atom.is_real is True and atom.is_finite is True, atom + assert sympy.im(atom) == 0, atom + # content with no number in it: before #823 neither a field value nor a + # coordinate was known real, so this was None and im() stayed unevaluated + e = uw.expression(r"e_{0022}", v.sym[0] ** 2 + v.sym[1].diff(x) + mesh.X[1], + "built on a field and a coordinate") + assert e.is_extended_real is True + assert sympy.im(e) == 0 + # `real` asked FIRST: with a class handler instead of a construction-time + # assumption this read a plain Symbol's cached None (test-order dependent) + for _ in range(20): + assert _JITConstant(0, "c").is_real is True + # and nothing leaks the other way: a plain SymPy symbol stays unknown + plain = sympy.Symbol("plain_0022") + assert plain.is_extended_real is None and plain.is_real is None + + +def test_derivatives_with_respect_to_a_field_keep_its_realness(): + """sympy.diff differentiates with respect to a field value or gradient through an + assumption-free Dummy, so a real field is complex while it is differentiated: an + Abs that realness made out of sqrt(g**2) leaves Derivative(u, u) unevaluated, and + an explicit Abs(u) comes back in re() and im() (both unprintable). The solvers + differentiate through uw.function.diff_wrt_field, whose stand-in is real.""" + from underworld3.function import diff_wrt_field, derive_by_array_wrt_field + + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.5) + u = uw.discretisation.MeshVariable("U0022d", mesh, 1, degree=1) + c = sympy.Symbol("c_0022", real=True) + s = sympy.Symbol("s_0022", positive=True) + for w in (u.sym[0], u.sym[0].diff(mesh.N.x)): + cases = { + sympy.sqrt((c + w) ** 2): sympy.sign(c + w), + sympy.Abs(w - c): sympy.sign(w - c), + (w ** 2 + c ** 2) ** s: 2 * s * w * (w ** 2 + c ** 2) ** (s - 1), + } + for f, expected in cases.items(): + d = diff_wrt_field(f, w) + assert not d.has(sympy.Derivative, sympy.re, sympy.im), (f, d) + assert sympy.simplify(d - expected) == 0, (f, d) + # a coordinate goes to sympy.diff unchanged, and so do an unevaluated Derivative + # (the swap would hide it from its variable) and a plain number + x = mesh.N.x + assert diff_wrt_field(x ** 2 * u.sym[0], x) == sympy.diff(x ** 2 * u.sym[0], x) + held = sympy.Derivative(u.sym[0] ** 2, x) + assert diff_wrt_field(held, u.sym[0]) == sympy.diff(held, u.sym[0]) != 0 + assert diff_wrt_field(3, u.sym[0]) == 0 + # ... and a field Abs beside a held Derivative still differentiates to its sign + beside = sympy.Abs(u.sym[0] - c) + sympy.Derivative(x ** 2 * c, x) + assert diff_wrt_field(beside, u.sym[0]) == sympy.sign(u.sym[0] - c) + # the array form has derive_by_array's layout: [i, j] = d f[j] / d dx[i] + f = sympy.Array([u.sym[0] ** 2, sympy.Abs(u.sym[0] - c)]) + dx = sympy.Array([u.sym[0], c]) + got = derive_by_array_wrt_field(f, dx) + assert got.shape == (2, 2) + assert got[0, 0] == 2 * u.sym[0] and got[0, 1] == sympy.sign(u.sym[0] - c) + assert got[1, 0] == 0 and got[1, 1] == sympy.sign(c - u.sym[0]) + + +def test_newton_poisson_with_an_abs_conductivity_matches_kirchhoff(): + """A Jacobian through Abs of the unknown: k(u) = 1 + |u - 0.2| on a unit square, + u = 0.5 at the bottom and 1 at the top, no source. The flux depends on y alone, and + for u > 0.2 the Kirchhoff transform phi(u) = 0.8 u + u**2 / 2 is linear in y, so + u(y) = -0.8 + sqrt(0.64 + 2 (0.525 + 0.775 y)). Before #823 the Newton tangent + (re and im of an applied function) could not be printed.""" + uw.reset_default_model() + mesh = uw.meshing.StructuredQuadBox(elementRes=(4, 16), minCoords=(0.0, 0.0), + maxCoords=(1.0, 1.0)) + u = uw.discretisation.MeshVariable("U0022k", mesh, 1, degree=2) + pois = uw.systems.Poisson(mesh, u_Field=u) + pois.constitutive_model = uw.constitutive_models.DiffusionModel + pois.constitutive_model.Parameters.diffusivity = 1 + sympy.Abs( + u.sym[0] - sympy.Rational(1, 5)) + pois.f = 0 + pois.add_dirichlet_bc(0.5, "Bottom") + pois.add_dirichlet_bc(1.0, "Top") + pois.consistent_jacobian = True + pois.tolerance = 1.0e-10 + u.array[...] = 0.75 + pois.solve(zero_init_guess=False) + assert pois.snes.getConvergedReason() > 0 + exact = -0.8 + np.sqrt(0.64 + 2 * (0.525 + 0.775 * u.coords[:, 1])) + assert np.max(np.abs(u.array[:, 0, 0] - exact)) < 1.0e-7 + # Newton on a smooth (u > 0.2 everywhere) problem: a handful of iterations + assert pois.snes.getIterationNumber() <= 6 + + +def test_newton_drucker_prager_with_a_yield_floor_compiles_and_solves(): + """The case that found it: at yield softness 0 the yield-stress floor is + smooth_max(tau_y, tau_min, 0) = (a + b + sqrt((a - b)**2)) / 2 = Max, and the + Newton tangent differentiates it with respect to the pressure field. The yield + stress is far above the stress, so the solve must reproduce the viscous one.""" + + def shear_box(name, constitutive_model): + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25) + v = uw.discretisation.MeshVariable("V" + name, mesh, 2, degree=2) + p = uw.discretisation.MeshVariable("P" + name, mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + stokes.constitutive_model = constitutive_model + stokes.add_dirichlet_bc((0.0, 0.0), "Bottom") + stokes.add_dirichlet_bc((1.0, 0.0), "Top") + stokes.bodyforce = sympy.Matrix([0, -mesh.X[0]]) + stokes.tolerance = 1.0e-10 + return stokes, v, p + + uw.reset_default_model() + stokes, v, p = shear_box("0023n", uw.constitutive_models.ViscoPlasticFlowModel) + params = stokes.constitutive_model.Parameters + params.shear_viscosity_0 = 1.0 + params.yield_stress = (uw.expression(r"C_{0023n}", 100.0, "cohesion") + + uw.expression(r"\mu_{0023n}", 0.6, "friction") * p.sym[0]) + params.yield_stress_min = uw.expression(r"\tau_{0023n}", 0.01, "yield floor") + stokes.constitutive_model.yield_softness = 0 + stokes.consistent_jacobian = True + stokes.solve() + assert stokes.snes.getConvergedReason() > 0 + + viscous, v0, _ = shear_box("0023v", uw.constitutive_models.ViscousFlowModel) + viscous.constitutive_model.Parameters.shear_viscosity_0 = 1.0 + viscous.solve() + v, v0 = np.asarray(v.array), np.asarray(v0.array) + assert np.max(np.abs(v - v0)) < 1.0e-8 * np.max(np.abs(v0)) + + +def test_no_solver_differentiates_with_plain_sympy_diff(): + """Every Jacobian in the solvers differentiates with respect to fields, so every + one must go through diff_wrt_field. A site written with sympy.diff would pass + every other test here until a law put an Abs or a sign of a field in its flux.""" + src = pathlib.Path(__file__).parents[1] / "src" / "underworld3" + sources = [src / "cython" / "petsc_generic_snes_solvers.pyx", + *sorted((src / "systems").glob("*.py"))] + for path in sources: + text = path.read_text() + for plain in ("sympy.diff(", "sympy.derive_by_array("): + assert plain not in text, (path.name, plain) + + +def test_newton_through_a_step_of_the_unknown_compiles_without_the_jump(): + """Differentiating a Heaviside of the unknown gives a DiracDelta, which a + pointwise kernel cannot carry: the tangent leaves the jump out and says so. + Before #823 the tangent could not be printed at all.""" + uw.reset_default_model() + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25) + u = uw.discretisation.MeshVariable("U0023h", mesh, 1, degree=1) + pois = uw.systems.Poisson(mesh, u_Field=u) + pois.constitutive_model = uw.constitutive_models.DiffusionModel + pois.constitutive_model.Parameters.diffusivity = 1 + sympy.Heaviside(u.sym[0] - 2) + pois.f = 1.0 + pois.add_dirichlet_bc(0.0, "Bottom") + pois.consistent_jacobian = True + with pytest.warns(UserWarning, match="DiracDelta"): + pois.solve() + # u stays below 2, where k = 1: the Poisson solve with k = 1 exactly + assert pois.snes.getConvergedReason() > 0 + reference = uw.discretisation.MeshVariable("U0023r", mesh, 1, degree=1) + plain = uw.systems.Poisson(mesh, u_Field=reference) + plain.constitutive_model = uw.constitutive_models.DiffusionModel + plain.constitutive_model.Parameters.diffusivity = 1.0 + plain.f = 1.0 + plain.add_dirichlet_bc(0.0, "Bottom") + plain.solve() + assert np.max(np.abs(np.asarray(u.array) - np.asarray(reference.array))) < 1.0e-10 + + +def test_a_dirac_delta_compiles_as_zero_and_says_so(): + """The coordinates are real, so sqrt((x - a)**2) is Abs(x - a) and its second + derivative is 2*DiracDelta(x - a), which C cannot print. It compiles as 0, its value + away from x = a: the solve is the solve without the delta, to the last bit.""" + uw.reset_default_model() + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25) + x, y = mesh.X + kink = sympy.sqrt((x - sympy.Rational(3, 10)) ** 2) + assert sympy.diff(kink, x, 2).has(sympy.DiracDelta) + + def solve(f, name): + u = uw.discretisation.MeshVariable(name, mesh, 1, degree=2) + pois = uw.systems.Poisson(mesh, u_Field=u) + pois.constitutive_model = uw.constitutive_models.DiffusionModel + pois.constitutive_model.Parameters.diffusivity = 1.0 + pois.f = f + pois.add_dirichlet_bc(0.0, "Bottom") + pois.solve() + return np.array(u.array) + + with pytest.warns(UserWarning, match="DiracDelta"): + with_delta = solve(1 + sympy.diff(kink, x, 2) * sympy.sin(sympy.pi * y), "U0023a") + without = solve(sympy.Integer(1), "U0023b") + assert np.array_equal(with_delta, without) + + # evaluate follows the same rule, with and without a field in the expression + points = np.array([[0.1, 0.5], [0.3, 0.5], [0.8, 0.2]]) + T = uw.discretisation.MeshVariable("T0023e", mesh, 1, degree=1) + T.array[...] = 2.0 + for f, expected, rbf in ((1 + sympy.diff(kink, x, 2), 1.0, False), + (T.sym[0] * (1 + sympy.diff(kink, x, 2)), 2.0, False), + (2 + T.sym[0].diff(x) * sympy.diff(kink, x, 2), 2.0, True)): + with pytest.warns(UserWarning, match="DiracDelta") as record: + values = uw.function.evaluate(f, points, rbf=rbf) + # attributed to this call, not to a frame inside underworld3 + assert record[0].filename == __file__ + assert np.asarray(values).shape == (len(points), 1, 1) + assert np.allclose(np.asarray(values).ravel(), expected, rtol=1.0e-12) + + +def test_parameters_given_with_units_are_known_real(): + """A UW expression reports realness from its content, and a parameter given with + units holds a UWQuantity, which had no realness to report. Every power over a sum + containing one was then evaluated in the complex plane: 36 s of the 43 s Newton + source on the Spiegelman notch (#823). A UWQuantity is real when its value is.""" + from underworld3.cython.generic_solvers import _jacobian_unwrap + from underworld3.function.expressions import UWexpression + from underworld3.utilities._jitextension import _unique_symbols + + uw.reset_default_model() + orchestration_model = uw.get_default_model() + orchestration_model.set_reference_quantities( + domain_depth=uw.quantity(100, "km"), + material_viscosity=uw.quantity(1e21, "Pa*s"), + lithostatic_pressure=uw.quantity(1e8, "Pa"), + ) + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.5) + v = uw.discretisation.MeshVariable("V0022u", mesh, 2, degree=2) + p = uw.discretisation.MeshVariable("P0022u", mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + stokes.constitutive_model = uw.constitutive_models.ViscoPlasticFlowModel + params = stokes.constitutive_model.Parameters + params.shear_viscosity_0 = uw.quantity(1e24, "Pa*s") + params.shear_viscosity_min = uw.quantity(1e20, "Pa*s") + params.yield_stress = uw.quantity(1e8, "Pa") + params.yield_stress_min = uw.quantity(0, "Pa") + + for value in (uw.quantity(1e24, "Pa*s"), uw.quantity(0, "Pa"), + uw.quantity(Fraction(1, 2), "Pa")): + assert value.is_extended_real is True and value.is_finite is True + infinite = uw.quantity(float("inf"), "Pa") + assert infinite.is_extended_real is True and infinite.is_finite is False + # unknown, as SymPy says for nan + nan = uw.quantity(float("nan"), "Pa") + assert nan.is_extended_real is None and nan.is_finite is None + + flux = _jacobian_unwrap(stokes.constitutive_model.flux) + held = [a for a in _unique_symbols(flux) if isinstance(a, UWexpression)] + assert held, "the Newton flux keeps its constant parameters as atoms" + unknown = [a for a in held if a.is_extended_real is not True] + assert not unknown, unknown + + +def test_the_power_mean_sharpness_follows_the_softness(): + """The power mean's sharpness s = 1/(delta + 0.001) is its own constant atom (an + inline -1/(delta + 0.001) exponent made SymPy evaluate im() of the whole base on + every rebuild: 40 s of the notch Newton source, #823). It must follow delta: a + solve after changing delta equals a fresh model built at that delta.""" + + def yielding_box(name, delta): + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25) + v = uw.discretisation.MeshVariable("V" + name, mesh, 2, degree=2) + p = uw.discretisation.MeshVariable("P" + name, mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + stokes.constitutive_model = uw.constitutive_models.ViscoPlasticFlowModel + cm = stokes.constitutive_model + cm.Parameters.shear_viscosity_0 = 1.0 + cm.Parameters.yield_stress = 0.8 + cm.yield_mode = "softmin" + cm.yield_smoother = "powermean" + cm.yield_softness = delta + stokes.add_dirichlet_bc((0.0, 0.0), "Bottom") + stokes.add_dirichlet_bc((1.0, 0.0), "Top") + stokes.tolerance = 1.0e-10 + stokes.consistent_jacobian = True + return stokes, v + + uw.reset_default_model() + ramped, v_ramped = yielding_box("0023s", 1.0) + from underworld3.cython.generic_solvers import _jacobian_unwrap + from underworld3.utilities._jitextension import _unique_symbols + + sharpness = ramped.constitutive_model._get_yield_sharpness() + assert sharpness in _unique_symbols(_jacobian_unwrap(ramped.constitutive_model.flux)) + ramped.solve() + assert ramped.snes.getConvergedReason() > 0 + at_one = np.array(v_ramped.array) + compiled = ramped._current_jit_cache_key + ramped.constitutive_model.yield_softness = 0.25 + ramped.solve(zero_init_guess=False) + # delta (and s with it) is a constants[] value: changing it does not recompile + assert ramped._current_jit_cache_key == compiled + fresh, v_fresh = yielding_box("0023f", 0.25) + fresh.solve() + assert ramped.snes.getConvergedReason() > 0 and fresh.snes.getConvergedReason() > 0 + assert np.max(np.abs(np.asarray(v_ramped.array) - np.asarray(v_fresh.array))) < 1.0e-7 + # and the softness matters here, or the comparison could not fail + assert np.max(np.abs(at_one - np.asarray(v_fresh.array))) > 1.0e-3