Engines

The engine contract, the registry, and the engines that ship with ABMfact.

abmfact.engines

Engines: one adapter contract for every simulator, discovered through entry points.

abmfact.engines.base

The adapter contract every engine implements: capabilities, prepare, run and collect.

exception abmfact.engines.base.EngineError[source]

Bases: RuntimeError

An engine cannot run a model, or a run failed.

class abmfact.engines.base.Capabilities(name: str, mechanics: str, dimensions: tuple[int, ...] = (), diffusion: bool = False, intracellular: tuple[str, ...] = (), gpu: bool = False, knobs: tuple[str, ...] = (), native_formats: tuple[str, ...] = (), ir_features: frozenset[str] = frozenset({}), notes: str = '', update_orders: tuple[str, ...] = ())[source]

Bases: object

What an engine can do, declared rather than assumed (platform design rule 5).

knobs lists the knobs the engine honours for every model; an engine may honour fewer for a particular model and says so in Engine.refuse(). ir_features names the ABM-IR features it runs (for example substrates, rules, chemotaxis).

to_dict() → dict[str, Any][source]

The capabilities as a JSON-ready dict, with tuples as lists and ir_features sorted.

class abmfact.engines.base.Availability(ok: bool, detail: str, version: str | None = None)[source]

Bases: object

Whether an engine can run on this machine now, as reported by Engine.availability().

ok

True when the engine can prepare and run models here.

Type:

bool

detail

A short human-readable explanation, for example what is installed or what is missing.

Type:

str

version

The version of the simulator found, when the engine knows it; otherwise None.

Type:

str | None

class abmfact.engines.base.PreparedRun(engine: str, request: RunRequest, workdir: Path | None = None, argv: list[str] | None = None, call: Callable[[], ~abmfact.records.schema.RunOutputs] | None=None, env: dict[str, str]=<factory>, image: str | None = None, timeout: float | None = None, context: dict[str, ~typing.Any]=<factory>)[source]

Bases: object

A run ready to start: either an in-process call or a native argv run in workdir.

class abmfact.engines.base.RunHandle(prepared: PreparedRun, backend: str, status: str = 'done', outputs: RunOutputs | None = None, returncode: int | None = None, wall_time: float | None = None, log_path: Path | None = None, error: str | None = None, job_id: str | None = None, image_digest: str | None = None)[source]

Bases: object

A started (or finished) run on a backend.

abmfact.engines.base.MAPPING_GAINS = ('pressure_gain', 'motility_gain')

the scale on the contact fraction that stands in for pressure, and the scale on motility strength in lattice engines.

Type:

Translation coefficients between modelling paradigms that T2 translation may calibrate, and nothing else

abmfact.engines.base.gain_suffix(gains: Mapping[str, float]) → str[source]

A cache-key suffix for mapping gains: empty when every gain is 1, so T1 exports keep their keys.

abmfact.engines.base.changed_knobs(knobs: Knobs) → list[str][source]

Knob names that differ from their defaults, in KNOB_NAMES order.

class abmfact.engines.base.Engine[source]

Bases: ABC

Base class for engines. Subclasses set name and implement the four contract methods.

abstractmethod capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

availability() → Availability[source]

Report whether the engine can run on this machine, for example whether its simulator is installed.

The default reports a built-in engine that is always available. Override it when the engine needs an external program, library or container, and report what is missing in the result rather than raise.

Returns:

An Availability with ok, a short detail and, when known, the version.

load(model: Any) → Any[source]

Turn a user-supplied model (often a path) into what prepare() takes. Default: unchanged.

translation(model: Any) → FidelityReport | None[source]

How faithfully this engine would run model, from a dry run of its translation.

None means the engine runs the model as given, with nothing translated: a native project, or an ABM-IR model that the engine reads directly. An engine that translates ABM-IR into its own format overrides this and returns the fidelity report of that translation, without running anything.

support_for(model: Any) → Support[source]

The knobs this engine honours for this model, found by asking refuse() about each one.

update_order lists Capabilities.update_orders (the first is the default). rng_streams is declared only when the engine manages its own streams; otherwise the seed is remapped.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

seed_for(seed: int, knobs: Knobs) → int[source]

The seed to pass on: remapped for rng_streams=independent unless the engine honours it.

abstractmethod prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Set up one run without starting it.

The engine builds the RunRequest that identifies the run, applies the parameters, knobs and seed, and returns either an in-process call or a native argv with its workdir. The request must include everything that decides the result, because records are cached by its key.

Parameters:
  • model – The model as the user gave it or as returned by load(); built-in engines accept both.

  • params – Parameter values to set for this run; their names follow the engine’s own conventions.

  • knobs – The knob settings; run_once() checks them with refuse() before calling this.

  • seed – The seed requested by the user. An engine that does not manage its own random streams passes it through seed_for() before use, and records the requested seed.

  • workdir – A folder the engine may use for this run’s files, or None to choose its own.

Returns:

A PreparedRun that a backend can start.

Raises:

EngineError – The model cannot be run as requested.

run(prepared: PreparedRun, backend: Backend | None = None) → RunHandle[source]

Start a prepared run on a backend, by default the local one.

Local and container backends finish the run before returning. A failed native run is reported in the handle’s status and error rather than raised. Override this when the engine must choose the backend itself.

Parameters:
  • prepared – The run returned by prepare().

  • backend – The backend to submit to, or None for a LocalBackend.

Returns:

A RunHandle for the started or finished run.

abstractmethod collect(handle: RunHandle) → RunRecord[source]

Turn a finished run into a run record.

The engine reads its outputs into the common schema when the handle does not already hold them, and adds output paths and warnings. record() builds the record and sets status from the handle. A failed run should give a record with status="failed" rather than raise.

Parameters:

handle – The finished run returned by run().

Returns:

The RunRecord for the run.

run_once(model: Any, params: Mapping[str, Any] | None = None, seed: int = 0, knobs: Knobs | None = None, backend: Backend | None = None, workdir: Path | None = None, store: RunStore | None = None) → RunRecord[source]

Prepare, run and collect one run, refusing first if the engine cannot honour it.

With a store, an identical earlier request is returned from it (status="cached") and a new successful run is written to it, except while the cache is bypassed (determinism reruns), when the run always executes and the store is left as it was.

record(handle: RunHandle, **extra: Any) → RunRecord[source]

A run record from a finished handle; subclasses add output paths and warnings.

abmfact.engines.registry

Engine discovery: built-in engines plus any registered under the abmfact.engines entry point group.

A third-party package registers an engine in its pyproject.toml:

[project.entry-points."abmfact.engines"]
myengine = "mypackage.engine:MyEngine"
abmfact.engines.registry.BUILTIN: dict[str, str] = {'command': 'abmfact.engines.legacy:CommandEngine', 'compucell3d': 'abmfact.engines.compucell3d:CompuCell3DEngine', 'mesa': 'abmfact.engines.legacy:MesaEngine', 'morpheus': 'abmfact.engines.morpheus:MorpheusEngine', 'netlogo': 'abmfact.engines.legacy:NetLogoEngine', 'physicell': 'abmfact.engines.physicell:PhysiCellEngine', 'python': 'abmfact.engines.legacy:PythonEngine', 'reference': 'abmfact.engines.reference:ReferenceEngine'}

