Reference engine internals

The numerics of the built-in 2D engine: diffusion, mechanics, phenotype and the simulation loop.

abmfact.reference

The built-in reference engine: a small, documented 2D agent-based simulator in NumPy.

It runs ABM-IR models directly: off-lattice centre-based mechanics (overdamped motion with PhysiCell’s repulsion and adhesion potentials), a live cell cycle with division, apoptosis and necrosis, substrates diffusing on a grid (abmfact.reference.diffusion states the scheme and its stability), secretion and uptake, chemotaxis, and Hill-type rules combined as PhysiCell combines them. It honours every v0.1 knob, so every audit check applies to it, and the same seed always gives the same run.

It is a baseline for verification and comparison, not a competitor to PhysiCell: no 3D, no intracellular models, no attack or phagocytosis (planned for milestone 3), and no custom code.

abmfact.reference.diffusion

Diffusion of a substrate on a regular 2D grid.

The PDE is dc/dt = D (c_xx + c_yy) - lambda(x) c + g(x), where lambda is decay plus cell uptake and g is cell secretion. Each side of the domain is no-flux, held at a value (Dirichlet), or periodic.

Default scheme: symmetrised backward-Euler locally one-dimensional (LOD) splitting. A sweep along x solves (I + dt lambda/2 - dt D d_xx) c* = c + dt g/2 with the standard three-point stencil, and a sweep along y does the same with d_yy. One step of length dt takes both orders, x then y and y then x, and averages them, so neither axis is privileged: rotating the world by 90 degrees gives the same result, which a fixed sweep order would not (its splitting error depends on the order). Reaction terms sit inside the implicit solves, so uptake competes with diffusion within each step instead of being capped at one step’s worth of substrate. Each line is a tridiagonal system; all lines of a sweep are solved together in one LAPACK banded solve, and periodic lines (cyclic systems) use the Sherman-Morrison correction. The scheme is first order in time and second order in space.

Stability: unconditionally stable for every dt > 0. Each sweep’s matrix is a strictly diagonally dominant M-matrix (diagonal 1 + 2r + dt lambda/2 against off-diagonals -r, r = D dt / h^2), so it never amplifies an error mode and it keeps concentrations non-negative; the average of the two orders is a convex combination and keeps both properties. Large dt costs accuracy, not stability: the splitting makes even the steady state first order in dt. Dirichlet sides are the outer layer of voxels, held at their value (BioFVM’s convention).

Explicit scheme (FTCS), for verification only. ftcs_step() uses forward Euler with the same stencil. Stability condition: D dt (1/dx^2 + 1/dy^2) <= 1/2, which for dx = dy is D dt / dx^2 <= 1/4. Beyond it the checkerboard mode is multiplied by 1 - 4 D dt (1/dx^2 + 1/dy^2) < -1 every step and the solution blows up. ftcs_stable_substeps() returns the number of equal substeps that satisfies the condition.

class abmfact.reference.diffusion.Boundary(x_min: float | None = None, x_max: float | None = None, y_min: float | None = None, y_max: float | None = None, periodic: bool = False)[source]

Bases: object

Per-side condition: a float holds that side at the value, None is no-flux.

periodic overrides both: the grid wraps in x and y.

mask_and_values(shape: tuple[int, int]) → tuple[ndarray, ndarray][source]

Boolean mask of Dirichlet voxels and the value each one is held at (later sides win at corners).

abmfact.reference.diffusion.tridiagonal_lines(sub: ndarray, diag: ndarray, sup: ndarray, rhs: ndarray) → ndarray[source]

Solve independent tridiagonal systems along axis 0, one per column, in a single banded solve.

The lines are stacked end to end into one banded system with zero coupling between lines and solved by LAPACK through scipy.linalg.solve_banded(). sub[0] and sup[-1] are ignored. rhs may carry extra trailing axes for several right-hand sides.

abmfact.reference.diffusion.cyclic_lines(off: ndarray, diag: ndarray, rhs: ndarray) → ndarray[source]

Periodic tridiagonal systems along axis 0 (constant off-diagonal, including the two corners), solved by the Sherman-Morrison correction to a non-periodic system.

abmfact.reference.diffusion.implicit_step(c: ndarray, D: float, decay: float, dt: float, dx: float, dy: float, boundary: Boundary, gain: ndarray | None = None, loss: ndarray | None = None) → ndarray[source]

One symmetrised backward-Euler LOD step with reactions inside the sweeps (see the module docstring).

gain (amount per time) and loss (rate, per time) are per-voxel cell terms; decay is the substrate’s own decay rate.

abmfact.reference.diffusion.laplacian(c: ndarray, dx: float, dy: float, periodic: bool) → ndarray[source]

Five-point Laplacian with mirror (no-flux) or wrapped edges.

