T05 — Export to groundinsight¶
groundfield is the field-level reference; the network-level studies
of a whole medium-voltage grid (fault currents, reduction factors,
touch voltages at many stations) run in the sister package
groundinsight. There a
grounding system is a bus whose impedance is given by a formula
\(Z(f, \rho)\) of its BusType. This tutorial turns the rho-f models
of T04 into BusTypes, writes
and reads them as JSON, checks that the exported formula reproduces
the fit and the field solution, and — if groundinsight is installed —
evaluates them inside a groundinsight network.
You will learn
- the BusType document: formula, samples and metadata;
- the round trip fit → JSON → formula and how accurate it is;
- why a vector fit needs
rho_at_fitand what the passivity check protects against; - how a BusType is used by groundinsight.
Prerequisites: pip install "groundfield[groundinsight]" for the
last section (the JSON export itself needs no extra). Runtime: about
10 s.
import json
import tempfile
import warnings
from pathlib import Path
import numpy as np
import groundfield as gf
print("groundfield", gf.__version__)
RHO_AL = 2.82e-8 # Ohm m
FREQUENCIES = [
0.0,
50.0,
150.0,
250.0,
350.0,
450.0,
550.0,
650.0,
750.0,
850.0,
1000.0,
]
def lv_network(rho=100.0, n_houses=4):
# The network of T04: substation earth plus houses on an inductive PEN chain.
world = gf.create_world(soil=gf.HomogeneousSoil(rho=rho))
gf.create_electrode(
world,
"grid_mesh",
name="station",
corner=(-2.0, -2.0, 0.6),
size=(4.0, 4.0),
n_x=1,
n_y=1,
)
for k, (x, y) in enumerate([(-2.0, -2.0), (2.0, -2.0), (2.0, 2.0)]):
gf.create_electrode(
world, "rod", name=f"station_rod_{k}", position=(x, y, 0.6), length=4.0
)
gf.create_conductor(
world, name=f"bond_{k}", start="station", end=f"station_rod_{k}"
)
previous = "station"
for k in range(n_houses):
x0 = 40.0 * (k + 1)
gf.create_electrode(
world,
"grid_mesh",
name=f"house_{k}",
corner=(x0 - 5.0, 10.0, 0.8),
size=(10.0, 10.0),
n_x=1,
n_y=1,
)
gf.create_conductor(
world,
name=f"pen_{k}",
start=previous,
end=f"house_{k}",
conductor_type="pen",
resistivity=RHO_AL,
cross_section=50e-6,
coupling_to_soil="isolated",
inductance_model="neumann",
)
previous = f"house_{k}"
gf.create_source(world, attached_to="station", magnitude=1.0)
return world
engine = gf.create_engine(segment_length=1.0, frequencies=FREQUENCIES)
RHOS = [100.0, 300.0, 1000.0]
results = {rho: engine.solve(lv_network(rho)) for rho in RHOS}
standard_fit = gf.rho_f_standard_from_results([results[rho] for rho in RHOS], RHOS)
vector_fit_100 = gf.rho_f_from_field_result(results[100.0], n_poles=2)
print(f"standard form: max_relative {standard_fit.max_relative:.2%}")
print(f"vector fit at 100 Ohm m: rms_relative {vector_fit_100.rms_relative:.1e}")
groundfield 2026.11.0
standard form: max_relative 1.70% vector fit at 100 Ohm m: rms_relative 1.9e-04
The BusType document¶
gf.to_bustype_dict converts a fit into the JSON-ready BusType
document (schema groundfield.bustype, version 1). It has three parts:
- the groundinsight fields
name,description,system_type,voltage_levelandimpedance_formula— a formula inf(Hz),rho(Ω·m) andj; samples— the impedances the formula was fitted to, so that the fit can be audited later;metadata— fit method and quality, coefficients, which impedance was fitted (quantity), howrhois defined (rho_definition), the passivity check, the groundfield version and the time of export.
decimals sets the significant digits of every coefficient (default
12).
document = gf.to_bustype_dict(
standard_fit,
name="lv_network_4_houses",
system_type="TN",
voltage_level=0.4,
description="LV network: substation earth and four houses on a 50 mm2 Al PEN",
soil_summary="homogeneous soil, 100 ... 1000 Ohm m",
)
print("impedance_formula:", document["impedance_formula"])
print("samples:", {key: len(values) for key, values in document["samples"].items()})
print(json.dumps(document["metadata"], indent=1))
impedance_formula: f*rho*(-1.89180216612e-7 + 7.51031569934e-8*j) + f*(0.00013601135615 + 0.000665147995802*j) + 0.0133319823764*rho + 0.015930720418
samples: {'frequency_Hz': 33, 'rho_Ohm_m': 33, 'Z_real_Ohm': 33, 'Z_imag_Ohm': 33}
{
"fit_method": "rho_f_standard",
"fit_quality": {
"rms_error_Ohm": 0.024655653378599575,
"rms_relative": 0.0039207192476463405,
"max_relative": 0.016961485496135426
},
"coefficients": {
"k0": 0.01593072041799054,
"k1": 0.013331982376407822,
"k2": 0.00013601135615025735,
"k3": 0.0006651479958017657,
"k4": -1.8918021661196002e-07,
"k5": 7.510315699339594e-08
},
"weights": "relative",
"quantity": "input",
"rho_definition": "effective_resistivity",
"rho_preset": null,
"electrode_name": null,
"soil_summary": "homogeneous soil, 100 ... 1000 Ohm m",
"source": "groundfield 2026.11.0",
"created_at_utc": "2026-11-15T21:25:32Z",
"passivity": {
"passed": true,
"min_re_Z_Ohm": 1.349128958058,
"f_at_min_Hz": 0.0,
"rho_at_min_Ohm_m": 100.0,
"f_checked_Hz": [
0.0,
2000.0
],
"rho_checked_Ohm_m": [
100.0,
1000.0
],
"n_points": 4
}
}
assert document["metadata"]["quantity"] == "input"
assert document["metadata"]["passivity"]["passed"]
Round trip: JSON file, formula, values¶
gf.save_bustype_json writes the same document to a file and
gf.load_bustype_json reads it back as a BusTypeSpec.
gf.evaluate_spec(spec, frequencies, rho) evaluates the formula of a
spec. Two comparisons tell us how good the exported model is:
- formula against the fit object — the error of the export (rounding
to
decimalsdigits); - formula against the field solution — the error of the reduced model itself.
workdir = Path(tempfile.mkdtemp())
path = gf.save_bustype_json(
standard_fit,
workdir / "lv_network_4_houses.json",
name="lv_network_4_houses",
system_type="TN",
voltage_level=0.4,
)
spec = gf.load_bustype_json(path)
print(gf.fit_quality_summary(spec))
f = np.array(FREQUENCIES)
for rho in RHOS:
z_formula = gf.evaluate_spec(spec, f, rho)
z_fit = standard_fit.evaluate(np.full(f.size, rho), f)
z_field = np.array(results[rho].input_impedance())
export_error = np.max(np.abs(z_formula / z_fit - 1.0))
model_error = np.max(np.abs(z_formula / z_field - 1.0))
print(
f"rho = {rho:6.0f} Ohm m: formula vs fit {export_error:.1e}, formula vs field solution {model_error:.2%}"
)
BusTypeSpec(name='lv_network_4_houses', method=rho_f_standard, rms=2.466e-02 Ω, rms_rel=0.39%, max_rel=1.70%, quantity=input) rho = 100 Ohm m: formula vs fit 6.6e-13, formula vs field solution 1.70% rho = 300 Ohm m: formula vs fit 6.3e-13, formula vs field solution 0.55% rho = 1000 Ohm m: formula vs fit 6.1e-13, formula vs field solution 0.55%
for rho in RHOS:
z_formula = gf.evaluate_spec(spec, f, rho)
assert (
np.max(np.abs(z_formula / standard_fit.evaluate(np.full(f.size, rho), f) - 1.0))
< 1e-10
)
assert (
np.max(np.abs(z_formula / np.array(results[rho].input_impedance()) - 1.0))
< 0.02
)
Vector fits carry their resistivity¶
A vector fit describes \(Z(f)\) for the one soil it was computed on; its
formula contains no rho. In groundinsight the BusType is paired with
a bus whose specific_earth_resistance must be that soil, so the
export requires rho_at_fit and records it. Without it the export
stops before anything is written, with a message that says what to
pass. This network lies in homogeneous soil, so rho_at_fit is its
resistivity. For layered soil it is the effective resistivity
\(\rho_\text{eff} = \rho_1^{1-w}\rho_2^{w}\),
gf.effective_resistivity(soil), the value the AP2 network model gives
a bus; a standard form over layered soils is fitted over the effective
resistivities of the solved soils (see the
Soil reference):
try:
gf.to_bustype_dict(
vector_fit_100, name="lv_100", system_type="TN", voltage_level=0.4
)
except ValueError as exc:
print("ValueError:", exc)
ValueError: to_bustype_dict: rho_at_fit is required for a VectorFitResult. A vector fit Z(f) holds for the one soil it was computed on; the BusType records that resistivity (samples['rho_Ohm_m'], metadata['rho_at_fit_Ohm_m']) so that it is paired with a groundinsight Bus of the same specific_earth_resistance. Pass it explicitly, e.g. to_bustype_dict(fit, ..., rho_at_fit=100.0). For layered soil the convention is the effective resistivity of the soil, rho_at_fit=groundfield.effective_resistivity(soil) (the rho that the groundinsight Bus carries), and the layers are described with soil_summary=...; standard-form fits (RhoFStandardFit) do not need it.
rho_bus = gf.effective_resistivity(results[100.0].soil) # homogeneous: 100 Ohm m
vector_document = gf.to_bustype_dict(
vector_fit_100,
name="lv_100",
system_type="TN",
voltage_level=0.4,
rho_at_fit=rho_bus,
decimals=8,
)
print("impedance_formula:", vector_document["impedance_formula"])
print("rho at fit:", vector_document["metadata"]["rho_at_fit_Ohm_m"], "Ohm m")
print("rho definition:", vector_document["metadata"]["rho_definition"])
layered = gf.TwoLayerSoil(rho_1=100.0, rho_2=30.0, h_1=5.0)
print(
f"in 100 over 30 Ohm m (h_1 = 5 m) a bus would carry {gf.effective_resistivity(layered):.2f} Ohm m"
)
vector_spec = gf.BusTypeSpec.from_dict(vector_document)
z_vector = gf.evaluate_spec(vector_spec, f, 100.0)
print(
f"formula vs field solution: {np.max(np.abs(z_vector / np.array(results[100.0].input_impedance()) - 1.0)):.1e}"
)
impedance_formula: 5.3175653 - 146440.61/(2*pi*f*j + 37356.434) - 200.73663/(2*pi*f*j + 5797.7274) rho at fit: 100.0 Ohm m rho definition: effective_resistivity in 100 over 30 Ohm m (h_1 = 5 m) a bus would carry 76.15 Ohm m formula vs field solution: 2.9e-04
assert np.max(np.abs(z_vector / vector_fit_100.evaluate(f) - 1.0)) < 1e-6 # 8 digits
assert (
np.max(np.abs(z_vector / np.array(results[100.0].input_impedance()) - 1.0)) < 1e-3
)
assert rho_bus == 100.0
assert vector_document["metadata"]["rho_definition"] == "effective_resistivity"
assert abs(gf.effective_resistivity(layered) - 76.1465) < 1e-4
Passivity: no negative resistance in the network model¶
A rational fit can be excellent at its samples and still have a
negative real part between or beyond them — typically a resonance
that the fit placed outside the sampled band. Inside a network model
such a bus would generate power. The export therefore checks the
formula from 0 Hz to twice the highest fitted frequency (over the
fitted \(\rho\) range for the standard form), records the result in
metadata["passivity"], warns with NonPassiveFitWarning, and with
require_passive=True refuses to export.
The fit below is built by hand to show the effect: a damped resonance at 1.5 kHz with a negative residue, sampled only up to 1 kHz, where it is passive.
from groundfield.postprocess.vector_fitting import VectorFitResult
alpha, beta = 2 * np.pi * 20.0, 2 * np.pi * 1500.0 # damping and resonance in rad/s
pole, residue = complex(-alpha, beta), complex(-3.0 * alpha, 0.0)
resonant = VectorFitResult(
poles=np.array([pole, pole.conjugate()]),
residues=np.array([residue, residue.conjugate()]),
R_inf=2.0,
L_inf=0.0,
rms_error=0.0,
fit_frequencies=f,
fit_values=np.zeros(f.size, dtype=complex),
)
print(f"min Re Z at the samples: {resonant.evaluate(f).real.min():.3f} Ohm")
report = gf.check_passivity(resonant)
print(
f"check_passivity: passed={report.passed}, min Re Z = {report.min_re_Z:.3f} Ohm at {report.f_at_min:.0f} Hz"
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
gf.to_bustype_dict(
resonant, name="resonant", system_type="TN", voltage_level=0.4, rho_at_fit=100.0
)
print(caught[0].category.__name__, "-", str(caught[0].message).split(". ")[0] + ".")
try:
gf.save_bustype_json(
resonant,
workdir / "resonant.json",
name="resonant",
system_type="TN",
voltage_level=0.4,
rho_at_fit=100.0,
require_passive=True,
)
except gf.NonPassiveFitError:
print(
"NonPassiveFitError raised; file written:", (workdir / "resonant.json").exists()
)
min Re Z at the samples: 1.995 Ohm check_passivity: passed=False, min Re Z = -1.000 Ohm at 1500 Hz NonPassiveFitWarning - BusType 'resonant': the exported impedance formula is not passive: it has Re Z = -1 Ohm at f = 1500 Hz, above the fitted band 0 to 1000 Hz (checked from 0 to 2000 Hz). NonPassiveFitError raised; file written: False
assert resonant.evaluate(f).real.min() > 0 and not report.passed
assert issubclass(caught[0].category, gf.NonPassiveFitWarning)
assert not (workdir / "resonant.json").exists()
Loading BusTypes from other people¶
A BusType file is data, and data may come from anywhere. The formula
is therefore never executed: an allow-list parser accepts numbers,
f, rho, j, pi, E, the four arithmetic operators, bounded
integer powers and sqrt/exp/log, and nothing else. A crafted
formula is rejected when the file is loaded:
crafted = dict(document, impedance_formula="__import__('os').getcwd() + rho")
try:
gf.BusTypeSpec.from_dict(crafted)
except gf.EvaluateSpecError as exc:
print("EvaluateSpecError:", exc)
EvaluateSpecError: BusType document 'lv_network_4_houses': impedance_formula is not an allowed impedance formula: character(s) not allowed in an impedance formula: "'" (U+0027). Allowed are ASCII letters, digits, '_', '.', '+', '-', '*', '/', '(', ')' and spaces. An impedance formula is an expression in f (Hz) and rho (Ohm m) built from numbers, j (or I), pi, E, + - * /, ** with a literal exponent, sqrt, exp and log; groundfield parses it and never runs it as code. Formulas written by groundfield's exporter always satisfy this grammar.
Inside groundinsight¶
With the groundinsight extra installed, gf.to_bustype returns a
live groundinsight BusType. A bus of that type in a groundinsight
network evaluates the formula at the network frequencies with its own
specific_earth_resistance; we compare its impedances with
evaluate_spec. The cell prints a note instead if groundinsight is
not installed.
try:
import groundinsight as gi
except ImportError:
gi = None
print("groundinsight is not installed: pip install 'groundfield[groundinsight]'")
if gi is not None:
network = gi.create_network(name="tutorial", frequencies=[50.0, 250.0, 1000.0])
bus_standard = gi.create_bus(
name="station_A",
type=gf.to_bustype(
standard_fit, name="lv_std", system_type="TN", voltage_level=0.4
),
specific_earth_resistance=300.0,
network=network,
)
bus_vector = gi.create_bus(
name="station_B",
type=gf.to_bustype(
vector_fit_100,
name="lv_100",
system_type="TN",
voltage_level=0.4,
rho_at_fit=100.0,
decimals=8,
),
specific_earth_resistance=100.0,
network=network,
)
gi_deviation = 0.0
for bus, bus_spec, rho in (
(bus_standard, spec, 300.0),
(bus_vector, vector_spec, 100.0),
):
for freq, z in bus.impedance.items():
z_gi = complex(z.real, z.imag)
z_gf = gf.evaluate_spec(bus_spec, [freq], rho)[0]
gi_deviation = max(gi_deviation, abs(z_gi / z_gf - 1.0))
print(f"{bus.name} at {freq:6.0f} Hz: groundinsight {z_gi:.5f} Ohm")
print(f"largest deviation groundinsight vs evaluate_spec: {gi_deviation:.1e}")
station_A at 50 Hz: groundinsight 4.01949+0.03438j Ohm station_A at 250 Hz: groundinsight 4.03534+0.17192j Ohm station_A at 1000 Hz: groundinsight 4.09478+0.68768j Ohm station_B at 50 Hz: groundinsight 1.36323+0.03484j Ohm station_B at 250 Hz: groundinsight 1.37214+0.17328j Ohm station_B at 1000 Hz: groundinsight 1.48940+0.65846j Ohm largest deviation groundinsight vs evaluate_spec: 1.3e-16
if gi is not None:
assert gi_deviation < 1e-9
Summary¶
to_bustype_dict/save_bustype_jsonwrite the formula together with its samples, quality figures and passivity check;load_bustype_jsonandevaluate_specread and evaluate it, andto_bustypehands it to groundinsight.- Check two errors separately: export (formula vs fit, set by
decimals) and model (formula vs field solution). - Vector fits need
rho_at_fit; non-passive formulas warn, andrequire_passive=Truerefuses them. - The formula parser never executes code from a file.
<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>