Skip to content

Replace the least-squares relaxation with contact dynamics coupled to growth - #54

Open
marpaia wants to merge 8 commits into
masterfrom
marpaia/hard-contact-solver
Open

marpaia wants to merge 8 commits into
masterfrom
marpaia/hard-contact-solver

Conversation

@marpaia

@marpaia marpaia commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements the plan in #53: contact is solved with non-negative forces, and growth is part of the same convex problem. This replaces the least-squares relaxation, which could not keep growing cells apart in a full space or stop growth when the space is full (#51). The old relaxation is removed; no compatibility with it is kept.

  • Simulation.step(dt, ContactDynamicsParameters) advances growth and contact together. MechanicsConfig holds its parameters, and a controller configured with it takes every step this way.
  • A cell's elongation responds to the axial load its contacts put on it: not at all, exponentially, or linearly to a stall load.
  • Constraints are rows in the same solve. A box or cylinder container reports one wall contact per face, so a cell end in a corner is held by every wall that meets there. Wall contacts have their own, larger stiffness.
  • With flow drift on, the flow velocity enters the solve as a known velocity, so contacts resist the flow pressing cells together.
  • CPU, Metal, and CUDA implement the solve. The projected-gradient iteration is shared; Metal runs a batch of steps per command buffer.
  • Every example and tutorial model uses the new solve. The trap example uses a linear growth load response in place of its overlap-based growth rule.
  • Design record: docs/architecture/0026-contact-dynamics.md.

Removed

  • The regularized least-squares solve, its conjugate-gradient iteration, the integration of its corrections, and the wall projection, on CPU, Metal, and CUDA.
  • Simulation.solve_cell_mechanics, Simulation.relax_cell_mechanics, MechanicsParameters, MechanicsSolveResult, CellCorrection, SolverStatus, SolverBreakdown, SolverReport, and BackendFeature.CELL_MECHANICS.
  • MechanicsConfig fields passes, gamma, mu_a, residual_rms_tolerance, require_convergence, max_rotation_radians, and the two activation margins. Controller checkpoints written with the old fields do not load.
  • MechanicsIntegrationParameters is replaced by FlowDriftParameters as the argument of the standalone apply_flow_drift.

Still present, and only meaningful to the removed solve: the weight field of contacts and the coefficient field of constraints. They are part of the checkpoint and scene formats, so removing them is a format change and is left out of this PR.

Results

Check Outcome
Closed 4×4×1.2 chamber Fills to 8–9 cells and holds; overlap under 0.01
Cell between two walls Stalls within 5% of the stall load and stops consuming nutrient
Collinear pair spanning a chamber Buckles when growth ignores load; a perfectly straight pair with a load response stalls
Free colony, no load response Elongates exactly as without mechanics; packing 0.92
Free colony pressure profile Parabolic, within 35% of the continuum prediction in every radial bin, no fitted constants
Load-sensitive colony Pressure profile and expansion speed within 25% of the published continuum solution; measured within about 10%
Trap example Steady turnover, about 260 cells in the trap; load rises from the mouth, levels off, peaks at the back wall
Checkpoint resume Reproduces the uninterrupted run exactly

Performance

A step now costs roughly 50–100 times what a least-squares relaxation pass did. The two are not doing the same work: the relaxation took one cheap linear solve and left the contacts unresolved, and the new step iterates until they are resolved.

Cost per step

Unconfined colony, no load response, dt = 0.05, default parameters, measured on an Apple-silicon laptop before the old solve was removed. Each figure is the mean of three steps.

Cells Contact dynamics, CPU Contact dynamics, Metal Least squares, CPU Ratio on CPU
500 35 ms 81 ms 0.7 ms 50×
2,000 176 ms 311 ms 4.5 ms 39×
5,000 1.6 s 0.9 s 13 ms 124×

Starting each substep's solve from the previous substep's forces, added afterwards, brought the 5,000-cell CPU figure to 1.2 s. The Metal figures predate that change.

The trap example, about 500 cells at steady state, runs 1,500 steps in about 34 s on CPU, or roughly 23 ms per step.

What has been tried

The iteration count is set by the conditioning of the contact network, which scales with contact stiffness × step length ÷ drag. That is why the changes below move it so little.

Change Result Status
Start each substep from the previous substep's forces 1.6 s → 1.2 s per step at 5,000 cells In this PR
Start each step from the previous step's forces 10–30% fewer iterations Not included; needs the forces in the checkpoint
Conjugate gradient on the active contacts No gain; it is bound by the same conditioning Dropped
Diagonal preconditioning About 5% Dropped
Shorter substeps 30–45% fewer iterations, about 20% less time, nothing on the trap example Not adopted
Softer or stiffer contacts Ten times the stiffness leaves a fifth of the overlap for about eight times the iterations (2,000 cells) A modelling choice, not an optimisation

What could be tried

  • Thread the CPU solve. It is single-threaded. A plausible 3–4× at a few thousand cells, little at a few hundred.
  • A preconditioner that captures the contact network. The only route to a large algorithmic gain, and a research problem on an irregular, changing graph.
  • A leaner Metal iteration. Each iteration issues about 20 small dispatches for its reductions, which is why Metal loses below a few thousand cells.
  • Fewer re-detection rounds. Each round repeats the solve; a curvature term in each row would make the first prediction more accurate.
  • Carry forces across steps, with a checkpoint format change, for the 10–30% above.
  • Time CUDA on hardware.

Why the new solve is more accurate

The claim rests on physical constraints the old solve violated and on agreement with analytic solutions. Neither solve has been compared with experimental data here.

What the least-squares relaxation got wrong

Measured on master during the investigation in #51:

  • Cells overlapped deeply in ordinary colonies. An unconfined 512-cell colony at the default gamma = 10 had a median per-cell overlap of 0.32 at radius 0.5, about two thirds of a radius. The solver reported convergence on every step.
  • A full space kept filling. A closed 4×4×1.2 chamber, which holds about nine cells in one layer, reached 256 cells by step 200, with a cell footprint 25 times the floor area.
  • Pairs inverted and never recovered. Once two cells overlapped by more than a radius they passed through each other or stacked, and the solve pushed them further rather than apart. Even with the overlap-based growth limit of Limit growth by compression in the engine #52 the chamber's worst pair overlapped by 1.77 radii.
  • No setting fixed both cases. gamma = 100 reduced the free colony's overlap to about 0.003 but made a full chamber creep; gamma = 10 did the reverse.

These follow from the formulation, not from tuning. Contacts were equalities solved in a least-squares sense, so a contact could pull as well as push, the solve minimized the sum of squared overlaps and so did not bound the largest one, and growth was committed before the solve with no way to yield.

What the new solve gets right

  • Non-penetration is a constraint, not a penalty to be traded off. Overlap is the contact force divided by the stiffness plus a stated tolerance: under 0.01 in the chamber and in colonies of a few hundred cells.
  • Contact forces only push. A contact carries a force only where its gap is closed.
  • A full space stops growing. The chamber fills to 8–9 cells and holds, and a cell between two walls stalls within 5% of its stall load and stops consuming nutrient.
  • Packing is physical. An unconfined colony packs to 0.92, against about 0.9 reported for rigid-contact models and above 5 for soft-contact models in the literature.
  • Unloaded growth is exact. Without a load response the colony's total length matches the same lineage grown with no mechanics, so contact resolution neither adds nor removes growth.
  • Loads match theory without fitted constants. The radial load profile of a free colony follows the continuum solution within 35% in every bin, and a load-sensitive colony follows the published solution for pressure and expansion speed to about 10%.
  • The trap behaves as a three-wall trap should. Load climbs from the mouth, levels off where it slows growth, and peaks at the back wall, the three regimes reported for this geometry.

Limits of the accuracy claim

  • At the default stiffness, a large colony whose growth ignores load does overlap: 0.11 at 2,000 cells. That is contact compliance under a load that grows with colony size, and it is controlled by the stiffness at the cost above.
  • In a rigid jam, loads above the stall load depend on small leftover overlaps and are not sharply determined.
  • The agreement with continuum theory is for mean loads in radial bins. Individual force chains are several times the mean and have no reference to check against.

Verification

  • 28 native tests pass on a Metal build, including a conformance test that holds Metal to the CPU solution of the same contact systems and to the chamber and free-colony trajectories.
  • 533 Python tests pass; pre-commit is clean.
  • CUDA compiles in nvidia/cuda:12.8.1-devel-ubuntu24.04. It has not been run: no NVIDIA GPU was available.

Closes #53. Closes #51. Supersedes #52.

Simulation.step(dt, ContactDynamicsParameters) advances cell growth and
contact in one convex problem per substep: contact forces are
non-negative, gaps stay non-negative, and a cell's elongation responds
to the axial load its contacts put on it. Rows that the move opens are
added to the same solve, and a substep that fails is retried at half its
length. The CPU backend implements the solve; a backend without the
feature rejects the step.

A box or cylinder container reports one wall contact per face to this
solve, so a cell end in a corner is held by every wall that meets there.

MechanicsConfig(contact_dynamics=ContactDynamicsConfig(...)) selects the
solve in a native controller, and payloads without the entry keep the
relaxation passes.
The projected-gradient iteration is shared: a backend supplies the gap
evaluation and the reductions over its own storage. The Metal backend
keeps the step length and stopping test on the device and runs a batch
of steps per command buffer. The CUDA backend reads the reduced step
terms back each step.

Simulation.solve_contact_system solves a standalone contact system on
the selected backend, and the conformance test holds every backend to
the CPU solution of the same systems and to the chamber and free-colony
trajectories.
A contact that persists from one substep to the next carries nearly the
same force, so the solve of the next substep starts there. A substep is
lengthened only after one that settled within two refinement rounds,
which stops the step length from alternating between one that fails and
one that succeeds.
With flow drift enabled, the velocity and Jeffery rotation the flow gives
each cell enter the contact solve as a known velocity, so contacts resist
the flow pressing cells together instead of correcting overlap after a
separate drift move.

Contacts with constraints use their own stiffness, a hundred times the
cell value by default, so cells rest on a wall within a small fraction of
the overlap they have with each other.

The trap example solves growth and contact together with a linear growth
load response in place of its overlap-based growth rule.
The settled colony's axial load climbs steeply from the trap mouth,
levels off where it slows growth, and peaks against the back wall.
A pair of cells spanning a closed chamber turns out of line when its
growth ignores load, and a perfectly straight pair with a load response
stalls where it is. A colony whose growth falls exponentially with load
follows the published continuum pressure profile and expansion speed.
Contact dynamics is the only contact solve. The regularized
least-squares solve, its conjugate-gradient iteration, the mechanics
integration of its corrections, the wall projection, and their Metal and
CUDA kernels are gone, with the backend feature, bindings, and tests
that served them. No compatibility with the removed solve is kept.

MechanicsConfig holds the contact dynamics parameters directly, and a
controller configured with it solves growth and contact together on
every step. Every example and tutorial model uses it. The planarity
diagnostic observes the contact step in place of relaxation passes.

FlowDriftParameters replaces the integration parameters as the argument
of the standalone flow drift.
@marpaia marpaia changed the title Solve growth and contact together with non-negative contact forces Replace the least-squares relaxation with contact dynamics coupled to growth Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant