Skip to content

Stokes refuses a P1 velocity on simplices; evaluate refuses a dimensional argument to exp, log and the trigonometric functions - #1197

Open
lmoresi wants to merge 18 commits into
developmentfrom
units/p1-simplex-and-transcendental
Open

lmoresi wants to merge 18 commits into
developmentfrom
units/p1-simplex-and-transcendental

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

What changes for users:

  • A Stokes-family solver on a triangle or tetrahedral mesh refuses a velocity of degree 1 and points to degree=2.
  • In a model with reference quantities, a function such as exp, log or sin of an argument that carries units is refused: at evaluate, when a constitutive parameter or the body force is set, when an integral is made, and at every solve.
  • That includes a bare coordinate: sin(pi*x) must be written sin(pi*x/W) with W a length.

This is the follow-up to #1182. Every part follows Louis's "more willing to raise errors":

  • He approved the P1 refusal as a change to solver behaviour.
  • He ruled that a bare coordinate inside a function is refused, not read in model units: "I would prefer refusal. What might be helpful for a human (let me hold your hand) is an anti-pattern for AI helping out. So let's assume that AI is the helper and the code is playing with a straight bat all the time."

Runs were on a 96-thread Linux workstation (single system image; Intel Xeon Gold 6240R, AVX-512; MPICH).

P1 velocity on simplices

P1/P0 locks, and P1/P1 is unstable. On simplices, degree=1 is in Louis's words "almost an incomplete specification".

  • Where: the Stokes base class (SNES_Stokes_SaddlePt), before any field is created. This covers Stokes, NavierStokes, VE_Stokes and Stokes_Constrained, whether the velocity comes from degree=1 or is passed in as a P1 field.
  • The message points to degree=2 (P2/P1).
  • Collective: the decision reads the mesh's isSimplex, which all ranks agree on at construction, so every rank refuses together.
  • Not refused:
    • Q1/P0 on quadrilaterals and hexahedra (the classic Underworld element);
    • P2/P0 on simplices;
    • Darcy, which is not a saddle-point solver.
  • The interface does not change.

Function arguments must be dimensionless

exp(eta1) has no meaning. In a model with reference quantities these are now refused:

  • By rule, not by a list. Any applied sympy function needs a dimensionless argument: exp, log, the trigonometric and hyperbolic functions and their inverses, erf and erfc.

  • Exempt: functions that pass units through: Abs, Min, Max, Piecewise, sign, Heaviside, floor, ceiling, re, im, conjugate, DiracDelta, and mesh-variable functions.

  • Powers: the exponent must be dimensionless.

  • Functions of a ratio: atan2's two arguments must share a dimension, not each be dimensionless. The library's polar, spherical and geographic angles are built from it, so mesh.CoordinateSystem.R[1] on an annulus evaluates in a units model.

  • Coordinates are lengths.

  • How dimension is judged: Units contract: evaluate refuses mixed units and far points; Stokes fields carry units (#771, #904, #881, #786, #844, #1001) #1182's reduction decides. exp(eta1/eta0), exp(-E/(R*T0)) and sin(pi*x/W) are dimensionless and accepted.

  • Where it is checked:

    • at evaluate;
    • when a constitutive parameter or the body force is set;
    • when an Integral, CellWiseIntegral or BdIntegral is made;
    • at every solve, over the solver's inputs: body force, source term f, essential and natural boundary values, and constitutive parameters. A named expression reassigned after it was set (k.sym = 1e21 Pa s inside eta0*exp(k)) is caught there.
  • Exempt work: library work inside the internal context, as for Units contract: evaluate refuses mixed units and far points; Stokes fields carry units (#771, #904, #881, #786, #844, #1001) #1182's refusals.

  • Cost: the verdict is cached on the expression and the current value and units of every named expression in it, and so is the units reduction of each argument, in bounded LRUs of 512 entries. A reassigned value is a new key. On a 40-term viscosity the check costs:

    • here: 0.9 ms per repeat solve (14.4 ms against 13.1 ms), and 1.0 to 6.9 ms when a named value changes before each check;
    • measured in the parallel review: 5 to 7 ms, and 24 to 26 ms after a reassignment, before the state key stopped formatting each named expression's units.
  • The units of a sum (compute_expression_units, behind uw.get_units). A sum of dimensionless terms returned None, meaning unknown, and get_units then took the units of the first field in it. So T/T0 - 1, E/(R*T) - E/(R*T0) and T/T0 + x/W came back in kelvin: the normalised Arrhenius factor was refused, while E*(1/T - 1/T0)/R was accepted. This is on development too.

    • A sum now has the dimension its terms share.
    • A sum of dimensionless terms that carry units is dimensionless.
    • A term that carries no units at all, such as a plain named parameter or a field without units, is a pure number beside such a ratio: T/T0 + k and beta*C - gamma*T/T0 are dimensionless.
    • A sum whose terms all carry no units has no units, as on development (test_0850, test_0851).
    • get_units no longer falls back to the first field's units for a sum.
    • A dimensionless constant, in any form (a number, uw.quantity(0.5, "dimensionless"), a non-dimensionalised value), may sit beside a dimensional term, and is read in model units.
    • Two terms that depend on the model and carry different dimensions raise MismatchedSumError, naming them. The hint names the units to give.
  • Functions that pass units through:

    • Min, Max and Piecewise take the units their branches share, and are refused if those disagree;
    • Abs and its kin keep their argument's units;
    • sign and Heaviside are pure numbers.

    So viscosity floors, caps and layers, such as eta_min + Min(eta1*exp(...), eta_max) and eta0 + Piecewise((eta1, x > W/2), (eta0, True)), keep the units of a viscosity. One helper does this for sums and for these functions. The message prints a constant as its number, and says to give a dimensionless quantity its units. This check also runs where an expression is set and at the solve, outside functions too, so a viscosity eta0 + T is refused when set. A sum made mismatched by a later reassignment is refused at the solve: get_units had swallowed the error inside a named expression's value. A sum of constants only is folded into one constant when it is set, on development too, so it never follows its parts.

  • The message names the fix.

    • For a coordinate, it names the coordinate and shows x/W, with an example W = uw.expression("W", uw.quantity(1000, "km"), "width").
    • For a power, it shows the power: 2**(... N.x/W ...).
    • Otherwise it points to a reference of the same dimension (T/T0, eta1/eta0, E/(R*T0)). A field's own coordinates do not count, so exp(T) is pointed to T/T0.

Tests

  • tests/test_0762_stokes_p1_on_simplices_refused.py, 9 tests.
    • Each refusal fails on development: Stokes, NavierStokes, VE_Stokes and Stokes_Constrained with a P1 velocity; degree=1 alone; a passed P1 velocity.
    • The allowed cases pass on both: Q1/P0 on quadrilaterals, P2/P0 on simplices, Darcy.
  • tests/test_0760_evaluate_units_contract.py, 42 new tests:
    • exp, log, sin and tanh of a viscosity;
    • erfc, asinh and atanh of one, which tests the rule;
    • 2**eta1;
    • refusal at the parameter setter;
    • a bare sin(pi*x) refused, with the message naming the coordinate and showing x/W;
    • three accepted arguments: eta1/eta0, E/(R*T0) and x/W;
    • from the parallel review, 11 more, each failing on the previous build (3960cfe):
      • a constant made dimensionless after a refusal is accepted;
      • a constant made dimensional after an acceptance is refused;
      • a length scale made a number after an acceptance is refused;
      • the cache is bounded;
      • atan2(y, x) is an angle, and atan2(y, eta1) is refused;
      • the annulus θ evaluates;
      • a bare coordinate in the body force is refused when set;
      • a bare coordinate in an Integral is refused when it is made;
      • a parameter whose inner value becomes dimensional is refused at the solve;
      • the hint for exp(T) names T/T0, not a coordinate;
      • the hint for 2**x shows the power;
    • from its second round, 7 more, and from the third, 4: T/T0 + k and beta*C - gamma*T/T0 evaluate to the hand value, eta0 + T is refused at the setter, and the message prints a negated constant as its number;
    • from the fourth review, 8:
      • a viscosity floor and cap, and a layer, set and solved;
      • exp(Max(T, T0)/T0 - 1) gives its value;
      • a Min of different dimensions is refused;
      • a dimensionless constant in three forms beside a length;
      • a sum made mismatched by a reassignment is refused at the solve;
    • the 7 from the second review: T/T0 - 1, E/(R T) - E/(R T0), T/T0 + x/W and E (1/T - 1/T0)/R are dimensionless arguments; the two normalised Arrhenius forms both evaluate to the hand value, 25.0722; and T + W is refused, naming both terms.
    • In a model with a temperature reference, E/R was not divided by it, so the activation term was 1000 times too large. That was fixed separately by A dimension with no reference has the SI base unit as its scale (E/R met the temperature reference) #1284, now in development. These tests use a model without a temperature reference.

Existing tests and examples that changed

  • Seven tests used a bare coordinate inside a function in a units model. They now divide by one model length, from the new tests/_units_helpers.model_length(), which is 1 without reference quantities. Every argument keeps its value, and no assertion changed.
    • test_1148_changing_timestep_keeps_the_snes: sin(pi*x);
    • test_0770_mesh_move_in_a_units_model: a Gaussian in r;
    • test_1057_ddt_transport_plugin: a Gaussian in x, y;
    • test_0033_adjoint_gradients_in_a_units_model and the parallel test_0035_adjoint_datum_sensitivity_parallel: sin(pi*x) in the body force, traction and misfit. The parallel file has no helper, so it writes the length as an expression of its reference;
    • test_0745_two_models_in_one_process and test_1131_rotated_nullspace_from_mesh's units-model box: sin(pi*x) in the body force.
  • test_1059_yield_stress_min_units read the evaluated viscosity as a bare model-unit number. That number came from Max dropping the units. It now reads Pa s and divides by eta_0, and its closed forms are unchanged.
  • test_0033 and the parallel test_0035 measured u_1*sin(pi*x/L) + u_0*y. That is a velocity plus a velocity times a length, now refused as a mismatched sum where the Integral is made. The second term is u_0*y/L, which has the same value.
  • docs/examples/tutorials/geographic/Ex_Geographic_Meshes.py subtracted the anomaly centre, a dimensionless quantity in model lengths, from the coordinates, and divided by a non-dimensional radius inside exp. The centre is now given its length (float(c) * L_0, with L_0 the 1000 km length reference), and the Gaussian divides by the dimensional radius. The run gives development's velocities: min -3.42e+02, max +2.09e+03, mean -1.14e+01, maximum upwelling at lon 140.6°, lat -33.6°, depth 230 km.
  • docs/examples/adjoint/fault_segments/fault_friction.py and .ipynb. These build their fault geometry and observation weights from x/D and y/D, with D the model depth as an expression.
  • Other docs: the units tutorials 14 and 15 and the thermal-convection units example already use dimensionless ratios or numpy on normalised arrays, so they are unchanged.
  • Ex_Stokes_Cartesian_SolNL.py built a P1 velocity with a P0 pressure on a simplex box. It is now P2/P1. A search of the other examples found no P1 velocity in a Stokes solver on simplices.

Regression runs

  • Serial: every tests/test_*.py except tier C, 6 xdist workers, on 179dfa2 (development 1e10c63 merged in). 4547 passed, 12 failed:
    • test_1059_yield_stress_min_units (9): it read the viscosity as a model-unit number that came from Max dropping its units. Changed (199955d), it gives 11 passed.
    • test_1086_mmpde_seam_matches_serial (3): its spawned runs timed out under load. Run alone on 199955d it gives 20 passed.
  • Parallel: scripts/test.sh --parallel-only --p 2 on 199955d: all passed.
  • Examples and tutorials, on deb68cb (before the merge of development) and on a development build: the beginner tutorials 3, 10, 11, 13, 14, 16 and 17; the geographic, unit-aware coordinates, dimensionality, scaling, Richards, annulus convection and sinker-transcript examples; the Taylor test. 16 files in all.
    • Every file has the same exit status on both builds.
    • The outputs differ only in paths, timestamps, roundoff at 1e-14, and one existing warning printing more often.
    • Tutorials 3 and 10 stop on both builds at the same line, for reasons outside this PR (UNFILED 40; an internal-primitive refusal).
  • Coverage: scripts/check_test_coverage.py passes.
  • Earlier rounds: on 28293ad, 4495 passed, plus test fixes; on 3960cfe, 4380 passed, 0 failed.

Checklist (UW3 Style Charter)

  • Followed the Style Charter over the surrounding code (S2)
  • No drive-by refactors (S9)
  • Regression tests written first, with level_* and tier_* markers (S8)
  • No hedging names, no commented-out code (S3, S4)
  • One sanctioned fallback, commented: units inference that cannot reduce an argument does not refuse (S4)
  • Parallel safety: the P1 refusal reads the agreed isSimplex; np 2 pass clean (S11)
  • No dependency changes
  • AI-assisted work carries the attribution line

Underworld development team with AI support from Claude Code

…onal argument to a transcendental function

- The Stokes base refuses a velocity of degree 1 on a simplex mesh, from
  degree=1 or a passed P1 velocity: P1/P0 locks and P1/P1 is unstable. The
  message points to degree=2 (P2/P1). Decided from the mesh's agreed isSimplex.
  Q1/P0 on quadrilaterals, P2/P0 on simplices and Darcy are unaffected.
  Approved by Louis as a change to solver behaviour.
- In a model with reference quantities, evaluate refuses exp, log, the
  trigonometric and hyperbolic functions and erf of an argument whose leaves,
  reduced together, carry a dimension, and a power with such an exponent:
  exp(eta1) is refused, exp(eta1/eta0) and exp(-E/(R*T0)) are not.

Underworld development team with AI support from Claude Code
Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings November 15, 2026 22:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@lmoresi

lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))

