Skip to content

Units frame defects: FreeSurface, parallel refinement and semi-Lagrangian transfers, swarm .array, coordinate label, and deform's plain arrays (#993, #992, #991, #979, #998, #1081) - #1205

Merged
lmoresi merged 15 commits into
developmentfrom
units/frame-defects
Nov 16, 2026
Merged

lmoresi merged 15 commits into
developmentfrom
units/frame-defects

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member

What changes for users: in a model with reference quantities, FreeSurface runs, refinement transfers run in parallel, a parallel semi-Lagrangian history is right, assigning to a swarm variable's .array converts units, mesh.X.units names the units mesh.X.coords carries, and mesh.deform refuses a plain array, which could be metres or model units.

These are the units "frame" defects: places where a dimensional array lost its units and was then read as model units, or the reverse. Each comes with a test that fails on development. Runs were on a 96-thread Linux workstation (single system image; Intel Xeon Gold 6240R, AVX-512; MPICH), on development fafbecb merged in. #990 was fixed by #1003 and is labelled separately.

The fixes

issue was now test
#993 SwarmVariable.array = value wrote the magnitude straight into .data, so 500 K stored 500 where 0.5 is right (1000 K reference) writes through the view, as MeshVariable does: a unit-aware value is converted, and a plain array is refused as ambiguous test_0117_swarm_array_assignment_units: 6 fail on development, 6 pass
#992 the parallel semi-Lagrangian record read the dimensional var.array, stripped it and stored it as non-dimensional: 500 at np 2 for a field holding 0.5 (0.5 at np 1) copies the non-dimensional var.data, for scalars and vectors; other layouts fall back to evaluate parallel/test_0992_…: fails at np 2 and 3 on development, passes at np 1, 2 and 3
#991 the parallel refinement transfers were refused in a units model (#1002), after being wrong by up to 3874 #1003 moved both sites to coords_nd and the storage layout, so the refusal is lifted: exact (< 1e-9) for scalar, vector, 2×3 MATRIX, TENSOR and SYM_TENSOR parallel/test_0785_… changed (see below): 10 fail on development, 16 pass at np 2 and 3
#979 mesh.X.units returned mesh.units (km for a reference length in km) while mesh.X.coords holds metres: a factor-1000 label error mesh.X.units is meter in a units model; mesh.units stays the unit output is written in test_0622_coordinate_units_label: 1 fails on development
#1081 mesh.deform guessed whether a plain array was metres or model units from its size; the guess failed when the length scale is near 1 in a units model a plain array is refused whatever its values, as a bare number for a dimensional parameter is (units ruling). Coordinates with units, or model coordinates marked units="dimensionless", are accepted, and the size guess is gone. test_0770 (serial and parallel) and parallel/test_0785 updated
#998 FreeSurface raised at its first solve: "surface trace-mass weights lost 6.281e+00 of 6.281e+00" works in model units throughout. Two steps of the test_1070 annulus give the same DM coordinates with and without reference quantities, to 1e-8 test_1070_free_surface_in_a_units_model: 2 fail on development

#998 needed three changes, found one after another:

  • Mesh nodes and field nodes were read from .coords, which is metres in a units model, and matched against DM and recovery positions in model units. They now come from mesh._coords and coords_nd.
  • utilities/boundary_flux.write_boundary_scalar_field keyed its nodes by field.coords against the recovery's model-unit positions. No key matched, so the recovered topography was zero, and the surface did not move. It now keys by coords_nd.
  • FreeSurface.estimate_dt took float() of the composition solver's dimensional step, which is seconds. Where that limit bound, the step was 7.6e10 where 2.4e-3 is right. The second test shows this, with the fix swapped out.

FreeSurface and the bare-number ruling. The free surface copies the free solve's parameters onto its helper solvers through unwrap, which turns a quantity into a bare number. That bare number would then be refused, and it has nothing to rebind anyway, so a constant is now copied as its expression, with its units. Its internal Laplacian smoother and its default composition diffusivity are library settings in model units, set inside the internal context of #1182. Its own target for mesh.deform is passed marked as model units.

#993 and an existing caller. The old setter reshaped rows, so (N, 2, 1) written into a vector viewed as (N, 1, 2) worked, and test_0504_projections relies on it. Writing through the view needs the exact shape. Shapes that differ only by axes of length one hold the entries in the same order, so they are reshaped first. A plain array written to a swarm variable with units in a units model is now refused, as it already is for a MeshVariable. That includes v.array = v.array, because the view is not itself unit-aware: the same as MeshVariable today.

Existing tests that changed

Regression runs

Every tests/test_*.py, excluding tier C, 6 xdist workers:

passed failed skipped xfailed xpassed
development 918c4ba, with this PR's new tests copied in 4275 9 (all the new tests) 31 18 2
this branch (development fafbecb merged in) 4293 1 31 18 2

Not touched

Solver defaults, petsc_generic_snes_solvers, rotated_bc.py, the custom multigrid. scripts/check_test_coverage.py passes.

Checklist (UW3 Style Charter)

Underworld development team with AI support from Claude Code

The setter wrote a value's magnitude straight into .data, so 500 K stored 500
where 0.5 is right. A unit-aware value is now converted and a plain array is
refused as ambiguous, as for MeshVariable.

Underworld development team with AI support from Claude Code
…992)

At np > 1 the record read the dimensional var.array, stripped its units and
stored the magnitude as non-dimensional: 500 at np 2 for a field holding 0.5.
It now reads var.data, for scalar and vector fields; other layouts fall back to
evaluate.

Underworld development team with AI support from Claude Code
#1003 moved both parallel sites to coords_nd and the storage layout, so the
refusal #1002 added is no longer needed: the transfers are exact for every
shape at np 2 and 3. test_0785's refusal tests now assert exactness, over
scalar, vector, 2x3 MATRIX, TENSOR and SYM_TENSOR.

Underworld development team with AI support from Claude Code
X.coords holds SI metres, from the length scale, but X.units returned
mesh.units (kilometres for a reference length in km), a factor-1000 label
mismatch. mesh.units stays the unit output is written in.

Underworld development team with AI support from Claude Code
…del (#998)

It read mesh nodes and field nodes from .coords, which is in metres in a units
model, against DM and recovery positions in model units: the first solve lost
every trace-mass weight, and write_boundary_scalar_field matched no key, so the
recovered topography was zero. Node and field coordinates now come from the
model-unit frame (mesh._coords, coords_nd), and estimate_dt converts a
dimensional solver step to model time instead of taking float() of seconds.

Two steps of the test_1070 annulus with and without reference quantities give
the same DM coordinates to 1e-8.

Underworld development team with AI support from Claude Code
#993)

The old setter reshaped rows, so (N, 2, 1) into a vector viewed as (N, 1, 2)
worked (test_0504_projections); writing through the view needs the exact
shape. Such shapes hold the entries in the same order and are reshaped first.

Underworld development team with AI support from Claude Code
…ts model now requires

Underworld development team with AI support from Claude Code
…ce copies constant parameters with their units

#1081: in a model with reference quantities a plain array is ambiguous (metres
or model units), and is refused whatever its values, as a bare number for a
dimensional parameter is. The size guess, which failed when the length scale is
near 1, is gone. Coordinates with units, or model coordinates marked
units="dimensionless", are accepted. FreeSurface passes its model-unit target
marked so. test_0770 (serial and parallel) and test_0785 move with the rule.

FreeSurface's helper solvers copied the free solve's parameters through unwrap,
which turns a quantity into a bare number; a constant is now copied as its
expression. Its internal smoother and composition defaults run in the internal
context.

Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings November 16, 2026 01:51

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 on head c66af42: changes requested. The six fixes do what they say, and each issue's reproducer passes on this branch and fails on development at the rank counts in the table below, including an empty rank for the refinement transfers. Two FreeSurface defects should be fixed before merge. Both can only happen now that FreeSurface runs in a units model, and both are small fixes: the drift guard is blind to constant parameters (M1), and the warm start copies dimensional velocity and pressure as model values (M2). The other findings are about test strength and documentation.

Per-issue result

All runs used development fafbecb against this head, through a Python overlay on one compiled build. Only .py files differ between them, so the compiled code is the same in both arms.

