Skip to content

Postprocess

The postprocess package turns a FieldResult into engineering quantities: potentials and their plots, touch and step voltages with the EN 50522 limits, the current sharing between electrodes and conductors, parameter sweeps and convergence studies, and the reduced rho-f models that are exported to groundinsight. Every function is available at the top level (gf.touch_voltage) and in the namespaces gf.plot, gf.safety and gf.fit.

Mathematical and physical context

Potentials. After the solve the leakage currents \(I_k\) of the segments are known, and the potential anywhere in or on the soil is the superposition \(\varphi(\mathbf{r}) = \sum_k G(\mathbf{r}, \mathbf{r}_k)\,I_k\) with the Green's function of the soil (homogeneous or two-layer).

Touch and step voltage (EN 50522:2022, IEC 61936-1). A person touches an accessible conductive part at the potential \(U_\text{part}\) of the earthing system it is bonded to and stands on the surface 1 m away from it (EN 50522's conventional position):

\[ U_T = U_\text{part} - \varphi(\mathbf{r}_\text{feet}), \qquad U_S = \varphi(\mathbf{r}_1) - \varphi(\mathbf{r}_1 + d_\text{step}\,\hat{\mathbf{e}}). \]

touch_voltage_at_part evaluates \(U_T\) at a touch point, an accessible metal part above ground (a station housing or door, a mast, a fence post, a service connection box): the feet stand on the circle of radius \(d\) (default 1 m) around the part, optionally only in given directions or outside the outlines where nobody can stand, and \(U_\text{part}\) is the potential of the electrode or junction the part is bonded to — a PEN junction at a house gives the transferred potential. Where the parts are not known, touch_voltage and touch_voltage_envelope take the electrode itself as the touched part, \(U_\text{part} = U_E = \varphi_\text{cluster}\), with the feet at distance \(d\) from its footprint, the horizontal projection of its wires; the envelope walks all around it. It samples nothing inside the footprint by default (there stands the station, the house, the steel structure or the mast); for open-air grids such as a substation yard, interior="meshes" adds the centres of the meshes (the analogue of the IEEE 80 mesh voltage) and of a ring, interior=True also the inside of closed polylines. permissible_touch_voltage_en50522(t_f) follows Figure 8 / Table B.4 of EN 50522:2022 up to 10 s and returns 80 V for every \(t_f > 10\) s, including an uncleared fault (math.inf), the value the standard allows for current-flow durations considerably longer than 10 s; permissible_prospective_touch_voltage_en50522 adds the body and footwear resistances of Annex B.4. For a fault current with harmonics, touch_voltage_spectrum returns the true-RMS value \(U_{T,\text{rms}} = \sqrt{\sum_k \lvert U_{T,k}\rvert^2}\) over the frequencies of the spectrum.

Current sharing. cluster_current_balance and electrode_current_table list the current every cluster and electrode leaks into the soil; split_factor is the share of a source current that leaves through the soil at the feeding cluster (the rest flows away through conductors). The inductive reduction factor of cable screens is not computed here.

Reduced models. The quantity a reduced model describes is selected with quantity= ("input", the default, "cluster" or "electrode", see the quickstart). Two families:

  • vector fitting (Gustavsen and Semlyen 1999) of a rational function in \(s = j\omega\) at a fixed soil, \(Z(s) \approx R_\infty + sL_\infty + \sum_k r_k/(s - p_k)\), with a passivity check (\(\operatorname{Re}Z \ge 0\)) before export;
  • the standard form fitted over a \(\rho\) and \(f\) sweep (for layered soil \(\rho\) is the effective resistivity of each solved soil, see Soil),

$$ Z(\rho, f) = k_0 + k_1\rho + (k_2 + jk_3)\,f + (k_4 + jk_5)\,f\rho , $$

with relative weights by default; max_relative is the quality figure to check (a fit above 5 % warns with RhoFStandardQualityWarning).

Validity. Quasi-static range \(f < 1\,\mathrm{kHz}\). The image family assumes a uniform current per unit length on each straight wire of an electrode (user decision Q30): near grids, meshes, stars, strip ends and bonded multi-electrode clusters its surface potentials are impedance-grade, not field-grade, and the safety helpers warn with UniformCurrentFieldWarning (re-solve with backend="mom" for field-grade values). FieldResult.potential and everything built on it support homogeneous and two-layer soil only.

Example

A ring earth carrying a fault current of 100 A at 50 Hz, the touch voltage 1 m outside its footprint, checked against a second backend and against the EN 50522 limit for a fault cleared in 0.5 s:

import groundfield as gf

world = gf.create_world(soil=gf.TwoLayerSoil(rho_1=100.0, rho_2=300.0, h_1=2.0))
gf.create_electrode(world, "ring", name="g1", center=(0.0, 0.0, 0.8), radius=3.0)
gf.create_source(world, attached_to="g1", magnitude=100.0)
result = gf.create_engine(frequencies=[50.0]).solve(world)

U_E = result.electrode_potentials["g1"][0]                       # 1381 V
U_T = gf.touch_voltage(result, world, electrode="g1", distance=1.0)   # 525 V
U_S = gf.step_voltage(result, position=(3.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), world=world)
U_Tp = gf.permissible_touch_voltage_en50522(0.5)                  # 225 V (Table B.4)

mom = gf.create_engine(backend="mom", frequencies=[50.0]).solve(world)
U_T_mom = gf.touch_voltage(mom, world, electrode="g1", distance=1.0)  # 517 V

assert abs(U_E - 1380.9) < 0.5 and abs(U_T - 525.3) < 0.5
assert abs(U_T - U_T_mom) / abs(U_T) < 0.02     # ring: both current ansätze agree
assert U_Tp == 225.0 and abs(U_T) > U_Tp        # this earth needs a closer look
assert 0 < U_S.real < U_T.real

The how-to guide Assess touch voltages and tutorial T08 show the complete assessment (touch points, transferred potential, envelope, prospective touch voltage, spectrum); tutorial T04 the frequency response and the rho-f fits.

Safety (touch and step voltage)

safety

Touch and step voltages for grounding-system safety assessment.

This module turns a groundfield.solver.result.FieldResult into the engineering quantities used in the grounding-system safety verification according to EN 50522:2022 (DIN EN 50522 (VDE 0101-2): 2023-10) / IEC 61936-1: the touch voltage \(U_T\) and the step voltage \(U_S\). It also provides the permissible values \(U_{Tp}(t_f)\) of EN 50522:2022, Table B.4 (the curve of Figure 8), the permissible prospective (open-circuit) touch voltage \(U_{vTp}\) of Annex B.4, and the true-RMS touch voltage over a fault-current spectrum.

Mathematical / physical content

A grounding cluster at earth potential rise

\[ U_E \;=\; \varphi_\text{cluster}, \]

is connected — through any galvanically bonded metallic part — to whatever a person can touch. Standing on the soil surface 1 m away from the touched part (the conventional position of EN 50522), the person's feet sit at the surface potential \(\varphi(\mathbf{r}_\text{feet})\). The prospective touch voltage is

\[ U_T \;=\; U_E \;-\; \varphi(\mathbf{r}_\text{feet}). \]

The touched parts are the accessible metal parts above ground: a station housing or its door, a mast, a fence, a service connection box. touch_voltage_at_part() takes such a part as a touch point — its horizontal position and the electrode or junction it is bonded to — and puts the feet on the circle of radius distance around it, optionally only in given directions or outside the outlines where nobody can stand (the housing or building itself). A part bonded to a node far from the faulted earth, for example to a PEN junction at a house, carries a transferred potential.

Where the parts are not known, touch_voltage() and touch_voltage_envelope() use the electrode itself: since review pass 10 (10.21) the metre is measured from its footprint — the horizontal projection of its wires — not from its connection point; the feet stand distance metres from the nearest wire, on the side given by direction (seen from the length-weighted centroid of the wires). The envelope does not sample the inside of the footprint by default, because there stands the station, the house, the steel structure or the mast. Over an open-air grid such as a substation yard people do walk inside the loops, where the surface potential sags: interior="meshes" adds the mesh centres of grids and the centre of a ring, the analogue of the IEEE Std 80 mesh voltage, and interior=True also the inside of a closed polyline.

For a step voltage the body bridges two surface points at the typical step distance \(d_\text{step} = 1\,\mathrm{m}\):

\[ U_S \;=\; \varphi(\mathbf{r}_1) \;-\; \varphi(\mathbf{r}_1 + d_\text{step}\,\hat{\mathbf e}). \]

Both quantities are returned as complex phasors per frequency index — consistent with the rest of groundfield — so that inductive- and resistive-coupling effects above DC remain visible.

Validity envelope
  • Frequency: quasi-static envelope \(f \le 1\,\mathrm{kHz}\), inherited from the underlying Green's function.
  • Current ansatz: the image family (image, image_2layer, image_nlayer, cim) solves one uniform current per straight wire of an electrode (a wire line of a grid, an arm of a star, a straight run of a polyline, user decision Q30 of 2026.11; a rod, a strip or a ring is one wire). Impedances are fine, but near grids, meshes, stars, strip ends and bonded multi-electrode clusters the surface potential is impedance-grade, not field-grade. Measured against the per-segment mom backend (homogeneous 100 Ω·m, segment_length 0.5 m) with the default line kernel, touch voltage with the feet 1 m outside the footprint and step voltage from 1 m to 2 m outside it: 20 m × 20 m grid with 4 × 4 meshes at the corner, touch +6 %, step −8 % (non-conservative; the step from the point above the corner 1 m outwards is −11 %; one current per grid, up to then, gave +20 % / −21 % / −28 %); 4-arm star (5 m arms) beyond a tip touch +8 %, step −9 %; 10 m strip beyond its end step −6 %; single rings, rods and closed rectangular loops within 2 %. A bonded cluster of a foundation mesh and a bare ring 1 m outside it reads +5 … +16 % with the feet right above the ring (example E02; the warning below fires for it, use mom). The point kernel, which mom shares, isolates the ansatz: grid +5 % / −8 % (−11 % from above the corner), star +7 % / −10 %, strip −7 %, rings, rods and loops within 1 %. The helpers emit UniformCurrentFieldWarning once per call when a uniform-current result is evaluated within NEAR_FIELD_DISTANCE_M of such an electrode; re-solve with backend="mom" for field-grade values.
  • Coordinate convention: the soil surface is at \(z = 0\), positive \(z\) points downwards into the soil (see groundfield.geometry.electrodes). The default surface_z = 0.0 therefore models bare-foot contact at the ground surface.
  • permissible_touch_voltage_en50522() interpolates EN 50522:2022, Table B.4 (the curve of Figure 8) for fault durations \(50\,\mathrm{ms} \le t_f \le 10\,\mathrm{s}\), clamps to 725 V below 50 ms and returns 80 V for every \(t_f > 10\,\mathrm{s}\) including an uncleared fault (the value the standard allows for current-flow durations considerably longer than 10 s).
References
  • EN 50522:2022 — Earthing of power installations exceeding 1 kV a.c., Annex B (Table B.1 body current, Table B.4 permissible touch voltage, B.4 prospective touch voltage). German edition DIN EN 50522 (VDE 0101-2):2023-10.
  • IEC 60479-1:2018 — Effects of current on human beings and livestock (curve c2, body impedance).
  • IEC 61936-1:2021 — Power installations exceeding 1 kV a.c.
  • IEEE Std 80-2013 — Guide for safety in AC substation grounding.

NEAR_FIELD_DISTANCE_M module-attribute

NEAR_FIELD_DISTANCE_M: float = 5.0

Distance in m within which the safety helpers warn about uniform currents.

Horizontal distance from a crowding electrode within which the safety helpers warn about uniform-current results (10.22). At 5 m from the footprint the measured touch / step deviations of the uniform ansatz against mom are at most 4 % for strips, bonded clusters and grids (2.5 % for a 20 m grid with 4 × 4 meshes since user decision Q30, 8 % with one current per grid before) and 6.5 % for a 4-arm star (default line kernel; with the point kernel 5 % for the star).

UniformCurrentFieldWarning

Bases: UserWarning

Field quantity from a uniform-current backend near a crowding geometry.

The image family assigns one uniform current density to every straight wire of an electrode (user decision Q30 of 2026.11). Near grids, meshes, stars, strip ends and bonded multi-electrode clusters the true current crowds to edges, corners and tips, so touch and step voltages computed there are impedance-grade (review pass 10, 10.22; see the module docstring for measured deviations). Re-solve with backend="mom" for field-grade values, or silence the category with warnings.simplefilter("ignore", UniformCurrentFieldWarning).

permissible_prospective_touch_voltage_en50522

permissible_prospective_touch_voltage_en50522(t_f: float, *, R_H: float = 0.0, R_F1: float = 0.0, rho_s: float | None = None, HF: float = 1.0) -> float

Permissible prospective touch voltage \(U_{vTp}\) (EN 50522:2022, B.4).

The prospective (open-circuit) touch voltage may exceed the permissible touch voltage across the body by the drop of the body current over the additional resistances (equivalent circuit of Figure B.2, Equation (A.3) of the standard):

\[ U_{vTp}(t_f) \;=\; U_{Tp}(t_f) \;+\; \frac{I_B(t_f)}{HF}\,R_A, \qquad R_A = R_H + R_{F1} + R_{F2}, \qquad R_{F2} = 1.5\,\mathrm{m}^{-1}\cdot\rho_s, \]

with \(U_{Tp}\) from permissible_touch_voltage_en50522() (Table B.4 up to 10 s, 80 V beyond) and the permissible body current \(I_B(t_f)\) of Table B.1 (0.05 s: 900 mA, 0.1 s: 800 mA, 0.2 s: 600 mA, 0.5 s: 200 mA, 1 s: 80 mA, 2 s: 60 mA, 5 s: 51 mA, 10 s: 50 mA; interpolated log-log, 900 mA below 50 ms, and held at 50 mA beyond 10 s).

Parameters:

Name Type Description Default
t_f float

Fault duration in s, > 0; math.inf for an earth fault that is not cleared.

required
R_H float

Hand resistance (e.g. gloves) in Ω, >= 0.

0.0
R_F1 float

Resistance of the footwear in Ω, >= 0 (EN 50522 quotes 1000 Ω as an average for worn, damp shoes).

0.0
rho_s float | None

Resistivity of the surface layer at the standing position in Ω·m; None (default) omits the standing-position resistance \(R_{F2}\).

None
HF float

Heart-current factor of the current path, > 0; 1 for left hand to feet, the path the standard uses here.

1.0

Returns:

Type Description
float

Permissible prospective touch voltage \(U_{vTp}\) in V.

Raises:

Type Description
ValueError

If a resistance or rho_s is negative or not finite, HF is not positive, or t_f is invalid (see permissible_touch_voltage_en50522()).

Examples:

Figure B.3 of the standard, 0.5 s, no footwear, 500 Ω·m gravel (\(R_F = 750\,\Omega\)): 225 V + 0.2 A · 750 Ω = 375 V.

>>> permissible_prospective_touch_voltage_en50522(0.5, rho_s=500.0)
375.0

An earth fault that is not cleared, 1000 Ω shoes: 80 V + 0.05 A · 1000 Ω = 130 V.

>>> permissible_prospective_touch_voltage_en50522(math.inf, R_F1=1000.0)
130.0
Source code in src/groundfield/postprocess/safety.py
def permissible_prospective_touch_voltage_en50522(
    t_f: float,
    *,
    R_H: float = 0.0,
    R_F1: float = 0.0,
    rho_s: float | None = None,
    HF: float = 1.0,
) -> float:
    """Permissible prospective touch voltage :math:`U_{vTp}` (EN 50522:2022, B.4).

    The prospective (open-circuit) touch voltage may exceed the
    permissible touch voltage across the body by the drop of the body
    current over the additional resistances (equivalent circuit of
    Figure B.2, Equation (A.3) of the standard):

    .. math::

        U_{vTp}(t_f) \\;=\\; U_{Tp}(t_f) \\;+\\;
        \\frac{I_B(t_f)}{HF}\\,R_A,
        \\qquad
        R_A = R_H + R_{F1} + R_{F2},
        \\qquad
        R_{F2} = 1.5\\,\\mathrm{m}^{-1}\\cdot\\rho_s,

    with :math:`U_{Tp}` from :func:`permissible_touch_voltage_en50522`
    (Table B.4 up to 10 s, 80 V beyond) and the permissible body current
    :math:`I_B(t_f)` of Table B.1 (0.05 s: 900 mA, 0.1 s: 800 mA,
    0.2 s: 600 mA, 0.5 s: 200 mA, 1 s: 80 mA, 2 s: 60 mA, 5 s: 51 mA,
    10 s: 50 mA; interpolated log-log, 900 mA below 50 ms, and held at
    50 mA beyond 10 s).

    Parameters
    ----------
    t_f
        Fault duration in s, ``> 0``; ``math.inf`` for an earth fault
        that is not cleared.
    R_H
        Hand resistance (e.g. gloves) in Ω, ``>= 0``.
    R_F1
        Resistance of the footwear in Ω, ``>= 0`` (EN 50522 quotes
        1000 Ω as an average for worn, damp shoes).
    rho_s
        Resistivity of the surface layer at the standing position in
        Ω·m; ``None`` (default) omits the standing-position resistance
        :math:`R_{F2}`.
    HF
        Heart-current factor of the current path, ``> 0``; 1 for left
        hand to feet, the path the standard uses here.

    Returns
    -------
    float
        Permissible prospective touch voltage :math:`U_{vTp}` in V.

    Raises
    ------
    ValueError
        If a resistance or ``rho_s`` is negative or not finite, ``HF`` is
        not positive, or ``t_f`` is invalid (see
        :func:`permissible_touch_voltage_en50522`).

    Examples
    --------
    Figure B.3 of the standard, 0.5 s, no footwear, 500 Ω·m gravel
    (:math:`R_F = 750\\,\\Omega`): 225 V + 0.2 A · 750 Ω = 375 V.

    >>> permissible_prospective_touch_voltage_en50522(0.5, rho_s=500.0)
    375.0

    An earth fault that is not cleared, 1000 Ω shoes:
    80 V + 0.05 A · 1000 Ω = 130 V.

    >>> permissible_prospective_touch_voltage_en50522(math.inf, R_F1=1000.0)
    130.0
    """
    for name, value in (("R_H", R_H), ("R_F1", R_F1)):
        if not math.isfinite(value) or value < 0.0:
            raise ValueError(f"{name} must be finite and >= 0 Ohm, got {value!r}.")
    if rho_s is not None and (not math.isfinite(rho_s) or rho_s < 0.0):
        raise ValueError(f"rho_s must be finite and >= 0 Ohm m, got {rho_s!r}.")
    if not math.isfinite(HF) or HF <= 0.0:
        raise ValueError(f"HF must be finite and > 0, got {HF!r}.")
    u_tp = permissible_touch_voltage_en50522(t_f)
    i_b = _loglog(
        min(float(t_f), _EN50522_CURVE_END_S), _EN50522_IB_GRID, exact_anchors=True
    )
    r_a = R_H + R_F1 + (0.0 if rho_s is None else 1.5 * float(rho_s))
    return u_tp + i_b / HF * r_a

permissible_touch_voltage_en50522

permissible_touch_voltage_en50522(t_clear_s: float) -> float

Permissible touch voltage \(U_{Tp}(t_f)\) per EN 50522:2022.

Returns the maximum admissible touch voltage as a function of the fault duration \(t_f\). Up to 10 s it follows the curve of Figure 8 in its tabulated form, Table B.4 (DIN EN 50522 (VDE 0101-2):2023-10),

\[ \{(t_k, U_{Tp,k})\} \;=\; \{(0.05, 725),\ (0.10, 655),\ (0.20, 525),\ (0.50, 225),\ (1.00, 115),\ (2.00, 95),\ (5.00, 85),\ (10.0, 85)\}, \]

in s and V (rounded to 5 V in the standard), interpolated linearly in \(\log t\)–\(\log U\) between the anchors and clamped to 725 V below 50 ms. Beyond the end of the curve,

\[ U_{Tp}(t_f) \;=\; 80\,\mathrm{V} \qquad \text{for } t_f > 10\,\mathrm{s}, \]

including an earth fault that is not cleared (math.inf).

Parameters:

Name Type Description Default
t_clear_s float

Fault duration \(t_f\) in s, > 0; math.inf for an earth fault that is not cleared.

required

Returns:

Type Description
float

Permissible touch voltage \(U_{Tp}\) in V.

Raises:

Type Description
ValueError

If t_clear_s is NaN or not strictly positive.

Notes

Where the values come from in EN 50522:2022:

  • 5.4.1, Figure 8: \(U_{Tp}\) as a function of the fault duration; Annex B, B.3, Table B.4: the values of that curve from 0.05 s to 10 s. The curve is not defined beyond 10 s.
  • The note to Figure 8 (5.4.1) and the paragraph after Table B.4 (B.3): for a current-flow duration considerably longer than 10 s, 80 V may be used as the permissible touch voltage.
  • 5.4.1 assumes that every earth fault is cleared, automatically or by hand, so that no touch voltage of very long or unlimited duration occurs. A resonant-earthed network can carry its earth fault for hours, which is where the 80 V value matters.

The helper uses 80 V for every \(t_f > 10\,\mathrm{s}\) instead of continuing the 85 V end value of Table B.4: 80 V is below 85 V, on the safe side where the curve gives no value. Hence the step from 85 V at 10 s to 80 V just above. Up to the 2026.11 development snapshots an opt-in keyword selected the 80 V and the default returned 85 V; v0.15.0 returned 85 V and rejected math.inf.

Review pass 10 (10.42) checked the anchors against the standard text: they are the published values. A secondary reproduction quoted in the review (716 / 654 / 537 / 220 / 117 / 96 / 86 / 85 V) does not match EN 50522:2022. Compare the value with touch_voltage(), touch_voltage_at_part() or touch_voltage_envelope() (or, with additional resistances, use permissible_prospective_touch_voltage_en50522()).

Source code in src/groundfield/postprocess/safety.py
def permissible_touch_voltage_en50522(t_clear_s: float) -> float:
    """Permissible touch voltage :math:`U_{Tp}(t_f)` per EN 50522:2022.

    Returns the maximum admissible touch voltage as a function of the
    fault duration :math:`t_f`. Up to 10 s it follows the curve of
    Figure 8 in its tabulated form, Table B.4 (DIN EN 50522
    (VDE 0101-2):2023-10),

    .. math::

        \\{(t_k, U_{Tp,k})\\} \\;=\\;
        \\{(0.05, 725),\\ (0.10, 655),\\ (0.20, 525),\\
        (0.50, 225),\\ (1.00, 115),\\ (2.00, 95),\\
        (5.00, 85),\\ (10.0, 85)\\},

    in s and V (rounded to 5 V in the standard), interpolated linearly in
    :math:`\\log t`–:math:`\\log U` between the anchors and clamped to
    725 V below 50 ms. Beyond the end of the curve,

    .. math::

        U_{Tp}(t_f) \\;=\\; 80\\,\\mathrm{V}
        \\qquad \\text{for } t_f > 10\\,\\mathrm{s},

    including an earth fault that is not cleared (``math.inf``).

    Parameters
    ----------
    t_clear_s
        Fault duration :math:`t_f` in s, ``> 0``; ``math.inf`` for an
        earth fault that is not cleared.

    Returns
    -------
    float
        Permissible touch voltage :math:`U_{Tp}` in V.

    Raises
    ------
    ValueError
        If ``t_clear_s`` is NaN or not strictly positive.

    Notes
    -----
    Where the values come from in EN 50522:2022:

    * 5.4.1, Figure 8: :math:`U_{Tp}` as a function of the fault
      duration; Annex B, B.3, Table B.4: the values of that curve from
      0.05 s to 10 s. The curve is not defined beyond 10 s.
    * The note to Figure 8 (5.4.1) and the paragraph after Table B.4
      (B.3): for a current-flow duration considerably longer than 10 s,
      80 V may be used as the permissible touch voltage.
    * 5.4.1 assumes that every earth fault is cleared, automatically or
      by hand, so that no touch voltage of very long or unlimited
      duration occurs. A resonant-earthed network can carry its earth
      fault for hours, which is where the 80 V value matters.

    The helper uses 80 V for every :math:`t_f > 10\\,\\mathrm{s}` instead
    of continuing the 85 V end value of Table B.4: 80 V is below 85 V,
    on the safe side where the curve gives no value. Hence the step from
    85 V at 10 s to 80 V just above. Up to the 2026.11 development
    snapshots an opt-in keyword selected the 80 V and the default
    returned 85 V; v0.15.0 returned 85 V and rejected ``math.inf``.

    Review pass 10 (10.42) checked the anchors against the standard
    text: they are the published values. A secondary reproduction quoted
    in the review (716 / 654 / 537 / 220 / 117 / 96 / 86 / 85 V) does not
    match EN 50522:2022. Compare the value with :func:`touch_voltage`,
    :func:`touch_voltage_at_part` or :func:`touch_voltage_envelope`
    (or, with additional resistances, use
    :func:`permissible_prospective_touch_voltage_en50522`).
    """
    # math.isnan rejects text (TypeError) before float() could parse it.
    if math.isnan(t_clear_s) or t_clear_s <= 0.0:
        raise ValueError(f"t_clear_s must be > 0 (s), got {t_clear_s!r}.")
    t = float(t_clear_s)
    # user decision Q4: 80 V beyond the end of Figure 8 / Table B.4.
    if t > _EN50522_CURVE_END_S:
        return _EN50522_TP_LONG_DURATION
    return _loglog(t, _EN50522_TP_GRID)

step_voltage

step_voltage(result: 'FieldResult', *, position: tuple[float, float, float], direction: tuple[float, float, float] = (1.0, 0.0, 0.0), step: float = 1.0, surface_z: float | None = None, frequency_index: int = 0, world: 'World | None' = None) -> complex

Step voltage between two surface points.

Evaluates \(U_S = \varphi(\mathbf{r}_1) - \varphi(\mathbf{r}_1 + d_\text{step}\,\hat{\mathbf{e}})\) on the soil surface.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output.

required
position tuple[float, float, float]

First foot position \((x, y, z)\) in m. The \(z\) coordinate is overridden by surface_z if the latter is given; the default keeps z as supplied so callers can use the helper for buried-step studies if desired.

required
direction tuple[float, float, float]

Step direction in world coordinates. The horizontal projection is used (the \(z\) component is ignored — both feet stay on the same surface).

(1.0, 0.0, 0.0)
step float

Step length \(d_\text{step}\) in m. EN 50522 uses 1.0.

1.0
surface_z float | None

Optional explicit surface \(z\) in m. None keeps the \(z\) of position (typical for bare-foot contact at the ground surface, position = (x, y, 0.0)).

None
frequency_index int

Index into FieldResult.frequencies.

0
world 'World | None'

Optional companion world. Only used to decide whether to emit UniformCurrentFieldWarning: with the world the warning is restricted to the electrode shapes with measured ansatz errors; without it any wire within NEAR_FIELD_DISTANCE_M of a uniform-current result triggers it.

None

Returns:

Type Description
complex

Phasor \(U_S(f)\) in V.

Raises:

Type Description
ValueError

If step is not strictly positive or direction has no horizontal component.

Warns:

Type Description
UniformCurrentFieldWarning

Once per call, see the module docstring. At the corner of a 20 m × 20 m grid the uniform-current ansatz under-estimates the step voltage by 21 % (feet 1 m and 2 m outside the corner) to 28 % (feet above the corner and 1 m outside), with either kernel.

Source code in src/groundfield/postprocess/safety.py
def step_voltage(
    result: "FieldResult",
    *,
    position: tuple[float, float, float],
    direction: tuple[float, float, float] = (1.0, 0.0, 0.0),
    step: float = 1.0,
    surface_z: float | None = None,
    frequency_index: int = 0,
    world: "World | None" = None,
) -> complex:
    """Step voltage between two surface points.

    Evaluates :math:`U_S = \\varphi(\\mathbf{r}_1) -
    \\varphi(\\mathbf{r}_1 + d_\\text{step}\\,\\hat{\\mathbf{e}})`
    on the soil surface.

    Parameters
    ----------
    result
        Solver output.
    position
        First foot position :math:`(x, y, z)` in m. The :math:`z`
        coordinate is overridden by ``surface_z`` if the latter is
        given; the default keeps ``z`` as supplied so callers can use
        the helper for buried-step studies if desired.
    direction
        Step direction in world coordinates. The horizontal
        projection is used (the :math:`z` component is ignored —
        both feet stay on the same surface).
    step
        Step length :math:`d_\\text{step}` in m. EN 50522 uses ``1.0``.
    surface_z
        Optional explicit surface :math:`z` in m. ``None`` keeps the
        :math:`z` of ``position`` (typical for bare-foot contact
        at the ground surface, ``position = (x, y, 0.0)``).
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    world
        Optional companion world. Only used to decide whether to emit
        :class:`UniformCurrentFieldWarning`: with the world the warning
        is restricted to the electrode shapes with measured ansatz
        errors; without it any wire within
        :data:`NEAR_FIELD_DISTANCE_M` of a uniform-current result
        triggers it.

    Returns
    -------
    complex
        Phasor :math:`U_S(f)` in V.

    Raises
    ------
    ValueError
        If ``step`` is not strictly positive or ``direction`` has
        no horizontal component.

    Warns
    -----
    UniformCurrentFieldWarning
        Once per call, see the module docstring. At the corner of a
        20 m × 20 m grid the uniform-current ansatz under-estimates the
        step voltage by 21 % (feet 1 m and 2 m outside the corner) to 28 %
        (feet above the corner and 1 m outside), with either kernel.
    """
    if not math.isfinite(step) or step <= 0.0:
        raise ValueError(f"step must be > 0, got {step!r}.")

    e_h = _horizontal(direction)
    z0 = float(position[2]) if surface_z is None else float(surface_z)
    p1 = np.array([float(position[0]), float(position[1]), z0])
    p2 = p1 + step * e_h
    pts = np.stack([p1, p2])
    _uniform_current_caveat(result, world, pts, caller="step_voltage")

    phi = result.potential(pts, frequency_index=frequency_index)
    return complex(phi[0] - phi[1])

touch_voltage

touch_voltage(result: 'FieldResult', world: 'World', *, electrode: str, distance: float = 1.0, direction: tuple[float, float, float] = (1.0, 0.0, 0.0), surface_z: float = 0.0, frequency_index: int = 0, anchor: Anchor = 'footprint') -> complex

Touch voltage at a single point on the soil surface.

Evaluates \(U_T = U_E - \varphi(\mathbf{r}_\text{feet})\), where \(U_E\) is the cluster potential of the touched electrode. With the default anchor="footprint" the feet stand distance metres (horizontally) from the nearest wire of the electrode, on the ray that leaves the electrode's footprint in the horizontal projection of direction: 1 m outside the edge of a grid, 1 m beyond the tip of a star arm, 1 m outside a ring on either side. This is a proxy for an unknown touched part; for a known accessible metal part use touch_voltage_at_part().

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output from Engine.solve().

required
world 'World'

Companion world used to resolve the electrode geometry.

required
electrode str

Name of the touched electrode. Its cluster potential is the EPR seen by the hand.

required
distance float

Horizontal distance between the touched part and the feet, in m. EN 50522 uses 1.0.

1.0
direction tuple[float, float, float]

Side of the electrode on which the person stands, in world coordinates, seen from the length-weighted centroid of the wires. Only the horizontal projection is used (the feet stay on the surface). Defaults to +x.

(1.0, 0.0, 0.0)
surface_z float

\(z\) coordinate of the soil surface in m. Default 0.0 (groundfield convention; positive z is below ground).

0.0
frequency_index int

Index into FieldResult.frequencies. Default 0.

0
anchor Anchor

"footprint" (default since review pass 10, 10.21) measures distance from the nearest wire; "connection_point" measures it from connection_point of electrode, the rule of v0.15.0. For a hand-built grid mesh or star that is its centre, as in v0.15.0. A rectangular foundation of the generators is since 2026.11 several bonded wires — one per mesh line (audit A2G-04), one per side without cross-braces (user decision Q38) — and the electrode named after it is its local \(-y\) side, whose connection point is a corner of the rectangle (in 0.15.0 one grid mesh connected at its centre): the feet then stand around that corner. For 100 A into a generated ring at 0.8 m in 100 Ω·m the largest value on the circle (default engine, 0.5 m segments; touch_voltage_at_part() on the same circle gives the same) is 270.89 V round the corner of a 10 m × 10 m ring against 245.22 V round its centre, 229.71 against 161.76 V for 20 m × 5 m, 91.10 against 111.38 V for 30 m × 30 m and, in 5 cm of 150 Ω·m concrete, 134.24 against 120.12 V for 40 m × 10 m (audit D3A-03; with the point kernel at 0.25 m segments 1.3 … 2.2 % lower). 0.15.0, whose circle went round the centre of one grid mesh, gave 240.82, 156.07 and 109.87 V for the bare rings, and 60.30 V for the encased one, whose shell it did not model (audit R4B-09). Use the default "footprint" for generated foundations; it takes the whole foundation and does not depend on the connection point.

'footprint'

Returns:

Type Description
complex

Phasor \(U_T(f) = U_E(f) - \varphi(\mathbf{r}_\text{feet}, f)\) in V.

Raises:

Type Description
KeyError

If electrode is unknown to world or result.

ValueError

If distance is not strictly positive, direction has no horizontal component, or anchor is unknown.

Warns:

Type Description
UniformCurrentFieldWarning

Once per call, for a uniform-current result evaluated near a crowding geometry (see the module docstring).

Notes

Up to v0.15.0 the metre was measured from the connection point, so for a 20 m × 20 m grid (4 × 4 meshes, 100 A, 100 Ω·m) the feet stood above the grid and the helper reported 9.92 V where 1 m outside the edge has 61.3 V (default line kernel; 60.0 V with the point kernel, 61.6 V per segment with mom; 69.6 V with one current over the whole grid, before user decision Q30; F13 / 10.21).

Source code in src/groundfield/postprocess/safety.py
def touch_voltage(
    result: "FieldResult",
    world: "World",
    *,
    electrode: str,
    distance: float = 1.0,
    direction: tuple[float, float, float] = (1.0, 0.0, 0.0),
    surface_z: float = 0.0,
    frequency_index: int = 0,
    anchor: Anchor = "footprint",
) -> complex:
    """Touch voltage at a single point on the soil surface.

    Evaluates :math:`U_T = U_E - \\varphi(\\mathbf{r}_\\text{feet})`,
    where :math:`U_E` is the cluster potential of the touched electrode.
    With the default ``anchor="footprint"`` the feet stand ``distance``
    metres (horizontally) from the nearest wire of the electrode, on the
    ray that leaves the electrode's footprint in the horizontal
    projection of ``direction``: 1 m outside the edge of a grid, 1 m
    beyond the tip of a star arm, 1 m outside a ring on either side.
    This is a proxy for an unknown touched part; for a known accessible
    metal part use :func:`touch_voltage_at_part`.

    Parameters
    ----------
    result
        Solver output from :meth:`Engine.solve`.
    world
        Companion world used to resolve the electrode geometry.
    electrode
        Name of the touched electrode. Its cluster potential is the
        EPR seen by the hand.
    distance
        Horizontal distance between the touched part and the feet,
        in m. EN 50522 uses ``1.0``.
    direction
        Side of the electrode on which the person stands, in world
        coordinates, seen from the length-weighted centroid of the wires.
        Only the horizontal projection is used (the feet stay on the
        surface). Defaults to ``+x``.
    surface_z
        :math:`z` coordinate of the soil surface in m. Default ``0.0``
        (groundfield convention; positive ``z`` is below ground).
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.
    anchor
        ``"footprint"`` (default since review pass 10, 10.21) measures
        ``distance`` from the nearest wire; ``"connection_point"``
        measures it from :attr:`connection_point` of ``electrode``, the
        rule of v0.15.0. For a hand-built grid mesh or star that is its
        centre, as in v0.15.0. A rectangular foundation of the generators
        is since 2026.11 several bonded wires — one per mesh line (audit
        A2G-04), one per side without cross-braces (user decision Q38) —
        and the electrode named after it is its local :math:`-y` side,
        whose connection point is a corner of the rectangle (in 0.15.0 one
        grid mesh connected at its centre): the feet then stand around that
        corner. For 100 A into a generated ring at 0.8 m in 100 Ω·m the
        largest value on the circle (default engine, 0.5 m segments;
        :func:`touch_voltage_at_part` on the same circle gives the same) is
        270.89 V round the corner of a 10 m × 10 m ring against 245.22 V
        round its centre, 229.71 against 161.76 V for 20 m × 5 m, 91.10
        against 111.38 V for 30 m × 30 m and, in 5 cm of 150 Ω·m concrete,
        134.24 against 120.12 V for 40 m × 10 m (audit D3A-03; with the
        point kernel at 0.25 m segments 1.3 … 2.2 % lower). 0.15.0, whose
        circle went round the centre of one grid mesh, gave 240.82, 156.07
        and 109.87 V for the bare rings, and 60.30 V for the encased one,
        whose shell it did not model (audit R4B-09). Use the default
        ``"footprint"`` for generated foundations;
        it takes the whole foundation and does not depend on the
        connection point.

    Returns
    -------
    complex
        Phasor :math:`U_T(f) = U_E(f) - \\varphi(\\mathbf{r}_\\text{feet}, f)`
        in V.

    Raises
    ------
    KeyError
        If ``electrode`` is unknown to ``world`` or ``result``.
    ValueError
        If ``distance`` is not strictly positive, ``direction`` has no
        horizontal component, or ``anchor`` is unknown.

    Warns
    -----
    UniformCurrentFieldWarning
        Once per call, for a uniform-current result evaluated near a
        crowding geometry (see the module docstring).

    Notes
    -----
    Up to v0.15.0 the metre was measured from the connection point, so
    for a 20 m × 20 m grid (4 × 4 meshes, 100 A, 100 Ω·m) the feet stood
    above the grid and the helper reported 9.92 V where 1 m outside the
    edge has 61.3 V (default line kernel; 60.0 V with the point kernel,
    61.6 V per segment with ``mom``; 69.6 V with one current over the
    whole grid, before user decision Q30; F13 / 10.21).
    """
    _check_distance(distance)
    _check_anchor(anchor)
    e_h = _horizontal(direction)
    feet_xy = _feet_xy(world, electrode, e_h[None, :2], distance, anchor, result)[0]
    feet = np.array([[feet_xy[0], feet_xy[1], surface_z]])
    _uniform_current_caveat(result, world, feet, caller="touch_voltage")
    phi_feet = complex(result.potential(feet, frequency_index=frequency_index)[0])
    U_E = _cluster_potential(result, electrode, frequency_index)
    return U_E - phi_feet

touch_voltage_at_part

touch_voltage_at_part(result: 'FieldResult', world: 'World | None' = None, *, position: Sequence[float], bonded_to: str, distance: float = 1.0, n_angles: int | None = None, directions: 'Sequence[Sequence[float]] | None' = None, exclude: 'Sequence[Sequence[Sequence[float]]] | None' = None, surface_z: float = 0.0, frequency_index: int = 0, return_points: bool = False) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]