(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict: changes requested. The Stokes refusal is correct and safe across ranks. The transcendental refusal has one regression: a correctly dimensionless coordinate argument such as sin(pi*x/W) is now refused, and development accepts it and gives the right value. It also misses erfc and asinh, which the code base uses. Head reviewed: d2cfb8c.

Findings, by severity

1. A dimensionless coordinate argument is refused, and a bare coordinate is accepted (regression)

_reduces_to_a_dimension replaces every coordinate by 1 before it reduces units. That rule was written for _mixed_product, and it is wrong for the argument of a transcendental function. In a units model get_units(x) is kilometer, so x/L is dimensionless. After the replacement it becomes 1/L, which has a dimension.

Units model with length 30 km, a T field in K, dT = 100 K and W = L = 30 km as uw.expression quantities, evaluated at (0.5, 0.5):

expression development this PR
dT*sin(pi*x/W) 100 K (correct) refused: "sin of pi*N.x/W, which carries units"
eta0*exp(x/L) accepted refused
eta0*exp(x) accepted accepted (but x carries km)
dT*sin(pi*x) accepted accepted
dT*exp(-((x-x0)/W)**2) accepted accepted (get_units raises after the replacement; the fallback says "not dimensional")

The repository's own units-model tests write sin(pi*x) with coordinates in model units, so they still pass. The careful form, a coordinate divided by a length, is the one refused, and the message tells the user to do exactly that.

A possible fix: refuse a transcendental argument only when it is dimensional both as written and with coordinates replaced. That keeps the model-units coordinate convention (sin(pi*x)) and accepts x/L. It still refuses exp(eta1) and exp(eta1*x). Please add sin(pi*x/W) to test_dimensionless_arguments_are_accepted.

2. Functions the refusal does not cover

These are evaluated without complaint on a 1e21 Pa s argument:

  • erfc, erfi, loggamma;
  • asinh, acosh, atanh;
  • sec, csc, cot, acot.

Two of them are used in the code base:

  • erfc in analytic/richards.py, and in half-space cooling profiles generally;
  • asinh in the rate-and-state friction law in utilities/fault_contact.py, where the argument is a velocity ratio.

Testing against sympy's base classes would cover the families and future members: TrigonometricFunction, InverseTrigonometricFunction, HyperbolicFunction, InverseHyperbolicFunction, ExpBase and log, plus the error-function family. The fixed tuple misses them.

Not gaps:

  • atan2(eta1, 1) is refused, because sympy rewrites it to atan.
  • log(eta1, 10) is refused.
  • sqrt is accepted, which is correct.
  • Heaviside, Piecewise, Min and Max are not transcendental. A Piecewise branch containing exp(eta1) is found and refused.

Unrelated to this PR, and present on development too: evaluate(Max(eta1, eta0)) returns 1.0, the non-dimensional value, with no units, and Min returns 0.001. That is worth a separate issue.

3. The refusal applies at evaluate only, not in solvers

With shear_viscosity_0 = eta0*exp(eta1) in a units model, Stokes.solve() is not refused. It runs, diverges (DIVERGED_LINE_SEARCH, reason -6), and only warns. The commit message scopes the check to evaluate, which matches what the code does, but the PR summary reads as if any units model refuses these. Please say "evaluate and global_evaluate refuse" in the summary, or open a follow-up for the solver path. Constitutive laws are where Arrhenius factors are usually written.

4. The Stokes refusal comes after the default fields are created (low)

With Stokes(mesh, degree=1) on a simplex mesh, V{i} and P{i} are created and registered on the mesh, and only then is the construction refused. After a caught refusal the mesh is left holding V6 and P6, as observed. All ranks create the fields, so this is not a hang risk. Still, the check can move above the creation block:

u_degree = velocityField.degree if velocityField is not None else degree
if self.mesh.isSimplex and u_degree == 1:
    raise ValueError(...)

5. The #844 message points to a refused case (low)

Stokes(mesh, velocityField=v_P1) on triangles, with the default degree, is refused by the #844 check with "Pass degree=1, or pass both fields". Both of those are now refused too. On a simplex mesh that message should point to a P2 velocity.

6. Cost (informational)

The new walk runs on every evaluate in a units model whose expression has dimensional leaves, and nothing is cached. On a valid expression of 40 terms, each with an Arrhenius exp and several powers:

  • the whole pre-check takes 126 ms, against 15 ms on development;
  • _dimensional_function_argument alone takes 116 ms;
  • the evaluate itself takes 8.4 s.

The added cost is about 1.4 % here. It is acceptable, but it grows with expression size, because each node calls atoms().

Confirmed correct

  • Agreement across ranks. mesh.isSimplex is all-gathered at mesh construction from the ranks that hold cells. On a triangle mesh with an empty rank (the right_triangle_of_cells fixture), the empty rank reports dm.isSimplex() == False and mesh.isSimplex == True:

    • at np 2, cells per rank are [0, 1];
    • at np 3, cells per rank are [8, 8, 0].

    Every rank raises the refusal, for both degree=1 and a passed P1 velocity, and an allreduce placed after the refusal completes. On development no rank raises, so the probe's two refusal cases fail there.

  • Order. The check runs in SNES_Stokes_SaddlePt.__init__, before any solver DM, section or SNES is built.

  • Routes. Stokes, VE_Stokes, Stokes_Constrained and NavierStokes all pass through the base, and the Eulerian composed Navier-Stokes inherits from SNES_Stokes. Swapping the velocity after construction (stokes.Unknowns.u = p1) is not a working route on development either: it fails at solve with a shape error.

  • Allowed cases. These are not refused:

    • Q1/P0 on quadrilaterals, by degree=1 or by passed fields, including with an empty rank;
    • P2/P0 and P2/P1 on simplices;
    • SteadyStateDarcy and TransientDarcy with a P1 flux.
  • Existing uses. An AST scan of tests/, docs/ (notebooks included) and src/ found no Stokes-family solver built with a P1 velocity on a simplex mesh, apart from the converted example. Every candidate hit was on a quadrilateral mesh, or was a Darcy or advection-diffusion velocity. Internal Stokes builders, such as the free-surface derived solves, use P2.

  • Detection. Detection is correct for:

    • nested and aliased uw.expressions, including exp inside a named expression;
    • mesh variables with units: exp(T) is refused, while exp(T/T0), exp((T-T0)/T0) and eta0*exp(-E/(R*T)) are accepted;
    • matrices, Piecewise and global_evaluate;
    • dimensional exponents: 2**eta1 is refused, while (eta1/eta0)**n and eta1**(eta1/eta0) are accepted.

    A bare uw.quantity cannot be placed inside a sympy function at all (SympifyError). With no reference quantities the check is off, as intended: exp(eta1) evaluates to inf without complaint.

  • Example. In the P2/P1 Ex_Stokes_Cartesian_SolNL, both solves converge. The script then fails at line 161 (stokes.u.sym - sol_vel.T, Matrix size mismatch (1, 2) + (2, 1)), and fails the same way on development. That failure is pre-existing; a one-line .T fix could ride along.

What was run

Serial runs were pinned to 8 cores; pytest -s -rA, or -n 8 for the large set.

  • New tests on this PR: test_0762_stokes_p1_on_simplices_refused.py and test_0760_evaluate_units_contract.py, 45 passed. The 15 new tests are among them.
  • New tests on development (one commit range ahead of the PR base, which already contains Units contract: evaluate refuses mixed units and far points; Stokes fields carry units (#771, #904, #881, #786, #844, #1001) #1182):
    • all 11 refusal tests fail, as the PR claims;
    • the 4 acceptance tests pass there too, as expected: Q1 on quads, P2/P0, Darcy, and dimensionless arguments.
  • Neighbouring tests: 149 files covering units, evaluate, Stokes, VE, Navier-Stokes, Darcy and constrained solvers, with a 400 s per-test limit.
    • This PR: 1207 passed, 2 failed, 13 skipped, 17 xfailed.
    • Development: the same counts, with the same 2 failures (test_1064_constrained_spherical_shell_response::test_default_constrained_matches_zhong_velocity_response and test_1081_objective_step_sphere::test_a_rigid_rotation_of_the_sphere_carries_the_stress_rigidly, PETSc error 101 in a 3D solve). They are not caused by this PR.
  • Parallel, under the MPI supervisor with a 300 s silence limit:
    • test_0762 at np 2: 9 passed.
    • The reviewer's empty-rank probe at np 2 and np 3 passed 4 of 4 on this PR, and 2 of 4 on development, where the refusal is absent. The probe covers:
      • P1 refused on every rank, by degree=1 and by a passed velocity;
      • P2 built;
      • Q1 on quads built with an empty rank.
  • Probes: reviewer scripts for the transcendental cases, the cost timings and the Stokes routes, run on both builds. Logs are kept by the reviewer.

Not run

  • test_0762 at np 3, which the empty-rank probe covers instead.
  • 3D simplex meshes.
  • evaluate refusals in parallel.
  • The full test suite.
  • Examples other than SolNL.

Underworld development team with AI support from Claude Code

…y rule, refused at the setter too (H1's review of #1197)

- Coordinates keep their length in a function argument's reduction, so
  sin(pi*x/W) and exp(x/L) are dimensionless and accepted.
- Every applied sympy function needs a dimensionless argument (erfc, asinh,
  atanh, …), except a short list that passes units through (Abs, Min, Max,
  Piecewise, sign, Heaviside, …) and a field's own function; a power keeps the
  exponent rule.
- The check runs where a parameter is set, as well as at evaluate, so a
  viscosity of eta0*exp(eta1) is refused before a solve runs with it.
- The verdict is cached per expression.
- The P1 refusal comes before any field is created, and before the #844
  degree messages, so a P1 velocity is pointed to degree=2.

Underworld development team with AI support from Claude Code
…e fix

Following the ruling that a coordinate inside exp, sin or log is refused in
a model with reference quantities, the refusal now names the coordinate and
shows the fix: divide it by a length, e.g. sin(pi*x/W) with W an expression
in km. A dimensional argument without a coordinate is pointed to a reference
of the same dimension.

Three tests that wrote sin(pi*x) or exp(-x**2) in a units model now divide
by one model length, from the new tests/_units_helpers.model_length(), which
returns 1 without reference quantities. The fault_friction example (.py and
notebook) builds its fault geometry and observation weights from x/D and
y/D, with D the model depth as an expression. The units tutorials 14 and 15
and the thermal-convection units example already use dimensionless ratios.

Underworld development team with AI support from Claude Code
…e shows the fix

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict at cca957b: changes requested. The coordinate-length rule follows the ruling, and the function coverage is complete. The P1 refusal is correct and collective, and the cost is small. What blocks the merge is the cache: the verdict is cached per expression, so it goes stale when a named expression's value is reassigned. It then refuses an expression that is now dimensionless and accepts one that is now dimensional. Two medium findings and two lows follow.

The PR was built fresh from cca957b (the .pyx changed), and the compiled modules have fresh mtimes. The baseline is development at the merge base, 4ab522a, run from an existing build of that commit whose installed sources match it exactly.

Against the earlier review

earlier finding status at cca957b evidence
1. sin(pi*x/W) refused fixed accepted with value 1.0, as is exp(x/L) (1.64872) and exp(-((x-x0)/W)**2) (1.0); sin(pi*x), exp(x) and exp(-(x-0.5)**2) are refused, and the message names N.x and shows N.x/W
2. missing functions fixed erfc, erfi, asinh, acosh, atanh, sec, csc, cot and loggamma of a dimensional argument are all refused, and so are erf, exp, log, sinh, cosh, tanh, asin, atan and gamma; Abs, Min, Max, Piecewise, sign, Heaviside and floor are not refused
3. check at evaluate only partly fixed constitutive parameter setters now refuse, on every rank at np 2 and 3 and with an empty rank; bodyforce and Integral are still not checked (finding 3)
4a. fields created before the P1 refusal fixed mesh.vars is empty after Stokes(mesh, degree=1) is refused, at np 2 and 3 and with an empty rank at np 2 and 3; every rank refuses
4b. the #844 message fixed a P1 velocity on simplices now gets the P1/P0 message, which points to degree=2; test_0760 was updated to match
4c. cost fixed the check alone takes 0.046 s on the first call and 0.01 ms cached, for a 40-term Arrhenius sum; the whole evaluate (500 points) takes 5.42 s on the first call and 5.35 s on repeats on the PR, against 5.39 s and 5.32 to 5.37 s on development

Without reference quantities, all 52 probe cases give the same values on the PR as on development: nothing new is refused. With units on mesh variables, exp(T) is refused and exp(T/T0) is accepted, as required.

Findings

  1. High: the cached verdict goes stale when a named expression's value is reassigned, in both directions.

    _function_argument_cache is keyed by the expression. A UWexpression keeps its identity when its .sym is reassigned, so the cached verdict outlives the value it was computed from. Live reassignment is how parameters are normally changed between solves. The failure cases, in a units model:

    • eta4 = uw.expression(..., uw.quantity(1e21, "Pa*s")). evaluate(exp(eta4)) is refused, correctly. Then set eta4.sym = 0.5: the same exp(eta4) is still refused, with the message "exp of 0.500000000000000, which carries units". A new top-level expression, 2*exp(eta4), is accepted.
    • eta5 = uw.expression(..., 0.5). exp(eta5) is accepted, correctly. Then set eta5.sym = uw.quantity(1e21, "Pa*s"): exp(eta5) is still accepted, and evaluates to 1.0010005, the very exp(eta1) the PR exists to refuse. 2*exp(eta5) is refused.
    • exp(x/W2) with W2 = 30 km is accepted. After W2.sym = 2.0, it is still accepted. A fresh exp(x/W3) with W3 = 2.0 is refused.

    The setter goes through the same cache, so it has the same staleness. Development has no cache, so it has no staleness.

    Suggested fix, any one of:

    • key the cache on the expression with its named expressions unwrapped to their current values;
    • fold a per-UWexpression version, bumped by the sym setter, into the key;
    • cache only the walk that collects arguments, and reduce their units on each call. On a cache miss the whole check costs 0.046 s for a 40-term sum.

    A test should reassign a named expression in each direction after a first evaluate.

  2. Medium: atan2 of two lengths is refused, and so is the library's own angular coordinate.

    atan2(y, x) is the angle of a ratio and is dimensionless whenever both arguments share a dimension. The rule treats each argument separately, so in a units model:

    • evaluate(sympy.atan2(y, x)) is refused;
    • evaluate(ann.CoordinateSystem.R[1]) on an Annulus is refused. This is the library's θ, Piecewise((0, x == 0), (atan2(y, x), True)).

    On development both evaluate to 0.7854 and 0.13255. The message tells the user to divide N.y by a length, which they cannot do inside mesh.CoordinateSystem.R or xR. The cylindrical, spherical and geographic systems build θ or longitude the same way (coordinates.py, at about lines 1504, 1532, 1579, 1686 and 1696). Examples evaluate CoordinateSystem.xR[1] (AnnulusFS.py), though not in a units model today. unit_e_0 and rRotN still evaluate, because sympy reduces cos(atan2(y, x)) to x/sqrt(x**2 + y**2).

    Suggested fix: for atan2 (and any other function of a ratio), require its two arguments to share a dimension, rather than each to be dimensionless.

  3. Medium: bodyforce and Integral still accept a bare coordinate inside a function.

    The setter check sits in ExpressionDescriptor, which covers constitutive parameters only. In a units model:

    • stokes.bodyforce = Matrix([0, f*sin(pi*x)]), with f in Pa/m, is accepted, and stokes.solve() runs.
    • uw.maths.Integral(mesh, sympy.sin(sympy.pi*x)).evaluate() returns 0.6366 km². The argument is read as the non-dimensional x, the same as on development.

    So sin(pi*x) is refused at evaluate but solved with and integrated. There is a related gap: a parameter that was dimensionless when it was set is not checked again after its inner value changes. For example, set shear_viscosity_0 = eta0*exp(k) with k = 0.5, then k.sym = 1e21 Pa s. The parameter holds exp(k) unrefused until something evaluates it. Please either cover the solver's other inputs (body force, F0 and F1 terms, boundary values, Integral), or say in the PR and the docs that the guarantee is for evaluate and constitutive parameters.

  4. Low: the refusal message gives a wrong hint in two cases.

    • For exp(T), with T a mesh variable in K, the message says "The coordinate N.x, N.y is a length here. Divide it by one". The coordinates are the arguments of T's own function, not the problem; the fix is T/T0. The coordinate hint should look only at coordinates outside mesh-variable functions.
    • For 2**x the message reads "write a power with exponent(... N.x/W ...)".
  5. Low: the cache is unbounded. 2000 calls on 2000 distinct expressions (a constant changing per step) left 2006 entries. Each entry holds its expression, and with it the named expressions and meshes that expression refers to. A bounded LRU, or the fix to finding 1, would remove this.

Confirmed correct

  • Coordinate rule as tabulated above. x, x**2, sqrt(x**2+y**2), 2**(x/W), dT/dx and exp(dT/dx*W/T0) are accepted, and 2**x is refused.
  • The setter at np 2 and 3, and with an empty rank at np 2 and 3. On every rank, shear_viscosity_0 = eta0*exp(eta1) and eta0*exp(y) are refused, and eta0*exp(-eta1/eta0) is accepted. Development accepts all three.
  • The P1 refusal. Stokes(mesh, degree=1) and Stokes(mesh, velocityField=P1) are refused before any field is created (mesh.vars is empty after the first), on every rank, including the ranks with no cells. Development created V and P for degree=1.
  • Converted tests. test_1148, test_0770 and test_1057 divide by model_length(). That is one model length in a units model and 1 without, so every argument has its old value and no assertion changed. All three pass. They test what they did.
  • fault_friction.py (the PR's version) runs past the converted geometry and stops at line 244, shear_viscosity_0 = eta_0 (the bare-number refusal), on both the PR and development, as the PR describes.

What was run

  • Probes, serially, on the PR and development, with and without reference quantities:
    • the rule probe: coordinates, mesh variables with units, 18 functions, the unit-passing list, atan2 and the annulus coordinates;
    • the cache probe;
    • the entry-point probe: Integral, body force and solve;
    • the 40-term Arrhenius cost probe.
  • Setter and P1 probe: np 2 and np 3, plus np 2 and np 3 with an empty rank; development at np 2.
  • Serial slice, PR, 79 files: every test file whose name matches units, evaluate or Stokes, plus test_0760, 0762, 1148 and 1057. Result: 647 passed, 7 skipped, 12 xfailed, 0 failed.
  • test_0762 at np 2, PR: 9 passed on each rank.
  • test_0760 at np 2: hangs on both the PR and development (a rank-local evaluate with the point on one rank: ranks end up in different collectives). It is a serial file, so this is not a finding against the PR, and np 2 results for it are not meaningful.
  • New tests on development: 16 fail (10 in test_0760, 6 in test_0762), and 35 pass, as expected.

Not run:

  • the full serial and parallel suites;
  • test_0760 in parallel (see above);
  • anything above np 3.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…very solve

H1's review of #1197 at cca957b:

- The verdict was cached per expression, and a named expression keeps its
  identity when its value is reassigned, so the verdict went stale both ways.
  The walk now runs on every call; only the units reduction of each argument
  is cached, keyed on the argument and the current value and units of every
  named expression in it, in a bounded LRU (512).
- atan2 is a function of a ratio: its two arguments must share a dimension.
  The library's polar, spherical and geographic angles are built from it.
- The body force is checked when set, and every Integral, CellWiseIntegral
  and BdIntegral when made. Every solve checks the solver's inputs (body
  force, source, boundary values, constitutive parameters), so a value
  reassigned inside an expression after it was set is caught too.
- The coordinate hint looks only at coordinates outside a field's own
  function (exp(T) points to T/T0), and a power's hint shows the power.

Underworld development team with AI support from Claude Code
The body force is now checked when set and at every solve, so four tests that
wrote sin(pi*x) in a units model were refused: test_0033, test_0745,
test_1131's units-model box and the parallel test_0035. Each divides by one
model length (model_length(), or an expression of the reference length in
the parallel file), so every argument keeps its value and no assertion moves.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Recheck at 883f1c5: changes requested. Every finding of the previous review is fixed, and each fix was confirmed with the earlier probes. One new problem blocks the merge, found while building the Arrhenius cost case. When a sum contains a mesh variable's dimensionless ratio, the argument's units come out as kelvin. The new refusal then rejects standard dimensionless forms: exp(T/T0 - 1), and exp(E/(R*T) - E/(R*T0)), the usual normalised Arrhenius law. This happens at evaluate, at the parameter setter and at every solve.

The .pyx and a header changed, so the PR was rebuilt at 883f1c5. The .pyx files that include the header were touched first, and all compiled modules have fresh mtimes. The baseline is development at the new merge base, 246d6ce. The probes were run with that commit's .py files laid over a build whose compiled sources match it; that overlay was diffed against the source tree and matches exactly.

Against the previous review (cca957b)

finding status at 883f1c5 evidence
1. High: stale cached verdict fixed exp(eta4): refused at 1e21 Pa s, accepted (1.6487) after eta4.sym = 0.5, refused again after it is set back. exp(eta5): accepted at 0.5, refused at 1e21 Pa s, accepted again at 0.5. exp(x/W2): accepted at 30 km, refused at plain 2.0, accepted at 60 km (1.2840). Through the setter, eta0*exp(eta6) is refused, then accepted after eta6.sym = 0.5; eta0*exp(eta7) is accepted at 0.5, then refused at 1e21 Pa s
2. Medium: atan2 and the library θ fixed atan2(y, x) gives 0.785398, atan2(y/W, x/W) gives 0.785398, and the annulus CoordinateSystem.R[1] and xR[1] give 0.132552, all identical to development; atan2(y, t), with y a length and t a time, is refused
3. Medium: bodyforce and integrals fixed bodyforce = [0, f*sin(pi*x)] is refused at the setter, and f*sin(pi*x/W) is accepted. Integral, CellWiseIntegral and BdIntegral each refuse sin(pi*x) and accept sin(pi*x/W), with values identical to development (0.636620; 0.033442 and 0.033212 in the first cells; 0.636620 over Top)
3b. a parameter's inner value reassigned after it was set fixed Set shear_viscosity_0 = eta0*exp(k) with k = 0.5; the solve runs. Reassign k to 1e21 Pa s: the next solve is refused. Set it back to 0.5: the solve runs. The same holds for W inside the body force reassigned to a plain 3.0. Every rank agrees at np 2 and np 3, and at np 3 with an empty rank (cells 20 / 22 / 0)
4. Low: hints fixed exp(T) now suggests "T/T0, eta1/eta0, E/(R*T0)", and no longer mentions coordinates. 2**x now reads "a power whose exponent is N.x ... write 2**(... N.x/W ...)"
5. Low: unbounded cache fixed 2000 distinct expressions leave exactly 512 entries

Findings

  1. High: a sum that holds a mesh variable's dimensionless ratio is read as kelvin, so standard dimensionless arguments are refused.

    get_units returns kelvin for sums such as T/T0 - 1, E/(R*T) - E/(R*T0), e1/e0 - T/T0 and T/T0 + x/W, with T a mesh variable in K and T0 an expression in K. Each term of each sum is dimensionless; get_units(E/(R*T)) on its own gives "dimensionless". The same sums without a mesh variable read correctly: T1/T0 - 1 with two constants, and x/W - 0.5. The PR's _reduces_to_a_dimension therefore treats these arguments as dimensional, and refuses:

    • evaluate(exp(E/(R*T) - E/(R*T0))). Development evaluates it.
    • shear_viscosity_0 = eta0 * sum_k exp(E_k/(R*T) - E_k/(R*T0)) at the setter, with the message "exp of E/(RT) - E/(RT0), which carries units".
    • The same at every solve, because the solve now checks again.

    exp(E*(1/T - 1/T0)/R) is accepted, so the refusal depends on how the user writes an identical, dimensionless argument.

    The fault is in get_units' handling of a sum and is already present on development. On development it only mislabels a result; this PR turns it into a refusal. Suggested fix:

    • in _reduces_to_a_dimension, judge an Add term by term (dimensionless when every term is); or fix the units of a sum in get_units;
    • add a test for exp(T/T0 - 1) and exp(E/(R*T) - E/(R*T0)) with T a mesh variable with units.
  2. Low: the check at every solve costs about 32 ms for a 40-term viscosity.

    The walk over the solver's inputs is repeated at every solve, by design, so a reassigned value is caught. On a Stokes solve with a 40-term Arrhenius-style viscosity (written in an accepted form), the check alone takes 31.5 to 31.8 ms. A repeat solve takes 0.057 s on the PR against 0.024 s on development; the first solve takes 7.50 s against 7.42 s. That is negligible against real solves, but it doubles the cost of a small repeated solve. A cheap fingerprint of the named-expression state, checked first, would avoid redoing an unchanged walk.

Noted, not from this PR: on both development and the PR, that viscosity evaluates to NaN in this units model (exp(A*T0/T)*exp(-A), with A = E/(R*T0) as a named expression). It deserves its own issue. It does not affect the timing above, which compares like with like.

The converted tests

The seven conversions across test_0033, test_0745, test_1131 and the parallel test_0035 change three kinds of input: body forces, a natural boundary value, and misfits. Each divides by model_length(), or, in test_0035, by a 30 km expression equal to that file's reference length. So every argument keeps its value, and no assertion or tolerance changed. All of them pass: the serial three in the slice below, and test_0035 at np 2.

What was run

  • Probes, serial, PR and development:
    • cache freshness through evaluate and the setter;
    • the 512 bound;
    • atan2 and the annulus coordinates;
    • the body force and the three integrals;
    • the hints;
    • the sum-units probe;
    • the 40-term solve cost.
  • Solve-time refusal: np 2, np 3, and np 3 with an empty rank.
  • Serial slice, PR, 82 files: every test file whose name matches units, evaluate or Stokes, plus test_0760, 0762, 1148, 1057, 0033, 0745 and 1131. Result: 696 passed, 7 skipped, 12 xfailed, 0 failed.
  • np 2, PR: test_0762 and the parallel test_0035: 13 passed on each rank.
  • New tests on development: test_0760 and test_0762 give 26 failed and 36 passed, as expected.

Not run:

  • the full suites;
  • anything above np 3.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…hes refused

H1's review of #1197 at 883f1c5. compute_expression_units returned None
("unknown") for a sum of dimensionless terms, and get_units then took the
units of the first field in it: T/T0 - 1, E/(R*T) - E/(R*T0) and T/T0 + x/W
came back in kelvin, so the normalised Arrhenius factor was refused while
E*(1/T - 1/T0)/R was accepted. A sum now has the dimension its terms share,
a sum of dimensionless terms is dimensionless, a plain number may sit beside
a dimensional term, and terms of different dimensions raise
MismatchedSumError naming them. A product with no dimensional factor and a
factor of unknown units (2*u, u a field without units) is unknown, not
dimensionless; the old sum rule hid that.

The whole verdict of the function-argument check is cached on the expression
and the state of its named expressions: a repeat solve with a 40-term
viscosity pays 1.2 ms for it.

Underworld development team with AI support from Claude Code
The first fix also changed two answers the tests rely on: a field without
units reads as a pure number (test_0850's T/x), and a sum of such terms has
no units (test_0851's strain rate of a unitless velocity, test_0760's plain
viscoplastic stress). A dimensionless term now counts only when it carries
units that cancel (a field or named expression with units, a coordinate), so
those keep their development answers, and the product rule is as it was.
T/T0 - 1, E/(R*T) - E/(R*T0) and T/T0 + x/W are still dimensionless, and two
terms that carry units of different dimensions are still refused.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Second recheck at 7355f46: changes requested. The sum fix works when every term of the sum carries units. T/T0 - 1, E/(R*T) - E/(R*T0), e1/e0 - T/T0 and T/T0 + x/W are now dimensionless. They are accepted at evaluate, at the setter and at the solve, on every rank. Two new false refusals block the merge:

  • A sum that also holds a plain named parameter, or a field without units, is still read as kelvin and refused: exp(T/T0 + k) and exp(beta*C - gamma*T/T0). Development evaluates both correctly.
  • The geographic tutorial in the docs now stops with MismatchedSumError. It runs on development and gives the intended value there.

The PR's own compiled sources are unchanged since 883f1c5. The merge of development brought in a changed .pyx, so the PR was built fresh at 7355f46; all compiled modules have fresh mtimes. The baseline is development at the new merge base, acc2cba. Its .py files were laid over a build whose compiled sources match acc2cba exactly, and the overlay was diffed against the source tree. Every run printed which underworld3 it loaded.

Against the previous recheck (883f1c5)

finding status at 7355f46 evidence
1. High: a sum holding a field's dimensionless ratio read as kelvin fixed for sums whose every term carries units; not fixed otherwise (new finding 1) get_units now gives "dimensionless" for T/T0 - 1, E/(R*T) - E/(R*T0), e1/e0 - T/T0, T/T0 + x/W, Tc/T0 - 1 (Tc in degC) and (D + W)/W (D a field in m, W in km). All five are accepted at evaluate. eta0*exp(T/T0 - 1), eta0*exp(E/(R*T) - E/(R*T0)) and eta0*exp(T/T0 + x/W - 1) pass the setter and the solve. That holds at np 2, at np 3, and at np 3 with an empty rank (cells 20 / 22 / 0)
Arrhenius, both forms, against the hand value as claimed without a temperature reference With no temperature reference, exp(E/(R*T) - E/(R*T0)) and exp(E*(1/T - 1/T0)/R) agree with exp(E/R*(1/1200 - 1/1000)) to 3e-14 for three values of E, on the PR and on development. With a 1000 K temperature reference, both builds give NaN. The argument comes out as -2004.65 instead of -2.00465, even with constants only. This is the 1000x defect the author has listed for a separate PR
2. Low: per-solve check cost improved, but 1.2 ms not reproduced here Same 40-term probe as before. The check alone takes 5.1 to 6.8 ms (was 31.5 to 31.8). A repeat solve takes 0.038 to 0.041 s, against 0.025 to 0.026 s on development. When a named value inside the viscosity changes before each solve, as a time-dependent parameter would, the check takes 24 to 26 ms. A profile shows the time goes to building the cache key: atoms() walks, plus the string form of each named expression's units
NaN in exp(A*T0/T)*exp(-A) unchanged, on both the same 1000x defect as above
earlier fixes (stale cache, atan2 and θ, body force and integrals, a parameter's inner value reassigned, hints, the 512 bound) still hold The recheck probe gives output identical to its run at 883f1c5. The reassignment probe at np 3 with an empty rank gives the same five verdicts on every rank

Examples and docs that build a units model

Every notebook and script under docs/ that uses uw.quantity, set_reference_quantities, units= or uw.scaling.units was run. (The tree has no top-level examples/ directory.) Each ran on both builds from a copy in a scratch directory, with a 900 s cap. Notebooks were converted with jupyter nbconvert --to script. Three edits were made in the copies only:

  • a %%timeit cell in tutorial 12 became the plain statement;
  • display was imported in tutorial 14;
  • the sinker target file was generated before the two Taylor-test scripts.

The fault_friction notebook is paired with its .py, with identical code, so it was run once. "Unit sums reached" counts the sums carrying units that get_units saw during the run (from an instrumented copy).

file unit sums reached development PR
beginner/tutorials/12-Units_System yes (2) fails, line 240: pint meter to kelvin same failure, same line
beginner/tutorials/13-Scaling-problems-with-physical-units no runs runs, same output
beginner/tutorials/14-Timestepping-with-physical-units yes (32 to 34) runs runs, same output
beginner/tutorials/15-Thermal-convection-with-units no fails, line 129: pint kilometer to dimensionless same
beginner/tutorials/16-Richards-Equation-Groundwater no runs runs, same output
examples/adjoint/fault_segments/fault_friction (.py and .ipynb) no fails, line 242: bare-number viscosity in a units model same failure (line 244); the PR's edited lines before it run
examples/adjoint/sinker_transcript/forward_sinker_transcript no runs runs, same output
examples/adjoint/sinker_transcript/taylor_test_library no runs runs; Taylor ratios identical
examples/adjoint/sinker_transcript/taylor_test_transcript no fails, line 39: plain array into a units field same
examples/convection/intermediate/Ex_Convection_Annulus_Recorded no runs runs; dt agrees to 4e-15 relative
examples/Dimensionality-Demo no runs runs, same output
examples/example_unit_aware_coordinates no runs runs, same output
examples/free_surface/advanced/AnnulusFS no fails, line 109: mesh file reader same
examples/tutorials/geographic/Ex_Geographic_Meshes yes (6) runs fails, line 236: MismatchedSumError (new finding 2)
examples/Tutorial_Thermal_Convection_Units no fails, line 254: bare-number viscosity same
examples/WIP/Benchmark/Ex_Richards_Tracy_Benchmark no runs runs, same output
examples/WIP/Benchmark/Ex_VP_Spiegelman_Benchmark no timed out at 900 s (default size, and at -uw_problem_size 1) timed out the same way; the first four nonlinear solves converge with identical iteration counts
examples/WIP/Geographical/Mesh-Adapted-2-Faults no fails: missing project_variables module same
examples/WIP/Geographical/Step4-FaultFlowWorkflow no fails, line 249: mesh.adapt changed meaning same
examples/fluid_mechanics/intermediate/Ex_stokes_sinkingBlock_benchmark no fails, line 245: PETSc error 56 same
examples/fluid_mechanics/intermediate/shear_box_2d_fault no fails, line 252: no parameter eta_0 same
examples/fluid_mechanics/intermediate/shear_box_2d_fault_adaptive no fails: no metric remesher in this PETSc same
examples/fluid_mechanics/intermediate/shear_box_3d_fault_adaptive no fails: no metric remesher same
examples/porous_flow/advanced/Ex_viscousFingering no fails, line 211: swarm recycling not implemented same
examples/utilities/basic/Ex_scaling no runs runs, same output
examples/fluid_mechanics/advanced/Ex_Stokes_Cartesian_SolNL (no units; edited by the PR) no fails, line 159: matrix shape mismatch same failure (line 161)

One new refusal, in the geographic tutorial. Fourteen files already fail on development, for reasons unrelated to this PR, and fail at the same statement on the PR. The Spiegelman benchmark times out on both. Those files exercise only the code before their failure point.

Findings

  1. High: a sum that holds a plain named parameter, or a field without units, beside a dimensionless ratio is still read as kelvin, so it is refused.

    With k = uw.expression("k", 0.5), beta and gamma plain named expressions, and C a composition field without units:

    • refused at evaluate: exp(T/T0 + k), exp(k*T/T0 - k), exp(C + T/T0), exp(2*C - 3*T/T0), exp(beta*C - gamma*T/T0), exp(beta*C - gamma*(T/T0 - 1)). get_units gives kelvin for each argument;
    • refused at the setter: eta0*exp(beta*C - gamma*T/T0) and eta0*exp(C + T/T0);
    • every rank agrees at np 3 with an empty rank.

    Development evaluates all six to the hand value, for example exp(0.6 - 3.6) = 0.0497871, and solves with both viscosities. The same argument with a literal number is accepted: exp(T/T0 + 0.5). So is a product with the composition field: exp(C*T/T0).

    The cause is the old fallback. A term that carries no units is "unknown". A sum with an unknown term and no dimensional term returns None. get_units then takes the units of the first field in the sum, which is kelvin. Composition-dependent and parameterised Arrhenius laws are written exactly this way, so this blocks the merge as the previous High did. Suggested fix:

    • when no term of a sum has a dimension, return dimensionless rather than None, unless a term is a field without units in a position the existing "fields without units beside factors with units" guard already refuses;
    • or stop get_units falling back to a field's units for an Add;
    • add tests for exp(T/T0 + k) and exp(beta*C - gamma*T/T0).
  2. High: the geographic tutorial in the docs is newly refused.

    docs/examples/tutorials/geographic/Ex_Geographic_Meshes.py, line 236, sets the body force. It builds (x - geo_center[0])**2 + ..., where geo_center comes from geo.to_cartesian(..., uw.non_dimensionalise(depth)). Each entry is a dimensionless UWQuantity, a position in model lengths. The PR raises "N.x is in kilometer and --3.9278552708377266 is in no units (a pure number)".

    On development, at the first node, x - geo_center[0] gives 369390 m: the centre is read in model lengths of 1000 km, which is what the tutorial means. The PR accepts x - float(geo_center[0]) with that same value. So a dimensionless quantity is refused where a bare number of the same value passes. That contradicts the PR's own rule that a plain number may sit beside a dimensional term. Either:

    • treat a dimensionless quantity beside a dimensional term as the plain number it is; or
    • if the refusal is meant, update the tutorial in this PR and say in the message how to write it.
  3. Medium: a mismatched sum outside a function is not refused at the setter or the solve.

    shear_viscosity_0 = eta0 + T (Pa s plus K) is accepted, and the solve runs, on the PR as on development. MismatchedSumError fires only where get_units walks the sum: at evaluate, and inside the argument of a transcendental function. At evaluate it is consistent: T + W, T + x, T/T0 + T, e1 + T and D + T all raise it on every rank at np 2 and np 3, and each message names both terms. This is not a regression, but the PR description says mismatched sums raise. Either check each solver input's sum, or say where the check applies.

  4. Low: the per-solve check costs 5 to 7 ms here, not the 1.2 ms quoted.

    See the table. This is a large improvement on 32 ms. The rest is spent building the cache key on every call: the walk over named expressions, and the formatting of each one's units. Caching the units string on the expression, or keying on a version counter bumped by the .sym setter, would remove most of it.

  5. Low: the mismatch message prints a negated number as "--3.9278552708377266". It should read "-(-3.93...)", or the term's value.

Also noted, on both builds and not changed by this PR:

  • T - 1, with T a field in K, reads the 1 as one reference temperature: at T = 1200 K it gives 200 K. The PR keeps this, and refuses exp(T - 1).
  • exp(C + x/W) is refused on both by the existing guard against a field without units beside factors with units.
  • On both builds, the plain value of U + T/T0, with U a field without units, is labelled kelvin and comes out 1000 times too large. The PR fixes the related U*T/T0 - 1: it gives -0.64 dimensionless, where development gives -640 K.

Unitless models

A probe with no reference quantities evaluates 14 expressions: sums, transcendental functions of sums, and atan2. It then runs a Stokes solve with the viscosity exp(E/T - E) + C. get_units results, values and the solve's maxima are identical on the PR and development.

The new tests

The six new tests in test_0760, plus the new bound assertion, pass on the PR. Run against development:

  • five fail: three of the four sum forms, the mismatch test, and the bound test (the cache does not exist there);
  • two pass, because development never refused them: the product form E (1/T - 1/T0)/R, and the test that the two Arrhenius forms are equal.

The new tests use no temperature reference, so they pass around the 1000x defect.

What was run

  • Probes, serial, PR and development:
    • units of 33 sums: matched, mismatched, plain numbers, compatible units (km and m, degC and K), fields without units;
    • Arrhenius, both forms, with and without a temperature reference, against the hand value;
    • fields without units and plain parameters inside exp: evaluate, setter, solve;
    • the geographic tutorial's sum;
    • a unitless model;
    • the 40-term cost, with a profile on the PR;
    • the recheck probe of the earlier fixes.
  • Parallel, PR:
    • the units-of-sums probe at np 2 and np 3: every result line is identical on every rank;
    • the setter and solve probe at np 2 and np 3, and at np 3 with an empty rank: identical verdicts on every rank (the empty rank also prints a probe-side message on an empty array);
    • the probe of fields without units at np 3 with an empty rank;
    • the earlier reassignment probe at np 3 with an empty rank. The setter and solve probe was also run on development at np 2.
  • Examples and docs: the 26 files in the table, on both builds.
  • Serial slice, PR, 82 files (the same slice as before): 702 passed, 7 skipped, 12 xfailed, 0 failed. That is 696 before, plus the six new tests.
  • np 2, PR: test_0762 and the parallel test_0035: 13 passed on each rank.
  • New tests on development: 5 failed, 2 passed, as described above.

Not run:

  • the full suites;
  • anything above np 3;
  • the Spiegelman benchmark to completion;
  • the docs' Markdown code blocks.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…used when set

H1's review of #1197 at 7355f46:

- A sum with a plain named parameter or a field without units beside a
  dimensionless ratio (T/T0 + k, beta*C - gamma*T/T0) still returned None,
  and get_units took the first field's kelvin. A term that carries no units
  is now a pure number beside the ratio, and get_units no longer falls back
  to a field's units for a sum: a sum of terms with no units has none.
- A sum of terms of different dimensions outside any function (a viscosity
  eta0 + T) is refused where it is set and at the solve, as at evaluate.
- The geographic tutorial subtracted a dimensionless quantity (the centre in
  model lengths) from a coordinate. The centre is now given its length, and
  the Gaussian divides by the dimensional radius: the run gives development's
  velocities. The message says to give such a quantity its units, and prints
  a negated constant as its number.
- The check's state key no longer formats each named expression's units: they
  follow from its value.

Underworld development team with AI support from Claude Code
test_0033 and the parallel test_0035 measured u_1*sin(pi*x/L) + u_0*y: a
velocity plus a velocity times a length, which a units model now refuses as
a sum of different dimensions where the Integral is made. The second term is
u_0*y/L, with L one model length (1 without reference quantities), so every
value is unchanged.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Third recheck at 5bac99b: changes requested. All five findings from the second recheck are fixed. A plain parameter or a field without units beside a ratio is now a pure number. The geographic tutorial runs and gives development's output. eta0 + T is refused when it is set. The message no longer prints --. The check is cheaper.

One new false refusal blocks the merge. It sits in the sum rule:

  • A sum that holds Min, Max, Abs or Piecewise of dimensional terms reads that term as "no units (a pure number)", so the sum is refused.
  • Development evaluates and solves eta_min + Min(eta1*exp(T0/T - 1), eta_max) and eta0 + Piecewise((eta1, x > W/2), (eta0, True)). At this head both are refused at evaluate, and now also when set as a viscosity.
  • The same cause refuses exp(Max(T, T0)/T0 - 1) and exp(-Abs(x - W/2)/W).

The PR's compiled sources changed. The merge of development brought in two changed .pyx files, so the PR was built fresh at 5bac99b, and the installed .py files match the source tree. The baseline is development at the new merge base, c20d352: its .py files were laid over a copy of a build whose compiled sources and environment files match c20d352 exactly. Every run printed which underworld3 it loaded.

Against the second recheck (7355f46)

finding status at 5bac99b evidence
1. High: a plain named parameter or a field without units beside a ratio read as kelvin fixed get_units gives dimensionless for all six arguments. At evaluate, exp(T/T0 + k), exp(k*T/T0 - k), exp(C + T/T0), exp(2*C - 3*T/T0), exp(beta*C - gamma*T/T0) and exp(beta*C - gamma*(T/T0 - 1)) each give the hand value (e.g. 0.0497871). eta0*exp(beta*C - gamma*T/T0), eta0*exp(C + T/T0) and eta0*exp(T/T0 + k) pass the setter and the solve. Every rank gives the same verdicts at np 2, np 3, and np 3 with an empty rank (cells 20 / 22 / 0)
2. High: geographic tutorial refused fixed by editing the tutorial It runs. Its printed output is identical to development's: velocity magnitude 0 to 2.09e+03, vertical min -3.42e+02 and max +2.09e+03, the same upwelling location. The new centre (float(c) * L_0) and the Gaussian over the dimensional radius give development's old-form values to 9 digits at three nodes. A dimensionless quantity beside a coordinate is still refused in user code (new finding 2)
3. Medium: eta0 + T not refused at the setter or the solve fixed at the setter Refused at the setter, naming both terms: eta0 + T, eta0 + eta1*T, eta0*(T/T0 + T), eta0 + x, and a body force [0, f + T]. The next solve then refuses the default viscosity. Legitimate sums are accepted, and their solves match development's to 10 digits: eta0 + eta1*exp(E/(R*T) - E/(R*T0)), eta0*(1 + T/T0), eta0*(1 + k), eta0*(1 + C), eta0 + 1, eta0*exp(T/T0 - 1). Every rank gives the same verdicts at np 2, np 3, and np 3 with an empty rank. A sum made mismatched by a later reassignment is not refused at the solve (new finding 3; same on development)
4. Low: per-solve check 5 to 7 ms improved Same 40-term probe. The check alone takes 4.4 to 4.6 ms, and 21 ms after a named value changes (was 24 to 26). A repeat solve takes 0.030 to 0.031 s, against 0.025 to 0.026 s on development. The 0.9 ms in the PR body is not reproduced here. Not blocking
5. Low: --3.93 in the message fixed The message now prints 3.92786 and -0.5
Arrhenius, both forms unchanged With no temperature reference, both forms agree with the hand value to 2.4e-14 to 3.2e-14 for three values of E. With a 1000 K temperature reference, both give NaN on the PR and on development. The 1000x fix is not in this head
earlier fixes (stale cache, atan2 and θ, body force and integrals, hints, the 512 bound) still hold The recheck probe's output is identical to its run at 7355f46
reassignment probe at np 3 with an empty rank still holds Every rank gives the same five verdicts. A parameter that becomes dimensional inside exp, and a plain W inside sin, are refused at the solve
the cache key now holds values only holds A reassignment that changes only the units is caught. W going from 30 km to 30 s, T0 going from 1000 K to 1000 m, both at evaluate and at the solve. Development accepts both

The questions asked of this head

The units of sums (33-sum probe and a 28-sum fallback probe, against development). Every sum that development evaluated correctly gives the same value on the PR. The values differ only in four cases:

  • Where development was wrong, the PR gives the right number:
    • T/T0 - 1: 0.2 (development: 200 K);
    • e1/e0 - T/T0: -1.199 (development: -1199 K);
    • T/T0 + x/W: 1.7 (development: 1700 K);
    • U + T/T0: 1.5 (development: 1500 K);
    • U*T/T0 - 1: -0.64 (development: -640 K);
    • 2*C - 3*T/T0 and C*T/T0 + k are now dimensionless; development labels them kelvin, 1000 times too large.
  • Where the sum is genuinely mismatched, the PR refuses it and development evaluates it silently: T + W, T + x, T/T0 + T, e1 + T, D + T.
  • Where the argument of exp carries a dimension, the PR refuses it, as before: exp(T - 1), exp(W + 0.5).
  • Where a sum holds Abs, Min, Max or Piecewise, the PR refuses it (new finding 1).

With U a field without units, get_units now gives:

  • U + T: kelvin, as on development. Evaluate is refused by the existing "field without units beside factors with units" guard, on both builds;
  • U*T/T0 - 1: dimensionless (development: kelvin);
  • U*(T/T0 - 1): dimensionless. It now evaluates to the right number, 900.03 at the probe's T; development refused it with the guard;
  • C + x/W: dimensionless (development: None). Evaluate is still refused by the guard on both builds;
  • U + 1, U + k, U + C: None on both, with the same values.

The adjoint tests. The old misfit, u_1*sin(pi*x/L) + u_0*y, adds a velocity to a velocity times a length (km·m/s). The PR rightly refuses it, at the Integral. All 7 cases of the pre-correction test_0033 fail on the PR with that message. The corrected misfit, u_0*y/L, gives the same numbers as the old misfit on development, because L is the length reference. On the units-coordinates case, J = 0.0119428460618926 and dJ/dα = 0.00616726509519003: identical to every digit across the PR (new misfit) and development (old and new misfit). The corrected test_0033 passes on development (7 passed).

The geographic example. Editing it is acceptable: it runs and its output matches development. But users with the old idiom will hit the refusal (new finding 2). They see:

evaluate: a sum of terms with different dimensions: N.x is in kilometer and 3.92786 is in no units (a pure number). Every term of a sum needs the same dimension. A plain number beside a dimensional term is read in model units; a dimensionless quantity there is ambiguous: give it its units (c * L, with L a length expression).

That says how to fix the coordinate case.

Examples and docs (short form: changes only)

The 26 files from the second recheck were run again on both builds, with the same copies, edits and 900 s cap. Two changed:

file development PR
examples/tutorials/geographic/Ex_Geographic_Meshes runs runs (was refused at 7355f46); output identical to development's
beginner/tutorials/13-Scaling-problems-with-physical-units (changed on development since the last recheck) runs runs, same output

The other 24 files behave as in the second recheck:

  • Each one that runs gives the same output on both builds, apart from paths and object ids. In the annulus example, dt agrees to 2e-14 relative.
  • Each one that fails stops at the same statement with the same error on both builds.
  • The Spiegelman benchmark times out at 900 s on both, with its first 23 nonlinear residual norms identical.

Findings

  1. High: a sum that holds Min, Max, Abs or Piecewise of dimensional terms is refused. At this head that happens at the setter as well as at evaluate.

    With eta0, eta1, eta_min and eta_max named viscosities, and T a field in K:

    • refused at evaluate and at the viscosity setter:
      • eta_min + Min(eta1*exp(T0/T - 1), eta_max);
      • Max(eta0, eta1*exp(T0/T - 1)) + eta_min;
      • eta0 + Piecewise((eta1, x > W/2), (eta0, True));
      • eta0 + Abs(eta1 - eta0);
    • refused at evaluate: T + Abs(T), T + Max(T, T0), T + Piecewise((T, x > 0.4), (T0, True));
    • refused as a dimensional argument: exp(Max(T, T0)/T0 - 1), exp(Min(T, T0)/T0), exp(-Abs(x - W/2)/W), exp(Abs(T - T0)/T0).

    Development evaluates all of these to the expected value, and solves with each viscosity. For example, exp(Max(T, T0)/T0 - 1) = 1.2214 at T = 1200 K. The message calls the Min(...) term "in no units (a pure number)". For Abs(eta1 - eta0) it prints the term as 9e+23, which hides what was summed. Every rank agrees at np 2, np 3, and np 3 with an empty rank.

    Two parts:

    • The refusals at evaluate and inside exp were already present at 7355f46. My second recheck missed them.
    • The refusal at the setter is new at 5bac99b, because the sum check now runs there. On the 7355f46 build all four viscosities above pass the setter and solve.

    Products survive, because no sum is involved: eta0*(1 + Max(T/T0 - 1, 0)) and eta0 + eta1*Heaviside(x - W/2) are accepted.

    A viscosity floor or cap and a layered viscosity are written exactly this way, so this blocks the merge.

    The cause: the PR lists Abs, Min, Max and Piecewise as functions that pass units through, but their units come out empty. Suggested fix:

    • give these functions their units from their arguments: Abs takes the units of its argument; Min, Max and Piecewise take the shared units of their arguments or branch values, and refuse branches of different dimensions;
    • or, at the least, treat such a term as unknown rather than as a pure number;
    • add tests: eta_min + Min(...) at the setter, and exp(Max(T, T0)/T0 - 1) against its hand value.
  2. Medium: a dimensionless quantity beside a dimensional term is refused, including the library's own model-unit values.

    • x - uw.non_dimensionalise(uw.quantity(200, "km")) is refused. Development gives 300000 m, the model-length reading that non_dimensionalise exists to produce. The geographic tutorial's geo.to_cartesian(...) results are refused in the same way.
    • Two spellings of the same value behave differently. x - uw.quantity(0.5) (no units given) is accepted as a plain number, but x - uw.quantity(0.5, "dimensionless") is refused.
    • The hint always reads "give it its units (c * L, with L a length expression)". That applies even to T - uw.quantity(1, "dimensionless"), where a temperature is meant, and to eta0 + T, where no dimensionless quantity is involved.

    The refusal is loud, and the hint fixes the coordinate case, so this does not block. Users with this idiom will meet it. Either:

    • treat a dimensionless quantity as the plain number the PR's own rule accepts; or
    • keep the refusal, have the hint name the dimension of the other term, and add it only when a dimensionless quantity is in the sum.

    Either way, say it in the PR description.

  3. Medium: a sum made mismatched by a reassignment after it was set is not refused at the solve.

    With eta0*exp(T/T0 - 1) + a set as the viscosity, a.sym = uw.quantity(1000, "K") leaves a viscosity that adds kelvin to Pa s. The next solve runs, reading 1000 K as one model unit (|v|max 8.35e-05, as on development). Evaluate of the same expression refuses it.

    The solver's input is the parameter's wrapper expression. The sum check asks for the wrapper's units, which are fixed when it is set, and does not walk into the sum. The function-argument check does walk into named expressions, so a parameter reassigned inside exp is refused at the solve, on every rank.

    The PR body says a reassigned named expression is caught at the solve. That is true for function arguments, not for sums. This is the same on development, so it is not a regression. Either walk into named expressions for the sum check too, or narrow the claim.

  4. Low: the PR description ("on … measurement") and a section comment added to test_0760 ("… review of Stokes refuses a P1 velocity on simplices; evaluate refuses a dimensional argument to exp, log and the trigonometric functions #1197 at 7355f46") name the reviewer by an internal session code. Describe the review instead.

Also noted, unchanged from development:

  • eta0*(1 + T) is accepted at the setter and solves: a plain 1 beside kelvin, giving a viscosity in Pa s K. Nothing checks that a parameter has the dimension it declares.
  • U + x/W and C + x/W are still refused by the existing guard, while U + T/T0 is accepted.

Unitless models

The same probe as before, with no reference quantities, was run on both builds. Its get_units results, values and Stokes maxima are identical on the PR and on development.

The new tests

On the PR, the four new items in test_0760 pass:

  • the two forms of "a plain parameter or a field without units beside a ratio is a pure number";
  • the setter refusal;
  • the message text.

Run against development, all four fail, as they should. The corrected test_0033 and the parallel test_0035 pass on the PR, and the corrected test_0033 passes on development.

What was run

  • Builds:
    • the PR, built fresh at 5bac99b;
    • development at the merge base c20d352: its .py files over a copy of a build whose compiled sources match.
  • Probes, serial, PR and development:
    • the 33-sum probe;
    • a 28-sum probe of sums whose units development took from the first field;
    • fields without units and plain parameters inside exp;
    • mismatched and legitimate viscosities at the setter and the solve, with a body force;
    • Min, Max, Abs and Piecewise in sums and in arguments (also run on the 7355f46 build);
    • dimensionless quantities beside coordinates and temperatures;
    • a cache key that changes only units;
    • a reassignment after the setter;
    • the adjoint misfit, old and new;
    • Arrhenius, both forms, with and without a temperature reference;
    • a unitless model;
    • the 40-term cost;
    • the recheck probe of the earlier fixes.
  • Parallel, PR:
    • at np 2 and np 3: the sum, setter, Min/Max, setter-and-solve, and fields-without-units probes;
    • at np 3 with an empty rank (cells 20 / 22 / 0): the same probes, plus the earlier reassignment probe and the reassignment-after-setter probe;
    • accept and refuse verdicts are identical on every rank. The empty rank's local evaluate at a point it does not own prints a different number, which is probe-side.
  • Examples and docs: the 26 files, on both builds.
  • Serial slice, PR, 82 files (the same slice as before): 709 passed, 7 skipped, 12 xfailed, 0 failed.
  • np 2, PR: test_0762 and the parallel test_0035: 13 passed on each rank.
  • On development:
    • the new test_0760 items: 4 failed;
    • the corrected test_0033: 7 passed.
  • The pre-correction test_0033 on the PR: 7 failed, each refused as a mismatched sum.

Not run:

  • the full suites;
  • test_1086 (not in the slice);
  • anything above np 3;
  • the Spiegelman benchmark to completion;
  • the docs' Markdown code blocks.

The runs shared the machine with other jobs.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…form

The parallel review of #1197 at 5bac99b:

- Min, Max and Piecewise read as pure numbers, so a viscosity floor, cap or
  layer beside a viscosity was refused as a mismatched sum. They now take the
  units their branches share (refused if those disagree), Abs and its kin
  keep their argument's, and sign and Heaviside are pure numbers. The rule
  is one helper, shared with a sum.
- A dimensionless constant in any form (a number, uw.quantity(0.5,
  "dimensionless"), a non-dimensionalised value) beside a dimensional term
  is read in model units; two terms that depend on the model and carry
  different dimensions are still refused. The hint names the units to give.
- A mismatched sum inside a named expression's value was swallowed by
  get_units's lookup of the value, so a sum made mismatched by a later
  reassignment ran at the solve. It is refused there now. (A sum of
  constants only is folded into one constant when set, and does not follow
  its parts at all.)
- Session codes are gone from test_0760's comments.

Underworld development team with AI support from Claude Code
…ex-and-transcendental

# Conflicts:
#	docs/examples/fluid_mechanics/advanced/Ex_Stokes_Cartesian_SolNL.py
The yield-stress floor is max(tau_y, tau_y_min); with Max now keeping its
arguments' units, evaluate returns the effective viscosity in Pa s, as the
dimensional gateway should, where the test read a bare model-unit number
that came from Max dropping them. It reads Pa s and divides by eta_0 for its
closed forms; the projected values, in a field without units, are unchanged.

Underworld development team with AI support from Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants