Modes

Running one model many times: the shared run loop, ensembles of seeds, sweeps over parameter designs, sensitivity analysis, calibration, T2 translation and visualisation.

abmfact.modes

Modes beyond a single run: ensembles of seeds, parameter sweeps and sensitivity analysis.

Each mode runs one model through the engine contract, many times, and reuses the run store so a repeated or interrupted mode picks up where it stopped. Submodules are imported on use, so import abmfact stays light.

abmfact.modes.batch

Run many jobs of one model: each job is an engine, its options, parameters and a seed.

This is the run loop every mode shares, and the one abmfact compare uses. Jobs run on the local backend, one process per worker; an engine that works in a container starts the container itself. Workers read the run store but never write it: the parent stores each finished run, so a mode that is run again, or resumed after an interruption, reuses every run that already finished.

class abmfact.modes.batch.Job(engine: str, seed: int, params: Mapping[str, ~typing.Any]=<factory>, options: Mapping[str, ~typing.Any]=<factory>, label: str = '')[source]

Bases: object

One run: an engine with its options, ABM-IR or native parameters, and a seed.

engine

The engine name, as for run-model --engine.

Type:

str

seed

The seed.

Type:

int

params

Parameters for this run: ABM-IR dotted paths, or native paths for engines that take them.

Type:

collections.abc.Mapping[str, Any]

options

Engine options, as for run-model --option.

Type:

collections.abc.Mapping[str, Any]

label

A name for the setting, such as a design point; runs with a label get their own folder.

Type:

str

folder(root: Path) → Path[source]

Where this run’s working files go under root.

class abmfact.modes.batch.JobResult(job: Job, record: RunRecord | None = None, error: str | None = None)[source]

Bases: object

What one job gave: a run record, or the error that stopped it before a record existed.

job

The job.

Type:

Job

record

The run record; its status says whether the run worked, and cached when it was reused.

Type:

RunRecord | None

error

Why no record exists.

Type:

str | None

property ok: bool

True when the run worked and its outputs are loaded.

property problem: str | None

Why the run gave no outputs, or None when it did.

abmfact.modes.batch.make_engine(name: str, options: Mapping[str, Any] | None = None) → Engine[source]

The engine name with options.

abmfact.modes.batch.warm_up(model: str | Path, engine: str, options: Mapping[str, Any], params: Mapping[str, Any], workdir: Path) → None[source]

Prepare one run in this process, so builds and translations are cached before workers start.

abmfact.modes.batch.engine_status(name: str, model: str | Path, options: Mapping[str, Any] | None = None) → tuple[str | None, dict[str, Any]][source]

(reason not to run, description) for one engine, with its fidelity report when it translates.

abmfact.modes.batch.run_batch(model: str | Path, jobs: Sequence[Job], *, workdir: str | Path | None = None, store: str | Path | None = None, workers: int = 1, warm: bool = True, progress: Callable[[int, int], None] | None = None) → list[JobResult][source]

Run every job and return their results in job order.

Parameters:
  • model – The model file or native project every job runs.

  • jobs – The runs.

  • workdir – Where run folders go; a temporary folder by default, removed afterwards.

  • store – A run store. Runs already in it are reused; new runs that worked are added to it.

  • workers – Runs at once.

  • warm – Prepare one run per distinct engine, options and parameters first, in this process, so builds and translations exist before workers start. A setting that cannot be prepared fails its jobs.

  • progress – Called with (done, total) after each run.

abmfact.modes.ensemble

Ensemble mode: many seeds of one setting in one engine, summarised with intervals.

Every observable series is summarised at each save time across the seeds: the mean with its 1 - 2*alpha t-interval (the interval the audit and compare use), the standard deviation and the 5%, 50% and 95% quantiles. Metrics such as last(cells) are summarised the same way, with each seed’s value kept. Runs go through the run store, so a larger ensemble later reuses the seeds already run.

abmfact.modes.ensemble.summarise(values: Sequence[float], alpha: float) → dict[str, float | int][source]

The mean with its interval, the standard deviation and the 5%, 50% and 95% quantiles of values.

abmfact.modes.ensemble.series_by_time(outputs: Sequence[Mapping[str, Any]]) → dict[str, dict[float, list[float]]][source]

Every observable series in outputs (each run’s scalars), as values per save time.

A series counts when it has one value per entry of the run’s time. Runs with different save times are aligned by time, so a time reached by fewer runs has a smaller n.

class abmfact.modes.ensemble.EnsembleResult(data: dict[str, Any])[source]

Bases: object

The outcome of an ensemble.

data

The settings, the engine and its fidelity, run counts, every seed’s run id, each observable’s summary per save time, and each metric’s summary with its per-seed values.

Type:

dict[str, Any]

to_json(include_timestamp: bool = True) → str[source]

The result as JSON; without the timestamp it is the same for the same runs.

rows() → list[list[Any]][source]

One row per observable and save time: name, time, n, mean, low, high, sd, q05, q50, q95.

write(out: str | Path) → dict[str, Path][source]

Write ensemble.json, ensemble.csv and report.html to out.

abmfact.modes.ensemble.run_ensemble(model: str | Path, engine: str = 'reference', seeds: int = 20, *, seed_start: int = 0, params: Mapping[str, Any] | None = None, options: Mapping[str, Any] | None = None, metrics: Sequence[str] = (), alpha: float = 0.05, jobs: int = 1, workdir: str | Path | None = None, store: str | Path | None = None, progress: Callable[[int, int], None] | None = None) → EnsembleResult[source]

Run seeds seeds of one setting and summarise every observable and metric.

Parameters:
  • model – An ABM-IR file, or a native project for engines that take one.

  • engine – The engine.

  • seeds – How many seeds, from seed_start.

  • seed_start – The first seed.

  • params – Parameters applied in every run.

  • options – Engine options.

  • metrics – Metric expressions to summarise, such as last(cells).

  • alpha – One-sided level; intervals cover 1 - 2*alpha (90% by default).

  • jobs – Runs at once.

  • workdir – Where run folders go; a temporary folder by default.

  • store – A run store; runs already in it are reused and new ones kept.

  • progress – Called with (done, total) after each run.

abmfact.modes.ensemble.summarise_results(model: str | Path, engine: str, results: Sequence[JobResult], *, info: Mapping[str, Any] | None = None, params: Mapping[str, Any] | None = None, options: Mapping[str, Any] | None = None, metrics: Sequence[Metric] = (), alpha: float = 0.05, seed_start: int = 0) → EnsembleResult[source]

Summarise finished runs of one setting as an ensemble (used by run_ensemble and by other modes).

abmfact.modes.ensemble.render_html(result: EnsembleResult) → str[source]

The ensemble as a self-contained HTML page: settings, runs, metrics and every series.

abmfact.modes.design

Parameters and designs for sweeps: full grids, Latin hypercubes and scrambled Sobol sequences.

A parameter is named the way runs take it:

  • an ABM-IR dotted path such as cell_types[tumour].cycle.rates[0];

  • a native path with / for engines that read their own files, such as overall/dt_mechanics;

  • option:NAME for an engine option, such as option:pressure_gain.

Designs are drawn on the unit cube with scipy.stats.qmc and scaled to each parameter’s range, linearly or on a log scale. Sobol points keep their balance only in powers of two, so other sizes give a warning.

exception abmfact.modes.design.DesignError[source]

Bases: ValueError

A parameter or design is not valid.

exception abmfact.modes.design.DesignWarning[source]

Bases: UserWarning

A design that runs but is weaker than it could be.

class abmfact.modes.design.Parameter(name: str, low: float, high: float, scale: Literal['linear', 'log'] = 'linear', integer: bool = False)[source]

Bases: object

One varied parameter and its range.

name

The parameter as runs take it: an ABM-IR path, a native path with /, or option:NAME.

Type:

str

low

The lower end of the range.

Type:

float

high

The upper end of the range.

Type:

float

scale

linear, or log for a range that spans orders of magnitude (both ends positive).

Type:

Literal[‘linear’, ‘log’]

integer

Round values to whole numbers.

Type:

bool

property kind: str

option for engine options, native for native paths, else ir.

property key: str

the option name for options, else the parameter path.

Type:

The name runs use

scaled(u: ndarray) → ndarray[source]

Map points u in [0, 1] onto this parameter’s range.

unit(v: ndarray) → ndarray[source]

Map values on this parameter’s range back to [0, 1].

classmethod from_mapping(raw: Mapping[str, Any]) → Parameter[source]

A parameter from {name, low, high, scale, integer}.

abmfact.modes.design.grid(params: Sequence[Parameter], levels: int | Sequence[int]) → ndarray[source]

Every combination of evenly spaced levels; one level is the middle of the range. Rows are points.

abmfact.modes.design.latin_hypercube(params: Sequence[Parameter], n: int, seed: int = 0) → ndarray[source]

n points with one point in each of n equal strata of every parameter.

abmfact.modes.design.sobol(params: Sequence[Parameter], n: int, seed: int = 0, scramble: bool = True) → ndarray[source]

n points of a (scrambled) Sobol sequence; balanced only when n is a power of two.

abmfact.modes.design.make_design(params: Sequence[Parameter], method: str, n: int | None = None, levels: int | Sequence[int] | None = None, seed: int = 0) → ndarray[source]

The points of a grid (with levels), lhs or sobol design (with n).

abmfact.modes.design.setting(params: Sequence[Parameter], point: Sequence[float], base_params: Mapping[str, Any] | None = None, base_options: Mapping[str, Any] | None = None) → tuple[dict[str, Any], dict[str, Any]][source]

The run parameters and engine options for one design point, on top of the fixed ones.

abmfact.modes.sweep

Sweep mode: run one model over a design of parameter settings, each with a few seeds.

A sweep file names the model, engine, varied parameters with their ranges, the design (a full grid, a Latin hypercube lhs or a scrambled sobol sequence), seeds per point and the metrics to record. Every point runs the same seeds, so differences between points are not blurred by different random streams. Runs go through the run store: a sweep that is run again, or stopped and restarted, reuses every finished run.

On a cluster, backend: slurm writes a Slurm job array for the runs not yet in the store. Each array task runs abmfact run-model into its own folder; collect then reads those folders back and summarises them.

class abmfact.modes.sweep.SweepSpec(title: str, model: ~pathlib.Path, engine: str, parameters: list[~abmfact.modes.design.Parameter], method: str = 'lhs', n: int | None = None, levels: int | list[int] | None = None, design_seed: int = 0, seeds_per_point: int = 1, seed_start: int = 0, params: dict[str, ~typing.Any] = <factory>, options: dict[str, ~typing.Any] = <factory>, metrics: list[~abmfact.claims.Metric] = <factory>, jobs: int = 1, alpha: float = 0.05, slurm: dict[str, ~typing.Any] = <factory>)[source]

Bases: object

A parsed sweep.

title

A short title.

Type:

str

model

The ABM-IR file or native project.

Type:

pathlib.Path

engine

The engine.

Type:

str

parameters

The varied parameters.

Type:

list[abmfact.modes.design.Parameter]

method

grid, lhs or sobol.

Type:

str

n

Points for lhs and sobol.

Type:

int | None

levels

Levels per parameter for grid.

Type:

int | list[int] | None

design_seed

The seed that draws lhs and sobol points.

Type:

int

seeds_per_point

Seeds at every point (the same seeds everywhere).

Type:

int

seed_start

The first seed.

Type:

int

params

Fixed parameters for every run.

Type:

dict[str, Any]

options

Fixed engine options.

Type:

dict[str, Any]

metrics

Metrics recorded for every run.

Type:

list[abmfact.claims.Metric]

jobs

Runs at once.

Type:

int

alpha

One-sided level for intervals.

Type:

float

slurm

Job-array settings for backend: slurm.

Type:

dict[str, Any]

points() → ndarray[source]

The design: one row per point, one column per parameter.

jobs_for(points: ndarray) → list[Job][source]

Every run: each point with each seed, labelled p0000, p0001 and so on.

abmfact.modes.sweep.load_sweep(path: str | Path, overrides: Mapping[str, Any] | None = None) → SweepSpec[source]

Read a sweep file; relative paths are resolved against its folder.

overrides replaces top-level keys, such as jobs from the command line.

abmfact.modes.sweep.spec_from_mapping(raw: Mapping[str, Any], base: Path, title: str = 'sweep') → SweepSpec[source]

A sweep from a parsed mapping, with paths relative to base.

class abmfact.modes.sweep.SweepResult(data: dict[str, Any])[source]

Bases: object

The outcome of a sweep.

data

The settings, the design points, every run with its metrics, each point’s summary per metric (mean with interval over its seeds), and run counts.

Type:

dict[str, Any]

to_json(include_timestamp: bool = True) → str[source]

The result as JSON; without the timestamp it is the same for the same runs.

values(metric: str) → ndarray[source]

Each point’s mean of metric over its seeds, in point order (NaN where no run gave it).

write(out: str | Path) → dict[str, Path][source]

Write sweep.json, design.csv, runs.csv, summary.csv and report.html.

abmfact.modes.sweep.run_sweep(spec: SweepSpec, *, points: ndarray | None = None, workdir: str | Path | None = None, store: str | Path | None = None, progress: Callable[[int, int], None] | None = None, collect_from: str | Path | None = None) → SweepResult[source]

Run every point of the design with its seeds and summarise each metric per point.

Parameters:
  • spec – The sweep.

  • points – Run these points instead of the spec’s design (rows are points); used by sensitivity analysis.

  • workdir – Where run folders go; a temporary folder by default.

  • store – A run store; finished runs are reused, new ones kept.

  • progress – Called with (done, total) after each run.

  • collect_from – Read the runs that a Slurm job array wrote under this folder instead of running them.

abmfact.modes.sweep.summarise_sweep(spec: SweepSpec, points: ndarray, results: Sequence[JobResult], info: Mapping[str, Any] | None = None) → SweepResult[source]

Turn finished runs into a sweep result: per-run metrics and a per-point summary.

abmfact.modes.sweep.write_slurm(spec: SweepSpec, out: str | Path, store: str | Path | None = None, submit: bool = False, points: ndarray | None = None) → tuple[Path | None, int, int][source]

Write a Slurm job array for every run not yet in store; submit it only when asked.

Returns (script or None, runs written, runs already stored). Each task runs abmfact run-model (or slurm.command) into out/jobs/<point>/seed-<n>; collect them with run_sweep(..., collect_from=out).

abmfact.modes.sweep.render_html(result: SweepResult) → str[source]

The sweep as a self-contained HTML page: settings, run counts and each point’s summary.

abmfact.modes.sensitivity

Sensitivity mode: Sobol (Saltelli) and Morris indices with bootstrap intervals, through SALib.

A sensitivity file is a sweep file without design and with a sensitivity section instead. SALib draws the points on the unit cube; each is scaled to its parameter’s range (linearly or on a log scale), run as a sweep point with seeds_per_point seeds, and the point’s mean is the model output SALib analyses. So the indices are for the parameters’ distributions as stated: uniform on the range, or log-uniform on a log scale. Morris effects are per unit of that scaled range.

  • Sobol: first-order (S1) and total (ST) indices, and second-order (S2) when asked, with 95% bootstrap intervals. The design needs N * (D + 2) points, or N * (2D + 2) with second order.

  • Morris: mu_star, mu and sigma from N trajectories over levels grid levels, with a bootstrap interval for mu_star.

The model is stochastic, so each point mean carries seed noise. The noise share, the mean variance between a point’s seeds over the total variance of all runs, says how much of what the indices split up is noise.

SALib (MIT) is an optional extra: pip install "abmfact[sensitivity]".

Herman, J. and Usher, W. (2017). SALib: an open-source Python library for sensitivity analysis. Journal of Open Source Software, 2(9), 97. Saltelli, A. et al. (2010). Variance based sensitivity analysis of model output. Computer Physics Communications, 181(2), 259-270. Morris, M. D. (1991). Factorial sampling plans for preliminary computational experiments. Technometrics, 33(2), 161-174.

class abmfact.modes.sensitivity.SensitivitySettings(method: str = 'sobol', n: int = 512, second_order: bool = False, levels: int = 4, num_resamples: int = 1000, conf_level: float = 0.95, seed: int = 0)[source]