Built-in engines, imported only when used.

abmfact.engines.registry.engine_targets() → dict[str, str][source]

Engine name to module:Class. Installed entry points add to, but never replace, built-ins.

abmfact.engines.registry.list_engines() → dict[str, type[Engine]][source]

Every known engine name and its class, sorted by name; each class is imported.

Raises:

EngineError – A registered target is not an Engine subclass.

abmfact.engines.registry.get_engine(name: str, **options: Any) → Engine[source]

An instance of the engine called name, built with options as keyword arguments.

Raises:

EngineError – No engine has that name, or its target is not an Engine subclass.

abmfact.engines.recommend

Recommend which engine suits a model, from what each engine declares about itself.

Nothing here is specific to one engine. For each engine, the recommendation asks the engine contract four questions: can it run this model (refuse()), how faithfully (translation()), which audit checks become testable (support_for()), and is it installed here (availability()). A new engine improves the recommendations without any change to this module.

abmfact.engines.recommend.CONVERGENCE = 'convergence'

The convergence check is not an audit check, but it is testable wherever the time step is.

class abmfact.engines.recommend.Recommendation(engine: str, description: str, runs: bool, reasons: list[str] = <factory>, route: str = '', tier: str = '', fidelity: dict[str, int]=<factory>, losses: list[tuple[str, str, str]]=<factory>, checks: list[str] = <factory>, available: bool = False, detail: str = '')[source]

Bases: object

How well one engine suits one model.

engine

The engine’s registered name.

Type:

str

description

The engine’s one-line description.

Type:

str

runs

Whether the engine can run the model as it stands.

Type:

bool

reasons

Why it cannot, when runs is false.

Type:

list[str]

route

as given (a native project), reads ABM-IR (the engine’s own format) or translated.

Type:

str

tier

The fidelity tier of the route.

Type:

str

fidelity

The counts of exact, approximated, dropped and native parts, for a translated route.

Type:

dict[str, int]

losses

The parts that are not exact, as (path, status, note), for a translated route.

Type:

list[tuple[str, str, str]]

checks

The checks that become testable with this engine, in the order an audit runs them.

Type:

list[str]

available

Whether the engine runs on this machine now.

Type:

bool

detail

What is installed, or what is missing.

Type:

str

property loss: int

each dropped or native part counts ten, each approximation one.

Type:

A single number for ranking

rank_key() → tuple[int, int, int, int, str][source]

Sort key: engines that run first, then installed ones, then least loss, then most checks.

to_dict() → dict[str, Any][source]

The recommendation as a JSON-ready dictionary.

abmfact.engines.recommend.testable_checks(engine: Engine, model: Any) → list[str][source]

The audit checks, plus convergence, that engine can test for model.

abmfact.engines.recommend.assess(name: str, engine: Engine, model: Any) → Recommendation[source]

How well engine suits model; errors while loading become reasons, not exceptions.

abmfact.engines.recommend.recommend(model: Any, engines: Mapping[str, Engine] | None = None) → list[Recommendation][source]

Every engine’s fit for model, best first.

Parameters:
  • model – An ABM-IR model or file, or a native project folder.

  • engines – Engines to consider, by name; by default one instance of every registered engine.

Returns:

engines that can run the model first, then installed ones, then the least translation loss, then the most testable checks.

Return type:

One Recommendation per engine

abmfact.engines.legacy

The v0.1 adapters (Python, Mesa, NetLogo, command) as engines under the adapter contract.

The model is the adapter itself. prepare builds an in-memory run, the local backend calls the adapter exactly as v0.1 did, and collect returns a record whose scalars are the v0.1 outputs, so audits through this contract give the same results as before.

abmfact.engines.legacy.adapter_hash(adapter: Adapter) → str[source]

Identifies a v0.1 model by its description (target, name and declared support).

class abmfact.engines.legacy.AdapterEngine(adapter: Adapter | None = None)[source]

Bases: Engine

Runs any v0.1 Adapter.

adapter_type

alias of Adapter

capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Set up one run without starting it.

The engine builds the RunRequest that identifies the run, applies the parameters, knobs and seed, and returns either an in-process call or a native argv with its workdir. The request must include everything that decides the result, because records are cached by its key.

Parameters:
  • model – The model as the user gave it or as returned by load(); built-in engines accept both.

  • params – Parameter values to set for this run; their names follow the engine’s own conventions.

  • knobs – The knob settings; run_once() checks them with refuse() before calling this.

  • seed – The seed requested by the user. An engine that does not manage its own random streams passes it through seed_for() before use, and records the requested seed.

  • workdir – A folder the engine may use for this run’s files, or None to choose its own.

Returns:

A PreparedRun that a backend can start.

Raises:

EngineError – The model cannot be run as requested.

collect(handle: RunHandle) → RunRecord[source]

Turn a finished run into a run record.

The engine reads its outputs into the common schema when the handle does not already hold them, and adds output paths and warnings. record() builds the record and sets status from the handle. A failed run should give a record with status="failed" rather than raise.

Parameters:

handle – The finished run returned by run().

Returns:

The RunRecord for the run.

class abmfact.engines.legacy.PythonEngine(adapter: Adapter | None = None)[source]

Bases: AdapterEngine

Runs a v0.1 PythonAdapter, a Python callable run(params, seed, knobs).

adapter_type

alias of PythonAdapter

class abmfact.engines.legacy.MesaEngine(adapter: Adapter | None = None)[source]

Bases: AdapterEngine

Runs a v0.1 MesaAdapter, a Mesa 3 model class.

adapter_type

alias of MesaAdapter

availability() → Availability[source]

Available when the mesa package is installed; the version is the installed Mesa version.

class abmfact.engines.legacy.NetLogoEngine(adapter: Adapter | None = None)[source]

Bases: AdapterEngine

Runs a v0.1 NetLogoAdapter, a NetLogo model driven through pynetlogo.

adapter_type

alias of NetLogoAdapter

availability() → Availability[source]

Available when pynetlogo is installed and NETLOGO_HOME names an existing NetLogo folder.

class abmfact.engines.legacy.CommandEngine(adapter: Adapter | None = None)[source]

Bases: AdapterEngine

Runs a v0.1 CommandAdapter, a program that reads JSON on stdin and prints JSON.

adapter_type

alias of CommandAdapter

availability() → Availability[source]

Always available: the model names its own executable, which is not checked here.

abmfact.engines.legacy.engine_for_adapter(adapter: Adapter) → AdapterEngine[source]

The engine that runs this adapter; unknown Adapter subclasses get the generic engine.

abmfact.engines.model_adapter

Run an engine’s model inside a v0.1 audit: the bridge from the adapter contract back to run().

class abmfact.engines.model_adapter.EngineModelAdapter(engine: str, model: Any, options: Mapping[str, Any] | None = None, store: str | Path | None = None, name: str | None = None)[source]

Bases: Adapter

A model plus an engine, as a v0.1 adapter.

The model’s observables become the run’s outputs (one series each, plus time), so claims use the usual metric grammar, for example last(cells). The engine decides which knobs the model supports. With a store directory, each run is cached there; the index is JSON lines so that parallel audit workers can append to it safely.

describe() → dict[str, Any][source]

The adapter description (type, name and declared support) plus the engine name.

abmfact.engines.reference

The reference engine under the adapter contract.

abmfact.engines.reference.as_model(model: Any) → IRModel[source]

An ABM-IR model unchanged, or one loaded from a file path; anything else raises EngineError.

class abmfact.engines.reference.ReferenceEngine(solver: str = 'implicit')[source]

Bases: Engine

The built-in 2D NumPy engine that runs ABM-IR models in process.

solver selects the diffusion solver, "implicit" (the default) or "explicit", and is recorded in each run request’s outputs_spec.

capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

load(model: Any) → IRModel[source]

Turn a user-supplied model (often a path) into what prepare() takes. Default: unchanged.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Set up one run without starting it.

The engine builds the RunRequest that identifies the run, applies the parameters, knobs and seed, and returns either an in-process call or a native argv with its workdir. The request must include everything that decides the result, because records are cached by its key.

Parameters:
  • model – The model as the user gave it or as returned by load(); built-in engines accept both.

  • params – Parameter values to set for this run; their names follow the engine’s own conventions.

  • knobs – The knob settings; run_once() checks them with refuse() before calling this.

  • seed – The seed requested by the user. An engine that does not manage its own random streams passes it through seed_for() before use, and records the requested seed.

  • workdir – A folder the engine may use for this run’s files, or None to choose its own.

Returns:

A PreparedRun that a backend can start.

Raises:

EngineError – The model cannot be run as requested.

collect(handle: RunHandle) → RunRecord[source]

Turn a finished run into a run record.

The engine reads its outputs into the common schema when the handle does not already hold them, and adds output paths and warnings. record() builds the record and sets status from the handle. A failed run should give a record with status="failed" rather than raise.

Parameters:

handle – The finished run returned by run().

Returns:

The RunRecord for the run.

abmfact.engines.physicell

PhysiCell and PhysiBoSS: settings and rules files, native runs, and translation to and from ABM-IR.

abmfact.engines.physicell.engine

PhysiCell and PhysiBoSS under the adapter contract.

Native mode (fidelity tier T0) runs a PhysiCell project as it is. For each run the engine copies the project’s config/ folder into a work directory and edits only the settings that a run controls: the seed, the three time steps (times dt_scale), the voxel size (times dx_scale), the output folder and interval, SVG snapshots (off; they do not affect dynamics), and any parameters the request sets. The binary is built once per source hash (see build) and the run record pins the PhysiCell version and, for container builds, the image digest.

An ABM-IR model (fidelity tier T1) is exported onto PhysiCell’s template project first (see translate), once per model hash; ABM-IR parameter paths in the request change the model before export, and settings paths (overall/max_time, user_parameters.<name>) change the exported XML.

Outputs are read into the common schema. Observables are the ones passed as observables (ABM-IR observable specs), or by default: cells, live, dead, live_<type> for each cell type and <substrate>_mean for each substrate.

abmfact.engines.physicell.engine.default_observables(settings: SettingsXML) → list[dict[str, Any]][source]

The default observables for a settings file, as ABM-IR observable specs.

They are cells, live, dead, live_<type> for each cell definition and <substrate>_mean for each substrate. Names are lower case, with each run of non-word characters replaced by _.

class abmfact.engines.physicell.engine.PhysiCellEngine(toolchain: str = 'auto', image: str = 'abmfact/physicell:1.14.2', cache_dir: str | Path | None = None, source: str | Path | None = None, threads: int | None = None, save_interval: float | None = None, observables: Sequence[Mapping[str, Any]] | None = None, timeout: float | None = None, build_jobs: int = 4, reader: str = 'auto', base: str | Path | None = None)[source]

Bases: Engine

Runs PhysiCell 1.14.2 and PhysiBoSS projects as they are (tier T0), or ABM-IR models exported to one (tier T1).

Parameters:
  • toolchain – "auto" (native, then docker), "native" or "docker".

  • image – The container image for docker builds and runs.

  • cache_dir – The folder for builds, exports and runs; default ~/.cache/abmfact/physicell.

  • source – A PhysiCell source tree for native builds; otherwise PHYSICELL_SOURCE or the project itself.

  • threads – The OpenMP thread count to write into each run’s settings; None keeps the project’s value.

  • save_interval – The full-data save interval to write into the settings; None keeps the project’s value.

  • observables – ABM-IR observable specs to compute; None uses the model’s own or default_observables().

  • timeout – The time limit for each run, in seconds; None for no limit.

  • build_jobs – The number of parallel make jobs for a build.

  • reader – The output reader, "auto", "pcdl" or "minimal".

  • base – The project whose C++ code ABM-IR models are exported onto; default PhysiCell’s template.

property toolchain: Toolchain

The build route on this machine, detected on first use from the toolchain preference.

capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

availability() → Availability[source]

Available when a native or docker toolchain is found; detail then names it, else what is missing.

load(model: Any) → Any[source]

A project folder (tier T0), or an ABM-IR model or file (tier T1, exported before each run).

translation(model: Any) → FidelityReport | None[source]

The fidelity report of exporting an ABM-IR model to a PhysiCell project, or None for a project.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Build the project if needed and write a fresh run folder with this run’s settings.

An ABM-IR model is first exported under cache_dir/exports, once per model hash, and the binary is built under cache_dir/builds, once per source hash. The run folder is workdir plus the first 16 characters of the request key, replaced if it exists, or else a new folder under cache_dir/runs.

The run folder receives a copy of the project’s config/ folder and an empty output/ folder. Its config/PhysiCell_settings.xml is then edited: the seed, the time steps times dt_scale, the voxel size times dx_scale, the threads and save interval when set, the output folder, SVG snapshots off, and the parameters.

For a project folder every parameter is a settings path or user_parameters.<name>. For an ABM-IR model, keys containing / or starting with user_parameters. edit the XML. Other keys change the model before export.

Returns:

A run whose argv starts the binary on the settings file, natively or in the container. Its context carries a warning when dt_diffusion exceeds dt_mechanics.

run(prepared: PreparedRun, backend: Any = None) → RunHandle[source]

Start a prepared run; a docker build runs in a container backend, replacing any other backend given.

Without a backend, a native build runs on a local backend with the engine’s timeout.

collect(handle: RunHandle) → RunRecord[source]

Read the run’s output/ folder into the common schema and compute the observables.

Output that cannot be read gives a failed record. The record lists the output folder and the warnings from prepare().

abmfact.engines.physicell.build

Find a way to build PhysiCell, and build a project once per source hash.

Two routes, tried in this order:

  • native: a GNU g++ with OpenMP on this machine. PHYSICELL_CPP names it; otherwise g++-15 down to g++-11 (Homebrew’s names on macOS) and plain g++ are tried, and the one used must compile -fopenmp. Apple’s g++ is clang without OpenMP and is skipped. The PhysiCell sources come from the project itself (a full PhysiCell tree) or from PHYSICELL_SOURCE.

  • docker: the image from containers/physicell/Dockerfile (PhysiCell 1.14.2 sources in /opt/PhysiCell), run with Docker or Podman. The image digest pins the build.

A project is the folder PhysiCell’s make <sample> populates: main.cpp, Makefile, custom_modules/ and config/. Its build folder gets those files plus the PhysiCell core (BioFVM, core, modules, addons), and make runs with portable compiler flags: the template’s -march=native -mfpmath=both -m64 do not compile on 64-bit ARM, so they are replaced.

abmfact.engines.physicell.build.native_sources_set() → bool[source]

True when PHYSICELL_SOURCE points at a PhysiCell tree, so native builds work for any project.

class abmfact.engines.physicell.build.Toolchain(kind: str, detail: str, compiler: str | None = None, image: str | None = None, runtime: str | None = None)[source]

Bases: object

A way to build and run PhysiCell on this machine, as found by detect_toolchain().

kind

"native", "docker" or "none" when no route works.

Type:

str

detail

What was found, or what is missing when kind is "none".

Type:

str

compiler

The path of the GNU g++ for a native build.

Type:

str | None

image

The container image for a docker build.

Type:

str | None

runtime

"docker" or "podman" for a docker build.

Type:

str | None

property ok: bool

True unless kind is "none".

abmfact.engines.physicell.build.find_compiler(which: ~collections.abc.Callable[[str], str | None] = <function which>, runner: ~collections.abc.Callable[[...], ~typing.Any] = <function run>) → str | None[source]

A GNU g++ that compiles OpenMP code, or None.

abmfact.engines.physicell.build.detect_toolchain(prefer: str = 'auto', image: str = 'abmfact/physicell:1.14.2', which: ~collections.abc.Callable[[str], str | None] = <function which>, runner: ~collections.abc.Callable[[...], ~typing.Any] = <function run>) → Toolchain[source]

The first usable route (native, then docker), or kind="none" with what is missing.

abmfact.engines.physicell.build.is_project(path: Path) → bool[source]

True when path holds main.cpp, Makefile and a config/ folder.

abmfact.engines.physicell.build.source_hash(project: Path, toolchain: Toolchain, identity: str) → str[source]

Hash of everything that decides the binary: project sources, build script and toolchain identity.

abmfact.engines.physicell.build.build_project(project: ~pathlib.Path, toolchain: ~abmfact.engines.physicell.build.Toolchain, cache_dir: ~pathlib.Path, identity: str, source: ~pathlib.Path | None = None, maboss: bool = False, jobs: int = 4, runner: ~collections.abc.Callable[[...], ~typing.Any] = <function run>) → Path[source]

Build project once per source hash and return the build folder (the binary is BINARY in it).

abmfact.engines.physicell.settings

Read and edit a PhysiCell settings XML file (config/PhysiCell_settings.xml).

Element paths follow the PhysiCell 1.14.2 settings template. The file is parsed with the standard library and written back with its comments kept; only the elements that are set change. This module reads and writes the XML itself and does not use any third-party settings library.

exception abmfact.engines.physicell.settings.SettingsError[source]

Bases: ValueError

The settings file is missing an element or holds a value that cannot be read.

class abmfact.engines.physicell.settings.SettingsXML(root: Element, source: Path | None = None)[source]

Bases: object

A PhysiCell settings document. Paths are ElementTree paths relative to the root element.

classmethod read(path: str | Path) → SettingsXML[source]

Parse a settings file, keeping its comments.

Raises:

SettingsError – The file is not valid XML or its root element is not <PhysiCell_settings>.

write(path: str | Path) → Path[source]

Write the document to path, creating parent folders, and return the path.

find(path: str) → Element | None[source]

The first element at path, or None.

get(path: str, default: str | None = None) → str | None[source]

The stripped text at path, or default when the element is missing or has no text.

get_float(path: str) → float[source]

The number at path; raises SettingsError when it is missing or not a number.

get_bool(path: str, default: bool = False) → bool[source]

True when the text at path is true, 1 or yes in any case; default when it is missing.

set(path: str, value: Any, create: bool = False) → None[source]

Set the text at path; booleans are written true or false.

A missing element raises SettingsError unless create is true. Then it is added with any missing parents, except that a path step with a predicate such as [@name='x'] cannot be created.

user_parameters() → dict[str, tuple[str, str]][source]

{name: (type, text)} for every user parameter.

set_param(key: str, value: Any) → None[source]

Set user_parameters.<name> or any element by path, for example overall/max_time or cell_definitions/cell_definition[@name='tumour']/phenotype/motility/speed.

seed_paths() → list[str][source]

The seed elements present, from options/random_seed and user_parameters/random_seed.

set_seed(seed: int) → list[str][source]

Set every seed location present, adding options/random_seed (which the core reads) if absent.

Some sample projects seed from user_parameters/random_seed in their custom code instead, so both are set when both exist. Returns the paths set.

property is_2d: bool

Whether domain/use_2D is true; false when it is missing.

time_steps() → dict[str, float][source]

The dt_diffusion, dt_mechanics and dt_phenotype values from overall, keyed by those names.

scale_time_steps(factor: float) → None[source]

Multiply the three time steps by factor.

voxel() → dict[str, float][source]

The voxel size: dx, dy and dz from domain.

scale_voxels(factor: float) → None[source]

Scale the voxel size; in 2D only dx and dy, since dz is the slab thickness.

set_threads(n: int) → None[source]

Set the OpenMP thread count, parallel/omp_num_threads, adding the element if absent.

set_output(folder: str = 'output', interval: float | None = None, svg: bool = False) → None[source]

Where full data goes and how often; SVG snapshots off by default (they do not affect dynamics).

substrates() → list[Element][source]

The microenvironment_setup/variable elements, one per substrate.

cell_definitions() → list[Element][source]

The cell_definitions/cell_definition elements, one per cell type.

ruleset() → tuple[bool, Path | None][source]

Whether a rules CSV is enabled, and its path relative to the run folder.

cell_positions() → tuple[bool, Path | None][source]

Whether an initial cell positions CSV is enabled, and its path relative to the run folder.

abmfact.engines.physicell.rules

PhysiCell rules CSV files (cell behaviour hypothesis grammar, version 3).

The format, as PhysiCell 1.14.2 reads it in core/PhysiCell_rules.cpp (parse_csv_rule_v3): no header, eight columns cell_type, signal, direction, behavior, saturation value, half-max, Hill power, apply to dead. Lines with another number of fields or an empty field are skipped, which is how lines starting with // act as comments. Versions below 3 are rejected by PhysiCell.

class abmfact.engines.physicell.rules.RuleRow(cell_type: str, signal: str, direction: str, behaviour: str, saturation_value: float, half_max: float, hill_power: float, apply_to_dead: bool)[source]

Bases: object

One rule from a PhysiCell rules CSV: a signal that raises or lowers a behaviour of one cell type.

cell_type

The cell definition the rule applies to.

Type:

str

signal

The signal name, as PhysiCell spells it.

Type:

str

direction

"increases" or "decreases".

Type:

str

behaviour

The behaviour name, as PhysiCell spells it (the column is behavior there).

Type:

str

saturation_value

The behaviour value approached as the signal grows.

Type:

float

half_max

The signal value at which the response is half its maximum.

Type:

float

hill_power

The Hill power of the response.

Type:

float

apply_to_dead

Whether the rule also applies to dead cells.

Type:

bool

to_fields() → list[str][source]

The eight CSV fields in PhysiCell’s column order.

Whole numbers are written without a decimal point, and apply_to_dead as 1 or 0.

class abmfact.engines.physicell.rules.Skipped(line: int, text: str, reason: str)[source]

Bases: object

A line of a rules CSV that PhysiCell would skip.

line

The line number, counting from 1.

Type:

int

text

The line with surrounding whitespace removed.

Type:

str

reason

Why PhysiCell skips it.

Type:

str

abmfact.engines.physicell.rules.parse_rules(text: str) → tuple[list[RuleRow], list[Skipped]][source]

Rules and the lines PhysiCell would skip (comments, blanks and malformed lines), with reasons.

abmfact.engines.physicell.rules.read_rules_csv(path: str | Path) → tuple[list[RuleRow], list[Skipped]][source]

The rules in a CSV file and the lines PhysiCell would skip, as parse_rules() returns them.

abmfact.engines.physicell.rules.write_rules_csv(rows: list[RuleRow], path: str | Path, comment: str | None = None) → Path[source]

Write rows as a rules CSV at path, creating parent folders, and return the path.

Each line of comment is written first as a // line, which PhysiCell skips.

abmfact.engines.physicell.outputs

Read PhysiCell output into the common schema.

PhysiCell 1.14.2 writes one outputNNNNNNNN.xml (MultiCellDS) per saved time. It names a cells matrix (*_cells.mat, variable cells: one row per variable, one column per cell, rows described by the simplified_data/labels elements) and a microenvironment matrix (*_microenvironment0.mat, variable multiscale_microenvironment: rows x, y, z, voxel volume, then one row per substrate in ID order; one column per voxel, x varying fastest). Both are MATLAB v4 files.

With the [physicell] extra, pcdl reads the files; otherwise the minimal reader here does. Both give the same tables (a test checks this on real PhysiCell output).

abmfact.engines.physicell.outputs.output_files(folder: str | Path) → list[Path][source]

The saved outputNNNNNNNN.xml files in time order.

abmfact.engines.physicell.outputs.read_output(folder: str | Path, reader: str = 'auto') → RunOutputs[source]

Every saved time in a PhysiCell output folder, in the common schema.

reader is "auto" (pcdl when installed), "pcdl" or "minimal".

abmfact.engines.physicell.translate

Translate between PhysiCell projects and ABM-IR, with a fidelity report each way (tier T1).

Import reads the declarative part of a project: the settings XML, the rules CSV and the initial cell positions. Custom C++ in custom_modules is listed as a native extension and never translated. Export writes a settings XML, a rules CSV and a cells CSV onto PhysiCell’s own template project (bundled, BSD-3), or onto a project you give. Every field is reported as exact, approximated, dropped or native.

abmfact.engines.physicell.translate.TEMPLATE_CUSTOM = {'custom.cpp': '2f70de6e7087126585b724ab9e5bdc1cbdcdd6e18e17e728cf5fa20edf07780d', 'custom.h': 'fc4f19caec74ecfc175493e4a8d1ca5366e73f26cc3e52515195e9c9c4d5f4cd'}

SHA-256 of the 1.14.2 template’s custom code, to say whether a project’s custom code is the template’s.

abmfact.engines.physicell.translate.DT_ORDER_NOTE = 'dt_diffusion lowered to dt_mechanics: PhysiCell runs mechanics at most once per diffusion step with a fixed dt_mechanics, so a longer diffusion step would slow every cell down'

PhysiCell runs mechanics at most once per diffusion step, and Cell::update_position fixes its step from the first call, so a diffusion step longer than the mechanics step slows every cell down.

abmfact.engines.physicell.translate.MAX_DIFFUSION_NUMBER = 0.25

Largest dt_diffusion * D / dx^2 an export keeps. BioFVM’s diffusion solver splits the step by axis and is far from converged above it: in the Gate 3 spheroid (D 1e5, dx 20, dt 0.1, so 25) a field with no cells settled at 33.0 at its centre, where the converged value is 36.4; at 0.25 it was 36.3 and the spheroid matched the reference.

abmfact.engines.physicell.translate.exporter_fingerprint() → str[source]

A hash of this module’s code and the bundled template, so a changed exporter never reuses old exports.

abmfact.engines.physicell.translate.INERT_SUBSTRATE = 'substrate'

The template’s only substrate, kept (inert) when an ABM-IR model has none.

abmfact.engines.physicell.translate.import_project(project: str | Path, out_dir: str | Path | None = None) → tuple[IRModel, FidelityReport][source]

Read a PhysiCell project into ABM-IR. Files the model needs (cells CSV, intracellular models) are copied to out_dir when given, so the model is self-contained there.

abmfact.engines.physicell.translate.export_project(model: IRModel, out: str | Path, base: str | Path | None = None) → FidelityReport[source]

Write model as a PhysiCell project in out: the C++ of base (default: PhysiCell’s template) plus config/PhysiCell_settings.xml, config/cell_rules.csv and config/cells.csv.

abmfact.engines.compucell3d

CompuCell3D, a cellular Potts simulator: native project runs (tier T0).

abmfact.engines.compucell3d.engine

CompuCell3D under the adapter contract.

Native mode (fidelity tier T0) runs a CompuCell3D project as it is. For each run the engine copies the project into a run folder and edits only what a run controls in its CC3DML model: the seed in Potts/RandomSeed, any parameters given as element paths (such as Potts/Steps), and the CenterOfMass plugin, which tracks centroids and changes no dynamics. A small driver then starts CompuCell3D’s own runner on the project with one extra steppable registered, which writes each cell’s centre, type and volume, and every chemical field, at MCS 0, every save_every steps and the last step. The project’s Python code runs as written.

CompuCell3D works in lattice sites and Monte Carlo steps (MCS). Outputs are reported in micron and minutes through site_length and mcs_minutes, both 1 by default, which keeps the native units. A Monte Carlo step is not a time step, so dt_scale and dx_scale are refused; the seed is remapped for rng_streams. CompuCell3D reads a seed of 0 as “seed from the clock”, so seed 0 is passed as ZERO_SEED.

CompuCell3D 4.10.0 runs either with a Python that has the cc3d package (CC3D_PYTHON), or in the image built from containers/compucell3d/Dockerfile. That image is amd64 only, as CompuCell3D publishes no linux-aarch64 build, so on Apple silicon it runs under emulation.

abmfact.engines.compucell3d.engine.DEFAULT_SITE_LENGTH = 2.0

a cell of PhysiCell’s default volume covers about 55 sites in 2D.

Type:

Micron per site for ABM-IR exports

abmfact.engines.compucell3d.engine.driver_source() → str[source]

The driver script, shipped with the package and copied into each run folder.

abmfact.engines.compucell3d.engine.default_observables(project: CC3DProject) → list[dict[str, Any]][source]

cells, then cells_<type> for each cell type, then <field>_mean for each chemical field.

abmfact.engines.compucell3d.engine.BOOKKEEPING = frozenset({'.exported', 'fidelity.md'})

Files ABMfact writes beside an exported project. CompuCell3D never reads them, so they stay out of the run key.

class abmfact.engines.compucell3d.engine.CompuCell3DEngine(toolchain: str = 'auto', image: str = 'abmfact/compucell3d:4.10.0', cache_dir: str | Path | None = None, save_every: int | None = None, site_length: float | None = None, mcs_minutes: float = 1.0, observables: Sequence[Mapping[str, Any]] | None = None, timeout: float | None = None, pressure_gain: float = 1.0, motility_gain: float = 1.0)[source]

Bases: Engine

Runs CompuCell3D 4.10.0 projects as they are (tier T0).

Parameters:
  • toolchain – "auto" (a native CC3D_PYTHON, then the container), "native" or "docker".

  • image – The container image.

  • cache_dir – The folder for run folders; default ~/.cache/abmfact/compucell3d.

  • save_every – Save outputs every this many MCS; default a tenth of the run, at least 1.

  • site_length – Micron per lattice site: 1 for native projects (lattice units) and 2 for ABM-IR exports, unless given.

  • mcs_minutes – Minutes per Monte Carlo step, used to report times.

  • observables – ABM-IR observable specs to compute; None uses default_observables().

  • timeout – The time limit for each run, in seconds; None for no limit.

  • pressure_gain – Scale on the contact fraction that stands in for pressure in ABM-IR translations; 1 (T1) unless calibrated (T2).

  • motility_gain – Scale on the motility strength in ABM-IR translations; 1 (T1) unless calibrated (T2).

capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

seed_for(seed: int, knobs: Knobs) → int[source]

The seed written to Potts/RandomSeed: never 0, which CompuCell3D would replace with a clock seed.

availability() → Availability[source]

Available when CC3D_PYTHON names a Python with cc3d, or the container image is present.

load(model: Any) → Any[source]

A CompuCell3D project folder (tier T0), or an ABM-IR model or file (tier T1, exported before running).

translation(model: Any) → FidelityReport | None[source]

The fidelity report of exporting an ABM-IR model to a CompuCell3D project, or None for a project.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Copy the project into a run folder, set the seed and parameters, and add the output driver.

Every parameter is an element path in the CC3DML model, such as Potts/Steps or Plugin[@Name='Volume']/VolumeEnergyParameters[@CellType='Condensing']; the element’s text is set.

run(prepared: PreparedRun, backend: Any = None) → RunHandle[source]

Start a prepared run; a container run uses a container backend for the amd64 image.

collect(handle: RunHandle) → RunRecord[source]

Read the driver’s output into the common schema and compute the observables.

abmfact.engines.compucell3d.project

Read and edit CompuCell3D projects with the standard library only.

A project is a folder with one .cc3d file. That file names the CC3DML model (XMLScript), the Python main script (PythonScript) and any other resources, by paths relative to the project folder:

<Simulation version="3.5.1">
   <XMLScript Type="XMLScript">Simulation/cellsorting.xml</XMLScript>
   <PythonScript Type="PythonScript">Simulation/cellsorting.py</PythonScript>
   <Resource Type="Python">Simulation/cellsortingSteppables.py</Resource>
</Simulation>

The engine edits only what a run controls, in a copy of the project: the random seed in Potts/RandomSeed, the number of Monte Carlo steps in Potts/Steps, and the CenterOfMass plugin, which ABMfact’s output steppable reads and which does not change the dynamics.

class abmfact.engines.compucell3d.project.CC3DProject(folder: Path, cc3d_file: Path, xml_path: Path | None, python_script: Path | None, resources: list[Path] = <factory>, root: Element | None = None)[source]

Bases: object

One CompuCell3D project: where its files are, and its CC3DML model parsed for editing.

folder

The project folder.

Type:

pathlib.Path

cc3d_file

The .cc3d file in it.

Type:

pathlib.Path

xml_path

The CC3DML model, or None for a project specified in Python only.

Type:

pathlib.Path | None

python_script

The Python main script, or None.

Type:

pathlib.Path | None

resources

Other files the .cc3d file names, such as steppable modules.

Type:

list[pathlib.Path]

root

The parsed CC3DML model, edited in place by the setters.

Type:

xml.etree.ElementTree.Element | None

classmethod read(folder: str | Path) → CC3DProject[source]

Read the project in folder; it must hold exactly one .cc3d file.

dimensions() → tuple[int, int, int][source]

The lattice size in sites, from Potts/Dimensions.

steps() → int[source]

The number of Monte Carlo steps the model runs.

seed() → int | None[source]

The seed in Potts/RandomSeed, or None when the model draws its own.

cell_types() → list[str][source]

Cell type names in type-id order, without Medium.

fields() → list[str][source]

Chemical field names declared to any diffusion solver, in order and without repeats.

Newer models name a field as <DiffusionField Name="...">; older ones in <DiffusionData><FieldName>.

python_files() → list[Path][source]

The main script and every Python resource: custom code that ABMfact runs but never translates.

set_seed(seed: int) → None[source]

Set Potts/RandomSeed, adding it if absent.

set_steps(steps: int) → None[source]

Set Potts/Steps, the number of Monte Carlo steps.

ensure_center_of_mass() → None[source]

Add the CenterOfMass plugin if the model lacks it; it tracks centroids and changes no dynamics.

set(path: str, value: str | float | int) → None[source]

Set the text of the element at path (an ElementTree path from the CC3DML root).

write_xml() → None[source]

Write the edited CC3DML model back to xml_path.

abmfact.engines.compucell3d.project.is_project(path: str | Path) → bool[source]

True when path is a folder holding exactly one .cc3d file.

abmfact.engines.compucell3d.outputs

Read what ABMfact’s output steppable writes during a CompuCell3D run into the common output schema.

The steppable (see abmfact.engines.compucell3d.engine.DRIVER) writes, in the run’s output folder:

  • meta.json: the saved Monte Carlo steps, the lattice size and whether the model is 2D or 3D;

  • cells.csv: one row per cell per save, with mcs, id, type, x, y, z, volume, state, where x, y, z is the centre of mass in lattice sites and volume the number of sites;

  • fields_<mcs>.npz: one array per chemical field per save, indexed [x, y, z].

Positions, volumes and times are converted with the engine’s site_length (micron per site) and mcs_minutes (minutes per Monte Carlo step). Both default to 1, which keeps the native units. CompuCell3D cells have no apoptotic or necrotic state of their own: cells of native projects are reported live, and cells of models exported from ABM-IR carry the state ABMfact’s steppable keeps for them.

abmfact.engines.compucell3d.outputs.read_output(folder: str | Path, type_names: list[str], site_length: float = 1.0, mcs_minutes: float = 1.0, origin: tuple[float, float, float] = (0.0, 0.0, 0.0)) → RunOutputs[source]

The run’s cells and fields in the common schema, with times in minutes and lengths in micron.

type_names are the model’s cell types in type-id order, without Medium; rows of other types are skipped. origin is the position of the lattice’s first corner, so a model exported from ABM-IR reports positions in its own frame.

abmfact.engines.compucell3d.translate

Translate ABM-IR models to CompuCell3D projects (tier T1), with a fidelity report.

ABM-IR describes centre-based cells in micron and minutes; CompuCell3D is a cellular Potts model on a lattice of sites, advanced in Monte Carlo steps (MCS). Every quantity is converted with two stated scales, site_length (micron per site) and mcs_minutes (minutes per MCS), and the fidelity report names both.

The exported project has three parts:

  • a CC3DML model for what the cellular Potts model does natively: the lattice, cell types, the volume constraint, contact energies from adhesion, and diffusion with decay and boundary values;

  • abmfact_model.json, the rest of the model converted to lattice units;

  • a generic steppable module that runs it: placements, the live cycle, death and removal, Hill-type rules, persistent and chemotactic motility, secretion and uptake, attack and damage, and timed events.

