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.

exception abmfact.config.ConfigError[source]

Bases: ValueError

The audit file is not valid.

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: object

How 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 budget section of an audit file, validating every field.

Raises ConfigError for unknown keys, fewer than 3 seeds, alpha outside 0 to 0.5, fewer than 1 job or unknown checks.

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

The budget as a plain dict for the audit record.

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: object

A parsed audit file: the model adapter, base parameters, claims and budget.

adapter

The adapter that runs the model.

Type:

abmfact.adapters.Adapter

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:

abmfact.config.Budget

model_cfg

The model section 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 convergence section, 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 Audit from a parsed YAML document.

base_dir is where relative model paths and modules are looked up, defaulting to the current directory. Raises ConfigError when 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.

overrides replaces budget fields, ignoring None values. Raises ConfigError when 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.

adapter is python, mesa, netlogo, command or engine; any other name raises ConfigError.

abmfact.claims

Claims: a model’s conclusions written as checkable statements.

exception abmfact.claims.ClaimError[source]

Bases: ValueError

A 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: object

A parsed metric expression: name, name[i] or f(name).

classmethod parse(expr: str) → Metric[source]

Parse a metric expression, raising ClaimError when 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. std is the sample standard deviation, and 0 for a single value. Raises ClaimError when 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: object

One 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:

abmfact.claims.Metric

test

One of greater_than, less_than, between, monotone_increasing or monotone_decreasing.

Type:

str

value

The threshold, or a (low, high) pair for between; None for 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; None uses default_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_increasing and monotone_decreasing tests.

points(base: Mapping[str, Any]) → list[dict[str, Any]][source]

Parameter dicts this claim is evaluated at: the cartesian product of where over base.

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

The claim as a plain dict for results.json; optional fields appear only when set.

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: object

Settings passed to every model run.

None for update_order means “use the model’s own default”. All other defaults are the identity: they leave a correct model unchanged. dx_scale multiplies the spatial resolution of a model’s fields (the voxel size); the convergence check refines it together with dt_scale.

with_(**changes: Any) → Knobs[source]

Return a copy with the given fields changed.

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

The knobs as a plain dict, with grid_offset as a list.

classmethod from_dict(d: Mapping[str, Any]) → Knobs[source]

Build knobs from a dict, such as one written by to_dict().

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

Only the knobs that differ from the defaults, for labels and reproducers.

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: object

What a model honours.

update_order lists the activation orders the model implements and which one is its default. The other fields say whether the model reads the corresponding knob.

classmethod from_mapping(m: Mapping[str, Any] | None) → Support[source]

Build support from a model’s supports mapping; an empty or missing mapping supports nothing.

update_order is a list whose first entry is the default, or a mapping with values and default. Unknown keys are kept in extra.

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

The support as a plain dict for the audit record; dx_scale appears only when declared.

abmfact.knobs.derived_seed(seed: int, salt: int = 180333685) → int[source]

An independent seed derived from seed. Used when a model does not manage streams.

abmfact.knobs.perm_seed(seed: int) → int[source]

Seed for the agent relabelling permutation, independent of the model’s own streams.

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: object

One perturbed condition. shuffle_ids asks for a per-seed relabelling permutation.

class abmfact.checks.Check(name: str, question: str, compare_spread: bool = True)[source]

Bases: object

One 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

variants(support: Support) → list[Variant] | None[source]

Variants to run, or None when the model does not declare the needed knob.

abmfact.checks.select_checks(names: list[str] | None) → list[Check][source]

Return the named checks in their standard order, or every check when names is empty or None.

Raises ValueError for an unknown check name.

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: object

One audit condition: a label, the check it belongs to, its knobs and the seeds it runs.

check is None for the baseline. shuffle_ids asks for a per-seed agent relabelling.

knobs_for(seed: int) → Knobs[source]

Knobs for one seed, with the relabelling permutation seed added when shuffle_ids is set.

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: object

The outcome of run_audit(): the full results.json document, held in data.

property verdicts: list[dict[str, Any]]

Every verdict row, one per claim and check.

matrix() → dict[str, dict[str, str]][source]

{claim_id: {check: verdict}}.

flagged_checks() → list[str][source]

Sorted names of the checks that judged at least one claim FRAGILE or SHIFTED.

property any_flagged: bool

True when any verdict is FRAGILE or SHIFTED.

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

Serialise the result as indented JSON with sorted keys and a trailing newline.

With include_timestamp false the created field is dropped, so repeated audits give identical text.

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 AuditResult with 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: object

An estimate with its interval, sample size and spread.

sd is 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.

to_dict() → dict[str, float | int][source]

The interval as a plain dict.

abmfact.stats.mean_interval(x: ndarray, alpha: float) → Interval[source]

Two-sided 1 - 2*alpha t-interval for the mean (so each side is a one-sided alpha test).

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 y on x with a t-interval.

abmfact.stats.side_status(iv: Interval, test: str, value: float | tuple[float, float] | None) → str[source]

holds, fails or uncertain for 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.

fails when the slope is confidently in the wrong direction, or confidently smaller in size than negligible (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: object

Brown-Forsythe p-value with two scale ratios, b / a: standard deviations and IQRs.

shifted(alpha: float) → bool[source]

Flag only a clear change: p below alpha / 10 and both ratios beyond 2 the same way.

abmfact.stats.spread(a: ndarray, b: ndarray) → Spread[source]

Compare the spread of b with that of a.

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_ZERO in 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.stats.default_tolerance(baseline: ndarray, fraction: float = 0.1) → float[source]

Default equivalence margin: fraction of the absolute baseline mean.

When the mean is zero it falls back to fraction of the standard deviation, then to 1e-9.

abmfact.diagnose

Map the pattern of flagged checks to the most likely cause and a fix to try first.

class abmfact.diagnose.Rule(check: str, unless: tuple[str, ...], cause: str, fix: str)[source]

Bases: object

A diagnosis rule: the likely cause and the fix to try first when check is flagged.

The rule is passed over when any check in unless is also flagged, so a later rule can apply.

abmfact.diagnose.diagnose(flagged: Iterable[str]) → list[dict[str, str]][source]

Return one finding per flagged check, choosing the most specific rule that applies.

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 replay command that reproduces one run.

item is a reproducer entry with seed and optional params and knobs. audit_path defaults to audit.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.json describing the audit files in out, and return its path.

files maps each file name to input or output. 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.html and an RO-Crate to out, creating it if needed.

When audit_file exists it is copied in as audit.yaml. Returns the written paths, keyed by audit, results, report and rocrate.

abmfact.adapters

Adapters turn a model, in whatever framework it is written, into run(params, seed, knobs).

exception abmfact.adapters.AdapterError[source]

Bases: RuntimeError

A 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: object

Base 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 knobs asks for independent streams and the model does not manage its own, the seed is remapped with derived_seed() first.

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

Return the adapter class, model name and declared support, for the audit record.

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: Adapter

Wrap 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: Adapter

Run a Mesa 3 model class.

outputs maps output names to either a callable taking the model, or the string "datacollector:<column>" for a model-level reporter series. knob_kwargs maps 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: Adapter

Run a NetLogo model through pynetlogo.

reporters maps 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_globals maps knob names to NetLogo global variable names. One workspace is kept per process and model file.

class abmfact.adapters.CommandAdapter(argv: Sequence[str], supports: Mapping[str, Any] | None = None, timeout: float = 600.0, cwd: str | None = None, name: str | None = None)[source]

Bases: Adapter

Run any program. It reads {"params", "seed", "knobs"} as JSON on stdin and prints a JSON object.

abmfact.adapters.import_target(target: str) → Any[source]

Import package.module:attribute.

abmfact.adapters.load_adapter(cfg: Mapping[str, Any], base_dir: Path | None = None) → Adapter[source]

Build an adapter from the model: section of an audit 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.