Touch voltage of an accessible metal part, feet distance around it.

EN 50522 defines the touch voltage between a conductive part that a person touches and the person's feet, standing 1 m away from the part. The touch points of an installation are its accessible metal parts above ground — a station housing or its door, a mast, a fence post, a cable cabinet, a service connection box — not the buried electrode. This helper takes one such part: its horizontal position \(\mathbf p\) and the electrode or junction it is bonded to, whose potential \(U_\text{part}\) it carries. The feet stand on the circle of radius \(d\) = distance around the part,

\[ \mathbf r_k = \mathbf p + d\,(\cos\theta_k, \sin\theta_k), \qquad U_{T,k} = U_\text{part} - \varphi(\mathbf r_k), \]

at n_angles equally spaced azimuths \(\theta_k = 2\pi k / n\), or only in the given directions; foot positions inside an outline of exclude (the housing or the building itself, where nobody can stand) are dropped. A part bonded to a node far from the faulted earth — a service connection box on the PEN junction of a house, a cable screen led out of a station — carries a transferred potential; U_T is then most of the earth potential rise.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output from Engine.solve().

required
world 'World | None'

Optional companion world. Only used to decide whether to emit UniformCurrentFieldWarning, as in step_voltage().

None
position Sequence[float]

Horizontal position (x, y) of the touched part in m. A third coordinate is accepted and ignored: the part stands above ground, the feet on the surface.

required
bonded_to str

Name of the electrode or junction (create_junction()) whose potential the part carries: the station earth for its housing, the PEN junction of a house for its connection box.

required
distance float

Horizontal distance between the part and the feet in m, > 0 (1.0 by EN 50522).

1.0
n_angles int | None

Number of equally spaced foot positions on the circle, >= 3; 24 when neither n_angles nor directions is given.

None
directions 'Sequence[Sequence[float]] | None'

Only these horizontal directions (2- or 3-vectors, the z component is ignored), seen from the part: for example the outside of a fence. Not together with n_angles.

None
exclude 'Sequence[Sequence[Sequence[float]]] | None'

Outlines where nobody can stand, each a polygon of vertices (x, y) or (x, y, z) in m (z ignored), e.g. the housing of a station or a building. Foot positions strictly inside an outline are dropped; positions on it (against the wall) are kept.

None
surface_z float

\(z\) coordinate of the soil surface in m. Default 0.0.

0.0
frequency_index int

Index into FieldResult.frequencies. Default 0.

0
return_points bool

Also return the foot positions.

False

Returns:

Name Type Description
angles (ndarray, shape(n))

Azimuth in radians in \([0, 2\pi)\) of each remaining foot position, seen from the part and measured from +x.

voltages np.ndarray, shape (n,), dtype complex

Touch-voltage phasor \(U_T\) in V at every foot position.

points (ndarray, shape(n, 3))

Foot positions in m; only with return_points=True.

Raises:

Type Description
KeyError

If bonded_to is neither an electrode nor a junction with a potential in result.

IndexError

If frequency_index is out of range.

ValueError

If distance is not a positive finite number, position is not a finite 2- or 3-vector, n_angles < 3, both n_angles and directions are given, a direction has no horizontal component, an outline is not a polygon, or every foot position lies inside an outline.

Warns:

Type Description
UniformCurrentFieldWarning

Once per call, for a uniform-current result evaluated near a crowding geometry (see the module docstring).

Notes

For a part on a wire of the electrode with the feet pointing away from it, the foot position is the one of touch_voltage() and so is the value. The voltage is the prospective (open-circuit) touch voltage; compare its magnitude with permissible_touch_voltage_en50522(), or with permissible_prospective_touch_voltage_en50522() when footwear or a surface layer adds resistance.

Source code in src/groundfield/postprocess/safety.py
def touch_voltage_at_part(
    result: "FieldResult",
    world: "World | None" = None,
    *,
    position: Sequence[float],
    bonded_to: str,
    distance: float = 1.0,
    n_angles: int | None = None,
    directions: "Sequence[Sequence[float]] | None" = None,
    exclude: "Sequence[Sequence[Sequence[float]]] | None" = None,
    surface_z: float = 0.0,
    frequency_index: int = 0,
    return_points: bool = False,
) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Touch voltage of an accessible metal part, feet ``distance`` around it.

    EN 50522 defines the touch voltage between a conductive part that a
    person touches and the person's feet, standing 1 m away from the
    part. The touch points of an installation are its accessible metal
    parts above ground — a station housing or its door, a mast, a fence
    post, a cable cabinet, a service connection box — not the buried
    electrode. This helper takes one such part: its horizontal position
    :math:`\\mathbf p` and the electrode or junction it is bonded to,
    whose potential :math:`U_\\text{part}` it carries. The feet stand on
    the circle of radius :math:`d` = ``distance`` around the part,

    .. math::

        \\mathbf r_k = \\mathbf p + d\\,(\\cos\\theta_k, \\sin\\theta_k),
        \\qquad
        U_{T,k} = U_\\text{part} - \\varphi(\\mathbf r_k),

    at ``n_angles`` equally spaced azimuths
    :math:`\\theta_k = 2\\pi k / n`, or only in the given ``directions``;
    foot positions inside an outline of ``exclude`` (the housing or the
    building itself, where nobody can stand) are dropped. A part bonded
    to a node far from the faulted earth — a service connection box on the
    PEN junction of a house, a cable screen led out of a station —
    carries a transferred potential; ``U_T`` is then most of the earth
    potential rise.

    Parameters
    ----------
    result
        Solver output from :meth:`Engine.solve`.
    world
        Optional companion world. Only used to decide whether to emit
        :class:`UniformCurrentFieldWarning`, as in :func:`step_voltage`.
    position
        Horizontal position ``(x, y)`` of the touched part in m. A third
        coordinate is accepted and ignored: the part stands above ground,
        the feet on the surface.
    bonded_to
        Name of the electrode or junction (:func:`~groundfield.create_junction`)
        whose potential the part carries: the station earth for its
        housing, the PEN junction of a house for its connection box.
    distance
        Horizontal distance between the part and the feet in m, ``> 0``
        (1.0 by EN 50522).
    n_angles
        Number of equally spaced foot positions on the circle, ``>= 3``;
        24 when neither ``n_angles`` nor ``directions`` is given.
    directions
        Only these horizontal directions (2- or 3-vectors, the ``z``
        component is ignored), seen from the part: for example the outside
        of a fence. Not together with ``n_angles``.
    exclude
        Outlines where nobody can stand, each a polygon of vertices
        ``(x, y)`` or ``(x, y, z)`` in m (``z`` ignored), e.g. the housing
        of a station or a building. Foot positions strictly inside an
        outline are dropped; positions on it (against the wall) are kept.
    surface_z
        :math:`z` coordinate of the soil surface in m. Default ``0.0``.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.
    return_points
        Also return the foot positions.

    Returns
    -------
    angles : np.ndarray, shape (n,)
        Azimuth in radians in :math:`[0, 2\\pi)` of each remaining foot
        position, seen from the part and measured from ``+x``.
    voltages : np.ndarray, shape (n,), dtype complex
        Touch-voltage phasor :math:`U_T` in V at every foot position.
    points : np.ndarray, shape (n, 3)
        Foot positions in m; only with ``return_points=True``.

    Raises
    ------
    KeyError
        If ``bonded_to`` is neither an electrode nor a junction with a
        potential in ``result``.
    IndexError
        If ``frequency_index`` is out of range.
    ValueError
        If ``distance`` is not a positive finite number, ``position`` is
        not a finite 2- or 3-vector, ``n_angles < 3``, both ``n_angles``
        and ``directions`` are given, a direction has no horizontal
        component, an outline is not a polygon, or every foot position
        lies inside an outline.

    Warns
    -----
    UniformCurrentFieldWarning
        Once per call, for a uniform-current result evaluated near a
        crowding geometry (see the module docstring).

    Notes
    -----
    For a part on a wire of the electrode with the feet pointing away
    from it, the foot position is the one of :func:`touch_voltage` and so
    is the value. The voltage is the prospective (open-circuit) touch
    voltage; compare its magnitude with
    :func:`permissible_touch_voltage_en50522`, or with
    :func:`permissible_prospective_touch_voltage_en50522` when footwear or
    a surface layer adds resistance.
    """
    # user decision Q3: touch points are the accessible metal parts.
    _check_distance(distance)
    origin = _horizontal_xy(position, "position")
    angles, unit = _part_directions(n_angles, directions)
    keep = _accessible(distance * unit, exclude, origin, distance)
    if not keep.any():
        raise ValueError(
            "every foot position around the part lies inside an outline of "
            "exclude; there is no accessible standing position."
        )
    angles, feet_xy = angles[keep], origin + distance * unit[keep]
    u_part = _node_potential(result, bonded_to, frequency_index)
    feet = np.column_stack([feet_xy, np.full(len(feet_xy), surface_z, dtype=float)])
    _uniform_current_caveat(result, world, feet, caller="touch_voltage_at_part")
    voltages = u_part - result.potential(feet, frequency_index=frequency_index)
    if return_points:
        return angles, voltages, feet
    return angles, voltages

touch_voltage_envelope

touch_voltage_envelope(result: 'FieldResult', world: 'World', *, electrode: str, distance: float = 1.0, n_angles: int = 24, surface_z: float = 0.0, frequency_index: int = 0, anchor: Anchor = 'footprint', interior: Interior = False, corners: bool = True, return_points: bool = False) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]

Touch voltages around an electrode, on request also inside its loops.

Walks n_angles equally spaced directions and places the feet as in touch_voltage(): with anchor="footprint" this traces the curve at distance from the electrode's wires (rounded around corners and arm tips). Equally spaced directions hit the rounded corners only by chance, and the touch voltage is largest there: the corners of a 60 m × 40 m grid lie at 33.7° from its centre, between the 30° and 45° rays of the default 24, and that envelope read 12 … 28 % low in two-layer soil (case study E03). With corners=True (the default) the feet also stand on the arc around every corner of the convex hull of the wires, nine per corner. The maximum of |U_T| is the conservative envelope used in safety verification when the touched parts are not known; where they are, touch_voltage_at_part() puts the feet around each part.

By default nothing inside the footprint is sampled: there stands the station, the house, the steel structure or the mast. Over an open-air grid such as a substation yard people walk inside the loops, and the surface potential sags there, so the touch voltage can exceed every value on the offset curve (a 20 m × 20 m perimeter loop at 0.5 m depth, 100 Ω·m, 100 A: 158 V in the centre against at most 141 V 1 m outside). For such grids interior="meshes" also evaluates the centre of every closed mesh, the analogue of the mesh voltage of IEEE Std 80 (the worst touch voltage inside a mesh of a grid, near the mesh centre).

Parameters:

Name Type Description Default
result 'FieldResult' required
world 'FieldResult' required
electrode str

Name of the touched electrode.

required
distance float

Horizontal distance from the wires in m (1.0 by EN 50522).

1.0
n_angles int

Number of equally spaced directions \(\theta_k = 2\pi k / n\) with \(k = 0, \dots, n - 1\). Must be >= 3.

24
surface_z float 0.0
frequency_index float 0.0
anchor float 0.0
interior Interior

Which closed loops are also sampled inside (review pass 10, 10.21). False (default): none, the offset curve only, for every electrode kind. "meshes": the centre of every mesh of a mesh / grid_mesh electrode, the centre of a ring, and the centre of every cell of a foundation built from bonded wires (foundation_wires(); the generators build every mesh foundation as one open polyline per wire line and every rectangle without cross-braces as one wire per side, user decision Q38), but not the inside of a closed polyline, the building-outline foundation of the generators. Use it where the inside of the loops is accessible open ground: a substation yard or another open-air grid, a ring around an open area. True: also a closed polyline, at the point inside it farthest from its wires. The modes cannot see buildings: a mesh foundation's cells lie under the house, a ring may surround a station housing or a mast foot.

False
corners bool

With anchor="footprint", also place nine feet on the arc of the offset curve around every corner of the convex hull of the wires, from one edge normal to the next (a half circle at each end of a single straight wire; none for one rod or a ring). False reproduces the equally spaced directions alone (the behaviour up to the final documentation pass of 2026.11.0). Ignored with anchor="connection_point".

True
return_points bool

Also return the foot positions.

False

Returns:

Name Type Description
angles (ndarray, shape(n))

Azimuth in radians of each foot position, measured from +x. The first n_angles entries are \(\theta_k\). The corner points follow (they lie on the offset curve too), then the interior points; both carry their azimuth seen from the centroid of the wires (0 for an interior point that coincides with it). To read the interior points alone, call once more with corners=False: they then start at index n_angles.

voltages np.ndarray, shape (n,), dtype complex

Touch-voltage phasor \(U_T\) in V at every foot position.

points (ndarray, shape(n, 3))

Foot positions in m; only with return_points=True.

Raises:

Type Description
ValueError

For n_angles < 3, a non-positive distance, an unknown anchor or an interior other than False, "meshes" and True.

Warns:

Type Description
UniformCurrentFieldWarning

Once per call, for a uniform-current result evaluated near a crowding geometry (see the module docstring).

Notes

n = n_angles plus the number of interior points and of corner points. The rule of v0.15.0 (circle around the connection point) is anchor="connection_point"; for a generated rectangular foundation that connection point is a corner since 2026.11, no longer the centre (see anchor in touch_voltage()). During the 2026.11 development the mesh sampling was the default (interior=None); it is now the explicit interior="meshes".

Source code in src/groundfield/postprocess/safety.py
def touch_voltage_envelope(
    result: "FieldResult",
    world: "World",
    *,
    electrode: str,
    distance: float = 1.0,
    n_angles: int = 24,
    surface_z: float = 0.0,
    frequency_index: int = 0,
    anchor: Anchor = "footprint",
    interior: Interior = False,
    corners: bool = True,
    return_points: bool = False,
) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Touch voltages around an electrode, on request also inside its loops.

    Walks ``n_angles`` equally spaced directions and places the feet as
    in :func:`touch_voltage`: with ``anchor="footprint"`` this traces
    the curve at ``distance`` from the electrode's wires (rounded around
    corners and arm tips). Equally spaced directions hit the rounded
    corners only by chance, and the touch voltage is largest there: the
    corners of a 60 m × 40 m grid lie at 33.7° from its centre, between
    the 30° and 45° rays of the default 24, and that envelope read 12 …
    28 % low in two-layer soil (case study E03). With ``corners=True``
    (the default) the feet also stand on the arc around every corner of
    the convex hull of the wires, nine per corner. The maximum of ``|U_T|`` is the conservative
    envelope used in safety verification when the touched parts are not
    known; where they are, :func:`touch_voltage_at_part` puts the feet
    around each part.

    By default nothing inside the footprint is sampled: there stands the
    station, the house, the steel structure or the mast. Over an open-air
    grid such as a substation yard people walk inside the loops, and the
    surface potential sags there, so the touch voltage can exceed every
    value on the offset curve (a 20 m × 20 m perimeter loop at 0.5 m
    depth, 100 Ω·m, 100 A: 158 V in the centre against at most 141 V
    1 m outside). For such grids ``interior="meshes"`` also evaluates the
    centre of every closed mesh, the analogue of the *mesh voltage* of
    IEEE Std 80 (the worst touch voltage inside a mesh of a grid, near
    the mesh centre).

    Parameters
    ----------
    result, world
        See :func:`touch_voltage`.
    electrode
        Name of the touched electrode.
    distance
        Horizontal distance from the wires in m (1.0 by EN 50522).
    n_angles
        Number of equally spaced directions
        :math:`\\theta_k = 2\\pi k / n` with :math:`k = 0, \\dots, n - 1`.
        Must be ``>= 3``.
    surface_z, frequency_index, anchor
        See :func:`touch_voltage`.
    interior
        Which closed loops are also sampled inside (review pass 10, 10.21).
        ``False`` (default): none, the offset curve only, for every
        electrode kind. ``"meshes"``: the centre of every mesh of a
        ``mesh`` / ``grid_mesh`` electrode, the centre of a ``ring``, and
        the centre of every cell of a foundation built from bonded wires
        (:func:`~groundfield.postprocess._footprint.foundation_wires`; the
        generators build every mesh foundation as one open polyline per
        wire line and every rectangle without cross-braces as one wire per
        side, user decision Q38), but not the inside of a closed
        ``polyline``, the
        building-outline foundation of the generators. Use it where the
        inside of the loops is accessible open ground: a substation yard
        or another open-air grid, a ring around an open area. ``True``:
        also a closed polyline, at the point inside it farthest from its
        wires. The modes cannot see buildings: a mesh foundation's cells
        lie under the house, a ring may surround a station housing or a
        mast foot.
    corners
        With ``anchor="footprint"``, also place nine feet on the arc of
        the offset curve around every corner of the convex hull of the
        wires, from one edge normal to the next (a half circle at each end
        of a single straight wire; none for one rod or a ring). ``False``
        reproduces the equally spaced directions alone (the behaviour up to
        the final documentation pass of 2026.11.0). Ignored with
        ``anchor="connection_point"``.
    return_points
        Also return the foot positions.

    Returns
    -------
    angles : np.ndarray, shape (n,)
        Azimuth in radians of each foot position, measured from ``+x``.
        The first ``n_angles`` entries are :math:`\\theta_k`. The corner
        points follow (they lie on the offset curve too), then the
        interior points; both carry their azimuth seen from the centroid of
        the wires (0 for an interior point that coincides with it). To
        read the interior points alone, call once more with
        ``corners=False``: they then start at index ``n_angles``.
    voltages : np.ndarray, shape (n,), dtype complex
        Touch-voltage phasor :math:`U_T` in V at every foot position.
    points : np.ndarray, shape (n, 3)
        Foot positions in m; only with ``return_points=True``.

    Raises
    ------
    ValueError
        For ``n_angles < 3``, a non-positive ``distance``, an unknown
        ``anchor`` or an ``interior`` other than ``False``, ``"meshes"``
        and ``True``.

    Warns
    -----
    UniformCurrentFieldWarning
        Once per call, for a uniform-current result evaluated near a
        crowding geometry (see the module docstring).

    Notes
    -----
    ``n = n_angles`` plus the number of interior points and of corner
    points. The rule of
    v0.15.0 (circle around the connection point) is
    ``anchor="connection_point"``; for a generated rectangular foundation
    that connection point is a corner since 2026.11, no longer the centre
    (see ``anchor`` in :func:`touch_voltage`). During the 2026.11 development the
    mesh sampling was the default (``interior=None``); it is now the
    explicit ``interior="meshes"``.
    """
    if n_angles < 3:
        raise ValueError(f"n_angles must be >= 3, got {n_angles}.")
    _check_distance(distance)
    _check_anchor(anchor)
    # user decision Q3: no interior sampling unless asked for.
    interior = _check_interior(interior)

    angles = np.linspace(0.0, 2.0 * np.pi, n_angles, endpoint=False)
    dirs = np.column_stack([np.cos(angles), np.sin(angles)])
    feet_xy = _feet_xy(world, electrode, dirs, distance, anchor, result)
    if corners and anchor == "footprint":
        fp = footprint_of(
            foundation_wires(world, electrode, getattr(result, "clusters", None))
        )
        corner = fp.corner_feet(distance)
        if len(corner):
            ref = fp.reference_point
            az = np.mod(
                np.arctan2(corner[:, 1] - ref[1], corner[:, 0] - ref[0]), 2 * np.pi
            )
            angles = np.concatenate([angles, az])
            feet_xy = np.vstack([feet_xy, corner])
    if interior is not False:
        wires = foundation_wires(world, electrode, getattr(result, "clusters", None))
        inner = interior_points_of(wires, outlines=interior is True)
        if len(inner):
            ref = footprint_of(wires).reference_point
            az = np.mod(
                np.arctan2(inner[:, 1] - ref[1], inner[:, 0] - ref[0]), 2 * np.pi
            )
            az[np.hypot(*(inner - ref).T) <= 1e-12] = 0.0
            angles = np.concatenate([angles, az])
            feet_xy = np.vstack([feet_xy, inner])
    feet = np.column_stack([feet_xy, np.full(len(feet_xy), surface_z, dtype=float)])
    _uniform_current_caveat(result, world, feet, caller="touch_voltage_envelope")
    phi_feet = result.potential(feet, frequency_index=frequency_index)
    U_E = _cluster_potential(result, electrode, frequency_index)
    voltages = U_E - phi_feet
    if return_points:
        return angles, voltages, feet
    return angles, voltages

touch_voltage_spectrum

touch_voltage_spectrum(result: 'FieldResult | Sequence[FieldResult]', world: 'World', *, electrode: str, currents: 'Sequence[complex] | Mapping[float, complex]', distance: float = 1.0, direction: tuple[float, float, float] = (1.0, 0.0, 0.0), surface_z: float = 0.0, anchor: Anchor = 'footprint', source: str | None = None) -> float

True-RMS touch voltage of a fault-current spectrum at one position.

The field problem is linear, so the touch voltage of harmonic \(k\) scales with the fault current \(I_k\) of that harmonic. With \(U_T(f_k)\) from a solve with source current \(I_\text{src}(f_k)\), the touch voltage at the fixed foot position of touch_voltage() is

\[ U_{T,\text{rms}} \;=\; \sqrt{\sum_k \left|U_T(f_k)\,\frac{I_k}{I_\text{src}(f_k)}\right|^2}, \]

the RMS value of the superposed harmonics (they are orthogonal over a period).

Parameters:

Name Type Description Default
result 'FieldResult | Sequence[FieldResult]'

One multi-frequency result, or a sequence of results whose frequencies are taken in order (for example one result per harmonic).

required
world 'World'

Companion world (geometry of the touched electrode).

required
electrode str

Name of the touched electrode.

required
currents 'Sequence[complex] | Mapping[float, complex]'

Fault current per frequency as RMS phasors (or RMS magnitudes) in A: either a sequence aligned with the frequencies of result, or a mapping {frequency_Hz: current} that covers every frequency exactly once.

required
distance float

Foot position, see touch_voltage(); the same position is used for every frequency.

1.0
direction float

Foot position, see touch_voltage(); the same position is used for every frequency.

1.0
surface_z float

Foot position, see touch_voltage(); the same position is used for every frequency.

1.0
anchor float

Foot position, see touch_voltage(); the same position is used for every frequency.

1.0
source str | None

Name of the current or voltage source the results were solved with (the denominator is its impressed or solved current); may be omitted when there is exactly one.

None

Returns:

Type Description
float

RMS touch voltage \(U_{T,\text{rms}}\) in V.

Raises:

Type Description
ValueError

If the currents do not match the frequencies, are not finite, a frequency appears in more than one result (it would be counted twice), a result carries no source snapshot or no source current per frequency (a voltage record without its solved current), or the source current is zero at some frequency.

Notes

EN 50522's permissible touch voltage is a 50 Hz curve; comparing a spectrum RMS with \(U_{Tp}\) ignores the frequency factors of IEC 60479-2 (the body tolerates more current at higher frequencies), which is conservative.

Source code in src/groundfield/postprocess/safety.py
def touch_voltage_spectrum(
    result: "FieldResult | Sequence[FieldResult]",
    world: "World",
    *,
    electrode: str,
    currents: "Sequence[complex] | Mapping[float, complex]",
    distance: float = 1.0,
    direction: tuple[float, float, float] = (1.0, 0.0, 0.0),
    surface_z: float = 0.0,
    anchor: Anchor = "footprint",
    source: str | None = None,
) -> float:
    """True-RMS touch voltage of a fault-current spectrum at one position.

    The field problem is linear, so the touch voltage of harmonic
    :math:`k` scales with the fault current :math:`I_k` of that
    harmonic. With :math:`U_T(f_k)` from a solve with source current
    :math:`I_\\text{src}(f_k)`, the touch voltage at the fixed foot
    position of :func:`touch_voltage` is

    .. math::

        U_{T,\\text{rms}} \\;=\\; \\sqrt{\\sum_k
        \\left|U_T(f_k)\\,\\frac{I_k}{I_\\text{src}(f_k)}\\right|^2},

    the RMS value of the superposed harmonics (they are orthogonal over
    a period).

    Parameters
    ----------
    result
        One multi-frequency result, or a sequence of results whose
        frequencies are taken in order (for example one result per
        harmonic).
    world
        Companion world (geometry of the touched electrode).
    electrode
        Name of the touched electrode.
    currents
        Fault current per frequency as RMS phasors (or RMS magnitudes)
        in A: either a sequence aligned with the frequencies of
        ``result``, or a mapping ``{frequency_Hz: current}`` that covers
        every frequency exactly once.
    distance, direction, surface_z, anchor
        Foot position, see :func:`touch_voltage`; the same position is
        used for every frequency.
    source
        Name of the current or voltage source the results were solved
        with (the denominator is its impressed or solved current); may be
        omitted when there is exactly one.

    Returns
    -------
    float
        RMS touch voltage :math:`U_{T,\\text{rms}}` in V.

    Raises
    ------
    ValueError
        If the currents do not match the frequencies, are not finite, a
        frequency appears in more than one result (it would be counted
        twice), a result carries no source snapshot or no source current
        per frequency (a voltage record without its solved current), or
        the source current is zero at some frequency.

    Notes
    -----
    EN 50522's permissible touch voltage is a 50 Hz curve; comparing a
    spectrum RMS with :math:`U_{Tp}` ignores the frequency factors of
    IEC 60479-2 (the body tolerates more current at higher frequencies),
    which is conservative.
    """
    results = [result] if hasattr(result, "frequencies") else list(result)
    pairs = [
        (res, k, float(f)) for res in results for k, f in enumerate(res.frequencies)
    ]
    freqs = [f for _, _, f in pairs]
    # The harmonics of a spectrum are orthogonal only at distinct
    # frequencies; a frequency carried by two results was counted twice
    # (audit 1, L4).
    ordered = sorted(freqs)
    for lo, hi in zip(ordered, ordered[1:], strict=False):
        if math.isclose(lo, hi, rel_tol=1e-9, abs_tol=1e-9):
            raise ValueError(
                f"touch_voltage_spectrum: {lo:g} Hz appears more than once among "
                "the results; give every harmonic once."
            )
    if isinstance(currents, Mapping):
        keys = [float(f) for f in currents]
        values = []
        used: set[int] = set()
        for f in freqs:
            hit = [
                i
                for i, key in enumerate(keys)
                if math.isclose(key, f, rel_tol=1e-9, abs_tol=1e-9)
            ]
            if len(hit) != 1:
                raise ValueError(
                    f"currents must give exactly one value for {f:g} Hz; "
                    f"keys: {sorted(keys)}."
                )
            used.add(hit[0])
            values.append(list(currents.values())[hit[0]])
        extra = [keys[i] for i in range(len(keys)) if i not in used]
        if extra:
            raise ValueError(f"currents has no result for frequencies {extra} Hz.")
    else:
        values = list(currents)
        if len(values) != len(pairs):
            raise ValueError(
                f"currents has {len(values)} entries but the results carry "
                f"{len(pairs)} frequencies."
            )
    i_k = np.asarray(values, dtype=complex)
    if not np.all(np.isfinite(i_k)):
        raise ValueError("currents must be finite.")

    _check_distance(distance)
    _check_anchor(anchor)
    e_h = _horizontal(direction)
    feet_xy = _feet_xy(world, electrode, e_h[None, :2], distance, anchor, results[0])[0]
    feet = np.array([[feet_xy[0], feet_xy[1], surface_z]])
    warned = set()
    total = 0.0
    for (res, k, _), i_fault in zip(pairs, i_k, strict=True):
        if res.backend not in warned:
            _uniform_current_caveat(res, world, feet, caller="touch_voltage_spectrum")
            warned.add(res.backend)
        u_t = _cluster_potential(res, electrode, k) - complex(
            res.potential(feet, frequency_index=k)[0]
        )
        total += abs(u_t * i_fault / _source_current(res, source, k)) ** 2
    return math.sqrt(total)

Current sharing

current_balance

Current sharing and split-factor analysis for a FieldResult.

This module turns the per-electrode currents stored in groundfield.solver.result.FieldResult into the engineering quantities that answer "where does the injected source current actually return?". In a TN-Ortsnetz with hundreds of houses, dozens of cable cabinets and one or more metallic return paths (PEN trunk, measurement leads, cable shields), the soil-leakage current of every cluster matters and cannot be read off electrode_currents directly without aggregation.

Quantities
  • Per-cluster soil leakage \(I_{c} = \sum_{e \in c} I_e\). With ideal galvanic bonds (cross_section=None) the cluster members share a potential \(U_c\); the cluster impedance is then \(Z_c = U_c / I_c\). Returned as a tabular summary by cluster_current_balance().
  • Per-electrode share of cluster current — what fraction of the cluster's net soil leakage flows through this specific electrode: \(s_{e \mid c} = I_e / I_c\) (complex). Returned alongside the per-electrode potential / impedance by electrode_current_table().
  • Split factor \(s = I_{c_\text{src}} / I_\text{src} = \sum_{e \in c_\text{src}} I_e / I_\text{src}\), with \(c_\text{src}\) the cluster of the source's attached_to electrode. s = 1 means the injected current leaves the source cluster entirely through the soil (no metallic short-cut to the return-path cluster). s < 1 means a metallic conductor (PEN trunk, parallel measurement lead, cable shield) carries part of the current as a parallel resistive path.

This is the galvanic current-split between parallel paths. It is not the Reduktionsfaktor in the German EVU / Schirmtechnik sense (Oeding & Oswald 2016): that latter quantity is the additional transformatorische / inductive coupling correction between a current-carrying conductor and a parallel grounding / shield conductor. The Reduktionsfaktor vanishes when the two conductors are perpendicular (no flux linkage) but the split factor still applies — the current always splits among parallel resistive paths irrespective of the geometric angle. A future helper may add the proper Reduktionsfaktor based on the Neumann mutual-inductance / Carson / Sommerfeld backends already present in groundfield.coupling.

Validity envelope
  • Frequency: quasi-static envelope \(f \le 1\,\mathrm{kHz}\).
  • Conventions: FieldResult.electrode_currents carries the per-electrode soil-leakage current in A (complex phasor), with positive sign in the direction electrode → soil. All quantities here are complex per frequency_index.
  • Cluster discovery uses FieldResult.clusters — the same map produced by every backend.
Which impedance (review pass 10, 10.18)

The Z columns of cluster_current_balance() are cluster impedances — a cluster's potential over its own soil leakage — and those of electrode_current_table() are electrode impedances \(U_e / I_e\). Neither is the input impedance a source sees (FieldResult.input_impedance(), the default quantity of groundfield.postprocess.sweep.sweep() and of the rho-f exporters). For one current source returning through remote earth the split factor links them: \(Z_\text{in} = s\,Z_c\).

cluster_current_balance

cluster_current_balance(result: 'FieldResult', *, frequency_index: int = 0) -> pd.DataFrame

Per-cluster soil leakage, potential and impedance.

Returns one row per unique galvanic cluster present in the result. The cluster impedance is computed as \(Z_c = U_c / I_c\) with \(I_c = \sum_{e \in c} I_e\) — the cluster's potential over its own soil leakage, not the input impedance a source sees when conductors carry current out of the cluster (see the module docstring). Where \(I_c = 0\) (purely passive observer cluster) the impedance columns are NaN.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output.

required
frequency_index int

Index into FieldResult.frequencies. Default 0.

0

Returns:

Type Description
DataFrame

Columns cluster_root, n_members, members (list of strings), U_re, U_im, abs_U, sum_I_re, sum_I_im, abs_sum_I, Z_re, Z_im, abs_Z, arg_Z_deg. Rows are sorted by descending abs_sum_I so the dominant clusters surface first — the typical debugging order.

Source code in src/groundfield/postprocess/current_balance.py
def cluster_current_balance(
    result: "FieldResult",
    *,
    frequency_index: int = 0,
) -> pd.DataFrame:
    """Per-cluster soil leakage, potential and impedance.

    Returns one row per *unique* galvanic cluster present in the
    result. The cluster impedance is computed as
    :math:`Z_c = U_c / I_c` with :math:`I_c = \\sum_{e \\in c} I_e`
    — the cluster's potential over its **own soil leakage**, not the
    input impedance a source sees when conductors carry current out of
    the cluster (see the module docstring). Where :math:`I_c = 0`
    (purely passive observer cluster) the impedance columns are ``NaN``.

    Parameters
    ----------
    result
        Solver output.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.

    Returns
    -------
    pandas.DataFrame
        Columns
        ``cluster_root``,
        ``n_members``,
        ``members`` (list of strings),
        ``U_re``, ``U_im``, ``abs_U``,
        ``sum_I_re``, ``sum_I_im``, ``abs_sum_I``,
        ``Z_re``, ``Z_im``, ``abs_Z``, ``arg_Z_deg``.
        Rows are sorted by descending ``abs_sum_I`` so the
        dominant clusters surface first — the typical
        debugging order.
    """
    rows = []
    for root, members in _unique_clusters(result).items():
        # Cluster potential = potential of any member (ideal cluster
        # bond -> shared phi). Use the canonical root.
        U = complex(result.electrode_potentials[root][frequency_index])
        sum_I = 0.0 + 0j
        for m in members:
            if m not in result.electrode_currents:
                continue
            sum_I += complex(result.electrode_currents[m][frequency_index])
        if sum_I != 0:
            Z = U / sum_I
        else:
            Z = complex("nan")
        rows.append(
            {
                "cluster_root": root,
                "n_members": len(members),
                "members": list(members),
                "U_re": U.real,
                "U_im": U.imag,
                "abs_U": abs(U),
                "sum_I_re": sum_I.real,
                "sum_I_im": sum_I.imag,
                "abs_sum_I": abs(sum_I),
                "Z_re": Z.real if np.isfinite(Z.real) else float("nan"),
                "Z_im": Z.imag if np.isfinite(Z.imag) else float("nan"),
                "abs_Z": (
                    abs(Z)
                    if (np.isfinite(Z.real) and np.isfinite(Z.imag))
                    else float("nan")
                ),
                "arg_Z_deg": (
                    math.degrees(cmath.phase(Z))
                    if (np.isfinite(Z.real) and np.isfinite(Z.imag))
                    else float("nan")
                ),
            }
        )
    df = pd.DataFrame(rows)
    if not df.empty:
        df = df.sort_values("abs_sum_I", ascending=False).reset_index(drop=True)
    return df

electrode_current_table

electrode_current_table(result: 'FieldResult', world: 'World | None' = None, *, frequency_index: int = 0) -> pd.DataFrame

Per-electrode potential, current and share of cluster current.

