CorePotts API Reference

This page provides the full docstring index for the CorePotts package.

[!NOTE] End users normally access this API through PottsToolkit, which re-exports all public symbols. You only need to qualify names with CorePotts. when writing extensions such as custom penalties or backends.


Types

CorePotts.AbstractEventType
AbstractEvent

The base type for native engine events in the Potts simulation. Events derived from AbstractEvent can be integrated directly into the PottsParameters and evaluated as part of the native sweep loop (Phase 6 of an MCS step), avoiding CPU/GPU synchronization overheads that arise when using standard SciML DiscreteCallbacks.

Any custom event should subtype AbstractEvent and provide a corresponding method for: CorePotts.evaluate_event!(evt, u, p, cache, t, deps) which launches the event asynchronously. KernelAbstractions 0.9 orders launches on the backend; the return value is nothing and host observation is handled separately.

CorePotts.AbstractPottsStateType
PottsState{Grid, CellData}

The mutable state vector u for a Cellular Potts Model simulation. Contains the grid, cell properties, and cell ID tracking structures.

CorePotts.AdhesionPenaltyType
AdhesionPenalty(J_matrix)

Calculates the differential adhesion (surface tension) between cells of different types, and between cells and the medium. Drives cell sorting and morphological clustering.

CorePotts.AsymmetricResetType
AsymmetricReset(parent_value, child_value) <: InheritanceRule

The parent has the property set to parent_value and the child has the property set to child_value.

CorePotts.AtMCSType

Run at an explicit, canonical collection of positive integer-MCS boundaries.

CorePotts.CartesianDomainType
CartesianDomain(dims; spacing, boundaries, obstacles)

Host scientific description of a rectangular ownership domain. obstacles is an iterable of site => MediumOwner(...) pairs. Obstacle sites remain in rectangular storage but are excluded from the mutable recipient set.

CorePotts.CellIDType

Public reusable finite-cell identity. Zero and negative values are never valid cell IDs.

CorePotts.CellSlotType

Internal fixed-capacity storage slot identity for a finite cell.

CorePotts.CellTypeIDType

Read-only compiled finite-cell-type identity; user-facing types remain symbolic.

CorePotts.CellTypeInType

Restrict a lifecycle event to one immutable set of finite cell-type IDs.

CorePotts.CheckerboardMetropolisType
CheckerboardMetropolis(; sampler=MetropolisSampler(), sweeps_per_step=10, active_fraction=0.1f0, T=1.0f0)

A deterministic-stochastic checkerboard engine. It calculates the mathematically perfect graph coloring for the topology to completely remove the random lottery and maximize GPU utilization while remaining mathematically equivalent.

CorePotts.ChemotaxisPenaltyType
ChemotaxisPenalty(lambdas, chemical_field)

Biases cell membrane extensions up (or down) a pre-computed spatial chemical gradient.

CorePotts.CloneType
Clone <: InheritanceRule

The child cell receives an exact copy of the parent cell's property (e.g. target_volume).

CorePotts.CompiledRuleType
CompiledRule{F, S} <: UpdateRule

A highly optimized native Julia closure rule generated by the @rule macro.

Type Parameters

  • F: The type of the native function closure (cell_data, cell_id, ctx) -> ...
  • S: The type of the spatial metadata tuple (ContactArea(...), ...)

Fields

  • func::F: The native function to execute on the GPU.
  • spatial_rules::S: The tuple of spatial extraction rules required by this closure.
CorePotts.CopyAttemptType

Union-free result of recipient/direction selection, including proposal-budget no-ops.

CorePotts.CopyProposalType
CopyProposal

Immutable complete local ownership-copy proposal. recipient is overwritten by gaining; donor is the neighboring site carrying that owner. It is intentionally independent of backend storage.

CorePotts.EventBuilderType
EventBuilder

A programmatic builder for constructing events with strongly-typed rules.

CorePotts.ExecutionPlanType

Immutable execution policy and backend paired with separately mutable instrumentation.

CorePotts.FlexibilityTraitType
FlexibilityTrait

Traits indicating whether a physical property or penalty is rigid (type-coupled) or flexible (per-cell and dynamically writable).

