diff --git a/cpp/core/mechanics_integration.cpp b/cpp/core/mechanics_integration.cpp index 5cea414..e41d3c0 100644 --- a/cpp/core/mechanics_integration.cpp +++ b/cpp/core/mechanics_integration.cpp @@ -41,6 +41,42 @@ void validate_mechanics_integration_parameters(const MechanicsIntegrationParamet } } +void validate_growth_limit_parameters(const GrowthLimitParameters& parameters) { + if (!std::isfinite(parameters.free_overlap) || parameters.free_overlap < 0.0F || + !std::isfinite(parameters.stall_overlap) || + parameters.stall_overlap <= parameters.free_overlap) { + throw std::invalid_argument( + "growth limit overlaps must be finite, non-negative, and increasing"); + } +} + +std::vector growth_limit_factors(const WorldState& state, const ContactGraph& contacts, + const GrowthLimitParameters& parameters) { + validate_growth_limit_parameters(parameters); + if (contacts.cell_count() != state.size()) { + throw std::invalid_argument("contact graph and world state cell counts disagree"); + } + std::vector deepest(state.size(), 0.0F); + for (const auto& contact : contacts.contacts()) { + const auto overlap = -contact.signed_separation; + for (const auto slot : {contact.first_slot, contact.second_slot}) { + auto& depth = deepest[static_cast(slot)]; + depth = std::max(depth, overlap); + } + } + const auto radii = state.geometry_state().radii; + const auto band = parameters.stall_overlap - parameters.free_overlap; + std::vector factors(state.size(), 1.0F); + for (std::size_t slot = 0; slot < factors.size(); ++slot) { + if (radii[slot] <= 0.0F) { + continue; + } + const auto excess = (deepest[slot] / radii[slot]) - parameters.free_overlap; + factors[slot] = std::clamp(1.0F - (excess / band), 0.0F, 1.0F); + } + return factors; +} + void integrate_mechanics_result(WorldState& state, const MechanicsSolveResult& result, const MechanicsIntegrationParameters& parameters, std::span desired_length_increments) { diff --git a/cpp/core/simulation.cpp b/cpp/core/simulation.cpp index d110152..87b0da5 100644 --- a/cpp/core/simulation.cpp +++ b/cpp/core/simulation.cpp @@ -312,11 +312,27 @@ std::pair Simulation::divide_equal(CellId parent_id) { } void Simulation::step(float dt) { + advance(dt, nullptr); +} + +void Simulation::step(float dt, const GrowthLimitParameters& growth_limit) { + validate_growth_limit_parameters(growth_limit); + advance(dt, &growth_limit); +} + +void Simulation::advance(float dt, const GrowthLimitParameters* growth_limit) { if (!std::isfinite(dt) || dt < 0.0F) { throw std::invalid_argument("time step must be finite and non-negative"); } const auto geometry = state_.geometry_state(); const std::vector previous_lengths(geometry.lengths.begin(), geometry.lengths.end()); + // Compression is read from the geometry the step starts from, which is the + // outcome of the previous step's relaxation. + std::vector growth_factors; + if (growth_limit != nullptr && !state_.empty()) { + growth_factors = growth_limit_factors( + state_, backend_->find_cell_contacts(state_, growth_limit->contacts), *growth_limit); + } if (coupled_rate_plan_.has_value()) { if (!backend_->supports(BackendFeature::coupled_rates)) { throw std::runtime_error("selected backend does not implement coupled rates"); @@ -346,6 +362,15 @@ void Simulation::step(float dt) { })) { throw std::runtime_error("growth produced a non-finite or negative cell length"); } + if (!growth_factors.empty()) { + const auto lengths = state_.growth_state().lengths; + for (std::size_t slot = 0; slot < lengths.size(); ++slot) { + const auto elongation = lengths[slot] - previous_lengths[slot]; + if (elongation > 0.0F) { + lengths[slot] = previous_lengths[slot] + (growth_factors[slot] * elongation); + } + } + } last_signal_solve_report_.reset(); if (coupled_rate_plan_.has_value()) { last_signal_solve_report_ = backend_->advance_coupled( diff --git a/cpp/include/microsimulator/mechanics.hpp b/cpp/include/microsimulator/mechanics.hpp index d56f95d..754bec3 100644 --- a/cpp/include/microsimulator/mechanics.hpp +++ b/cpp/include/microsimulator/mechanics.hpp @@ -55,8 +55,26 @@ struct MechanicsIntegrationParameters { bool require_convergence{true}; }; +// Growth that responds to compression. A cell's elongation over a step is +// scaled by a factor that is one while its deepest overlap with a neighbor is +// at most `free_overlap` cell radii and falls linearly to zero at +// `stall_overlap` radii. Contact relaxation leaves a small overlap between +// growing neighbors that are free to move, which the free band ignores; a cell +// that relaxation cannot separate from its neighbors stops elongating. +struct GrowthLimitParameters { + float free_overlap{0.1F}; + float stall_overlap{0.4F}; + ContactParameters contacts; +}; + void validate_mechanics_parameters(const MechanicsParameters& parameters); void validate_mechanics_integration_parameters(const MechanicsIntegrationParameters& parameters); +void validate_growth_limit_parameters(const GrowthLimitParameters& parameters); + +// The factor by which compression scales each cell's elongation, one per slot. +[[nodiscard]] std::vector growth_limit_factors(const WorldState& state, + const ContactGraph& contacts, + const GrowthLimitParameters& parameters); // The axis-angle rotation of a unit direction by a rotation vector, with the // angle capped at ``max_rotation``. diff --git a/cpp/include/microsimulator/simulation.hpp b/cpp/include/microsimulator/simulation.hpp index 8a899fc..8743b35 100644 --- a/cpp/include/microsimulator/simulation.hpp +++ b/cpp/include/microsimulator/simulation.hpp @@ -51,6 +51,10 @@ class Simulation { std::pair divide(CellId parent_id, float first_fraction); std::pair divide_equal(CellId parent_id); void step(float dt); + // A step whose growth responds to compression: each cell's elongation is + // scaled by its growth limit factor before species and signals advance, so + // they see the growth that happened. + void step(float dt, const GrowthLimitParameters& growth_limit); [[nodiscard]] ContactGraph find_cell_contacts( const ContactParameters& parameters = ContactParameters{}); [[nodiscard]] ExternalContactGraph find_external_contacts( @@ -81,6 +85,8 @@ class Simulation { void validate() const; private: + void advance(float dt, const GrowthLimitParameters* growth_limit); + WorldState state_; ConstraintSet constraints_; std::unique_ptr backend_; diff --git a/cpp/python/bindings.cpp b/cpp/python/bindings.cpp index 11c1f76..12dab8f 100644 --- a/cpp/python/bindings.cpp +++ b/cpp/python/bindings.cpp @@ -505,6 +505,12 @@ NB_MODULE(_core, module) { .def_rw("require_convergence", µsimulator::MechanicsIntegrationParameters::require_convergence); + nb::class_(module, "GrowthLimitParameters") + .def(nb::init<>()) + .def_rw("free_overlap", µsimulator::GrowthLimitParameters::free_overlap) + .def_rw("stall_overlap", µsimulator::GrowthLimitParameters::stall_overlap) + .def_rw("contacts", µsimulator::GrowthLimitParameters::contacts); + nb::class_(module, "SolverReport") .def_ro("status", µsimulator::SolverReport::status) .def_ro("breakdown", µsimulator::SolverReport::breakdown) @@ -606,7 +612,17 @@ NB_MODULE(_core, module) { .def("divide_equal", microsimulator::python::exclusive(µsimulator::Simulation::divide_equal), "parent_id"_a) - .def("step", microsimulator::python::released(µsimulator::Simulation::step), "dt"_a) + .def( + "step", + microsimulator::python::released(static_cast( + µsimulator::Simulation::step)), + "dt"_a) + .def("step", + microsimulator::python::released( + static_cast( + µsimulator::Simulation::step)), + "dt"_a, "growth_limit"_a) .def("find_cell_contacts", microsimulator::python::released(µsimulator::Simulation::find_cell_contacts), "parameters"_a = microsimulator::ContactParameters{}) diff --git a/docs/architecture/0002-contact-mechanics.md b/docs/architecture/0002-contact-mechanics.md index a640374..6c00e2b 100644 --- a/docs/architecture/0002-contact-mechanics.md +++ b/docs/architecture/0002-contact-mechanics.md @@ -35,6 +35,16 @@ The reference solver starts from zero and uses unpreconditioned conjugate gradie Integration is a separate backend-neutral operation over a solver result. It requires convergence by default, applies translation directly, interprets the rotation vector as axis-angle and caps it at five degrees, and computes the length increment as `max(0, desired_increment + delta_l)`. Mechanics may suppress requested elongation but may not directly shorten a cell. All updates are validated before any world-state array is mutated. `Simulation.step` remains the growth-only primitive; `relax_cell_mechanics` is the explicit contact-relaxation operation. +### Growth under compression + +`Simulation.step` commits growth before any relaxation runs, and `relax_cell_mechanics` integrates without length increments, so on their own growth and contact do not interact: a colony with nowhere to go keeps elongating into itself. `Simulation.step(dt, GrowthLimitParameters)` makes growth respond to compression. Before growth it finds the cell contacts of the geometry the step starts from, which is the outcome of the previous step's relaxation, and takes each cell's deepest overlap with a neighbor in units of that cell's radius. A cell's elongation over the step is multiplied by a factor that is one up to `free_overlap`, falls linearly, and is zero from `stall_overlap`. The defaults are 0.1 and 0.4. The scaling is applied before species, coupled, and signal updates, so uptake tied to volume change is charged for the growth that happened. Shrinkage is never scaled, and wall contacts do not enter the measure, because the wall projection leaves no wall overlap to read. + +The free band exists because relaxation leaves a small overlap between growing neighbors that are free to move, which should not slow them. The rule is a response to measured overlap, not a contact force law, and it inherits what the relaxation can and cannot do: + +- It needs relaxation that keeps free neighbors apart. With `gamma = 10` an unconfined colony of a few hundred cells carries overlaps of a quarter radius and more, and the limit then slows it; with `gamma = 100` a 256-cell colony keeps about 94% of its unlimited length. +- In a closed space it stops growth once the space is full, and the population then holds. The regularized solve minimizes the sum of squared overlaps, which does not bound the largest one, so a full space can still hold pairs overlapping by more than a radius. A pair pushed past one radius has inverted and the solve no longer separates it. +- With stiff relaxation (`gamma = 100`) a full closed space keeps trading overlap between pairs, cells that come out shallow resume growing, and the population creeps upward slowly instead of holding. + Walls are impenetrable. The regularized solve weighs each wall row against the cells pressing on it, so on its own it leaves a crowded cell part-way through a wall. After integrating a pass, `relax_cell_mechanics` therefore moves every mobile cell that is more than `1e-4` inside a constraint out of it. Each end of the cell's centerline moves back along the normals of the contacts it is inside, to a depth of `5e-5` so the resting contact stays active for the next solve and visible to contact analysis; a mid-span contact moves both ends; and the cell is rebuilt at its own length between the moved ends. A rod tilted against a wall comes to lie along it, and a rod wedged upright between a floor and a ceiling is turned flat. Up to eight sweeps settle the ends against each other. Length is unchanged, fixed cells are not moved, and the overlap this opens between cells is left to the next contact solve. A cell deeper than a wall's mid-plane would resolve toward the far face, so when any correction exceeds its cell's radius the pass is applied in up to sixteen equal parts that each move a cell at most one radius, projecting after each part. The projection uses the host constraint geometry on every backend. A wall thinner than a cell's diameter, or a correction longer than sixteen radii, is outside this guarantee. Planes, spheres, boxes, and cylinders are stored in a simulation-owned constraint set with stable IDs shared across constraint kinds. A plane declares a point and a normalized inward normal; its permitted half-space lies in the inward direction. Each finite constraint explicitly declares whether cells are permitted inside or outside. Negative separation means penetration in every case. diff --git a/docs/architecture/0014-native-controllers.md b/docs/architecture/0014-native-controllers.md index 09b8278..d2ce222 100644 --- a/docs/architecture/0014-native-controllers.md +++ b/docs/architecture/0014-native-controllers.md @@ -29,13 +29,13 @@ A controller-backed model resumes through `resume(context, checkpoint)`. The ope 2. apply cell attributes, species, and fixed-state updates; 3. apply division requests and division callbacks; 4. apply requested cell removals; -5. execute `Simulation.step(dt)` for growth and typed rate plans; +5. execute `Simulation.step(dt)` for growth and typed rate plans, with the growth limit when the mechanics configuration enables it; 6. apply flow drift when enabled in the mechanics configuration; and 7. execute exactly `MechanicsConfig.passes` contact/relaxation passes when mechanics is configured and cells remain. Each pass ends by projecting mobile cells out of the external constraints, so cells end the step resting on or clear of the walls. `UniformLengthDivision.jitter_z` controls only the random perturbation added to daughter orientation: `None` disables jitter, `False` adds XY-only jitter, and `True` adds XYZ jitter. Native normalization can change an inherited nonzero Z component even when the added Z perturbation is zero. Division places daughters along the parent's three-dimensional axis; subsequent contact relaxation and flow drift remain three-dimensional. See the [planarity diagnostics and tutorial audit](../tutorials/planarity.md) for reproducible examples and the limits of finite-height confinement. -The standard payload records a stable model ID and version, completed-step counter, model JSON state, random stream, and every mechanics parameter. `NativeController.from_checkpoint` validates and restores that payload while the checkpoint's native state retains rate plans, signal grids, geometry, and lineage. The number of mechanics passes is an explicit part of the native-controller contract. +The standard payload records a stable model ID and version, completed-step counter, model JSON state, random stream, and every mechanics parameter. `NativeController.from_checkpoint` validates and restores that payload while the checkpoint's native state retains rate plans, signal grids, geometry, and lineage. The number of mechanics passes is an explicit part of the native-controller contract. `MechanicsConfig(growth_limit=True)` makes the controller's growth step respond to compression, with `growth_free_overlap` and `growth_stall_overlap` setting the band in cell radii; the [contact mechanics design](0002-contact-mechanics.md#growth-under-compression) defines the rule. A payload that carries none of the three growth-limit fields restores with the limit off. ## Consequences diff --git a/docs/tutorials/microfluidics.md b/docs/tutorials/microfluidics.md index 01dfc8f..b7d3864 100644 --- a/docs/tutorials/microfluidics.md +++ b/docs/tutorials/microfluidics.md @@ -21,7 +21,7 @@ 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. +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 controller runs with `MechanicsConfig(growth_limit=True, growth_free_overlap=0.0, growth_stall_overlap=0.4)`, which scales each cell's elongation by a factor that falls linearly to zero as its deepest overlap with a neighbor reaches 0.4 radii, a fifth of its diameter. The packed interior stops elongating while cells at the mouth keep growing, spill into the channel, and wash out, and nutrient is consumed only for the growth that happened. The population settles near 320 cells with continuous turnover. The stall overlap is a model choice, not a measured mechanical response. ## Walls that cells and chemistry both respect diff --git a/examples/microfluidic_trap.py b/examples/microfluidic_trap.py index 0cbecd5..703c523 100644 --- a/examples/microfluidic_trap.py +++ b/examples/microfluidic_trap.py @@ -42,7 +42,7 @@ from microsimulator.microfluidics import TrapChannelDevice MODEL_ID = "examples.microfluidic-trap" -MODEL_VERSION = 5 +MODEL_VERSION = 6 DIVISION = UniformLengthDivision(3.2, 3.8, jitter_z=False) FLOW_SPEED = 20.0 @@ -68,11 +68,12 @@ # 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 +# reaches this many cell radii 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. +STALL_OVERLAP = 0.4 WASHOUT_Y = DEVICE.channel_half_length - 10.0 # Resistance feedback uses only fixed (attached) cells, with a physical @@ -129,18 +130,6 @@ 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( @@ -159,14 +148,9 @@ 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) - * max(0.0, 1.0 - compression.get(cell.id, 0.0) / COMPRESSION_LIMIT), - ) + CellUpdate(cell.id, growth_rate=_nutrient_growth(step.simulation, cell.position)) for cell in step.cells if cell.id not in washed ), @@ -200,7 +184,12 @@ def build(context: ModelContext) -> NativeController: rng=context.rng, regulate=_regulate, on_division=_divided, - mechanics=MechanicsConfig(flow_drift=True), + mechanics=MechanicsConfig( + flow_drift=True, + growth_limit=True, + growth_free_overlap=0.0, + growth_stall_overlap=STALL_OVERLAP, + ), state=state, ) diff --git a/python/src/microsimulator/__init__.py b/python/src/microsimulator/__init__.py index 33c01a8..8d3de1e 100644 --- a/python/src/microsimulator/__init__.py +++ b/python/src/microsimulator/__init__.py @@ -34,6 +34,7 @@ GridBoundary, GridBoundaryKind, GridShape, + GrowthLimitParameters, MechanicsIntegrationParameters, MechanicsParameters, MechanicsSolveResult, @@ -182,6 +183,7 @@ "GridBoundary", "GridBoundaryKind", "GridShape", + "GrowthLimitParameters", "MechanicsConfig", "MechanicsIntegrationParameters", "MechanicsParameters", diff --git a/python/src/microsimulator/_core.pyi b/python/src/microsimulator/_core.pyi index 37aafd1..6f3614f 100644 --- a/python/src/microsimulator/_core.pyi +++ b/python/src/microsimulator/_core.pyi @@ -612,6 +612,13 @@ class MechanicsIntegrationParameters: def __init__(self) -> None: ... +class GrowthLimitParameters: + free_overlap: float + stall_overlap: float + contacts: ContactParameters + + def __init__(self) -> None: ... + class SolverReport: @property def status(self) -> SolverStatus: ... @@ -687,7 +694,10 @@ class Simulation: def set_signal_reaction(self, reaction: SignalGridAffineReaction | None) -> None: ... def divide(self, parent_id: int, first_fraction: float) -> tuple[int, int]: ... def divide_equal(self, parent_id: int) -> tuple[int, int]: ... + @overload def step(self, dt: float) -> None: ... + @overload + def step(self, dt: float, growth_limit: GrowthLimitParameters) -> None: ... def find_cell_contacts(self, parameters: ContactParameters = ...) -> ContactGraph: ... def find_external_contacts( self, parameters: ConstraintContactParameters = ... diff --git a/python/src/microsimulator/controller.py b/python/src/microsimulator/controller.py index 3a404f4..56015f6 100644 --- a/python/src/microsimulator/controller.py +++ b/python/src/microsimulator/controller.py @@ -13,6 +13,7 @@ CellSnapshot, ConstraintContactParameters, ContactParameters, + GrowthLimitParameters, MechanicsIntegrationParameters, MechanicsParameters, MechanicsSolveResult, @@ -170,6 +171,11 @@ def _json_object(value: Mapping[str, JSONValue], path: str) -> dict[str, JSONVal return cast(dict[str, JSONValue], decoded) +_OPTIONAL_MECHANICS_FIELDS = frozenset( + {"growth_limit", "growth_free_overlap", "growth_stall_overlap"} +) + + @dataclass(frozen=True, slots=True) class MechanicsConfig: """Checkpointable parameters for exact mechanics passes after each step.""" @@ -187,6 +193,9 @@ class MechanicsConfig: constraint_activation_margin: float = 0.0 constraint_degeneracy_epsilon: float = 1.0e-6 flow_drift: bool = False + growth_limit: bool = False + growth_free_overlap: float = 0.1 + growth_stall_overlap: float = 0.4 def __post_init__(self) -> None: _integer(self.passes, "mechanics.passes", 1, _UINT32_MAX) @@ -225,6 +234,25 @@ def __post_init__(self) -> None: raise ControllerStateError("mechanics.require_convergence must be Boolean") if not isinstance(cast(object, self.flow_drift), bool): raise ControllerStateError("mechanics.flow_drift must be Boolean") + if not isinstance(cast(object, self.growth_limit), bool): + raise ControllerStateError("mechanics.growth_limit must be Boolean") + free_overlap = _finite_number(self.growth_free_overlap, "mechanics.growth_free_overlap") + stall_overlap = _finite_number(self.growth_stall_overlap, "mechanics.growth_stall_overlap") + if free_overlap < 0.0 or stall_overlap <= free_overlap: + raise ControllerStateError( + "mechanics growth limit overlaps must be non-negative and increasing" + ) + + def growth_limit_parameters(self) -> GrowthLimitParameters | None: + """The compression response of growth, or None when growth ignores contact.""" + + if not self.growth_limit: + return None + limit = GrowthLimitParameters() + limit.free_overlap = self.growth_free_overlap + limit.stall_overlap = self.growth_stall_overlap + limit.contacts = self.native_parameters()[1] + return limit def native_parameters( self, @@ -259,10 +287,18 @@ def to_json(self) -> dict[str, JSONValue]: @classmethod def from_json(cls, value: JSONValue) -> MechanicsConfig: - if not isinstance(value, dict) or set(value) != { - field.name for field in fields(MechanicsConfig) - }: + names = {field.name for field in fields(MechanicsConfig)} + # A checkpoint written by a controller without the growth limit carries + # none of its fields, and resumes with growth that ignores contact. + if ( + not isinstance(value, dict) + or not set(value) <= names + or not names - _OPTIONAL_MECHANICS_FIELDS <= set(value) + ): raise ControllerStateError("controller mechanics configuration is invalid") + growth_limit = value.get("growth_limit", False) + if not isinstance(growth_limit, bool): + raise ControllerStateError("mechanics.growth_limit must be Boolean") require_convergence = value["require_convergence"] if not isinstance(require_convergence, bool): raise ControllerStateError("mechanics.require_convergence must be Boolean") @@ -304,6 +340,13 @@ def from_json(cls, value: JSONValue) -> MechanicsConfig: "mechanics.constraint_degeneracy_epsilon", ), flow_drift=flow_drift, + growth_limit=growth_limit, + growth_free_overlap=_finite_number( + value.get("growth_free_overlap", 0.1), "mechanics.growth_free_overlap" + ), + growth_stall_overlap=_finite_number( + value.get("growth_stall_overlap", 0.4), "mechanics.growth_stall_overlap" + ), ) @@ -471,7 +514,13 @@ def step(self, dt: float) -> None: for removal in plan.removals: self.simulation.remove_cell(removal) - self.simulation.step(dt) + growth_limit = ( + None if self._mechanics is None else self._mechanics.growth_limit_parameters() + ) + if growth_limit is None: + self.simulation.step(dt) + else: + self.simulation.step(dt, growth_limit) reports: list[MechanicsSolveResult] = [] if ( self._mechanics is not None diff --git a/python/tests/test_growth_limit.py b/python/tests/test_growth_limit.py new file mode 100644 index 0000000..4f052ef --- /dev/null +++ b/python/tests/test_growth_limit.py @@ -0,0 +1,257 @@ +"""Growth that responds to compression, natively and through the controller.""" + +from __future__ import annotations + +import math +import random + +import pytest +from microsimulator import ( + BackendKind, + BoxConstraintInit, + CellInit, + ConstraintRegion, + ControllerStep, + DivisionEvent, + DivisionRequest, + GridShape, + GrowthLimitParameters, + MechanicsConfig, + NativeController, + RatePlanBuilder, + SignalGridSpec, + Simulation, + StepPlan, + UniformLengthDivision, + Vec3, + backend_available, +) + +_BACKENDS = [BackendKind.CPU, BackendKind.METAL, BackendKind.CUDA] +_RADIUS = 0.5 + + +def _limit(free_overlap: float = 0.1, stall_overlap: float = 0.5) -> GrowthLimitParameters: + limit = GrowthLimitParameters() + limit.free_overlap = free_overlap + limit.stall_overlap = stall_overlap + return limit + + +def _pair(simulation: Simulation, overlap_radii: float) -> None: + """Two parallel rods side by side, overlapping by a number of radii.""" + + cell = CellInit() + cell.length = 2.0 + cell.radius = _RADIUS + cell.growth_rate = 1.0 + cell.position = Vec3(4.0, 4.0, 0.5) + simulation.add_cell(cell) + cell.position = Vec3(4.0, 4.0 + 2.0 * _RADIUS - overlap_radii * _RADIUS, 0.5) + simulation.add_cell(cell) + + +@pytest.mark.parametrize("backend", _BACKENDS) +@pytest.mark.parametrize( + ("overlap_radii", "kept"), + [(0.0, 1.0), (0.1, 1.0), (0.3, 0.5), (0.5, 0.0), (0.9, 0.0)], +) +def test_elongation_falls_linearly_between_the_free_and_stall_overlaps( + backend: BackendKind, overlap_radii: float, kept: float +) -> None: + if not backend_available(backend): + pytest.skip(f"{backend.name} backend is unavailable") + simulation = Simulation(backend) + _pair(simulation, overlap_radii) + simulation.step(0.1, _limit()) + for cell in simulation.cells(): + assert math.isclose(cell.length, 2.0 + kept * 0.2, abs_tol=1.0e-4) + assert math.isclose(simulation.time, 0.1, rel_tol=1.0e-6) + + +def test_cells_out_of_contact_grow_as_in_an_unlimited_step() -> None: + limited = Simulation() + unlimited = Simulation() + for simulation in (limited, unlimited): + _pair(simulation, -2.0) + limited.step(0.1, _limit()) + unlimited.step(0.1) + assert [cell.length for cell in limited.cells()] == [cell.length for cell in unlimited.cells()] + + +def test_invalid_growth_limits_are_rejected_before_the_step() -> None: + simulation = Simulation() + _pair(simulation, 0.2) + for free_overlap, stall_overlap in ((-0.1, 0.4), (0.4, 0.4), (0.5, 0.4), (0.1, math.inf)): + with pytest.raises(ValueError, match="growth limit overlaps"): + simulation.step(0.1, _limit(free_overlap, stall_overlap)) + assert simulation.time == 0.0 + assert [cell.length for cell in simulation.cells()] == [2.0, 2.0] + + +@pytest.mark.parametrize("backend", _BACKENDS) +def test_nutrient_is_charged_only_for_growth_that_happened(backend: BackendKind) -> None: + if not backend_available(backend): + pytest.skip(f"{backend.name} backend is unavailable") + + def consumed(overlap_radii: float) -> float: + shape = GridShape() + shape.x, shape.y, shape.z = 9, 9, 2 + spec = SignalGridSpec() + spec.signal_count = 1 + spec.shape = shape + spec.diffusion = [0.0] + spec.advection = [Vec3()] + simulation = Simulation(backend) + levels = [10.0] * (9 * 9 * 2) + simulation.configure_signal_grid(spec, levels) + rates = RatePlanBuilder() + simulation.set_coupled_rate_plan( + rates.coupled_plan(0, 1, (), (-rates.cell_volume_change_rate(),)) + ) + _pair(simulation, overlap_radii) + simulation.step(0.05, _limit()) + return sum(levels) - sum(simulation.signal_levels) + + free = consumed(0.0) + assert free > 0.0 + assert math.isclose(consumed(0.3), 0.5 * free, rel_tol=1.0e-3) + assert abs(consumed(0.6)) <= 1.0e-4 * free + + +def test_mechanics_config_carries_the_growth_limit_through_json() -> None: + assert MechanicsConfig().growth_limit_parameters() is None + + configuration = MechanicsConfig( + growth_limit=True, growth_free_overlap=0.05, growth_stall_overlap=0.3 + ) + assert MechanicsConfig.from_json(configuration.to_json()) == configuration + limit = configuration.growth_limit_parameters() + assert limit is not None + assert math.isclose(limit.free_overlap, 0.05, rel_tol=1.0e-6) + assert math.isclose(limit.stall_overlap, 0.3, rel_tol=1.0e-6) + assert math.isclose( + limit.contacts.activation_margin, configuration.contact_activation_margin, rel_tol=1.0e-6 + ) + + # A configuration saved without the growth limit resumes with it off. + legacy = configuration.to_json() + for name in ("growth_limit", "growth_free_overlap", "growth_stall_overlap"): + del legacy[name] + assert MechanicsConfig.from_json(legacy) == MechanicsConfig() + + with pytest.raises(ValueError, match="non-negative and increasing"): + MechanicsConfig(growth_free_overlap=0.4, growth_stall_overlap=0.4) + invalid = configuration.to_json() + invalid["growth_limit"] = 1 + with pytest.raises(ValueError, match=r"mechanics\.growth_limit must be Boolean"): + MechanicsConfig.from_json(invalid) + unknown = configuration.to_json() + unknown["growth_pressure"] = 1.0 + with pytest.raises(ValueError, match="mechanics configuration is invalid"): + MechanicsConfig.from_json(unknown) + + +def _chamber(mechanics: MechanicsConfig) -> NativeController: + """One founder in a closed 4 by 4 chamber a cell and a half deep.""" + + simulation = Simulation() + chamber = BoxConstraintInit() + chamber.half_extents = Vec3(2.0, 2.0, 0.6) + chamber.allowed_region = ConstraintRegion.INSIDE + simulation.add_box_constraint(chamber) + founder = CellInit() + founder.length = 1.0 + founder.radius = 0.4 + founder.growth_rate = 1.0 + simulation.add_cell(founder) + rng = random.Random(0) + + def regulate(step: ControllerStep) -> StepPlan: + return StepPlan( + divisions=tuple(DivisionRequest(cell.id) for cell in step.cells if cell.length > 2.0) + ) + + def divided(step: ControllerStep, event: DivisionEvent) -> None: + # Daughters leave the division slightly splayed so a pair spanning the + # chamber can turn instead of staying end to end. + sign = 1.0 if step.rng.randrange(2) else -1.0 + for cell, turn in ((event.first, sign), (event.second, -sign)): + angle = math.atan2(cell.direction.y, cell.direction.x) + 0.01 * turn + step.simulation.set_cell_geometry( + cell.id, cell.position, Vec3(math.cos(angle), math.sin(angle), 0.0), cell.length + ) + + return NativeController( + simulation, + model_id="tests.closed-chamber", + model_version=1, + rng=rng, + regulate=regulate, + on_division=divided, + mechanics=mechanics, + ) + + +def _floor_coverage(simulation: Simulation) -> float: + return ( + sum( + math.pi * cell.radius**2 + 2.0 * cell.radius * cell.length + for cell in simulation.cells() + ) + / 16.0 + ) + + +def test_a_closed_chamber_fills_and_then_holds_its_population() -> None: + limited = _chamber(MechanicsConfig(growth_limit=True)) + unlimited = _chamber(MechanicsConfig()) + for _ in range(200): + limited.step(0.05) + unlimited.step(0.05) + # Growth that ignores contact has packed the chamber many times over. + assert unlimited.simulation.cell_count >= 200 + assert _floor_coverage(unlimited.simulation) > 10.0 + + # The limited colony used the floor before it stopped, and stays put. + filled = limited.simulation.cell_count + assert 8 <= filled <= 20 + assert _floor_coverage(limited.simulation) > 0.75 + for _ in range(400): + limited.step(0.05) + assert limited.simulation.cell_count <= filled + 4 + assert _floor_coverage(limited.simulation) < 1.5 + + +def test_an_unconfined_colony_keeps_most_of_its_growth() -> None: + division = UniformLengthDivision(3.2, 3.8, jitter_z=False) + + def total_length(mechanics: MechanicsConfig) -> float: + simulation = Simulation(reserved_capacity=2_000) + rng = random.Random(0) + founder = CellInit() + founder.length = 3.0 + founder.radius = _RADIUS + founder.growth_rate = 1.0 + state: dict[str, object] = {} + division.initialize_founders(simulation, state, rng, (founder,)) # type: ignore[arg-type] + controller = NativeController( + simulation, + model_id="tests.unconfined-colony", + model_version=1, + rng=rng, + regulate=lambda step: StepPlan(divisions=division.requests(step)), + on_division=division.on_division, + mechanics=mechanics, + state=state, # type: ignore[arg-type] + ) + for _ in range(160): + controller.step(0.05) + return sum(cell.length + 2.0 * cell.radius for cell in simulation.cells()) + + # Relaxation stiff enough to keep free neighbors apart leaves little + # overlap for the limit to respond to. + unlimited = total_length(MechanicsConfig(gamma=100.0)) + limited = total_length(MechanicsConfig(gamma=100.0, growth_limit=True)) + assert limited <= unlimited + assert limited >= 0.85 * unlimited diff --git a/tests/cpp/mechanics_integration_test.cpp b/tests/cpp/mechanics_integration_test.cpp index 6b1a142..9365374 100644 --- a/tests/cpp/mechanics_integration_test.cpp +++ b/tests/cpp/mechanics_integration_test.cpp @@ -195,6 +195,74 @@ void test_simulation_relaxation_cannot_carry_a_cell_through_a_thin_wall() { assert(deepest_wall_penetration(simulation) >= -1.0e-4F); } +// Two parallel rods side by side, overlapping by `overlap`. +microsimulator::Simulation overlapping_pair(float overlap) { + microsimulator::Simulation simulation(microsimulator::BackendKind::cpu, 0, 0, 0); + microsimulator::CellInit cell; + cell.length = 2.0F; + cell.radius = 0.5F; + cell.growth_rate = 1.0F; + simulation.add_cell(cell); + cell.position = {0.0F, 1.0F - overlap, 0.0F}; + simulation.add_cell(cell); + return simulation; +} + +void test_growth_limit_scales_elongation_by_compression() { + microsimulator::GrowthLimitParameters limit; + limit.free_overlap = 0.1F; + limit.stall_overlap = 0.5F; + const float dt = 0.1F; + const float full = 2.0F * dt; + // Overlap in radii, and the fraction of the full elongation it leaves. + const float cases[][2] = {{0.0F, 1.0F}, {0.1F, 1.0F}, {0.3F, 0.5F}, {0.5F, 0.0F}, {0.9F, 0.0F}}; + for (const auto& [overlap_radii, expected] : cases) { + auto simulation = overlapping_pair(overlap_radii * 0.5F); + simulation.step(dt, limit); + for (const auto& cell : simulation.cells()) { + assert(close(cell.length, 2.0F + (expected * full), 1.0e-4F)); + } + assert(close(static_cast(simulation.time()), dt)); + } + + // Cells out of contact grow as an unlimited step grows them. + auto apart = overlapping_pair(-1.0F); + auto reference = overlapping_pair(-1.0F); + apart.step(dt, limit); + reference.step(dt); + assert(apart.cells()[0].length == reference.cells()[0].length); + + // The limit never turns shrinkage into growth or holds it back. + auto shrinking = overlapping_pair(0.45F); + for (const auto& cell : shrinking.cells()) { + shrinking.set_cell_attributes(cell.id, -1.0F, cell.cell_type); + } + shrinking.step(dt, limit); + assert(close(shrinking.cells()[0].length, 2.0F - full, 1.0e-4F)); +} + +void test_growth_limit_rejects_invalid_parameters() { + auto simulation = overlapping_pair(0.1F); + const auto rejected = [&](float free_overlap, float stall_overlap) { + microsimulator::GrowthLimitParameters limit; + limit.free_overlap = free_overlap; + limit.stall_overlap = stall_overlap; + try { + simulation.step(0.1F, limit); + } catch (const std::invalid_argument&) { + return true; + } + return false; + }; + assert(rejected(-0.1F, 0.4F)); + assert(rejected(0.4F, 0.4F)); + assert(rejected(0.1F, std::numeric_limits::infinity())); + assert(rejected(std::numeric_limits::quiet_NaN(), 0.4F)); + // A rejected step leaves the cells and the clock as they were. + assert(simulation.cells()[0].length == 2.0F); + assert(simulation.time() == 0.0); +} + } // namespace int main() { @@ -205,5 +273,7 @@ int main() { test_simulation_relaxation_reduces_penetration(); test_simulation_relaxation_leaves_no_cell_inside_a_wall(); test_simulation_relaxation_cannot_carry_a_cell_through_a_thin_wall(); + test_growth_limit_scales_elongation_by_compression(); + test_growth_limit_rejects_invalid_parameters(); return 0; }