Audits¶
Loading an audit file, running it, and the claims, knobs, checks and statistics behind each verdict.
abmfact¶
ABMfact: run agent-based models across simulators and check their conclusions.
Run a model in several simulators through one engine contract, translate it through ABM-IR with a fidelity report, and audit its conclusions by rerunning it under changes that a correct implementation must not care about. ABMfact reports which conclusions survive: are they findings or artefacts?
abmfact.config¶
Audit files: one YAML document with the model, its parameters, the claims and the budget.
- class abmfact.config.Budget(seeds: int = 100, seed_start: int = 0, jobs: int = 1, alpha: float = 0.05, determinism_reruns: int = 8, checks: tuple[str, ...] = ())[source]¶
Bases:
objectHow much an audit runs: seeds, workers, significance level and which checks.
- seeds¶
Seeds per condition and parameter point.
- Type:
int
- seed_start¶
The first seed; seeds run upwards from here.
- Type:
int
- jobs¶
Worker processes.
- Type:
int
- alpha¶
One-sided significance level; intervals cover
1 - 2*alpha.- Type:
float
- determinism_reruns¶
How many seeds the determinism check reruns.
- Type:
int
- checks¶
Checks to run; empty runs every check.
- Type:
tuple[str, …]
- classmethod from_mapping(m: Mapping[str, Any] | None) Budget[source]¶
Build a budget from the
budgetsection of an audit file, validating every field.Raises
ConfigErrorfor unknown keys, fewer than 3 seeds,alphaoutside 0 to 0.5, fewer than 1 job or unknown checks.
- class abmfact.config.Audit(adapter: ~abmfact.adapters.Adapter, params: dict[str, ~typing.Any], claims: list[~abmfact.claims.Claim], budget: ~abmfact.config.Budget = <factory>, model_cfg: dict[str, ~typing.Any] = <factory>, source: ~pathlib.Path | None = None, sha256: str | None = None, title: str = 'ABMfact audit', convergence: dict[str, ~typing.Any] = <factory>)[source]¶
Bases:
objectA parsed audit file: the model adapter, base parameters, claims and budget.
- adapter¶
The adapter that runs the model.
- Type:
- params¶
Base parameters passed to every run.
- Type:
dict[str, Any]
- claims¶
The claims to audit.
- Type:
list[abmfact.claims.Claim]
- budget¶
Seeds, workers, significance level and checks.
- Type:
- model_cfg¶
The
modelsection as written.- Type:
dict[str, Any]
- source¶
Path of the audit file, when it was loaded from one.
- Type:
pathlib.Path | None
- sha256¶
SHA-256 of the audit file’s bytes.
- Type:
str | None
- title¶
Title shown in the report.
- Type:
str
- convergence¶
The
convergencesection, with settings for the convergence check.- Type:
dict[str, Any]
- abmfact.config.parse_audit(doc: Mapping[str, Any], base_dir: Path | None = None) Audit[source]¶
Build an
Auditfrom a parsed YAML document.base_diris where relative model paths and modules are looked up, defaulting to the current directory. RaisesConfigErrorwhen the document is not a valid audit.
- abmfact.config.load_audit(path: str | Path, overrides: Mapping[str, Any] | None = None) Audit[source]¶
Read and parse an audit file, recording its path and SHA-256.
overridesreplaces budget fields, ignoringNonevalues. RaisesConfigErrorwhen the file is not valid YAML or not a valid audit.
- abmfact.config.template(adapter: str = 'python') str[source]¶
Return a commented audit file template for one adapter.
adapterispython,mesa,netlogo,commandorengine; any other name raisesConfigError.
abmfact.claims¶
Claims: a model’s conclusions written as checkable statements.
- exception abmfact.claims.ClaimError[source]¶
Bases:
ValueErrorA claim or metric expression is not valid.
- class abmfact.claims.Metric(expr: str, name: str, func: str | None = None, index: int | None = None)[source]¶
Bases:
objectA parsed metric expression:
name,name[i]orf(name).- classmethod parse(expr: str) Metric[source]¶
Parse a metric expression, raising
ClaimErrorwhen it is malformed or uses an unknown function.
- evaluate(outputs: Mapping[str, Any]) float[source]¶
Compute the metric from one run’s outputs.
A plain name must refer to a scalar output.
stdis the sample standard deviation, and 0 for a single value. RaisesClaimErrorwhen the output is missing or empty, or the index is out of range.
- class abmfact.claims.Claim(id: str, statement: str, metric: Metric, test: str, value: float | tuple[float, float] | None=None, over: str | None = None, where: dict[str, list[~typing.Any]]=<factory>, tolerance: float | None = None, skip_checks: dict[str, str]=<factory>)[source]¶
Bases:
objectOne conclusion of a model, written as a test on a metric.
- id¶
Short identifier, unique within the audit.
- Type:
str
- statement¶
The conclusion in plain words.
- Type:
str
- metric¶
The parsed metric the test applies to.
- Type:
- test¶
One of
greater_than,less_than,between,monotone_increasingormonotone_decreasing.- Type:
str
- value¶
The threshold, or a
(low, high)pair forbetween;Nonefor monotone tests.- Type:
float | tuple[float, float] | None
- over¶
The parameter a monotone claim varies.
- Type:
str | None
- where¶
Values of each parameter to evaluate the claim at; their combinations form the grid.
- Type:
dict[str, list[Any]]
- tolerance¶
Absolute equivalence margin;
Noneusesdefault_tolerance().- Type:
float | None
- skip_checks¶
Checks to skip, each mapped to the reason.
- Type:
dict[str, str]
- property is_monotone: bool¶
True for the
monotone_increasingandmonotone_decreasingtests.
- abmfact.claims.parse_claim(raw: Mapping[str, Any], known_checks: Sequence[str] = ()) Claim[source]¶
Parse and validate one claim from an audit file.
- Parameters:
raw – The claim mapping as read from YAML.
known_checks – Check names allowed in
skip_checks; when empty, those names are not checked.
- Returns:
The parsed
Claim.- Raises:
ClaimError – When a required key is missing or a field is not valid for the test.
- abmfact.claims.parse_claims(raw: Sequence[Mapping[str, Any]], known_checks: Sequence[str] = ()) list[Claim][source]¶
Parse a list of claims with
parse_claim(), rejecting an empty list and duplicate ids.
abmfact.knobs¶
Implementation choices that an audit varies, and what a model declares it supports.
- abmfact.knobs.RNG_SALT = 180333685¶
Salt mixed into seeds when a model does not manage its own streams.
- class abmfact.knobs.Knobs(update_order: str | None = None, agent_order: str = 'default', agent_perm_seed: int | None = None, rng_streams: str = 'default', grid_offset: tuple[float, float] = (0.0, 0.0), grid_rotation: int = 0, dt_scale: float = 1.0, pop_scale: float = 1.0, dx_scale: float = 1.0)[source]¶
Bases:
objectSettings passed to every model run.
Noneforupdate_ordermeans “use the model’s own default”. All other defaults are the identity: they leave a correct model unchanged.dx_scalemultiplies the spatial resolution of a model’s fields (the voxel size); the convergence check refines it together withdt_scale.
- class abmfact.knobs.Support(update_order: tuple[str, ...]=(), update_order_default: str | None = None, agent_order: bool = False, rng_streams: bool = False, grid: bool = False, dt_scale: bool = False, pop_scale: bool = False, dx_scale: bool = False, extra: dict[str, ~typing.Any]=<factory>)[source]¶
Bases:
objectWhat a model honours.
update_orderlists the activation orders the model implements and which one is its default. The other fields say whether the model reads the corresponding knob.
abmfact.checks¶
The checks: changes that a correct implementation must not care about.
- class abmfact.checks.Variant(check: str, label: str, knobs: Knobs, shuffle_ids: bool = False)[source]¶
Bases:
objectOne perturbed condition.
shuffle_idsasks for a per-seed relabelling permutation.
- class abmfact.checks.Check(name: str, question: str, compare_spread: bool = True)[source]¶
Bases:
objectOne audit check: a change that a correct implementation must not care about.
- name¶
The check’s name, as used in audit files and results.
- Type:
str
- question¶
The question the check answers, in plain words.
- Type:
str
- compare_spread¶
Whether the spread over seeds is compared as well as the mean.
- Type:
bool
abmfact.audit¶
Run an audit: execute every condition, then turn the runs into verdicts.
- abmfact.audit.point_key(params: dict[str, Any]) str[source]¶
Return a canonical JSON key for a parameter point, with keys sorted.
- class abmfact.audit.Condition(label: str, check: str | None, knobs: Knobs, shuffle_ids: bool = False, seeds: list[int] = <factory>)[source]¶
Bases:
objectOne audit condition: a label, the check it belongs to, its knobs and the seeds it runs.
checkisNonefor the baseline.shuffle_idsasks for a per-seed agent relabelling.
- abmfact.audit.execute(adapter: Adapter, jobs: list[tuple[str, str, dict[str, Any], int, dict[str, Any]]], workers: int, progress: Callable[[int, int], None] | None = None) dict[tuple[str, str, int], dict[str, float | list[float]]][source]¶
Run every job through the adapter’s engine on the local backend, in parallel when possible.
Results are keyed, so order never matters.
- class abmfact.audit.AuditResult(data: dict[str, Any])[source]¶
Bases:
objectThe outcome of
run_audit(): the fullresults.jsondocument, held indata.- property verdicts: list[dict[str, Any]]¶
Every verdict row, one per claim and check.
- flagged_checks() list[str][source]¶
Sorted names of the checks that judged at least one claim
FRAGILEorSHIFTED.
- property any_flagged: bool¶
True when any verdict is
FRAGILEorSHIFTED.
- abmfact.audit.run_audit(audit: Audit, progress: Callable[[int, int], None] | None = None) AuditResult[source]¶
Run every condition of an audit and return a verdict for each claim under each check.
- Parameters:
audit – The parsed audit file.
progress – Optional callback, called with the number of runs done and the total.
- Returns:
The
AuditResultwith claims, conditions, verdicts, summary and diagnosis.
abmfact.stats¶
Small, explicit statistics: intervals, three-outcome equivalence, slopes and spread.
- class abmfact.stats.Interval(estimate: float, low: float, high: float, n: int, sd: float = 0.0)[source]¶
Bases:
objectAn estimate with its interval, sample size and spread.
sdis the sample standard deviation for a mean interval, and the standard error for difference and slope intervals.- property half_width: float¶
Half the width of the interval.
- abmfact.stats.mean_interval(x: ndarray, alpha: float) Interval[source]¶
Two-sided
1 - 2*alphat-interval for the mean (so each side is a one-sidedalphatest).
- abmfact.stats.diff_interval(a: ndarray, b: ndarray, alpha: float) Interval[source]¶
Welch interval for
mean(b) - mean(a).
- abmfact.stats.slope_interval(x: ndarray, y: ndarray, alpha: float) Interval[source]¶
OLS slope of
yonxwith a t-interval.
- abmfact.stats.side_status(iv: Interval, test: str, value: float | tuple[float, float] | None) str[source]¶
holds,failsoruncertainfor a threshold test on an interval.
- abmfact.stats.trend_status(iv: Interval, increasing: bool, negligible: float) str[source]¶
Status of a monotone claim from a slope interval.
failswhen the slope is confidently in the wrong direction, or confidently smaller in size thannegligible(the trend has vanished).
- abmfact.stats.equivalence(iv: Interval, tol: float) str[source]¶
Three outcomes for a difference interval against a margin
tol.
- class abmfact.stats.Spread(p: float, sd_ratio: float, iqr_ratio: float)[source]¶
Bases:
objectBrown-Forsythe p-value with two scale ratios,
b / a: standard deviations and IQRs.
- abmfact.stats.spread(a: ndarray, b: ndarray) Spread[source]¶
Compare the spread of
bwith that ofa.The p-value is 1 when either sample has fewer than three values or neither varies. Both ratios are
b / a.
- abmfact.stats.seeds_needed(n: int, half_width: float, gap: float) int[source]¶
Seeds per condition needed for an interval of this width to clear a gap of this size.
- abmfact.stats.NEAR_ZERO = 0.01¶
Below this absolute baseline mean (in the metric’s own units) a relative tolerance is a tiny number.
- abmfact.stats.tolerance_warning(baseline: ndarray, tol: float) str | None[source]¶
Why a default relative tolerance may mislead for this baseline, or
None.Two triggers: the tolerance is smaller than the standard error of the baseline mean, so the seeds cannot resolve it; or the baseline mean is below
NEAR_ZEROin absolute value, so 10% of it is a tiny absolute margin. The second is in the metric’s units: most claim metrics are fractions or counts, where 0.01 is close to zero.
abmfact.diagnose¶
Map the pattern of flagged checks to the most likely cause and a fix to try first.
abmfact.report¶
Write an audit’s outputs: results.json, a self-contained report.html and an RO-Crate.
- abmfact.report.replay_command(audit_path: str | None, item: dict[str, Any]) str[source]¶
Return the shell-quoted
abmfact replaycommand that reproduces one run.itemis a reproducer entry withseedand optionalparamsandknobs.audit_pathdefaults toaudit.yaml.
- abmfact.report.render_html(result: AuditResult) str[source]¶
Render the audit result as a self-contained HTML report.
- abmfact.report.write_rocrate(out: Path, files: dict[str, str], result: AuditResult) Path[source]¶
Write
ro-crate-metadata.jsondescribing the audit files inout, and return its path.filesmaps each file name toinputoroutput. Each file is recorded with its size and SHA-256.
- abmfact.report.write_outputs(result: AuditResult, out: str | Path, audit_file: str | Path | None = None) dict[str, Path][source]¶
Write
results.json,report.htmland an RO-Crate toout, creating it if needed.When
audit_fileexists it is copied in asaudit.yaml. Returns the written paths, keyed byaudit,results,reportandrocrate.
abmfact.adapters¶
Adapters turn a model, in whatever framework it is written, into run(params, seed, knobs).
- exception abmfact.adapters.AdapterError[source]¶
Bases:
RuntimeErrorA model could not be built, run, or returned outputs ABMfact cannot read.
- abmfact.adapters.normalise_outputs(raw: Mapping[str, Any]) dict[str, float | list[float]][source]¶
Coerce model outputs to floats and lists of floats, rejecting anything else.
- class abmfact.adapters.Adapter[source]¶
Bases:
objectBase class. Subclasses implement
_run().The base class implements
rng_streams="independent"for models that do not manage their own streams, by remapping the seed through an independent derivation.- run(params: Mapping[str, Any], seed: int, knobs: Knobs) dict[str, float | list[float]][source]¶
Run the model once and return its outputs as floats and lists of floats.
When
knobsasks for independent streams and the model does not manage its own, the seed is remapped withderived_seed()first.
- class abmfact.adapters.PythonAdapter(fn: Callable[[Mapping[str, Any], int, Knobs], Mapping[str, Any]], supports: Mapping[str, Any] | Support | None = None, name: str | None = None)[source]¶
Bases:
AdapterWrap a plain Python callable
fn(params, seed, knobs) -> dict.
- class abmfact.adapters.MesaAdapter(model_cls: Any, steps: int, outputs: Mapping[str, Any], knob_kwargs: Mapping[str, str] | None = None, update_orders: Sequence[str] = (), update_order_default: str | None = None, seed_kwarg: str = 'rng', name: str | None = None)[source]¶
Bases:
AdapterRun a Mesa 3 model class.
outputsmaps output names to either a callable taking the model, or the string"datacollector:<column>"for a model-level reporter series.knob_kwargsmaps knob names (update_order,agent_order,rng_streams,grid_offset,grid_rotation,dt_scale,pop_scale,dx_scale) to constructor keyword names. A knob is supported exactly when it is mapped.
- class abmfact.adapters.NetLogoAdapter(model_path: str | PathLike[str], reporters: Mapping[str, str], ticks: int, knob_globals: Mapping[str, str] | None = None, update_orders: Sequence[str] = (), update_order_default: str | None = None, setup: str = 'setup', go: str = 'go', netlogo_home: str | None = None, link_factory: Callable[[str, str | None], Any] | None = None, name: str | None = None)[source]¶
Bases:
AdapterRun a NetLogo model through pynetlogo.
reportersmaps output names to NetLogo reporter strings. A reporter whose name ends with[]is collected every tick as a series, otherwise once at the end.knob_globalsmaps knob names to NetLogo global variable names. One workspace is kept per process and model file.
abmfact.digest¶
Content digests that identify models and builds the same way on every platform.
Git on Windows usually checks text files out with CRLF line endings. A digest of the raw bytes would then
give the same model a different identity there, and a different cache key. content_bytes() turns CRLF
into LF for text files before hashing; other files are hashed as they are. Digests that certify the exact
bytes on disk (the run store’s output hashes, the RO-Crate record of an audit) do not use this.
- abmfact.digest.TEXT_SUFFIXES = frozenset({'.bnd', '.c', '.cc', '.cfg', '.cpp', '.csv', '.cxx', '.h', '.hh', '.hpp', '.jl', '.json', '.md', '.nlogo', '.py', '.r', '.sbml', '.tsv', '.txt', '.xml', '.yaml', '.yml'})¶
Suffixes read as text. Files without a suffix are text only when named here.
- abmfact.digest.is_text(path: Path) bool[source]¶
True when the file is treated as text, by its suffix or by its name (such as
Makefile).
- abmfact.digest.content_bytes(path: str | Path) bytes[source]¶
The file’s bytes, with CRLF line endings turned into LF when it is a text file.
- abmfact.digest.content_digest(path: str | Path) str[source]¶
SHA-256 of
content_bytes(): the same for LF and CRLF copies of a text file.