What has no exact counterpart is marked approximated with a note, never converted silently: contact energies from adhesion strengths, the volume stiffness, motility strength, pressure (read as the fraction of a cell’s boundary in contact with other cells), and diffusion coefficients too large for the explicit solver.

abmfact.engines.compucell3d.translate.J_MEDIUM = 10.0

Contact energy between a cell and the medium; cells adhere to each other when J(a, b) < 2 * J_MEDIUM.

abmfact.engines.compucell3d.translate.ADHESION_REF = 0.4

The PhysiCell default adhesion strength, which maps to J(a, b) = J_MEDIUM.

abmfact.engines.compucell3d.translate.LAMBDA_VOLUME = 2.0

Volume constraint stiffness; cellular Potts only.

abmfact.engines.compucell3d.translate.TEMPERATURE = 10.0

Temperature of the Metropolis dynamics.

abmfact.engines.compucell3d.translate.MOTILITY_LAMBDA = 50.0

External-potential strength per site per MCS of requested speed.

abmfact.engines.compucell3d.translate.MAX_DIFFUSION = 200.0

Largest diffusion coefficient, in sites squared per MCS, run without capping; the explicit solver substeps automatically, so its cost grows with the coefficient.

abmfact.engines.compucell3d.translate.cc3d_name(name: str) → str[source]

A CompuCell3D type name for an ABM-IR name: non-word characters become underscores.

abmfact.engines.compucell3d.translate.exporter_fingerprint() → str[source]

A hash of this module and the steppable template, so a changed exporter never reuses old exports.

abmfact.engines.compucell3d.translate.export_project(model: IRModel, out: str | Path, site_length: float = 2.0, mcs_minutes: float = 1.0, pressure_gain: float = 1.0, motility_gain: float = 1.0) → FidelityReport[source]

Write model as a CompuCell3D project in out and return what was kept, approximated or dropped.

pressure_gain scales the contact fraction that stands in for pressure, and motility_gain the strength of the motility potential. Both are 1 in a structural (T1) translation; T2 translation calibrates them.

abmfact.engines.compucell3d.translate.import_project(folder: str | Path, site_length: float = 1.0, mcs_minutes: float = 1.0) → tuple[IRModel, FidelityReport][source]

Read a CompuCell3D project into ABM-IR, with what was kept, approximated, dropped or left native.

Lattice sites become site_length micron and Monte Carlo steps mcs_minutes minutes; with the defaults the model stays in lattice units. Only what the CC3DML declares is read; the project’s Python code is a native extension, run by CompuCell3D and never translated.

abmfact.engines.morpheus

Morpheus, a modelling environment for multicellular systems: native model runs (tier T0).

abmfact.engines.morpheus.engine

Morpheus under the adapter contract.

Native mode (fidelity tier T0) runs a MorpheusML model as it is. An ABM-IR model is first translated to a MorpheusML model (tier T1, abmfact.engines.morpheus.translate) and the export is cached by the model’s hash, the translator’s own hash and the two scales. For each run the engine copies the model into a run folder, sets any element a parameter names, and adds two loggers to its Analysis section: one for each cell’s id, type, centre and volume, one for every field. Loggers are Morpheus’s own output components and change no dynamics. Morpheus then runs with the seed, one thread unless told otherwise, gnuplot off, and the run’s output folder, all on its command line.

Morpheus models carry their own units: lattice nodes, and time in whatever unit the model chose. Outputs are reported in micron and minutes through node_length and time_minutes. Both are 1 by default for native models, which keeps the model’s own units; translated models use 2 micron per node and 1 minute per step. Refining the time step or the lattice of a cellular Potts model needs other parameters rescaled with it, so dt_scale and dx_scale are refused. Morpheus has one random stream, set by the seed on its command line, so rng_streams is tested by remapping the seed.

Morpheus 2.4.1 runs either from MORPHEUS_BIN (a morpheus executable) or in the image built from containers/morpheus/Dockerfile, which holds the static x86-64 binary Morpheus publishes; on Apple silicon that image runs under emulation.

abmfact.engines.morpheus.engine.default_observables(model: MorpheusModel) → list[dict[str, Any]][source]

cells, then cells_<type> for each cell type, then <field>_mean for each field.

class abmfact.engines.morpheus.engine.MorpheusEngine(toolchain: str = 'auto', image: str = 'abmfact/morpheus:2.4.1', cache_dir: str | Path | None = None, save_every: float | None = None, node_length: float | None = None, time_minutes: float = 1.0, threads: int = 1, observables: Sequence[Mapping[str, Any]] | None = None, timeout: float | None = None, pressure_gain: float = 1.0, motility_gain: float = 1.0)[source]

Bases: Engine

Runs Morpheus 2.4.1 models as they are (tier T0), and ABM-IR models through a translation (tier T1).

Parameters:
  • toolchain – "auto" (a native MORPHEUS_BIN, then the container), "native" or "docker".

  • image – The container image.

  • cache_dir – The folder for run folders; default ~/.cache/abmfact/morpheus.

  • save_every – Save outputs every this many model time units; default a tenth of the run.

  • node_length – Micron per lattice node: 1 for native models (lattice units) and 2 for ABM-IR exports, unless given.

  • time_minutes – Minutes per Morpheus time unit, used to report times.

  • threads – Morpheus threads; 1 by default, so a seed always gives the same run.

  • pressure_gain – Scale on the contact fraction that stands in for pressure in ABM-IR translations; 1 (T1) unless calibrated (T2).

  • motility_gain – Scale on the motility strength in ABM-IR translations; 1 (T1) unless calibrated (T2).

  • observables – ABM-IR observable specs to compute; None uses default_observables().

  • timeout – The time limit for each run, in seconds; None for no limit.

capabilities() → Capabilities[source]

Declare what this engine can do, for every model it runs.

It takes no model, so it describes the engine as a whole; refuse() reports the limits for a particular model. The default refuse() and support_for() read knobs and update_orders from it.

Returns:

The engine’s Capabilities.

availability() → Availability[source]

Available when MORPHEUS_BIN names a morpheus executable, or the container image is present.

load(model: Any) → Any[source]

A MorpheusML model file (tier T0), or an ABM-IR model or file (tier T1, translated before running).

translation(model: Any) → FidelityReport | None[source]

The fidelity report of translating an ABM-IR model to Morpheus, or None for a MorpheusML model.

refuse(model: Any, knobs: Knobs) → list[str][source]

Reasons this engine cannot honour the request; empty when it can run it.

The default refuses knobs outside Capabilities.knobs. rng_streams is always honoured, because seed_for() remaps the seed when an engine does not manage its own streams.

prepare(model: Any, params: Mapping[str, Any], knobs: Knobs, seed: int, workdir: Path | None = None) → PreparedRun[source]

Copy the model into a run folder, set parameters, add the loggers, and build the command line.

A parameter Time/StopTime sets the stop time; a parameter with a / is an element path whose value attribute is set, such as Global/Constant[@symbol='d']. For an ABM-IR model, a dotted parameter such as cell_types[tumour].volume is applied to the model before it is translated.

run(prepared: PreparedRun, backend: Any = None) → RunHandle[source]

