Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
18 changes: 12 additions & 6 deletions cpp/core/signal_jacobi.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ struct SignalJacobiOperations {
// Residual RMS of the starting iterate.
std::function<float()> initial_residual_rms;
std::function<float()> 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<void()> begin_sweeps;
Expand All @@ -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<float>::epsilon() * operations.right_hand_side_rms();
const auto floor = std::numeric_limits<float>::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) {
Expand Down
16 changes: 16 additions & 0 deletions cpp/core/signals.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 =
[&] {
Expand Down
9 changes: 6 additions & 3 deletions cpp/cuda/cuda_backend.cu
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<std::uint32_t>(signal_count_size),
static_cast<std::uint32_t>(grid_level_count), spec.solver);
static_cast<std::uint32_t>(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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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_),
Expand Down
6 changes: 6 additions & 0 deletions cpp/include/microsimulator/signals.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> levels = {});
Expand Down
9 changes: 6 additions & 3 deletions cpp/metal/metal_backend.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -1136,7 +1138,7 @@ void ensure_signal_solve_capacity(std::uint32_t level_count) {
id<MTLBuffer> y_faces, id<MTLBuffer> z_faces, std::uint32_t has_velocity_field,
id<MTLBuffer> error, const std::array<std::uint32_t, 6>& 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<MTLBuffer> current = initial;
Expand All @@ -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<std::uint32_t*>(error.contents) = 0; },
.sweep =
[&] {
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/0008-crank-nicolson-signals.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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

Expand All @@ -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
Expand Down Expand Up @@ -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

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

Expand Down
Loading