issue development fafbecb this PR c66af42
#993 SwarmVariable.array = 500 K stored as 500 (0.5 is right), for scalar, vector, MATRIX, TENSOR and SYM_TENSOR, at np 1 and 2. A plain array is accepted and stored ×1000. 0.5 for all five shapes at np 1 and 2. A plain array is refused and storage is unchanged. (N,2,1) and (N,2) unit-aware values give the right vector. No regression in a model without units: plain arrays, proxies, SYM_TENSOR.
#992 parallel semi-Lagrangian record At np 2 and 4, records are ×1003 for T, a vector component and MATRIX components. Without units, SYM_TENSOR S[1,1] is read from S[0,1]'s slot (ratio 0.547 at np 2). Same values as serial at np 2 and 4, with and without monotone_mode="clamp", for T, W[1], S[1,1], S[0,1], M[1,0] and M[0,1], with and without units.
#991 parallel refinement transfers Refused with NotImplementedError (#1002) at np 2 and 4. Exact (≤ 3.6e-15) at np 2 and 4. Covers scalar, vector, 2×3 MATRIX, TENSOR, SYM_TENSOR, K→none, none→K, K→mK and no units, with scaling on and off. Also exact with an empty rank at np 2, 3 and 4.
#979 mesh.X.units kilometer while .coords holds metres. Labelling .coords with it gives 1e6 km. meter, matching .coords.units, with scaling on and off. None without units.
#998 FreeSurface AttributeError: 'float' object has no attribute 'subs' at construction in a units model. test_1070 passes. Two steps with and without reference quantities agree within the test's 1e-8 serial (np 2: 1.15e-8; np 4: 3.9e-9). See M1 and M2.
#1081 plain array to mesh.deform The size guess refuses 1.5 × model coords with L = 2 m, and also refuses them marked dimensionless. A plain array is refused whatever its values. The same coordinates marked dimensionless are accepted, and coordinates with units are converted. The refusal is uniform across ranks at np 2 and 4. A model without units still accepts plain arrays.

Findings

M1 (medium): in a units model, the FreeSurface drift guard does not catch a constant re-assigned after construction

_copy_constitutive_model now checks hasattr(unwrapped, "subs") before rebinding. _check_derived_solvers_match still does unwrap(expected, keep_constants=True, return_self=True).subs(rebind). In a units model a constant parameter unwraps to a Python float, so that call raises AttributeError, and the surrounding except Exception: pass hides it. In a units model the guard never compares a constant parameter.

The PR makes a constant parameter live: the helper solvers hold the free solve's own expression. So re-assigning one constant to another is tracked, and that part is right (see "Confirmed correct"). But an expression is still copied as a rebound snapshot. If the user later re-assigns it to a constant, the helper solves keep the old expression, and nothing refuses the solve.

Failure case: the test_1070 annulus, one solve() and advance(0.01). Build with shear_viscosity_0 = model_units(1, "Pa*s") * (1 + 20 r²), then set shear_viscosity_0 = model_units(1, "Pa*s") before solving.

  • Without reference quantities, solve() raises "the free surface's derived solves no longer match the free solve" (correct, as on development).
  • With reference quantities (1000 km, 1 Myr, 1e24 kg, 1000 K), solve() runs. The DM coordinates differ from a run built with the constant viscosity by 9.85e-4, the same amount as a run that keeps 1 + 20 r² throughout. So the held and consistent solves used the stale viscosity.

Fix: guard the check the same way as the copy. Compare the unwrapped values when the unwrapped value has no .subs. Narrowing the except would have exposed this.

The same guard reports the opposite case correctly. Build with a constant, then re-assign a strain-rate-dependent expression: the live copy then carries the free solve's velocity atoms, and the guard raises, as it should.

M2 (medium): in a units model, the consistent-solve warm start writes dimensional velocity and pressure as model values

_solve_consistent does self.consistent.u.array[...] = self.free.u.array and does the same for p. The consistent solve's own V_cons and P_cons have no units. When the user's Stokes velocity carries units, the right-hand side is a unit-aware array, and the view's write path stores its magnitude as model units without converting it.

Failure case: a units model, a velocity in cm/yr holding 0.01 model units, copied with .array[...] = into a variable without units. The stored value is 1.0, 100 times too large. The pressure copy has the same form, so a pressure in Pa is written as its Pa magnitude; I did not measure it separately.

Measured effect: test_1070's two steps, with the free solve's velocity in cm/yr and pressure in Pa, differ from the run without reference quantities by 1.8e-7. With the default fields, which carry no units, they agree within 1e-8 in serial (the test passes), and to 1.15e-8 at np 2. The case is isoviscous and linear, so the solve converges anyway. The code comment says the warm start exists because a cold start stalls a power-law Newton line search. A warm start 100 times too large is a bad start for that case. No nonlinear run was made.

This is one of the "about 15 sites" from #998 that the PR leaves as it was. test_1070 does not reach it, because its fields have no units.

Fix: copy .data when the layouts match, as the PR already does in ddt.py.

L1 (low): test_0785's refinement pair does not refine

_units_refinement_pair sets the metric to 0.1. A metric is M = 1/h², so h is about 3.2 and adapt marks nothing: the child has the same 128 cells as the base, at every rank count. The new exactness tests therefore transfer between coincident nodes. They still catch #991, which was about the coordinate frame and is seen at any node layout, but they do not exercise interpolation.