Bases: object

How indices are estimated.

method

sobol or morris.

Type:

str

n

Sobol base sample size N, or the number of Morris trajectories.

Type:

int

second_order

Also estimate Sobol second-order indices.

Type:

bool

levels

Morris grid levels (even numbers are recommended).

Type:

int

num_resamples

Bootstrap resamples for the intervals.

Type:

int

conf_level

Interval coverage.

Type:

float

seed

Seed for SALib’s sampling and bootstrap.

Type:

int

classmethod from_mapping(raw: Mapping[str, Any]) → SensitivitySettings[source]

Settings from a file’s sensitivity section.

abmfact.modes.sensitivity.sample(params: Sequence[Parameter], settings: SensitivitySettings) → ndarray[source]

The unit-cube points SALib asks for, in its order (rows are points).

abmfact.modes.sensitivity.design_warnings(params: Sequence[Parameter], settings: SensitivitySettings) → list[str][source]

Reasons the requested design is too small or badly shaped for stable indices, known before any run.

abmfact.modes.sensitivity.analyse(params: Sequence[Parameter], x_unit: ndarray, y: ndarray, settings: SensitivitySettings) → dict[str, Any][source]

Indices for outputs y at unit-cube points x_unit (as drawn by sample()).

abmfact.modes.sensitivity.result_warnings(method: str, analysis: Mapping[str, Any], noise_share: float | None) → list[str][source]

Reasons the estimated indices should be read with care, found after the runs.

abmfact.modes.sensitivity.noise_share(sweep: SweepResult, metric: str) → float | None[source]

The mean within-point variance of metric over its total variance across all runs (None with 1 seed).

class abmfact.modes.sensitivity.SensitivityResult(data: dict[str, Any], sweep: SweepResult)[source]

Bases: object

The outcome of a sensitivity analysis.

data

Settings, warnings, and per metric the indices with intervals and the noise share.

Type:

dict[str, Any]

sweep

The sweep that produced the outputs.

Type:

abmfact.modes.sweep.SweepResult

to_json(include_timestamp: bool = True) → str[source]

The result as JSON; without the timestamp it is the same for the same runs.

rows() → list[list[Any]][source]

One row per metric, parameter and index: metric, parameter, index, value, interval half-width.

write(out: str | Path) → dict[str, Path][source]

Write indices.json, indices.csv, report.html, and the sweep’s tables under sweep/.

abmfact.modes.sensitivity.load_sensitivity(path: str | Path, overrides: Mapping[str, Any] | None = None) → tuple[SweepSpec, SensitivitySettings][source]

Read a sensitivity file: a sweep file with a sensitivity section and no design.

overrides replaces top-level keys (jobs) and sensitivity keys (method, n).

abmfact.modes.sensitivity.run_sensitivity(spec: SweepSpec, settings: SensitivitySettings, *, workdir: str | Path | None = None, store: str | Path | None = None, progress: Callable[[int, int], None] | None = None) → SensitivityResult[source]

Draw SALib’s points, run them as a sweep, and estimate indices for every metric.

abmfact.modes.sensitivity.render_html(result: SensitivityResult) → str[source]

The indices as a self-contained HTML page, with every warning first.

abmfact.modes.calibrate

Calibrate mode: fit parameters so a model’s observables match target data or another engine’s ensemble.

A calibration file names the model, engine, the free parameters with their ranges (ABM-IR paths, native paths, or engine options such as option:pressure_gain), the target, the observables to fit, seeds per evaluation and the method. The target is one of:

  • data: a CSV with columns time, observable, value and optionally sd;

  • ensemble: an ensemble.json written by abmfact ensemble;

  • engine: an engine to run as an ensemble now, with seeds, seed_start, params and options.

Each evaluation runs the model over its seeds, takes the mean of each observable at the target’s times (linear interpolation between saves), and scores the fit with

distance = mean over observables and times of ((simulated mean - target) / scale) ** 2,

where scale is the target’s standard deviation (from the data or the target ensemble). Where the target has no spread, the scale is the range of the target’s values for that observable, and the result says so.

Methods: bayesopt (Bayesian optimisation through bayesian-optimization, MIT) and abc-smc (approximate Bayesian computation through pyABC, BSD-3). Others register through the entry point group abmfact.calibrators. Both libraries are in the optional [calibrate] extra.

exception abmfact.modes.calibrate.CalibrationError[source]

Bases: ValueError

A calibration file, target or method is not valid.

class abmfact.modes.calibrate.Target(series: dict[str, tuple[~numpy.ndarray, ~numpy.ndarray, ~numpy.ndarray | None]], source: dict[str, ~typing.Any] = <factory>)[source]

Bases: object

What to match: per observable, the target values at their times and their spread where known.

series

{observable: (times, values, sd or None)}.

Type:

dict[str, tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray | None]]

source

Where the target came from, with a SHA-256 of any file.

Type:

dict[str, Any]

features(observables: Sequence[str]) → tuple[list[tuple[str, float]], ndarray, ndarray, dict[str, str]][source]

The fitted points: labels (observable, time), target values, scales, and each observable’s scale kind.

abmfact.modes.calibrate.load_target_csv(path: str | Path) → Target[source]

A target from a CSV with time, observable, value and optionally sd columns.

abmfact.modes.calibrate.target_from_ensemble(data: Mapping[str, Any], source: Mapping[str, Any]) → Target[source]

A target from an ensemble result: each observable’s mean and standard deviation at every save time.