CorePotts.FocalPointSpringPenaltyType
FocalPointSpringPenalty(lambdas, target_lengths, connectivity)

Models strong mechanical junctions (springs) between the centers of mass of specific cells. Useful for modeling epithelial sheets or rigid tissue structures.

CorePotts.HDF5BackendType
HDF5Backend(path::String)

Streams the simulation out-of-core to an HDF5 dataset on disk. Requires using HDF5.

CorePotts.HSTFocalPointPenaltyType
HSTFocalPointPenalty(lambdas, connectivity)

A thermodynamically consistent (fluctuating force) version of the focal point spring.

CorePotts.HSTLengthPenaltyType
HSTLengthPenalty(lambdas)

Constrains the major axis length of a cell, inducing elongation and polarity.

CorePotts.HSTSurfaceAreaPenaltyType
HSTSurfaceAreaPenalty(lambdas; eta=1.0f0)

A hydrostatic formulation of the surface area constraint using fluctuating membrane tensions. Prevents cells from fragmenting or infinitely stretching.

CorePotts.HSTVolumePenaltyType
HSTVolumePenalty(lambdas; eta=1.0f0)

A hydrostatic formulation of the volume constraint. Uses a fluctuating internal pressure p for each cell instead of a rigid quadratic constraint, allowing for thermodynamic detailed balance.

CorePotts.InheritAddType
InheritAdd(value) <: InheritanceRule

Both parent and child have value added to their property.

CorePotts.InheritMultiplyType
InheritMultiply(value) <: InheritanceRule

Both parent and child have their property multiplied by value.

CorePotts.IntrinsicCheckerboardMetropolisType
IntrinsicCheckerboardMetropolis(; sampler=MetropolisSampler(), sweeps_per_step=10, active_fraction=0.1f0, T=1.0f0)

The flagship, hardware-accelerated Monte Carlo engine of the Potts.jl ecosystem.

Standard GPU Cellular Potts Models suffer from the Global Volume Paradox: maintaining exact thermodynamics (Detailed Balance) requires perfectly tracking the volume of every cell. Global atomics cause massive memory contention, while removing them breaks the physics.

IntrinsicCheckerboardMetropolis solves this paradox by utilizing branchless SIMT Subgroup Reductions via KernelIntrinsics.jl. It uses low-level hardware intrinsics (like NVIDIA's PTX @shfl and @match, or Apple Silicon's air.simd_ballot) to instantaneously aggregate volume changes inside the hardware registers of the 32-thread warp. A single elected "Leader" thread then performs an O(1) atomic write to global memory.

Properties

  • Mathematically Exact: Perfectly preserves rigorous Detailed Balance.
  • Maximally Parallel: Completely eliminates global memory locking and atomic contention serialization.
  • Hardware Native: Compiles directly down to native Metal shading language (Apple) or PTX (NVIDIA) subgroup instructions.
Hardware Requirement

Requires a GPU backend that supports subgroup intrinsics (e.g., MetalBackend or CUDABackend). It will throw a MethodError if run on standard CPU threads.

CorePotts.LegacyPottsIntegratorType
LegacyPottsIntegrator{uType, pType, tType, algType, cacheType, OptsType}

The active simulation state, holding u, p, t, alg, and the cache. Provides SciML-compatible continuous integration for the Potts.

CorePotts.LegacyPottsProblemType
LegacyPottsProblem{uType, tType, pType} <: AbstractPottsProblem

A SciML-compatible problem definition for a Cellular Potts Model.

Fields

  • u0: The initial state (PottsState).
  • tspan: A tuple (t_start, t_end) defining the simulation duration in Monte Carlo steps.
  • p: The simulation parameters (PottsParameters).
CorePotts.LegacyPottsSolutionType
LegacyPottsSolution{T, P, A} <: SciMLBase.AbstractTimeseriesSolution

The result of a completed simulation. Contains the saved grid states and cell property states over time. Accessible like an array: sol[i] returns the state at time sol.t[i].

CorePotts.LocalNeuralPenaltyType
LocalNeuralPenalty{M, W, S}

A Neural Penalty that evaluates an allocation-free Neural Network (e.g. from SimpleChains.jl) over a localized spatial patch.