With M = 400 (child 4 times finer), I measured the same exactness, ≤ 3.6e-15, at np 1, 2 and 4 and with an empty rank at np 2, 3 and 4. A metric like that would make the test show what its name says. The 1e-9 tolerance is meaningful either way: values are O(1), and the old errors were O(1) to O(1e3).

L2 (low): test_0992 covers the scalar only

The PR adds a VECTOR branch to the direct copy, and sends MATRIX, TENSOR and SYM_TENSOR components to evaluate. That fallback also fixes #992's second defect, the SYM_TENSOR slot: without units at np 2, development reads S[1,1] at 0.547 of its value. Neither case has a test. A parametrisation over T.sym[0], W.sym[1] and S.sym[1, 1] on a linear field would cover both. The probe used for the table above can be supplied.

L3 (low): API changes with no changelog entry

There are two API changes:

  • mesh.deform now refuses plain arrays in a units model, with no deprecation step;
  • SwarmVariable.array = plain is now refused for a variable with units, and that includes v.array = v.array.

Both are deliberate and the error messages are clear. Scripts in units models will meet them, so they deserve an entry in docs/developer/CHANGELOG.md.

Related: test_0770 no longer asserts that a dimensionless-marked array of metres is refused. Such an array is now accepted and scales the mesh by the length scale. That follows from the #1081 ruling (the caller's statement decides, with no size guess), but the changelog should say it.

Notes (no action needed)

  • At np > 1, the parallel semi-Lagrangian record now sends MATRIX and TENSOR components to evaluate. Before, they took the direct copy, which was right without units. The direct copy exists to avoid seam mislocation. On a linear field at np 2 and 4, the evaluate route gives the same error as serial, so I see no cost.
  • test_1070's 1e-8 bound sits near the floor that a solver tolerance of 1e-5 allows. Serial is inside the bound (the test passes). At np 2 the same problem gives 1.15e-8, so the bound would be fragile if the test were ever run in parallel.