class abmfact.modes.calibrate.CalibrationSpec(title: str, model: ~pathlib.Path, engine: str, parameters: list[~abmfact.modes.design.Parameter], target: dict[str, ~typing.Any], observables: list[str] = <factory>, seeds_per_evaluation: int = 10, seed_start: int = 0, method: str = 'bayesopt', settings: dict[str, ~typing.Any] = <factory>, params: dict[str, ~typing.Any] = <factory>, options: dict[str, ~typing.Any] = <factory>, jobs: int = 1, alpha: float = 0.05, base: ~pathlib.Path = <factory>)[source]

Bases: object

A parsed calibration.

title

A short title.

Type:

str

model

The ABM-IR file or native project.

Type:

pathlib.Path

engine

The engine whose parameters are fitted.

Type:

str

parameters

The free parameters and their ranges.

Type:

list[abmfact.modes.design.Parameter]

target

The target settings (data, ensemble or engine).

Type:

dict[str, Any]

observables

The observables fitted; all the target’s by default.

Type:

list[str]

seeds_per_evaluation

Seeds behind each evaluation’s means.

Type:

int

seed_start

The first seed.

Type:

int

method

bayesopt, abc-smc or a registered plug-in.

Type:

str

settings

The method’s settings (the file’s bayesopt, abc_smc or plugin section).

Type:

dict[str, Any]

params

Fixed parameters for every run.

Type:

dict[str, Any]

options

Fixed engine options.

Type:

dict[str, Any]

jobs

Runs at once.

Type:

int

alpha

One-sided level for intervals.

Type:

float

base

The folder relative paths are read from.

Type:

pathlib.Path

abmfact.modes.calibrate.spec_from_mapping(raw: Mapping[str, Any], base: Path, title: str = 'calibration') → CalibrationSpec[source]

A calibration from a parsed mapping, with paths relative to base.

abmfact.modes.calibrate.load_calibration(path: str | Path, overrides: Mapping[str, Any] | None = None) → CalibrationSpec[source]

Read a calibration file; relative paths are resolved against its folder.

abmfact.modes.calibrate.resolve_target(spec: CalibrationSpec, *, workdir: str | Path | None = None, store: str | Path | None = None, progress: Callable[[int, int], None] | None = None) → tuple[Target, dict[str, Any] | None][source]

The target, running the target engine’s ensemble when the file asks for one. Returns (target, ensemble).

class abmfact.modes.calibrate.Evaluation(index: int, values: dict[str, float], distance: float, per_seed: ~numpy.ndarray, runs: list[str | None], errors: list[str], method_info: dict[str, ~typing.Any] = <factory>)[source]

Bases: object

One evaluated setting: its parameter values, distance, per-seed features and run ids.

class abmfact.modes.calibrate.Problem(spec: CalibrationSpec, target: Target, *, workdir: str | Path | None = None, store: str | Path | None = None, on_evaluation: Callable[[Evaluation], None] | None = None)[source]

Bases: object

A calibration problem: simulate a setting over its seeds and score it against the target.

Methods see the parameters, call evaluate() with parameter values, and read evaluations.

property parameters: list[Parameter]

The free parameters.

features(scalars: Mapping[str, Any]) → ndarray[source]

A run’s observables at the target’s times, interpolated between saves.

A target time up to half a save interval beyond the run’s first or last save takes that save’s value, since engines differ by a step in where they place their saves (CompuCell3D saves its last Monte Carlo step at 1439 minutes of a 1440-minute run). Times further outside the run are missing (NaN).

missing() → list[str][source]

The fitted points that no run of any evaluation could give, as observable at time.

score(per_seed: ndarray) → float[source]

The distance of the seeds’ means from the target; infinite when a fitted point has no value.

runs(params: Mapping[str, Any], options: Mapping[str, Any], label: str) → tuple[list[Mapping[str, Any]], list[str | None], list[str]][source]

