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:
objectOne 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
- class abmfact.modes.batch.JobResult(job: Job, record: RunRecord | None = None, error: str | None = None)[source]¶
Bases:
objectWhat one job gave: a run record, or the error that stopped it before a record existed.
- record¶
The run record; its status says whether the run worked, and
cachedwhen 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
namewithoptions.
- 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 smallern.
- class abmfact.modes.ensemble.EnsembleResult(data: dict[str, Any])[source]¶
Bases:
objectThe 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.
- 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
seedsseeds 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_ensembleand 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 asoverall/dt_mechanics;option:NAMEfor an engine option, such asoption: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:
ValueErrorA parameter or design is not valid.
- exception abmfact.modes.design.DesignWarning[source]¶
Bases:
UserWarningA 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:
objectOne varied parameter and its range.
- name¶
The parameter as runs take it: an ABM-IR path, a native path with
/, oroption:NAME.- Type:
str
- low¶
The lower end of the range.
- Type:
float
- high¶
The upper end of the range.
- Type:
float
- scale¶
linear, orlogfor 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¶
optionfor engine options,nativefor native paths, elseir.
- property key: str¶
the option name for options, else the parameter path.
- Type:
The name runs use
- 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]¶
npoints with one point in each ofnequal strata of every parameter.
- abmfact.modes.design.sobol(params: Sequence[Parameter], n: int, seed: int = 0, scramble: bool = True) ndarray[source]¶
npoints of a (scrambled) Sobol sequence; balanced only whennis 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(withlevels),lhsorsoboldesign (withn).
- 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:
objectA 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:
- method¶
grid,lhsorsobol.- Type:
str
- n¶
Points for
lhsandsobol.- Type:
int | None
- levels¶
Levels per parameter for
grid.- Type:
int | list[int] | None
- design_seed¶
The seed that draws
lhsandsobolpoints.- 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]
- 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.
overridesreplaces top-level keys, such asjobsfrom 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:
objectThe 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.
- 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 runsabmfact run-model(orslurm.command) intoout/jobs/<point>/seed-<n>; collect them withrun_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 needsN * (D + 2)points, orN * (2D + 2)with second order.Morris:
mu_star,muandsigmafromNtrajectories overlevelsgrid levels, with a bootstrap interval formu_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:
objectHow indices are estimated.
- method¶
sobolormorris.- 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
sensitivitysection.
- 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
yat unit-cube pointsx_unit(as drawn bysample()).
- 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.
The mean within-point variance of
metricover its total variance across all runs (None with 1 seed).
- class abmfact.modes.sensitivity.SensitivityResult(data: dict[str, Any], sweep: SweepResult)[source]¶
Bases:
objectThe 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.
- to_json(include_timestamp: bool = True) str[source]¶
The result as JSON; without the timestamp it is the same for the same runs.
- 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
sensitivitysection and nodesign.overridesreplaces 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 columnstime,observable,valueand optionallysd;ensemble: anensemble.jsonwritten byabmfact ensemble;engine: an engine to run as an ensemble now, withseeds,seed_start,paramsandoptions.
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:
ValueErrorA 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:
objectWhat 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]
- abmfact.modes.calibrate.load_target_csv(path: str | Path) Target[source]¶
A target from a CSV with
time,observable,valueand optionallysdcolumns.
- 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:
objectA 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:
- target¶
The target settings (
data,ensembleorengine).- 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-smcor a registered plug-in.- Type:
str
- settings¶
The method’s settings (the file’s
bayesopt,abc_smcorpluginsection).- 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:
objectOne 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:
objectA calibration problem: simulate a setting over its seeds and score it against the target.
Methods see the parameters, call
evaluate()with parameter values, and readevaluations.- 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
levelquantile 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) andseed. 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:
objectThe 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.
- 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
- 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_evaluationis 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
qquantile of valuesxwith weightsw(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) andseed.abcsmc_classandtransitionreplace pyABC’sABCSMCand 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 withpip 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 toabc-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
CheckedABCSMCandScaledMultivariateNormalTransition.settingsare those ofabc_smc, plusmax_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.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:
objectA T2 translation.
- title¶
A short title.
- Type:
str
- model¶
The ABM-IR model.
- Type:
pathlib.Path
- to¶
The target engine:
compucell3dormorpheus.- Type:
str
- source¶
The source ensemble:
engine(defaultreference),seeds,seed_startandoptions.- 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:
- 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¶
bayesoptorabc-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:HIGHgains 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:
objectA T2 translation: the calibrated gains, the held-out check and the calibration behind them.
- data¶
What
translation.jsonholds.- Type:
dict[str, Any]
- calibration¶
The calibration result.
- spec¶
The translation.
- property gains: dict[str, float]¶
The calibrated gains, by option name.
- 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.visualise¶
Visualise mode: plots, snapshots, fields and movies from the common output schema, for any engine.
An
ensemble.jsongives one time-series plot per observable: the mean, its interval, and the 5% to 95% band.A
sweep.jsongives each metric’s point means against each parameter, with intervals.An
indices.jsongives the sensitivity indices with their intervals.A
calibration.jsongives 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
timeas discs of their equivalent radius, coloured bytypeorstate.
- 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
pathends 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.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
.pvdcollection 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.pvdcollections by name.
abmfact.modes.report¶
Self-contained HTML pages for the modes, in the same style as the audit report.
- abmfact.modes.report.num(x: Any) str[source]¶
A number with four significant digits; anything else as text, and
n/afor None.
- abmfact.modes.report.table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) str[source]¶
An HTML table; numbers get four significant digits.
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=VALUEpairs; 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.