T10 — Reproducible studies¶
A number in a report or a dissertation is only as good as the ability
to produce it again. This tutorial shows the tools groundfield
offers for that: seeds that pin a stochastic realisation, network
plans and world JSON that pin the geometry, the provenance record of
every solve, versioned result files, and regression checks that tell
you when an upgrade changes your numbers.
You will learn
- how to make a stochastic network reproducible, and what to store;
- what
result.metadata["provenance"]records; - how to save and load results losslessly (
gf.save_result,gf.load_result); - how to re-run a study in a fresh process and verify that it gives the same numbers;
- how to guard a study with a reference ("golden") check.
Runtime: about 15 s (one solve runs in a separate Python process).
import json
import subprocess
import sys
import tempfile
from pathlib import Path
import numpy as np
import groundfield as gf
from groundfield.generators import (
ManhattanGridPlacement,
NetworkPlan,
RadialTrunkTopology,
TnNetworkConfig,
TnNetworkGenerator,
TwoLayerSoilSpec,
Uniform,
materialise_plan,
)
print("groundfield", gf.__version__)
workdir = Path(tempfile.mkdtemp())
groundfield 2026.11.0
1. Pin the realisation¶
The configuration below has two random axes: the resistivity and the thickness of the upper soil layer. Three things reproduce a realisation:
- the seed —
TnNetworkGenerator(cfg, seed=...), orsample_world(rng=seed), draws everything from one stream; - the resolved configuration that
sample_worldreturns — the same configuration with every distribution replaced by its drawn value; - the network plan (
generator.plan()) — the pure-data description of the sites, electrodes, cables and sources, from whichmaterialise_planrebuilds the world.
gf.world_fingerprint (SHA-256 of the canonical world JSON) tells
whether two worlds are identical.
cfg = TnNetworkConfig(
soil=TwoLayerSoilSpec(
rho_1=Uniform(low=100.0, high=300.0), rho_2=50.0, h_1=Uniform(low=2.0, high=8.0)
),
building_counts={"residential": 8},
placement=ManhattanGridPlacement(spacing_x_m=25.0, spacing_y_m=30.0, n_per_row=4),
pen_topology=RadialTrunkTopology(
n_feeders=2, slots_per_substation=4, slots_per_cabinet=4, cabinet_spacing_m=50.0
),
)
world, resolved = TnNetworkGenerator(cfg, seed=0).sample_world(rng=2026)
print("drawn soil:", resolved.soil)
# (a) the seed
again, _ = TnNetworkGenerator(cfg, seed=0).sample_world(rng=2026)
# (b) the resolved configuration, stored as JSON
(workdir / "resolved_config.json").write_text(resolved.model_dump_json(indent=1))
replayed = TnNetworkGenerator(
TnNetworkConfig.model_validate_json((workdir / "resolved_config.json").read_text())
).build()
# (c) the network plan, stored as JSON
plan_json = TnNetworkGenerator(cfg, seed=0).plan().model_dump_json()
from_plan = materialise_plan(NetworkPlan.model_validate_json(plan_json))
built = TnNetworkGenerator(cfg, seed=0).build()
fingerprint = gf.world_fingerprint(world)
print("fingerprint:", fingerprint)
print("same seed ->", gf.world_fingerprint(again) == fingerprint)
print("resolved config JSON ->", gf.world_fingerprint(replayed) == fingerprint)
print(
"network plan JSON ->",
gf.world_fingerprint(from_plan) == gf.world_fingerprint(built),
)
drawn soil: kind='two_layer' rho_1=135.78696273508723 rho_2=50.0 h_1=5.8394789942909275 relative_permittivity=10.0 fingerprint: sha256:f0fc893360acaf7006d90af6a0cb2827221c78dc919cf5dd2c194c7a30c338a8 same seed -> True resolved config JSON -> True network plan JSON -> True
assert gf.world_fingerprint(again) == fingerprint
assert gf.world_fingerprint(replayed) == fingerprint
assert gf.world_fingerprint(from_plan) == gf.world_fingerprint(built)
The resolved configuration replays the world with any seed here,
because this configuration has no per-site randomness (no presence
probabilities between 0 and 1, no placement jitter). If yours has,
store the seed, the plan or simply the world JSON
(world.model_dump_json()), which is always complete.
2. Provenance of every solve¶
Every result records how it was made: the versions of groundfield, Python and the numerical libraries, the platform, the complete engine configuration, the fingerprint of the solved world and the UTC time.
engine = gf.create_engine(segment_length=1.0, frequencies=[50.0, 1000.0])
result = engine.solve(world)
provenance = result.metadata["provenance"]
print(json.dumps({k: v for k, v in provenance.items() if k != "engine"}, indent=1))
print("engine:", json.dumps(provenance["engine"]))
print("kernel that ran:", result.metadata["kernel"])
{
"groundfield_version": "2026.11.0",
"python": "3.12.16",
"numpy": "2.4.4",
"scipy": "1.17.1",
"pydantic": "2.13.3",
"platform": "macOS-27.2.1-arm64-arm-64bit",
"world_fingerprint": "sha256:f0fc893360acaf7006d90af6a0cb2827221c78dc919cf5dd2c194c7a30c338a8",
"solved_at_utc": "2026-11-16T03:25:47.354256Z"
}
engine: {"backend": "image", "frequencies": [50.0, 1000.0], "segment_length": 1.0, "tolerance": 1e-06, "max_iterations": 200, "earth_inductive_model": "sommerfeld", "image_max_terms": 300, "kernel": null, "image_series_tol": 1e-06, "image_far_field": "quadrupole", "options": {}, "sommerfeld_assembly": "tabulated", "max_segments": null, "warn_segments": null}
kernel that ran: line
assert provenance["world_fingerprint"] == fingerprint
assert provenance["groundfield_version"] == gf.__version__
The engine record is complete enough to rebuild the engine; with the world (identified by its fingerprint) the solve can be repeated:
rebuilt_engine = gf.Engine.model_validate(provenance["engine"])
repeated = rebuilt_engine.solve(world)
print("Z_in, original:", np.round(result.input_impedance(), 6))
print("Z_in, repeated:", np.round(repeated.input_impedance(), 6))
Z_in, original: [0.80455+0.j 0.80455+0.j] Z_in, repeated: [0.80455+0.j 0.80455+0.j]
assert repeated.input_impedance() == result.input_impedance() # bit for bit
3. Save and load results¶
gf.save_result writes one standard-JSON file with a small envelope
(format, schema_version, written_by, provenance, result). No
pickle is involved, so a result file can be read anywhere and does not
execute code when loaded; the write is atomic and refuses to
overwrite unless asked to. gf.load_result restores the result
losslessly — complex values, infinities and the metadata included —
and rejects files of a newer schema with ResultFormatError.
path = gf.save_result(result, workdir / "network_result.json")
envelope = json.loads(path.read_text())
print(
{k: envelope[k] for k in ("format", "schema_version", "written_by")},
f"{path.stat().st_size} bytes",
)
loaded = gf.load_result(path)
same = all(
np.array_equal(
np.asarray(result.electrode_potentials[name]),
np.asarray(loaded.electrode_potentials[name]),
)
for name in result.electrode_potentials
)
print("potentials identical after the round trip:", same)
try:
gf.save_result(result, path)
except FileExistsError as exc:
# the temporary directory differs per run; print the message without it
print("FileExistsError:", str(exc).replace(str(workdir), "<workdir>"))
{'format': 'groundfield.result', 'schema_version': 1, 'written_by': 'groundfield 2026.11.0'} 126868 bytes
potentials identical after the round trip: True
FileExistsError: <workdir>/network_result.json exists; pass overwrite=True to replace it.
assert same and loaded.input_impedance() == result.input_impedance()
assert loaded.metadata["provenance"] == provenance
4. Re-run in a fresh process¶
The strongest everyday check of reproducibility is to repeat the computation from the stored inputs in a new Python process and compare. We store the world and the engine as JSON, run a short script with the same interpreter, and load its result file.
(workdir / "world.json").write_text(world.model_dump_json())
(workdir / "engine.json").write_text(engine.model_dump_json())
script = f"""
import groundfield as gf
from pathlib import Path
d = Path({str(workdir)!r})
world = gf.World.model_validate_json((d / "world.json").read_text())
engine = gf.Engine.model_validate_json((d / "engine.json").read_text())
gf.save_result(engine.solve(world), d / "fresh_result.json")
"""
subprocess.run(
[sys.executable, "-c", "\n".join(line.strip() for line in script.splitlines())],
check=True,
)
fresh = gf.load_result(workdir / "fresh_result.json")
print(
"same world fingerprint:",
fresh.metadata["provenance"]["world_fingerprint"] == fingerprint,
)
print("same impedances: ", fresh.input_impedance() == result.input_impedance())
same world fingerprint: True same impedances: True
assert fresh.metadata["provenance"]["world_fingerprint"] == fingerprint
assert fresh.input_impedance() == result.input_impedance()
Bit-identical results are expected on the same machine with the same library versions. Across machines, BLAS libraries and versions, the last digits may differ; compare with a tolerance there.
5. A reference ("golden") check for your study¶
Store the key numbers of a study once, together with the inputs and a tolerance, and check them whenever you upgrade groundfield or change your environment. The check below compares the input impedance at every frequency with a relative tolerance and reports the worst deviation.
def write_reference(result, path, *, rtol):
# Key numbers of the study plus the tolerance they must keep.
z = result.input_impedance()
reference = {
"rtol": rtol,
"world_fingerprint": result.metadata["provenance"]["world_fingerprint"],
"groundfield_version": result.metadata["groundfield_version"],
"frequencies_hz": list(result.frequencies),
"z_in_re": [v.real for v in z],
"z_in_im": [v.imag for v in z],
}
Path(path).write_text(json.dumps(reference, indent=1))
def check_reference(result, path):
# Return the worst relative deviation from the stored reference.
reference = json.loads(Path(path).read_text())
z_ref = np.array(reference["z_in_re"]) + 1j * np.array(reference["z_in_im"])
z_now = np.array(result.input_impedance())
worst = float(np.max(np.abs(z_now / z_ref - 1.0)))
ok = (
worst <= reference["rtol"]
and list(result.frequencies) == reference["frequencies_hz"]
)
return ok, worst
write_reference(result, workdir / "reference.json", rtol=1e-9)
print("fresh process:", check_reference(fresh, workdir / "reference.json"))
fresh process: (True, 0.0)
What a numbers-changing release looks like: up to 0.15.0 the image
family used the point kernel; this release made the exact line-source
kernel the default (see the changelog's list of numbers-changing
releases). Solving with kernel="point" reproduces the old numbers —
and the check against the reference made with the new default fails,
naming the size of the change:
old_behaviour = gf.create_engine(
segment_length=1.0, frequencies=[50.0, 1000.0], kernel="point"
).solve(world)
ok, worst = check_reference(old_behaviour, workdir / "reference.json")
print(f"kernel='point': check passed = {ok}, worst deviation {worst:.2%}")
kernel='point': check passed = False, worst deviation 0.77%
assert check_reference(fresh, workdir / "reference.json")[0]
assert not ok and worst > 1e-3
In a project, put the check into a test so that it runs with every change, for example with pytest (a sketch — paths and names are yours):
# tests/test_study_reference.py
import groundfield as gf
from my_study import build_world, ENGINE, check_reference
def test_station_impedance_is_unchanged():
result = ENGINE.solve(build_world())
ok, worst = check_reference(result, "reference/station.json")
assert ok, f"input impedance moved by {worst:.2e}"
When a check fails after an upgrade, read the "numbers that change" section of the release notes before you accept new reference values.
Summary¶
- Store the seed and the configuration — or the network plan or world
JSON — with every study; compare worlds with
gf.world_fingerprint. result.metadata["provenance"]records versions, engine and world fingerprint;gf.save_result/gf.load_resultkeep results losslessly in standard JSON.- Re-run from stored inputs in a fresh process, and guard key numbers with a reference check and a stated tolerance.
This is the last tutorial. The how-to guides cover individual tasks (sweeps and Monte Carlo, plots, exports, warnings), the explanation section the theory behind every engine.
<style>
['pre { line-height: 125%; }\ntd.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\nspan.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\ntd.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\nspan.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n.highlight-ipynb .hll { background-color: var(--jp-cell-editor-active-background) }\n.highlight-ipynb { background: var(--jp-cell-editor-background); color: var(--jp-mirror-editor-variable-color) }\n.highlight-ipynb .c { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment */\n.highlight-ipynb .err { color: var(--jp-mirror-editor-error-color) } /* Error */\n.highlight-ipynb .k { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword */\n.highlight-ipynb .o { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator */\n.highlight-ipynb .p { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation */\n.highlight-ipynb .ch { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Hashbang */\n.highlight-ipynb .cm { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Multiline */\n.highlight-ipynb .cp { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Preproc */\n.highlight-ipynb .cpf { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.PreprocFile */\n.highlight-ipynb .c1 { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Single */\n.highlight-ipynb .cs { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Special */\n.highlight-ipynb .kc { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Constant */\n.highlight-ipynb .kd { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Declaration */\n.highlight-ipynb .kn { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Namespace */\n.highlight-ipynb .kp { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Pseudo */\n.highlight-ipynb .kr { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Reserved */\n.highlight-ipynb .kt { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Type */\n.highlight-ipynb .m { color: var(--jp-mirror-editor-number-color) } /* Literal.Number */\n.highlight-ipynb .s { color: var(--jp-mirror-editor-string-color) } /* Literal.String */\n.highlight-ipynb .ow { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator.Word */\n.highlight-ipynb .pm { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation.Marker */\n.highlight-ipynb .w { color: var(--jp-mirror-editor-variable-color) } /* Text.Whitespace */\n.highlight-ipynb .mb { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Bin */\n.highlight-ipynb .mf { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Float */\n.highlight-ipynb .mh { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Hex */\n.highlight-ipynb .mi { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer */\n.highlight-ipynb .mo { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Oct */\n.highlight-ipynb .sa { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Affix */\n.highlight-ipynb .sb { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Backtick */\n.highlight-ipynb .sc { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Char */\n.highlight-ipynb .dl { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Delimiter */\n.highlight-ipynb .sd { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Doc */\n.highlight-ipynb .s2 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Double */\n.highlight-ipynb .se { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Escape */\n.highlight-ipynb .sh { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Heredoc */\n.highlight-ipynb .si { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Interpol */\n.highlight-ipynb .sx { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Other */\n.highlight-ipynb .sr { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Regex */\n.highlight-ipynb .s1 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Single */\n.highlight-ipynb .ss { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Symbol */\n.highlight-ipynb .il { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer.Long */']
</style>