IO and groundinsight¶
The io package is the boundary between groundfield and the rest of
the software family: the export of reduced rho-f models as
groundinsight BusType definitions (JSON file or live object, ADR-0008),
CSV tables with a provenance header, and legacy VTK files for ParaView.
Result files of a solve are described on Result files.
Mathematical and physical context¶
The reduction pipeline is
groundinsight evaluates the formula with two free symbols, f (Hz)
and rho (the Bus.specific_earth_resistance in Ω·m), and the
imaginary unit j. Both fit families are projected onto that set:
- standard form (
RhoFStandardFit), fitted over a sweep of \(\rho\) and \(f\): \(Z = k_0 + k_1\rho + (k_2 + jk_3)f + (k_4 + jk_5)f\rho\), already in(rho, f); - vector fit (
VectorFitResult) at one soil: a rational function of \(s\), exported with \(s \to j2\pi f\), so the formula depends onfonly. The soil it belongs to must be given asrho_at_fit.
The rho of layered soil. A Bus carries one resistivity. For
homogeneous soil it is \(\rho\); for layered soil it is the effective
resistivity of the AP1 catalogue,
with the weights \((w_0, \beta)\) of the electrode class: \(w_0 = 0.13\),
\(\beta = 0.8\) of the LV networks by default, or a preset of the AP2
hand-over such as "station" (0.06, 1.3) or "lv_group_2_p10"
(gf.effective_resistivity(soil, preset=...), see
Soil). It is the value the AP2 network
model gives a bus. A vector fit therefore passes
rho_at_fit=gf.effective_resistivity(soil, preset=...), and a standard
form is fitted over the effective resistivities of the solved soils,
gf.rho_f_standard_from_results(results, [gf.effective_resistivity(r.soil, preset=...) for r in results]);
both kinds of BusType then pair with a Bus whose resistivity uses the
same preset. Every document records the convention as
metadata["rho_definition"] = "effective_resistivity" (documents of
0.15.0 have no such entry) and the preset you name with rho_preset=...
(a key of gf.soil.EFFECTIVE_RESISTIVITY_PRESETS) as
metadata["rho_preset"], None when none is named (user decision Q39;
documents of earlier versions load with None, spec.rho_preset). The
exporter cannot check the number it is given against the preset; the
paths that serve a bus can: evaluate_spec(spec, f, rho, rho_preset=...)
and bustype_from_spec(spec, rho_preset=...) (the live groundinsight
BusType of a loaded document) take the preset of the bus and emit
RhoPresetMismatchWarning when the document names another one — a preset
holds for its electrode class only (the AP1 station paired with
"lv_group_4_p40" misses the field solution by 39.9 % rms). The live
BusType of to_bustype, save_bustype_to_db and bustype_from_spec
has no metadata; with a preset its description ends with the line
groundfield rho_preset: <name> (a preset line in the given description
is replaced), which the groundinsight database keeps, and
gf.bustype_rho_preset(bus_type) reads it back, also from a BusType
loaded with gi.load_bustypes_from_db() (audit W3B-06; None without a
preset line). On load metadata["rho_preset"] must be a
preset name or null, as the exporters write it (padding, line breaks and
unknown names are refused); only the exact line groundfield rho_preset:
<name> of a description is the record, the other lines stay as given
(audit W3R2B-06). Describe
the layers, and explicit weights \(w_0\), \(\beta\), in soil_summary.
Before a BusType is written, the exported formula (with its rounded
coefficients) is checked for passivity, \(\operatorname{Re}Z \ge 0\) from
0 Hz to twice the highest fitted frequency; a violation warns with
NonPassiveFitWarning (or raises NonPassiveFitError with
require_passive=True). A formula read from a file is untrusted text:
load_bustype_json and evaluate_spec parse it with an allow-list
parser that builds the expression from the syntax tree and never
evaluates the text (numbers, f, rho, j, pi, E, arithmetic,
literal powers, sqrt / exp / log, within size bounds). Every node
is built unevaluated; the parser computes the numbers itself in bounded
floating point, and evaluate_spec evaluates the tree with its own
numeric function instead of SymPy's lambdify, so a crafted formula
cannot make SymPy expand or simplify it. Printing a parsed formula or
handing it to lambdify lets SymPy evaluate parts of it again: show the
formula text of an untrusted file instead. The parser collects like
terms of a sum itself; a real or imaginary part that cancels below
\(2^{-100}\) times the largest magnitude of that part among the terms is
zero, the other part is kept. Non-finite numbers of a BusType document
(an unknown rms error, a non-finite sample) are written as null, so the
file is strict JSON. load_bustype_json also checks the rest of the
document: name and system_type are not objects or lists,
description is a string or null, and the free-form metadata nest at
most MAX_METADATA_DEPTH (32) levels; anything else raises ValueError.
fit_quality_summary reads only finite numbers and strings from the
metadata, so a loaded document never makes it fail.
Validity. The exported model inherits the quasi-static band
(\(f < 1\,\mathrm{kHz}\)) and the linearity of the field model; it is meant
for fault-current, EPR and reduction studies, not for impulse or
lightning transients. One BusType is the impedance of one terminal
(the input impedance by default); mutual impedances (BranchType) are
not exported.
Transport¶
| Path | Functions | Needs groundinsight |
|---|---|---|
| JSON file | save_bustype_json, load_bustype_json, to_bustype_dict |
no |
| Python object | to_bustype (live groundinsight.BusType), save_bustype_to_db |
yes (pip install "groundfield[groundinsight]") |
| Check | evaluate_spec(spec, frequencies, rho), fit_quality_summary(spec) |
no |
Example¶
A station earth (ring and rod) in two-layer soil, swept over the
upper-layer resistivity \(\rho_1\) (fixed \(\rho_2 = 100\,\Omega\,\mathrm{m}\),
\(h_1 = 5\,\mathrm{m}\)), fitted with the standard form over the effective
resistivities of the four soils (weights of the "station" preset) and
exported:
import groundfield as gf
def station(rho_1):
world = gf.create_world(soil=gf.TwoLayerSoil(rho_1=rho_1, rho_2=100.0, h_1=5.0))
gf.create_electrode(world, "ring", name="station", center=(0.0, 0.0, 0.8), radius=2.0)
gf.create_electrode(world, "rod", name="rod", position=(2.0, 0.0, 0.8), length=3.0)
gf.create_conductor(world, name="bond", start="station", end="rod") # ideal bond
gf.create_source(world, attached_to="station", magnitude=1.0)
return world
engine = gf.create_engine(frequencies=[50.0, 1000.0])
results = [engine.solve(station(rho_1)) for rho_1 in (30.0, 100.0, 300.0, 1000.0)]
rhos = [gf.effective_resistivity(r.soil, preset="station") for r in results] # 35.8 ... 711.6 Ohm m
fit = gf.rho_f_standard_from_results(results, rhos, max_relative_tol=0.10) # input impedance
path = gf.save_bustype_json(
fit, "station.bustype.json", name="Station", system_type="Substation", voltage_level=20.0,
soil_summary="TwoLayerSoil(rho_1 sweep, rho_2=100, h_1=5)", rho_preset="station",
)
spec = gf.load_bustype_json(path)
print(gf.fit_quality_summary(spec)) # ... max_rel=7.48%, quantity=input, rho_preset=station
Z_formula = gf.evaluate_spec(spec, frequencies=[50.0], rho=rhos[3], rho_preset="station")[0]
Z_field = results[3].input_impedance()[0]
assert abs(Z_formula - Z_field) / abs(Z_field) <= fit.max_relative + 1e-9
assert spec.metadata["rho_definition"] == "effective_resistivity"
assert spec.rho_preset == "station"
assert abs(rhos[3] - 711.64) < 0.01 and fit.max_relative < 0.10
A bus whose resistivity comes from another preset is reported:
import warnings
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
gf.evaluate_spec(spec, [50.0], gf.effective_resistivity(results[3].soil), rho_preset="lv_network")
assert any(issubclass(w.category, gf.RhoPresetMismatchWarning) for w in caught)
The station is compact and lies in the upper layer, so it sees less of
the lower layer than an LV network: the standard form fits it to 7.5 %
over \(\rho_\text{eff}\) with the station weights, against 13.4 % with the
default weights of the LV networks. Over \(\rho_1\) it would fit to 3.9 %,
because at fixed \(\rho_2\) the constant \(k_0\) absorbs the lower layer, but
the bus the BusType is paired with carries \(\rho_\text{eff}\), here with
the station preset. Check max_relative, and see
Soil for the presets and the validity
of \(\rho_\text{eff}\). Without inductive conductors the impedance does not
depend on frequency, and the frequency coefficients \(k_2 \ldots k_5\) come
out at round-off level. Tutorial T05 shows the export of a
frequency-dependent system, including the vector-fit path with
rho_at_fit.
CSV and VTK¶
The CSV writers (save_potential_path_csv, save_electrode_table_csv,
save_cluster_impedances_csv) write UTF-8, comma-separated files at full
precision with a # header that records the package version, the
backend, the frequencies and the solve provenance;
read_csv_with_provenance(path) returns the table and the header. A
complex quantity is written as <symbol>_re, <symbol>_im,
abs_<symbol>. overwrite=False (default) refuses to replace a file.
export_geometry_vtk(world, path) writes the electrodes and conductors
as legacy ASCII POLYDATA (cell scalar role: 0 electrode,
1 conductor), export_field_vtk(result, path, extent=..., z=...) the
surface potential as STRUCTURED_POINTS with real and imaginary part.
Coordinates are double precision; \(z\) points down, so apply a
Transform with scale \((1, 1, -1)\) in ParaView for the usual view.
world = station(100.0)
result = results[1]
csv_path = gf.save_potential_path_csv(
result, "profile.csv", start=(2.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), distance=30.0, n=31
)
table, header = gf.read_csv_with_provenance(csv_path)
gf.export_geometry_vtk(world, "station.vtk")
gf.export_field_vtk(result, "surface_potential.vtk", extent=(-10.0, 10.0, -10.0, 10.0), n=(41, 41))
assert len(table) == 2 * 31 # 31 points at each of the two frequencies
assert {"frequency_Hz", "phi_re", "phi_im", "abs_phi"} <= set(table.columns)
assert header["backend"] == "image_2layer"
API: groundinsight bridge¶
groundinsight ¶
Export of reduced rho-f fits to groundinsight.
This module is the canonical bridge between the field-grade
reference computation in groundfield and the reduced equivalent
network model in groundinsight.
Two equally supported transports are provided:
- JSON file — neutral, language-agnostic schema versioned via
schema_version. Produce withto_bustype_dict()/save_bustype_json(); read back withload_bustype_json(). - Python API —
to_bustype()returns a livegroundinsight.BusTypePydantic instance via a lazy import.groundinsightis therefore an optional dependency ofgroundfield(extras group[groundinsight]). The JSON path does not requiregroundinsightat all.
Mathematical background
groundinsight.BusType.impedance_formula is parsed with two free
symbols, f (frequency in Hz) and rho
(Bus.specific_earth_resistance), and the imaginary unit j.
Both fit families exported here are projected onto that symbol set:
RhoFStandardFitis already in the canonical(rho, f)form
$$ Z(\rho, f) \;=\; k_1\rho \;+\; (k_2 + j k_3)\,f \;+\; (k_4 + j k_5)\,f\,\rho. $$
VectorFitResultis a rational function of the Laplace variable \(s = j\,2\pi f\). The export substitutes \(s\to j\,2\pi f\) symbolically so the resulting expression is infonly (independent ofrho); the soil resistivity the fit belongs to (rho_at_fit) is recorded in the samples and metadata blocks.
A groundinsight Bus carries one specific_earth_resistance,
the rho of the formula: \(\rho\) for homogeneous soil and, for
layered soil, the effective resistivity
with the weights \((w_0, \beta)\) of the electrode class: the AP1
calibration \(w_0 = 0.13\), \(\beta = 0.8\) by default, or a preset of
EFFECTIVE_RESISTIVITY_PRESETS such as
"station" or "lv_group_2_p10"
(effective_resistivity(); ADR-0008), the value
the AP2 network model gives a bus. A vector fit therefore passes
rho_at_fit=effective_resistivity(soil, preset=...), and a
standard-form fit over layered soils is fitted over the effective
resistivities of the solved soils, rho_f_standard_from_results(results,
[effective_resistivity(r.soil, preset=...) for r in results]); both kinds
of BusType then pair with a Bus whose resistivity uses the same
preset. Every document records this convention as
metadata["rho_definition"] = "effective_resistivity" (documents of
0.15.0 have no such entry) and the preset the caller names,
metadata["rho_preset"] (rho_preset=... of the exporters, None
when no preset is named; user decision Q39; documents of earlier versions
have no such entry and load with None). The live groundinsight
BusType of to_bustype(), save_bustype_to_db() and
bustype_from_spec() has no metadata; it carries the preset as the last
line of its description, groundfield rho_preset: <name>, which the
groundinsight database keeps, and bustype_rho_preset() reads it
back (audit W3B-06). Only that exact line, with a known preset name, is the
record: the rest of a given description stays as it is (audit W3R2B-06),
and a document is loaded only with a known preset name (or none), as the
exporters write it. The exporter cannot check the
number it is given against the preset. evaluate_spec() and
bustype_from_spec() take the preset of the bus they serve and emit
RhoPresetMismatchWarning when the document names another one (a
preset holds for its electrode class only: the AP1 station paired with
"lv_group_4_p40" misses the field solution by 39.9 % rms). The layers
themselves, and explicit weights \(w_0\), \(\beta\), go into
soil_summary.
The exporter does not care which impedance was fitted (input impedance, cluster impedance or the impedance of one electrode); it exports the function it is given.
Formula text
The formula keeps the structure of the fit (partial fractions for a
vector fit, the standard form term by term) and prints every
floating-point coefficient once, rounded to decimals significant
digits with Python's correctly rounded float formatting, so the text is
identical on every platform. The expression comes from the same
renderer as fit_to_sympy()
and fit_to_sympy_standard()
(one pole-pairing rule, no sympy.simplify). A coefficient therefore
carries a relative rounding error of at most \(\tfrac12\,10^{1-N}\) for
\(N\) = decimals; with the default \(N = 12\) the formula reproduces
fit.evaluate to about \(10^{-11}\) relative.
Formula safety
A formula read from a file is untrusted text. evaluate_spec(),
BusTypeSpec.from_dict() and load_bustype_json() parse it
with an allow-list parser that builds the SymPy expression from the
Python syntax tree and never evaluates the text: numbers, f,
rho, j / I, pi, E, + - * /, ** with a
literal exponent, and sqrt / exp / log, within size and
magnitude bounds. Every formula written by the exporter satisfies this
grammar, including those of groundfield 0.15.0 and earlier.
Passivity
A grounding impedance is the driving-point impedance of a passive one-port, so its real part is non-negative at every frequency,
A fit can violate this between its samples (a spurious resonance) or
beyond them. Before a BusType is built the exported formula (what
groundinsight will evaluate, coefficients rounded) goes through
check_passivity(), the one
passivity check of the package, over its default band from 0 Hz to
twice the highest fitted frequency: for a vector fit a dense grid
(linear and logarithmic points, the samples and the midpoints between
them, points around every pole) whose lowest minima are refined by a
bounded scalar minimisation; for the standard form, whose real part is
bilinear in \((\rho, f)\), the four corners of the fitted range of
rho times the band, which is exact. The report
(as_dict())
is stored in metadata["passivity"]; a violation emits
NonPassiveFitWarning, or raises NonPassiveFitError
with require_passive=True.
See also
docs/adr/0008-groundinsight-bridge.md — full design
rationale, JSON schema, and validation programme.
MAX_METADATA_DEPTH
module-attribute
¶
Deepest nesting of objects and lists in the metadata of a BusType document.
The exporters write at most four levels. A deeper document is refused on
load (ValueError); the JSON decoder reads thousands of levels, but
every consumer that walks the metadata recursively would fail with
RecursionError.
SCHEMA_NAME
module-attribute
¶
Value of the schema key of a BusType JSON document.
SCHEMA_VERSION
module-attribute
¶
Value of the schema_version key; the only version written and read.
BusTypeSpec
dataclass
¶
BusTypeSpec(name: str, description: Optional[str], system_type: str, voltage_level: float, impedance_formula: str, samples: dict[str, list[float]], metadata: dict[str, Any])
Neutral, in-memory representation of an exported BusType.
The spec is what to_bustype_dict() returns under the hood and
what load_bustype_json() reads back. It carries everything
necessary to either build a groundinsight.BusType (via
to_bustype()) or to write the on-disk JSON document.
Attributes:
| Name | Type | Description |
|---|---|---|
name, description, system_type, voltage_level |
The four scalar fields that the |
|
impedance_formula |
str
|
The fitted |
samples |
dict[str, list[float]]
|
Dict with the parallel tabular representation. Keys
|
metadata |
dict[str, Any]
|
Free-form metadata dict; populated by the exporters with
the fit method, fit quality ( |
rho_preset
property
¶
Effective-resistivity preset of the rho of the formula.
metadata["rho_preset"] (user decision Q39): the preset name the
exporter was given, None when none was named and for documents
of earlier versions, which have no such entry.
from_dict
classmethod
¶
Build a BusTypeSpec from a JSON-loaded dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict
|
Schema-v1 document as produced by |
required |
Returns:
| Type | Description |
|---|---|
BusTypeSpec
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the payload is not a schema-v1 BusType document: not a
|
EvaluateSpecError
|
If |
Source code in src/groundfield/io/groundinsight.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
to_dict ¶
Return a JSON-ready dict matching schema v1.
The result is strict JSON: every number that is not finite (a
sample, a fit-quality figure of a hand-built fit, a description
that is not a string, ...) is written as None (JSON null).
Raises:
| Type | Description |
|---|---|
ValueError
|
If the metadata nest deeper than |
Source code in src/groundfield/io/groundinsight.py
EvaluateSpecError ¶
Bases: ValueError
Raised when a BusTypeSpec or its formula is rejected.
Raised by evaluate_spec() and, for a formula outside the
allowed grammar, already by BusTypeSpec.from_dict() and
load_bustype_json(). Subclass of ValueError so legacy
except ValueError blocks keep working unchanged; downstream
consumers (notably the groundinsight consumer of the bridge
format) can catch the typed exception instead of matching against
str(exc) substrings.
NonPassiveFitError ¶
Bases: ValueError
Raised instead of NonPassiveFitWarning with require_passive=True.
NonPassiveFitWarning ¶
Bases: UserWarning
The exported impedance formula has Re Z < 0 somewhere.
A passive grounding impedance satisfies \(\operatorname{Re} Z \ge 0\)
at every frequency. The warning names the frequency (and rho)
of the most negative real part; metadata["passivity"] of the
exported document carries the same numbers. Refit, or export with
require_passive=True to turn the warning into
NonPassiveFitError.
RhoPresetMismatchWarning ¶
Bases: UserWarning
The BusType was fitted over another effective-resistivity preset.
Emitted by evaluate_spec() and bustype_from_spec() when the
caller names the preset of its bus (rho_preset=...) and the document
records a different one in metadata["rho_preset"] (user decision
Q39): the rho of the bus then means another resistivity than the
rho of the formula.
bustype_from_spec ¶
Build a live groundinsight.BusType from a loaded document.
The groundinsight model of a spec built by the exporters or read
with load_bustype_json() (its four scalar fields and the
formula; the metadata is not carried over, as with to_bustype(),
except the preset the document records: the description ends with
groundfield rho_preset: <name>, audit W3B-06).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
BusTypeSpec
|
The document. |
required |
rho_preset
|
str
|
The preset of |
None
|
Returns:
| Type | Description |
|---|---|
BusType
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
ImportError
|
If |
Warns:
| Type | Description |
|---|---|
RhoPresetMismatchWarning
|
If |
Source code in src/groundfield/io/groundinsight.py
bustype_rho_preset ¶
Effective-resistivity preset recorded on a BusType (audit W3B-06).
A live groundinsight.BusType built by to_bustype(),
save_bustype_to_db() or bustype_from_spec() from a fit or a
document with a preset carries it as the last line of its description,
groundfield rho_preset: <name>; the groundinsight database keeps
the description, so the preset of a BusType loaded from it
(gi.load_bustypes_from_db()) is read the same way. Compare it with
the preset of the bus's specific_earth_resistance
(effective_resistivity()); for a document use
BusTypeSpec.rho_preset or the check of evaluate_spec().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus_type
|
groundinsight.BusType, BusTypeSpec or any object with a ``description``
|
The BusType. For a |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
The preset name, or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in src/groundfield/io/groundinsight.py
evaluate_spec ¶
evaluate_spec(spec: BusTypeSpec, frequencies: Sequence[float], rho: float, *, rho_preset: Optional[str] = None) -> np.ndarray
Evaluate a BusTypeSpec at arbitrary frequencies.
Parses the stored impedance_formula with the allow-list parser
(see the module docstring; the text is never evaluated as code) and
evaluates the resulting expression with NumPy at the provided
rho and f values, node by node through
formula_function() (complex
arithmetic, principal branch for roots and logarithms; SymPy's code
generation is not used). Useful for cheap sanity checks that do not
require groundinsight to be installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
BusTypeSpec
|
Loaded spec (e.g. from |
required |
frequencies
|
sequence of float
|
Frequencies in Hz. |
required |
rho
|
float
|
Soil resistivity in \(\Omega\,\mathrm{m}\). Ignored if the
formula does not depend on |
required |
rho_preset
|
str
|
The preset of |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Complex-valued \(Z\) in \(\Omega\) at every requested frequency. |
Raises:
| Type | Description |
|---|---|
EvaluateSpecError
|
Subclass of |
Warns:
| Type | Description |
|---|---|
RhoPresetMismatchWarning
|
If |
Source code in src/groundfield/io/groundinsight.py
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 | |
fit_quality_summary ¶
One-line human-readable summary of fit quality / kind.
Names the fit method, the rms error, the relative rms and worst
pointwise relative error when the document records them, and the
impedance the fit represents (quantity: input,
cluster or electrode) when known.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
BusTypeSpec
|
Exported or loaded BusType document. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in src/groundfield/io/groundinsight.py
load_bustype_json ¶
Load a BusType JSON document into a BusTypeSpec.
Validates the schema name and version and parses the formula with
the allow-list parser (it is never evaluated as code).
Forward-compatibility for future schema versions is the explicit
responsibility of this function: when schema_version differs
from SCHEMA_VERSION, dispatch to the appropriate loader.
Today only v1 exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
JSON file written by |
required |
Returns:
| Type | Description |
|---|---|
BusTypeSpec
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file is not valid JSON (also: nested too deeply to be
read) or not a schema-v1 BusType document, see
|
EvaluateSpecError
|
If |
Source code in src/groundfield/io/groundinsight.py
save_bustype_json ¶
save_bustype_json(fit: FitLike, path: Union[str, Path], *, name: str, system_type: str, voltage_level: float, description: Optional[str] = None, decimals: int = 12, rho_at_fit: Optional[float] = None, electrode_name: Optional[str] = None, soil_summary: Optional[str] = None, indent: int = 2, require_passive: bool = False, rho_preset: Optional[str] = None) -> Path
Write the schema-v1 JSON file to disk.
Performs the conversion and checks of to_bustype_dict().
Nothing is written when the export is refused (missing
rho_at_fit for a vector fit, require_passive=True with a
failed passivity check).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit
|
RhoFStandardFit or VectorFitResult
|
The fitted rho-f model. |
required |
path
|
str or Path
|
Target file; parent directories are created. |
required |
name
|
str
|
The |
required |
system_type
|
str
|
The |
required |
voltage_level
|
str
|
The |
required |
description
|
str
|
The |
required |
decimals
|
int
|
Significant digits per coefficient (default 12), see
|
12
|
rho_at_fit
|
float
|
Soil resistivity in \(\Omega\,\mathrm{m}\) of a
|
None
|
electrode_name
|
str
|
Free-form metadata entries. |
None
|
soil_summary
|
str
|
Free-form metadata entries. |
None
|
indent
|
int
|
JSON indentation. Default 2. |
2
|
require_passive
|
bool
|
Raise |
False
|
rho_preset
|
str
|
The preset of |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The path the file was actually written to, for chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NonPassiveFitError
|
With |
Warns:
| Type | Description |
|---|---|
NonPassiveFitWarning
|
If the passivity check fails and |
Source code in src/groundfield/io/groundinsight.py
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 | |
save_bustype_to_db ¶
save_bustype_to_db(fit: FitLike, *, name: str, system_type: str, voltage_level: float, description: Optional[str] = None, decimals: int = 12, rho_at_fit: Optional[float] = None, electrode_name: Optional[str] = None, soil_summary: Optional[str] = None, overwrite: bool = False, require_passive: bool = False, rho_preset: Optional[str] = None) -> None
Build a BusType and save it to the groundinsight database.
Writes into the SQLite store opened by gi.start_dbsession(path);
requires groundinsight to be installed and a session to be
active. Performs the same conversion and checks as
to_bustype_dict().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit
|
RhoFStandardFit or VectorFitResult
|
The fitted rho-f model. |
required |
name
|
str
|
The |
required |
system_type
|
str
|
The |
required |
voltage_level
|
str
|
The |
required |
description
|
str
|
The |
required |
decimals
|
int
|
Significant digits per coefficient (default 12). |
12
|
rho_at_fit
|
float
|
Soil resistivity in \(\Omega\,\mathrm{m}\) of a
|
None
|
electrode_name
|
str
|
Free-form metadata entries (not stored in the database). |
None
|
soil_summary
|
str
|
Free-form metadata entries (not stored in the database). |
None
|
overwrite
|
bool
|
Replace an existing |
False
|
require_passive
|
bool
|
Raise |
False
|
rho_preset
|
str
|
The preset of |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NonPassiveFitError
|
With |
ImportError
|
If |
RuntimeError
|
From |
Warns:
| Type | Description |
|---|---|
NonPassiveFitWarning
|
If the passivity check fails and |
Source code in src/groundfield/io/groundinsight.py
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 | |
to_bustype ¶
to_bustype(fit: FitLike, *, name: str, system_type: str, voltage_level: float, description: Optional[str] = None, decimals: int = 12, rho_at_fit: Optional[float] = None, electrode_name: Optional[str] = None, soil_summary: Optional[str] = None, require_passive: bool = False, rho_preset: Optional[str] = None)
Build a live groundinsight.BusType from a fit.
Performs the same conversion and checks as to_bustype_dict(),
but returns a fully-validated BusType Pydantic instance instead
of a JSON-ready dict. The arguments are validated before
groundinsight is imported lazily; a missing install raises an
ImportError with a clear pointer to the optional install.
The metadata block (including the passivity check) is not
carried over into the returned BusType (the BusType schema
has no metadata field) — use to_bustype_dict() or
save_bustype_json() if metadata must be persisted. The one
exception is the preset: with rho_preset the description of the
BusType ends with the line groundfield rho_preset: <name>
(bustype_rho_preset() reads it back; audit W3B-06).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit
|
RhoFStandardFit or VectorFitResult
|
The fitted rho-f model. |
required |
name
|
str
|
The |
required |
system_type
|
str
|
The |
required |
voltage_level
|
str
|
The |
required |
description
|
str
|
The |
required |
decimals
|
int
|
Significant digits per coefficient (default 12). |
12
|
rho_at_fit
|
float
|
Soil resistivity in \(\Omega\,\mathrm{m}\) of a
|
None
|
electrode_name
|
str
|
Free-form metadata entries (not part of the live |
None
|
soil_summary
|
str
|
Free-form metadata entries (not part of the live |
None
|
require_passive
|
bool
|
Raise |
False
|
rho_preset
|
str
|
The preset of |
None
|
Returns:
| Type | Description |
|---|---|
BusType
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NonPassiveFitError
|
With |
ImportError
|
If |
Warns:
| Type | Description |
|---|---|
NonPassiveFitWarning
|
If the passivity check fails and |
Source code in src/groundfield/io/groundinsight.py
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 | |
to_bustype_dict ¶
to_bustype_dict(fit: FitLike, *, name: str, system_type: str, voltage_level: float, description: Optional[str] = None, decimals: int = 12, rho_at_fit: Optional[float] = None, electrode_name: Optional[str] = None, soil_summary: Optional[str] = None, require_passive: bool = False, rho_preset: Optional[str] = None) -> dict[str, Any]
Convert a fit into the JSON-ready schema-v1 dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit
|
RhoFStandardFit or VectorFitResult
|
The fitted rho-f model. |
required |
name
|
str
|
|
required |
system_type
|
str
|
|
required |
voltage_level
|
float
|
|
required |
description
|
str
|
|
None
|
decimals
|
int
|
Significant digits of every floating-point coefficient of the
formula (1 to 17; larger values are treated as 17). Default 12:
the formula then reproduces |
12
|
rho_at_fit
|
float
|
Soil resistivity in \(\Omega\,\mathrm{m}\) at which a
|
None
|
electrode_name
|
str
|
Free-form metadata entries; recommended for traceability. |
None
|
soil_summary
|
str
|
Free-form metadata entries; recommended for traceability. |
None
|
require_passive
|
bool
|
If True, raise |
False
|
rho_preset
|
str
|
The preset of |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
JSON-ready |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NonPassiveFitError
|
With |
TypeError
|
If |
Warns:
| Type | Description |
|---|---|
NonPassiveFitWarning
|
If the passivity check fails and |
Source code in src/groundfield/io/groundinsight.py
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 | |
API: CSV¶
csv ¶
CSV exports for groundfield results.
This module provides three convenience writers that turn a
FieldResult (and optionally its companion World)
into machine-readable, tool-agnostic CSV files. They wrap the
existing postprocess helpers — no new science here, just a
clean disk format for sharing typical results across notebooks,
spreadsheets, and downstream pipelines.
Functions:
| Name | Description |
|---|---|
|
Sample |
|
Wrap |
|
Wrap |
Column-name convention
All complex-valued quantities follow the same <symbol>_re,
<symbol>_im, abs_<symbol> triple where symbol is the
physical symbol of the quantity:
- potential —
phi_re/phi_im/abs_phi; - current —
I_re/I_im/abs_I; - impedance —
Z_re/Z_im/abs_Z.
The three writers therefore deliberately use different magnitude
columns (abs_phi for the potential path, abs_I for the
electrode table, abs_Z for the cluster table). They are not
intended to be concat/merge-ed on the magnitude column
without an explicit rename; the column constants below
(POTENTIAL_PATH_COLUMNS, etc.) lock the schema for
downstream consumers.
The identifier columns follow the postprocess tables the writers
wrap: an electrode row is keyed by name, a cluster row by
cluster_root (the canonical member of the galvanic cluster).
There is no electrode or cluster column.
All writers use UTF-8, comma-separated, with a header row; floating-point values are written at full precision so the files round-trip without loss of accuracy.
Frequency and provenance (review pass 10, 10.73)
Every table records its frequency in Hz: the electrode and cluster
tables in a frequency_hz column (lower-case unit suffix, the
convention of the spec layer and of FieldResult.to_dataframe(),
10.69), the potential path in its frequency_Hz column of v0.15.0.
Every file starts with # comment lines that record where it came
from::
# groundfield csv: electrode_table
# groundfield_version: 2026.11.0
# written_utc: 2026-11-07T19:30:00Z
# backend: image
# frequency_hz: 50
# frequency_index: 0
followed by the provenance block of the solve (solve.* keys) when
the result carries one. Read such a file with
read_csv_with_provenance(), which skips exactly the leading
comment lines and returns the metadata as a dict, or with
pandas.read_csv(path, comment="#") when no value contains #.
Pass provenance=False for a plain CSV. The writers refuse to
replace an existing file unless overwrite=True.
CLUSTER_IMPEDANCE_REQUIRED_COLUMNS
module-attribute
¶
CLUSTER_IMPEDANCE_REQUIRED_COLUMNS: tuple[str, ...] = ('cluster_root', 'Z_re', 'Z_im', 'abs_Z', 'frequency_hz')
Mandatory columns of save_cluster_impedances_csv().
A cluster is identified by cluster_root, the canonical (alphabetically
first) member of the galvanic cluster, as emitted by
groundfield.postprocess.cluster_current_balance().
ELECTRODE_TABLE_REQUIRED_COLUMNS
module-attribute
¶
ELECTRODE_TABLE_REQUIRED_COLUMNS: tuple[str, ...] = ('name', 'cluster_root', 'I_re', 'I_im', 'abs_I', 'frequency_hz')
Mandatory columns of save_electrode_table_csv().
Additional columns such as kind / depth_m may appear when a
world is supplied. The electrode is identified by name
and its galvanic cluster by cluster_root — the column names
emitted by groundfield.postprocess.electrode_current_table().
POTENTIAL_PATH_COLUMNS
module-attribute
¶
POTENTIAL_PATH_COLUMNS: tuple[str, ...] = ('s', 'x', 'y', 'z', 'frequency_Hz', 'phi_re', 'phi_im', 'abs_phi')
Columns of save_potential_path_csv(), in the order written.
The writer always emits exactly these columns in exactly this order. Locking this contract here makes regressions on the column name convention test-detectable.
read_csv_with_provenance ¶
Read a CSV written by this module, with its provenance header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File written by one of the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
The table. Only the leading |
provenance |
dict[str, str]
|
|
Source code in src/groundfield/io/csv.py
save_cluster_impedances_csv ¶
save_cluster_impedances_csv(result: 'FieldResult', path: str | Path, *, frequency_index: int = 0, overwrite: bool = False, provenance: bool = True) -> Path
Wrap cluster_current_balance() and write to CSV.
Note that the members column of
cluster_current_balance() carries Python lists; CSV is
a flat format, so the lists are joined into ';'-separated
strings before writing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
'FieldResult'
|
Solver output. |
required |
path
|
str | Path
|
Destination CSV path. |
required |
frequency_index
|
int
|
Index into |
0
|
overwrite
|
bool
|
Replace an existing file (default |
False
|
provenance
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If |
Notes
The Z columns are cluster impedances (a cluster's potential over
its own soil leakage), not the input impedance a source sees.
Source code in src/groundfield/io/csv.py
save_electrode_table_csv ¶
save_electrode_table_csv(result: 'FieldResult', path: str | Path, *, world: 'World | None' = None, frequency_index: int = 0, overwrite: bool = False, provenance: bool = True) -> Path
Wrap electrode_current_table() and write to CSV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
'FieldResult'
|
Solver output. |
required |
path
|
str | Path
|
Destination CSV path. |
required |
world
|
'World | None'
|
Optional companion world; when given, the table includes
the |
None
|
frequency_index
|
int
|
Index into |
0
|
overwrite
|
bool
|
Replace an existing file (default |
False
|
provenance
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If |
Source code in src/groundfield/io/csv.py
save_potential_path_csv ¶
save_potential_path_csv(result: 'FieldResult', path: str | Path, *, start: tuple[float, float, float], direction: tuple[float, float, float] = (1.0, 0.0, 0.0), distance: float = 30.0, n: int = 200, frequency_indices: Sequence[int] | None = None, overwrite: bool = False, provenance: bool = True) -> Path
Sample the potential along a line and write to CSV.
Builds an evenly spaced set of n field points starting at
start and walking distance metres along the unit
vector of direction, evaluates
FieldResult.potential() at every selected frequency
index, and writes the result to path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
'FieldResult'
|
Solver output. Must carry |
required |
path
|
str | Path
|
Destination CSV path. Parent directories are created automatically. |
required |
start
|
tuple[float, float, float]
|
Path start point |
required |
direction
|
tuple[float, float, float]
|
Direction vector. Will be normalised to unit length.
Default |
(1.0, 0.0, 0.0)
|
distance
|
float
|
Path length in metres. Default 30. |
30.0
|
n
|
int
|
Number of sample points along the path. Default 200. |
200
|
frequency_indices
|
Sequence[int] | None
|
Iterable of integer indices into
|
None
|
overwrite
|
bool
|
Replace an existing file (default |
False
|
provenance
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
The path the file was written to. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileExistsError
|
If |
Source code in src/groundfield/io/csv.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
API: VTK¶
vtk ¶
Legacy ASCII VTK exports for ParaView / VisIt / Mayavi.
This module writes two flavours of the legacy ASCII VTK file
format (.vtk), keeping the dependency surface zero — no
pyvista or vtk Python bindings are required:
export_geometry_vtk()— POLYDATA with the electrode wires (rod, ring, strip, mesh, grid_mesh) and the conductor line segments. Useful for "drag the world into ParaView and rotate it" inspections of large typical networks.export_field_vtk()— STRUCTURED_POINTS with the soil surface (or any horizontal slice) sampled on a regular(N_x, N_y)grid. The potential is exported as a single scalar field; ParaView's contour / colour-map filters take it from there.
Why legacy ASCII VTK?
The legacy format is the smallest common denominator: every VTK
reader since the 90s opens it, the on-disk layout is plain text
(diff-able, version-controllable), and the writer is ~30 lines
of pure-Python without any external library. For large research
runs prefer pyvista once you need binary I/O and unstructured
grids; for production-grade networks at notebook scale this format is
fast enough.
Format details (review pass 10, 10.10)
- Coordinates and scalars are declared
double:floatmakes readers store 32-bit values, which quantises UTM-scale coordinates (northings of 5.2e6–6.2e6 m) by up to 0.25 m. - The free-text header line is sanitised: control and line-separator
characters in
world.namebecome spaces, and the line is limited to 256 bytes as the legacy format requires. A newline in the name used to corrupt the file. groundfieldmeasures \(z\) downwards (depth below the soil surface). ParaView shows the world upside down; apply a Transform filter with scale(1, 1, -1)for a conventional view.
References
- Schroeder, W., Martin, K., Lorensen, B. (2006). The Visualization Toolkit, 4th ed., Kitware. Section 19.5 (Legacy file format).
- VTK File Formats reference: https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf
export_field_vtk ¶
export_field_vtk(result: 'FieldResult', path: str | Path, *, extent: tuple[float, float, float, float], z: float = 0.0, n: tuple[int, int] = (120, 120), frequency_index: int = 0) -> Path
Sample the potential on a horizontal grid and write a VTK file.
Evaluates FieldResult.potential() on a regular
\(N_x \times N_y\) grid in the plane \(z = z_0\) and
writes a DATASET STRUCTURED_POINTS (a.k.a. uniform grid)
with a single scalar field potential_re. The imaginary
part is included as a second scalar potential_im for
above-DC typical studies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
'FieldResult'
|
Solver output. Must carry |
required |
path
|
str | Path
|
Destination |
required |
extent
|
tuple[float, float, float, float]
|
Plot extent |
required |
z
|
float
|
Slice depth in metres (default |
0.0
|
n
|
tuple[int, int]
|
Grid resolution |
(120, 120)
|
frequency_index
|
int
|
Index into |
0
|
Returns:
| Type | Description |
|---|---|
Path
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On bad extent or non-positive grid sizes. |
Source code in src/groundfield/io/vtk.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | |
export_geometry_vtk ¶
Export the world geometry as a legacy ASCII VTK PolyData file.
Writes electrodes (rods, rings, strips, mesh / grid_mesh
perimeters) and conductors as 3-D polylines. The on-disk
layout uses VTK's DATASET POLYDATA with a LINES block;
cell data carries an integer role field (0 = electrode,
1 = conductor) so colour-by-role works directly in ParaView.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
'World'
|
World to export. May be empty (the writer still produces
a syntactically valid header-only file). Its |
required |
path
|
str | Path
|
Destination |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path the file was written to. |
Notes
POINTS are written as double; \(z\) is the depth below the
surface (positive downwards), see the module docstring.
Source code in src/groundfield/io/vtk.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |