Skip to content

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

\[ \text{field model} \;\longrightarrow\; Z(\rho, f) \;\longrightarrow\; \texttt{BusType.impedance\_formula} \;\longrightarrow\; \text{network model}. \]

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 on f only. The soil it belongs to must be given as rho_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,

\[ \rho_\text{eff} = \rho_1^{\,1-w}\,\rho_2^{\,w}, \qquad w = w_0\,(h_1/10\ \mathrm{m})^{-\beta}, \]

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 with to_bustype_dict() / save_bustype_json(); read back with load_bustype_json().
  • Python API — to_bustype() returns a live groundinsight.BusType Pydantic instance via a lazy import. groundinsight is therefore an optional dependency of groundfield (extras group [groundinsight]). The JSON path does not require groundinsight at 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:

$$ Z(\rho, f) \;=\; k_1\rho \;+\; (k_2 + j k_3)\,f \;+\; (k_4 + j k_5)\,f\,\rho. $$

  • VectorFitResult is 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 in f only (independent of rho); 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

\[ \rho_\text{eff} = \rho_1^{\,1-w}\,\rho_2^{\,w}, \qquad w = w_0\,(h_1 / 10\ \mathrm{m})^{-\beta}, \]

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,

\[ \operatorname{Re} Z(j\,2\pi f) \;\ge\; 0 \qquad (f \ge 0). \]

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

MAX_METADATA_DEPTH = 32

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

SCHEMA_NAME = 'groundfield.bustype'

Value of the schema key of a BusType JSON document.

SCHEMA_VERSION module-attribute

SCHEMA_VERSION = 1

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 groundinsight.BusType Pydantic model carries.

impedance_formula str

The fitted Z(rho, f) expression as text. Free symbols: f (Hz) and rho (\(\Omega\,\mathrm{m}\)); imaginary unit j. Only the grammar described in the module docstring is accepted when the spec is loaded or evaluated.

samples dict[str, list[float]]

Dict with the parallel tabular representation. Keys "frequency_Hz", "rho_Ohm_m", "Z_real_Ohm", "Z_imag_Ohm" each map to a list of floats of equal length (null in the JSON document for a value that is not finite). Provided so a future tabular ingest path on the groundinsight side can be served immediately.

metadata dict[str, Any]

Free-form metadata dict; populated by the exporters with the fit method, fit quality (rms_error_Ohm, rms_relative, for the standard form max_relative; null when unknown), the impedance the fit represents ("quantity": "input", "cluster", "electrode" or null for raw samples), how rho is defined ("rho_definition": "effective_resistivity", see the module docstring), fit-method-specific details (poles/residues for vector fits, \(k_0\dots k_5\) and the "weights" for the standard form), the passivity check ("passivity"), the source groundfield version and a UTC timestamp.

rho_preset property
rho_preset: Optional[str]

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
from_dict(payload: dict[str, Any]) -> 'BusTypeSpec'

Build a BusTypeSpec from a JSON-loaded dict.

Parameters:

Name Type Description Default
payload dict

Schema-v1 document as produced by to_bustype_dict().

required

Returns:

Type Description
BusTypeSpec

Raises:

Type Description
ValueError

If the payload is not a schema-v1 BusType document: not a dict, a wrong schema name or version, a missing name, system_type or voltage_level, a name or system_type that is an object or a list, a description that is neither a string nor null, a voltage_level that is not a finite number, samples / metadata that are not objects (sample lists hold numbers or None), or metadata nested deeper than MAX_METADATA_DEPTH.

EvaluateSpecError

If impedance_formula is missing, not a string or a number, or outside the allowed formula grammar. The formula is parsed, never evaluated as code; the message names the offending element.

Source code in src/groundfield/io/groundinsight.py
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> "BusTypeSpec":
    """Build a :class:`BusTypeSpec` from a JSON-loaded ``dict``.

    Parameters
    ----------
    payload : dict
        Schema-v1 document as produced by :func:`to_bustype_dict`.

    Returns
    -------
    BusTypeSpec

    Raises
    ------
    ValueError
        If the payload is not a schema-v1 BusType document: not a
        ``dict``, a wrong schema name or version, a missing ``name``,
        ``system_type`` or ``voltage_level``, a ``name`` or
        ``system_type`` that is an object or a list, a ``description``
        that is neither a string nor ``null``, a ``voltage_level`` that
        is not a finite number, ``samples`` / ``metadata`` that are not
        objects (sample lists hold numbers or ``None``), or metadata
        nested deeper than :data:`MAX_METADATA_DEPTH`.
    EvaluateSpecError
        If ``impedance_formula`` is missing, not a string or a number,
        or outside the allowed formula grammar. The formula is parsed,
        never evaluated as code; the message names the offending
        element.
    """
    if not isinstance(payload, dict):
        raise ValueError(
            f"a BusType document is a JSON object, got {type(payload).__name__}"
        )
    if payload.get("schema") != SCHEMA_NAME:
        raise ValueError(
            f"unexpected schema name: got {payload.get('schema')!r}, "
            f"expected {SCHEMA_NAME!r}"
        )
    try:
        version = int(payload.get("schema_version", 0))
    except (TypeError, ValueError, OverflowError):
        raise ValueError(
            "unsupported schema_version "
            f"{str(payload.get('schema_version'))[:40]!r}; this groundfield "
            f"build only reads v{SCHEMA_VERSION}"
        ) from None
    if version != SCHEMA_VERSION:
        raise ValueError(
            f"unsupported schema_version {version}; this groundfield "
            f"build only reads v{SCHEMA_VERSION}"
        )
    for key in ("name", "system_type", "voltage_level"):
        if key not in payload:
            raise ValueError(f"BusType document has no {key!r}")
    for key in ("name", "system_type"):
        if isinstance(payload[key], (dict, list)):
            raise ValueError(
                f"BusType document: {key!r} must be a string, got a JSON "
                f"{'object' if isinstance(payload[key], dict) else 'array'}"
            )
    name = str(payload["name"])
    description = payload.get("description")
    if description is not None and not isinstance(description, str):
        raise ValueError(
            f"BusType document {name!r}: description must be a string or "
            f"null, got {type(description).__name__}"
        )
    formula = payload.get("impedance_formula")
    if formula is None:
        raise EvaluateSpecError(
            f"BusType document {name!r} has no 'impedance_formula'."
        )
    if isinstance(formula, (dict, list)):
        raise EvaluateSpecError(
            f"BusType document {name!r}: impedance_formula must be a string."
        )
    formula = formula if isinstance(formula, str) else str(formula)
    _parse_formula(formula, context=f"BusType document {name!r}")
    samples = payload.get("samples") or {}
    try:
        voltage_level = float(payload["voltage_level"])
    except (TypeError, ValueError, OverflowError):
        voltage_level = math.nan
    if not math.isfinite(voltage_level):
        raise ValueError(
            f"BusType document {name!r}: voltage_level must be a finite "
            f"number, got {str(payload['voltage_level'])[:40]!r}"
        )
    metadata = payload.get("metadata") or {}
    if not isinstance(samples, dict) or not isinstance(metadata, dict):
        raise ValueError(
            f"BusType document {name!r}: samples and metadata must be JSON objects"
        )
    _strict_json(metadata, context=f"BusType document {name!r}: metadata")
    # a preset name as the exporters write it (audit W3R2B-06: blank
    # names were refused, but padding, line breaks and unknown names
    # loaded, and the live BusType could not carry them)
    _check_rho_preset(
        metadata.get("rho_preset"),
        f"BusType document {name!r}: metadata['rho_preset']",
    )
    sample_lists: dict[str, list[Any]] = {}
    for key in ("frequency_Hz", "rho_Ohm_m", "Z_real_Ohm", "Z_imag_Ohm"):
        values = samples.get(key, [])
        if isinstance(values, np.ndarray):
            values = values.tolist()
        if not isinstance(values, (list, tuple)) or not all(
            value is None
            or (isinstance(value, numbers.Real) and not isinstance(value, bool))
            for value in values
        ):
            raise ValueError(
                f"BusType document {name!r}: samples[{key!r}] must be a list "
                "of numbers (null for a value that is not finite)"
            )
        sample_lists[key] = list(values)
    return cls(
        name=name,
        description=description,
        system_type=str(payload["system_type"]),
        voltage_level=voltage_level,
        impedance_formula=formula,
        samples=sample_lists,
        metadata=dict(metadata),
    )
