Skip to content

evaluate and global_evaluate: add nothing to the expression, broadcast constant entries - #1295

Open
lmoresi wants to merge 2 commits into
developmentfrom
bugfix/evaluate-no-epsilon-term
Open

lmoresi wants to merge 2 commits into
developmentfrom
bugfix/evaluate-no-epsilon-term

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 20, 2026

Copy link
Copy Markdown
Member

What changed and why

UNFILED 42, from the parallel review desk's review of #1284. This is the core evaluation path; the change is confined to how evaluate and global_evaluate shape a result.

Both evaluators added mesh.CoordinateSystem.zero_matrix(expr.shape) to every expression before lambdify (introduced in ff65767, "Evaluation updates"). Each entry of that matrix is uw.maths.functions.vanishing * x * y (* z in 3-D), that is 1e-18·x·y. Its purpose was shape: a matrix that mixes constant entries with coordinate-dependent ones does not lambdify to a uniform numpy array, and the added term made every entry depend on the coordinates. But it is added to the value, so wherever the value itself is of order 1e-18 it is most of the answer:

integral and the solvers do not add it and were exact.

Now nothing is added to the expression. _lambdify_and_evaluate, the final step shared by both evaluators, lambdifies the entries as a flat list and fills the (n_points, entries) result entry by entry; an entry that depends on no coordinate and no variable comes back as a number, which numpy broadcasts over the points. The result is then reshaped to (n_points, *shape) exactly as before. This cannot change a value: each entry is the lambdified entry itself, and the only operation applied to it is assignment into the result array (broadcasting a number repeats it). The result dtype is numpy's result type of the entries (at least float64), as lambdify's array was before.

What a user's run sees: values of evaluate and global_evaluate that differ from before by the removed 1e-18·x·y (relative to the domain scale), which is visible only where the evaluated values are themselves that small. Shapes are unchanged.

Left as is

The coordinate systems use the same term as an exact-looking zero inside their rotation matrices (coordinates.py: independent_of_N in the third row of the spherical rRotN and in the 3-D cylindrical east unit vector). Those forms are also compiled by the solvers, so they are not changed here; evaluating those unit vectors still carries 1e-18·x·y·z where the entry is zero.

Tests

  • tests/test_1295_evaluate_adds_nothing_to_small_values.py (serial; evaluate is rank-local): 1e-19*T and 1e-30*x against their exact values (T holds x + 2y on a degree-1 variable) through both evaluators; a matrix mixing a small field entry and a constant, and a 2x2 matrix mixing coordinates, constants and a small term; constants (an integer, a rational, 2.5e-20) and a constant matrix broadcast to the right shape; an expression in a parameter only. On development 4 of the 10 fail (the small-field and small-coordinate cases and the mixed matrix); the shape cases passed already and pin the shapes.
  • tests/parallel/test_1295_global_evaluate_adds_nothing_to_small_values_parallel.py: the same through global_evaluate, each rank asking for its own points. Fails on development at np 2; passes at np 2 and np 3.

Cost

evaluate of a P2 field expression on a 2-D box (cell 1/64), median of five calls, same base before and after:

expression 1e4 points 1e6 points
scalar, exp(-T)*x 0.1006 → 0.1026 s 8.64 → 8.85 s
vector mixing a field product and a constant 0.0973 → 0.0938 s 8.69 → 8.88 s

Within run-to-run noise (a first run against an older build moved the other way by a similar amount).

What was run

On a 96-thread Linux workstation (single system image, Intel Xeon Gold 6240R, MPICH):

What Result
69 serial files on evaluate, functions, units, expressions, interpolation, lambdify and coordinates 618 passed, 7 skipped, 12 xfailed, 1 xpassed (test_0720 ... test_mesh_coordinates_complex, which also xpasses on development)
10 parallel evaluate files at np 2 54 passed, 1 skipped, on both ranks
new parallel file at np 2 and 3 passes on every rank
collective guard scan 20 passed
check_test_coverage.py, check_deprecated_patterns.py OK

Not run

np 4 or more, 3-D evaluation at scale, macOS, the full suite.

Underworld development team with AI support from Claude Code

On development evaluate(1e-19*T) and global_evaluate of the same are wrong
by the 1e-18*x*y term the evaluators add, and a matrix mixing a small field
entry with a constant one is wrong in that entry.

Underworld development team with AI support from Claude Code
… instead

evaluate and global_evaluate added zero_matrix(shape), 1e-18*x*y in every
entry, so that lambdify returned a uniform array for a matrix mixing
constant and coordinate-dependent entries. _lambdify_and_evaluate now
lambdifies the entries as a flat list and fills the result entry by entry,
numpy broadcasting a constant entry over the points.

Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings November 20, 2026 13:09

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 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.)

#1295 at 4257f04: evaluate and global_evaluate no longer add 1e-18·x·y