abmfact.reference.diffusion.ftcs_step(c: ndarray, D: float, decay: float, dt: float, dx: float, dy: float, boundary: Boundary) → ndarray[source]

One explicit forward-Euler step. Stable only when D dt (1/dx^2 + 1/dy^2) <= 1/2.

abmfact.reference.diffusion.ftcs_number(D: float, dt: float, dx: float, dy: float) → float[source]

D dt (1/dx^2 + 1/dy^2); the explicit scheme is stable when this is at most 1/2.

abmfact.reference.diffusion.ftcs_stable_substeps(D: float, dt: float, dx: float, dy: float | None = None) → int[source]

The fewest equal substeps of dt that keep the explicit scheme within its stability limit.

abmfact.reference.mechanics

Centre-based mechanics with PhysiCell’s potentials, in 2D.

Cells are discs moving by overdamped dynamics: velocity is the sum of pairwise forces plus a motility term, and positions advance by second-order Adams-Bashforth, x += dt (1.5 v - 0.5 v_prev). For cells i, j at distance d the pair speed along the unit vector from j to i is:

  c_r (1 - d/R)^2  for d < R          (repulsion, R = r_i + r_j, c_r = sqrt(c_r,i c_r,j))
- c_a (1 - d/S)^2  for d < S          (adhesion, S = s_i r_i + s_j r_j, c_a = sqrt(a_i a_j))

where s is the relative maximum adhesion distance and a_i the adhesion strength times the affinity for the other cell’s type. Simple pressure is sum (1 - d/R)^2 / 0.027288820670331. These follow Cell::add_potentials and Cell::update_position in core/PhysiCell_cell.cpp of PhysiCell 1.14.2.

abmfact.reference.mechanics.SIMPLE_PRESSURE_SCALE = 0.027288820670331

pressure 1 is a hexagonally packed cell.

Type:

PhysiCell’s normalisation, 12 (1 - sqrt(pi / (2 sqrt 3)))^2

class abmfact.reference.mechanics.Domain(lo: ndarray, hi: ndarray, periodic: bool)[source]

Bases: object

A rectangular 2D domain, closed or periodic.

lo

The lower corner, (x, y).

Type:

numpy.ndarray

hi

The upper corner, (x, y).

Type:

numpy.ndarray

periodic

Whether positions wrap around; otherwise they are held at the edge.

Type:

bool

property size: ndarray

The side lengths, hi - lo.

wrap(pos: ndarray) → ndarray[source]

Map positions back into the domain: wrap when periodic, else hold them at the edge.

displacement(a: ndarray, b: ndarray) → ndarray[source]

a - b with the minimum-image convention on a periodic domain.

abmfact.reference.mechanics.pairs_within(pos: ndarray, cutoff: float, domain: Domain) → ndarray[source]

All pairs (i, j), i < j, closer than cutoff, sorted, as an (m, 2) array.

class abmfact.reference.mechanics.PairForces(velocity: ndarray, pressure: ndarray, neighbours: ndarray)[source]

Bases: object

What pair_forces() returns.

velocity

The (n, 2) velocity of each cell from the pair potentials.

Type:

numpy.ndarray

pressure

The simple pressure on each cell.

Type:

numpy.ndarray

neighbours

The (m, 2) pairs within the adhesion distance.

Type:

numpy.ndarray

abmfact.reference.mechanics.pair_forces(pos: ndarray, radius: ndarray, rep: ndarray, adh_strength: ndarray, rel_adh_dist: ndarray, affinity: ndarray, types: ndarray, pairs: ndarray, domain: Domain) → PairForces[source]

Velocities from pair potentials, simple pressure, and the pairs in contact.

affinity[t_i, t_j] is cell type t_i’s adhesive affinity for type t_j.

abmfact.reference.phenotype

Hill-type rules and the behaviours and signals the reference engine supports.

Rules combine exactly as in PhysiCell 1.14.2 (core/PhysiCell_rules.cpp: parse_csv_rule_v3, set_behavior_min_value, set_behavior_max_value and Hypothesis_Rule::evaluate; and multivariate_Hill_response_function in core/PhysiCell_basic_signaling.cpp). For one behaviour of one cell type with base value b0 (from the cell type):

  • every increases rule raises the maximum bM to its saturation value if higher and lowers the minimum bm to b0 if lower; every decreases rule lowers bm to its saturation value and raises bM to b0;

  • the up-regulating signals combine as U = S / (1 + S) with S = sum (s_k / h_k)^n_k over the increases rules, and likewise D over the decreases rules;

  • the behaviour is b = b_up + (bm - b_up) D with b_up = b0 + (bM - b0) U.

A dead cell sees a signal of 0 for every rule that does not apply to dead cells, and when no rule applies to it the behaviour is left unchanged.

abmfact.reference.phenotype.signal_supported(name: str, model: IRModel) → bool[source]

Whether the reference engine can compute the signal name for this model’s substrates and cell types.

abmfact.reference.phenotype.behaviour_supported(name: str, model: IRModel) → bool[source]

Whether the reference engine can set the behaviour name for this model’s substrates.

abmfact.reference.phenotype.base_value(ct: CellType, behaviour: str) → float[source]

The behaviour’s value as the cell type defines it, before any rule.

class abmfact.reference.phenotype.Term(signal: str, half_max: float, hill_power: float, apply_to_dead: bool)[source]

Bases: object

One rule’s signal and Hill parameters within a Ruleset.

signal

The signal name.

Type:

str

half_max

The signal value at which the Hill response is one half.

Type:

float

hill_power

The Hill exponent.

Type:

float

apply_to_dead

Whether the rule also acts on dead cells.

Type:

bool

class abmfact.reference.phenotype.Ruleset(behaviour: str, base: float, min_value: float = 9e+99, max_value: float = -9e+99, up: list[Term] = <factory>, down: list[Term] = <factory>)[source]

Bases: object

All rules acting on one behaviour of one cell type.

property signals: list[str]

The signal of every rule, the increases rules first.

evaluate(signals: Mapping[str, ndarray], dead: ndarray, current: ndarray) → ndarray[source]

The behaviour for every cell. Cells to which no rule applies keep current.

abmfact.reference.phenotype.build_rulesets(model: IRModel) → dict[tuple[str, str], Ruleset][source]

Rulesets keyed by (cell type, behaviour), with minima and maxima set as PhysiCell sets them.

abmfact.reference.sim

The reference engine’s simulation loop.

Time advances in ticks of the smallest of the three steps (diffusion, mechanics, phenotype); each process runs when its own step comes round. Within a tick the order is: timed events, diffusion, phenotype (rules, death, division, removal), mechanics. Every per-cell random number comes from a stream spawned from the run seed, assigned to cells in activation order, so the same seed always gives the same run and the activation order changes only which cell receives which number.

Motility follows Cell::update_motility_vector in core/PhysiCell_cell.cpp of PhysiCell 1.14.2: a cell picks a new direction with probability dt / persistence_time per mechanics step (none before its first turn), mixing a random unit vector with its bias direction (the substrate gradient, for chemotaxis), each normalised as PhysiCell normalises them.

Attacks follow standard_cell_cell_interactions in core/PhysiCell_standard_models.cpp and Cell::attack_cell in core/PhysiCell_cell.cpp. Once per mechanics step, after the pair forces, each live effector without a target tries its live neighbours (cells within the adhesion distance) in a random order and starts an attack on the first with probability attack_rate * immunogenicity * dt. While attacking, it adds damage_rate * dt to its target’s damage, and ends the attack with probability dt / attack_duration or when the target dies. Damage grows and is repaired as in Cell_Integrity::advance_damage, once per phenotype step after the rules, and kills only through rules that read the damage signal. PhysiCell also links the two cells by a spring during an attack; the reference engine does not.

abmfact.reference.sim.refusals(model: IRModel, knobs: Knobs) → list[str][source]

Reasons the reference engine cannot run this model with these knobs; empty when it can.

class abmfact.reference.sim.Simulation(model: IRModel, seed: int, knobs: Knobs, solver: str = 'implicit')[source]

Bases: object

One run of an ABM-IR model. Use abmfact.reference.simulate().

events() → None[source]

Start every timed event whose time has come, and end those whose until has passed.

diffuse() → None[source]

Advance every substrate field by one diffusion step, with secretion, uptake and export by live cells.

phenotype() → None[source]

One phenotype step: apply the rules, draw deaths and divisions, and remove cleared dead cells.

mechanics() → None[source]

One mechanics step: pair forces, motility turns, then the Adams-Bashforth position update.

attacks() → None[source]

One round of effector attacks over the current neighbour pairs; see the module docstring.

run() → RunOutputs[source]

Run to max_time and return the saved outputs, with observables computed and warnings attached.

abmfact.reference.sim.physicell_normalize(v: ndarray) → ndarray[source]

Rows divided by sqrt(1e-32 + |v|^2), and set to zero where the norm is at most 1e-16.

This is normalize in BioFVM/BioFVM_vector.cpp of PhysiCell 1.14.2. A vanishing gradient gives no bias, rather than a full-strength bias in whatever direction rounding happens to point.

abmfact.reference.sim.simulate(model: IRModel, seed: int, knobs: Knobs | None = None, solver: str = 'implicit') → RunOutputs[source]

Run an ABM-IR model in the reference engine and return its outputs in the common schema.