Start a prepared run; a container run uses a container backend for the amd64 image.

collect(handle: RunHandle) → RunRecord[source]

Read the loggers’ output into the common schema and compute the observables.

abmfact.engines.morpheus.model

Read and edit MorpheusML models with the standard library only.

A Morpheus model is one XML file (<MorpheusModel version="...">). The engine edits only what a run controls, in a copy: the stop time when a parameter sets it, any element a parameter names, and two loggers ABMfact adds to the Analysis section. One logs each cell’s id, type, centre and volume; the other logs every field, one file per save. Loggers are Morpheus’s own output components and change no dynamics. The seed and the thread count are set on the command line.

class abmfact.engines.morpheus.model.MorpheusModel(path: Path, root: Element)[source]

Bases: object

One MorpheusML model, parsed for reading and editing.

path

The model file.

Type:

pathlib.Path

root

The parsed MorpheusModel element, edited in place by the setters.

Type:

xml.etree.ElementTree.Element

classmethod read(path: str | Path) → MorpheusModel[source]

Read the model at path; it must be a MorpheusModel document.

property version: str

The MorpheusML version the file declares.

title() → str[source]

The model’s title, or the file name.

lattice() → tuple[int, int, int][source]

The lattice size in nodes, from Space/Lattice/Size; a size can be an expression only in 2.4+.

dimensions() → int[source]

2 for a flat lattice (z of 0 or 1), else 3.

stop_time() → float[source]

The model’s stop time, in its own time units.

cell_types() → list[str][source]

Every cell type name in declaration order, including the medium; cell.type indexes this list.

biological_types() → list[str][source]

Cell types that are cells, not the medium.

fields() → list[str][source]

Symbols of the global fields, the model’s chemical fields.

set_stop_time(value: float) → None[source]

Set Time/StopTime.

set(path: str, value: str | float | int) → None[source]

Set the value attribute of the element at path (an ElementTree path from the root).

add_output_loggers(every: float, cell_symbols: tuple[str, ...] = ()) → tuple[int, int][source]

Add ABMfact’s cell and field loggers, saving every every time units.

cell_symbols are logged for each cell after the standard ones, such as the state property of a translated model.

Returns:

The 1-based positions of the two loggers among the model’s loggers, which name their files (logger_<n>.csv and logger_<n>_<time>.csv). The first is 0 when the model has no cell types, as Morpheus refuses cell symbols then; the second is 0 when the model has no fields.

write(path: str | Path | None = None) → Path[source]

Write the model to path, by default where it was read from.

abmfact.engines.morpheus.model.is_model(path: str | Path) → bool[source]

True when path is an XML file whose root element is MorpheusModel.

abmfact.engines.morpheus.outputs

Read what ABMfact’s two loggers write during a Morpheus run into the common output schema.

The cell logger writes one tab-separated file, logger_<n>.csv (logger.csv when it is the model’s only logger), with a row per cell per save: time, cell.id (added by Morpheus), then the logged cell.id, cell.type (an index into the model’s cell types), cell.center.x, cell.center.y (and cell.center.z in 3D) and cell.volume in lattice nodes. The field logger writes one file per save, logger_<m>_<time>.csv, with time, space.x, space.y (and space.z) and one column per field.

Lengths are converted with node_length (micron per node) and times with time_minutes (minutes per Morpheus time unit); both default to 1, which keeps the model’s own units. Morpheus cells have no apoptotic or necrotic state of their own, so every cell is reported live unless the logger has a state column, which models translated from ABM-IR keep (0 live, 1 apoptotic, 2 necrotic).

abmfact.engines.morpheus.outputs.read_output(folder: str | Path, type_names: list[str], loggers: tuple[int, int], node_length: float = 1.0, time_minutes: float = 1.0, origin: tuple[float, float, float] = (0.0, 0.0, 0.0), dimensions: int = 2) → RunOutputs[source]

The run’s cells and fields in the common schema.

Parameters:
  • folder – The run’s output folder.

  • type_names – The model’s cell types in declaration order, including the medium.

  • loggers – The 1-based positions of ABMfact’s cell and field loggers; 0 for a logger not added.

  • node_length – Micron per lattice node.

  • time_minutes – Minutes per Morpheus time unit.

  • origin – The position of the lattice’s first corner, so translated models report their own frame.

  • dimensions – 2 or 3, for converting volumes.

abmfact.engines.morpheus.translate

Translate between ABM-IR models and Morpheus models (tier T1), with a fidelity report.

Morpheus can say most of ABM-IR in its own language, so the translation is one MorpheusML file with no extra code. Lengths are converted with node_length (micron per lattice node) and times with time_minutes (minutes per Morpheus time unit, which is also one Monte Carlo step); the fidelity report names both.

  • Each cell keeps its state (live, apoptotic, necrotic), its damage and its behaviours as cell properties. A behaviour with rules is PhysiCell 1.14.2’s Hill combination written as a Morpheus expression; the signals come from Mapper (the field under the cell) and NeighborhoodReporter (contacts and neighbours).

  • Division, death and removal are CellDivision, Event and CellDeath with the per-step probabilities of the ABM-IR rates. Fields are DiffEqn with secretion and uptake by the cells covering each node.

  • A drug pulse is a pair of Event that set the boundary value while the event lasts.

Chemotaxis is DirectedMotion along the gradient’s direction averaged over the cell, from two helper fields, as ABM-IR’s chemotaxis follows the gradient’s direction only. A field whose diffusion is capped for speed has its reactions slowed by the same factor, which keeps its steady profile.

What has no exact counterpart is marked approximated with a note: contact energies, the volume constraint, motility and chemotaxis strengths, capped diffusion, pressure (the fraction of the cell’s boundary touching other cells), attack (damage from each touching effector at the steady share of time an effector spends attacking), and a boundary that is no-flux in ABM-IR but holds a value while an event lasts.

import_model() reads a MorpheusML model back: the lattice, cell types, target areas, contact energies, fields and circle or rectangle initialisers, with rates read where they are plain numbers. Everything else is listed as dropped.

abmfact.engines.morpheus.translate.translator_fingerprint() → str[source]

A hash of this module, so a changed translator never reuses an old export.

abmfact.engines.morpheus.translate.symbol(name: str) → str[source]

A Morpheus symbol for an ABM-IR name: non-word characters become underscores.

abmfact.engines.morpheus.translate.export_model(model: IRModel, out: str | Path, node_length: float = 2.0, time_minutes: float = 1.0, pressure_gain: float = 1.0, motility_gain: float = 1.0) → FidelityReport[source]

Write model as a Morpheus model in the folder out and return what was kept or changed.

pressure_gain scales the contact fraction that stands in for pressure, and motility_gain the strength of persistent and directed motion. Both are 1 in a structural (T1) translation; T2 translation calibrates them.

abmfact.engines.morpheus.translate.import_model(path: str | Path, node_length: float = 1.0, time_minutes: float = 1.0) → tuple[IRModel, FidelityReport][source]

Read a MorpheusML model into ABM-IR, with what was kept, approximated or dropped.

Lattice nodes become node_length micron and Morpheus time units time_minutes minutes; with the defaults the model stays in its own units. Rates and speeds are read only where the model gives them as plain numbers, as an export from ABM-IR does; any other expression is reported as dropped.