Confirmed correct

  • mesh.deform in a units model decides a plain array's frame by guessing from its size #1081, collective: the refusal depends only on uw.get_default_model().has_units() and on the type of the argument, with no reduction, so every rank decides alike. At np 2 and 4 every rank refused, or every rank accepted. The empty-rank deform test (test_0770 parallel) passes with the dimensionless-marked target.
  • Internal callers of the deform path: free_surface.py is the only caller of mesh.deform in src/, and it now marks its target dimensionless. MMPDE and smoothing (meshing/smoothing/api.py, mmpde.py), remesh.py, ddt.py (old frame) and Mesh.ephemeral_coords call _deform_mesh with model coordinates, so they never reach _model_coordinates_from and do not break.
  • Other mesh.deform callers: none of the tests, docs or examples that call mesh.deform in a units model passes a plain array, apart from the tests this PR updates. docs/examples and the tutorial notebook call it without reference quantities, which is unchanged.
  • Helper-solver parameter copy in a units model: it is live. After construction, re-assigning shear_viscosity_0 to a new constant, or setting .sym, reaches the held and consistent solves. One step built with η = 1 + 20 r² and one built with η = 1 and then re-assigned to 1 + 20 r² agree to 1.1e-16. Without reference quantities the copy is a snapshot, as on development, and the guard refuses the solve. The behaviour therefore differs between the two kinds of model; the _check_derived_solvers_match docstring ("Only re-assignment drifts") now describes only the second.
  • boundary_flux.write_boundary_scalar_field: both callers, boundary_flux_field and rotated_bc.dynamic_topography_field, key their maps by DM coordinates in model units, so coords_nd is the matching frame. In a model without units coords_nd equals coords, so nothing changes there.
  • discretisation_mesh.py (−43 lines): the removal of the Mesh.remesh transfers past an empty rank, units included; global_evaluate no longer transposes #1002 guard and of the size guess is complete. Nothing else references _refuse_parallel_refinement_with_units. Both parallel transfer sites already evaluate at coords_nd under _internal_resampling and write through _evaluated_in_storage_layout, which reduces unit-aware values. I found no double conversion: K→mK gives the same non-dimensional values as K→K, and a field with units into one without, or the reverse, is exact.
  • ddt.py record: it reads var.data and returns non-dimensional (N,1,1) values, which _write_evaluated stores unchanged. It is right with scaling on and off, because both sides of the copy are in the same frame.
  • SwarmVariable.array setter: the new setter writes through the view, which converts units and packs tensors, and it keeps the old setter's tolerance of length-one axes. A scalar such as v.array = 7.0 now broadcasts; it used to raise AttributeError.
  • coordinates.py: X.units is now set under the same condition (mesh.units is not None) that makes .coords a metre-labelled UnitAwareArray, so the two cannot disagree.
  • FreeSurface.estimate_dt: _model_time gives the same step with and without reference quantities (test_1070's second test).

What was run

Logs and probe scripts are kept by the reviewer.

Underworld development team with AI support from Claude Code

…tant, the warm start copies stored values (H1's review of #1205)

- _check_derived_solvers_match called .subs on the plain number a constant
  unwraps to in a units model, and a bare except hid it: a re-assigned
  viscosity was not caught and the solve ran on the stale one. Constants are
  compared as they are, and the swallow is gone.
- _solve_consistent warm-started V_cons and P_cons through .array, which put
  a velocity with units into a field without them; it copies .data, the raw
  variable-to-variable copy inside the non-dimensional boundary, as ddt.py does.
- test_0785's refinement metric is 400 (h = 0.05), which refines; 0.1 was an h
  of 3.2 and refined nothing. test_0992 covers a vector.
- CHANGELOG: the two API breaks of the units ruling (#1182, #1081).

Underworld development team with AI support from Claude Code
@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.)

Re-check of head d2804e3: ready to merge on green from this review. M1 and M2 are fixed, and L1 to L3 are addressed. The test-order failure that the new test_1070 docstring describes is real. It is not caused by the refused solve, and it is already on development, so it should be filed on its own (below). It does not block this PR.

The new commit changes only .py files, plus tests and the changelog. The merge base is still development fafbecb, so the runs used the same Python overlay on the same compiled build as before.

item at c66af42 at d2804e3
M1: drift guard in a units model Build with η = 1 + 20 r², re-assign η = 1, and the solve ran on the stale viscosity (9.85e-4 off). solve() raises "derived solves no longer match", in a units model as without one. A constant re-assigned to another constant is still tracked live, with no false drift: one step agrees to 1.1e-16 with a run built with the new value. The bare except is gone.
M2: warm start A free velocity in cm/yr was stored 100 times too large in V_cons. With the free solve's velocity in cm/yr and pressure in Pa, the consistent solve starts from exactly the free solve's stored values: max difference 0 for u (max 343) and for p (max 6.7e4). The new test fails at c66af42 and passes here.
L1: test_0785 refinement The child was not refined (128 = 128 cells). Metric 400, and the test asserts the child is finer. It passes at np 2 and 4.
L2: test_0992 coverage Scalar only. Adds a vector case, with and without the clamp. It passes at np 2 and 4.
L3: changelog No entry. An entry for the mesh.deform and bare-number API breaks. Two things that would belong in it are missing: SwarmVariable.array = plain is now refused for a variable with units, and a dimensionless-marked array of metres is now accepted as model coordinates. Optional.
#991, #992 (fixed, as reviewed) Unchanged on a rerun at np 2 and 4. #991 is exact (≤ 3.6e-15) for every shape and unit mix on a refined child. The #992 records match serial for T, W[1], S[1,1], S[0,1], M[1,0] and M[0,1].

The test-order note: a state leak, but not from the refused solve, and not new. In one process I built a first model, reset the default model, and then built a FreeSurface on a new annulus mesh whose viscosity depends on the coordinates (1 + 20 r²). The second build fails whenever the first model had a coordinate expression on its own mesh:

  • a FreeSurface that was built and never solved: foreign-mesh ValueError;
  • one that solved: "analytic normal for boundary 'Upper' contains symbols ['N.x', 'N.y'] that are not mesh coordinates";
  • one whose solve was refused: foreign-mesh ValueError;
  • a plain Stokes solve with a coordinate-dependent viscosity: the same "analytic normal" error.

The second build succeeds:

  • after a first model with a constant viscosity;
  • when the second viscosity is constant.

This holds with and without reference quantities, and on development fafbecb in a model without units. So some state keyed on coordinate expressions carries across meshes; it is not left by the refused solve. In test_1070, running the drift test and then the warm-start test fails the second with the foreign-mesh error. Running the drift test after the others passes, which is the order the file uses. Suggestions:

  • file the leak as its own issue;
  • reword the docstring of test_a_reassigned_viscosity_is_refused_as_drift_in_a_units_model, since the refusal is not the cause.

The new warm-start test uses a radial viscosity, which is spatially variable but not nonlinear. No power-law case was run.

Runs at d2804e3:

run passed skipped xfailed failed
Serial, 147 targeted files, 4 xdist workers, excluding tier C 1272 14 15 0
tests/parallel, 19 files on the changed paths, np 2 76 7 – 0
test_0770, test_0785 and test_0992 parallel, np 4 22 1 – 0
test_1070, serial 4 – – 0

Logs and probe scripts are kept by the reviewer.

Underworld development team with AI support from Claude Code

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