Run one setting over its seeds: (each working run's scalars, run ids, errors).

evaluate(values: Sequence[float], info: Mapping[str, Any] | None = None) → float[source]

Run the setting values (one per free parameter) over its seeds and return its distance.

bootstrap_threshold(best: Evaluation, level: float = 0.95, seed: int = 0) → float[source]

The level quantile of the best evaluation’s distance when its seeds are resampled.

abmfact.modes.calibrate.bayesopt(problem: Problem, settings: Mapping[str, Any]) → dict[str, Any][source]

Bayesian optimisation of the distance over the unit cube, with an interval from a bootstrap of the seeds.

settings: n_init (Latin hypercube start, default 8), n_iter (further evaluations, default 16), kappa (exploration of the upper confidence bound, default 2.576), refine (bisection steps per interval edge, default 4) and seed. The optimiser maximises -log10(distance).

For each parameter, with the others at the best fit, the interval holds the values whose distance lies within the 95th percentile of the best fit’s distances when its seeds are resampled: settings the seeds cannot tell from the best. Its edges are found by bisection, each step a new evaluation.

abmfact.modes.calibrate.calibrators() → dict[str, Callable[[Problem, Mapping[str, Any]], dict[str, Any]]][source]

Every calibration method: the built-ins and those registered under abmfact.calibrators.

class abmfact.modes.calibrate.CalibrationResult(data: dict[str, Any], spec: CalibrationSpec)[source]

Bases: object

The outcome of a calibration.

data

Settings, target, the method’s result (best fit or posterior with intervals and diagnostics), and every evaluation.

Type:

dict[str, Any]

spec

The calibration.

Type:

abmfact.modes.calibrate.CalibrationSpec

to_json(include_timestamp: bool = True) → str[source]

The result as JSON; without the timestamp it is the same for the same runs.

property best: dict[str, float]

the best fit, or the posterior median for ABC-SMC.

Type:

The calibrated values

write(out: str | Path) → dict[str, Path][source]

Write calibration.json, evaluations.csv, report.html, and the calibrated model or options.

abmfact.modes.calibrate.run_calibration(spec: CalibrationSpec, *, workdir: str | Path | None = None, store: str | Path | None = None, on_evaluation: Callable[[Evaluation], None] | None = None) → CalibrationResult[source]

Resolve the target, run the method, and collect the result.

on_evaluation is called with each evaluation as it finishes.

abmfact.modes.calibrate.collect(spec: CalibrationSpec, problem: Problem, result: Mapping[str, Any], info: Mapping[str, Any] | None, ensemble: Mapping[str, Any] | None = None) → CalibrationResult[source]

A result from a finished method run.

abmfact.modes.calibrate.render_html(result: CalibrationResult) → str[source]

The calibration as a self-contained HTML page.

abmfact.modes.abc_smc

ABC-SMC calibration through pyABC: a weighted posterior sample of the free parameters.

Approximate Bayesian computation with sequential Monte Carlo draws particles from the prior (uniform on each parameter’s range, or log-uniform on a log scale), keeps those whose distance to the target falls below a shrinking threshold, and reweights them generation by generation. The posterior median is reported as the calibrated value, with a 1 - 2*alpha credible interval from the weighted quantiles.

Every particle is one evaluation: the model over its seeds, scored with the calibration’s distance. That is many runs, so ABC-SMC suits cheap models; Bayesian optimisation finds a best fit with far fewer.

Toni, T., Welch, D., Strelkowa, N., Ipsen, A. and Stumpf, M. P. H. (2009). Approximate Bayesian computation scheme for parameter inference and model selection in dynamical systems. Journal of the Royal Society Interface, 6(31), 187-202. Schaelte, Y. et al. (2022). pyABC: efficient and robust easy-to-use approximate Bayesian computation. Journal of Open Source Software, 7(74), 4304.

abmfact.modes.abc_smc.weighted_quantile(x: ndarray, w: ndarray, q: float) → float[source]

The q quantile of values x with weights w (the inverse of the weighted empirical CDF).

abmfact.modes.abc_smc.abc_smc(problem: Problem, settings: Mapping[str, Any], *, abcsmc_class: Callable[..., Any] | None = None, transition: Any = None, method_detail: str = 'pyABC ABC-SMC') → dict[str, Any][source]

Calibrate by ABC-SMC.

settings: population (particles per generation, default 50), generations (at most, default 8), min_epsilon (stop once the threshold is this small, default 0), max_simulations (stop after this many evaluations, default 2000) and seed. abcsmc_class and transition replace pyABC’s ABCSMC and its multivariate normal kernel, so plug-ins can supply their own.

abmfact.modes.plugins

Calibration plug-in slots for tools from the agent-based modelling community.

  • uq-physicell: UQ-PhysiCell (BSD-3; Rocha et al.) adds safeguards to pyABC’s ABC-SMC, checking particle weights and transition kernels between generations, and a kernel fitted on standardised parameters so parameters on very different scales are all perturbed. This slot runs ABMfact’s ABC-SMC with those two pieces, through any engine. Install with pip install uq-physicell.

  • fitmulticell: FitMultiCell (BSD-3; Alamoudi et al.) runs pyABC on Morpheus models through its own model class, which calls a native Morpheus executable. ABMfact does not bridge that class yet, so this slot reports what is installed and points to abc-smc, which runs the same pyABC algorithm through ABMfact’s engines, Morpheus in its container included.

Further tools register a calibrator under the entry point group abmfact.calibrators: a callable taking the calibration Problem and the file’s plugin settings, and returning a result with best, best_distance, interval, interval_meaning, diagnostics and warnings.

abmfact.modes.plugins.installed(distribution: str) → str | None[source]

The installed version of distribution, or None.

abmfact.modes.plugins.status() → list[dict[str, Any]][source]

Each plug-in slot, whether its tool is installed here, and what the slot does.

abmfact.modes.plugins.uq_physicell(problem: Problem, settings: Mapping[str, Any]) → dict[str, Any][source]

ABC-SMC with UQ-PhysiCell’s CheckedABCSMC and ScaledMultivariateNormalTransition.

settings are those of abc_smc, plus max_zero_weight_fraction (default 0.05): the largest share of particles allowed a zero weight in a generation before UQ-PhysiCell stops the run.

abmfact.modes.plugins.fitmulticell(problem: Problem, settings: Mapping[str, Any]) → dict[str, Any][source]

Report what FitMultiCell needs; its native-Morpheus calibration is not bridged.

abmfact.modes.plugins.builtin_plugins() → dict[str, Callable[[Problem, Mapping[str, Any]], dict[str, Any]]][source]

The built-in plug-in slots by method name.

abmfact.modes.translate

T2 translation: calibrate a lattice engine’s mapping gains so its observables match the source model’s.

A structural (T1) translation maps every ABM-IR concept it can, but two mappings between centre-based and cellular Potts models are coefficients with no exact counterpart: the contact fraction that stands in for pressure, and the strength that drives motility. T2 translation fits those coefficients, and only those (the pressure_gain and motility_gain engine options), so that the translated model reproduces chosen observables of the source model’s ensemble. Biological parameters such as rates, half-max values or adhesion are never varied: a T2 translation changes how the model is expressed in the target engine, not the model.

The observables used for calibration and those held out must not overlap, and at least one must be held out, so a T2 translation cannot match by construction what is later used to judge it. The held-out observables are reported beside the calibration, with the difference and its interval, but not judged here.

The output folder holds the exported project at the calibrated gains, translation.json (tier T2, the gains with their intervals, the calibration and the held-out check), fidelity.md and the calibration’s own files.

abmfact.modes.translate.AFFECTS = {'motility_gain': ('.motility',), 'pressure_gain': ('rules.pressure',)}

The fidelity entries each gain calibrates.

class abmfact.modes.translate.TranslationSpec(title: str, model: ~pathlib.Path, to: str, calibrate_on: list[str], hold_out: list[str], free: list[~abmfact.modes.design.Parameter], source: dict[str, ~typing.Any] = <factory>, options: dict[str, ~typing.Any] = <factory>, params: dict[str, ~typing.Any] = <factory>, seeds_per_evaluation: int = 10, seed_start: int = 0, method: str = 'bayesopt', settings: dict[str, ~typing.Any] = <factory>, jobs: int = 1, alpha: float = 0.05)[source]

Bases: object

A T2 translation.

title

A short title.

Type:

str

model

The ABM-IR model.

Type:

pathlib.Path

to

The target engine: compucell3d or morpheus.

Type:

str

source

The source ensemble: engine (default reference), seeds, seed_start and options.

Type:

dict[str, Any]

calibrate_on

Observables the gains are fitted to.

Type:

list[str]

hold_out

Observables kept out of the fit and reported beside it.

Type:

list[str]

free

The mapping gains to fit, with their ranges.

Type:

list[abmfact.modes.design.Parameter]

options

Fixed target-engine options, such as a gain fitted earlier.

Type:

dict[str, Any]

params

Fixed ABM-IR parameters for both engines, such as a shorter run.

Type:

dict[str, Any]

seeds_per_evaluation

Seeds behind each evaluation of the target engine.

Type:

int

seed_start

The first seed of each evaluation.

Type:

int

method

bayesopt or abc-smc.

Type:

str

settings

The method’s settings.

Type:

dict[str, Any]

jobs

Runs at once.

Type:

int

alpha

One-sided level for intervals.

Type:

float

check() → None[source]

Refuse a translation that could match by construction or that varies anything but the mapping gains.

calibration() → CalibrationSpec[source]

The calibration this translation runs: the gains of the target engine against the source ensemble.

abmfact.modes.translate.parse_free(items: Sequence[str]) → list[Parameter][source]

NAME=LOW:HIGH gains from the command line, on a log scale.

abmfact.modes.translate.load_translation(path: str | Path, overrides: Mapping[str, Any] | None = None) → TranslationSpec[source]

Read a translation file; relative paths are resolved against its folder.

class abmfact.modes.translate.TranslationResult(data: dict[str, Any], calibration: CalibrationResult, spec: TranslationSpec)[source]

Bases: object

A T2 translation: the calibrated gains, the held-out check and the calibration behind them.

data

What translation.json holds.

Type:

dict[str, Any]

calibration

The calibration result.

Type:

abmfact.modes.calibrate.CalibrationResult

spec

The translation.

Type:

abmfact.modes.translate.TranslationSpec

property gains: dict[str, float]

The calibrated gains, by option name.

write(out: str | Path) → dict[str, Path][source]

Write the project at the calibrated gains, translation.json, fidelity.md and the calibration.

abmfact.modes.translate.export(spec: TranslationSpec, options: Mapping[str, Any], folder: Path) → Any[source]

Export the model to the target engine with options (gains included); return the fidelity report.

abmfact.modes.translate.annotate(report: Any, data: Mapping[str, Any]) → None[source]

Mark the report tier T2 and add each gain’s calibration to the entries it governs.

abmfact.modes.translate.held_out_check(spec: TranslationSpec, gains: Mapping[str, float], *, workdir: str | Path | None, store: str | Path | None) → list[dict[str, Any]][source]

Each held-out observable at the end of the run: source and target means and their difference’s interval.

abmfact.modes.translate.translate(spec: TranslationSpec, *, workdir: str | Path | None = None, store: str | Path | None = None, on_evaluation: Callable[[Evaluation], None] | None = None) → TranslationResult[source]

Calibrate the gains, then check the held-out observables at the calibrated gains.

abmfact.modes.translate.options_from(path: str | Path, engine: str) → dict[str, float][source]

The calibrated gains of a translation.json for engine, checking that it is a T2 translation for it.

abmfact.modes.visualise

Visualise mode: plots, snapshots, fields and movies from the common output schema, for any engine.

  • An ensemble.json gives one time-series plot per observable: the mean, its interval, and the 5% to 95% band.

  • A sweep.json gives each metric’s point means against each parameter, with intervals.

  • An indices.json gives the sensitivity indices with their intervals.

  • A calibration.json gives the distance of every evaluation, and the best fit against the target.

  • A run (a folder written by run-model, or a run id in a store) gives cell snapshots coloured by type or state, substrate fields, a movie (GIF, or MP4 through imageio-ffmpeg), and a VTK export for ParaView.

Plots need matplotlib and movies imageio, both in the optional [viz] extra. The VTK export needs neither.

abmfact.modes.visualise.plot_ensemble(data: dict[str, Any], out: Path) → list[Path][source]

One plot per observable: the mean over seeds, its interval, and the 5% to 95% band.

abmfact.modes.visualise.plot_sweep(data: dict[str, Any], out: Path) → list[Path][source]

Each metric’s point means, with intervals, against each varied parameter.

abmfact.modes.visualise.plot_sensitivity(data: dict[str, Any], out: Path) → list[Path][source]

Sobol S1 and ST, or Morris mu* and sigma, per parameter with their intervals.

abmfact.modes.visualise.plot_calibration(data: dict[str, Any], out: Path) → list[Path][source]

The distance of each evaluation with the best so far, and the best fit against the target.

abmfact.modes.visualise.draw_cells(ax: Any, outputs: RunOutputs, time: float, colour: str = 'type', bounds: Sequence[float] | None = None) → None[source]

Draw the cells at time as discs of their equivalent radius, coloured by type or state.

abmfact.modes.visualise.snapshot(outputs: RunOutputs, time: float, path: Path, colour: str = 'type') → Path[source]

A picture of the cells at one save time.

abmfact.modes.visualise.field_plot(outputs: RunOutputs, substrate: str, time: float, path: Path) → Path[source]

A heat map of one substrate at one save time (the middle slice in 3D).

abmfact.modes.visualise.movie(outputs: RunOutputs, path: Path, colour: str = 'type', fps: int = 4) → Path[source]

Every save time as one frame: a GIF, or an MP4 through imageio-ffmpeg when path ends in .mp4.

abmfact.modes.visualise.visualise_run(outputs: RunOutputs, out: Path, *, times: str = 'last', colour: str = 'type', fields: Sequence[str] | None = None, film: str | None = None, vtk: bool = False) → list[Path][source]

Snapshots, field maps, a movie and a VTK export of one run, as asked.

abmfact.modes.visualise.visualise_result(path: Path, out: Path) → list[Path][source]

Plots for a mode’s result file: ensemble, sweep, sensitivity or calibration.

abmfact.modes.vtk

VTK export of a run, for ParaView and other VTK readers, written without any dependency.

Cells at each save time become a .vtp file (VTK XML PolyData): one point per cell with its id, type, state, volume and equivalent radius as point data. Each substrate at each save time becomes a .vti file (VTK XML ImageData) on its voxel grid. A .pvd collection per series lists the files by time, so ParaView opens the whole run as one time series.

abmfact.modes.vtk.equivalent_radius(volume: ndarray) → ndarray[source]

The radius of a sphere with volume.

abmfact.modes.vtk.cells_vtp(cells: dict[str, ndarray], type_names: Sequence[str] = ()) → str[source]

One save time’s cells as VTK XML PolyData: a vertex per cell, with its columns as point data.

abmfact.modes.vtk.field_vti(frame: FieldFrame) → str[source]

One substrate frame as VTK XML ImageData, with values at the voxel centres.

abmfact.modes.vtk.collection(entries: Iterable[tuple[float, str]]) → str[source]

A .pvd collection listing (time, file) pairs.

abmfact.modes.vtk.export_vtk(outputs: RunOutputs, folder: str | Path) → dict[str, Path][source]

Write every save time’s cells and fields under folder; return the .pvd collections by name.

abmfact.modes.report

Self-contained HTML pages for the modes, in the same style as the audit report.

abmfact.modes.report.esc(x: Any) → str[source]

x as HTML-escaped text.

abmfact.modes.report.num(x: Any) → str[source]

A number with four significant digits; anything else as text, and n/a for None.

abmfact.modes.report.table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) → str[source]