CorePotts.LogicalPottsStateType
LogicalPottsState

Final CPU logical state boundary. The underscored fields are deliberately storage details; callers use the accessors below so this state can later be lowered to backend-specific representations without changing scientific meaning.

CorePotts.LotteryCPMType

Topology-calibrated parallel lottery CPM with equal per-site expected activation.

CorePotts.MajorAxisOrientationType
MajorAxisOrientation <: DivisionOrientation

Cell division occurs perpendicular to the cell's major (longest) axis.

CorePotts.MediumIDType

Conceptual medium-domain identity, distinct from finite-cell identities.

CorePotts.MemoryBackendType
MemoryBackend()

The default out-of-core data saving backend. Pushes grid and cell_data into an array in RAM.

CorePotts.MinorAxisOrientationType
MinorAxisOrientation <: DivisionOrientation

Cell division occurs perpendicular to the cell's minor (shortest) axis.

CorePotts.MooreTopologyType
MooreTopology{N}

A standard periodic N-dimensional Moore neighborhood (8-connected in 2D, 26-connected in 3D).

CorePotts.OwnerRefType
OwnerRef

Compact, isbits logical owner identity for one realized lattice site. The tag makes finite-cell and medium-domain identity disjoint even when their numeric identifiers are equal. It is a host representation in this phase; a future device lowering may use a different encoding while exposing the same accessors.

CorePotts.ParallelMetropolisType
ParallelMetropolis(; sampler=MetropolisSampler(), sweeps_per_step=10, active_fraction=0.1f0, T=1.0f0)

The solver algorithm for LegacyPottsProblems. Specifies how Monte Carlo Sweeps are executed.

Keyword Arguments

  • sampler: The sampling strategy (default MetropolisSampler()).
  • sweeps_per_step: How many Monte Carlo Sweeps equal one simulation time unit (default 10).
  • active_fraction: Fraction of the grid proposed for updates per sweep (default 0.1).
  • T: The computational temperature regulating membrane fluctuation (default 1.0).
CorePotts.PottsCacheType
PottsCache{N}

The algorithmic workspace and cache used during Monte Carlo execution.

CorePotts.PottsModelType
PottsModel(proposal_relation, boundary_tracker; components, parameters, ...)

Reusable scientific meaning for the Phase 9 interface. A custom parameterization is an ordinary typed callable which maps the problem's concrete parameter container to a ScientificComponentSet on the host before device adaptation.

CorePotts.PottsParametersType
PottsParameters{Topo, P, Tr, Ev}

The physics definition parameters p for a Cellular Potts Model simulation.

CorePotts.PottsTrainingCacheType
PottsTrainingCache{State, Params, Alg}

Holds the persistent MCMC chains used for negative sampling during Contrastive Divergence training.

CorePotts.RNGAddressType
RNGAddress

Complete scheduling-independent coordinates for one block of four random UInt32 values. Valid addresses pack injectively into the Philox 128-bit counter for a fixed master seed and cell generation. invocation is the local retry/invocation coordinate; draw distinguishes lexical or algorithmic draws owned by one operation.

CorePotts.RNGStreamType

Stable named stream families. Numeric values are part of the RNG contract.

CorePotts.RandomNormalType
RandomNormal(mean, std) <: InheritanceRule

Both parent and child have their property drawn from a normal distribution.

CorePotts.RandomUniformType
RandomUniform(min, max) <: InheritanceRule

Both parent and child have their property drawn from a uniform distribution [min, max].

CorePotts.ResetType
Reset(value) <: InheritanceRule

Both parent and child have the property set to value.

CorePotts.ResetChildType
ResetChild(value) <: InheritanceRule

The parent retains its property, but the child has the property set to value.

CorePotts.RuleBuilderType
RuleBuilder

A programmatic builder for CompiledRule objects. Ensures that the provided closure matches the expected 4-argument signature: (cell_data, cell_id, ctx, current_val) before wrapping it in a CompiledRule.

CorePotts.SequentialMetropolisType
SequentialMetropolis(; sampler=MetropolisSampler(), sweeps_per_step=10, active_fraction=0.1f0, T=1.0f0)

A strictly sequential CPU algorithm that processes sites randomly one-by-one. No parallel contention.

CorePotts.SnapshotScientificAccessType
SnapshotScientificAccess(relations=(); cell_wide=false, private_workspace=false)

Auditable access trait for a component evaluated against a common immutable subround snapshot. relations contains every realized spatial relation whose simultaneous recipient writes could interact. cell_wide declares dependence on mutable finite-cell state, and private_workspace requires proposal-private scratch storage before parallel execution can be qualified.

CorePotts.SplitType
Split(fraction=0.5f0) <: InheritanceRule

The parent cell's property is split between the parent and child according to the fraction.

CorePotts.SurfaceAreaTrackerType
SurfaceAreaTracker

A global state tracker that automatically tracks the surface area (number of dissimilar neighbor interactions) for each cell dynamically as the grid is updated.

CorePotts.VectorOrientationType
VectorOrientation(nx, ny, nz) <: DivisionOrientation

Cell division occurs perpendicular to the specified normal vector.

CorePotts.VolumePenaltyType
VolumePenalty(lambdas)

The classic cellular volume constraint. Acts as a harmonic spring, penalizing deviations from a cell's target_volume according to its type-specific lambda.

CorePotts.VolumeThresholdTriggerType
VolumeThresholdTrigger(multiplier=2.0)

A callable trigger that evaluates to true when a cell's current volume is greater than or equal to multiplier * target_volume. Used to trigger mitosis.

CorePotts.VolumeTrackerType
VolumeTracker

A global state tracker that automatically tracks the volume (number of grid sites) belonging to each cell without requiring O(N) recalculations per step.

CorePotts.VonNeumannTopologyType
VonNeumannTopology{N}

A standard periodic N-dimensional Von Neumann neighborhood (4-connected in 2D, 6-connected in 3D).

CorePotts.ZarrBackendType
ZarrBackend(path::String)

Streams the simulation out-of-core to a Zarr dataset on disk. Requires using Zarr.


Functions

CommonSolve.solve!Method
SciMLBase.solve!(integrator::LegacyPottsIntegrator)

In-place execution of the Potts simulation. Steps the integrator forward in time until it reaches the end of the problem's timespan. Useful for manual loop control and avoiding memory reallocation.

CommonSolve.solveMethod
SciMLBase.solve(prob::LegacyPottsProblem, alg::AbstractPottsAlgorithm, args...; kwargs...)

Standard out-of-place execution interface. Dynamically initializes a new LegacyPottsIntegrator, allocates engine structures, executes the full simulation, and returns a LegacyPottsSolution.

CommonSolve.step!Method

Dispatch one complete MCS through the algorithm-owned open hook.

CorePotts._extract_reqsMethod
build_cell_data(grid, N_cells; custom_fields...)

Allocates and constructs a StructArray on the same backend as grid (CPU or GPU) to hold macroscopic cell properties like :volumes, :target_volumes, :cell_types, :pressures, etc.

CorePotts._kernel_reset_hst_fields!Method
reset_hst_fields_after_division!(engine, pen::AbstractHSTPenalty)

Resets the stochastic auxiliary field for all live cells to its thermodynamic mean immediately after a mitosis event, preventing O(1/η) MCS transients.

CorePotts.apply_division_batchMethod
apply_division_batch(state, requests; minimum_daughter_volume=1)

Validate all requested geometries from one snapshot, preflight the full fixed-capacity batch, then commit deterministic parent/child assignments to a private candidate. Capacity failure leaves the input state untouched; slots retired in this MCS are absent from _available_lifecycle_slots until release_retired_slots is called at the next boundary.

CorePotts.commit_copy_proposalMethod
commit_copy_proposal(state, proposal; accepted=true, constraints=())

Apply one accepted typed ownership-copy proposal to a private logical-state candidate. The lattice is authoritative; derived occupancy is rebuilt and any extinct finite owner is retired immediately, while the resulting slot remains unavailable for reuse until the lifecycle boundary releases it.

CorePotts.construct_copy_attemptMethod
construct_copy_attempt(state, domain, proposal_relation, recipient, direction; mcs, semantic_id)

Construct one conventional neighbor-site attempt. Exact transition multiplicities are counted around the recipient so Metropolis-Hastings receives complete forward/reverse proposal support.

CorePotts.dispatch_kernel!Method
dispatch_kernel!(backend, kernel, args...; ndrange, workgroupsize=nothing)

KernelAbstractions 0.9 launch spelling for historical consumers. Launches are asynchronous and ordered on every supported backend. New compiled execution code uses instrumented launch! and synchronizes only through synchronize_observation!.

CorePotts.evaluate_penaltyMethod
evaluate_penalty(p::Union{FocalPointSpringPenalty, HSTFocalPointPenalty}, ctx)

Evaluates the focal point spring penalty.

Note: To avoid the severe performance penalty of calculating the exact quadratic center-of-mass shift and resolving atan2 circular statistics for every proposed pixel flip on periodic boundaries, this function evaluates the energy using the linearized auxiliary field approximation (Force * Δx). The exact forces (and any HST stochastic noise) are computed once per cell during the sweep auxiliary step.

CorePotts.evaluate_triggerMethod
evaluate_trigger(evt::AbstractEvent, i::Int, cell_data, t)

Evaluates the event trigger for cell i on the device. Only called if has_device_trigger(evt) returns true. Should return a Bool.

CorePotts.event_effectsFunction

Typed effects emitted from one event-phase snapshot; extensions implement this method.

CorePotts.execute_step!Function
execute_step!(u::AbstractPottsState, p::PottsParameters, cache::PottsCache, alg::CheckerboardMetropolis)

Executes a single Monte Carlo Sweep (MCS) across the grid using a deterministic checkerboard algorithm.

CorePotts.execute_step!Function
execute_step!(u::AbstractPottsState, p::PottsParameters, cache::PottsCache, alg::ParallelMetropolis)

Executes a single Monte Carlo Sweep (MCS) across the grid using the stochastic lottery algorithm.

CorePotts.execute_step!Function
execute_step!(u::AbstractPottsState, p::PottsParameters, cache::PottsCache, alg::SequentialMetropolis)

Executes a single Monte Carlo Sweep (MCS) sequentially on the CPU without atomic locks.

CorePotts.finalize_initial_stateMethod
finalize_initial_state(shape, layouts...; capacity, medium_domains, property_schema,
                       overlap_policy=RejectInitialOverlap())

Finalize open layout claims in an order-independent host pipeline: resolve overlaps, remove empty entities, assign compact runtime IDs by semantic identity, validate capacity, initialize schema properties, reconstruct derived state, and publish only an invariant-valid logical state.

CorePotts.get_event_argsMethod
get_event_args(evt::AbstractEvent, mask, u::AbstractPottsState, p::PottsParameters, cache::PottsCache, t)

Returns a tuple of arguments to be splatted into the event's kernel function. Users defining custom events must implement this method. Returning a tuple of exactly what the kernel needs prevents massive memory closures and GPU compiler crashes on Metal.jl.

Note that mask is passed directly. If your kernel requires the mask as its first argument, you must explicitly include it in the returned tuple, e.g. return (mask, u.cell_data.volumes).

If the event should not run during the current step (e.g. t % check_interval != 0), return nothing to skip kernel execution.

CorePotts.get_event_kernelMethod
get_event_kernel(evt::AbstractEvent, backend, block_size)

Returns the compiled @kernel function for the given event. Users defining custom events must implement this method and return the kernel instance initialized with the backend and block_size.

CorePotts.get_event_ndrangeMethod
get_event_ndrange(evt::AbstractEvent, mask, u)

Returns the size of the iteration space for this event's kernel. By default, this sweeps over all cells (length(mask)).

CorePotts.has_device_triggerMethod
has_device_trigger(evt::AbstractEvent)

Returns true if this event provides a device-side evaluate_trigger function that should be evaluated in the unified event kernel to generate a boolean mask. By default, this is false.

CorePotts.init_scientificMethod
init_scientific(state, proposal_relation, components, algorithm; seed, plan, ...)

Construct the Phase 7 scientific integrator over already compiled, backend-resident state. The seed is execution state rather than algorithm configuration. No simulation work or observation sync is performed during construction.

CorePotts.initialize_com_anchors!Method
initialize_com_anchors!(u, p, cache)