For each electrode in the result the table reports the potential \(U_e\) (= cluster potential), the soil-leakage current \(I_e\), the implied two-terminal impedance \(Z_e = U_e / I_e\) (the electrode's own leakage impedance, quantity="electrode" in the sweep / rho-f helpers), and the fractional share of the cluster total \(s_{e \mid c} = I_e / I_c\). The latter is the engineering key indicator for "of all the soil current leaving cluster c, how much physically flows through this specific electrode" — useful when looking at a single transformer station with a ring + several rods, or a building cluster with multiple foundation parts.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output.

required
world 'World | None'

Optional companion world. When given, the table includes the electrode kind (rod / ring / mesh / ...) and the connection-point depth in metres — a small but very helpful annotation when scanning a 200-EFH typical run.

None
frequency_index int

Index into FieldResult.frequencies. Default 0.

0

Returns:

Type Description
DataFrame

Columns name, cluster_root, kind (if world), depth_m (if world), U_re, U_im, abs_U, I_re, I_im, abs_I, Z_re, Z_im, abs_Z, arg_Z_deg, share_of_cluster_re, share_of_cluster_im, share_of_cluster_pct. Sorted by descending abs_I.

Source code in src/groundfield/postprocess/current_balance.py
def electrode_current_table(
    result: "FieldResult",
    world: "World | None" = None,
    *,
    frequency_index: int = 0,
) -> pd.DataFrame:
    """Per-electrode potential, current and share of cluster current.

    For each electrode in the result the table reports the
    potential :math:`U_e` (= cluster potential), the soil-leakage
    current :math:`I_e`, the implied two-terminal impedance
    :math:`Z_e = U_e / I_e` (the electrode's own leakage impedance,
    ``quantity="electrode"`` in the sweep / rho-f helpers), and the
    **fractional share** of the
    cluster total :math:`s_{e \\mid c} = I_e / I_c`. The latter is
    the engineering key indicator for "of all the soil current
    leaving cluster *c*, how much physically flows through this
    specific electrode" — useful when looking at a single
    transformer station with a ring + several rods, or a building
    cluster with multiple foundation parts.

    Parameters
    ----------
    result
        Solver output.
    world
        Optional companion world. When given, the table includes
        the electrode kind (``rod`` / ``ring`` / ``mesh`` / ...)
        and the connection-point depth in metres — a small but
        very helpful annotation when scanning a 200-EFH typical run.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.

    Returns
    -------
    pandas.DataFrame
        Columns
        ``name``, ``cluster_root``, ``kind`` (if ``world``),
        ``depth_m`` (if ``world``),
        ``U_re``, ``U_im``, ``abs_U``,
        ``I_re``, ``I_im``, ``abs_I``,
        ``Z_re``, ``Z_im``, ``abs_Z``, ``arg_Z_deg``,
        ``share_of_cluster_re``, ``share_of_cluster_im``,
        ``share_of_cluster_pct``. Sorted by descending ``abs_I``.
    """
    # Map every electrode to its cluster root and to the cluster's
    # net soil-leakage current at the chosen frequency.
    cluster_root_of: dict[str, str] = {}
    cluster_sum_I: dict[str, complex] = {}
    for root, members in _unique_clusters(result).items():
        s = 0.0 + 0j
        for m in members:
            if m in result.electrode_currents:
                s += complex(result.electrode_currents[m][frequency_index])
        cluster_sum_I[root] = s
        for m in members:
            cluster_root_of[m] = root

    geo_lookup: dict[str, tuple[str, float]] = {}
    if world is not None:
        for e in world.electrodes:
            cp = e.connection_point
            geo_lookup[e.name] = (e.kind, float(cp[2]))

    rows = []
    for name in sorted(result.electrode_potentials.keys()):
        U = complex(result.electrode_potentials[name][frequency_index])
        I = complex(
            result.electrode_currents.get(name, [0.0 + 0j] * (frequency_index + 1))[
                frequency_index
            ]
        )
        if I != 0:
            Z = U / I
        else:
            Z = complex("nan")
        root = cluster_root_of.get(name, name)
        I_c = cluster_sum_I.get(root, 0.0 + 0j)
        if I_c != 0:
            s_e = I / I_c
            s_pct = abs(s_e) * 100.0
        else:
            s_e = complex("nan")
            s_pct = float("nan")

        row: dict[str, object] = {
            "name": name,
            "cluster_root": root,
        }
        if world is not None:
            kind, depth = geo_lookup.get(name, ("?", float("nan")))
            row["kind"] = kind
            row["depth_m"] = depth
        row.update(
            {
                "U_re": U.real,
                "U_im": U.imag,
                "abs_U": abs(U),
                "I_re": I.real,
                "I_im": I.imag,
                "abs_I": abs(I),
                "Z_re": Z.real if np.isfinite(Z.real) else float("nan"),
                "Z_im": Z.imag if np.isfinite(Z.imag) else float("nan"),
                "abs_Z": (
                    abs(Z)
                    if (np.isfinite(Z.real) and np.isfinite(Z.imag))
                    else float("nan")
                ),
                "arg_Z_deg": (
                    math.degrees(cmath.phase(Z))
                    if (np.isfinite(Z.real) and np.isfinite(Z.imag))
                    else float("nan")
                ),
                "share_of_cluster_re": (
                    s_e.real if np.isfinite(s_e.real) else float("nan")
                ),
                "share_of_cluster_im": (
                    s_e.imag if np.isfinite(s_e.imag) else float("nan")
                ),
                "share_of_cluster_pct": s_pct,
            }
        )
        rows.append(row)
    df = pd.DataFrame(rows)
    if not df.empty:
        df = df.sort_values("abs_I", ascending=False).reset_index(drop=True)
    return df

plot_current_sharing

plot_current_sharing(result: 'FieldResult', world: 'World | None' = None, *, by: Literal['electrode', 'cluster'] = 'electrode', top_n: int = 15, frequency_index: int = 0, figsize: tuple[float, float] = (8.0, 5.0), title: str | None = None)

Bar chart of the top_n current contributors.

Renders |I| (in A) for either every electrode or every galvanic cluster, sorted descending. The default by = "electrode" is the default — which physical electrode actually carries the test current? The companion option by = "cluster" aggregates over each cluster.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output.

required
world 'World | None'

Optional companion world. Forwarded to electrode_current_table() for the kind / depth annotations; ignored otherwise.

None
by Literal['electrode', 'cluster']

"electrode" (default) or "cluster".

'electrode'
top_n int

Maximum number of bars to render. Smaller contributors are truncated. Pass 0 to render all.

15
frequency_index int

Index into FieldResult.frequencies.

0
figsize tuple[float, float]

Matplotlib figure size in inches.

(8.0, 5.0)
title str | None

Optional title override.

None

Returns:

Type Description
Figure

Raises:

Type Description
ValueError

If by is neither "electrode" nor "cluster".

Source code in src/groundfield/postprocess/current_balance.py
def plot_current_sharing(
    result: "FieldResult",
    world: "World | None" = None,
    *,
    by: Literal["electrode", "cluster"] = "electrode",
    top_n: int = 15,
    frequency_index: int = 0,
    figsize: tuple[float, float] = (8.0, 5.0),
    title: str | None = None,
):
    """Bar chart of the ``top_n`` current contributors.

    Renders ``|I|`` (in A) for either every electrode or every
    galvanic cluster, sorted descending. The default ``by =
    "electrode"`` is the default — *which physical electrode
    actually carries the test current?* The companion option
    ``by = "cluster"`` aggregates over each cluster.

    Parameters
    ----------
    result
        Solver output.
    world
        Optional companion world. Forwarded to
        :func:`electrode_current_table` for the kind / depth
        annotations; ignored otherwise.
    by
        ``"electrode"`` (default) or ``"cluster"``.
    top_n
        Maximum number of bars to render. Smaller contributors are
        truncated. Pass ``0`` to render all.
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    figsize
        Matplotlib figure size in inches.
    title
        Optional title override.

    Returns
    -------
    matplotlib.figure.Figure

    Raises
    ------
    ValueError
        If ``by`` is neither ``"electrode"`` nor ``"cluster"``.
    """
    import matplotlib.pyplot as plt

    if by == "electrode":
        df = electrode_current_table(
            result, world=world, frequency_index=frequency_index
        )
        labels = df["name"].tolist()
        magnitudes = df["abs_I"].to_numpy()
        ylabel = "|I| in A (per electrode)"
    elif by == "cluster":
        df = cluster_current_balance(result, frequency_index=frequency_index)
        labels = df["cluster_root"].tolist()
        magnitudes = df["abs_sum_I"].to_numpy()
        ylabel = "|ΣI| in A (per cluster)"
    else:
        raise ValueError(f"by must be 'electrode' or 'cluster', got {by!r}.")

    if top_n and top_n > 0:
        labels = labels[:top_n]
        magnitudes = magnitudes[:top_n]

    fig, ax = plt.subplots(figsize=figsize)
    ax.bar(range(len(labels)), magnitudes, color="C0")
    ax.set_xticks(range(len(labels)))
    ax.set_xticklabels(labels, rotation=45, ha="right")
    ax.set_ylabel(ylabel)
    ax.grid(True, axis="y", alpha=0.3)

    if title is None:
        f_hz = result.frequencies[frequency_index]
        suffix = f"top {top_n}" if (top_n and top_n > 0) else "all"
        title = f"Current sharing by {by} — {suffix}, f = {f_hz:g} Hz"
    ax.set_title(title)
    fig.tight_layout()
    return fig

split_factor

split_factor(result: 'FieldResult', world: 'World', *, source_name: str | None = None, frequency_index: int = 0) -> complex

Split factor \(s = I_{c_\text{src}} / I_\text{src}\).

Computes the galvanic split factor of a current source: the fraction of the injected current that leaves the source cluster through the soil rather than through any metallic parallel path (PEN trunk, parallel measurement lead, cable shield).

Mathematically

\[ s \;=\; \frac{\sum_{e \in c_\text{src}} I_e}{I_\text{src}}, \]

with \(c_\text{src}\) the galvanic cluster of the source's attached_to electrode and \(I_\text{src}\) the complex phasor of the source. By construction:

  • For a stand-alone source on an electrode without metallic parallel paths, KCL forces \(s = 1 + 0\,j\). The injected current leaves the cluster entirely through the soil.
  • For a source whose cluster is connected to another grounding cluster (e.g. the auxiliary electrode of a fall-of-potential measurement) by a metallic conductor, \(s < 1\). The smaller the conductor's series impedance, the smaller \(s\).
  • The complex argument \(\arg s\) reveals the inductive content of the parallel path — a Carson- or Sommerfeld- corrected lead at frequency >0 produces an imaginary share.
  • For a source returning through remote earth it links the input impedance and the cluster impedance of the feeding cluster, \(Z_\text{in} = s\,Z_c\) (review pass 10, 10.18).

The denominator \(I_\text{src}\) is the source current of the solve, read from the snapshot FieldResult.sources when the result carries one (since review pass 10); otherwise from the world's source. For a voltage source it is the solved source current (since 2026.11).

Not to be confused with the Reduktionsfaktor

In the German EVU / Schirmtechnik literature (Oeding & Oswald 2016), the Reduktionsfaktor refers to the transformatorische / inductive coupling correction between a current-carrying conductor and a parallel grounding / shield conductor. That quantity is angle-dependent: it vanishes when the two conductors are perpendicular (no flux linkage) but is large for collinear runs.

The split factor implemented here is purely galvanic — the resistive division of current across parallel paths. It is present whenever there are multiple parallel paths, regardless of their geometric orientation.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output.

required
world 'World'

Companion world used to resolve the source object.

required
source_name str | None

Optional name of the current source. None (default) picks the unique current source; raises if the world contains more than one.

None
frequency_index int

Index into FieldResult.frequencies. Default 0.

0

Returns:

Type Description
complex

Phasor \(s(f)\) (dimensionless).

Raises:

Type Description
ValueError

If the world has no current source, multiple current sources without explicit source_name, or the source has zero magnitude.

KeyError

If source_name does not exist among current sources, or the source's attached_to electrode is unknown to the result.

Source code in src/groundfield/postprocess/current_balance.py
def split_factor(
    result: "FieldResult",
    world: "World",
    *,
    source_name: str | None = None,
    frequency_index: int = 0,
) -> complex:
    """Split factor :math:`s = I_{c_\\text{src}} / I_\\text{src}`.

    Computes the **galvanic split factor** of a current source:
    the fraction of the injected current that leaves the source
    cluster through the **soil** rather than through any metallic
    parallel path (PEN trunk, parallel measurement lead, cable
    shield).

    Mathematically

    .. math::

        s \\;=\\; \\frac{\\sum_{e \\in c_\\text{src}} I_e}{I_\\text{src}},

    with :math:`c_\\text{src}` the galvanic cluster of the source's
    ``attached_to`` electrode and :math:`I_\\text{src}` the complex
    phasor of the source. By construction:

    * For a stand-alone source on an electrode without metallic
      parallel paths, KCL forces :math:`s = 1 + 0\\,j`. The
      injected current leaves the cluster entirely through the
      soil.
    * For a source whose cluster is connected to *another*
      grounding cluster (e.g. the auxiliary electrode of a
      fall-of-potential measurement) by a metallic conductor,
      :math:`s < 1`. The smaller the conductor's series
      impedance, the smaller :math:`s`.
    * The complex argument :math:`\\arg s` reveals the inductive
      content of the parallel path — a Carson- or Sommerfeld-
      corrected lead at frequency >0 produces an imaginary share.
    * For a source returning through remote earth it links the input
      impedance and the cluster impedance of the feeding cluster,
      :math:`Z_\\text{in} = s\\,Z_c` (review pass 10, 10.18).

    The denominator :math:`I_\\text{src}` is the source current of the
    solve, read from the snapshot :attr:`FieldResult.sources` when the
    result carries one (since review pass 10); otherwise from the
    world's source. For a voltage source it is the solved source current
    (since 2026.11).

    Not to be confused with the *Reduktionsfaktor*
    -----------------------------------------------
    In the German EVU / Schirmtechnik literature (Oeding & Oswald
    2016), the *Reduktionsfaktor* refers to the **transformatorische
    / inductive coupling correction** between a current-carrying
    conductor and a parallel grounding / shield conductor. That
    quantity is angle-dependent: it vanishes when the two conductors
    are perpendicular (no flux linkage) but is large for collinear
    runs.

    The split factor implemented here is **purely galvanic** — the
    resistive division of current across parallel paths. It is
    present whenever there are multiple parallel paths, regardless
    of their geometric orientation.

    Parameters
    ----------
    result
        Solver output.
    world
        Companion world used to resolve the source object.
    source_name
        Optional name of the current source. ``None`` (default)
        picks the unique current source; raises if the world
        contains more than one.
    frequency_index
        Index into :attr:`FieldResult.frequencies`. Default 0.

    Returns
    -------
    complex
        Phasor :math:`s(f)` (dimensionless).

    Raises
    ------
    ValueError
        If the world has no current source, multiple current
        sources without explicit ``source_name``, or the source
        has zero magnitude.
    KeyError
        If ``source_name`` does not exist among current sources,
        or the source's ``attached_to`` electrode is unknown to
        the result.
    """
    source = _resolve_source(world, source_name)
    I_src = _solved_source_current(result, source, frequency_index)
    if abs(I_src) == 0.0:
        raise ValueError(
            f"Source '{source.name}' has zero magnitude — split factor is undefined."
        )

    attached = source.attached_to
    members = result.clusters.get(attached, [attached])
    if not members:
        raise KeyError(
            f"Source '{source.name}' is attached to '{attached}', "
            "which has no cluster entry in the result."
        )

    sum_I = 0.0 + 0j
    for m in members:
        if m in result.electrode_currents:
            sum_I += complex(result.electrode_currents[m][frequency_index])
    return sum_I / I_src

Sweeps and convergence studies

sweep

Cartesian-product parameter sweeps for parameter axis studies.

This module turns the typical study axes — soil resistivity \(\rho_1\) / \(\rho_2\), layer thickness \(h_1\), electrode geometry, frequency — into a single tabular response that is cheap to plot and easy to feed into vector-fitting, \(\rho\)-\(f\) regression, or downstream groundinsight.

API surface

sweep() Walk the Cartesian product of an arbitrary number of named axes, build a fresh World (and optionally a fresh Engine) per combination, solve, and extract a scalar response per frequency. Returns a long-format pandas.DataFrame with one row per (axis values × frequency). plot_sweep_lines() Line plot of one response column against a chosen axis, optionally with one curve per value of a second axis. plot_sweep_heatmap() Pivot-table heatmap of one response column over a (x_axis, y_axis) pair (e.g. \(\rho_1\) vs. \(h_1\)).

Mathematical / physical content

The default response extractor reports one impedance per frequency, selected by quantity (review pass 10, 10.18):

  • "input" (default) — the input (driving-point) impedance \(Z_\text{in} = (\varphi_a - \varphi_r) / I_s\) of the current source: what a measurement instrument or a fault sees at the feeding point (FieldResult.input_impedance());
  • "cluster" — the cluster impedance \(Z_c = \varphi_c / \sum_{e \in c} I_e\) of the source's galvanic cluster over its own soil leakage (the default up to v0.15.0);
  • "electrode" — \(\varphi_e / I_e\) of the feeding electrode alone.

As soon as conductors (PEN, shields, leads) carry part of the injected current away, the cluster impedance describes only the local electrode: for a station with three houses on a PEN it is 1.79 times the input impedance (1.26 times with one house, 3.09 times with eight; review pass 10). The response is the engineering \(Z(\rho_1, h_1, f)\) curve that groundfield.postprocess.rho_f_standard and groundfield.postprocess.vector_fitting consume.

Validity envelope
  • Frequency: quasi-static envelope \(f \le 1\,\mathrm{kHz}\).
  • Linearity: the sweep does not interpolate between samples — for a smooth \(Z(\rho, f)\) surface, hand the resulting DataFrame to fit_rho_f_standard() / fit_to_sympy_standard().
  • Cost: every Cartesian combination triggers one full Engine.solve(). For 50 ρ-values × 10 h-values × 1 frequency list with N segments each, expect 500 dense system solves; budget accordingly with expected_segments().
  • Parallelism: the combinations are independent, so sweep(..., n_jobs=k) solves them in k worker processes (review pass 10, 10.64). The dense LU factorisation is only 0.2–1.5 % of a solve (kernel assembly dominates), so a multi-threaded BLAS does not parallelise a solve; separate processes do (measured 1.98× on 2 workers for a 20-house world). Workers run their BLAS on one thread; the result is bit-identical to the serial run when the calling process also runs a single-threaded BLAS (results differ at the 1e-15 level between 1 and 2 BLAS threads).

plot_sweep_heatmap

plot_sweep_heatmap(df: DataFrame, *, x: str, y: str, response: str = 'abs_Z', frequency_Hz: float | None = None, agg: str = 'mean', cmap: str = 'viridis', figsize: tuple[float, float] = (7.5, 5.5), title: str | None = None)

Heatmap of response over the (x, y) axis pair.

Pivot-tables df by y (rows) and x (columns), aggregating response with the chosen agg (default "mean" — useful when the sweep contains additional axes that should collapse). Selects a single frequency slice when frequency_Hz is given.

Parameters:

Name Type Description Default
df DataFrame

Long-format DataFrame from sweep().

required
x str

Column names for the heatmap axes. Both must be numeric.

required
y str

Column names for the heatmap axes. Both must be numeric.

required
response str

Column to colour-code. Default "abs_Z".

'abs_Z'
frequency_Hz float | None

If given and the DataFrame has a frequency_Hz column, keep only rows that match this frequency. Raises if no rows match.

None
agg str

Aggregation passed to pd.DataFrame.pivot_table(). Default "mean".

'mean'
cmap str

Standard matplotlib options.

'viridis'
figsize str

Standard matplotlib options.

'viridis'
title str

Standard matplotlib options.

'viridis'

Returns:

Type Description
Figure

Raises:

Type Description
KeyError

If x, y or response is not a column of df.

ValueError

If frequency_Hz is given and no row matches it.

Source code in src/groundfield/postprocess/sweep.py
def plot_sweep_heatmap(
    df: pd.DataFrame,
    *,
    x: str,
    y: str,
    response: str = "abs_Z",
    frequency_Hz: float | None = None,
    agg: str = "mean",
    cmap: str = "viridis",
    figsize: tuple[float, float] = (7.5, 5.5),
    title: str | None = None,
):
    """Heatmap of ``response`` over the ``(x, y)`` axis pair.

    Pivot-tables ``df`` by ``y`` (rows) and ``x`` (columns),
    aggregating ``response`` with the chosen ``agg`` (default
    ``"mean"`` — useful when the sweep contains additional axes
    that should collapse). Selects a single frequency slice
    when ``frequency_Hz`` is given.

    Parameters
    ----------
    df
        Long-format DataFrame from :func:`sweep`.
    x, y
        Column names for the heatmap axes. Both must be numeric.
    response
        Column to colour-code. Default ``"abs_Z"``.
    frequency_Hz
        If given and the DataFrame has a ``frequency_Hz`` column,
        keep only rows that match this frequency. Raises if no
        rows match.
    agg
        Aggregation passed to :meth:`pd.DataFrame.pivot_table`.
        Default ``"mean"``.
    cmap, figsize, title
        Standard matplotlib options.

    Returns
    -------
    matplotlib.figure.Figure

    Raises
    ------
    KeyError
        If ``x``, ``y`` or ``response`` is not a column of ``df``.
    ValueError
        If ``frequency_Hz`` is given and no row matches it.
    """
    import matplotlib.pyplot as plt

    for col in (x, y, response):
        if col not in df.columns:
            raise KeyError(f"column '{col}' not in DataFrame; have: {list(df.columns)}")

    sub = df
    if frequency_Hz is not None and "frequency_Hz" in df.columns:
        sub = df[df["frequency_Hz"] == frequency_Hz]
        if sub.empty:
            raise ValueError(
                f"No rows match frequency_Hz={frequency_Hz}; "
                f"available: {sorted(df['frequency_Hz'].unique())}"
            )

    pivot = sub.pivot_table(index=y, columns=x, values=response, aggfunc=agg)
    fig, ax = plt.subplots(figsize=figsize)
    im = ax.imshow(
        pivot.values,
        origin="lower",
        aspect="auto",
        extent=(
            float(pivot.columns.min()),
            float(pivot.columns.max()),
            float(pivot.index.min()),
            float(pivot.index.max()),
        ),
        cmap=cmap,
        interpolation="nearest",
    )
    fig.colorbar(im, ax=ax, label=response)
    ax.set_xlabel(x)
    ax.set_ylabel(y)
    if title is None:
        title = f"{response}({x}, {y})"
        if frequency_Hz is not None:
            title += f"  @ f = {frequency_Hz:g} Hz"
    ax.set_title(title)
    fig.tight_layout()
    return fig

plot_sweep_lines

plot_sweep_lines(df: DataFrame, *, x: str, y: str = 'abs_Z', color: str | None = None, figsize: tuple[float, float] = (8.0, 5.0), log_x: bool = False, log_y: bool = False, title: str | None = None)

Line plot of y versus x, one curve per color value.

Parameters:

Name Type Description Default
df DataFrame

Long-format DataFrame as produced by sweep().

required
x str

Column name to use on the x-axis.

required
y str

Column name of the response. Default "abs_Z".

'abs_Z'
color str | None

Optional second column name; one line per distinct value is drawn. None (default) collapses to a single line.

None
figsize tuple[float, float]

Standard matplotlib options.

(8.0, 5.0)
log_x tuple[float, float]

Standard matplotlib options.

(8.0, 5.0)
log_y tuple[float, float]

Standard matplotlib options.

(8.0, 5.0)
title tuple[float, float]

Standard matplotlib options.

(8.0, 5.0)

Returns:

Type Description
Figure

Raises:

Type Description
KeyError

If x, y or color is not a column of df.

Source code in src/groundfield/postprocess/sweep.py
def plot_sweep_lines(
    df: pd.DataFrame,
    *,
    x: str,
    y: str = "abs_Z",
    color: str | None = None,
    figsize: tuple[float, float] = (8.0, 5.0),
    log_x: bool = False,
    log_y: bool = False,
    title: str | None = None,
):
    """Line plot of ``y`` versus ``x``, one curve per ``color`` value.

    Parameters
    ----------
    df
        Long-format DataFrame as produced by :func:`sweep`.
    x
        Column name to use on the x-axis.
    y
        Column name of the response. Default ``"abs_Z"``.
    color
        Optional second column name; one line per distinct value
        is drawn. ``None`` (default) collapses to a single line.
    figsize, log_x, log_y, title
        Standard matplotlib options.

    Returns
    -------
    matplotlib.figure.Figure

    Raises
    ------
    KeyError
        If ``x``, ``y`` or ``color`` is not a column of ``df``.
    """
    import matplotlib.pyplot as plt

    if x not in df.columns:
        raise KeyError(f"column '{x}' not in DataFrame; have: {list(df.columns)}")
    if y not in df.columns:
        raise KeyError(f"column '{y}' not in DataFrame; have: {list(df.columns)}")

    fig, ax = plt.subplots(figsize=figsize)
    if color is None:
        sub = df.sort_values(x)
        ax.plot(sub[x], sub[y], marker="o")
    else:
        if color not in df.columns:
            raise KeyError(
                f"color column '{color}' not in DataFrame; have: {list(df.columns)}"
            )
        for val, sub in df.groupby(color):
            sub = sub.sort_values(x)
            ax.plot(sub[x], sub[y], marker="o", label=f"{color} = {val}")
        ax.legend()

    if log_x:
        ax.set_xscale("log")
    if log_y:
        ax.set_yscale("log")
    ax.set_xlabel(x)
    ax.set_ylabel(y)
    ax.grid(True, which="both", alpha=0.3)
    if title is None:
        title = f"{y} vs. {x}" + (f"  (color: {color})" if color else "")
    ax.set_title(title)
    fig.tight_layout()
    return fig

sweep

sweep(world_factory: Callable[..., 'World'], engine: 'Engine | Callable[..., Engine]', *, axes: dict[str, Sequence[Any]], response: Callable[['FieldResult', 'World', int], dict[str, float]] | None = None, quantity: Quantity = 'input', source: str | None = None, n_jobs: int = 1) -> pd.DataFrame

Cartesian-product parameter sweep across user-defined axes.

For every combination (a_1 = v_1, a_2 = v_2, ...) in the Cartesian product of axes, the function

  1. builds a fresh world via world_factory(**combination),
  2. resolves the engine — either the static Engine passed in or a per-combination engine via engine(**combination) if a callable is given,
  3. solves with World.solve(),
  4. iterates over every frequency in FieldResult.frequencies and extracts a row via response(result, world, frequency_index).

The axis values and frequency_Hz are added to every row automatically.

Parameters:

Name Type Description Default
world_factory Callable[..., 'World']

Callable that builds a fresh World from the per-combination kwargs. Must return a fully populated world (soil, electrodes, sources, optional conductors).

required
engine 'Engine | Callable[..., Engine]'

Either a static Engine (reused for every combination) or a callable engine(**combination) -> Engine (rebuilt per combination — useful when the segment length depends on the geometry).

required
axes dict[str, Sequence[Any]]

Mapping axis_name -> Sequence of values. Must contain at least one axis. Empty sequences raise immediately.

required
response Callable[['FieldResult', 'World', int], dict[str, float]] | None

Optional response extractor. Receives (result, world, frequency_index) and must return a dict[str, float|complex]. Defaults to the impedance selected by quantity with the columns U_E_re, U_E_im, abs_U_E, I_re, I_im, abs_I, Z_re, Z_im, abs_Z, arg_Z_deg (see the module docstring).

None
quantity Quantity

Impedance of the default response: "input" (default since review pass 10, 10.18) — the driving-point impedance of the source; "cluster" — the source cluster's potential over its own leakage (the v0.15.0 default); "electrode" — the feeding electrode's own U/I. Only with the default response.

'input'
source str | None

Name of the current source the default response refers to; may be omitted when the world has exactly one current source (with several, v0.15.0 silently used the first one; now it raises).

None
n_jobs int

Number of worker processes (default 1: serial, in this process). -1 uses every logical CPU. With n_jobs > 1 the combinations are solved in a process pool (spawn start method, BLAS pinned to one thread per worker); rows keep the order of the serial run and warnings raised in the workers are re-issued here. world_factory, engine and response must then be picklable: module-level functions or an Engine, not lambdas or functions defined in a notebook (put those into a small .py module).

1

Returns:

Type Description
DataFrame

Long-format. Columns are the axis names, frequency_Hz, and every key returned by response. One row per Cartesian-product point per frequency. With the default response, df.attrs["impedance_quantity"] records quantity.

Raises:

Type Description
ValueError

If axes is empty or any axis is empty, quantity is unknown, quantity / source are combined with a custom response, the default response finds several current sources and source is omitted, or n_jobs is 0 or below -1.

TypeError

With n_jobs > 1, if a callable cannot be sent to the worker processes.

Notes

With n_jobs > 1 the result is bit-identical to n_jobs=1 when the calling process runs a single-threaded BLAS as well (OPENBLAS_NUM_THREADS=1); otherwise the two agree to round-off. Process start-up costs about a second per worker, so parallel runs pay off for solves of a second or more.

Source code in src/groundfield/postprocess/sweep.py
def sweep(
    world_factory: Callable[..., "World"],
    engine: "Engine | Callable[..., Engine]",
    *,
    axes: dict[str, Sequence[Any]],
    response: Callable[["FieldResult", "World", int], dict[str, float]] | None = None,
    quantity: Quantity = "input",
    source: str | None = None,
    n_jobs: int = 1,
) -> pd.DataFrame:
    """Cartesian-product parameter sweep across user-defined axes.

    For every combination ``(a_1 = v_1, a_2 = v_2, ...)`` in the
    Cartesian product of ``axes``, the function

    1. builds a fresh world via ``world_factory(**combination)``,
    2. resolves the engine — either the static :class:`Engine`
       passed in or a per-combination engine via
       ``engine(**combination)`` if a callable is given,
    3. solves with :meth:`World.solve`,
    4. iterates over every frequency in
       :attr:`FieldResult.frequencies` and extracts a row via
       ``response(result, world, frequency_index)``.

    The axis values and ``frequency_Hz`` are added to every row
    automatically.

    Parameters
    ----------
    world_factory
        Callable that builds a fresh :class:`World` from the
        per-combination kwargs. Must return a fully populated
        world (soil, electrodes, sources, optional conductors).
    engine
        Either a static :class:`Engine` (reused for every
        combination) or a callable
        ``engine(**combination) -> Engine`` (rebuilt per
        combination — useful when the segment length depends on
        the geometry).
    axes
        Mapping ``axis_name -> Sequence`` of values. Must contain
        at least one axis. Empty sequences raise immediately.
    response
        Optional response extractor. Receives
        ``(result, world, frequency_index)`` and must return a
        ``dict[str, float|complex]``. Defaults to the impedance
        selected by ``quantity`` with the columns ``U_E_re``,
        ``U_E_im``, ``abs_U_E``, ``I_re``, ``I_im``, ``abs_I``,
        ``Z_re``, ``Z_im``, ``abs_Z``, ``arg_Z_deg`` (see the module
        docstring).
    quantity
        Impedance of the default response: ``"input"`` (default since
        review pass 10, 10.18) — the driving-point impedance of the
        source; ``"cluster"`` — the source cluster's potential over its
        own leakage (the v0.15.0 default); ``"electrode"`` — the feeding
        electrode's own U/I. Only with the default response.
    source
        Name of the current source the default response refers to; may
        be omitted when the world has exactly one current source (with
        several, v0.15.0 silently used the first one; now it raises).
    n_jobs
        Number of worker processes (default 1: serial, in this process).
        ``-1`` uses every logical CPU. With ``n_jobs > 1`` the
        combinations are solved in a process pool (``spawn`` start
        method, BLAS pinned to one thread per worker); rows keep the
        order of the serial run and warnings raised in the workers are
        re-issued here. ``world_factory``, ``engine`` and ``response``
        must then be picklable: module-level functions or an
        :class:`Engine`, not lambdas or functions defined in a notebook
        (put those into a small ``.py`` module).

    Returns
    -------
    pandas.DataFrame
        Long-format. Columns are the axis names, ``frequency_Hz``,
        and every key returned by ``response``. One row per
        Cartesian-product point per frequency. With the default
        response, ``df.attrs["impedance_quantity"]`` records
        ``quantity``.

    Raises
    ------
    ValueError
        If ``axes`` is empty or any axis is empty, ``quantity`` is
        unknown, ``quantity`` / ``source`` are combined with a custom
        ``response``, the default response finds several current
        sources and ``source`` is omitted, or ``n_jobs`` is 0 or below -1.
    TypeError
        With ``n_jobs > 1``, if a callable cannot be sent to the worker
        processes.

    Notes
    -----
    With ``n_jobs > 1`` the result is bit-identical to ``n_jobs=1``
    when the calling process runs a single-threaded BLAS as well
    (``OPENBLAS_NUM_THREADS=1``); otherwise the two agree to round-off.
    Process start-up costs about a second per worker, so parallel runs
    pay off for solves of a second or more.
    """
    from groundfield.solver.engine import Engine

    if not axes:
        raise ValueError("axes must contain at least one axis.")
    for name, values in axes.items():
        if len(list(values)) == 0:
            raise ValueError(f"axis '{name}' is empty.")

    default = response is None
    response = _resolve_response(response, quantity, source, "sweep")
    if isinstance(n_jobs, bool) or not isinstance(n_jobs, int):
        raise ValueError(f"n_jobs must be an integer, got {n_jobs!r}.")
    if n_jobs == -1:
        n_jobs = os.cpu_count() or 1
    if n_jobs < 1:
        raise ValueError(f"n_jobs must be >= 1 or -1, got {n_jobs}.")

    keys = list(axes.keys())
    values_list = [list(axes[k]) for k in keys]
    combos = [dict(zip(keys, c, strict=True)) for c in itertools.product(*values_list)]

    rows: list[dict[str, Any]] = []
    if n_jobs == 1 or len(combos) == 1:
        for params in combos:
            world = world_factory(**params)
            eng = engine if isinstance(engine, Engine) else engine(**params)
            result = eng.solve(world)
            for f_idx, f_hz in enumerate(result.frequencies):
                row = dict(params)
                row["frequency_Hz"] = float(f_hz)
                row.update(response(result, world, f_idx))
                rows.append(row)
    else:
        rows = _parallel_rows(world_factory, engine, response, combos, n_jobs)
    df = pd.DataFrame(rows)
    if default:
        df.attrs["impedance_quantity"] = quantity
    return df

convergence

Convergence study over the engine's segment_length.

The PDE / field model in groundfield is a reference computation (see CLAUDE.md); to honour that role every non-trivial result should be backed up by a refinement study. This module turns the canonical "halve the segment length, watch what happens" experiment into one function call.

Mathematical / physical content

The image-family discretiser splits each electrode into segments of length \(\Delta s\). As \(\Delta s \to 0\) the multi-port grounding matrix approaches the continuous integral operator and the cluster impedance \(Z_c\) converges to the PDE-grade reference. The convergence is monotone in \(\Delta s\) for the average-potential method (cf. Sunde 1968; Tagg 1964). A practical refinement plot therefore answers two questions at once:

  • "Has my chosen \(\Delta s\) already converged within X %?" — the curve flattens out.
  • "What is the asymptotic (PDE-grade) value?" — extrapolation / Richardson if needed.
Validity envelope
  • Frequency: quasi-static envelope \(f \le 1\,\mathrm{kHz}\).
  • Backends: any image-family solver (image / image_2layer / image_nlayer / mom / mom_sommerfeld / cim / bem). FEM is supported but its mesh is generated independently — the segment_length knob does not directly control its accuracy.
  • The function copies the engine per step (the original engine is not mutated) without the validating Engine.model_copy(), whose warning capture resets every module's "shown once" registry: a warning that a plain loop over the same engines shows once was shown once per step (audit round 2, A2S-08). The segment lengths are validated here instead.

convergence_study

convergence_study(world: 'World', engine: 'Engine', *, segment_lengths: Sequence[float], response: Callable[['FieldResult', 'World', int], dict[str, float]] | None = None, quantity: Quantity = 'input', source: str | None = None) -> pd.DataFrame

Solve the same world repeatedly with refining segment_length.

For every \(\Delta s_k\) in segment_lengths the function builds a clone of the engine (only segment_length differs), solves the world, and extracts a scalar response per frequency. The returned DataFrame is sorted descending in segment_length_m so finer resolutions land on the right in the default plot.

Parameters:

Name Type Description Default
world 'World'

World to solve. Not modified.

required
engine 'Engine'

Base engine. Cloned per refinement step via an internal copy per step; the original is left untouched.

required
segment_lengths Sequence[float]

Sequence of segment lengths in metres. Must be strictly positive and contain at least two distinct values.

required
response Callable[['FieldResult', 'World', int], dict[str, float]] | None

Optional response extractor (result, world, frequency_index) -> dict. Defaults to the impedance response of groundfield.postprocess.sweep.sweep().

None
quantity Quantity

Impedance of the default response: "input" (default since review pass 10, 10.18; the driving-point impedance of the source), "cluster" (the v0.15.0 default) or "electrode". See groundfield.postprocess.sweep.sweep().

'input'
source str | None

Current source of the default response; may be omitted with a single current source.

None

Returns:

Type Description
DataFrame

Long-format. Columns segment_length_m, frequency_Hz, n_segments and every key of the response (e.g. Z_re, Z_im, abs_Z, arg_Z_deg, U_E_re, ...). With the default response df.attrs["impedance_quantity"] records quantity.

Raises:

Type Description
ValueError

If segment_lengths is empty, contains non-positive values, or has fewer than two distinct values (a convergence study below two refinement steps is meaningless); for an unknown quantity.

Source code in src/groundfield/postprocess/convergence.py
def convergence_study(
    world: "World",
    engine: "Engine",
    *,
    segment_lengths: Sequence[float],
    response: Callable[["FieldResult", "World", int], dict[str, float]] | None = None,
    quantity: Quantity = "input",
    source: str | None = None,
) -> pd.DataFrame:
    """Solve the same world repeatedly with refining ``segment_length``.

    For every :math:`\\Delta s_k` in ``segment_lengths`` the
    function builds a clone of the engine (only ``segment_length``
    differs), solves the world, and extracts a scalar response
    per frequency. The returned DataFrame is sorted **descending**
    in ``segment_length_m`` so finer resolutions land on the right
    in the default plot.

    Parameters
    ----------
    world
        World to solve. **Not modified.**
    engine
        Base engine. Cloned per refinement step via
        an internal copy per step; the original is left untouched.
    segment_lengths
        Sequence of segment lengths in metres. Must be strictly
        positive and contain at least two distinct values.
    response
        Optional response extractor ``(result, world,
        frequency_index) -> dict``. Defaults to the impedance response
        of :func:`groundfield.postprocess.sweep.sweep`.
    quantity
        Impedance of the default response: ``"input"`` (default since
        review pass 10, 10.18; the driving-point impedance of the
        source), ``"cluster"`` (the v0.15.0 default) or ``"electrode"``.
        See :func:`groundfield.postprocess.sweep.sweep`.
    source
        Current source of the default response; may be omitted with a
        single current source.

    Returns
    -------
    pandas.DataFrame
        Long-format. Columns ``segment_length_m``,
        ``frequency_Hz``, ``n_segments`` and every key of the
        response (e.g. ``Z_re``, ``Z_im``, ``abs_Z``,
        ``arg_Z_deg``, ``U_E_re``, ...). With the default response
        ``df.attrs["impedance_quantity"]`` records ``quantity``.

    Raises
    ------
    ValueError
        If ``segment_lengths`` is empty, contains non-positive
        values, or has fewer than two distinct values (a
        convergence study below two refinement steps is
        meaningless); for an unknown ``quantity``.
    """
    ds_list = [float(ds) for ds in segment_lengths]
    if len(ds_list) < 2:
        raise ValueError(
            f"segment_lengths must contain at least 2 values, got {len(ds_list)}."
        )
    if any(not (ds > 0 and math.isfinite(ds)) for ds in ds_list):
        raise ValueError(
            f"segment_lengths must be finite and strictly positive, got {ds_list}."
        )
    if len(set(ds_list)) < 2:
        raise ValueError("segment_lengths must contain at least 2 distinct values.")

    default = response is None
    response = _resolve_response(response, quantity, source, "convergence_study")

    rows: list[dict[str, Any]] = []
    for ds in ds_list:
        # Not the validating model_copy (A2S-08, see the module docstring);
        # ds is validated above.
        eng = engine._with(segment_length=ds)
        result = world.solve(eng)
        n_seg = len(result.point_sources)
        for f_idx, f_hz in enumerate(result.frequencies):
            row: dict[str, Any] = {
                "segment_length_m": ds,
                "frequency_Hz": float(f_hz),
                "n_segments": n_seg,
            }
            row.update(response(result, world, f_idx))
            rows.append(row)
    df = (
        pd.DataFrame(rows)
        .sort_values(["frequency_Hz", "segment_length_m"], ascending=[True, False])
        .reset_index(drop=True)
    )
    if default:
        df.attrs["impedance_quantity"] = quantity
    return df

plot_convergence

plot_convergence(df: DataFrame, *, response: str = 'abs_Z', reference: float | None = None, figsize: tuple[float, float] = (7.5, 4.5), title: str | None = None)

Plot response versus segment_length (one line per frequency).

The x-axis is logarithmic and inverted so finer resolutions sit on the right (the convergence "asymptote direction"). When the DataFrame contains a single frequency only, the legend is suppressed.

Parameters:

Name Type Description Default
df DataFrame

DataFrame returned by convergence_study().

required
response str

Column name to plot. Default "abs_Z".

'abs_Z'
reference float | None

Optional asymptotic value to draw as a horizontal dashed reference line — useful when an analytical reference (Sunde, Dwight, IEEE Std 80) is known.

None
figsize tuple[float, float]

Standard matplotlib options.

(7.5, 4.5)
title tuple[float, float]

Standard matplotlib options.

(7.5, 4.5)

Returns:

Type Description
Figure

Raises:

Type Description
KeyError

If df has no column response or no segment_length_m column.

Source code in src/groundfield/postprocess/convergence.py
def plot_convergence(
    df: pd.DataFrame,
    *,
    response: str = "abs_Z",
    reference: float | None = None,
    figsize: tuple[float, float] = (7.5, 4.5),
    title: str | None = None,
):
    """Plot ``response`` versus ``segment_length`` (one line per frequency).

    The x-axis is logarithmic and **inverted** so finer
    resolutions sit on the right (the convergence "asymptote
    direction"). When the DataFrame contains a single frequency
    only, the legend is suppressed.

    Parameters
    ----------
    df
        DataFrame returned by :func:`convergence_study`.
    response
        Column name to plot. Default ``"abs_Z"``.
    reference
        Optional asymptotic value to draw as a horizontal dashed
        reference line — useful when an analytical reference
        (Sunde, Dwight, IEEE Std 80) is known.
    figsize, title
        Standard matplotlib options.

    Returns
    -------
    matplotlib.figure.Figure

    Raises
    ------
    KeyError
        If ``df`` has no column ``response`` or no ``segment_length_m``
        column.
    """
    import matplotlib.pyplot as plt

    if response not in df.columns:
        raise KeyError(
            f"column '{response}' not in DataFrame; have: {list(df.columns)}"
        )
    if "segment_length_m" not in df.columns:
        raise KeyError(
            "DataFrame must have a 'segment_length_m' column "
            "(produced by convergence_study)."
        )

    fig, ax = plt.subplots(figsize=figsize)
    if "frequency_Hz" in df.columns and df["frequency_Hz"].nunique() > 1:
        for f_hz, sub in df.groupby("frequency_Hz"):
            sub = sub.sort_values("segment_length_m", ascending=False)
            ax.plot(
                sub["segment_length_m"],
                sub[response],
                marker="o",
                label=f"f = {f_hz:g} Hz",
            )
        ax.legend()
    else:
        sub = df.sort_values("segment_length_m", ascending=False)
        ax.plot(sub["segment_length_m"], sub[response], marker="o")

    if reference is not None:
        ax.axhline(
            float(reference),
            ls="--",
            color="k",
            alpha=0.6,
            label=f"reference = {reference:g}",
        )
        # Re-render legend so the reference line appears even in
        # the single-frequency case.
        ax.legend()

    ax.set_xscale("log")
    ax.invert_xaxis()  # finer ds (smaller value) on the right
    ax.set_xlabel("segment_length in m")
    ax.set_ylabel(response)
    ax.grid(True, which="both", alpha=0.3)
    if title is None:
        title = f"Convergence of {response} vs. segment_length"
    ax.set_title(title)
    fig.tight_layout()
    return fig

Vector fitting

vector_fitting

Vector fitting and SymPy export for the rho-f reduced model.

This module turns a frequency response computed by groundfield into a closed-form rational impedance expression that groundinsight can consume as BusType.impedance_formula. It is the bridge between the field-grade reference computation (groundfield) and the reduced equivalent-network model (groundinsight).

Mathematical background

For a passive, linear, time-invariant grounding cluster, the driving-point impedance \(Z(s)\) at the feed-in electrode is a rational function of the Laplace variable \(s = j\omega\). Under the \(f \le 1\,\mathrm{kHz}\) assumption the function is well approximated by a low-order partial-fraction expansion

\[ Z(s) \;\approx\; R_\infty \;+\; s\,L_\infty \;+\; \sum_{k=1}^{N_p}\,\frac{r_k}{s - p_k}, \]

with poles \(p_k\) on the negative real axis (damped RC modes) and residues \(r_k\). Complex-conjugate pole pairs are admissible too — they produce damped resonant LC-like behaviour. The fit is constructed by the Vector Fitting algorithm of Gustavsen & Semlyen 1999, which iterates pole locations to a stable solution and is the de-facto standard for transmission-line and grounding modelling.

Implementation

This module implements a clean, dependency-free version of vector fitting in NumPy:

  1. Initial pole guess: linearly spaced on the negative real axis between the smallest and largest sampled frequencies.
  2. Pole relocation via Sanathanan-Koerner-style least squares with a shared denominator (the canonical Gustavsen iteration).
  3. Residue solve given the converged poles.
  4. Stability enforcement: any pole ending up in the right half plane is reflected.

The exported SymPy expression follows the groundinsight.BusType.impedance_formula convention: a single free symbol s and arbitrary numeric constants.

References
  • Gustavsen, B. & Semlyen, A. (1999). Rational approximation of frequency domain responses by Vector Fitting. IEEE Trans. Power Delivery 14(3), 1052–1061.
  • Gustavsen, B. (2006). Improving the pole relocating properties of vector fitting. IEEE Trans. Power Delivery 21(3), 1587–1592.

PassivityReport dataclass

PassivityReport(passed: bool, min_re_Z: float, f_at_min: float, f_max: float, rho_at_min: float | None = None, rho_range: tuple[float, float] | None = None, n_points: int = 0)

Outcome of check_passivity().

Attributes:

Name Type Description
passed bool

True when \(\Re Z \ge -10^{-9} \max|Z|\) everywhere on the checked band and every value is finite.

min_re_Z float

Smallest \(\Re Z\) found, in Ω; nan if \(Z\) is not finite somewhere (f_at_min then names the frequency).

f_at_min float

Frequency of min_re_Z in Hz.

f_max float

Upper end of the checked band in Hz (the band starts at 0 Hz).

rho_at_min float | None

Soil resistivity of min_re_Z in Ω·m: the corner of the checked \(\rho\) range for a standard-form fit, the resistivity the fit belongs to for an exported vector fit, else None.

rho_range tuple[float, float] | None

Checked resistivity range (min, max) in Ω·m, or None.

n_points int

Number of grid points evaluated (before the refinement).

as_dict
as_dict() -> dict[str, object]

Strict-JSON summary; the metadata["passivity"] block of an export.

Keys: passed, min_re_Z_Ohm (None when not finite), f_at_min_Hz, rho_at_min_Ohm_m, f_checked_Hz ([0, f_max]), rho_checked_Ohm_m ([min, max] or None) and n_points.

Source code in src/groundfield/postprocess/vector_fitting.py
def as_dict(self) -> dict[str, object]:
    """Strict-JSON summary; the ``metadata["passivity"]`` block of an export.

    Keys: ``passed``, ``min_re_Z_Ohm`` (``None`` when not finite),
    ``f_at_min_Hz``, ``rho_at_min_Ohm_m``, ``f_checked_Hz``
    (``[0, f_max]``), ``rho_checked_Ohm_m`` (``[min, max]`` or
    ``None``) and ``n_points``.
    """
    finite = math.isfinite(self.min_re_Z)
    return {
        "passed": bool(self.passed),
        "min_re_Z_Ohm": float(self.min_re_Z) if finite else None,
        "f_at_min_Hz": float(self.f_at_min),
        "rho_at_min_Ohm_m": (
            None if self.rho_at_min is None else float(self.rho_at_min)
        ),
        "f_checked_Hz": [0.0, float(self.f_max)],
        "rho_checked_Ohm_m": (
            None if self.rho_range is None else [float(x) for x in self.rho_range]
        ),
        "n_points": int(self.n_points),
    }

VectorFitConvergenceWarning

Bases: UserWarning

The pole-relocation loop did not converge.

Emitted when the relative pole displacement of the last relocation step is still above 1 % after n_iter iterations (audit 2026-07-08, WP-B4 — the historic implementation ran a fixed number of blind iterations with no convergence check). Inspect VectorFitResult.pole_shift / n_iter_used and consider more iterations, a different n_poles, or weighting="inverse_magnitude" for wide-dynamic-range data.

VectorFitQualityWarning

Bases: UserWarning

The vector fit is poor, or a sample had to be corrected.

Emitted (review pass 10, 10.41) when the relative rms error rms_error / mean|Z| exceeds rms_tol (default 1 %), and when the imaginary part of a 0 Hz sample exceeds 0.1 % of its magnitude (it is discarded: a rational model with real coefficients is real at \(s = 0\)). Inspect VectorFitResult.rms_relative; try other n_poles, more samples, or weighting="inverse_magnitude".

VectorFitResult dataclass

VectorFitResult(poles: ndarray, residues: ndarray, R_inf: float, L_inf: float, rms_error: float, fit_frequencies: ndarray, fit_values: ndarray, n_iter_used: int = 0, pole_shift: float = 0.0, rms_relative: float = math.nan, quantity: str | None = None)

Result of a vector fit.

Attributes:

Name Type Description
poles ndarray

Complex poles \(p_k\) (1-D array, length \(N_p\)). Stable poles have poles.real <= 0.

residues ndarray

Complex residues \(r_k\) (same shape as poles).

R_inf float

Real constant offset \(R_\infty\) (DC residual).

L_inf float

Real proportional-to-\(s\) term \(L_\infty\) (high-frequency slope). 0 if the fit was performed without it.

rms_error float

Root-mean-square residual fitting error in \(\Omega\), taken over the input frequency points.

fit_frequencies ndarray

Frequencies (Hz) used for the fit, kept for diagnostics.

fit_values ndarray

\(Z(s)\) values used for the fit (0 Hz samples projected onto their real part).

n_iter_used, pole_shift

Iterations of the pole relocation and the last relative pole displacement.

rms_relative float

rms_error divided by the mean of \(|Z|\) (dimensionless).

quantity str | None

Impedance the samples represent when the fit was built by rho_f_from_field_result() ("input", "cluster" or "electrode"); None for raw samples.

evaluate
evaluate(frequencies: Sequence[float]) -> np.ndarray

Evaluate the fitted \(Z(s)\) at arbitrary frequencies.

Source code in src/groundfield/postprocess/vector_fitting.py
def evaluate(self, frequencies: Sequence[float]) -> np.ndarray:
    """Evaluate the fitted $Z(s)$ at arbitrary frequencies."""
    s = 2j * math.pi * np.asarray(frequencies, dtype=float)
    Z = np.full_like(s, self.R_inf, dtype=complex)
    Z = Z + self.L_inf * s
    for p, r in zip(self.poles, self.residues, strict=True):
        Z = Z + r / (s - p)
    return Z

VectorFitUnderdeterminedWarning

Bases: UserWarning

Vector fit is under- or exactly-determined.

A vector fit with n_poles poles has 2 * n_poles + extras real unknowns (residues plus optional R_inf / L_inf); the real-imag stacking of an input of length N gives 2 N equations. n_poles >= N therefore leads to an under- or exactly-determined least-squares problem. The fit can succeed numerically but is effectively an identity interpolation that carries no information beyond the input samples.

A dedicated warning category lets users opt into / out of the diagnostic with warnings.simplefilter("once", VectorFitUnderdeterminedWarning).

check_passivity

check_passivity(fit, f_max: float | None = None, *, n: int = 2001, rho_range: tuple[float, float] | None = None) -> PassivityReport

Check \(\Re Z(j 2\pi f) \ge 0\) of a fitted rho-f model on a band.

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 rational fit can violate this between or beyond its samples: review pass 10 found a 4-pole fit of passive data (rms 4.4 mΩ, no warning) with \(\Re Z = -0.019\,\Omega\) at 5.5 Hz, between the 0 Hz and 50 Hz samples (10.40 / 10.41). This is the one passivity check of the package: the groundinsight exporter runs the same implementation on the formula it writes.

Parameters:

Name Type Description Default
fit required
f_max float | None

Upper end of the band in Hz (the band starts at 0 Hz). Default: twice the highest fitted frequency, the band of the export check.

None
n int

Number of points of the linear frequency grid of a vector fit (>= 2). The grid also holds 3 n // 10 logarithmically spaced points from \(10^{-6} f_\max\), the samples and the midpoints between them, and 161 points within eight half-widths \(|\Re p|\) of every pole frequency \(|\Im p|/2\pi\), which resolve resonances narrower than any fixed grid. The ten lowest local minima of the grid are refined by a bounded scalar minimisation.

2001
rho_range tuple[float, float] | None

(rho_min, rho_max) in Ω·m for a standard-form fit; default the sampled range. \(\Re Z = k_0 + k_1\rho + k_2 f + k_4 f\rho\) is bilinear, so its minimum over the box \([\rho_\min, \rho_\max] \times [0, f_\max]\) lies at a corner and the check is exact.

None

Returns:

Type Description
PassivityReport

passed is True when every evaluated \(Z\) is finite and \(\min \Re Z \ge -10^{-9} \max |Z|\) (the tolerance absorbs round-off and the coefficient rounding of an exported formula).

Raises:

Type Description
TypeError

For an unsupported fit type.

ValueError

For f_max <= 0, n < 2 or an invalid rho_range.

Source code in src/groundfield/postprocess/vector_fitting.py
def check_passivity(
    fit,
    f_max: float | None = None,
    *,
    n: int = 2001,
    rho_range: tuple[float, float] | None = None,
) -> PassivityReport:
    """Check :math:`\\Re Z(j 2\\pi f) \\ge 0` of a fitted rho-f model on a band.

    A grounding impedance is the driving-point impedance of a passive
    one-port, so its real part is non-negative at every frequency,

    .. math::

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

    A rational fit can violate this *between* or *beyond* its samples:
    review pass 10 found a 4-pole fit of passive data (rms 4.4 mΩ, no
    warning) with :math:`\\Re Z = -0.019\\,\\Omega` at 5.5 Hz, between the
    0 Hz and 50 Hz samples (10.40 / 10.41). This is the one passivity
    check of the package: the groundinsight exporter runs the same
    implementation on the formula it writes.

    Parameters
    ----------
    fit
        :class:`VectorFitResult` or
        :class:`~groundfield.postprocess.rho_f_standard.RhoFStandardFit`.
    f_max
        Upper end of the band in Hz (the band starts at 0 Hz). Default:
        twice the highest fitted frequency, the band of the export check.
    n
        Number of points of the linear frequency grid of a vector fit
        (``>= 2``). The grid also holds ``3 n // 10`` logarithmically
        spaced points from :math:`10^{-6} f_\\max`, the samples and the
        midpoints between them, and 161 points within eight half-widths
        :math:`|\\Re p|` of every pole frequency :math:`|\\Im p|/2\\pi`,
        which resolve resonances narrower than any fixed grid. The ten
        lowest local minima of the grid are refined by a bounded scalar
        minimisation.
    rho_range
        ``(rho_min, rho_max)`` in Ω·m for a standard-form fit; default
        the sampled range. :math:`\\Re Z = k_0 + k_1\\rho + k_2 f +
        k_4 f\\rho` is bilinear, so its minimum over the box
        :math:`[\\rho_\\min, \\rho_\\max] \\times [0, f_\\max]` lies at a
        corner and the check is exact.

    Returns
    -------
    PassivityReport
        ``passed`` is ``True`` when every evaluated :math:`Z` is finite and
        :math:`\\min \\Re Z \\ge -10^{-9} \\max |Z|` (the tolerance absorbs
        round-off and the coefficient rounding of an exported formula).

    Raises
    ------
    TypeError
        For an unsupported fit type.
    ValueError
        For ``f_max <= 0``, ``n < 2`` or an invalid ``rho_range``.
    """
    return _check_passivity(fit, f_max=f_max, n=n, rho_range=rho_range)

fit_to_sympy

fit_to_sympy(fit: VectorFitResult, *, decimals: int = 6)

Convert a VectorFitResult to a SymPy expression in s.

The expression is the partial-fraction form of the fit,

\[ Z(s) \;=\; R_\infty \;+\; L_\infty \cdot s \;+\; \sum_k\,\frac{r_k}{s - p_k}, \]

with every complex-conjugate pole/residue pair combined into one real second-order term,

\[ \frac{r}{s - p} + \frac{r^*}{s - p^*} \;=\; \frac{2\,\Re(r)\,(s - \Re(p)) - 2\,\Im(r)\,\Im(p)} {(s - \Re(p))^2 + \Im(p)^2}, \]

so the expression is real for real s. It is built by the renderer the groundinsight exporter uses (one term per real pole or pole pair; review pass 10, 10.73) and is not simplified: up to the calendar release sympy.simplify merged the terms into one rational function of degree four over three.

Parameters:

Name Type Description Default
fit VectorFitResult

The vector fit.

required
decimals int

Significant digits of every floating-point coefficient (1 to 17; larger values count as 17). Each coefficient is the full-precision value correctly rounded once to decimals digits, so its relative error is at most \(\tfrac12\,10^{1-N}\) for \(N\) = decimals. Evaluated with sympy.lambdify() on reviewer R5's 98 vector fits (0 to 2 kHz), the worst deviation from VectorFitResult.evaluate(), relative to \(\max|Z|\), is \(4.0\cdot10^{-6}\) at the default 6 digits and \(4.8\cdot10^{-12}\) at 12.

6

Returns:

Type Description
Expr

Expression in the free symbol s (sympy.Symbol("s", complex=True)).

Raises:

Type Description
ValueError

If decimals is not a positive integer.

Warns:

Type Description
UserWarning

If the expression does not depend on s (a fit without poles and with \(L_\infty = 0\)).

Source code in src/groundfield/postprocess/vector_fitting.py
def fit_to_sympy(fit: VectorFitResult, *, decimals: int = 6):
    """Convert a :class:`VectorFitResult` to a SymPy expression in ``s``.

    The expression is the partial-fraction form of the fit,

    $$
    Z(s) \\;=\\; R_\\infty \\;+\\; L_\\infty \\cdot s \\;+\\;
    \\sum_k\\,\\frac{r_k}{s - p_k},
    $$

    with every complex-conjugate pole/residue pair combined into one
    real second-order term,

    $$
    \\frac{r}{s - p} + \\frac{r^*}{s - p^*}
    \\;=\\; \\frac{2\\,\\Re(r)\\,(s - \\Re(p)) -
                  2\\,\\Im(r)\\,\\Im(p)}
                 {(s - \\Re(p))^2 + \\Im(p)^2},
    $$

    so the expression is real for real ``s``. It is built by the renderer
    the ``groundinsight`` exporter uses (one term per real pole or pole
    pair; review pass 10, 10.73) and is not simplified: up to the
    calendar release ``sympy.simplify`` merged the terms into one rational
    function of degree four over three.

    Parameters
    ----------
    fit
        The vector fit.
    decimals
        Significant digits of every floating-point coefficient (1 to 17;
        larger values count as 17). Each coefficient is the full-precision
        value correctly rounded **once** to ``decimals`` digits, so its
        relative error is at most :math:`\\tfrac12\\,10^{1-N}` for
        :math:`N` = ``decimals``. Evaluated with :func:`sympy.lambdify`
        on reviewer R5's 98 vector fits (0 to 2 kHz), the worst deviation
        from :meth:`VectorFitResult.evaluate`, relative to
        :math:`\\max|Z|`, is :math:`4.0\\cdot10^{-6}` at the default
        6 digits and :math:`4.8\\cdot10^{-12}` at 12.

    Returns
    -------
    sympy.Expr
        Expression in the free symbol ``s`` (``sympy.Symbol("s",
        complex=True)``).

    Raises
    ------
    ValueError
        If ``decimals`` is not a positive integer.

    Warns
    -----
    UserWarning
        If the expression does not depend on ``s`` (a fit without poles
        and with :math:`L_\\infty = 0`).
    """
    import sympy as sp

    from groundfield.io._formula import round_coefficients

    s = sp.Symbol("s", complex=True)
    expr = round_coefficients(_partial_fractions(fit, s), decimals)

    # Defensive guard: every rho-f formula must depend on ``s``. A
    # constant Z(rho, f) silently breaks the groundinsight BusType
    # extraction, so we surface that as a ``UserWarning`` here. This
    # cannot trigger under the current ``vector_fit`` because
    # ``n_poles >= 1`` is enforced — the guard catches programmatically
    # constructed ``VectorFitResult`` objects with zero poles and zero
    # ``L_inf``.
    if s not in expr.free_symbols:
        import warnings

        warnings.warn(
            "fit_to_sympy: the resulting expression has no dependency "
            f"on the frequency-domain variable s ({expr!r}). Downstream "
            "groundinsight BusType.impedance_formula consumers expect "
            "a frequency-dependent rho-f model. Re-run vector_fit with "
            "n_poles >= 1 and at least one non-zero residue, or pass "
            "include_L_inf=True if you genuinely want a constant + "
            "inductive shoulder.",
            UserWarning,
            stacklevel=2,
        )

    return expr

rho_f_from_field_result

rho_f_from_field_result(result, electrode_name: str | None = None, *, quantity: Quantity = 'input', source: str | None = None, n_poles: int = 4, n_iter: int = 8, include_R_inf: bool = True, include_L_inf: bool = False, complex_poles: bool = True) -> VectorFitResult

Fit \(Z(s)\) to the impedance of a FieldResult.

Reads the impedance selected by quantity at every frequency in result.frequencies and runs vector_fit() on the series.

Parameters:

Name Type Description Default
result

groundfield.FieldResult produced by an Engine.solve call with at least 4–8 frequency samples.

required
electrode_name str | None

Electrode whose impedance is fitted. Required for quantity="cluster" and "electrode". With "input" it is optional; when given it must belong to the cluster the source feeds (and selects among several sources).

None
quantity Quantity

"input" (default since review pass 10, 10.19): the driving-point impedance \((\varphi_a - \varphi_r)/I_s\) of the current source (FieldResult.input_impedance()) — the impedance a groundinsight BusType stands for. "cluster": FieldResult.cluster_impedance() of electrode_name. "electrode": \(U_e/I_e\) of the named electrode alone, the quantity v0.15.0 fitted (17 % above the cluster impedance for a ring with two bonded rods).

'input'
source str | None

Current source for quantity="input"; may be omitted when the result carries exactly one.

None
n_poles int

Forwarded to vector_fit().

4
n_iter int

Forwarded to vector_fit().

4
include_R_inf int

Forwarded to vector_fit().

4
include_L_inf int

Forwarded to vector_fit().

4
complex_poles int

Forwarded to vector_fit().

4

Returns:

Type Description
VectorFitResult

Raises:

Type Description
ValueError

For an unknown quantity; for "input" on a result without source snapshot or with an electrode_name the source does not feed; for "cluster" / "electrode" without electrode_name; if the denominator current is zero at every frequency.

KeyError

If electrode_name or source is unknown.

Notes

Frequencies at which the denominator current is zero (a passive electrode, a dead column) are masked with a UserWarning instead of being entered as \(Z = 0\).

Source code in src/groundfield/postprocess/vector_fitting.py
def rho_f_from_field_result(
    result,
    electrode_name: str | None = None,
    *,
    quantity: Quantity = "input",
    source: str | None = None,
    n_poles: int = 4,
    n_iter: int = 8,
    include_R_inf: bool = True,
    include_L_inf: bool = False,
    complex_poles: bool = True,
) -> VectorFitResult:
    """Fit $Z(s)$ to the impedance of a :class:`FieldResult`.

    Reads the impedance selected by ``quantity`` at every frequency in
    ``result.frequencies`` and runs :func:`vector_fit` on the series.

    Parameters
    ----------
    result
        :class:`groundfield.FieldResult` produced by an
        ``Engine.solve`` call with at least 4–8 frequency samples.
    electrode_name
        Electrode whose impedance is fitted. Required for
        ``quantity="cluster"`` and ``"electrode"``. With ``"input"`` it
        is optional; when given it must belong to the cluster the source
        feeds (and selects among several sources).
    quantity
        ``"input"`` (default since review pass 10, 10.19): the
        driving-point impedance :math:`(\\varphi_a - \\varphi_r)/I_s`
        of the current source (:meth:`FieldResult.input_impedance`) —
        the impedance a groundinsight BusType stands for.
        ``"cluster"``: :meth:`FieldResult.cluster_impedance` of
        ``electrode_name``. ``"electrode"``: :math:`U_e/I_e` of the
        named electrode alone, the quantity v0.15.0 fitted (17 % above
        the cluster impedance for a ring with two bonded rods).
    source
        Current source for ``quantity="input"``; may be omitted when the
        result carries exactly one.
    n_poles, n_iter, include_R_inf, include_L_inf, complex_poles
        Forwarded to :func:`vector_fit`.

    Returns
    -------
    VectorFitResult

    Raises
    ------
    ValueError
        For an unknown ``quantity``; for ``"input"`` on a result without
        source snapshot or with an ``electrode_name`` the source does not
        feed; for ``"cluster"`` / ``"electrode"`` without
        ``electrode_name``; if the denominator current is zero at every
        frequency.
    KeyError
        If ``electrode_name`` or ``source`` is unknown.

    Notes
    -----
    Frequencies at which the denominator current is zero (a passive
    electrode, a dead column) are masked with a :class:`UserWarning`
    instead of being entered as :math:`Z = 0`.
    """
    z_all, i_all = impedance_series(
        result,
        quantity,
        electrode_name=electrode_name,
        source=source,
        caller="rho_f_from_field_result",
    )
    freqs = np.asarray(result.frequencies, dtype=float)
    if i_all.shape != freqs.shape:
        raise ValueError(
            "Inconsistent shapes between frequencies and electrode currents"
        )
    label = f"electrode '{electrode_name}'" if quantity != "input" else "the source"
    # Audit 2026-07-08, WP-B4 (finding N23): frequencies where the
    # denominator current vanishes (passive electrode / dead column)
    # are MASKED instead of being injected as Z = 0 samples — a
    # single dead frequency used to pull the whole fit through the
    # origin silently.
    alive = np.abs(i_all) > 0.0
    if not alive.any():
        raise ValueError(
            f"rho_f_from_field_result: {label} carries no current at any "
            "frequency — Z = U/I is undefined. Fit the driven electrode "
            "instead."
        )
    if not alive.all():
        import warnings as _warnings

        _warnings.warn(
            f"rho_f_from_field_result: {label} carries no current at "
            f"{int((~alive).sum())} of {alive.size} frequencies; those "
            "samples are excluded from the fit (historic behaviour injected "
            "Z = 0 there).",
            UserWarning,
            stacklevel=2,
        )
    fit = vector_fit(
        freqs[alive],
        z_all[alive],
        n_poles=n_poles,
        n_iter=n_iter,
        include_R_inf=include_R_inf,
        include_L_inf=include_L_inf,
        complex_poles=complex_poles,
    )
    return dataclasses.replace(fit, quantity=quantity)

vector_fit

vector_fit(frequencies: Sequence[float], Z_values: Sequence[complex], *, n_poles: int = 4, n_iter: int = 8, include_R_inf: bool = True, include_L_inf: bool = False, complex_poles: bool = True, weighting: str = 'uniform', rms_tol: float = 0.01) -> VectorFitResult

Fit a rational \(Z(s)\) approximation to a sampled frequency response.

Implements the Vector Fitting algorithm of Gustavsen & Semlyen 1999 in its single-output, equal-weight form. The denominator polynomial is shared between numerator and denominator estimation (Sanathanan-Koerner with iterative pole relocation); after n_iter outer iterations the poles are taken as fixed and the residues are solved from a final linear system.

Parameters:

Name Type Description Default
frequencies Sequence[float]

Frequency samples in Hz, length \(N\).

required
Z_values Sequence[complex]

Complex impedance samples \(Z(j2\pi f_k)\) in \(\Omega\), length \(N\).

required
n_poles int

Target number of poles. Complex-conjugate pairs count as 2 poles each.

4
n_iter int

Number of pole-relocation iterations.

8
include_R_inf bool

Whether to fit a constant offset \(R_\infty\) (DC residual).

True
include_L_inf bool

Whether to fit a \(s\cdot L_\infty\) proportional term.

False
complex_poles bool

True (default) initialises with complex-conjugate pole pairs, suitable for resonant behaviour. Set False for purely-resistive / monotonic responses.

True
weighting str

"uniform" (default, historic behaviour) or "inverse_magnitude": weights every sample by 1/|Z_n|, the standard remedy when |Z| spans several decades and the unweighted LS would fit only the largest magnitudes (audit 2026-07-08, WP-B4).

'uniform'
rms_tol float

Warn with VectorFitQualityWarning when the relative rms error rms_error / mean|Z| exceeds this value (default 0.01).

0.01

Raises:

Type Description
ValueError

If the samples are not finite, no sample has f > 0, n_poles < 1, weighting is unknown, or the least-squares problem cannot be solved (instead of numpy's LinAlgError).

Warns:

Type Description
VectorFitQualityWarning

Relative rms above rms_tol; imaginary part of a 0 Hz sample above 0.1 % of its magnitude (discarded).

(VectorFitConvergenceWarning, VectorFitUnderdeterminedWarning)

See the warning classes.

Notes

0 Hz samples (review pass 10, 10.41). The model has real coefficients, so it is real at \(s = 0\). A 0 Hz sample with an imaginary part (measured or averaged data) cannot be represented; up to v0.15.0 the pole relocation then moved a pole onto the origin and the fit collapsed to \(Z \approx 0\) at every other frequency (relative rms 0.99, 20 of 20 noisy data sets) or numpy raised LinAlgError. The 0 Hz samples are now projected onto their real part before fitting, which is bit-for-bit neutral for real 0 Hz samples (all solver output).

Since the 2026-07-08 audit (WP-B4) the least-squares systems use the conjugate-pair real basis (see _pair_basis()): complex pole pairs carry genuinely complex residues, matching the cited Gustavsen & Semlyen algorithm. The pole-relocation loop additionally monitors the relative pole displacement, breaks early below 1e-8 and warns (VectorFitConvergenceWarning) when it is still above 1 % after n_iter iterations; the diagnostics are exposed as VectorFitResult.n_iter_used / pole_shift.

Returns:

Type Description
VectorFitResult
Source code in src/groundfield/postprocess/vector_fitting.py
def vector_fit(
    frequencies: Sequence[float],
    Z_values: Sequence[complex],
    *,
    n_poles: int = 4,
    n_iter: int = 8,
    include_R_inf: bool = True,
    include_L_inf: bool = False,
    complex_poles: bool = True,
    weighting: str = "uniform",
    rms_tol: float = 0.01,
) -> VectorFitResult:
    """Fit a rational $Z(s)$ approximation to a sampled frequency response.

    Implements the Vector Fitting algorithm of Gustavsen & Semlyen
    1999 in its single-output, equal-weight form. The denominator
    polynomial is shared between numerator and denominator
    estimation (Sanathanan-Koerner with iterative pole relocation);
    after ``n_iter`` outer iterations the poles are taken as fixed
    and the residues are solved from a final linear system.

    Parameters
    ----------
    frequencies
        Frequency samples in Hz, length $N$.
    Z_values
        Complex impedance samples $Z(j2\\pi f_k)$ in $\\Omega$,
        length $N$.
    n_poles
        Target number of poles. Complex-conjugate pairs count as
        2 poles each.
    n_iter
        Number of pole-relocation iterations.
    include_R_inf
        Whether to fit a constant offset $R_\\infty$ (DC residual).
    include_L_inf
        Whether to fit a $s\\cdot L_\\infty$ proportional term.
    complex_poles
        ``True`` (default) initialises with complex-conjugate pole
        pairs, suitable for resonant behaviour. Set ``False`` for
        purely-resistive / monotonic responses.
    weighting
        ``"uniform"`` (default, historic behaviour) or
        ``"inverse_magnitude"``: weights every sample by
        ``1/|Z_n|``, the standard remedy when ``|Z|`` spans several
        decades and the unweighted LS would fit only the largest
        magnitudes (audit 2026-07-08, WP-B4).
    rms_tol
        Warn with :class:`VectorFitQualityWarning` when the relative rms
        error ``rms_error / mean|Z|`` exceeds this value (default 0.01).

    Raises
    ------
    ValueError
        If the samples are not finite, no sample has ``f > 0``,
        ``n_poles < 1``, ``weighting`` is unknown, or the least-squares
        problem cannot be solved (instead of numpy's ``LinAlgError``).

    Warns
    -----
    VectorFitQualityWarning
        Relative rms above ``rms_tol``; imaginary part of a 0 Hz sample
        above 0.1 % of its magnitude (discarded).
    VectorFitConvergenceWarning, VectorFitUnderdeterminedWarning
        See the warning classes.

    Notes
    -----
    **0 Hz samples** (review pass 10, 10.41). The model has real
    coefficients, so it is real at :math:`s = 0`. A 0 Hz sample with an
    imaginary part (measured or averaged data) cannot be represented;
    up to v0.15.0 the pole relocation then moved a pole onto the origin
    and the fit collapsed to :math:`Z \\approx 0` at every other
    frequency (relative rms 0.99, 20 of 20 noisy data sets) or numpy
    raised ``LinAlgError``. The 0 Hz samples are now projected onto
    their real part before fitting, which is bit-for-bit neutral for
    real 0 Hz samples (all solver output).

    Since the 2026-07-08 audit (WP-B4) the least-squares systems use
    the **conjugate-pair real basis** (see :func:`_pair_basis`):
    complex pole pairs carry genuinely complex residues, matching
    the cited Gustavsen & Semlyen algorithm. The pole-relocation
    loop additionally monitors the relative pole displacement,
    breaks early below ``1e-8`` and warns
    (:class:`VectorFitConvergenceWarning`) when it is still above
    1 % after ``n_iter`` iterations; the diagnostics are exposed as
    ``VectorFitResult.n_iter_used`` / ``pole_shift``.

    Returns
    -------
    VectorFitResult
    """
    frequencies = np.asarray(frequencies, dtype=float)
    Z = np.asarray(Z_values, dtype=complex)
    if frequencies.shape != Z.shape:
        raise ValueError("frequencies and Z_values must have the same shape")
    if not (np.all(np.isfinite(frequencies)) and np.all(np.isfinite(Z))):
        raise ValueError("vector_fit: frequencies and Z_values must be finite.")
    if not np.any(frequencies > 0.0):
        raise ValueError(
            "vector_fit: needs at least one sample with f > 0; a pure DC "
            "data set has no frequency dependence to fit."
        )
    dc = frequencies == 0.0
    if np.any(dc) and np.any(Z[dc].imag != 0.0):
        # A real-coefficient rational model is real at s = 0: project
        # the 0 Hz samples onto their real part (10.41). Bit-neutral for
        # real DC samples.
        worst = float(np.max(np.abs(Z[dc].imag) / np.maximum(np.abs(Z[dc]), 1e-300)))
        if worst > 1e-3:
            import warnings as _warnings

            _warnings.warn(
                "vector_fit: the 0 Hz sample has an imaginary part of "
                f"{worst:.2%} of its magnitude; it is discarded (the rational "
                "model is real at f = 0). Check the DC value of the data.",
                VectorFitQualityWarning,
                stacklevel=2,
            )
        Z = Z.copy()
        Z[dc] = Z[dc].real
    if n_poles < 1:
        raise ValueError(
            "vector_fit: n_poles must be at least 1, got "
            f"n_poles={n_poles}. n_poles == 0 produces an s-free fit "
            "whose SymPy conversion yields a constant Z(rho, f) "
            "expression without frequency dependence — that is never "
            "the intended behaviour, so this case is rejected at the "
            "API boundary."
        )
    # The previous trigger
    # ``2 * n_poles >= N`` counted 4 real DOFs per pole regardless of
    # whether the search was constrained to conjugate-symmetric pairs.
    # Under ``complex_poles=True`` (the default) the conjugate-symmetry
    # constraint halves the actual free parameters: a pair carries
    # 4 real DOFs (real pole, imag pole, real residue, imag residue),
    # and a lone unpaired real pole carries 2. The corrected formula
    # counts ``n_independent_poles = n_poles // 2 + (n_poles % 2)`` for
    # the pair-constrained search and ``n_poles`` for the all-real one.
    # The strict ``>`` in the conjugate branch keeps a uniquely
    # determined fit (e.g. ``n_poles=2, N=2``) from emitting a false
    # positive.
    if complex_poles:
        n_independent_poles = n_poles // 2 + (n_poles % 2)
        is_underdetermined = 2 * n_independent_poles > frequencies.size
    else:
        is_underdetermined = 2 * n_poles >= frequencies.size
    if is_underdetermined:
        import warnings as _warnings

        if complex_poles:
            ratio_explanation = (
                "2 * n_independent_poles > len(frequencies) is the "
                "critical ratio under complex-conjugate-pair fitting"
            )
        else:
            ratio_explanation = (
                "2 * n_poles >= len(frequencies) is the critical "
                "ratio under all-real-pole fitting"
            )
        _warnings.warn(
            "vector_fit: n_poles="
            f"{n_poles} with len(frequencies)={frequencies.size} "
            "leads to an under- or exactly-determined least-squares "
            "fit (each pole contributes residue + pole-location "
            f"DOFs; {ratio_explanation}). The numerical solve may "
            "succeed but produces an identity interpolation of the "
            "input samples that carries no information beyond the "
            "raw frequency response. Reduce n_poles to "
            f"{max(1, frequencies.size // 2 - 1)} or fewer, or supply "
            "more frequency samples.",
            VectorFitUnderdeterminedWarning,
            stacklevel=2,
        )
    if weighting not in ("uniform", "inverse_magnitude"):
        raise ValueError(
            "vector_fit: weighting must be 'uniform' or "
            f"'inverse_magnitude', got {weighting!r}."
        )
    s = 2j * math.pi * frequencies
    if weighting == "inverse_magnitude":
        w = 1.0 / np.maximum(np.abs(Z), 1e-12 * float(np.max(np.abs(Z))))
    else:
        w = np.ones(s.size)

    poles = _initial_poles(frequencies, n_poles, complex_conj=complex_poles)
    poles = _enforce_conjugate_symmetry(poles)

    # Outer loop: pole relocation. The system is, schematically,
    #   sum_k r_k / (s_n - p_k) + d + s_n*h - sum_k r'_k Z_n / (s_n - p_k)
    #     = Z_n
    # where {r_k, d, h, r'_k} are the unknowns and the new poles are
    # the zeros of the denominator polynomial 1 + sum r'_k/(s-p_k).
    # Both the numerator residues r_k and the sigma residues r'_k use
    # the conjugate-pair real basis (audit 2026-07-08, WP-B4), so
    # complex pole pairs carry genuinely complex residues.
    extras = (1 if include_R_inf else 0) + (1 if include_L_inf else 0)
    n_iter_used = 0
    pole_shift = float("inf")
    for _ in range(max(1, n_iter)):
        structure = _pole_pair_structure(poles)
        basis = _pair_basis(s, poles, structure)  # (N, n_poles)
        A = np.zeros((s.size, n_poles + extras + n_poles), dtype=complex)
        A[:, :n_poles] = basis
        col = n_poles
        if include_R_inf:
            A[:, col] = 1.0
            col += 1
        if include_L_inf:
            A[:, col] = s
            col += 1
        A[:, col : col + n_poles] = -Z[:, None] * basis

        # Solve with real-imag stacking (least-squares), optionally
        # row-weighted.
        Aw = A * w[:, None]
        M = np.vstack([Aw.real, Aw.imag])
        rhs = np.concatenate([(w * Z).real, (w * Z).imag])
        sol = _solve_lstsq(M, rhs, poles)

        # Reconstruct the complex sigma residues from the pair basis.
        sigma_residues = _coeffs_to_residues(
            sol[n_poles + extras :],
            poles,
            structure,
        )
        # New poles: eigenvalues of A_p - b·c^T where A_p = diag(poles),
        # b = ones, c = sigma_residues. (Standard Gustavsen formulation.)
        Ap = np.diag(poles)
        b = np.ones(n_poles)
        try:
            new_poles = np.linalg.eigvals(Ap - np.outer(b, sigma_residues))
        except np.linalg.LinAlgError as exc:
            raise ValueError(
                f"vector_fit: pole relocation failed ({exc}); reduce n_poles or "
                "check the samples."
            ) from exc
        new_poles = _enforce_stability(new_poles)
        new_poles = _enforce_conjugate_symmetry(new_poles)
        # Sort for deterministic order (deepest |imag| first).
        sorted_idx = np.argsort(-np.abs(new_poles.imag))
        new_poles = new_poles[sorted_idx]
        n_iter_used += 1
        scale = float(np.max(np.abs(poles))) or 1.0
        pole_shift = (
            float(np.max(np.abs(np.sort_complex(new_poles) - np.sort_complex(poles))))
            / scale
        )
        poles = new_poles
        if pole_shift < 1e-8:
            break
    if pole_shift > 1e-2:
        import warnings as _warnings

        _warnings.warn(
            f"vector_fit: pole relocation did not converge within "
            f"n_iter={n_iter} iterations (last relative pole shift "
            f"{pole_shift:.2e}). The returned fit may sit in a limit "
            "cycle; inspect rms_error, increase n_iter, or adjust "
            "n_poles / weighting.",
            VectorFitConvergenceWarning,
            stacklevel=2,
        )

    # Final residue solve with the converged poles (pair basis —
    # residues at conjugate poles are exact conjugates by
    # construction, no post-hoc repair required).
    structure = _pole_pair_structure(poles)
    basis = _pair_basis(s, poles, structure)
    A = np.zeros((s.size, n_poles + extras), dtype=complex)
    A[:, :n_poles] = basis
    col = n_poles
    if include_R_inf:
        A[:, col] = 1.0
        col += 1
    if include_L_inf:
        A[:, col] = s
        col += 1
    Aw = A * w[:, None]
    M = np.vstack([Aw.real, Aw.imag])
    rhs = np.concatenate([(w * Z).real, (w * Z).imag])
    sol = _solve_lstsq(M, rhs, poles)
    residues = _coeffs_to_residues(sol[:n_poles], poles, structure)
    R_inf = float(sol[n_poles]) if include_R_inf else 0.0
    L_inf = float(sol[n_poles + (1 if include_R_inf else 0)]) if include_L_inf else 0.0

    Z_fit = (
        np.full_like(s, R_inf, dtype=complex)
        + L_inf * s
        + np.sum(residues[:, None] / (s[None, :] - poles[:, None]), axis=0)
    )
    rms = float(np.sqrt(np.mean(np.abs(Z_fit - Z) ** 2)))
    rms_rel = rms / max(float(np.mean(np.abs(Z))), 1e-300)
    if rms_rel > rms_tol:
        import warnings as _warnings

        _warnings.warn(
            f"vector_fit: relative rms error {rms_rel:.2%} exceeds "
            f"{rms_tol:.2%} (n_poles={n_poles}). The rational model does not "
            "represent the samples; try another n_poles, more samples or "
            "weighting='inverse_magnitude'.",
            VectorFitQualityWarning,
            stacklevel=2,
        )

    return VectorFitResult(
        rms_relative=rms_rel,
        n_iter_used=n_iter_used,
        pole_shift=pole_shift,
        poles=poles,
        residues=residues,
        R_inf=R_inf,
        L_inf=L_inf,
        rms_error=rms,
        fit_frequencies=frequencies,
        fit_values=Z,
    )

Standard rho-f form

rho_f_standard

Standard-form rho-f model for the groundinsight bridge.

The reduced grounding-cluster impedance uses the physically-motivated standard form

\[ Z(\rho, f) \;=\; k_0 \;+\; k_1 \rho \;+\; (k_2 + j k_3)\,f \;+\; (k_4 + j k_5)\,f\,\rho, \]

with \(\rho\) a soil-resistivity parameter (typically the upper-layer \(\rho_1\) in a fixed-structure 2-layer setup) and \(f\) the frequency. The real coefficients have direct physical interpretation:

  • \(k_0\) — resistance that does not scale with \(\rho\) in \(\Omega\): the share of the lower layer in a \(\rho_1\) sweep (\(R(\rho_1 \to 0)\) stays finite, set by \(\rho_2\)), or the series resistance of conductors in a network. Optional (k0=True by default since review pass 10, 10.27); real, so that \(Z(f = 0)\) is real.
  • \(k_1\,\rho\) — DC spreading resistance (Dwight-class scaling with the dominant local soil resistivity).
  • \(k_2\,f\) — soil-independent resistive frequency dependence in \(\Omega/\mathrm{Hz}\) (skin/proximity losses of the metallic parts; negligible in most quasi-static typical studies).
  • \(k_3\,f\) — soil-independent reactive coupling in \(\Omega/\mathrm{Hz}\), i.e. the loop-inductance term of a metallic path; the equivalent inductance is \(L = k_3 / (2\pi)\) in H.
  • \(k_4\,f\,\rho\) — Carson-type earth-return resistance: scales with both frequency and soil resistivity.
  • \(k_5\,f\,\rho\) — Carson-type earth-return reactance.

This is not a general rational function — it is a fixed parametric ansatz that captures the leading orders for production-grade grounding-cluster impedances. It is fitted from a parametric family of groundfield runs that span both \(\rho\) and \(f\), and exported as a SymPy expression with two free symbols \(\rho\) (rho) and \(f\) (f) — the BusType.impedance_formula convention used by groundinsight.

Mathematically the fit is a weighted linear least-squares problem:

  • Real part: \(\Re Z = k_0 + k_1\rho + k_2 f + k_4 f\rho\) → regression in (\(1\), \(\rho\), \(f\), \(f\rho\)).
  • Imaginary part: \(\Im Z = k_3 f + k_5 f\rho\) → regression in (\(f\), \(f\rho\)).

With weights="relative" (default since review pass 10) every sample is weighted by \(1/|Z_n|\), i.e. the fit minimises the sum of squared relative errors; with "uniform" it minimises absolute errors, which concentrates the error on the low-impedance samples (low \(\rho\)), where the high-\(\rho\) samples dominate the residual.

So \(k_2\) and \(k_4\) live in the real (resistive) half and \(k_3\) and \(k_5\) in the imaginary (reactive) half — the pairing implied by the complex factors \((k_2 + j k_3)\) and \((k_4 + j k_5)\) above.

Both halves are decoupled in the coefficients, so the fit is unique whenever the sample set spans at least two distinct \(\rho\) values and at least two distinct frequencies (and, with \(k_0\), the real design matrix has full rank). The two conditions remove two different collinearities of the design matrix:

  • A single \(\rho = R\) makes the columns \(f\) and \(f\rho = R f\) proportional, so only \(k_2 + R\,k_4\) (resp. \(k_3 + R\,k_5\)) is identifiable.
  • A single \(f = F\) makes the columns \(\rho\) and \(f\rho = F\rho\) proportional, so only \(k_1 + F\,k_4\) is identifiable.
Fit quality

rms_relative (rms error over the mean \(|Z|\)) is dominated by the high-impedance samples and hides large relative errors at low \(\rho\). max_relative = \(\max_n |Z_\text{fit} - Z_n| / |Z_n|\) is the figure to check; above max_relative_tol (5 %) the fit warns with RhoFStandardQualityWarning. Review pass 10 measured on a \(\rho_1\) sweep (30…1000 Ω·m) of a 2 m ring in two-layer soil (\(\rho_2\) = 100 Ω·m, \(h_1\) = 5 m): v0.15.0 form 27 % worst error at \(\rho_1\) = 30 (rms_relative 2.6 %), with \(k_0\) and relative weights 3.3 %; an AP1-like station (4 m × 4 m loop with three 4 m rods) 43 % against 6.2 %.

References
  • The rho-f model is the reduced grey-box representation handed to groundinsight.
  • groundinsight.BusType.impedance_formula: the consumer of the SymPy expression returned by fit_to_sympy_standard().

RhoFStandardFit dataclass

RhoFStandardFit(k1: float, k2: float, k3: float, k4: float, k5: float, rms_error: float, rms_relative: float, sample_rho: ndarray, sample_f: ndarray, sample_Z: ndarray, k0: float = 0.0, max_relative: float = math.nan, weights: str = 'uniform', quantity: str | None = None)

Result of a standard-form rho-f fit.

Attributes:

Name Type Description
k1, k2, k3, k4, k5

Real coefficients of \(Z = k_0 + k_1\rho + (k_2 + j k_3)f + (k_4 + j k_5)f\rho\). k1 is the DC spreading-resistance slope in \(\Omega/(\Omega\,\mathrm{m})\); k2 (real) and k3 (imaginary) are the soil-independent resistive resp. reactive frequency slopes in \(\Omega/\mathrm{Hz}\); k4 (real) and k5 (imaginary) are the Carson-type earth-return resistance resp. reactance slopes in \(\Omega/(\mathrm{Hz}\,\Omega\,\mathrm{m})\).

rms_error float

Root-mean-square residual error in \(\Omega\) over the input samples.

rms_relative float

rms_error divided by the mean of \(|Z|\) over the samples — a dimensionless figure dominated by the large samples.

sample_rho, sample_f, sample_Z

Original samples used for the fit (1-D arrays of length \(N\)), kept for diagnostics.

k0 float

Constant term in \(\Omega\) (0 when fitted with k0=False).

max_relative float

Worst pointwise relative error \(\max_n |Z_\text{fit}(\rho_n, f_n) - Z_n| / |Z_n|\) over the samples with \(Z_n \ne 0\) (dimensionless); nan for hand-built instances.

weights str

Weighting used in the fit, "uniform" or "relative".

quantity str | None

Impedance the samples represent when the fit was built by rho_f_standard_from_results() ("input", "cluster" or "electrode"); None for raw samples.

coefficients property
coefficients: dict[str, float]

Return the coefficients k0 … k5 as a dict.

evaluate
evaluate(rho: float | ndarray, f: float | ndarray) -> complex | np.ndarray

Evaluate the fitted \(Z(\rho, f)\) in Ω at arbitrary points.

Parameters:

Name Type Description Default
rho float | ndarray

Soil resistivity in Ω·m (scalar or array).

required
f float | ndarray

Frequency in Hz (scalar or array, broadcast with rho).

required
Source code in src/groundfield/postprocess/rho_f_standard.py
def evaluate(
    self,
    rho: float | np.ndarray,
    f: float | np.ndarray,
) -> complex | np.ndarray:
    """Evaluate the fitted $Z(\\rho, f)$ in Ω at arbitrary points.

    Parameters
    ----------
    rho
        Soil resistivity in Ω·m (scalar or array).
    f
        Frequency in Hz (scalar or array, broadcast with ``rho``).
    """
    rho = np.asarray(rho, dtype=float)
    f = np.asarray(f, dtype=float)
    return (
        self.k0
        + self.k1 * rho
        + (self.k2 + 1j * self.k3) * f
        + (self.k4 + 1j * self.k5) * f * rho
    )

RhoFStandardQualityWarning

Bases: UserWarning

The standard-form fit misses a sample by more than max_relative_tol.

The standard form is a fixed ansatz; a large pointwise error means it cannot represent the sampled \(Z(\rho, f)\) (review pass 10, 10.27). Check RhoFStandardFit.max_relative, restrict the \(\rho\) range, or fit per \(\rho\) with vector fitting.

fit_rho_f_standard

fit_rho_f_standard(rho_samples: Sequence[float], f_samples: Sequence[float], Z_samples: Sequence[complex], *, k0: bool = True, weights: Weights = 'relative', max_relative_tol: float = 0.05) -> RhoFStandardFit

Fit the standard rho-f form via weighted linear least squares.

Parameters:

Name Type Description Default
rho_samples Sequence[float]

Soil-resistivity values \(\rho\) in \(\Omega\,\mathrm{m}\) for each sample (length \(N\)).

required
f_samples Sequence[float]

Frequencies \(f\) in Hz for each sample (length \(N\)).

required
Z_samples Sequence[complex]

Complex impedances \(Z\) in \(\Omega\) at each \((\rho, f)\) sample (length \(N\)).

required
k0 bool

Fit the constant term \(k_0\) (default True since review pass 10, 10.27). False gives the five-coefficient form of v0.15.0.

True
weights Weights

"relative" (default since review pass 10): weight each sample by \(1/|Z_n|\) — minimise relative errors. "uniform": minimise absolute errors (v0.15.0).

'relative'
max_relative_tol float

Warn with RhoFStandardQualityWarning when max_relative exceeds this value (dimensionless, default 0.05).

0.05

Returns:

Type Description
RhoFStandardFit

Raises:

Type Description
ValueError

If sample arrays have inconsistent lengths, there are fewer than four samples, fewer than two distinct \(\rho\) values or fewer than two distinct \(f\) values, the design matrix is rank deficient, weights is unknown, or weights="relative" meets a sample with \(Z = 0\).

Warns:

Type Description
RhoFStandardQualityWarning

If the worst pointwise relative error exceeds max_relative_tol.

Notes

k0=False, weights="uniform" reproduces the v0.15.0 coefficients bit for bit.

Source code in src/groundfield/postprocess/rho_f_standard.py
def fit_rho_f_standard(
    rho_samples: Sequence[float],
    f_samples: Sequence[float],
    Z_samples: Sequence[complex],
    *,
    k0: bool = True,
    weights: Weights = "relative",
    max_relative_tol: float = 0.05,
) -> RhoFStandardFit:
    """Fit the standard rho-f form via weighted linear least squares.

    Parameters
    ----------
    rho_samples
        Soil-resistivity values $\\rho$ in $\\Omega\\,\\mathrm{m}$
        for each sample (length $N$).
    f_samples
        Frequencies $f$ in Hz for each sample (length $N$).
    Z_samples
        Complex impedances $Z$ in $\\Omega$ at each $(\\rho, f)$ sample
        (length $N$).
    k0
        Fit the constant term $k_0$ (default ``True`` since review pass
        10, 10.27). ``False`` gives the five-coefficient form of v0.15.0.
    weights
        ``"relative"`` (default since review pass 10): weight each
        sample by $1/|Z_n|$ — minimise relative errors. ``"uniform"``:
        minimise absolute errors (v0.15.0).
    max_relative_tol
        Warn with :class:`RhoFStandardQualityWarning` when
        ``max_relative`` exceeds this value (dimensionless, default
        0.05).

    Returns
    -------
    RhoFStandardFit

    Raises
    ------
    ValueError
        If sample arrays have inconsistent lengths, there are fewer than
        four samples, fewer than two distinct $\\rho$ values *or* fewer
        than two distinct $f$ values, the design matrix is rank
        deficient, ``weights`` is unknown, or ``weights="relative"`` meets
        a sample with $Z = 0$.

    Warns
    -----
    RhoFStandardQualityWarning
        If the worst pointwise relative error exceeds ``max_relative_tol``.

    Notes
    -----
    ``k0=False, weights="uniform"`` reproduces the v0.15.0 coefficients
    bit for bit.
    """
    rho = np.asarray(rho_samples, dtype=float)
    f = np.asarray(f_samples, dtype=float)
    Z = np.asarray(Z_samples, dtype=complex)
    if rho.shape != f.shape or rho.shape != Z.shape:
        raise ValueError(
            "rho_samples, f_samples and Z_samples must have identical shape; "
            f"got rho={rho.shape}, f={f.shape}, Z={Z.shape}."
        )
    if rho.size < 4:
        raise ValueError(
            f"fit_rho_f_standard needs at least 4 samples; got {rho.size}."
        )
    # Identifiability: a constant rho makes the columns f and f*rho
    # proportional (k2/k4 and k3/k5 confounded); a constant f makes
    # the columns rho and f*rho proportional (k1/k4 confounded).
    if np.unique(rho).size < 2:
        raise ValueError(
            "fit_rho_f_standard needs at least two distinct rho values "
            "to identify k2 and k4 (and k3 and k5) separately."
        )
    if np.unique(f).size < 2:
        raise ValueError(
            "fit_rho_f_standard needs at least two distinct f values "
            "to identify k1 and k4 separately."
        )
    if weights not in ("uniform", "relative"):
        raise ValueError(f"weights must be 'uniform' or 'relative', got {weights!r}.")
    absZ = np.abs(Z)
    if weights == "relative":
        if np.any(absZ == 0.0):
            raise ValueError(
                "weights='relative' needs |Z| > 0 at every sample; use "
                "weights='uniform' or drop the zero samples."
            )
        w = 1.0 / absZ
    else:
        w = None

    # Real part: Re(Z) = k0 + k1·ρ + k2·f + k4·f·ρ
    cols = [rho, f, f * rho]
    if k0:
        cols.insert(0, np.ones_like(rho))
    A_real = np.column_stack(cols)
    A_imag = np.column_stack([f, f * rho])
    b_real, b_imag = Z.real, Z.imag
    if w is not None:
        A_real, b_real = A_real * w[:, None], b_real * w
        A_imag, b_imag = A_imag * w[:, None], b_imag * w
    sol_real = _lstsq(A_real, b_real, "real-part")
    c0 = float(sol_real[0]) if k0 else 0.0
    k1, k2, k4 = (float(x) for x in sol_real[-3:])

    # Imag part: Im(Z) = k3·f + k5·f·ρ
    sol_imag = _lstsq(A_imag, b_imag, "imaginary-part")
    k3, k5 = float(sol_imag[0]), float(sol_imag[1])

    Z_fit = c0 + k1 * rho + (k2 + 1j * k3) * f + (k4 + 1j * k5) * f * rho
    err = np.abs(Z_fit - Z)
    rms = float(np.sqrt(np.mean(err**2)))
    rms_rel = rms / max(float(np.mean(absZ)), 1e-12)
    nonzero = absZ > 0.0
    max_rel = float(np.max(err[nonzero] / absZ[nonzero])) if nonzero.any() else math.nan
    if max_rel > max_relative_tol:
        worst = int(np.flatnonzero(nonzero)[np.argmax(err[nonzero] / absZ[nonzero])])
        warnings.warn(
            f"fit_rho_f_standard: max_relative = {max_rel:.1%} exceeds "
            f"{max_relative_tol:.1%} (worst sample rho = {rho[worst]:g} Ohm m, "
            f"f = {f[worst]:g} Hz; rms_relative = {rms_rel:.1%}). The standard "
            "form does not represent these samples well.",
            RhoFStandardQualityWarning,
            stacklevel=2,
        )

    return RhoFStandardFit(
        k1=k1,
        k2=k2,
        k3=k3,
        k4=k4,
        k5=k5,
        rms_error=rms,
        rms_relative=rms_rel,
        sample_rho=rho,
        sample_f=f,
        sample_Z=Z,
        k0=c0,
        max_relative=max_rel,
        weights=weights,
    )

fit_to_sympy_standard

fit_to_sympy_standard(fit: RhoFStandardFit, *, decimals: int = 6)

Convert a RhoFStandardFit to a SymPy expression.

Returns a sympy.Expr in two free symbols rho and f (both real), in the standard form

\[ Z(\rho, f) \;=\; k_0 \;+\; k_1\rho \;+\; (k_2 + j k_3)\,f \;+\; (k_4 + j k_5)\,f\,\rho, \]

the constant term only when it is non-zero. The expression is built term by term by the renderer the groundinsight exporter uses (review pass 10, 10.73) and is suitable for direct insertion into groundinsight.BusType.impedance_formula.

Parameters:

Name Type Description Default
fit RhoFStandardFit

Standard-form fit.

required
decimals int

Significant digits of every coefficient (1 to 17; larger values count as 17). Each coefficient is correctly rounded once, so its relative error is at most \(\tfrac12\,10^{1-N}\) for \(N\) = decimals.

6

Returns:

Type Description
Expr

Raises:

Type Description
ValueError

If decimals is not a positive integer.

Source code in src/groundfield/postprocess/rho_f_standard.py
def fit_to_sympy_standard(fit: RhoFStandardFit, *, decimals: int = 6):
    """Convert a :class:`RhoFStandardFit` to a SymPy expression.

    Returns a :class:`sympy.Expr` in two free symbols ``rho`` and
    ``f`` (both real), in the standard form

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

    the constant term only when it is non-zero. The expression is built
    term by term by the renderer the ``groundinsight`` exporter uses
    (review pass 10, 10.73) and is suitable for direct insertion into
    ``groundinsight.BusType.impedance_formula``.

    Parameters
    ----------
    fit
        Standard-form fit.
    decimals
        Significant digits of every coefficient (1 to 17; larger values
        count as 17). Each coefficient is correctly rounded **once**, so
        its relative error is at most :math:`\\tfrac12\\,10^{1-N}` for
        :math:`N` = ``decimals``.

    Returns
    -------
    sympy.Expr

    Raises
    ------
    ValueError
        If ``decimals`` is not a positive integer.
    """
    import sympy as sp

    from groundfield.io._formula import round_coefficients

    rho = sp.Symbol("rho", real=True, positive=True)
    f = sp.Symbol("f", real=True, positive=True)
    return round_coefficients(_standard_expression(fit, rho, f), decimals)

rho_f_standard_from_results

rho_f_standard_from_results(results: Sequence, rhos: Sequence[float], electrode_name: str | None = None, *, quantity: Quantity = 'input', source: str | None = None, k0: bool = True, weights: Weights = 'relative', max_relative_tol: float = 0.05) -> RhoFStandardFit

Build the (ρ, f, Z) sample table from a list of FieldResults and fit.

Use case: parametric soil-resistivity sweep. Run one Engine.solve per soil resistivity, collect the FieldResults along with the driving \(\rho\), and pass the lot to this function.

Parameters:

Name Type Description Default
results Sequence

List of groundfield.FieldResult (one per \(\rho\) value).

required
rhos Sequence[float]

Soil-resistivity parameter \(\rho\) in Ω·m corresponding to each FieldResult (same length).

required
electrode_name str | None

Electrode whose impedance is fitted; required for quantity="cluster" and "electrode", optional for "input" (see groundfield.postprocess.vector_fitting.rho_f_from_field_result()).

None
quantity Quantity

"input" (default since review pass 10, 10.19): the driving-point impedance of the current source. "cluster": the cluster impedance of electrode_name. "electrode": \(U_e/I_e\) of the named electrode, the quantity v0.15.0 fitted.

'input'
source str | None

Current source for quantity="input"; may be omitted with a single current source.

None
k0 bool

Forwarded to fit_rho_f_standard().

True
weights bool

Forwarded to fit_rho_f_standard().

True
max_relative_tol bool

Forwarded to fit_rho_f_standard().

True

Returns:

Type Description
RhoFStandardFit

Raises:

Type Description
ValueError

If results and rhos differ in length, if the per-electrode arrays of a result do not match its frequencies, if the denominator current is zero at every \((\rho, f)\) sample (then \(Z = U/I\) is nowhere defined), or for an invalid quantity / electrode_name combination.

KeyError

If electrode_name is absent from a result's electrode_potentials or electrode_currents.

Notes

Samples at which the denominator current is zero are masked out rather than entered as \(Z = 0\): a vanishing current means the impedance is undefined, not zero, and a single injected zero row pulls the least-squares plane through the origin (a 1-in-7 dead DC column biases \(k_1\) by tens of percent). Masking mirrors groundfield.postprocess.vector_fitting.rho_f_from_field_result(); a UserWarning reports how many samples were dropped.

Source code in src/groundfield/postprocess/rho_f_standard.py
def rho_f_standard_from_results(
    results: Sequence,
    rhos: Sequence[float],
    electrode_name: str | None = None,
    *,
    quantity: Quantity = "input",
    source: str | None = None,
    k0: bool = True,
    weights: Weights = "relative",
    max_relative_tol: float = 0.05,
) -> RhoFStandardFit:
    """Build the (ρ, f, Z) sample table from a list of FieldResults and fit.

    Use case: parametric soil-resistivity sweep. Run one
    ``Engine.solve`` per soil resistivity, collect the FieldResults
    along with the driving $\\rho$, and pass the lot to this
    function.

    Parameters
    ----------
    results
        List of :class:`groundfield.FieldResult` (one per
        $\\rho$ value).
    rhos
        Soil-resistivity parameter $\\rho$ in Ω·m corresponding to each
        FieldResult (same length).
    electrode_name
        Electrode whose impedance is fitted; required for
        ``quantity="cluster"`` and ``"electrode"``, optional for
        ``"input"`` (see
        :func:`groundfield.postprocess.vector_fitting.rho_f_from_field_result`).
    quantity
        ``"input"`` (default since review pass 10, 10.19): the
        driving-point impedance of the current source.
        ``"cluster"``: the cluster impedance of ``electrode_name``.
        ``"electrode"``: :math:`U_e/I_e` of the named electrode, the
        quantity v0.15.0 fitted.
    source
        Current source for ``quantity="input"``; may be omitted with a
        single current source.
    k0, weights, max_relative_tol
        Forwarded to :func:`fit_rho_f_standard`.

    Returns
    -------
    RhoFStandardFit

    Raises
    ------
    ValueError
        If ``results`` and ``rhos`` differ in length, if the
        per-electrode arrays of a result do not match its
        ``frequencies``, if the denominator current is zero at *every*
        $(\\rho, f)$ sample (then $Z = U/I$ is nowhere defined), or for
        an invalid ``quantity`` / ``electrode_name`` combination.
    KeyError
        If ``electrode_name`` is absent from a result's
        ``electrode_potentials`` or ``electrode_currents``.

    Notes
    -----
    Samples at which the denominator current is **zero** are
    *masked out* rather than entered as $Z = 0$: a vanishing current
    means the impedance is undefined, not zero, and a single injected
    zero row pulls the least-squares plane through the origin (a 1-in-7
    dead DC column biases $k_1$ by tens of percent). Masking mirrors
    :func:`groundfield.postprocess.vector_fitting.rho_f_from_field_result`;
    a :class:`UserWarning` reports how many samples were dropped.
    """
    if len(results) != len(rhos):
        raise ValueError(
            f"results and rhos must have same length; "
            f"got {len(results)} vs {len(rhos)}."
        )
    rho_arr: list[float] = []
    f_arr: list[float] = []
    Z_arr: list[complex] = []
    n_dead = 0
    n_total = 0
    for res, rho_val in zip(results, rhos, strict=True):
        z_all, i_all = impedance_series(
            res,
            quantity,
            electrode_name=electrode_name,
            source=source,
            caller="rho_f_standard_from_results",
        )
        f_local = np.asarray(res.frequencies, dtype=float)
        # Review pass 9 (finding F41), mirroring the earlier fix N23 in
        # vector_fitting.rho_f_from_field_result: frequencies at which
        # the denominator current vanishes are MASKED, not injected as
        # Z = 0 samples, which used to drag the fit toward the origin.
        alive = np.abs(i_all) > 0.0
        n_total += int(alive.size)
        n_dead += int((~alive).sum())
        rho_arr.extend([float(rho_val)] * int(alive.sum()))
        f_arr.extend(f_local[alive].tolist())
        Z_arr.extend(z_all[alive].tolist())

    label = f"electrode '{electrode_name}'" if quantity != "input" else "the source"
    if not Z_arr:
        raise ValueError(
            f"rho_f_standard_from_results: {label} carries no current at any "
            f"of the {n_total} (rho, f) samples — Z = U/I is undefined. Fit "
            "the driven electrode instead."
        )
    if n_dead:
        import warnings as _warnings

        _warnings.warn(
            f"rho_f_standard_from_results: {label} carries no current at "
            f"{n_dead} of {n_total} (rho, f) samples; those samples are "
            "excluded from the fit (historic behaviour injected Z = 0 there).",
            UserWarning,
            stacklevel=2,
        )
    fit = fit_rho_f_standard(
        rho_arr,
        f_arr,
        Z_arr,
        k0=k0,
        weights=weights,
        max_relative_tol=max_relative_tol,
    )
    return dataclasses.replace(fit, quantity=quantity)

Potential plots

plotting

Matplotlib plots for potential distributions and profiles.

Functions:

Name Description
plot_potential_contour

Contour / pseudo-colour plot of the potential in a slice plane (xy at fixed \(z\) or xz at fixed \(y\)).

plot_potential_profile

Line plot of the potential along an arbitrary direction for one or several \(z\) depths.

plot_potential_radial

Radial profile \(\varphi(r)\) starting from an electrode for several depths — the standard "how far does the trumpet reach?" plot.

All functions return the ``matplotlib.figure.Figure`` they produce so
that notebooks can post-process them
The potential is a complex phasor. Every plot takes
``component="real" | "imag" | "abs" | "phase"``
the part plotted up to v0.15.0) and labels the axis with what it draws
— ``Re φ``, ``Im φ``, ``|φ|`` in V or ``arg φ`` in degrees
pass 10, 10.73). With phase-shifted sources or inductive coupling the
real part is not the magnitude; use ``component="abs"`` for safety
plots.

