From b891e5f773f4f6b9e15e52c307ecd6d1fdde9df7 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Thu, 12 Nov 2026 11:42:06 +0000 Subject: [PATCH 1/2] Scale the implicit signal floor by the operator diagonal The implicit signal solve raises its absolute tolerance to a float32 floor of epsilon times the right-hand side's RMS. The residual is the right-hand side minus the implicit operator applied to the iterate, so its rounding error also grows with the operator's diagonal. On a lattice that is fine along one axis, or under a strong affine loss, the floor sat below what single precision can reach and a step that had little left to resolve ran to the iteration limit and failed. The floor is now multiplied by the largest diagonal entry of the implicit operator. The Danino clock, which stopped at 1,024 cells as its first AHL pulse raised the loss, runs through it. --- cpp/core/signal_jacobi.hpp | 18 +++++++---- cpp/core/signals.cpp | 16 ++++++++++ cpp/cuda/cuda_backend.cu | 9 ++++-- cpp/include/microsimulator/signals.hpp | 6 ++++ cpp/metal/metal_backend.mm | 9 ++++-- .../0008-crank-nicolson-signals.md | 4 +-- tests/cpp/signal_grid_test.cpp | 32 +++++++++++++++++++ 7 files changed, 80 insertions(+), 14 deletions(-) diff --git a/cpp/core/signal_jacobi.hpp b/cpp/core/signal_jacobi.hpp index fda4c41..b33bf56 100644 --- a/cpp/core/signal_jacobi.hpp +++ b/cpp/core/signal_jacobi.hpp @@ -24,6 +24,9 @@ struct SignalJacobiOperations { // Residual RMS of the starting iterate. std::function initial_residual_rms; std::function right_hand_side_rms; + // Largest diagonal entry of the implicit operator, from + // signal_implicit_operator_scale. + float operator_scale{1.0F}; // Called once, before the first sweep, when the starting iterate is not // already converged. std::function begin_sweeps; @@ -40,16 +43,19 @@ struct SignalJacobiOperations { // the threshold and be discarded; scaling by the initial residual asks for a // fixed reduction of whatever this step actually has to resolve. // -// A residual cannot fall below what float32 can represent for a field of this -// magnitude, and the right-hand side carries both the field and the operator -// terms of the step, so it sets that floor. An absolute tolerance asking for -// less than the floor is raised to it rather than making the solve -// unreachable. +// A residual cannot fall below what float32 can represent. It is the +// difference between the right-hand side and the implicit operator applied to +// the iterate, so its rounding error scales with the field's magnitude, which +// the right-hand side carries, times the operator's largest diagonal entry: a +// fine lattice or a strong loss makes that entry large and the reachable +// residual correspondingly coarser. An absolute tolerance asking for less +// than this floor is raised to it rather than making the solve unreachable. [[nodiscard]] inline SignalSolveReport solve_signal_jacobi( const SignalJacobiOperations& operations, const SignalSolveParameters& parameters) { SignalSolveReport report; report.residual_rms = operations.initial_residual_rms(); - const auto floor = std::numeric_limits::epsilon() * operations.right_hand_side_rms(); + const auto floor = std::numeric_limits::epsilon() * operations.right_hand_side_rms() * + operations.operator_scale; const auto threshold = std::max(parameters.absolute_tolerance, floor) + (parameters.relative_tolerance * report.residual_rms); if (std::isfinite(report.residual_rms) && report.residual_rms <= threshold) { diff --git a/cpp/core/signals.cpp b/cpp/core/signals.cpp index 9bb2c2d..496e81f 100644 --- a/cpp/core/signals.cpp +++ b/cpp/core/signals.cpp @@ -331,6 +331,21 @@ SignalGridStencil signal_grid_stencil(const SignalGridSpec& spec, Vec3 position, return result; } +float signal_implicit_operator_scale(const SignalGridSpec& spec, float implicit_dt) { + auto scale = 1.0F; + for (std::size_t signal = 0; signal < spec.signal_count; ++signal) { + for (std::uint32_t x = 0; x < spec.shape.x; ++x) { + for (std::uint32_t y = 0; y < spec.shape.y; ++y) { + for (std::uint32_t z = 0; z < spec.shape.z; ++z) { + scale = std::max(scale, + 1.0F - (implicit_dt * signal_operator_diagonal(spec, signal, x, y, z))); + } + } + } + } + return scale; +} + void GridBoundary::validate(std::size_t signal_count) const { switch (kind) { case GridBoundaryKind::no_flux: @@ -911,6 +926,7 @@ SignalSolveResult signal_grid_crank_nicolson_candidate(const SignalGrid& grid, f const detail::SignalJacobiOperations operations{ .initial_residual_rms = residual_rms, .right_hand_side_rms = [&] { return rms(right_hand_side); }, + .operator_scale = signal_implicit_operator_scale(spec, half_dt), .begin_sweeps = [] {}, .sweep = [&] { diff --git a/cpp/cuda/cuda_backend.cu b/cpp/cuda/cuda_backend.cu index 8731b31..7408caf 100644 --- a/cpp/cuda/cuda_backend.cu +++ b/cpp/cuda/cuda_backend.cu @@ -395,7 +395,8 @@ class CudaBackend final : public ComputeBackend { signal_reaction_loss_.data(), signal_obstacles_.data(), signal_x_faces_.data(), signal_y_faces_.data(), signal_z_faces_.data(), has_velocity_field, signal_error_.data(), boundaries, shape, make_float4(spec.spacing.x, spec.spacing.y, spec.spacing.z, 0.0F), - (crank_nicolson == 2 ? dt : 0.5F * dt), signal_count, level_count, spec.solver); + (crank_nicolson == 2 ? dt : 0.5F * dt), signal_count, level_count, spec.solver, + signal_implicit_operator_scale(spec, crank_nicolson == 2 ? dt : 0.5F * dt)); result_device = solve.first; report = solve.second; if (!report.converged) { @@ -647,7 +648,8 @@ class CudaBackend final : public ComputeBackend { coupled_error_.data(), boundaries, shape, make_float4(spec.spacing.x, spec.spacing.y, spec.spacing.z, 0.0F), (crank_nicolson == 2 ? dt : 0.5F * dt), static_cast(signal_count_size), - static_cast(grid_level_count), spec.solver); + static_cast(grid_level_count), spec.solver, + signal_implicit_operator_scale(spec, crank_nicolson == 2 ? dt : 0.5F * dt)); result_device = solve.first; report = solve.second; if (!report.converged) { @@ -1337,7 +1339,7 @@ class CudaBackend final : public ComputeBackend { const float* y_faces, const float* z_faces, std::uint32_t has_velocity_field, std::uint32_t* error, cuda::SignalGridBoundariesGpu boundaries, cuda::SignalGridShapeGpu shape, float4 spacing, float dt, std::uint32_t signal_count, - std::uint32_t level_count, const SignalSolveParameters& parameters) { + std::uint32_t level_count, const SignalSolveParameters& parameters, float operator_scale) { ensure_signal_solve_capacity(level_count); const auto half_dt = dt; const float* current = initial; @@ -1350,6 +1352,7 @@ class CudaBackend final : public ComputeBackend { shape, spacing, half_dt, signal_count, level_count); }, .right_hand_side_rms = [&] { return signal_rhs_rms(right_hand_side, level_count); }, + .operator_scale = operator_scale, .begin_sweeps = [&] { check_cuda(cudaMemsetAsync(error, 0, sizeof(std::uint32_t), stream_), diff --git a/cpp/include/microsimulator/signals.hpp b/cpp/include/microsimulator/signals.hpp index 76439a8..030acae 100644 --- a/cpp/include/microsimulator/signals.hpp +++ b/cpp/include/microsimulator/signals.hpp @@ -123,6 +123,12 @@ enum class GridSampleBound : std::uint8_t { inside, clamped }; [[nodiscard]] SignalGridStencil signal_grid_stencil( const SignalGridSpec& spec, Vec3 position, GridSampleBound bound = GridSampleBound::inside); +// Largest diagonal entry of the operator an implicit step of `implicit_dt` +// solves, I - implicit_dt * L, where L is the grid's transport and loss +// operator. It is at least one, and grows with diffusion over the squared +// spacing, outflow, and loss. +[[nodiscard]] float signal_implicit_operator_scale(const SignalGridSpec& spec, float implicit_dt); + class SignalGrid { public: explicit SignalGrid(const SignalGridSpec& spec, std::vector levels = {}); diff --git a/cpp/metal/metal_backend.mm b/cpp/metal/metal_backend.mm index dea047d..ee04908 100644 --- a/cpp/metal/metal_backend.mm +++ b/cpp/metal/metal_backend.mm @@ -505,7 +505,8 @@ SignalSolveReport advance_signal_grid(SignalGrid& grid, float dt) override { signal_fixed_values_, signal_reaction_source_, signal_reaction_loss_, signal_obstacles_, signal_x_faces_, signal_y_faces_, signal_z_faces_, has_velocity_field, signal_error_, boundary_kinds, shape, spacing, (crank_nicolson == 2 ? dt : 0.5F * dt), signal_count, - level_count, spec.solver); + level_count, spec.solver, + signal_implicit_operator_scale(spec, crank_nicolson == 2 ? dt : 0.5F * dt)); result_buffer = solve.first; report = solve.second; if (!report.converged) { @@ -727,7 +728,8 @@ SignalSolveReport advance_coupled(WorldState& state, SignalGrid& grid, coupled_fixed_values_, coupled_reaction_source_, coupled_reaction_loss_, coupled_obstacles_, coupled_x_faces_, coupled_y_faces_, coupled_z_faces_, has_velocity_field, coupled_error_, boundary_kinds, shape, spacing, - (crank_nicolson == 2 ? dt : 0.5F * dt), signal_count, level_count, spec.solver); + (crank_nicolson == 2 ? dt : 0.5F * dt), signal_count, level_count, spec.solver, + signal_implicit_operator_scale(spec, crank_nicolson == 2 ? dt : 0.5F * dt)); result_buffer = solve.first; report = solve.second; if (!report.converged) { @@ -1136,7 +1138,7 @@ void ensure_signal_solve_capacity(std::uint32_t level_count) { id y_faces, id z_faces, std::uint32_t has_velocity_field, id error, const std::array& boundary_kinds, const MetalGridShape& shape, const MetalFloat4& spacing, float dt, std::uint32_t signal_count, - std::uint32_t level_count, const SignalSolveParameters& parameters) { + std::uint32_t level_count, const SignalSolveParameters& parameters, float operator_scale) { ensure_signal_solve_capacity(level_count); const auto half_dt = dt; id current = initial; @@ -1149,6 +1151,7 @@ void ensure_signal_solve_capacity(std::uint32_t level_count) { boundary_kinds, shape, spacing, half_dt, signal_count, level_count); }, .right_hand_side_rms = [&] { return signal_rhs_rms(right_hand_side, level_count); }, + .operator_scale = operator_scale, .begin_sweeps = [&] { *static_cast(error.contents) = 0; }, .sweep = [&] { diff --git a/docs/architecture/0008-crank-nicolson-signals.md b/docs/architecture/0008-crank-nicolson-signals.md index 6f5f0d4..26fb839 100644 --- a/docs/architecture/0008-crank-nicolson-signals.md +++ b/docs/architecture/0008-crank-nicolson-signals.md @@ -30,13 +30,13 @@ The linear system is solved by matrix-free Jacobi iteration over the local trans Convergence uses the RMS residual of the declared equation: ```text -residual_rms <= max(absolute_tolerance, epsilon * rms(right_hand_side)) +residual_rms <= max(absolute_tolerance, epsilon * rms(right_hand_side) * operator_scale) + relative_tolerance * initial_residual_rms ``` The relative term scales the residual the step begins with, not the field it begins from. A field's magnitude says nothing about how much of it one step has to change, so scaling by the field makes the threshold grow with the background: a cell's exchange with a well-stocked field then falls under it and the solve returns the old field, discarding the source. Scaling by the initial residual instead asks for a fixed reduction of whatever this step actually has to resolve, so the accuracy a model gets is the accuracy it asked for, independent of concentration scale. -The absolute term is raised to the residual floor of the field, `epsilon * rms(right_hand_side)` in float32. The right-hand side carries both the field and the step's operator terms, so this tracks stiffness as well as magnitude. A tolerance below the floor is unreachable, and clamping it up converges rather than iterating to the limit on rounding noise. The floor is also the resolution limit of an implicit step: a source that moves the field by less than its own float32 resolution leaves no residual to detect, and the step converges without it. A model whose exchange is that small next to its background belongs on forward Euler, which applies sources unconditionally, or on a concentration scale that resolves it. +The absolute term is raised to the residual floor of the field, `epsilon * rms(right_hand_side) * operator_scale` in float32. The residual is the difference between the right-hand side and the implicit operator applied to the iterate, so its rounding error scales with the field's magnitude, which the right-hand side carries, times `operator_scale`, the largest diagonal entry of the implicit operator. That entry is one plus the step times the largest sum of diffusive, outflow, and loss rates at a site, so a lattice that is fine along any axis or a strong affine loss raises the floor. A tolerance below the floor is unreachable, and clamping it up converges rather than iterating to the limit on rounding noise. The floor is also the resolution limit of an implicit step: a source that moves the field by less than its own float32 resolution leaves no residual to detect, and the step converges without it. A model whose exchange is that small next to its background belongs on forward Euler, which applies sources unconditionally, or on a concentration scale that resolves it. The grid specification records the integration kind, maximum iteration count, and both tolerances. These fields are exact checkpoint state, so a checkpoint written before this rule resumes with the tolerances it recorded and the current interpretation of them. A solver that reaches the iteration limit or produces a non-finite residual fails the step; it never commits an unconverged field. A successful step exposes its iteration count and final residual. Final concentrations retain the engine-wide finite, non-negative invariant. Crank-Nicolson is stable for large diffusion steps but is not positivity preserving, so an oscillatory negative result is rejected. diff --git a/tests/cpp/signal_grid_test.cpp b/tests/cpp/signal_grid_test.cpp index 747ca76..9b5d7c2 100644 --- a/tests/cpp/signal_grid_test.cpp +++ b/tests/cpp/signal_grid_test.cpp @@ -577,4 +577,36 @@ int main() { assert_close(frozen.cell(frozen_id).direction.x, 0.0F); assert_close(frozen.cell(frozen_id).direction.y, 1.0F); } + { + // A lattice fine enough through the depth that the implicit operator's + // diagonal is several times the identity. The residual of a field near + // ten cannot reach the default absolute tolerance in single precision, so + // the solve converges only if its floor accounts for that diagonal. + microsimulator::SignalGridSpec spec; + spec.signal_count = 1; + spec.shape = {4, 8, 4}; + spec.spacing = {2.0F, 2.0F, 0.75F}; + spec.diffusion = {40.0F}; + spec.advection = {microsimulator::Vec3{}}; + spec.integration = microsimulator::SignalIntegrationKind::backward_euler; + spec.y_lower.kind = microsimulator::GridBoundaryKind::fixed; + spec.y_lower.values = {10.0F}; + spec.y_upper.kind = microsimulator::GridBoundaryKind::fixed; + spec.y_upper.values = {0.0F}; + const auto dt = 0.02F; + const auto interior_diagonal = 2.0F * 40.0F * (0.25F + 0.25F + (1.0F / 0.5625F)); + const auto scale = microsimulator::signal_implicit_operator_scale(spec, dt); + assert(scale >= 1.0F + (dt * interior_diagonal)); + assert(scale <= 1.0F + (dt * (interior_diagonal + 20.0F)) + 1.0e-3F); + + // As the field settles toward its steady profile each step starts with + // less to resolve, until the floor alone decides convergence. + microsimulator::SignalGrid grid(spec, std::vector(spec.level_count(), 10.0F)); + for (int step = 0; step < 1500; ++step) { + const auto report = microsimulator::advance_signal_grid_cpu(grid, dt); + assert(report.converged); + assert(report.iterations < 200); + } + } + } From 8e54d7e4a592ca0627ed9ffeff8899d0505265de Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Thu, 12 Nov 2026 11:42:06 +0000 Subject: [PATCH 2/2] Size the trap example to a monolayer of a few hundred cells The trap was 120 by 30 by 6 micrometers, six cell layers deep, and held several thousand cells before any could leave it, so a run slowed long before it reached a steady state. It is now 40 by 20 by 1.5 beside a 20-wide channel, on a lattice whose fluid sites span the device exactly. Growth is multiplied by a compression factor that falls to zero as a cell's deepest overlap with a neighbor reaches a fifth of its diameter. Without it the packed colony keeps elongating into itself faster than contact relaxation can push cells out of the trap mouth. With it the trap holds about 280 cells, sheds cells into the channel continuously, and settles near 320 in total. --- README.md | 2 +- docs/tutorials/microfluidics.md | 6 ++- docs/tutorials/planarity.md | 3 +- examples/microfluidic_trap.py | 62 ++++++++++++++++++++++++------ python/tests/test_microfluidics.py | 43 +++++++++++++++------ 5 files changed, 90 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 797de17..fa18ff8 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ uv run microsimulator view \ --open ``` -This opens a cell trap supplied with nutrient through a flowing channel in the live viewer. Press **Play** to watch the colony grow, choose `Growth rate` coloring to see how nutrient supply shapes the population, and click a cell to inspect it. **Stop session** or Ctrl+C in the terminal ends the run. +This opens a cell trap supplied with nutrient through a flowing channel in the live viewer. Press **Play** to watch the colony fill the trap and spill into the channel, where the flow carries cells to the outlet. Choose `Growth rate` coloring to see the packed interior stop growing while the cells at the trap mouth keep dividing, and click a cell to inspect it. **Stop session** or Ctrl+C in the terminal ends the run. The same model runs headlessly with `microsimulator run`, which saves a restartable checkpoint: diff --git a/docs/tutorials/microfluidics.md b/docs/tutorials/microfluidics.md index a4330e6..01dfc8f 100644 --- a/docs/tutorials/microfluidics.md +++ b/docs/tutorials/microfluidics.md @@ -11,7 +11,7 @@ The microfluidic-trap, Danino, biopixel, and pillar tutorial founders request ce | Model | Device | Demonstrates | | --- | --- | --- | | [`examples/culture_dish.py`](../../examples/culture_dish.py) | round dish | one inside-cylinder constraint as a dish | -| [`examples/microfluidic_trap.py`](../../examples/microfluidic_trap.py) | trap + channel | flow, obstacles, drift, washout | +| [`examples/microfluidic_trap.py`](../../examples/microfluidic_trap.py) | monolayer trap + channel | flow, obstacles, drift, crowding-limited growth, washout | | [`examples/tutorials/danino_clock.py`](../../examples/tutorials/danino_clock.py) | trap + channel | the full quorum clock in a device | | [`examples/tutorials/biopixel_trap.py`](../../examples/tutorials/biopixel_trap.py) | biopixel array trap | reported cavity, CAD layout, monolayer model | @@ -21,6 +21,8 @@ Run any of them live: uv run microsimulator view --model examples/microfluidic_trap.py --seed 42 --dt 0.02 --backend cpu --open ``` +The trap example is sized to one population: a 40 by 20 micrometer trap, 1.5 micrometers deep, beside a 20 micrometer channel. A few hundred cells fill it as a monolayer. Its growth rule multiplies the Monod rate by a compression factor that falls linearly to zero as a cell's deepest overlap with a neighbor reaches a fifth of its diameter, so the packed interior stops elongating while cells at the mouth keep growing, spill into the channel, and wash out. The population settles near 320 cells with continuous turnover. The compression limit is a model choice, not a measured mechanical response. + ## Walls that cells and chemistry both respect Mechanical walls are typed external constraints: infinite planes, spheres, axis-aligned @@ -59,7 +61,7 @@ DEVICE.apply_to_grid( ) ``` -`apply_to_grid` materializes the solid mask, fixed inlet and outlet boundaries on the y axis, and the numerically solved steady device flow on the grid's face-staggered velocity field (see the next section). Passing the model's `Simulation` makes the solve execute through the backend selected by the runner. Flow runs through the channel, circulates weakly at the open trap face, and the dead-end trap exchanges with the channel chiefly by diffusion in this model. +The constructor's keyword arguments set the trap, channel, and wall dimensions; the trap example passes its own, and the Danino clock uses the defaults. `apply_to_grid` materializes the solid mask, fixed inlet and outlet boundaries on the y axis, and the numerically solved steady device flow on the grid's face-staggered velocity field (see the next section). Passing the model's `Simulation` makes the solve execute through the backend selected by the runner. Flow runs through the channel, circulates weakly at the open trap face, and the dead-end trap exchanges with the channel chiefly by diffusion in this model. ## Flow on signals and on cells diff --git a/docs/tutorials/planarity.md b/docs/tutorials/planarity.md index 2af6cab..ed04ee7 100644 --- a/docs/tutorials/planarity.md +++ b/docs/tutorials/planarity.md @@ -19,7 +19,8 @@ The following contracts describe the checked-in models after the founder-initial | `simbol_circuits.py`: all six circuits | Centers Z=0, directions in XY; XY-only jitter | No mechanical walls; unrestricted 3D. | | `plasmid_segregation.py`, `conjugation.py` | Centers Z=0, directions in XY; no orientation jitter | Division inherits the parent axis; contact mechanics remains unrestricted 3D. | | `pillar_channel.py` | Centers Z=0, directions in XY; XY-only jitter | Box walls at Z=±3 and cylindrical pillars. Attached cells are fixed; released daughters move in a finite-height 3D chamber. | -| `danino_clock.py`, `examples/microfluidic_trap.py` | Centers Z=0, directions in XY; XY-only jitter | Trap walls at Z=±3. These permit nonzero Z and tilt within a finite-height 3D device. | +| `danino_clock.py` | Centers Z=0, directions in XY; XY-only jitter | Trap walls at Z=±3. These permit nonzero Z and tilt within a finite-height 3D device. | +| `examples/microfluidic_trap.py` | Centers Z=0, directions in XY; XY-only jitter | Device walls at Z=±0.75, half again a cell's diameter apart. The thin device holds a monolayer but does not force identical center Z or zero tilt. | | `biopixel_trap.py` | Centers Z=0.825, directions in XY; XY-only jitter | Trap floor Z=0 and roof Z=1.65; the channel is taller. The thin trap encourages a monolayer but does not force identical center Z or zero tilt. | | `examples/culture_dish.py` | Centers Z=0, directions in XY; XY-only jitter | Inside cylinder with caps at Z=±1. Finite-height confinement permits nonzero Z and tilt. | diff --git a/examples/microfluidic_trap.py b/examples/microfluidic_trap.py index 0dd2bdb..0cbecd5 100644 --- a/examples/microfluidic_trap.py +++ b/examples/microfluidic_trap.py @@ -8,6 +8,11 @@ nutrient at a fixed yield, so the colony's growth pattern reflects the balance between flow supply, diffusion into the trap, and consumption by the cells already there. + +The trap is a monolayer that a few hundred cells fill. A cell pressed into its +neighbors stops elongating, so the packed colony holds its density while the +cells at the trap mouth, which have room, keep growing, spill into the channel, +and are carried to the outlet. The population settles at a steady turnover. """ from __future__ import annotations @@ -37,12 +42,24 @@ from microsimulator.microfluidics import TrapChannelDevice MODEL_ID = "examples.microfluidic-trap" -MODEL_VERSION = 4 +MODEL_VERSION = 5 DIVISION = UniformLengthDivision(3.2, 3.8, jitter_z=False) FLOW_SPEED = 20.0 -DEVICE = TrapChannelDevice(mean_flow_speed=FLOW_SPEED) CELL_RADIUS = 0.5 +# Lengths are micrometers. The device is 1.5 deep, half again a cell's +# diameter, so the colony is a monolayer, and the trap is 40 long by 20 wide, +# which a few hundred cells fill. From then on growth pushes cells out of the +# trap mouth into the 20-wide channel, where the flow carries them away. +DEVICE = TrapChannelDevice( + trap_open_x=-20.0, + trap_back_x=20.0, + trap_half_y=10.0, + trap_half_z=0.75, + channel_far_x=-40.0, + channel_half_length=60.0, + mean_flow_speed=FLOW_SPEED, +) NUTRIENT_INLET = 10.0 BASE_GROWTH_RATE = 1.0 NUTRIENT_K = 5.0 @@ -50,6 +67,12 @@ # the actual increase of B = pi*r^2*(length + 2*r), divided by this yield. # The value is illustrative; penetration and growth require refinement checks. NUTRIENT_YIELD = 0.5 +# Growth stops under compression: a cell whose deepest overlap with a neighbor +# reaches this depth does not elongate, and growth falls off linearly up to +# it. Contact relaxation spreads overlap over several steps, so growth that +# ignored it would keep packing cells into a full trap. The value is a model +# choice, a fifth of a cell's diameter, not a measured mechanical response. +COMPRESSION_LIMIT = 0.2 WASHOUT_Y = DEVICE.channel_half_length - 10.0 # Resistance feedback uses only fixed (attached) cells, with a physical @@ -60,16 +83,16 @@ def _grid(simulation: Simulation | None = None) -> SignalGridSpec: shape = GridShape() - shape.x, shape.y, shape.z = 64, 72, 6 + shape.x, shape.y, shape.z = 39, 66, 6 grid = SignalGridSpec() grid.signal_count = 1 grid.shape = shape - # Two z layers span the trap's six-micrometer depth exactly, so its fluid - # volume is the device's rather than the half voxel of slack a coarser - # lattice would leave on each side, and the lattice still reaches a voxel - # past the walls, because sampling outside the lattice is an error. - grid.origin = Vec3(-140.0, -144.0, -7.5) - grid.spacing = Vec3(4.0, 4.0, 3.0) + # Every wall lies midway between two planes of site centers, so the fluid + # sites span exactly the device: ten across the channel, twenty along the + # trap, and two through the depth. The lattice still reaches past the + # walls, because sampling outside the lattice is an error. + grid.origin = Vec3(-47.0, -65.0, -1.875) + grid.spacing = Vec3(2.0, 2.0, 0.75) grid.diffusion = [40.0] grid.advection = [Vec3()] grid.integration = SignalIntegrationKind.BACKWARD_EULER @@ -106,6 +129,18 @@ def _nutrient_growth(simulation: Simulation, position: Vec3) -> float: return BASE_GROWTH_RATE * nutrient / (NUTRIENT_K + nutrient) +def _compression(simulation: Simulation) -> dict[int, float]: + """Each cell's deepest overlap with a neighbor, for the cells that have one.""" + + deepest: dict[int, float] = {} + for contact in simulation.find_cell_contacts().contacts: + overlap = -contact.signed_separation + if overlap > 0.0: + for cell_id in (contact.first_id, contact.second_id): + deepest[cell_id] = max(deepest.get(cell_id, 0.0), overlap) + return deepest + + def _regulate(step: ControllerStep) -> StepPlan: if step.completed_steps and step.completed_steps % RESOLVE_INTERVAL == 0: mobility = colony_mobility( @@ -124,9 +159,14 @@ def _regulate(step: ControllerStep) -> StepPlan: if washed: DIVISION.forget(step, washed) divisions = tuple(request for request in divisions if request.parent_id not in washed) + compression = _compression(step.simulation) return StepPlan( updates=tuple( - CellUpdate(cell.id, growth_rate=_nutrient_growth(step.simulation, cell.position)) + CellUpdate( + cell.id, + growth_rate=_nutrient_growth(step.simulation, cell.position) + * max(0.0, 1.0 - compression.get(cell.id, 0.0) / COMPRESSION_LIMIT), + ) for cell in step.cells if cell.id not in washed ), @@ -140,7 +180,7 @@ def _divided(step: ControllerStep, event: DivisionEvent) -> None: def build(context: ModelContext) -> NativeController: - simulation = context.simulation(reserved_capacity=10_000) + simulation = context.simulation(reserved_capacity=2_000) grid = _grid(simulation) simulation.configure_signal_grid(grid, _primed_levels(grid)) simulation.set_coupled_rate_plan(_rate_plan()) diff --git a/python/tests/test_microfluidics.py b/python/tests/test_microfluidics.py index 6b806b8..7ac46bb 100644 --- a/python/tests/test_microfluidics.py +++ b/python/tests/test_microfluidics.py @@ -3,6 +3,7 @@ from __future__ import annotations import math +import runpy from pathlib import Path import pytest @@ -149,6 +150,12 @@ def test_planar_mask_wall_error_is_bounded_by_half_spacing() -> None: assert abs(upper - device.trap_back_x) <= h / 2 + 1e-5 +def _trap_example_device() -> TrapChannelDevice: + device = runpy.run_path(str(_EXAMPLES / "microfluidic_trap.py"))["DEVICE"] + assert isinstance(device, TrapChannelDevice) + return device + + def test_trap_example_builds_steps_and_transports_nutrient() -> None: model, _ = build_model( _EXAMPLES / "microfluidic_trap.py", @@ -159,37 +166,51 @@ def test_trap_example_builds_steps_and_transports_nutrient() -> None: model.step(0.02) simulation = model.simulation - device = TrapChannelDevice() + device = _trap_example_device() channel_x = (device.channel_far_x + device.trap_open_x) * 0.5 - upstream = simulation.sample_signals(Vec3(channel_x, -100.0, 0.0))[0] + upstream_y = -device.channel_half_length + 10.0 + upstream = simulation.sample_signals(Vec3(channel_x, upstream_y, 0.0))[0] trap_interior = simulation.sample_signals(Vec3(0.0, 0.0, 0.0))[0] assert upstream > 5.0 assert trap_interior > 5.0 assert upstream >= trap_interior - 1.0e-3 with pytest.raises(ValueError, match="inside a grid obstacle"): - simulation.sample_signals(Vec3(0.0, 100.0, 0.0)) + simulation.sample_signals(Vec3(0.0, device.trap_half_y + 20.0, 0.0)) assert len(simulation.cells()) >= 1 -def test_crowded_trap_colony_stays_inside_the_walls() -> None: +def test_trap_example_fills_and_settles_at_a_steady_turnover() -> None: model, _ = build_model( _EXAMPLES / "microfluidic_trap.py", ModelContext(BackendKind.CPU, 0, seed=42), ) assert isinstance(model, SimulationController) - # Long enough for the colony to span the trap and press on all three walls. - for _ in range(620): + simulation = model.simulation + device = _trap_example_device() + populations: list[int] = [] + # Long enough for the colony to fill the trap, press on all three walls, + # and shed cells into the channel for several doubling times. + for step in range(1, 1501): model.step(0.02) + if step % 100 == 0: + populations.append(len(simulation.cells())) - simulation = model.simulation - device = TrapChannelDevice() cells = simulation.cells() - assert len(cells) >= 200 + in_trap = [cell for cell in cells if cell.position.x > device.trap_open_x] + in_channel = [cell for cell in cells if cell.position.x <= device.trap_open_x] + # A monolayer of this footprint holds a few hundred cells, and the trap + # stays full while cells keep leaving through its mouth. + assert 150 <= len(in_trap) <= 450 + assert in_channel + assert max(cell.id for cell in cells) > 3 * len(cells) + settled = populations[-5:] + assert max(settled) - min(settled) <= 0.15 * max(settled) + walls = simulation.find_external_contacts().contacts assert walls # Resting depth of the wall projection, with room for its last sweep. - assert min(contact.signed_separation for contact in walls) >= -1.0e-3 - slack = 1.0e-3 + assert min(contact.signed_separation for contact in walls) >= -2.0e-3 + slack = 2.0e-3 for cell in cells: reach = abs(cell.direction.x) * cell.length * 0.5 + cell.radius assert cell.position.x + reach <= device.trap_back_x + slack