Runs the two Center-of-Mass kernels sequentially to pre-initialize the anchor coordinates. This is called exactly once per simulation during sync_cell_data! so that the fused HSTLengthPenalty kernel has valid previous-step anchors on its very first sweep.

CorePotts.initialize_workspaceMethod
initialize_workspace(evt::AbstractEvent, u::AbstractPottsState, topology::AbstractTopology)

Called exactly once during simulation initialization. By default, returns evt unmodified. Custom events can override this to allocate dynamic memory workspaces.

CorePotts.is_allowedMethod

Allocation-free exact connectivity predicate for compiled CPU/GPU execution.

CorePotts.neighbor_cells!Method
neighbor_cells!(workspace, state, domain, relation, owner, filter, medium_types, epoch)

Write canonical distinct finite-cell IDs into workspace.ids and return their count. epoch must be nonzero and unique for every live use of the workspace; clear seen_epochs before epoch reuse. The routine allocates nothing and is valid inside a single device work item.

CorePotts.normalized_kernel_relationMethod
normalized_kernel_relation(Val(N); spacing)

Published square-order-4 (N == 2) or cubic-order-6 (N == 3) surface stencil. The corresponding correction factor belongs to NormalizedKernelMeasure, not to relation weights.

CorePotts.poisson_inversionMethod
poisson_inversion(contract, seed, address, rate)

Exact inversion sampler for 0 ≤ rate ≤ 64. It is intentionally domain-limited rather than silently switching algorithms. Each loop iteration owns a distinct local draw address.

CorePotts.potts_lossMethod
potts_loss(theta, cache::PottsTrainingCache, data_batch, update_fn)

The pure mathematical loss function for Persistent Contrastive Divergence EBM training. update_fn(p::PottsParameters, theta) maps the flat/ComponentArray theta back into a full PottsParameters struct. This function evaluates the global energy difference E_data - E_model. NOTE: The MCMC sampling step (execute_step!) must be run outside this function (e.g., in an Optimization.jl callback) so that AD engines do not attempt to trace it.

CorePotts.process_death_events!Method
process_death_events!(engine)

Scans the grid for any cells whose target_volume is less than or equal to 0. These cells are killed (removed from the grid) and their IDs are recycled for future use.

CorePotts.process_mitosis_events!Method
process_mitosis_events!(engine; trigger=VolumeThresholdTrigger(), orientation=RandomOrientation(), inheritance_rules)

Evaluates the trigger for all active cells. For any cell where the trigger is true, the cell is divided in half according to the geometric orientation. Properties are inherited by the new daughter cell according to inheritance_rules.

CorePotts.proposal_lawMethod

Proposal law selected by an algorithm; downstream algorithms may extend this method.

CorePotts.rebuild_trackerFunction

Complete tracker reconstruction from authoritative ownership; extensions implement this method.

CorePotts.required_variablesMethod
required_variables(component)

Returns a NamedTuple mapping the required variables to their types for a given physics penalty or tracker.

CorePotts.small_permutation!Method
small_permutation!(destination, contract, seed, address)

Exact Fisher–Yates permutation for small scientific schedules such as checkerboard colors. The destination length is limited by the v1 draw domain; large layout permutations use a separately compiled primitive.

CorePotts.spawn_hypersphere!Method
spawn_hypersphere!(grid, grid_dims, center, radius, cell_id)

Paints a spherical cluster of cell_id onto the grid centered at center with radius. Works in both 2D and 3D.

CorePotts.sync_cell_data!Method
sync_cell_data!(u::AbstractPottsState, p::PottsParameters, cache::PottsCache, num_cells::Int; set_targets::Bool=true)

Scans the grid and calculates the actual volumes and centroids for all cells from 1 to num_cells. If set_targets is true, sets target_volume to match the initial volume.

CorePotts.sync_cell_data!Method
sync_cell_data!(grid, cell_data, num_cells)

A utility to manually count cell volumes from the grid and set them in cell_data. Sets both volumes and target_volumes to the counted value.

CorePotts.validate_closure!Method
validate_closure!(closure)

Pre-flight validation to ensure the closure signature is structurally sound before we send it to the GPU. Catches errors like 3-argument vs 4-argument mismatches.


Constants