to_dict
to_dict() -> dict[str, Any]

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 MAX_METADATA_DEPTH.

Source code in src/groundfield/io/groundinsight.py
def to_dict(self) -> dict[str, Any]:
    """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
    ------
    ValueError
        If the metadata nest deeper than :data:`MAX_METADATA_DEPTH`.
    """
    return {
        "schema": SCHEMA_NAME,
        "schema_version": SCHEMA_VERSION,
        "name": self.name,
        "description": _strict_json(self.description),
        "system_type": self.system_type,
        "voltage_level": float(self.voltage_level),
        "impedance_formula": self.impedance_formula,
        "samples": {
            key: [_finite_or_none(x) for x in self.samples.get(key, [])]
            for key in ("frequency_Hz", "rho_Ohm_m", "Z_real_Ohm", "Z_imag_Ohm")
        },
        "metadata": _strict_json(dict(self.metadata)),
    }

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

bustype_from_spec(spec: BusTypeSpec, *, rho_preset: Optional[str] = None)

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 effective_resistivity() that the bus of this BusType uses for its specific_earth_resistance. A different preset recorded in the document emits RhoPresetMismatchWarning (user decision Q39); None (default) checks nothing.

None

Returns:

Type Description
BusType

Raises:

Type Description
TypeError

If spec is not a BusTypeSpec.

ValueError

If rho_preset is not a preset name.

ImportError

If groundinsight is not installed.

Warns:

Type Description
RhoPresetMismatchWarning

If rho_preset differs from the preset the document records.

Source code in src/groundfield/io/groundinsight.py
def bustype_from_spec(spec: BusTypeSpec, *, rho_preset: Optional[str] = None):
    """Build a live :class:`groundinsight.BusType` from a loaded document.

    The ``groundinsight`` model of a spec built by the exporters or read
    with :func:`load_bustype_json` (its four scalar fields and the
    formula; the metadata is not carried over, as with :func:`to_bustype`,
    except the preset the document records: the description ends with
    ``groundfield rho_preset: <name>``, audit W3B-06).

    Parameters
    ----------
    spec : BusTypeSpec
        The document.
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` that
        the bus of this BusType uses for its ``specific_earth_resistance``.
        A different preset recorded in the document emits
        :class:`RhoPresetMismatchWarning` (user decision Q39); ``None``
        (default) checks nothing.

    Returns
    -------
    groundinsight.models.core_models.BusType

    Raises
    ------
    TypeError
        If ``spec`` is not a :class:`BusTypeSpec`.
    ValueError
        If ``rho_preset`` is not a preset name.
    ImportError
        If ``groundinsight`` is not installed.

    Warns
    -----
    RhoPresetMismatchWarning
        If ``rho_preset`` differs from the preset the document records.
    """
    if not isinstance(spec, BusTypeSpec):
        raise TypeError(
            f"bustype_from_spec: expected a BusTypeSpec, got {type(spec).__name__}"
        )
    _warn_on_preset_mismatch(spec, rho_preset, "bustype_from_spec")
    return _to_live_bustype(spec)

bustype_rho_preset

bustype_rho_preset(bus_type: Any) -> Optional[str]

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 BusTypeSpec the preset its metadata records (BusTypeSpec.rho_preset).

required

Returns:

Type Description
str or None

The preset name, or None when the last line of the description is not exactly groundfield rho_preset: <name> with a name of EFFECTIVE_RESISTIVITY_PRESETS (no preset was named, the BusType was not built by groundfield 2026.11 or later, or the line is the user's own text; audit W3R2B-06).

Raises:

Type Description
TypeError

If bus_type has no description or a description that is neither a string nor None.

Source code in src/groundfield/io/groundinsight.py
def bustype_rho_preset(bus_type: Any) -> Optional[str]:
    """Effective-resistivity preset recorded on a BusType (audit W3B-06).

    A live ``groundinsight.BusType`` built by :func:`to_bustype`,
    :func:`save_bustype_to_db` or :func:`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``
    (:func:`~groundfield.soil.effective_resistivity`); for a document use
    :attr:`BusTypeSpec.rho_preset` or the check of :func:`evaluate_spec`.

    Parameters
    ----------
    bus_type : groundinsight.BusType, BusTypeSpec or any object with a ``description``
        The BusType. For a :class:`BusTypeSpec` the preset its metadata
        records (:attr:`BusTypeSpec.rho_preset`).

    Returns
    -------
    str or None
        The preset name, or ``None`` when the last line of the description
        is not exactly ``groundfield rho_preset: <name>`` with a name of
        :data:`~groundfield.soil.EFFECTIVE_RESISTIVITY_PRESETS` (no preset
        was named, the BusType was not built by groundfield 2026.11 or
        later, or the line is the user's own text; audit W3R2B-06).

    Raises
    ------
    TypeError
        If ``bus_type`` has no ``description`` or a description that is
        neither a string nor ``None``.
    """
    if isinstance(bus_type, BusTypeSpec):
        return bus_type.rho_preset
    try:
        text = bus_type.description
    except AttributeError:
        raise TypeError(
            "bustype_rho_preset: expected a groundinsight BusType (an object "
            f"with a description), got {type(bus_type).__name__}"
        ) from None
    if text is None:
        return None
    if not isinstance(text, str):
        raise TypeError(
            "bustype_rho_preset: the description must be a string or None, got "
            f"{type(text).__name__}"
        )
    lines = text.splitlines()
    return _preset_of_line(lines[-1]) if lines else None

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 load_bustype_json()).

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 rho (vector-fit case).

