Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions cpp/core/mechanics_integration.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> 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<float> 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<std::size_t>(slot)];
depth = std::max(depth, overlap);
}
}
const auto radii = state.geometry_state().radii;
const auto band = parameters.stall_overlap - parameters.free_overlap;
std::vector<float> 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<const float> desired_length_increments) {
Expand Down
25 changes: 25 additions & 0 deletions cpp/core/simulation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -312,11 +312,27 @@ std::pair<CellId, CellId> 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<float> 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<float> 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");
Expand Down Expand Up @@ -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(
Expand Down
18 changes: 18 additions & 0 deletions cpp/include/microsimulator/mechanics.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> 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``.
Expand Down
6 changes: 6 additions & 0 deletions cpp/include/microsimulator/simulation.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ class Simulation {
std::pair<CellId, CellId> divide(CellId parent_id, float first_fraction);
std::pair<CellId, CellId> 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(
Expand Down Expand Up @@ -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<ComputeBackend> backend_;
Expand Down
18 changes: 17 additions & 1 deletion cpp/python/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,12 @@ NB_MODULE(_core, module) {
.def_rw("require_convergence",
&microsimulator::MechanicsIntegrationParameters::require_convergence);

nb::class_<microsimulator::GrowthLimitParameters>(module, "GrowthLimitParameters")
.def(nb::init<>())
.def_rw("free_overlap", &microsimulator::GrowthLimitParameters::free_overlap)
.def_rw("stall_overlap", &microsimulator::GrowthLimitParameters::stall_overlap)
.def_rw("contacts", &microsimulator::GrowthLimitParameters::contacts);

nb::class_<microsimulator::SolverReport>(module, "SolverReport")
.def_ro("status", &microsimulator::SolverReport::status)
.def_ro("breakdown", &microsimulator::SolverReport::breakdown)
Expand Down Expand Up @@ -606,7 +612,17 @@ NB_MODULE(_core, module) {
.def("divide_equal",
microsimulator::python::exclusive(&microsimulator::Simulation::divide_equal),
"parent_id"_a)
.def("step", microsimulator::python::released(&microsimulator::Simulation::step), "dt"_a)
.def(
"step",
microsimulator::python::released(static_cast<void (microsimulator::Simulation::*)(float)>(
&microsimulator::Simulation::step)),
"dt"_a)
.def("step",
microsimulator::python::released(
static_cast<void (microsimulator::Simulation::*)(
float, const microsimulator::GrowthLimitParameters&)>(
&microsimulator::Simulation::step)),
"dt"_a, "growth_limit"_a)
.def("find_cell_contacts",
microsimulator::python::released(&microsimulator::Simulation::find_cell_contacts),
"parameters"_a = microsimulator::ContactParameters{})
Expand Down
10 changes: 10 additions & 0 deletions docs/architecture/0002-contact-mechanics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/0014-native-controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/microfluidics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
39 changes: 14 additions & 25 deletions examples/microfluidic_trap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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
),
Expand Down Expand Up @@ -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,
)

Expand Down
2 changes: 2 additions & 0 deletions python/src/microsimulator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
GridBoundary,
GridBoundaryKind,
GridShape,
GrowthLimitParameters,
MechanicsIntegrationParameters,
MechanicsParameters,
MechanicsSolveResult,
Expand Down Expand Up @@ -182,6 +183,7 @@
"GridBoundary",
"GridBoundaryKind",
"GridShape",
"GrowthLimitParameters",
"MechanicsConfig",
"MechanicsIntegrationParameters",
"MechanicsParameters",
Expand Down
Loading