plot_potential_contour

plot_potential_contour(result: 'FieldResult', *, world: 'World | None' = None, plane: Literal['xy', 'xz'] = 'xy', z: float = 0.0, y: float = 0.0, extent: tuple[float, float, float, float] | None = None, n: int = 120, frequency_index: int = 0, levels: int = 20, log: bool = False, cmap: str = 'viridis', component: Component = 'real')

Contour plot of the potential in a slice plane.

Parameters:

Name Type Description Default
result 'FieldResult'

Result object from Engine.solve().

required
world 'World | None'

Optional companion world; if given, electrodes are drawn into the plot.

None
plane Literal['xy', 'xz']

"xy" (horizontal slice at depth \(z\)) or "xz" (vertical slice at \(y\)).

'xy'
z float

Depth or \(y\) value of the slice plane in metres.

0.0
y float

Depth or \(y\) value of the slice plane in metres.

0.0
extent tuple[float, float, float, float] | None

(a_min, a_max, b_min, b_max) of the slice plane in metres. Default is derived from the point-source distribution.

None
n int

Resolution per axis.

120
frequency_index int

Index into FieldResult.frequencies.

0
levels int

Number of contour levels.

20
log bool

Logarithmic colour scale (better for fields that span several decades).

False
cmap str

Matplotlib colormap name.

'viridis'
component Component

Part of the complex potential to draw: "real" (default), "imag", "abs" or "phase" (degrees).

'real'

Returns:

Name Type Description
fig Figure

Raises:

Type Description
ValueError

For an unknown component or log=True with "phase".

Source code in src/groundfield/postprocess/plotting.py
def plot_potential_contour(
    result: "FieldResult",
    *,
    world: "World | None" = None,
    plane: Literal["xy", "xz"] = "xy",
    z: float = 0.0,
    y: float = 0.0,
    extent: tuple[float, float, float, float] | None = None,
    n: int = 120,
    frequency_index: int = 0,
    levels: int = 20,
    log: bool = False,
    cmap: str = "viridis",
    component: Component = "real",
):
    """Contour plot of the potential in a slice plane.

    Parameters
    ----------
    result
        Result object from :meth:`Engine.solve`.
    world
        Optional companion world; if given, electrodes are drawn into
        the plot.
    plane
        ``"xy"`` (horizontal slice at depth $z$) or ``"xz"``
        (vertical slice at $y$).
    z, y
        Depth or $y$ value of the slice plane in metres.
    extent
        ``(a_min, a_max, b_min, b_max)`` of the slice plane in metres.
        Default is derived from the point-source distribution.
    n
        Resolution per axis.
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    levels
        Number of contour levels.
    log
        Logarithmic colour scale (better for fields that span several
        decades).
    cmap
        Matplotlib colormap name.
    component
        Part of the complex potential to draw: ``"real"`` (default),
        ``"imag"``, ``"abs"`` or ``"phase"`` (degrees).

    Returns
    -------
    fig : matplotlib.figure.Figure

    Raises
    ------
    ValueError
        For an unknown ``component`` or ``log=True`` with ``"phase"``.
    """
    import matplotlib.pyplot as plt

    _component(np.zeros(1, dtype=complex), component)
    _check_log(component, log)
    if extent is None:
        srcs = np.array([ps.position for ps in result.point_sources])
        if plane == "xy":
            ax = srcs[:, 0]
            bx = srcs[:, 1]
        else:
            ax = srcs[:, 0]
            bx = srcs[:, 2]
        # ``np.ptp(arr)``, not ``arr.ptp()`` — the ndarray method was
        # removed in NumPy 2.0, and the project requires numpy >= 2.1.
        pad = max(5.0, 0.5 * (np.ptp(ax) + np.ptp(bx)))
        extent = (ax.min() - pad, ax.max() + pad, bx.min() - pad, bx.max() + pad)

    fixed = z if plane == "xy" else y
    A, B, flat = _make_grid(plane, extent, fixed, n)

    phi = _component(result.potential(flat, frequency_index=frequency_index), component)
    phi = phi.reshape(A.shape)

    fig, axx = plt.subplots(figsize=(7, 5))
    if log:
        # Drop non-positive values, otherwise the log scale breaks.
        phi_plot = np.where(phi > 0, phi, np.nan)
        cs = axx.contourf(
            A,
            B,
            phi_plot,
            levels=levels,
            cmap=cmap,
            locator=__import__(
                "matplotlib.ticker", fromlist=["LogLocator"]
            ).LogLocator(),
        )
    else:
        cs = axx.contourf(A, B, phi, levels=levels, cmap=cmap)
    contours = axx.contour(
        A, B, phi, levels=levels, colors="k", linewidths=0.4, alpha=0.5
    )
    axx.clabel(contours, inline=True, fontsize=7, fmt="%.0f")

    cbar = fig.colorbar(cs, ax=axx)
    cbar.set_label(_label(component))
    sym = _SYMBOL[component]

    if plane == "xy":
        axx.set_xlabel("x in m")
        axx.set_ylabel("y in m")
        axx.set_title(
            f"{sym}(x, y, z={z:g} m), f={result.frequencies[frequency_index]} Hz"
        )
        axx.set_aspect("equal")
    else:
        axx.set_xlabel("x in m")
        axx.set_ylabel("z in m (depth)")
        axx.invert_yaxis()  # soil downwards
        axx.set_title(
            f"{sym}(x, y={y:g} m, z), f={result.frequencies[frequency_index]} Hz"
        )

    if world is not None:
        _draw_electrodes(axx, world, plane)

    fig.tight_layout()
    return fig