Verdict at 4257f04: changes requested. The defect is gone. Small values now come back exact through both evaluators, serial and in parallel, including on a rank with no cells. Every value that ran on both builds differs from development by at most the removed 1e-18·x·y. Shapes, dtypes and cost are unchanged. But the change removes more than the added term. The deleted lines also ran a second _unwrap_expressions pass, and that pass is what resolved uw.expression parameters left inside a matrix. Without it, global_evaluate raises for almost any expression that holds a uw.expression, and evaluate raises for a matrix that holds one next to a mesh variable (finding 1). One existing test catches it: test_0066 fails on head and passes on development. The fix is small: keep the unwrap and drop only the added term.

Method

Results

The defect (T holds x + 2y, degree 1; Ts holds 1e-20·(x + 2y), degree 2; six points; tolerance rel 1e-12)

case development head
evaluate(1e-19*T) 2.67× too large at (0.5, 0.5); max rel err 2.9 rel 2e-16
evaluate(Ts) (field at 1e-20) 17.7× at (0.5, 0.5); max rel err 29 rel 4e-16
evaluate of [[1e-19 T, 4], [x, 1e-25 y]] max rel err 9e6 rel 2e-16
evaluate(1e-30), evaluate(1e-30*x) exact exact
global_evaluate(1e-30*x) 5e11× too large exact
global_evaluate, all of the above, np 1 8 of 10 wrong (all but the constant) all exact
same, np 2 (own points and all points) 8 wrong per rank 0 wrong
same, np 3, rank 2 with no cells (asks for nothing, then all points) 8, 8, 4 wrong 0 wrong on every rank
units model with #1284, no temperature reference: evaluate(R*T) at 1200 K 27801 and 11403 (wrong) 9976.8 (right)
same, a J/mol field set to 3e5 317825 and 301426 300000
same with a 1000 K reference same wrong values 9976.8 and 300000
same through global_evaluate, np 1 and np 2 the same wrong values raises NameError (finding 1)

Nothing else changed. I ran a battery through evaluate and global_evaluate on six meshes: a gmsh triangle box, a quad box, a gmsh tet box, a hex box, an annulus and a spherical shell. Each used 200 points, plus one point and zero points. The expressions:

  • constants: an integer, a float, 1e-30, a constant 2x2 and a constant 1x3
  • coordinate expressions: x, xy, sin·cos, mesh.X
  • mixed constant and coordinate matrices: 1x2, 2x2, 3x3 and 1x3
  • Piecewise; exp, sqrt, Abs and Max
  • P1, P2 and P3 scalars; a P2 vector; P1 symmetric and full tensors
  • products, u^T u, derivatives and Jacobians of P2 fields
  • N.x·T, N.x·N.y, a complex expression (I x + 1)
  • a swarm variable
  • the coordinate system's unit_e_*, rRotN, xRotN and R
2-D meshes 3-D meshes
cases 294 306
bit-identical 230 242
differ by at most 1e-18·|x·y(·z)| (+ 8 ulp) 60 57
any other value difference 0 0
shape or dtype differs 0 0
same error on both builds 4 (global_evaluate(mesh.X), annulus R) 4
works on development, raises on head 0 3: shell global_evaluate of unit_e_0, unit_e_2 and rRotN
  • Constant expressions return arrays of length n, not scalars, as before.
  • One point gives (1, …) and zero points give (0, …), with no crash, on both builds.
  • Complex expressions keep their dtype on both builds.

Expressions that hold a uw.expression (a = 3, b = 5a nested, η = 2 exp(−aT), a Stokes flux built with η; gmsh box and annulus)

expression development, both evaluators head evaluate head global_evaluate (np 1 and np 2)
a*T right right NameError a_c
Matrix([[a*T]]), a*u (u a vector field) right NameError NameError
b*T right right NameError b_c
Matrix([[b*T, 1]]) right NameError NameError
eta, eta*T right right NameError / SyntaxError (\eta)
vanishing*T right right SyntaxError (\varepsilon)
Stokes flux (stress) right right right
annulus unit_e_0, unit_e_0*T, rRotN*T right right right
shell rRotN*T, unit_e_2*T right SyntaxError SyntaxError
shear_viscosity_0 parameter right / SyntaxError right SyntaxError (also on development)

Cost (hex box 12³, P2 scalar and vector fields; median of 3 after a warm-up; at np 4 each rank asks for a quarter of the points, max over ranks)

development head
np 1, evaluate, scalar / 3x3 tensor, 1e4 0.268 / 0.281 s 0.268 / 0.270 s
np 1, global_evaluate, scalar / 3x3, 1e4 0.318 / 0.332 s 0.316 / 0.323 s
np 1, evaluate, scalar / 3x3, 1e6 25.23 / 25.52 s 25.41 / 25.80 s
np 1, global_evaluate, scalar / 3x3, 1e6 30.19 / 30.84 s 30.51 / 31.58 s
np 4, evaluate, scalar / 3x3, 1e4 0.067 / 0.094 s 0.059 / 0.067 s
np 4, global_evaluate, scalar / 3x3, 1e4 0.138 / 0.145 s 0.126 / 0.130 s
np 4, evaluate, scalar / 3x3, 1e6 3.957 / 3.984 s 3.950 / 3.969 s
np 4, global_evaluate, scalar / 3x3, 1e6 10.61 / 10.83 s 10.59 / 10.82 s

At 1e6 points the differences are within 2.4%, in both directions. That is within run-to-run noise with other jobs on the machine. At 1e4 points and np 4, head was 6–29% faster, on times under 0.15 s.

Tests

run development head
172 serial files that call evaluate/global_evaluate, not tier C, 4 xdist workers 1435 passed, 4 failed (the new file's 4), 10 skipped, 11 xfailed, 2 xpassed 1437 passed, 2 failed (test_0066 ...second_order[ip-ramp] and [nodal-ramp]: NameError: name 'c_ramp' is not defined), same skips
test_1295_evaluate_adds_nothing_to_small_values.py 4 of 10 fail 10 passed
17 parallel evaluate files, np 2 all pass except the new file (fails) all pass
same, np 4 all pass except the new file (fails) all pass
24 more parallel files that call evaluate, np 2 outcomes below identical outcomes
  • In the 24-file run, test_1063 and test_1064 went silent for 60 s and the supervisor stopped them, on both builds. test_1074 skips at np 2 on both builds.
  • test_0066's ramp case advects with velocity c_ramp * v. That is a uw.expression times a vector field, and it goes through the semi-Lagrangian history's global_evaluate. So the failure reaches the solvers, not only direct calls.

Findings

  1. High: global_evaluate raises for expressions that hold a uw.expression. evaluate raises when such an expression is a matrix with a mesh variable.
    • Before this PR, petsc_interpolate and rbf_evaluate ran _unwrap_expressions(expr, keep_constants=False) twice. The first call is at the top. The second came after expr + zero_matrix(...) in the deleted block. The PR deletes the second call along with the term.
    • One pass is not enough for a matrix. On both builds, a single _unwrap_expressions call returns Matrix([[a_{c}*T]]) unchanged, and a second call gives Matrix([[3.0*T]]). A scalar a*T unwraps in one pass.
    • evaluate survives scalars because its gateway unwraps first. global_evaluate passes the raw expression and wraps it in a Matrix. So the leftover symbols reach lambdify as names (a_c) or LaTeX (\eta, \varepsilon) and raise NameError or SyntaxError.
    • Affected: user parameters (a*T, a*u), nested expressions, a viscosity expression, the shell's unit_e_2 and rRotN (they hold independent_of_N), and any semi-Lagrangian advection whose velocity holds a parameter (test_0066 ramp). It also blocks the A dimension with no reference has the SI base unit as its scale (E/R met the temperature reference) #1284 units case through global_evaluate.
    • Suggested fix: keep the second expr = uw.function.expressions._unwrap_expressions(expr, keep_constants=False) in both petsc_interpolate and rbf_evaluate, without the zero_matrix term. Or unwrap until nothing changes.
    • Add a test: evaluate and global_evaluate (serial and np 2) of uw.expression("a", 3) * T.sym[0] and uw.expression("a", 3) * u.sym.
    • The PR body's 69-file serial run did not include test_0066. It is among the 172 files run here.
  2. Low: the remaining independent_of_N in coordinates.py is harmless where it sits, as the PR says.
    • On the spherical shell, the third row of rRotN and the third entry of unit_e_2 evaluate to exactly 1e-18·x·y·z (6.4e-20 at (0.4, 0.4, 0.4), 7e-25 at (1e-3, 1e-3, 0.7)), on both builds. Development added a second 1e-18·x·y·z wherever it added the term: global_evaluate always, and evaluate when a field was present (1.28e-19 there).
    • In forms, the term always multiplies a component of the vector being rotated, next to O(1) entries in the same row. So its contribution relative to that row is at most 1e-18·|x·y·z|, below double precision. It cannot change an assembled matrix beyond round-off.
    • It is visible only when the unit vector itself is evaluated and the exact zero matters. A follow-up could replace it with sympy.S.Zero, now that the evaluators no longer need uniform entries. That needs a check that the solvers' code generation is happy with a literal zero there.
    • I did not assemble solver matrices to measure this. The argument above is from the forms.
  3. Low: the code in _lambdify_and_evaluate reads correctly.
    • The flat-list lambdify and list(Matrix) are both row-major, so reshape(-1, *shape) puts entries where they were.
    • A constant entry broadcasts on assignment. np.result_type(np.float64, *values) keeps complex (development's constant branch would have cast it to float). Zero points give np.empty((0, k)).
    • A sympy.vector Vector or Dyadic still takes shape = (1, 1) while giving dim entries. That quirk is unchanged from development and was not reached by any test or probe.
    • The rbf_evaluate branch for mesh is None (which found a coordinate system from the expression's base scalars) is gone along with its unwrap. Finding 1's fix should cover that path too.
  4. Low: PR body.
    • "The change is confined to how evaluate and global_evaluate shape a result" is not accurate while finding 1 stands.
    • The 3.08× figure comes from a different field. With T = x + 2y the factor at (0.5, 0.5) is 2.67, as the new test's setup gives.

What was run and not run

  • Run:
  • Not run:
    • the battery in parallel (only the small-value and UW-expression probes ran at np 2 and 3)
    • a check of finding 1's suggested fix (needs a rebuild)
    • assembled-matrix measurements for finding 2
    • tier C tests, examples, the full suite, macOS

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