An HTML table; numbers get four significant digits.

abmfact.modes.report.page(title: str, subtitle: str, sections: Sequence[tuple[str, str]]) → str[source]

A whole HTML page: a title, a muted subtitle and (heading, html) sections.

abmfact.modes.report.dumps(data: Any) → str[source]

data as indented JSON, with NumPy values and non-finite numbers made plain.

abmfact.modes.commands

Command line for the modes: abmfact ensemble, sweep, sensitivity, calibrate, translate and visualise.

Only argparse is imported here at load time; each command imports what it needs when it runs.

abmfact.modes.commands.add_parsers(sub: Any) → None[source]

Add the mode subcommands to the main parser’s subparsers.

abmfact.modes.commands.run(args: Namespace) → int[source]

Run the chosen mode command and return its exit code.

abmfact.modes.commands.pairs(items: list[str] | None, what: str) → dict[str, Any][source]

KEY=VALUE pairs; a value is read as JSON when it parses, else kept as text.

abmfact.modes.commands.cmd_ensemble(args: Namespace) → int[source]

Run abmfact ensemble; exit code 1 when any run failed, else 0.

abmfact.modes.commands.cmd_sweep(args: Namespace) → int[source]

Run abmfact sweep; exit code 1 when any run failed or was not collected, else 0.

abmfact.modes.commands.cmd_sensitivity(args: Namespace) → int[source]

Run abmfact sensitivity; exit code 1 when any run failed or a metric got no indices, else 0.

abmfact.modes.commands.cmd_calibrate(args: Namespace) → int[source]

Run abmfact calibrate; exit code 0 when a fit was found, 2 for an invalid file or no usable evaluation.

abmfact.modes.commands.cmd_translate(args: Namespace) → int[source]

Run abmfact translate; exit code 0 when the gains were calibrated, 2 for an invalid translation.

abmfact.modes.commands.cmd_visualise(args: Namespace) → int[source]

Run abmfact visualise; exit code 0 when something was drawn, 2 when the target is not recognised.