plot_potential_profile

plot_potential_profile(result: 'FieldResult', *, start: tuple[float, float, float], direction: tuple[float, float, float] = (1.0, 0.0, 0.0), distance: float = 30.0, n: int = 200, depths: Iterable[float] | None = None, frequency_index: int = 0, component: Component = 'real')

Potential along an arbitrary line, optionally for several depths.

Parameters:

Name Type Description Default
result 'FieldResult'

Result object.

required
start tuple[float, float, float]

Start point (x, y, z) of the line in metres. z is overridden by depths if given.

required
direction tuple[float, float, float]

Direction vector (will be normalised).

(1.0, 0.0, 0.0)
distance float

Length of the line in metres.

30.0
n int

Number of evaluation points.

200
depths Iterable[float] | None

List of depths \(z\) in metres. One curve per depth.

None
frequency_index int

Index into FieldResult.frequencies.

0
component Component

"real" (default), "imag", "abs" or "phase" (degrees) of the complex potential.

'real'

Returns:

Name Type Description
fig Figure
Source code in src/groundfield/postprocess/plotting.py
def plot_potential_profile(
    result: "FieldResult",
    *,
    start: tuple[float, float, float],
    direction: tuple[float, float, float] = (1.0, 0.0, 0.0),
    distance: float = 30.0,
    n: int = 200,
    depths: Iterable[float] | None = None,
    frequency_index: int = 0,
    component: Component = "real",
):
    """Potential along an arbitrary line, optionally for several depths.

    Parameters
    ----------
    result
        Result object.
    start
        Start point ``(x, y, z)`` of the line in metres. ``z`` is
        overridden by ``depths`` if given.
    direction
        Direction vector (will be normalised).
    distance
        Length of the line in metres.
    n
        Number of evaluation points.
    depths
        List of depths $z$ in metres. One curve per depth.
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    component
        ``"real"`` (default), ``"imag"``, ``"abs"`` or ``"phase"``
        (degrees) of the complex potential.

    Returns
    -------
    fig : matplotlib.figure.Figure
    """
    import matplotlib.pyplot as plt

    _component(np.zeros(1, dtype=complex), component)
    if depths is None:
        depths = [0.0]
    direction_arr = np.asarray(direction, dtype=float)
    direction_arr = direction_arr / np.linalg.norm(direction_arr)
    s = np.linspace(0.0, distance, n)

    fig, ax = plt.subplots(figsize=(7, 4))
    for z_d in depths:
        pts = np.column_stack(
            [
                start[0] + s * direction_arr[0],
                start[1] + s * direction_arr[1],
                np.full_like(s, z_d),
            ]
        )
        phi = _component(
            result.potential(pts, frequency_index=frequency_index), component
        )
        ax.plot(s, phi, label=f"z = {z_d:g} m")

    ax.set_xlabel("distance s along profile in m")
    ax.set_ylabel(_label(component))
    ax.set_title(
        f"{_SYMBOL[component]} profile from {start}, "
        f"f = {result.frequencies[frequency_index]} Hz"
    )
    ax.grid(True, alpha=0.3)
    ax.legend()
    fig.tight_layout()
    return fig

plot_potential_radial

plot_potential_radial(result: 'FieldResult', *, around: str | tuple[float, float, float], world: 'World | None' = None, r_max: float = 30.0, n: int = 200, depths: Iterable[float] = (0.0, 0.5, 1.0), frequency_index: int = 0, log_x: bool = False, component: Component = 'real')

Trumpet-shape decay around an electrode (or fixed point).

Evaluates \(\varphi(r)\) along the +x direction starting at the connection point of the given electrode (or at a fixed point). Multiple depths produce multiple curves — the typical "surface vs. deeper soil" comparison.

For a rectangular foundation of the generators the connection point is a corner, the start of its local \(-y\) side (since 2026.11: meshes since audit A2G-04, rectangles without cross-braces since user decision Q38; in 0.15.0 one grid mesh connected at its centre), so the profile starts there; pass around=(x, y, z) for another start.

Parameters:

Name Type Description Default
result 'FieldResult'

Solved field (homogeneous or two-layer soil).

required
around str | tuple[float, float, float]

Electrode name (resolved via world) or (x, y, z) tuple.

required
world 'World | None'

Required when around is an electrode name.

None
r_max float

Maximum radius in metres.

30.0
n int

Number of evaluation points.

200
depths Iterable[float]

\(z\) depths for the comparison curves.

(0.0, 0.5, 1.0)
frequency_index int

Index into FieldResult.frequencies.

0
log_x bool

If True use a logarithmic x-axis (better visibility of the trumpet shape).

False
component Component

"real" (default), "imag", "abs" or "phase" (degrees) of the complex potential.

'real'

Returns:

Name Type Description
fig Figure

Raises:

Type Description
ValueError

If component is not one of the four values, or if around is an electrode name and world is None.

Source code in src/groundfield/postprocess/plotting.py
def plot_potential_radial(
    result: "FieldResult",
    *,
    around: str | tuple[float, float, float],
    world: "World | None" = None,
    r_max: float = 30.0,
    n: int = 200,
    depths: Iterable[float] = (0.0, 0.5, 1.0),
    frequency_index: int = 0,
    log_x: bool = False,
    component: Component = "real",
):
    """Trumpet-shape decay around an electrode (or fixed point).

    Evaluates $\\varphi(r)$ along the ``+x`` direction starting
    at the connection point of the given electrode (or at a fixed
    point). Multiple ``depths`` produce multiple curves — the typical
    "surface vs. deeper soil" comparison.

    For a rectangular foundation of the generators the connection point
    is a corner, the start of its local :math:`-y` side (since 2026.11:
    meshes since audit A2G-04, rectangles without cross-braces since user
    decision Q38; in 0.15.0 one grid mesh connected at its centre), so the
    profile starts there; pass ``around=(x, y, z)`` for another start.

    Parameters
    ----------
    result
        Solved field (homogeneous or two-layer soil).
    around
        Electrode name (resolved via ``world``) or ``(x, y, z)`` tuple.
    world
        Required when ``around`` is an electrode name.
    r_max
        Maximum radius in metres.
    n
        Number of evaluation points.
    depths
        $z$ depths for the comparison curves.
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    log_x
        If ``True`` use a logarithmic x-axis (better visibility of the
        trumpet shape).
    component
        ``"real"`` (default), ``"imag"``, ``"abs"`` or ``"phase"``
        (degrees) of the complex potential.

    Returns
    -------
    fig : matplotlib.figure.Figure

    Raises
    ------
    ValueError
        If ``component`` is not one of the four values, or if ``around``
        is an electrode name and ``world`` is ``None``.
    """
    import matplotlib.pyplot as plt

    _component(np.zeros(1, dtype=complex), component)
    if isinstance(around, str):
        if world is None:
            raise ValueError("When 'around' is an electrode name, 'world' is required.")
        cp = world.get_electrode(around).connection_point
        x0, y0 = cp[0], cp[1]
        label_origin = around
    else:
        x0, y0 = around[0], around[1]
        label_origin = f"{around}"

    rs = np.linspace(0.1 if not log_x else 0.05, r_max, n)
    fig, ax = plt.subplots(figsize=(7, 4))
    for z_d in depths:
        pts = np.column_stack([x0 + rs, np.full_like(rs, y0), np.full_like(rs, z_d)])
        phi = _component(
            result.potential(pts, frequency_index=frequency_index), component
        )
        ax.plot(rs, phi, label=f"z = {z_d:g} m")

    ax.set_xlabel(f"distance r from {label_origin} in m")
    ax.set_ylabel(_label(component))
    ax.set_title(
        f"Radial profile around {label_origin}, "
        f"f = {result.frequencies[frequency_index]} Hz"
    )
    if log_x:
        ax.set_xscale("log")
    ax.grid(True, which="both", alpha=0.3)
    ax.legend()
    fig.tight_layout()
    return fig

plot_surface_potential

plot_surface_potential(result: 'FieldResult', world: 'World', *, z: float = 0.0, padding_m: float = 15.0, n: int = 200, extent: tuple[float, float, float, float] | None = None, frequency_index: int = 0, levels: int = 25, log: bool = False, symmetric: bool = False, cmap: str = 'viridis', show_electrodes: bool = True, show_contour_lines: bool = True, figsize: tuple[float, float] = (8.5, 7.0), title: str | None = None, component: Component = 'real')

Surface-potential pseudo-colour plot over the entire world.

Differs from plot_potential_contour() in two ways:

  1. The default extent is derived from the world's electrode bounding box (via world_bounds_xy()) plus padding_m, not from the discretised current point sources. This makes the plot naturally cover all buildings, cable cabinets and the substation in a TN network — including the "boundary regions" where the potential decays back to remote earth.
  2. The plot is locked to a horizontal slice (always plane="xy"); this is what typical calls the surface potential. Use plot_potential_contour() for vertical slices.
Mathematical content

For each grid point \((x_i, y_j, z)\) the function evaluates

\[ \varphi(x_i, y_j, z) \;=\; \frac{1}{4\pi\sigma_0} \sum_k \frac{I_k}{|\mathbf{r}_{ij} - \mathbf{r}_k|} \;+\; \text{image-charge series} \]

via FieldResult.potential(), which dispatches to the correct Green's function for the soil model the result was computed with (homogeneous / 2-layer / multi-layer). The component (default the real part) is plotted; for log=True the colour scale uses the logarithm of its magnitude so the boundary decay is visible across several decades.

Parameters:

Name Type Description Default
result 'FieldResult'

Solver output from Engine.solve().

required
world 'World'

Companion world used both to derive the plot extent and (optionally) to overlay electrodes.

required
z float

Depth of the slice in metres. 0.0 is the ground surface; positive values go into the soil.

0.0
padding_m float

Extra space added on each side of the electrode bounding box, in metres. Larger values let you see how the potential decays towards remote earth.

15.0
n int

Resolution per axis (the grid is n × n).

200
extent tuple[float, float, float, float] | None

Optional explicit (x_min, x_max, y_min, y_max) override. None (default) uses world_bounds_xy(world) plus padding_m.

None
frequency_index int

Index into FieldResult.frequencies.

0
levels int

Number of contour fill levels.

25
log bool

Logarithmic colour scale based on |φ| (better for the boundary decay).

False
symmetric bool

Use a symmetric [-φ_max, +φ_max] colour scale around 0. Useful when the potential takes both signs (multi-source or net-injection-zero studies).

False
cmap str

Matplotlib colormap name.

'viridis'
show_electrodes bool

Draw the electrode geometry on top of the contour.

True
show_contour_lines bool

Draw black iso-potential lines on top of the fill.

True
figsize tuple[float, float]

Matplotlib figure size in inches.

(8.5, 7.0)
title str | None

Optional title override; if None a sensible default is constructed from z and the chosen frequency.

None
component Component

"real" (default), "imag", "abs" or "phase" (degrees) of the complex potential; "phase" cannot be combined with log=True.

'real'

Returns:

Name Type Description
fig Figure
Source code in src/groundfield/postprocess/plotting.py
def plot_surface_potential(
    result: "FieldResult",
    world: "World",
    *,
    z: float = 0.0,
    padding_m: float = 15.0,
    n: int = 200,
    extent: tuple[float, float, float, float] | None = None,
    frequency_index: int = 0,
    levels: int = 25,
    log: bool = False,
    symmetric: bool = False,
    cmap: str = "viridis",
    show_electrodes: bool = True,
    show_contour_lines: bool = True,
    figsize: tuple[float, float] = (8.5, 7.0),
    title: str | None = None,
    component: Component = "real",
):
    """Surface-potential pseudo-colour plot over the entire world.

    Differs from :func:`plot_potential_contour` in two ways:

    1. The default ``extent`` is derived from the *world's
       electrode bounding box* (via :func:`world_bounds_xy`) plus
       ``padding_m``, not from the discretised current point
       sources. This makes the plot naturally cover all
       buildings, cable cabinets and the substation in a TN
       network — including the "boundary regions" where the
       potential decays back to remote earth.
    2. The plot is locked to a horizontal slice (always
       ``plane="xy"``); this is what typical calls the *surface
       potential*. Use :func:`plot_potential_contour` for vertical
       slices.

    Mathematical content
    --------------------
    For each grid point $(x_i, y_j, z)$ the function evaluates

    .. math::

        \\varphi(x_i, y_j, z) \\;=\\; \\frac{1}{4\\pi\\sigma_0}
        \\sum_k \\frac{I_k}{|\\mathbf{r}_{ij} - \\mathbf{r}_k|}
        \\;+\\; \\text{image-charge series}

    via :meth:`FieldResult.potential`, which dispatches to the
    correct Green's function for the soil model the result was
    computed with (homogeneous / 2-layer / multi-layer). The
    ``component`` (default the real part) is plotted; for ``log=True``
    the colour scale uses the logarithm of its magnitude so the boundary
    decay is visible across several decades.

    Parameters
    ----------
    result
        Solver output from :meth:`Engine.solve`.
    world
        Companion world used both to derive the plot extent and
        (optionally) to overlay electrodes.
    z
        Depth of the slice in metres. ``0.0`` is the ground
        surface; positive values go into the soil.
    padding_m
        Extra space added on each side of the electrode bounding
        box, in metres. Larger values let you see how the
        potential decays towards remote earth.
    n
        Resolution per axis (the grid is ``n × n``).
    extent
        Optional explicit ``(x_min, x_max, y_min, y_max)``
        override. ``None`` (default) uses
        ``world_bounds_xy(world)`` plus ``padding_m``.
    frequency_index
        Index into :attr:`FieldResult.frequencies`.
    levels
        Number of contour fill levels.
    log
        Logarithmic colour scale based on ``|φ|`` (better for the
        boundary decay).
    symmetric
        Use a symmetric ``[-φ_max, +φ_max]`` colour scale around 0.
        Useful when the potential takes both signs (multi-source
        or net-injection-zero studies).
    cmap
        Matplotlib colormap name.
    show_electrodes
        Draw the electrode geometry on top of the contour.
    show_contour_lines
        Draw black iso-potential lines on top of the fill.
    figsize
        Matplotlib figure size in inches.
    title
        Optional title override; if ``None`` a sensible default is
        constructed from ``z`` and the chosen frequency.
    component
        ``"real"`` (default), ``"imag"``, ``"abs"`` or ``"phase"``
        (degrees) of the complex potential; ``"phase"`` cannot be
        combined with ``log=True``.

    Returns
    -------
    fig : matplotlib.figure.Figure
    """
    import matplotlib.pyplot as plt
    from matplotlib.colors import LogNorm, Normalize

    _component(np.zeros(1, dtype=complex), component)
    _check_log(component, log)
    if extent is None:
        x_min, x_max, y_min, y_max = world_bounds_xy(world)
        extent = (
            x_min - padding_m,
            x_max + padding_m,
            y_min - padding_m,
            y_max + padding_m,
        )

    A, B, flat = _make_grid("xy", extent, z, n)
    phi = _component(result.potential(flat, frequency_index=frequency_index), component)
    phi = phi.reshape(A.shape)

    fig, ax = plt.subplots(figsize=figsize)

    if log:
        phi_abs = np.abs(phi)
        # Avoid log(0) by clipping at the smallest positive value;
        # mask-zero so the contourf renders the under-range as bg.
        positive = phi_abs[phi_abs > 0]
        v_min = float(positive.min()) if positive.size else 1e-9
        v_max = float(phi_abs.max()) if phi_abs.size else 1.0
        v_lo = max(v_min, 1e-9)
        norm = LogNorm(vmin=v_lo, vmax=max(v_max, 10 * v_lo))
        cs = ax.contourf(A, B, phi_abs, levels=levels, cmap=cmap, norm=norm)
        cbar_label = _label(component, log=True)
    elif symmetric:
        v = float(np.max(np.abs(phi)))
        norm = Normalize(vmin=-v, vmax=v)
        cs = ax.contourf(A, B, phi, levels=levels, cmap=cmap, norm=norm)
        cbar_label = _label(component)
    else:
        cs = ax.contourf(A, B, phi, levels=levels, cmap=cmap)
        cbar_label = _label(component)

    if show_contour_lines and not log:
        contours = ax.contour(
            A, B, phi, levels=levels, colors="k", linewidths=0.4, alpha=0.4
        )
        ax.clabel(contours, inline=True, fontsize=7, fmt="%.0f")
    elif show_contour_lines and log:
        # Log mode: contour lines on the absolute value, fewer levels
        # so labels stay legible.
        n_lines = max(5, levels // 3)
        contours = ax.contour(
            A, B, np.abs(phi), levels=n_lines, colors="k", linewidths=0.4, alpha=0.4
        )

    cbar = fig.colorbar(cs, ax=ax)
    cbar.set_label(cbar_label)

    ax.set_xlabel("x in m")
    ax.set_ylabel("y in m")
    ax.set_aspect("equal")
    if title is None:
        f_hz = result.frequencies[frequency_index]
        title = f"Surface potential {_SYMBOL[component]}(x, y, z = {z:g} m), f = {f_hz:g} Hz"
    ax.set_title(title)

    if show_electrodes:
        _draw_electrodes(ax, world, "xy")

    fig.tight_layout()
    return fig

world_bounds_xy

world_bounds_xy(world: 'World') -> tuple[float, float, float, float]

Compute the horizontal bounding box of a world's electrodes.

Inspects every electrode in world.electrodes and returns the smallest axis-aligned rectangle in the \((x, y)\) plane that contains the geometry. Used by plot_surface_potential() as the natural "the whole world" extent for a surface contour plot.

The footprint of each electrode kind is treated explicitly:

Parameters:

Name Type Description Default
world 'World'

World whose electrodes are inspected.

required

Returns:

Type Description
tuple

(x_min, x_max, y_min, y_max) in metres. For a world with no electrodes the result is the trivial (0, 0, 0, 0); callers should add positive padding before plotting.

Source code in src/groundfield/postprocess/plotting.py
def world_bounds_xy(world: "World") -> tuple[float, float, float, float]:
    """Compute the horizontal bounding box of a world's electrodes.

    Inspects every electrode in ``world.electrodes`` and returns
    the smallest axis-aligned rectangle in the $(x, y)$ plane that
    contains the geometry. Used by :func:`plot_surface_potential` as
    the natural "the whole world" extent for a surface contour plot.

    The footprint of each electrode kind is treated explicitly:

    * :class:`RodElectrode` — point at ``position[:2]``.
    * :class:`RingElectrode` — square of side $2r$ around the centre.
    * :class:`StripElectrode` — bounding box of ``start`` and ``end``.
    * :class:`MeshElectrode` / :class:`GridMeshElectrode` —
      ``corner`` to ``corner + size``.

    Parameters
    ----------
    world
        World whose electrodes are inspected.

    Returns
    -------
    tuple
        ``(x_min, x_max, y_min, y_max)`` in metres. For a world with
        no electrodes the result is the trivial ``(0, 0, 0, 0)``;
        callers should add positive padding before plotting.
    """
    from groundfield.geometry.electrodes import (
        GridMeshElectrode,
        MeshElectrode,
        PolylineElectrode,
        RingElectrode,
        RodElectrode,
        StarElectrode,
        StripElectrode,
    )

    if not world.electrodes:
        return (0.0, 0.0, 0.0, 0.0)

    xs: list[float] = []
    ys: list[float] = []
    for e in world.electrodes:
        if isinstance(e, RodElectrode):
            xs.append(e.position[0])
            ys.append(e.position[1])
        elif isinstance(e, RingElectrode):
            cx, cy, _ = e.center
            xs.extend([cx - e.radius, cx + e.radius])
            ys.extend([cy - e.radius, cy + e.radius])
        elif isinstance(e, StripElectrode):
            xs.extend([e.start[0], e.end[0]])
            ys.extend([e.start[1], e.end[1]])
        elif isinstance(e, (MeshElectrode, GridMeshElectrode)):
            cx, cy, _ = e.corner
            dx, dy = e.size
            xs.extend([cx, cx + dx])
            ys.extend([cy, cy + dy])
        elif isinstance(e, PolylineElectrode):
            xs.extend(v[0] for v in e.vertices)
            ys.extend(v[1] for v in e.vertices)
        elif isinstance(e, StarElectrode):
            for start, end in e.edges:
                xs.extend([start[0], end[0]])
                ys.extend([start[1], end[1]])
        else:  # pragma: no cover — defensive against future kinds
            cp = e.connection_point
            xs.append(cp[0])
            ys.append(cp[1])
    return (min(xs), max(xs), min(ys), max(ys))

Geometry plots

geometry_plot

World-geometry plots (no solve required).

This module provides quick visualisations of the physical world — electrodes, conductors and current sources — before the solver runs. In default setups with several hundred electrodes (200 EFH plus KVS plus substation plus measurement aux/probe) it is very useful to inspect the geometry first to catch typos in positions, accidental clusters, missing conductors, or sources attached to the wrong electrode, without paying the cost of a field solve.

Functions:

Name Description
world_bounds_3d

Smallest axis-aligned bounding box in \((x, y, z)\) of the world's electrodes plus conductor endpoints. Extension of groundfield.postprocess.plotting.world_bounds_xy() to three dimensions.

plot_world

2-D top-down (plane="xy") or vertical (plane="xz") geometry plot. Electrodes drawn via the existing _draw_electrodes() helper of groundfield.postprocess.plotting; conductors as colour-coded line segments; sources as red star markers with an optional arrow to return_to.

plot_world_3d

3-D wireframe with the soil-surface plane shown in light grey and the \(z\)-axis pointing downwards (groundfield convention; positive depth is below ground).

Conductor colour scheme

The conductor colour follows groundfield.conductors.ConductorType:

================== ========================= ===================== conductor_type Colour Default style ================== ========================= ===================== pen #2c7a2c (green) solid bare_copper #d97300 (orange) solid cable_shield #888888 (grey) solid overhead #1f77b4 (steel blue) solid generic #444444 (dark grey) solid ================== ========================= =====================

The line style flags the soil-coupling mode of the conductor: coupling_to_soil = "galvanic" is drawn solid, "isolated" is drawn dashed.

Validity

Pure geometry — no solver result is required. The plot does not visualise any field quantity; for that, see groundfield.postprocess.plotting.plot_potential_contour() and friends. Best used as a debugging step before world.solve(...).

plot_world

plot_world(world: 'World', *, plane: Literal['xy', 'xz'] = 'xy', extent: tuple[float, float, float, float] | None = None, padding_m: float = 5.0, show_conductors: bool = True, show_sources: bool = True, annotate_electrodes: bool = False, figsize: tuple[float, float] = (8.0, 6.0), ax=None, title: str | None = None)

Top-down or vertical 2-D geometry plot of a World.

Pure-geometry visualisation; no field quantity is evaluated and no solver is invoked. Useful as a sanity check before World.solve() on a large typical network.

Parameters:

Name Type Description Default
world 'World'

World to draw.

required
plane Literal['xy', 'xz']

"xy" (default — top-down) or "xz" (side / vertical slice).

'xy'
extent tuple[float, float, float, float] | None

Optional explicit (a_min, a_max, b_min, b_max) of the plotted area in metres. None (default) derives the extent from world_bounds_3d() plus padding_m.

None
padding_m float

Extra padding on each side of the bounding box in metres (used only when extent is None).

5.0
show_conductors bool

If True (default), draw every entry of World.conductors as a colour-coded line.

True
show_sources bool

If True (default), draw every entry of World.sources as a red star at its anchor electrode, plus an arrow to return_to if set.

True
annotate_electrodes bool

If True, attach a small text label with the electrode name to each electrode. Default False because production-grade worlds with > 50 electrodes look cluttered.

False
figsize tuple[float, float]

Matplotlib figure size in inches (used when ax is None).

(8.0, 6.0)
ax

Optional pre-existing matplotlib.axes.Axes. When passed, figsize is ignored and the host figure is returned.

None
title str | None

Optional title override; default World 'name' — plane geometry.

None

Returns:

Type Description
Figure

Raises:

Type Description
ValueError

If plane is neither "xy" nor "xz".

Source code in src/groundfield/postprocess/geometry_plot.py
def plot_world(
    world: "World",
    *,
    plane: Literal["xy", "xz"] = "xy",
    extent: tuple[float, float, float, float] | None = None,
    padding_m: float = 5.0,
    show_conductors: bool = True,
    show_sources: bool = True,
    annotate_electrodes: bool = False,
    figsize: tuple[float, float] = (8.0, 6.0),
    ax=None,
    title: str | None = None,
):
    """Top-down or vertical 2-D geometry plot of a :class:`World`.

    Pure-geometry visualisation; no field quantity is evaluated
    and no solver is invoked. Useful as a sanity check before
    :meth:`World.solve` on a large typical network.

    Parameters
    ----------
    world
        World to draw.
    plane
        ``"xy"`` (default — top-down) or ``"xz"`` (side / vertical
        slice).
    extent
        Optional explicit ``(a_min, a_max, b_min, b_max)`` of the
        plotted area in metres. ``None`` (default) derives the
        extent from :func:`world_bounds_3d` plus ``padding_m``.
    padding_m
        Extra padding on each side of the bounding box in metres
        (used only when ``extent`` is ``None``).
    show_conductors
        If ``True`` (default), draw every entry of
        :attr:`World.conductors` as a colour-coded line.
    show_sources
        If ``True`` (default), draw every entry of
        :attr:`World.sources` as a red star at its anchor
        electrode, plus an arrow to ``return_to`` if set.
    annotate_electrodes
        If ``True``, attach a small text label with the electrode
        name to each electrode. Default ``False`` because
        production-grade worlds with > 50 electrodes look cluttered.
    figsize
        Matplotlib figure size in inches (used when ``ax`` is
        ``None``).
    ax
        Optional pre-existing :class:`matplotlib.axes.Axes`. When
        passed, ``figsize`` is ignored and the host figure is
        returned.
    title
        Optional title override; default ``World 'name' — plane
        geometry``.

    Returns
    -------
    matplotlib.figure.Figure

    Raises
    ------
    ValueError
        If ``plane`` is neither ``"xy"`` nor ``"xz"``.
    """
    import matplotlib.pyplot as plt

    from groundfield.postprocess.plotting import _draw_electrodes

    if extent is None:
        bounds = world_bounds_3d(world)
        x_min, x_max, y_min, y_max, z_min, z_max = bounds
        if plane == "xy":
            extent = (
                x_min - padding_m,
                x_max + padding_m,
                y_min - padding_m,
                y_max + padding_m,
            )
        elif plane == "xz":
            # In z, "padding" should not push the surface (z=0)
            # below the soil — but z<0 (overhead) is legitimate.
            # We pad symmetrically and rely on plot inversion.
            extent = (
                x_min - padding_m,
                x_max + padding_m,
                z_min - padding_m,
                z_max + padding_m,
            )
        else:
            raise ValueError(f"plane must be 'xy' or 'xz', got {plane!r}.")

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    # 1. Surface line for the xz view — emphasises the soil
    #    boundary at z = 0.
    if plane == "xz":
        ax.axhline(
            0.0, color="#666666", linestyle=":", linewidth=0.8, alpha=0.7, zorder=1
        )

    # 2. Conductors first (so electrodes draw on top).
    if show_conductors:
        for c in world.conductors:
            _draw_conductor_2d(ax, c, plane)

    # 3. Electrodes — reuse the existing helper for consistency
    #    with the field plots.
    _draw_electrodes(ax, world, plane)

    # 4. Sources on top.
    if show_sources:
        for s in world.sources:
            _draw_source_2d(ax, s, world, plane)

    # 5. Optional annotations.
    if annotate_electrodes:
        for e in world.electrodes:
            cp = e.connection_point
            x, y = _project_2d(cp, plane)
            ax.annotate(
                e.name,
                (x, y),
                textcoords="offset points",
                xytext=(5, 5),
                fontsize=7,
                alpha=0.85,
                zorder=6,
            )

    ax.set_xlim(extent[0], extent[1])
    ax.set_ylim(extent[2], extent[3])
    ax.set_aspect("equal")
    ax.grid(True, alpha=0.3)
    if plane == "xy":
        ax.set_xlabel("x in m")
        ax.set_ylabel("y in m")
    else:
        ax.set_xlabel("x in m")
        ax.set_ylabel("z in m (depth)")
        ax.invert_yaxis()  # soil downwards

    if title is None:
        n_e = len(world.electrodes)
        n_c = len(world.conductors)
        n_s = len(world.sources)
        title = (
            f"World '{world.name}' — {plane} geometry "
            f"({n_e} electrodes, {n_c} conductors, {n_s} sources)"
        )
    ax.set_title(title)

    _build_legend(ax, world, show_conductors, show_sources)
    fig.tight_layout()
    return fig

plot_world_3d

plot_world_3d(world: 'World', *, show_conductors: bool = True, show_sources: bool = True, show_surface: bool = True, figsize: tuple[float, float] = (9.0, 7.0), elev: float = 22.0, azim: float = -55.0, title: str | None = None)

3-D wireframe of a World using mpl_toolkits.mplot3d.

The \(z\) axis is inverted so that depth points downwards on screen (groundfield convention: positive \(z\) is into the soil). A faint grey surface plane at \(z = 0\) marks the soil surface.

Parameters:

Name Type Description Default
world 'World'

World to draw.

required
show_conductors bool True
show_sources bool True
show_surface bool

If True (default), render a translucent grey square at \(z = 0\) over the world's \((x, y)\) bounding box plus 5 m padding.

True
figsize tuple[float, float]

Matplotlib figure size in inches.

(9.0, 7.0)
elev float

Initial viewing angles (passed to Axes3D.view_init()).

22.0
azim float

Initial viewing angles (passed to Axes3D.view_init()).

22.0
title str | None

Optional title override.

None

Returns:

Type Description
Figure
Source code in src/groundfield/postprocess/geometry_plot.py
def plot_world_3d(
    world: "World",
    *,
    show_conductors: bool = True,
    show_sources: bool = True,
    show_surface: bool = True,
    figsize: tuple[float, float] = (9.0, 7.0),
    elev: float = 22.0,
    azim: float = -55.0,
    title: str | None = None,
):
    """3-D wireframe of a :class:`World` using ``mpl_toolkits.mplot3d``.

    The :math:`z` axis is **inverted** so that depth points
    downwards on screen (groundfield convention: positive
    :math:`z` is into the soil). A faint grey surface plane at
    :math:`z = 0` marks the soil surface.

    Parameters
    ----------
    world
        World to draw.
    show_conductors, show_sources
        See :func:`plot_world`.
    show_surface
        If ``True`` (default), render a translucent grey square
        at :math:`z = 0` over the world's :math:`(x, y)` bounding
        box plus 5 m padding.
    figsize
        Matplotlib figure size in inches.
    elev, azim
        Initial viewing angles (passed to
        :meth:`Axes3D.view_init`).
    title
        Optional title override.

    Returns
    -------
    matplotlib.figure.Figure
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401  (registers 3d projection)

    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection="3d")

    bounds = world_bounds_3d(world)
    x_min, x_max, y_min, y_max, z_min, z_max = bounds

    # Optional surface plane at z = 0.
    if show_surface and (world.electrodes or world.conductors):
        pad = 5.0
        xs = np.array([[x_min - pad, x_max + pad], [x_min - pad, x_max + pad]])
        ys = np.array([[y_min - pad, y_min - pad], [y_max + pad, y_max + pad]])
        zs = np.zeros_like(xs)
        ax.plot_surface(
            xs, ys, zs, color="#cccccc", alpha=0.25, edgecolor="none", linewidth=0
        )

    if show_conductors:
        for c in world.conductors:
            _draw_conductor_3d(ax, c)

    for e in world.electrodes:
        _draw_electrode_3d(ax, e)

    if show_sources:
        for s in world.sources:
            _draw_source_3d(ax, s, world)

    ax.set_xlabel("x in m")
    ax.set_ylabel("y in m")
    ax.set_zlabel("z in m (depth)")
    # Invert z so that depth points downwards on screen.
    ax.invert_zaxis()
    ax.view_init(elev=elev, azim=azim)
    if title is None:
        title = (
            f"World '{world.name}' — 3-D geometry "
            f"({len(world.electrodes)} electrodes, "
            f"{len(world.conductors)} conductors, "
            f"{len(world.sources)} sources)"
        )
    ax.set_title(title)
    fig.tight_layout()
    return fig

world_bounds_3d

world_bounds_3d(world: 'World') -> tuple[float, float, float, float, float, float]

Smallest axis-aligned \((x, y, z)\) bounding box of the world.

Inspects every electrode in World.electrodes and every conductor endpoint in World.conductors, returning the six bounds (x_min, x_max, y_min, y_max, z_min, z_max) in metres.

The \((x, y)\) portion is consistent with groundfield.postprocess.plotting.world_bounds_xy() but additionally includes conductor endpoints — important for overhead lines or measurement leads that extend well beyond the electrode footprint. The \(z\) portion uses

Parameters:

Name Type Description Default
world 'World'

World whose electrodes and conductors are inspected.

required

Returns:

Type Description
tuple

(x_min, x_max, y_min, y_max, z_min, z_max) in metres. For an empty world the result is the trivial (0, 0, 0, 0, 0, 0); callers should add positive padding before plotting.

Source code in src/groundfield/postprocess/geometry_plot.py
def world_bounds_3d(
    world: "World",
) -> tuple[float, float, float, float, float, float]:
    """Smallest axis-aligned :math:`(x, y, z)` bounding box of the world.

    Inspects every electrode in :attr:`World.electrodes` and every
    conductor endpoint in :attr:`World.conductors`, returning the
    six bounds ``(x_min, x_max, y_min, y_max, z_min, z_max)`` in
    metres.

    The :math:`(x, y)` portion is consistent with
    :func:`groundfield.postprocess.plotting.world_bounds_xy` but
    additionally includes conductor endpoints — important for
    overhead lines or measurement leads that extend well beyond
    the electrode footprint. The :math:`z` portion uses

    * :class:`RodElectrode`: ``[position[2], position[2] + length]``
      (head + foot of the rod).
    * :class:`RingElectrode`, :class:`StripElectrode`,
      :class:`PolylineElectrode`, :class:`MeshElectrode`,
      :class:`GridMeshElectrode`: the :math:`z` coordinate(s) of the
      electrode (single buried depth).
    * Conductors: ``min/max`` over both endpoint :math:`z` values
      (catches overhead :math:`z<0` and buried :math:`z>0`).

    Parameters
    ----------
    world
        World whose electrodes and conductors are inspected.

    Returns
    -------
    tuple
        ``(x_min, x_max, y_min, y_max, z_min, z_max)`` in metres.
        For an empty world the result is the trivial
        ``(0, 0, 0, 0, 0, 0)``; callers should add positive
        padding before plotting.
    """
    from groundfield.geometry.electrodes import (
        GridMeshElectrode,
        MeshElectrode,
        PolylineElectrode,
        RingElectrode,
        RodElectrode,
        StarElectrode,
        StripElectrode,
    )

    if not world.electrodes and not world.conductors:
        return (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

    xs: list[float] = []
    ys: list[float] = []
    zs: list[float] = []

    for e in world.electrodes:
        if isinstance(e, RodElectrode):
            x, y, z = e.position
            xs.append(x)
            ys.append(y)
            zs.extend([z, z + e.length])
        elif isinstance(e, RingElectrode):
            cx, cy, cz = e.center
            xs.extend([cx - e.radius, cx + e.radius])
            ys.extend([cy - e.radius, cy + e.radius])
            zs.append(cz)
        elif isinstance(e, StripElectrode):
            xs.extend([e.start[0], e.end[0]])
            ys.extend([e.start[1], e.end[1]])
            zs.extend([e.start[2], e.end[2]])
        elif isinstance(e, (MeshElectrode, GridMeshElectrode)):
            cx, cy, cz = e.corner
            dx, dy = e.size
            xs.extend([cx, cx + dx])
            ys.extend([cy, cy + dy])
            zs.append(cz)
        elif isinstance(e, PolylineElectrode):
            xs.extend(v[0] for v in e.vertices)
            ys.extend(v[1] for v in e.vertices)
            zs.extend(v[2] for v in e.vertices)
        elif isinstance(e, StarElectrode):
            for start, end in e.edges:
                xs.extend([start[0], end[0]])
                ys.extend([start[1], end[1]])
                zs.extend([start[2], end[2]])
        else:  # pragma: no cover — defensive
            cp = e.connection_point
            xs.append(cp[0])
            ys.append(cp[1])
            zs.append(cp[2])

    for c in world.conductors:
        for endpoint in (c.start, c.end):
            xs.append(endpoint[0])
            ys.append(endpoint[1])
            zs.append(endpoint[2])

    return (min(xs), max(xs), min(ys), max(ys), min(zs), max(zs))