required
rho_preset str

The preset of effective_resistivity() that gave rho (the bus's preset). When the document records another one (BusTypeSpec.rho_preset), a RhoPresetMismatchWarning is emitted (user decision Q39); None (default), or a document without a recorded preset, checks nothing.

None

Returns:

Type Description
ndarray

Complex-valued \(Z\) in \(\Omega\) at every requested frequency.

Raises:

Type Description
EvaluateSpecError

Subclass of ValueError; raised when spec is not a BusTypeSpec instance, impedance_formula is empty / missing on the spec, or the formula is outside the allowed grammar or its size and magnitude bounds (including unknown free symbols — anything other than f, rho, j / I, pi and E). The exception is typed so downstream consumers (notably groundinsight) can catch it without substring matching on the message. Existing except ValueError blocks keep working because EvaluateSpecError inherits from ValueError. A rho_preset that is not a preset name raises ValueError.

Warns:

Type Description
RhoPresetMismatchWarning

If rho_preset differs from the preset the document records.

Source code in src/groundfield/io/groundinsight.py
def evaluate_spec(
    spec: BusTypeSpec,
    frequencies: Sequence[float],
    rho: float,
    *,
    rho_preset: Optional[str] = None,
) -> np.ndarray:
    """Evaluate a :class:`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
    :func:`~groundfield.io._formula.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
    ----------
    spec : BusTypeSpec
        Loaded spec (e.g. from :func:`load_bustype_json`).
    frequencies : sequence of float
        Frequencies in Hz.
    rho : float
        Soil resistivity in $\\Omega\\,\\mathrm{m}$. Ignored if the
        formula does not depend on ``rho`` (vector-fit case).
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` that
        gave ``rho`` (the bus's preset). When the document records another
        one (:attr:`BusTypeSpec.rho_preset`), a
        :class:`RhoPresetMismatchWarning` is emitted (user decision Q39);
        ``None`` (default), or a document without a recorded preset, checks
        nothing.

    Returns
    -------
    np.ndarray
        Complex-valued $Z$ in $\\Omega$ at every requested frequency.

    Raises
    ------
    EvaluateSpecError
        Subclass of :class:`ValueError`; raised when ``spec`` is not a
        :class:`BusTypeSpec` instance, ``impedance_formula`` is empty
        / missing on the spec, or the formula is outside the allowed
        grammar or its size and magnitude bounds (including unknown
        free symbols — anything other than ``f``, ``rho``, ``j`` /
        ``I``, ``pi`` and ``E``). The exception is typed so downstream
        consumers (notably ``groundinsight``) can catch it without
        substring matching on the message. Existing ``except
        ValueError`` blocks keep working because
        :class:`EvaluateSpecError` inherits from :class:`ValueError`.
        A ``rho_preset`` that is not a preset name raises
        :class:`ValueError`.

    Warns
    -----
    RhoPresetMismatchWarning
        If ``rho_preset`` differs from the preset the document records.
    """
    from groundfield.io._formula import formula_function

    # Defensive entry-point validation. Hand-rolled BusTypeSpec-like
    # dicts (e.g. constructed in a CLI helper from a YAML campaign
    # config) routinely miss the impedance_formula; surface the real
    # problem here instead of an opaque error deep in SymPy.
    if not isinstance(spec, BusTypeSpec):
        raise EvaluateSpecError(
            "evaluate_spec: expected a BusTypeSpec instance, got "
            f"{type(spec).__name__}. Build one via load_bustype_json "
            "or BusTypeSpec.from_dict before calling evaluate_spec."
        )
    formula = getattr(spec, "impedance_formula", None)
    if formula is None or not str(formula).strip():
        raise EvaluateSpecError(
            "evaluate_spec: spec.impedance_formula is missing or "
            "empty. A BusTypeSpec must carry a non-empty "
            "impedance_formula string with free symbols in "
            "{f, rho, j}."
        )
    expr = _parse_formula(
        formula if isinstance(formula, str) else str(formula),
        context="evaluate_spec: spec.impedance_formula",
    )
    _warn_on_preset_mismatch(spec, rho_preset, "evaluate_spec")
    func = formula_function(expr, ("f", "rho"))
    f_arr = np.asarray(frequencies, dtype=float)
    out = func(f_arr, float(rho))
    return np.broadcast_to(out, f_arr.shape).copy()

fit_quality_summary

fit_quality_summary(spec: BusTypeSpec) -> str

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

BusTypeSpec(name=..., method=..., rms=..., ...); a figure the document does not record is left out (the rms reads unknown).

Source code in src/groundfield/io/groundinsight.py
def fit_quality_summary(spec: BusTypeSpec) -> str:
    """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
    ----------
    spec
        Exported or loaded BusType document.

    Returns
    -------
    str
        ``BusTypeSpec(name=..., method=..., rms=..., ...)``; a figure the
        document does not record is left out (the rms reads ``unknown``).
    """
    md = spec.metadata if isinstance(spec.metadata, dict) else {}
    fq = md.get("fit_quality")
    if not isinstance(fq, dict):
        fq = {}
    method = _summary_label(md.get("fit_method")) or "unknown"
    rms = _summary_figure(fq.get("rms_error_Ohm"))
    rms_text = "unknown" if rms is None else f"{rms:.3e} Ω"
    parts = [f"name={spec.name!r}", f"method={method}", f"rms={rms_text}"]
    rms_relative = _summary_figure(fq.get("rms_relative"))
    if rms_relative is not None:
        parts.append(f"rms_rel={rms_relative:.2%}")
    max_relative = _summary_figure(fq.get("max_relative"))
    if max_relative is not None:
        parts.append(f"max_rel={max_relative:.2%}")
    quantity = _summary_label(md.get("quantity"))
    if quantity is not None:
        parts.append(f"quantity={quantity}")
    preset = spec.rho_preset if isinstance(spec, BusTypeSpec) else None
    if preset is not None:
        parts.append(f"rho_preset={preset}")
    return f"BusTypeSpec({', '.join(parts)})"

load_bustype_json

load_bustype_json(path: Union[str, Path]) -> BusTypeSpec

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 save_bustype_json().

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 BusTypeSpec.from_dict().

EvaluateSpecError

If impedance_formula is missing or outside the allowed formula grammar.

Source code in src/groundfield/io/groundinsight.py
def load_bustype_json(path: Union[str, Path]) -> BusTypeSpec:
    """Load a ``BusType`` JSON document into a :class:`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 :data:`SCHEMA_VERSION`, dispatch to the appropriate loader.
    Today only v1 exists.

    Parameters
    ----------
    path : str or pathlib.Path
        JSON file written by :func:`save_bustype_json`.

    Returns
    -------
    BusTypeSpec

    Raises
    ------
    ValueError
        If the file is not valid JSON (also: nested too deeply to be
        read) or not a schema-v1 BusType document, see
        :meth:`BusTypeSpec.from_dict`.
    EvaluateSpecError
        If ``impedance_formula`` is missing or outside the allowed
        formula grammar.
    """
    p = Path(path)
    with p.open("r", encoding="utf-8") as fh:
        try:
            payload = json.load(fh)
        except RecursionError:
            raise ValueError(
                f"BusType document {p.name!r} is nested too deeply to be read"
            ) from None
    return BusTypeSpec.from_dict(payload)

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 BusType fields, see to_bustype_dict().

required
system_type str

The BusType fields, see to_bustype_dict().

required
voltage_level str

The BusType fields, see to_bustype_dict().

required
description str

The BusType fields, see to_bustype_dict().

required
decimals int

Significant digits per coefficient (default 12), see to_bustype_dict().

12
rho_at_fit float

Soil resistivity in \(\Omega\,\mathrm{m}\) of a VectorFitResult; required for vector fits, ignored for standard-form fits. For layered soil the convention is the effective resistivity effective_resistivity(soil, preset=...) (see to_bustype_dict()).

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 NonPassiveFitError instead of warning when the passivity check fails. Default False.

False
rho_preset str

The preset of effective_resistivity() behind the rho of the fit, recorded as metadata["rho_preset"] (default None: none named), see to_bustype_dict().

None

Returns:

Type Description
Path

The path the file was actually written to, for chaining.

Raises:

Type Description
ValueError

If rho_at_fit is missing for a vector fit or invalid.

NonPassiveFitError

With require_passive=True, if the passivity check fails.

Warns:

Type Description
NonPassiveFitWarning

If the passivity check fails and require_passive is False.

Source code in src/groundfield/io/groundinsight.py
def 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 :func:`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
    ----------
    fit : RhoFStandardFit or VectorFitResult
        The fitted rho-f model.
    path : str or pathlib.Path
        Target file; parent directories are created.
    name, system_type, voltage_level, description
        The ``BusType`` fields, see :func:`to_bustype_dict`.
    decimals : int, optional
        Significant digits per coefficient (default 12), see
        :func:`to_bustype_dict`.
    rho_at_fit : float, optional
        Soil resistivity in $\\Omega\\,\\mathrm{m}$ of a
        :class:`VectorFitResult`; required for vector fits, ignored for
        standard-form fits. For layered soil the convention is the
        effective resistivity ``effective_resistivity(soil, preset=...)``
        (see :func:`to_bustype_dict`).
    electrode_name, soil_summary : str, optional
        Free-form metadata entries.
    indent : int, optional
        JSON indentation. Default 2.
    require_passive : bool, optional
        Raise :class:`NonPassiveFitError` instead of warning when the
        passivity check fails. Default False.
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` behind
        the ``rho`` of the fit, recorded as ``metadata["rho_preset"]``
        (default ``None``: none named), see :func:`to_bustype_dict`.

    Returns
    -------
    pathlib.Path
        The path the file was actually written to, for chaining.

    Raises
    ------
    ValueError
        If ``rho_at_fit`` is missing for a vector fit or invalid.
    NonPassiveFitError
        With ``require_passive=True``, if the passivity check fails.

    Warns
    -----
    NonPassiveFitWarning
        If the passivity check fails and ``require_passive`` is False.
    """
    payload = _build_spec(
        fit,
        name=name,
        system_type=system_type,
        voltage_level=voltage_level,
        description=description,
        decimals=decimals,
        rho_at_fit=rho_at_fit,
        electrode_name=electrode_name,
        soil_summary=soil_summary,
        require_passive=require_passive,
        caller="save_bustype_json",
        rho_preset=rho_preset,
    ).to_dict()
    text = json.dumps(payload, indent=indent, sort_keys=False, allow_nan=False)
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    with p.open("w", encoding="utf-8") as fh:
        fh.write(text + "\n")
    return p

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 BusType fields, see to_bustype_dict().

required
system_type str

The BusType fields, see to_bustype_dict().

required
voltage_level str

The BusType fields, see to_bustype_dict().

required
description str

The BusType fields, see to_bustype_dict().

required
decimals int

Significant digits per coefficient (default 12).

12
rho_at_fit float

Soil resistivity in \(\Omega\,\mathrm{m}\) of a VectorFitResult; required for vector fits, ignored for standard-form fits. For layered soil the convention is the effective resistivity effective_resistivity(soil, preset=...) (see to_bustype_dict()).

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 BusType of the same name. Default False.

False
require_passive bool

Raise NonPassiveFitError instead of warning when the passivity check fails. Default False.

False
rho_preset str

The preset of effective_resistivity() behind the rho of the fit (default None: none named), see to_bustype_dict(); stored as the last line of the description, groundfield rho_preset: <name>, which the database keeps: bustype_rho_preset() reads it from a BusType loaded with gi.load_bustypes_from_db() (audit W3B-06).

None

Raises:

Type Description
ValueError

If rho_at_fit is missing for a vector fit or invalid.

NonPassiveFitError

With require_passive=True, if the passivity check fails.

ImportError

If groundinsight is not installed.

RuntimeError

From groundinsight if no database session is open.

Warns:

Type Description
NonPassiveFitWarning

If the passivity check fails and require_passive is False.

Source code in src/groundfield/io/groundinsight.py
def 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
    :func:`to_bustype_dict`.

    Parameters
    ----------
    fit : RhoFStandardFit or VectorFitResult
        The fitted rho-f model.
    name, system_type, voltage_level, description
        The ``BusType`` fields, see :func:`to_bustype_dict`.
    decimals : int, optional
        Significant digits per coefficient (default 12).
    rho_at_fit : float, optional
        Soil resistivity in $\\Omega\\,\\mathrm{m}$ of a
        :class:`VectorFitResult`; required for vector fits, ignored for
        standard-form fits. For layered soil the convention is the
        effective resistivity ``effective_resistivity(soil, preset=...)``
        (see :func:`to_bustype_dict`).
    electrode_name, soil_summary : str, optional
        Free-form metadata entries (not stored in the database).
    overwrite : bool, optional
        Replace an existing ``BusType`` of the same name. Default False.
    require_passive : bool, optional
        Raise :class:`NonPassiveFitError` instead of warning when the
        passivity check fails. Default False.
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` behind
        the ``rho`` of the fit (default ``None``: none named), see
        :func:`to_bustype_dict`; stored as the last line of the description,
        ``groundfield rho_preset: <name>``, which the database keeps:
        :func:`bustype_rho_preset` reads it from a BusType loaded with
        ``gi.load_bustypes_from_db()`` (audit W3B-06).

    Raises
    ------
    ValueError
        If ``rho_at_fit`` is missing for a vector fit or invalid.
    NonPassiveFitError
        With ``require_passive=True``, if the passivity check fails.
    ImportError
        If ``groundinsight`` is not installed.
    RuntimeError
        From ``groundinsight`` if no database session is open.

    Warns
    -----
    NonPassiveFitWarning
        If the passivity check fails and ``require_passive`` is False.
    """
    spec = _build_spec(
        fit,
        name=name,
        system_type=system_type,
        voltage_level=voltage_level,
        description=description,
        decimals=decimals,
        rho_at_fit=rho_at_fit,
        electrode_name=electrode_name,
        soil_summary=soil_summary,
        require_passive=require_passive,
        caller="save_bustype_to_db",
        rho_preset=rho_preset,
    )
    bustype = _to_live_bustype(spec)
    import groundinsight as gi  # already verified by _to_live_bustype

    gi.save_bustype_to_db(bustype, overwrite=overwrite)

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 BusType fields, see to_bustype_dict().

required
system_type str

The BusType fields, see to_bustype_dict().

required
voltage_level str

The BusType fields, see to_bustype_dict().

required
description str

The BusType fields, see to_bustype_dict().

required
decimals int

Significant digits per coefficient (default 12).

12
rho_at_fit float

Soil resistivity in \(\Omega\,\mathrm{m}\) of a VectorFitResult; required for vector fits, ignored for standard-form fits. For layered soil the convention is the effective resistivity effective_resistivity(soil, preset=...) (see to_bustype_dict()).

None
electrode_name str

Free-form metadata entries (not part of the live BusType).

None
soil_summary str

Free-form metadata entries (not part of the live BusType).

None
require_passive bool

Raise NonPassiveFitError instead of warning when the passivity check fails. Default False.

False
rho_preset str

The preset of effective_resistivity() behind the rho of the fit (default None: none named), see to_bustype_dict(); recorded as the last line of the description, groundfield rho_preset: <name> (a preset line in description is replaced; the rest of the description stays as given).

None

Returns:

Type Description
BusType

Raises:

Type Description
ValueError

If rho_at_fit is missing for a vector fit or invalid.

NonPassiveFitError

With require_passive=True, if the passivity check fails.

ImportError

If groundinsight is not installed.

Warns:

Type Description
NonPassiveFitWarning

If the passivity check fails and require_passive is False.

Source code in src/groundfield/io/groundinsight.py
def 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 :class:`groundinsight.BusType` from a fit.

    Performs the same conversion and checks as :func:`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
    :class:`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 :func:`to_bustype_dict` or
    :func:`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>``
    (:func:`bustype_rho_preset` reads it back; audit W3B-06).

    Parameters
    ----------
    fit : RhoFStandardFit or VectorFitResult
        The fitted rho-f model.
    name, system_type, voltage_level, description
        The ``BusType`` fields, see :func:`to_bustype_dict`.
    decimals : int, optional
        Significant digits per coefficient (default 12).
    rho_at_fit : float, optional
        Soil resistivity in $\\Omega\\,\\mathrm{m}$ of a
        :class:`VectorFitResult`; required for vector fits, ignored for
        standard-form fits. For layered soil the convention is the
        effective resistivity ``effective_resistivity(soil, preset=...)``
        (see :func:`to_bustype_dict`).
    electrode_name, soil_summary : str, optional
        Free-form metadata entries (not part of the live ``BusType``).
    require_passive : bool, optional
        Raise :class:`NonPassiveFitError` instead of warning when the
        passivity check fails. Default False.
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` behind
        the ``rho`` of the fit (default ``None``: none named), see
        :func:`to_bustype_dict`; recorded as the last line of the
        description, ``groundfield rho_preset: <name>`` (a preset line in
        ``description`` is replaced; the rest of the description stays as
        given).

    Returns
    -------
    groundinsight.models.core_models.BusType

    Raises
    ------
    ValueError
        If ``rho_at_fit`` is missing for a vector fit or invalid.
    NonPassiveFitError
        With ``require_passive=True``, if the passivity check fails.
    ImportError
        If ``groundinsight`` is not installed.

    Warns
    -----
    NonPassiveFitWarning
        If the passivity check fails and ``require_passive`` is False.
    """
    spec = _build_spec(
        fit,
        name=name,
        system_type=system_type,
        voltage_level=voltage_level,
        description=description,
        decimals=decimals,
        rho_at_fit=rho_at_fit,
        electrode_name=electrode_name,
        soil_summary=soil_summary,
        require_passive=require_passive,
        caller="to_bustype",
        rho_preset=rho_preset,
    )
    return _to_live_bustype(spec)

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

BusType.name.

required
system_type str

BusType.system_type (e.g. "TN", "LV").

required
voltage_level float

BusType.voltage_level in the unit used by groundinsight.

required
description str

BusType.description.

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 fit.evaluate to about \(10^{-11}\) relative (ADR-0008 requires \(10^{-9}\)); 6 gives a short formula with about \(10^{-6}\) relative deviation.

12
rho_at_fit float

Soil resistivity in \(\Omega\,\mathrm{m}\) at which a VectorFitResult was computed. Required for vector fits (it goes into samples["rho_Ohm_m"] and metadata["rho_at_fit_Ohm_m"]); ignored for standard-form fits. For layered soil the convention is the effective resistivity of the soil with the weight preset of the electrode class, effective_resistivity(soil, preset=...) (effective_resistivity()), the value a groundinsight Bus with the same preset carries as specific_earth_resistance (see the module docstring); describe the layers and the preset in soil_summary.

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 NonPassiveFitError instead of warning when the formula has \(\operatorname{Re} Z < 0\) somewhere in the checked band. Default False.

False
rho_preset str

The preset of effective_resistivity() that gave the rho of the fit (rho_at_fit of a vector fit, the rho samples of a standard form), a key of EFFECTIVE_RESISTIVITY_PRESETS, recorded as metadata["rho_preset"]. Default None: no preset named (homogeneous soil, explicit weights, or not stated). A bus that uses another preset is then reported by evaluate_spec() and bustype_from_spec() (user decision Q39).

None

Returns:

Type Description
dict

JSON-ready dict matching schema_version = 1 of groundfield.bustype (strict JSON: a number that is not finite, such as the unknown rms error of a hand-built fit, is None), including metadata["passivity"] with the keys passed, min_re_Z_Ohm, f_at_min_Hz, rho_at_min_Ohm_m, f_checked_Hz, rho_checked_Ohm_m and n_points.

Raises:

Type Description
ValueError

If rho_at_fit is missing for a vector fit or not a positive finite number, if voltage_level is not finite, if the fit has non-finite coefficients, or if rho_preset is not a preset name.

NonPassiveFitError

With require_passive=True, if the passivity check fails.

TypeError

If fit is not a supported fit object.

Warns:

Type Description
NonPassiveFitWarning

If the passivity check fails and require_passive is False.

Source code in src/groundfield/io/groundinsight.py
def 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
    ----------
    fit : RhoFStandardFit or VectorFitResult
        The fitted rho-f model.
    name : str
        ``BusType.name``.
    system_type : str
        ``BusType.system_type`` (e.g. ``"TN"``, ``"LV"``).
    voltage_level : float
        ``BusType.voltage_level`` in the unit used by ``groundinsight``.
    description : str, optional
        ``BusType.description``.
    decimals : int, optional
        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 ``fit.evaluate`` to about
        $10^{-11}$ relative (ADR-0008 requires $10^{-9}$); 6 gives a
        short formula with about $10^{-6}$ relative deviation.
    rho_at_fit : float, optional
        Soil resistivity in $\\Omega\\,\\mathrm{m}$ at which a
        :class:`VectorFitResult` was computed. Required for vector
        fits (it goes into ``samples["rho_Ohm_m"]`` and
        ``metadata["rho_at_fit_Ohm_m"]``); ignored for standard-form
        fits. For layered soil the convention is the
        effective resistivity of the soil with the weight preset of the
        electrode class, ``effective_resistivity(soil, preset=...)``
        (:func:`~groundfield.soil.effective_resistivity`), the value a
        ``groundinsight`` ``Bus`` with the same preset carries as
        ``specific_earth_resistance`` (see the module docstring); describe
        the layers and the preset in ``soil_summary``.
    electrode_name, soil_summary : str, optional
        Free-form metadata entries; recommended for traceability.
    require_passive : bool, optional
        If True, raise :class:`NonPassiveFitError` instead of warning
        when the formula has $\\operatorname{Re} Z < 0$ somewhere in
        the checked band. Default False.
    rho_preset : str, optional
        The preset of :func:`~groundfield.soil.effective_resistivity` that
        gave the ``rho`` of the fit (``rho_at_fit`` of a vector fit, the
        ``rho`` samples of a standard form), a key of
        :data:`~groundfield.soil.EFFECTIVE_RESISTIVITY_PRESETS`, recorded as
        ``metadata["rho_preset"]``. Default ``None``: no preset named
        (homogeneous soil, explicit weights, or not stated). A bus that uses
        another preset is then reported by :func:`evaluate_spec` and
        :func:`bustype_from_spec` (user decision Q39).

    Returns
    -------
    dict
        JSON-ready ``dict`` matching ``schema_version = 1`` of
        ``groundfield.bustype`` (strict JSON: a number that is not
        finite, such as the unknown rms error of a hand-built fit, is
        ``None``), including ``metadata["passivity"]``
        with the keys ``passed``, ``min_re_Z_Ohm``, ``f_at_min_Hz``,
        ``rho_at_min_Ohm_m``, ``f_checked_Hz``, ``rho_checked_Ohm_m``
        and ``n_points``.

    Raises
    ------
    ValueError
        If ``rho_at_fit`` is missing for a vector fit or not a positive
        finite number, if ``voltage_level`` is not finite, if the fit
        has non-finite coefficients, or if ``rho_preset`` is not a preset
        name.
    NonPassiveFitError
        With ``require_passive=True``, if the passivity check fails.
    TypeError
        If ``fit`` is not a supported fit object.

    Warns
    -----
    NonPassiveFitWarning
        If the passivity check fails and ``require_passive`` is False.
    """
    spec = _build_spec(
        fit,
        name=name,
        system_type=system_type,
        voltage_level=voltage_level,
        description=description,
        decimals=decimals,
        rho_at_fit=rho_at_fit,
        electrode_name=electrode_name,
        soil_summary=soil_summary,
        require_passive=require_passive,
        caller="to_bustype_dict",
        rho_preset=rho_preset,
    )
    return spec.to_dict()

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
save_potential_path_csv"><autoref identifier="groundfield.io.csv.save_potential_path_csv" optional><code>save_potential_path_csv

Sample FieldResult.potential() along a straight line on or below the soil surface and write (s, x, y, z, frequency_Hz, phi_re, phi_im, abs_phi) rows.

save_electrode_table_csv"><autoref identifier="groundfield.io.csv.save_electrode_table_csv" optional><code>save_electrode_table_csv

Wrap groundfield.postprocess.electrode_current_table() and dump the per-electrode summary.

save_cluster_impedances_csv"><autoref identifier="groundfield.io.csv.save_cluster_impedances_csv" optional><code>save_cluster_impedances_csv

Wrap groundfield.postprocess.cluster_current_balance() and dump the per-cluster summary.

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_csv_with_provenance(path: str | Path) -> tuple[pd.DataFrame, dict[str, str]]

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 save_*_csv writers (with or without provenance header).

required

Returns:

Name Type Description
df DataFrame

The table. Only the leading # lines are skipped, so values that contain # (electrode names) stay intact.

provenance dict[str, str]

key -> value of the header lines (the first line's groundfield csv: <table> appears as key groundfield csv); empty for a plain CSV.

Source code in src/groundfield/io/csv.py
def read_csv_with_provenance(path: str | Path) -> tuple[pd.DataFrame, dict[str, str]]:
    """Read a CSV written by this module, with its provenance header.

    Parameters
    ----------
    path
        File written by one of the ``save_*_csv`` writers (with or
        without provenance header).

    Returns
    -------
    df : pandas.DataFrame
        The table. Only the leading ``#`` lines are skipped, so values
        that contain ``#`` (electrode names) stay intact.
    provenance : dict[str, str]
        ``key -> value`` of the header lines (the first line's
        ``groundfield csv: <table>`` appears as key ``groundfield csv``);
        empty for a plain CSV.
    """
    p = Path(path)
    meta: dict[str, str] = {}
    n_comment = 0
    with p.open(encoding="utf-8") as fh:
        for line in fh:
            if not line.startswith("#"):
                break
            n_comment += 1
            key, sep, value = line[1:].strip().partition(":")
            if sep:
                meta[key.strip()] = value.strip()
    return pd.read_csv(p, skiprows=n_comment), meta

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 FieldResult.frequencies. Default 0. The frequency is written to the frequency_hz column.

0
overwrite bool

Replace an existing file (default False: raise).

False
provenance bool

Write the # provenance header (default True).

True

Returns:

Type Description
Path

Raises:

Type Description
FileExistsError

If path exists and overwrite is False.

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
def save_cluster_impedances_csv(
    result: "FieldResult",
    path: str | Path,
    *,
    frequency_index: int = 0,
    overwrite: bool = False,
    provenance: bool = True,
) -> Path:
    """Wrap :func:`cluster_current_balance` and write to CSV.

    Note that the ``members`` column of
    :func:`cluster_current_balance` carries Python lists; CSV is
    a flat format, so the lists are joined into ``';'``-separated
    strings before writing.

    Parameters
    ----------
    result
        Solver output.
    path
        Destination CSV path.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0. The
        frequency is written to the ``frequency_hz`` column.
    overwrite
        Replace an existing file (default ``False``: raise).
    provenance
        Write the ``#`` provenance header (default ``True``).

    Returns
    -------
    pathlib.Path

    Raises
    ------
    FileExistsError
        If ``path`` exists and ``overwrite`` is ``False``.

    Notes
    -----
    The ``Z`` columns are cluster impedances (a cluster's potential over
    its own soil leakage), not the input impedance a source sees.
    """
    from groundfield.postprocess.current_balance import cluster_current_balance

    out = _ensure_path(path, overwrite)
    df = cluster_current_balance(result, frequency_index=frequency_index)
    if "members" in df.columns:
        df = df.copy()
        df["members"] = df["members"].apply(lambda lst: ";".join(lst))
    f_hz = float(result.frequencies[frequency_index])
    df.insert(min(1, len(df.columns)), "frequency_hz", f_hz)
    header = None
    if provenance:
        header = _provenance_lines(
            result,
            "cluster_impedances",
            {"frequency_hz": _fmt_number(f_hz), "frequency_index": frequency_index},
        )
    return _write(df, out, header)

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 kind and depth_m columns.

None
frequency_index int

Index into FieldResult.frequencies. Default 0. The frequency is written to the frequency_hz column.

0
overwrite bool

Replace an existing file (default False: raise).

False
provenance bool

Write the # provenance header (default True).

True

Returns:

Type Description
Path

Raises:

Type Description
FileExistsError

If path exists and overwrite is False.

Source code in src/groundfield/io/csv.py
def 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 :func:`electrode_current_table` and write to CSV.

    Parameters
    ----------
    result
        Solver output.
    path
        Destination CSV path.
    world
        Optional companion world; when given, the table includes
        the ``kind`` and ``depth_m`` columns.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0. The
        frequency is written to the ``frequency_hz`` column.
    overwrite
        Replace an existing file (default ``False``: raise).
    provenance
        Write the ``#`` provenance header (default ``True``).

    Returns
    -------
    pathlib.Path

    Raises
    ------
    FileExistsError
        If ``path`` exists and ``overwrite`` is ``False``.
    """
    from groundfield.postprocess.current_balance import electrode_current_table

    out = _ensure_path(path, overwrite)
    df = electrode_current_table(result, world=world, frequency_index=frequency_index)
    f_hz = float(result.frequencies[frequency_index])
    df.insert(min(2, len(df.columns)), "frequency_hz", f_hz)
    header = None
    if provenance:
        header = _provenance_lines(
            result,
            "electrode_table",
            {"frequency_hz": _fmt_number(f_hz), "frequency_index": frequency_index},
        )
    return _write(df, out, header)

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 point_sources (i.e. not a stub backend).

required
path str | Path

Destination CSV path. Parent directories are created automatically.

required
start tuple[float, float, float]

Path start point (x, y, z) in metres.

required
direction tuple[float, float, float]

Direction vector. Will be normalised to unit length. Default (1, 0, 0).

(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 FieldResult.frequencies. None (default) uses every available frequency.

None
overwrite bool

Replace an existing file (default False: raise).

False
provenance bool

Write the # provenance header (default True, see the module docstring).

True

Returns:

Type Description
Path

The path the file was written to.

Raises:

Type Description
ValueError

If distance <= 0, n < 2, direction is the zero vector, or any frequency_indices value is out of range.

FileExistsError

If path exists and overwrite is False.

Source code in src/groundfield/io/csv.py
def 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
    :meth:`FieldResult.potential` at every selected frequency
    index, and writes the result to ``path``.

    Parameters
    ----------
    result
        Solver output. Must carry ``point_sources`` (i.e. not a
        stub backend).
    path
        Destination CSV path. Parent directories are created
        automatically.
    start
        Path start point ``(x, y, z)`` in metres.
    direction
        Direction vector. Will be normalised to unit length.
        Default ``(1, 0, 0)``.
    distance
        Path length in metres. Default 30.
    n
        Number of sample points along the path. Default 200.
    frequency_indices
        Iterable of integer indices into
        :attr:`FieldResult.frequencies`. ``None`` (default)
        uses every available frequency.
    overwrite
        Replace an existing file (default ``False``: raise).
    provenance
        Write the ``#`` provenance header (default ``True``, see the
        module docstring).

    Returns
    -------
    pathlib.Path
        The path the file was written to.

    Raises
    ------
    ValueError
        If ``distance <= 0``, ``n < 2``, ``direction`` is the zero
        vector, or any ``frequency_indices`` value is out of range.
    FileExistsError
        If ``path`` exists and ``overwrite`` is ``False``.
    """
    if distance <= 0.0:
        raise ValueError(f"distance must be > 0, got {distance!r}.")
    if n < 2:
        raise ValueError(f"n must be >= 2, got {n!r}.")
    direction_arr = np.asarray(direction, dtype=float)
    norm = float(np.linalg.norm(direction_arr))
    if norm == 0.0:
        raise ValueError(f"direction must be non-zero, got {tuple(direction)}.")
    direction_arr = direction_arr / norm

    if frequency_indices is None:
        f_idx = list(range(len(result.frequencies)))
    else:
        f_idx = list(frequency_indices)
        for k in f_idx:
            if not (0 <= k < len(result.frequencies)):
                raise ValueError(
                    f"frequency index {k} out of range [0, {len(result.frequencies)})."
                )

    out = _ensure_path(path, overwrite)
    s = np.linspace(0.0, float(distance), int(n))
    pts = np.column_stack(
        [
            start[0] + s * direction_arr[0],
            start[1] + s * direction_arr[1],
            start[2] + s * direction_arr[2],
        ]
    )

    rows = []
    for k in f_idx:
        f_hz = float(result.frequencies[k])
        phi = result.potential(pts, frequency_index=k)
        for i in range(len(s)):
            rows.append(
                {
                    "s": float(s[i]),
                    "x": float(pts[i, 0]),
                    "y": float(pts[i, 1]),
                    "z": float(pts[i, 2]),
                    "frequency_Hz": f_hz,
                    "phi_re": float(phi[i].real),
                    "phi_im": float(phi[i].imag),
                    "abs_phi": float(abs(phi[i])),
                }
            )

    header = None
    if provenance:
        header = _provenance_lines(
            result,
            "potential_path",
            {
                "frequencies_hz": ", ".join(
                    _fmt_number(result.frequencies[k]) for k in f_idx
                ),
                "frequency_indices": ", ".join(str(k) for k in f_idx),
            },
        )
    return _write(pd.DataFrame(rows, columns=list(POTENTIAL_PATH_COLUMNS)), out, header)

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: float makes 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.name become spaces, and the line is limited to 256 bytes as the legacy format requires. A newline in the name used to corrupt the file.
  • groundfield measures \(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 point_sources (not a stub).

required
path str | Path

Destination .vtk path.

required
extent tuple[float, float, float, float]

Plot extent (x_min, x_max, y_min, y_max) in metres.

required
z float

Slice depth in metres (default 0.0 — soil surface). Positive z is below ground.

0.0
n tuple[int, int]

Grid resolution (n_x, n_y). Default (120, 120).

(120, 120)
frequency_index int

Index into FieldResult.frequencies. Default 0.

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
def 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 :meth:`FieldResult.potential` on a regular
    :math:`N_x \\times N_y` grid in the plane :math:`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
    ----------
    result
        Solver output. Must carry ``point_sources`` (not a stub).
    path
        Destination ``.vtk`` path.
    extent
        Plot extent ``(x_min, x_max, y_min, y_max)`` in metres.
    z
        Slice depth in metres (default ``0.0`` — soil surface).
        Positive ``z`` is below ground.
    n
        Grid resolution ``(n_x, n_y)``. Default ``(120, 120)``.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.

    Returns
    -------
    pathlib.Path

    Raises
    ------
    ValueError
        On bad extent or non-positive grid sizes.
    """
    x_min, x_max, y_min, y_max = extent
    if x_max <= x_min or y_max <= y_min:
        raise ValueError(
            f"extent must satisfy x_max > x_min and y_max > y_min, got {extent!r}."
        )
    n_x, n_y = n
    if n_x < 2 or n_y < 2:
        raise ValueError(f"n must be >= (2, 2), got {n!r}.")

    xs = np.linspace(float(x_min), float(x_max), int(n_x))
    ys = np.linspace(float(y_min), float(y_max), int(n_y))
    X, Y = np.meshgrid(xs, ys, indexing="xy")
    pts = np.column_stack([X.ravel(), Y.ravel(), np.full(X.size, float(z))])
    phi = result.potential(pts, frequency_index=frequency_index)
    phi = phi.reshape(X.shape)

    dx = (x_max - x_min) / (n_x - 1)
    dy = (y_max - y_min) / (n_y - 1)

    out = _ensure_path(path)
    buf = StringIO()
    buf.write("# vtk DataFile Version 3.0\n")
    buf.write(
        _header_line(
            f"groundfield potential @ z={z} m, "
            f"f={result.frequencies[frequency_index]} Hz"
        )
        + "\n"
    )
    buf.write("ASCII\n")
    buf.write("DATASET STRUCTURED_POINTS\n")
    buf.write(f"DIMENSIONS {n_x} {n_y} 1\n")
    buf.write(f"ORIGIN {x_min:.17g} {y_min:.17g} {z:.17g}\n")
    buf.write(f"SPACING {dx:.17g} {dy:.17g} 1\n")

    n_pts = n_x * n_y
    buf.write(f"POINT_DATA {n_pts}\n")
    buf.write("SCALARS potential_re double 1\n")
    buf.write("LOOKUP_TABLE default\n")
    # The order in STRUCTURED_POINTS is x fastest, then y, then z.
    # numpy meshgrid with indexing='xy' gives Y[i, j], X[i, j];
    # ravel() with C-order then walks j (x) before i (y) — exactly
    # what VTK expects.
    for v in phi.real.ravel():
        buf.write(f"{float(v):.17g}\n")

    buf.write("SCALARS potential_im double 1\n")
    buf.write("LOOKUP_TABLE default\n")
    for v in phi.imag.ravel():
        buf.write(f"{float(v):.17g}\n")

    out.write_text(buf.getvalue(), encoding="utf-8")
    return out

export_geometry_vtk

export_geometry_vtk(world: 'World', path: str | Path) -> Path

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 name goes into the (sanitised) header line.

required
path str | Path

Destination .vtk path. Parent directories are created automatically.

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
def export_geometry_vtk(world: "World", path: str | Path) -> Path:
    """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
    ----------
    world
        World to export. May be empty (the writer still produces
        a syntactically valid header-only file). Its ``name`` goes into
        the (sanitised) header line.
    path
        Destination ``.vtk`` path. Parent directories are created
        automatically.

    Returns
    -------
    pathlib.Path
        The path the file was written to.

    Notes
    -----
    POINTS are written as ``double``; :math:`z` is the depth below the
    surface (positive downwards), see the module docstring.
    """
    polylines: list[np.ndarray] = []
    roles: list[int] = []

    for e in world.electrodes:
        for poly in _polylines_for_electrode(e):
            polylines.append(poly)
            roles.append(0)

    for c in world.conductors:
        seg = np.array([list(c.start), list(c.end)], dtype=float)
        polylines.append(seg)
        roles.append(1)

    out = _ensure_path(path)
    buf = StringIO()
    buf.write("# vtk DataFile Version 3.0\n")
    buf.write(_header_line(f"groundfield geometry: {world.name}") + "\n")
    buf.write("ASCII\n")
    buf.write("DATASET POLYDATA\n")

    if not polylines:
        buf.write("POINTS 0 double\n")
        out.write_text(buf.getvalue(), encoding="utf-8")
        return out

    n_points = sum(p.shape[0] for p in polylines)
    n_lines = len(polylines)
    n_line_data = n_lines + n_points  # one count + entries per line

    buf.write(f"POINTS {n_points} double\n")
    for poly in polylines:
        for x, y, z in poly:
            buf.write(f"{x:.17g} {y:.17g} {z:.17g}\n")

    buf.write(f"LINES {n_lines} {n_line_data}\n")
    offset = 0
    for poly in polylines:
        n = poly.shape[0]
        idx_list = " ".join(str(offset + k) for k in range(n))
        buf.write(f"{n} {idx_list}\n")
        offset += n

    # Cell data: role per polyline (0 = electrode, 1 = conductor).
    buf.write(f"CELL_DATA {n_lines}\n")
    buf.write("SCALARS role int 1\n")
    buf.write("LOOKUP_TABLE default\n")
    for r in roles:
        buf.write(f"{r}\n")

    out.write_text(buf.getvalue(), encoding="utf-8")
    return out