Skip to content

Coupling

The coupling package collects the coupling relations the solvers consume: the Neumann partial inductances between conductor segments (inductance, ADR-0004), the earth-return correction of that inductance — Carson's per-metre series for long parallel wires over homogeneous earth (carson, ADR-0005) and the geometric Sommerfeld/Pollaczek integral for any geometry and any number of layers (sommerfeld_inductance, ADR-0006) — and the scalar Green's function of two-layer soil for electrodes through the layer interface (layered_green, ADR-0007). There is no capacitive coupling: below 1 kHz it is negligible for buried conductors.

Mathematical and physical context

Conductors with inductance_model="neumann" are split into segments whose series impedance matrix is

\[ \mathbf{Z}_b(\omega) = \mathbf{R} + j\omega\,\mathbf{L} + \Delta\mathbf{Z}_\text{earth}(\omega), \qquad L_{ij} = \frac{\mu_0}{4\pi}\int_{\Gamma_i}\!\int_{\Gamma_j} \frac{\mathrm{d}\mathbf{l}_i\cdot\mathrm{d}\mathbf{l}_j}{\lvert\mathbf{r}_i - \mathbf{r}_j\rvert}, \]

the Neumann double-line integral (closed forms for parallel and touching segments, Gauss–Legendre otherwise) plus the internal inductance \(\mu_0\ell/(8\pi)\) on the diagonal. The earth enters twice: as an image term in \(\mathbf{L}\) and as the frequency-dependent correction \(\Delta\mathbf{Z}_\text{earth}\); the two are only meaningful together, which is why every builder takes the same image= convention ("none": free space; "additive": perfect magnetic mirror; "antiparallel": perfect electric conductor).

Carson (1926). For a long straight wire above homogeneous earth of conductivity \(\sigma\), against the antiparallel image,

\[ \Delta Z_\text{Carson} = \frac{\omega\mu_0}{\pi}\bigl[P(a,\theta) + jQ(a,\theta)\bigr], \qquad a = D\sqrt{\omega\mu_0\sigma} = \frac{\sqrt{2}\,D}{\delta}, \]

with \(D = 2h\) (self) or the image distance of a pair (mutual) and \(\delta = \sqrt{2/(\omega\mu_0\sigma)}\) the skin depth in the soil. \(P, Q\) are evaluated by Carson's series (\(a \le 0.25\)), quadrature (\(0.25 < a \le 15\)) and the asymptotic expansion (\(a > 15\)). The correction is per metre and scaled by the segment-pair length, so it is exact only for long parallel wires; for a layered soil the upper-layer resistivity is used with a warning.

Sommerfeld / Pollaczek. The quasi-static vector-potential Green's function of the layered half-space,

\[ G(\rho, z, z') = \delta_{kj}\,\frac{e^{-\gamma_k R}}{R} + \int_0^\infty \lambda\,F_{kj}(\lambda; z, z')\,J_0(\lambda\rho)\,\mathrm{d}\lambda, \qquad \gamma_k^2 = j\omega\mu_0\sigma_k , \]

is integrated over every segment pair (time convention \(e^{+j\omega t}\)). It handles short and non-parallel wires, buried and overhead conductors and any number of layers, and is the default (Engine.earth_inductive_model="sommerfeld"). In the long-wire limit it gives the Pollaczek line impedance with the earth-return resistance \(R' \approx \omega\mu_0/8\).

Choosing the earth-return model

earth_inductive_model Use for Limits
"sommerfeld" (default) quantitative \(Z(f)\) of buried and overhead conductors, layered soil, short or bent conductors cost grows with the number of segment pairs; the default tabulated assembly (Engine.sommerfeld_assembly) shares one table per pair of depth groups, "exact" integrates every pair
"carson_series" fast scoping of long parallel conductors over homogeneous soil per-metre approximation; layered soil uses \(\rho_1\) (warning); rejects segments in the surface plane
"perfect_mirror" diagnostic baseline only frequency-independent image, far from the physics of buried conductors below 1 kHz

The theory, the validation against Carson's and Pollaczek's line impedances, and the history of these models are on the earth return page.

Example

The per-metre impedance of a conductor buried 0.7 m deep (wire radius 5 mm, internal inductance included via \(\mathrm{GMR} = a\,e^{-1/4}\)), from the closed-form references the solver is validated against:

import math

from groundfield.references import earth_return, pollaczek

gmr = 0.005 * math.exp(-0.25)
for f in (50.0, 1000.0):
    z_carson = earth_return.carson_self_impedance(100.0, f, gmr=gmr)       # Ω/m
    z_buried = pollaczek.pollaczek_self_impedance(100.0, 100.0, 5.0, f, depth=0.7, gmr=gmr)
    z_layered = pollaczek.pollaczek_self_impedance(100.0, 1000.0, 5.0, f, depth=0.7, gmr=gmr)
    # homogeneous soil: the buried (Pollaczek) and Carson line impedances agree
    assert abs(z_buried - z_carson) / abs(z_carson) < 1e-3
    # earth-return resistance omega*mu0/8: 49.3 mOhm/km at 50 Hz
    assert abs(z_carson.real - earth_return.carson_earth_return_resistance(f)) < 1e-12
    # 1000 Ohm m below 5 m of 100 Ohm m soil: about 9 % more reactance
    assert 1.08 < z_layered.imag / z_buried.imag < 1.10

Neumann inductance (ADR-0004)

inductance

Self- and mutual-inductance helpers for distributed conductors.

This module implements the inductance physics described in ADR-0004. It provides three public functions:

  • thin_wire_self_inductance() — closed-form self-inductance of a straight thin-wire segment of length \(\ell\) and radius \(a\) (Grover 1946): \(L_\text{self} = (\mu_0\,\ell)/(2\pi) \bigl[\ln(2\ell/a) - 1\bigr]\).
  • parallel_segments_mutual() — closed-form mutual inductance of two parallel coaxial segments of equal length \(\ell\) at perpendicular distance \(d\).
  • neumann_mutual() — generic Neumann double-line integral via two-point Gauss–Legendre quadrature, valid for any 3-D segment-pair geometry.

Earth-image contributions are handled by the caller: for a perfect-mirror earth the caller adds the integral against the mirror image of the source segment (see perfect_mirror_self_pair_inductance() and the assembly logic in build_inductance_matrix()).

Conventions

Image convention (image=). The earth image of a segment \((p_1 \to p_2)\) is the segment \((p_1' \to p_2')\) with \(z \to -z\) (the \(z\)-axis points into the soil). Its Neumann integral against a partner carries the orientation through the dot product, so the mirrored-endpoint image is the image in a perfect magnetic conductor (horizontal currents co-directed, vertical currents reversed). Three conventions are offered:

  • "none" — free space, \(L = L_\text{dir}\). The exact quasi-static baseline of the Sommerfeld earth-return correction (groundfield.coupling.sommerfeld_inductance): at DC the soil is magnetically transparent.
  • "additive" — \(L = L_\text{dir} + L_\text{img}\), the ADR-0004 "perfect mirror" (historic default, use_image=True).
  • "antiparallel" — \(L = L_\text{dir} - L_\text{img}\), the perfect-electric-conductor image (horizontal currents reversed). This is the baseline against which Carson's correction \(\Delta Z = (\omega\mu_0/\pi)(P + jQ)\) is defined (groundfield.coupling.carson). A perfect conductor screens the soil: a pair on opposite sides of the surface has \(L = 0\) (since audit round 2 of the calendar release; the mirrored-endpoint image of a buried partner lands above ground and gave \(\ln(D_\text{mirror}/D) < 0\)), and its whole coupling is in the earth-return correction.

An earth-return correction matrix is only meaningful together with the image convention of the inductance matrix it is added to; the correction builders therefore take the same image= argument.

Internal inductance (include_internal=). The diagonal (partial self) term is the external thin-wire inductance plus, by default, the DC internal inductance of a solid round conductor, \(\mu_0 \ell/(8\pi)\). Every function of this package that returns a self term uses this one convention, controlled by include_internal (default True; the solver passes False for the conductors of conductor_type="cable_shield", thin-walled tubes, user decision Q33). A per-unit-length reference that includes the internal flux uses the geometric mean radius \(\mathrm{GMR} = a\,e^{-1/4}\); with include_internal=False the matching reference uses \(\mathrm{GMR} = a\). The frequency dependence of the internal impedance (skin effect) is provided by groundfield.conductors.Conductor.internal_impedance_per_length() as a correction relative to this DC convention.

Wires lying beside each other. Where a point of one wire lies beside another wire (its foot on that wire's axis falls inside the wire) closer than the sum of the radii \(r_i + r_j\) — two conductors in one trench, a service drop routed back along its PEN main, coincident leads, wires leaving a junction or crossing at a small angle — the distance from the other axis is taken as \(r_i + r_j\) (touching wires) inside the Neumann integral of build_inductance_matrix(), or as the radius of the thicker wire where the thinner one runs inside it and the thicker one is marked as a cable shield (shields=; a core inside a cable shield couples as a filament inside a thin tube). The marker is explicit since the user decision Q32 of 2026.11: two unmarked wires on one axis are separate conductors that touch. For parallel wires the rule refers to whole conductors (conductors=, one label per conductor, as the solver passes them; audit W1A-02 of the calendar release): a thinner wire inside a cable shield couples at the shield radius at every axial offset (exact for a filament on the axis of a thin tube), and a point lies beside another conductor when its foot falls inside that conductor, so the sub-pieces of two conductors lying beside each other add up to the lumped pair (a 100 m coax in 1 m pieces read 2.2 % low before). Pieces tilted against each other by more than the closed form's tolerance of about 4.5e-5 rad, at any angle and whatever their length, get the same two readings with the stretches inside, beside and away from the partner found exactly (audits W1R2-01, W1R3-01, W1R3-02; a core tilted by 4.5e-5 rad read 7.4 % low in 0.25 m pieces, with a step at the tolerance; until W1R3 the rule stopped where the lateral distance changed by more than the touching distance along a piece, or at \(|\cos\varphi| = 0.99\), and a core crossing its shield's axis read -8.6e-5 of the loop off the lumped pair in 10 m pieces, two wires leaving a junction stepped by 1.5e-3 at 8.1°). The filament integral diverges for coincident axes (two coincident 50 m leads read +587j Ω at 50 Hz) and exceeds the self inductance once the wires are closer than about their radius (an indefinite matrix, a TN network with drops along its PEN main had a negative input reactance). The rule acts pointwise and on both one-sided integrals, so the value is continuous in the geometry and independent of the order and direction of the segments (audit round 3 of the calendar release; the whole-pair switch of audit round 2 depended on which segment was the row). Chain neighbours and bends turning by less than 90° keep their closed forms.

Close pairs. Nearly parallel wires close together whose directions differ by more than the closed form's tolerance, crossing and skew pairs are integrated semi-analytically with touching="exact"; the 16x16 rule was +12 % at 10 cm and up to +250 % at 1 cm for two 5 m segments (audit round 2 of the calendar release).

Touching segments (touching=). The Neumann integrand is log-singular for segments that share an end point (bends, chain neighbours) or lie on one axis. "exact" (the default since the calendar release 2026.11) uses the closed forms (Grover 1946: two filaments meeting at a point; coaxial filaments with a gap), accurate to machine precision; a straight wire split into any number of segments keeps the self inductance of the unsplit wire. "quadrature" (the default up to 0.15.0, kept to reproduce old numbers) integrates such pairs with the 16x16 Gauss–Legendre rule, which is accurate to about -0.3 % ... +0.8 % for them (review pass 10, finding 10.46). The closed forms of all coaxial pairs of a segment are evaluated in one vectorised call — a straight conductor of \(M\) sub-segments has \(M(M-1)/2\) of them — bit-identical with the scalar routine (audit round 2 of the calendar release, A2C-5).

References
  • Grover, F. W. (1946). Inductance Calculations: Working Formulas and Tables. Dover (reprint 2004).
  • Sunde, E. D. (1968). Earth Conduction Effects in Transmission Systems. Dover, ch. 7.
  • Paul, C. R. (2010). Inductance: Loop and Partial. Wiley.

ImageConvention module-attribute

ImageConvention = Literal['none', 'additive', 'antiparallel']

Image convention of an inductance matrix.

  • "none": free space, no image;
  • "additive": perfect magnetic mirror at the soil surface (ADR-0004);
  • "antiparallel": perfect electric mirror, Carson's baseline.

MU_0 module-attribute

MU_0 = 4e-07 * math.pi

Vacuum permeability μ0 = 4π · 10⁻⁷ H/m (the conventional value).

Exact in the pre-2019 SI; the CODATA 2018 value 1.25663706212e-6 differs by 5.5 · 10⁻¹⁰ relative, which is irrelevant here.

TouchingRule module-attribute

TouchingRule = Literal['quadrature', 'exact']

Treatment of touching and coaxial segment pairs in the Neumann integral.

  • "exact": closed forms (the default);
  • "quadrature": the 16 x 16 Gauss–Legendre rule (the default up to 0.15.0).

build_carson_correction_matrices

build_carson_correction_matrices(seg_endpoints: ndarray, wire_radii: ndarray, *, omegas, sigma_earth: float, image: ImageConvention = 'antiparallel') -> np.ndarray

Carson earth-return correction matrices for several frequencies.

Multi-frequency form of build_carson_correction_matrix(): the frequency-independent tiling geometry (pair classification, axial overlaps, Carson heights) is built once and every frequency only evaluates the per-metre Carson values. Entry k equals build_carson_correction_matrix(..., omega=omegas[k]) bit for bit.

Parameters:

Name Type Description Default
seg_endpoints ndarray

Array of shape (M, 2, 3) (m), as in build_inductance_matrix().

required
wire_radii ndarray

Per-branch wire radii in m, shape (M,).

required
omegas

Angular frequencies in rad/s (sequence of floats); entries <= 0 give zero matrices.

required
sigma_earth float

Earth conductivity in S/m.

required
image ImageConvention

Image convention of the inductance matrix this correction is added to (see build_carson_correction_matrix()).

'antiparallel'

Returns:

Name Type Description
dZ np.ndarray, shape (n_f, M, M), dtype complex

Correction matrices in Ω.

Source code in src/groundfield/coupling/inductance.py
def build_carson_correction_matrices(
    seg_endpoints: np.ndarray,  # shape (M, 2, 3)
    wire_radii: np.ndarray,  # shape (M,)
    *,
    omegas,
    sigma_earth: float,
    image: ImageConvention = "antiparallel",
) -> np.ndarray:
    """Carson earth-return correction matrices for several frequencies.

    Multi-frequency form of :func:`build_carson_correction_matrix`: the
    frequency-independent tiling geometry (pair classification, axial
    overlaps, Carson heights) is built once and every frequency only
    evaluates the per-metre Carson values. Entry ``k`` equals
    ``build_carson_correction_matrix(..., omega=omegas[k])`` bit for
    bit.

    Parameters
    ----------
    seg_endpoints
        Array of shape ``(M, 2, 3)`` (m), as in
        :func:`build_inductance_matrix`.
    wire_radii
        Per-branch wire radii in m, shape ``(M,)``.
    omegas
        Angular frequencies in rad/s (sequence of floats); entries
        ``<= 0`` give zero matrices.
    sigma_earth
        Earth conductivity in S/m.
    image
        Image convention of the inductance matrix this correction is
        added to (see :func:`build_carson_correction_matrix`).

    Returns
    -------
    dZ : np.ndarray, shape (n_f, M, M), dtype complex
        Correction matrices in Ω.
    """
    mode = _resolve_image(image, None)
    omegas = [float(om) for om in np.atleast_1d(np.asarray(omegas, dtype=float))]
    from groundfield.coupling.carson import (
        carson_mixed_mutual_correction,
        carson_mutual_correction,
    )

    M = seg_endpoints.shape[0]
    out = np.zeros((len(omegas), M, M), dtype=complex)
    if M == 0 or sigma_earth <= 0.0 or all(om <= 0.0 for om in omegas):
        return out
    radii = np.asarray(wire_radii, dtype=float)
    heights, lengths, horizontal, entries, fallback = _carson_pair_plan(
        seg_endpoints, radii
    )
    p1 = seg_endpoints[:, 0, :].astype(float, copy=False)
    p2 = seg_endpoints[:, 1, :].astype(float, copy=False)
    above = _overhead(p1, p2)
    opposite = above[:, None] != above[None, :]
    fallback_values = (
        _carson_fallback_values(seg_endpoints, radii, fallback, omegas, sigma_earth)
        if fallback
        else {}
    )
    M_conv = None
    if mode != "antiparallel":
        # Carson's correction is defined against the anti-parallel
        # image: L_anti = L_dir - L_img on one side of the surface, 0
        # across it. Moving it onto an inductance matrix with another
        # image convention, dZ -> dZ - scale jw M_conv:
        #   additive: L_add - L_anti = 2 L_img  |  L_dir + L_img (across)
        #   none:     L_dir - L_anti =   L_img  |  L_dir         (across)
        M_conv = _image_inductance_matrix(seg_endpoints, wire_radii=radii)
        if opposite.any():
            L_dir = _direct_mutual_matrix(seg_endpoints, radii)
            if mode == "additive":
                M_conv[opposite] = 0.5 * (L_dir[opposite] + M_conv[opposite])
            else:
                M_conv[opposite] = L_dir[opposite]
    for k, omega in enumerate(omegas):
        if omega <= 0.0:
            continue
        dZ = out[k]
        for i in range(M):
            if not horizontal[i]:
                continue  # inclined / vertical: Sommerfeld (fallback)
            # Diagonal: self correction (parallel-to-self ⇒ θ = 0),
            # per-unit-length value times this branch's length.
            dz_per_m = carson_mutual_correction(
                omega=omega,
                height_i=heights[i],
                height_j=heights[i],
                horizontal_distance=0.0,
                sigma_earth=sigma_earth,
            )
            dZ[i, i] = dz_per_m * lengths[i]
        for i, j, d_h, factor, sign in entries:
            if opposite[i, j]:
                # Overhead wire parallel to a buried one: the field
                # transmitted into the soil (no PEC baseline across the
                # surface; audit A2C-1).
                h_air, d_soil = (
                    (heights[i], heights[j]) if above[i] else (heights[j], heights[i])
                )
                dz_per_m = carson_mixed_mutual_correction(
                    omega, h_air, d_soil, d_h, sigma_earth
                )
            else:
                dz_per_m = carson_mutual_correction(
                    omega=omega,
                    height_i=heights[i],
                    height_j=heights[j],
                    horizontal_distance=d_h,
                    sigma_earth=sigma_earth,
                )
            # += : a tilted pair has one entry per node of its stretch
            dZ[i, j] += sign * dz_per_m * factor
            dZ[j, i] = dZ[i, j]
        for (i, j), vals in fallback_values.items():
            dZ[i, j] = dZ[j, i] = vals[k]
        if M_conv is not None:
            scale = 2.0 if mode == "additive" else 1.0
            dZ -= scale * 1j * omega * M_conv
    return out

build_carson_correction_matrix

build_carson_correction_matrix(seg_endpoints: ndarray, wire_radii: ndarray, *, omega: float, sigma_earth: float, image: ImageConvention = 'antiparallel') -> np.ndarray

Assemble the dense Carson earth-return correction matrix.

Returns the per-segment-pair impedance correction \(\Delta Z^{(i,j)}_\text{Carson}(\omega)\) described in ADR-0005. The output has the same shape as build_inductance_matrix() but is complex and frequency-dependent — it is therefore rebuilt at every frequency by the solver (or built for all frequencies at once with build_carson_correction_matrices()).

Image baseline (review pass 10, findings 10.20 / F32)

Carson's correction \((\omega\mu_0/\pi)(P + jQ)\) is defined against the anti-parallel (perfect-electric-conductor) image: the complete series impedance is \(Z = j\omega L_\text{antiparallel} + \Delta Z_\text{Carson}\) with \(L_\text{antiparallel}\) from build_inductance_matrix(image="antiparallel"). The image argument names the image convention of the inductance matrix the returned correction is added to; for "additive" / "none" the matrix is shifted by \(-2j\omega L_\text{img}\) / \(-j\omega L_\text{img}\) so that the sum is the same physical impedance. The default "antiparallel" returns the plain Carson correction (bit-identical to earlier releases). The docstring of earlier releases said the correction goes "on top of the perfect-mirror (additive) Neumann matrix" — that pairing double-counts the image and gives 1.66–2.25× the earth-return reactance on 100 m – 1 km lines.

Tiling convention (audit 2026-07-08, WP-C3)

Carson's correction is an infinite-wire, per-unit-length concept. To make the assembled matrix consistent — and, crucially, convergent under mesh refinement — the per-pair entries tile the per-unit-length values without double counting:

  • Diagonal dZ[i, i]: self correction per metre × segment length. Summed over a refined straight wire this reproduces the full z'_self · ℓ exactly, independent of the segment count.
  • Collinear pairs (same axis, negligible perpendicular offset): zero. The infinite-wire self value on the diagonal already contains the interaction with the rest of the same wire.
  • Near-parallel pairs on distinct axes (|cosφ| > 0.99) of near-horizontal segments: mutual correction per metre at the perpendicular horizontal axis separation, weighted by the axial overlap length of the two segment intervals — measured along the bisector of the two axes for a pair that is not exactly parallel, so that the order of the segments does not matter (audit round 3 of the calendar release; on the first segment's axis the entries moved by up to 3.1 % of the largest one). Non-overlapping (e.g. staggered or end-to-end) pairs contribute zero. Two different conductors that overlap on one axis are wires lying side by side: the mutual at the distance of touching wires \(r_i + r_j\) (they used to get none).
  • Pairs on opposite sides of the surface (an overhead wire parallel to a buried one): the field transmitted into the soil, carson_mixed_mutual_correction() — the anti-parallel baseline of such a pair is zero (audit round 2 of the calendar release, A2C-1; the buried wire used to be treated as an overhead wire at height \(|z|\) on the mirrored-endpoint image: -36 % mutual reactance for a lead 1 m above a PEN at 0.7 m, 1 kHz).
  • Outside Carson's domain — oblique pairs (1e-9 < |cosφ| ≤ 0.99) and every pair and self term of a segment inclined by more than 8.1 deg: the exact quasi-static Sommerfeld correction of a homogeneous earth of the same conductivity (tabulated assembly), moved onto the anti-parallel baseline. Up to audit round 2 oblique pairs got the projected geometric-mean heuristic \(\sqrt{\ell_i\ell_j}\,|\cos\varphi|\) per segment pair, which grows with the number of segments (a probe lead turning 8.1 deg against the feed lead changed the reading 17.6-fold). At the domain boundary the result steps from the per-metre tiling to the Sommerfeld value, by the model error of the tiling there (two 1 km leads 2 m apart, 1 kHz: 13 %). Orthogonal pairs contribute zero by symmetry.
Earth-conductivity sign convention

In groundfield the \(z\)-axis points into the soil. A wire above ground has \(z < 0\) and height = -z > 0. A wire just below the surface has \(z > 0\) and we use height = z as the Sunde-equivalent depth (Carson's \(h\)).

Parameters:

Name Type Description Default
seg_endpoints ndarray

Array of shape (M, 2, 3) in m — same layout as build_inductance_matrix().

required
wire_radii ndarray

Per-branch wire radii in metres (only used as a regulariser for a wire exactly at the surface; the Carson kernel itself does not depend on the radius).

required
omega float

Angular frequency in rad/s.

required
sigma_earth float

Earth conductivity in S/m.

required
image ImageConvention

Image convention of the inductance matrix the correction is added to: "antiparallel" (default, Carson's own baseline), "additive" or "none".

'antiparallel'

Returns:

Name Type Description
dZ np.ndarray, shape (M, M), dtype complex

Symmetric Carson correction matrix in \(\Omega\).

Source code in src/groundfield/coupling/inductance.py
def build_carson_correction_matrix(
    seg_endpoints: np.ndarray,  # shape (M, 2, 3)
    wire_radii: np.ndarray,  # shape (M,)
    *,
    omega: float,
    sigma_earth: float,
    image: ImageConvention = "antiparallel",
) -> np.ndarray:
    """Assemble the dense Carson earth-return correction matrix.

    Returns the per-segment-pair impedance correction
    $\\Delta Z^{(i,j)}_\\text{Carson}(\\omega)$ described in ADR-0005.
    The output has the same shape as :func:`build_inductance_matrix`
    but is **complex** and **frequency-dependent** — it is therefore
    rebuilt at every frequency by the solver (or built for all
    frequencies at once with :func:`build_carson_correction_matrices`).

    Image baseline (review pass 10, findings 10.20 / F32)
    -----------------------------------------------------
    Carson's correction $(\\omega\\mu_0/\\pi)(P + jQ)$ is defined
    against the **anti-parallel** (perfect-electric-conductor) image:
    the complete series impedance is
    $Z = j\\omega L_\\text{antiparallel} + \\Delta Z_\\text{Carson}$
    with $L_\\text{antiparallel}$ from
    ``build_inductance_matrix(image="antiparallel")``. The ``image``
    argument names the image convention of the inductance matrix the
    returned correction is **added to**; for ``"additive"`` /
    ``"none"`` the matrix is shifted by $-2j\\omega L_\\text{img}$ /
    $-j\\omega L_\\text{img}$ so that the sum is the same physical
    impedance. The default ``"antiparallel"`` returns the plain Carson
    correction (bit-identical to earlier releases). The docstring of
    earlier releases said the correction goes "on top of the
    perfect-mirror (additive) Neumann matrix" — that pairing
    double-counts the image and gives 1.66–2.25× the earth-return
    reactance on 100 m – 1 km lines.

    Tiling convention (audit 2026-07-08, WP-C3)
    -------------------------------------------
    Carson's correction is an *infinite-wire, per-unit-length*
    concept. To make the assembled matrix consistent — and, crucially,
    **convergent under mesh refinement** — the per-pair entries tile
    the per-unit-length values without double counting:

    - **Diagonal** ``dZ[i, i]``: self correction per metre × segment
      length. Summed over a refined straight wire this reproduces the
      full ``z'_self · ℓ`` exactly, independent of the segment count.
    - **Collinear pairs** (same axis, negligible perpendicular
      offset): **zero.** The infinite-wire self value on the diagonal
      already contains the interaction with the rest of the same
      wire.
    - **Near-parallel pairs on distinct axes** (``|cosφ| > 0.99``) of
      near-horizontal segments: mutual correction per metre at the
      **perpendicular** horizontal axis separation, weighted by the
      **axial overlap length** of the two segment intervals — measured
      along the bisector of the two axes for a pair that is not exactly
      parallel, so that the order of the segments does not matter
      (audit round 3 of the calendar release; on the first segment's axis
      the entries moved by up to 3.1 % of the largest one).
      Non-overlapping (e.g. staggered or end-to-end) pairs contribute
      zero. Two different conductors that overlap on one axis are
      wires lying side by side: the mutual at the distance of touching
      wires $r_i + r_j$ (they used to get none).
    - **Pairs on opposite sides of the surface** (an overhead wire
      parallel to a buried one): the field transmitted into the soil,
      :func:`~groundfield.coupling.carson.carson_mixed_mutual_correction`
      — the anti-parallel baseline of such a pair is zero (audit round 2
      of the calendar release, A2C-1; the buried wire used to be treated
      as an overhead wire at height $|z|$ on the mirrored-endpoint image:
      -36 % mutual reactance for a lead 1 m above a PEN at 0.7 m, 1 kHz).
    - **Outside Carson's domain** — oblique pairs
      (``1e-9 < |cosφ| ≤ 0.99``) and every pair and self term of a
      segment inclined by more than 8.1 deg: the exact quasi-static
      Sommerfeld correction of a homogeneous earth of the same
      conductivity (tabulated assembly), moved onto the anti-parallel
      baseline. Up to audit round 2 oblique pairs got the projected
      geometric-mean heuristic $\\sqrt{\\ell_i\\ell_j}\\,|\\cos\\varphi|$ per
      segment pair, which grows with the number of segments (a probe lead
      turning 8.1 deg against the feed lead changed the reading
      17.6-fold). At the domain boundary the result steps from the
      per-metre tiling to the Sommerfeld value, by the model error of
      the tiling there (two 1 km leads 2 m apart, 1 kHz: 13 %).
      Orthogonal pairs contribute zero by symmetry.

    Earth-conductivity sign convention
    ----------------------------------
    In ``groundfield`` the $z$-axis points *into* the soil. A wire
    above ground has $z < 0$ and ``height = -z > 0``. A wire just
    below the surface has $z > 0$ and we use ``height = z`` as the
    Sunde-equivalent depth (Carson's $h$).

    Parameters
    ----------
    seg_endpoints
        Array of shape ``(M, 2, 3)`` in m — same layout as
        :func:`build_inductance_matrix`.
    wire_radii
        Per-branch wire radii in metres (only used as a regulariser
        for a wire exactly at the surface; the Carson kernel itself
        does not depend on the radius).
    omega
        Angular frequency in rad/s.
    sigma_earth
        Earth conductivity in S/m.
    image
        Image convention of the inductance matrix the correction is
        added to: ``"antiparallel"`` (default, Carson's own baseline),
        ``"additive"`` or ``"none"``.

    Returns
    -------
    dZ : np.ndarray, shape (M, M), dtype complex
        Symmetric Carson correction matrix in $\\Omega$.
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return np.zeros(
            (seg_endpoints.shape[0], seg_endpoints.shape[0]),
            dtype=complex,
        )
    return build_carson_correction_matrices(
        seg_endpoints,
        wire_radii,
        omegas=[omega],
        sigma_earth=sigma_earth,
        image=image,
    )[0]

build_inductance_matrix

build_inductance_matrix(seg_endpoints: ndarray, wire_radii: ndarray, *, use_image: bool | None = None, image: ImageConvention | None = None, include_internal: bool | ndarray = True, touching: TouchingRule = 'exact', shields: bool | ndarray | None = None, conductors: ndarray | None = None) -> np.ndarray

Assemble the dense partial-inductance matrix over branches.

Vectorised implementation per ADR-0010 Tier 0b. Reproduces _build_inductance_matrix_loop() bit-exactly to floating- point precision but evaluates the off-diagonal entries one row at a time in batched NumPy calls — typical networks (~1000 segments) speed up by 1–2 orders of magnitude.

Parameters:

Name Type Description Default
seg_endpoints ndarray

Array of shape (M, 2, 3) with the start- and end-points (in m, \(z\) positive into the soil) of every distributed-conductor longitudinal-branch segment.

required
wire_radii ndarray

Per-branch wire radii in metres, shape (M,): the thin-wire self terms, and the distance of touching wires \(r_i + r_j\) (or the shield radius for a wire inside a cable shield, see shields) taken where two wires lie beside each other closer than that (module docstring, "Wires lying beside each other").

required
use_image bool | None

Legacy switch: True is image="additive", False is image="none". Pass either this or image, not both.

None
image ImageConvention | None

Image convention of the returned matrix (see the module docstring): "none" (free space), "additive" (perfect magnetic mirror, the historic default) or "antiparallel" (perfect electric mirror — Carson's baseline). The image term is the Neumann integral against the mirrored partner (and the segment's own image on the diagonal). Defaults to "additive".

None
include_internal bool | ndarray

Add the DC internal inductance \(\mu_0\ell/(8\pi)\) to the self terms (default True). A boolean applies to every segment; an array of shape (M,) selects it per segment (e.g. False for conductors whose internal impedance is supplied separately by a skin-effect model).

True
touching TouchingRule

"exact" (default): closed forms for pairs that share an end point or lie on one axis; "quadrature": the 16x16 rule of 0.15.0 (see neumann_mutual()).

'exact'
shields bool | ndarray | None

Segments of cable shields (a bool for all, or an array of shape (M,); None, the default, for none). A thinner wire parallel inside a shield (\(\delta + r_\text{thin} \le r_s\)) couples to it at the shield radius, at every axial offset (a core inside a cable shield; user decision Q32 of 2026.11); two unmarked wires on one axis touch. The self terms do not depend on it: pass include_internal=~shields to drop the internal inductance of a solid wire from the shields, as the solver does for conductor_type="cable_shield" (Q33). Without it a shield keeps \(\mu_0\ell/(8\pi)\) = 50 nH/m: the 100 m coax with 5 mm core and 15 mm shield reads 31.97 µH instead of 26.97 µH.

None
conductors ndarray | None

Conductor label of every segment, shape (M,) (any values that can be compared for equality, e.g. conductor names; None, the default: every segment is a conductor of its own). For two conductors lying beside each other (a pair of their segments closer than touching: on one axis, tilted against each other, crossing, leaving one junction), a point lies beside the partner when its foot falls inside the partner's whole conductor — the straight run of its segments with that label — so the sub-pieces of the two conductors add up to the lumped pair (audit W1A-02 of the calendar release). For segments that are not parallel the stretches inside, beside and away from the partner are found exactly, at any angle and for pieces of any length (audits W1R2-01, W1R3-01, W1R3-02: a slightly tilted core, a core crossing its shield's axis, two wires leaving a junction add up within 3e-12; up to W1R3 the rule stopped where the lateral distance changed by more than \(r_i + r_j\) along a segment and at \(|\cos\varphi| = 0.99\), and the pieces read up to 1.6e-3 off the lumped pair). Pieces of one conductor and conductors that only meet end to end keep the filament integral. Without labels, unmarked touching pieces of one cable are not recognised as one conductor: they keep the rule of the single segments and do not add up (the 100 m pair of 5 and 15 mm wires reads 40.34 µH in 0.25 m pieces against 43.47 µH lumped); the inside reading of a marked shield (shields) needs no labels and adds up either way (audit W1R2-08). The solver passes one label per conductor.

None

Returns:

Name Type Description
L (ndarray, shape(M, M))

Symmetric partial-inductance matrix in H. Entry L[i, j] is the partial mutual inductance between branch i and branch j (and the diagonal is the self-inductance + image).

Raises:

Type Description
ValueError

With an image convention other than "none": a segment that crosses the soil surface (its image intersects it) or lies in the surface plane (its image coincides with it). A segment of zero length.

Notes

The legacy loop-based implementation is kept as _build_inductance_matrix_loop() for regression testing. See :file:tests/test_inductance_vectorised.py for the bit-exact regression suite.

Source code in src/groundfield/coupling/inductance.py
def build_inductance_matrix(
    seg_endpoints: np.ndarray,  # shape (M, 2, 3): each branch's [start, end]
    wire_radii: np.ndarray,  # shape (M,)
    *,
    use_image: bool | None = None,
    image: ImageConvention | None = None,
    include_internal: bool | np.ndarray = True,
    touching: TouchingRule = "exact",
    shields: bool | np.ndarray | None = None,
    conductors: np.ndarray | None = None,
) -> np.ndarray:
    """Assemble the dense partial-inductance matrix over branches.

    Vectorised implementation per ADR-0010 Tier 0b. Reproduces
    :func:`_build_inductance_matrix_loop` bit-exactly to floating-
    point precision but evaluates the off-diagonal entries one row
    at a time in batched NumPy calls — typical networks
    (~1000 segments) speed up by 1–2 orders of magnitude.

    Parameters
    ----------
    seg_endpoints
        Array of shape ``(M, 2, 3)`` with the start- and end-points
        (in m, $z$ positive into the soil) of every
        distributed-conductor longitudinal-branch segment.
    wire_radii
        Per-branch wire radii in metres, shape ``(M,)``: the thin-wire
        self terms, and the distance of touching wires $r_i + r_j$ (or
        the shield radius for a wire inside a cable shield, see
        ``shields``) taken where two wires lie beside each other closer
        than that (module docstring, "Wires lying beside each other").
    use_image
        Legacy switch: ``True`` is ``image="additive"``, ``False`` is
        ``image="none"``. Pass either this or ``image``, not both.
    image
        Image convention of the returned matrix (see the module
        docstring): ``"none"`` (free space), ``"additive"`` (perfect
        magnetic mirror, the historic default) or ``"antiparallel"``
        (perfect electric mirror — Carson's baseline). The image term
        is the Neumann integral against the mirrored partner (and the
        segment's own image on the diagonal). Defaults to
        ``"additive"``.
    include_internal
        Add the DC internal inductance $\\mu_0\\ell/(8\\pi)$ to the
        self terms (default ``True``). A boolean applies to every
        segment; an array of shape ``(M,)`` selects it per segment
        (e.g. ``False`` for conductors whose internal impedance is
        supplied separately by a skin-effect model).
    touching
        ``"exact"`` (default): closed forms for pairs that share an end
        point or lie on one axis; ``"quadrature"``: the 16x16 rule of
        0.15.0 (see :func:`neumann_mutual`).
    shields
        Segments of cable shields (a bool for all, or an array of shape
        ``(M,)``; ``None``, the default, for none). A thinner wire
        parallel inside a shield ($\\delta + r_\\text{thin} \\le r_s$)
        couples to it at the shield radius, at every axial offset (a core
        inside a cable shield; user decision Q32 of 2026.11); two unmarked
        wires on one axis touch. **The self terms do not depend on it**:
        pass ``include_internal=~shields`` to drop the internal inductance
        of a solid wire from the shields, as the solver does for
        ``conductor_type="cable_shield"`` (Q33). Without it a shield keeps
        $\\mu_0\\ell/(8\\pi)$ = 50 nH/m: the 100 m coax with 5 mm core and
        15 mm shield reads 31.97 µH instead of 26.97 µH.
    conductors
        Conductor label of every segment, shape ``(M,)`` (any values that
        can be compared for equality, e.g. conductor names; ``None``, the
        default: every segment is a conductor of its own). For two
        conductors lying beside each other (a pair of their segments closer
        than touching: on one axis, tilted against each other, crossing,
        leaving one junction), a point lies beside the partner when its
        foot falls inside the partner's whole conductor — the straight run
        of its segments with that label — so the sub-pieces of the two
        conductors add up to the lumped pair (audit W1A-02 of the calendar
        release). For segments that are not parallel the stretches inside,
        beside and away from the partner are found exactly, at any angle and
        for pieces of any length (audits W1R2-01, W1R3-01, W1R3-02: a
        slightly tilted core, a core crossing its shield's axis, two wires
        leaving a junction add up within 3e-12; up to W1R3 the rule stopped
        where the lateral distance changed by more than $r_i + r_j$ along a
        segment and at $|\\cos\\varphi| = 0.99$, and the pieces read up to
        1.6e-3 off the lumped pair). Pieces of one
        conductor and conductors that only meet end to end keep the
        filament integral. **Without labels**, unmarked touching pieces of
        one cable are not recognised as one conductor: they keep the rule
        of the single segments and do not add up (the 100 m pair of 5 and
        15 mm wires reads 40.34 µH in 0.25 m pieces against 43.47 µH
        lumped); the inside reading of a marked shield (``shields``) needs
        no labels and adds up either way (audit W1R2-08). The solver
        passes one label per conductor.

    Returns
    -------
    L : np.ndarray, shape (M, M)
        Symmetric partial-inductance matrix in H. Entry ``L[i, j]``
        is the partial mutual inductance between branch *i* and
        branch *j* (and the diagonal is the self-inductance + image).

    Raises
    ------
    ValueError
        With an image convention other than ``"none"``: a segment
        that crosses the soil surface (its image intersects it) or
        lies in the surface plane (its image coincides with it). A
        segment of zero length.

    Notes
    -----
    The legacy loop-based implementation is kept as
    :func:`_build_inductance_matrix_loop` for regression testing.
    See :file:`tests/test_inductance_vectorised.py` for the
    bit-exact regression suite.
    """
    mode = _resolve_image(image, use_image)
    _check_touching_rule(touching)
    M = seg_endpoints.shape[0]
    if M == 0:
        return np.zeros((0, 0), dtype=float)

    p1 = seg_endpoints[:, 0, :].astype(float, copy=False)  # (M, 3)
    p2 = seg_endpoints[:, 1, :].astype(float, copy=False)  # (M, 3)
    radii = np.asarray(wire_radii, dtype=float)
    internal = _include_internal_array(include_internal, M)
    if mode != "none":
        _check_image_geometry(p1, p2, radii, where="build_inductance_matrix")
    shield = _shield_array(shields, M)
    labels = _conductor_labels(conductors, M)
    hits: list[tuple[int, int]] = []
    L_dir, L_img = _inductance_blocks(
        p1,
        p2,
        radii,
        want_direct=True,
        want_image=mode != "none",
        self_from_rows=mode == "none",
        include_internal=internal,
        touching=touching,
        shields=shield,
        beside_hits=hits,
    )
    _apply_bundles(L_dir, p1, p2, radii, shield, labels, hits)
    if mode == "none":
        return L_dir
    if mode == "additive":
        return L_dir + L_img
    L = L_dir - L_img
    # A perfect conductor screens the soil: a pair on opposite sides of
    # the surface has no anti-parallel baseline (audit A2C-1).
    L[_opposite_sides(p1, p2)] = 0.0
    return L

neumann_mutual

neumann_mutual(p1_a: ndarray, p2_a: ndarray, p1_b: ndarray, p2_b: ndarray, *, min_distance: float = 1e-06, parallel_tol: float = 1e-09, touching: TouchingRule = 'exact') -> float

Neumann mutual-inductance integral between two straight segments.

Hybrid implementation:

  1. If the two segments are parallel (or anti-parallel) within parallel_tol on distinct axes, the closed-form Grover expression in _parallel_filaments_mutual() is used — exact, no quadrature error. This fast path covers the bulk of the typical inductance assembly (parallel PEN strands).
  2. With touching="exact", pairs that share an end point (chain neighbours, bends) or lie on one axis without overlapping use their closed forms (Grover 1946; see the module docstring).
  3. Otherwise the Neumann double integral is evaluated by 16×16 Gauss–Legendre quadrature: exact to round-off for pairs separated by more than about half their length, but only to -0.3 % ... +0.8 % for touching pairs (review pass 10, finding 10.46), and up to +250 % for nearly parallel wires 1 cm apart (audit round 2 of the calendar release). With touching="exact" such close pairs — nearest quadrature nodes within half the longer segment, no shared end point, not coaxial — are integrated semi-analytically instead (inner integral in closed form, outer panels graded towards the near-singular points; _close_pair_mutual()).

Accuracy (measured against adaptive mpmath references, audit round 3 of the calendar release): closed forms to round-off; filaments from one vertex to round-off on axis-parallel geometry and to 4e-10 in a general orientation down to 3e-9 rad (the angle itself carries about 1e-16/angle); close pairs as stated in _close_pair_mutual() (5e-11 above 1e-6 rad, 1.0e-9 at 1e-8 rad). Pairs inside the parallel tolerance — directions within parallel_tol in cos (4.5e-5 rad) and a lateral offset that varies by at most parallel_tol m along the segment — use the parallel closed form at the offset of the start point, off by about the relative variation of the offset (4.2e-9 for wires 1 cm apart tilted by 1e-10 rad over 5 m, 1.7e-5 at 1 µm).

The kernel \(1/r\) is clamped at min_distance to suppress the integrable singularity for segments that touch — physically the diagonal uses thin_wire_self_inductance() instead, so this only affects pathological inputs.

Parameters:

Name Type Description Default
p1_a ndarray

Endpoints of segment a as (x, y, z) arrays in metres.

required
p2_a ndarray

Endpoints of segment a as (x, y, z) arrays in metres.

required
p1_b ndarray

Endpoints of segment b.

required
p2_b ndarray

Endpoints of segment b.

required
min_distance float

Numerical floor on \(|r_a - r_b|\) in metres.

1e-06
parallel_tol float

Tolerance on \(||\hat{u}_a\cdot\hat{u}_b| - 1|\) that triggers the closed-form fast path.

1e-09
touching TouchingRule

"exact" (default) or "quadrature" (the 16x16 rule, the default up to 0.15.0) — the treatment of touching and coaxial pairs.

'exact'

Returns:

Name Type Description
M float

Partial mutual inductance in H.

Raises:

Type Description
ValueError

If touching is not "exact" or "quadrature", or if a segment of the generic (non-parallel, non-touching) case has zero length.

Source code in src/groundfield/coupling/inductance.py
def neumann_mutual(
    p1_a: np.ndarray,
    p2_a: np.ndarray,
    p1_b: np.ndarray,
    p2_b: np.ndarray,
    *,
    min_distance: float = 1e-6,
    parallel_tol: float = 1e-9,
    touching: TouchingRule = "exact",
) -> float:
    """Neumann mutual-inductance integral between two straight segments.

    Hybrid implementation:

    1. If the two segments are **parallel** (or anti-parallel) within
       ``parallel_tol`` on distinct axes, the closed-form Grover
       expression in :func:`_parallel_filaments_mutual` is used —
       exact, no quadrature error. This fast path covers the bulk of
       the typical inductance assembly (parallel PEN strands).
    2. With ``touching="exact"``, pairs that share an end point (chain
       neighbours, bends) or lie on one axis without overlapping use
       their closed forms (Grover 1946; see the module docstring).
    3. Otherwise the Neumann double integral is evaluated by 16×16
       Gauss–Legendre quadrature: exact to round-off for pairs
       separated by more than about half their length, but only
       to -0.3 % ... +0.8 % for touching pairs (review pass 10,
       finding 10.46), and up to +250 % for nearly parallel wires 1 cm
       apart (audit round 2 of the calendar release). With
       ``touching="exact"`` such close pairs — nearest quadrature nodes
       within half the longer segment, no shared end point, not coaxial
       — are integrated semi-analytically instead (inner integral in
       closed form, outer panels graded towards the near-singular
       points; :func:`_close_pair_mutual`).

    Accuracy (measured against adaptive mpmath references, audit round 3
    of the calendar release): closed forms to round-off; filaments from
    one vertex to round-off on axis-parallel geometry and to 4e-10 in a
    general orientation down to 3e-9 rad (the angle itself carries about
    1e-16/angle); close pairs as stated in :func:`_close_pair_mutual`
    (5e-11 above 1e-6 rad, 1.0e-9 at 1e-8 rad). Pairs inside the
    parallel tolerance — directions within ``parallel_tol`` in cos (4.5e-5
    rad) and a lateral offset that varies by at most ``parallel_tol`` m
    along the segment — use the parallel closed form at the offset of the
    start point, off by about the relative variation of the offset
    (4.2e-9 for wires 1 cm apart tilted by 1e-10 rad over 5 m, 1.7e-5 at
    1 µm).

    The kernel $1/r$ is clamped at ``min_distance`` to suppress the
    integrable singularity for segments that touch — physically the
    diagonal uses :func:`thin_wire_self_inductance` instead, so
    this only affects pathological inputs.

    Parameters
    ----------
    p1_a, p2_a
        Endpoints of segment *a* as ``(x, y, z)`` arrays in metres.
    p1_b, p2_b
        Endpoints of segment *b*.
    min_distance
        Numerical floor on $|r_a - r_b|$ in metres.
    parallel_tol
        Tolerance on $||\\hat{u}_a\\cdot\\hat{u}_b| - 1|$ that
        triggers the closed-form fast path.
    touching
        ``"exact"`` (default) or ``"quadrature"`` (the 16x16 rule, the
        default up to 0.15.0) — the treatment of touching and coaxial
        pairs.

    Returns
    -------
    M : float
        Partial mutual inductance in H.

    Raises
    ------
    ValueError
        If ``touching`` is not ``"exact"`` or ``"quadrature"``, or if a
        segment of the generic (non-parallel, non-touching) case has
        zero length.
    """
    _check_touching_rule(touching)
    p1_a = np.asarray(p1_a, dtype=float)
    p2_a = np.asarray(p2_a, dtype=float)
    p1_b = np.asarray(p1_b, dtype=float)
    p2_b = np.asarray(p2_b, dtype=float)

    if touching == "exact":
        M_touch = _touching_mutual(p1_a, p2_a, p1_b, p2_b)
        if M_touch is not None:
            return M_touch

    # Fast path: parallel filaments with closed form.
    M_par = _parallel_filaments_mutual(
        p1_a,
        p2_a,
        p1_b,
        p2_b,
        parallel_tol=parallel_tol,
    )
    if M_par is not None:
        return M_par

    # Generic 3-D case: Gauss–Legendre quadrature.
    da = p2_a - p1_a
    db = p2_b - p1_b
    la = float(np.linalg.norm(da))
    lb = float(np.linalg.norm(db))
    if la <= 0.0 or lb <= 0.0:
        raise ValueError("segment lengths must be positive")
    ua = da / la
    ub = db / lb
    dot = float(ua @ ub)
    if dot == 0.0:
        return 0.0  # perpendicular — orthogonality kills the integral
    s_nodes = 0.5 * (_GL_NODES + 1.0)
    w_nodes = 0.5 * _GL_WEIGHTS
    pts_a = p1_a[None, :] + s_nodes[:, None] * da[None, :]
    pts_b = p1_b[None, :] + s_nodes[:, None] * db[None, :]
    diff = pts_a[:, None, :] - pts_b[None, :, :]
    r = np.linalg.norm(diff, axis=2)
    if touching == "exact" and _needs_close_rule(
        p1_a, p2_a, p1_b, p2_b, float(r.min())
    ):
        return _close_pair_mutual(p1_a, p2_a, p1_b, p2_b)
    np.maximum(r, min_distance, out=r)
    inv_r = 1.0 / r
    integral = float(np.einsum("i,j,ij->", w_nodes, w_nodes, inv_r))
    return MU_0 / (4.0 * math.pi) * dot * la * lb * integral

parallel_segments_mutual

parallel_segments_mutual(length: float, distance: float) -> float

Closed-form mutual inductance of two parallel coaxial segments.

For two segments of equal length \(\ell\) that share the same axis direction and are placed at perpendicular distance \(d\),

\[ M_\parallel(\ell, d) \;=\; \frac{\mu_0\,\ell}{2\pi} \Bigl[\ln\!\Bigl(\frac{\ell + \sqrt{\ell^2 + d^2}}{d}\Bigr) - \frac{\sqrt{\ell^2 + d^2} - d}{\ell}\Bigr]. \]

Used both as an internal closed-form fast path (when the segment pair geometry matches the assumption) and as a reference in the test suite.

Parameters:

Name Type Description Default
length float

Segment length \(\ell\) in m (both segments have the same).

required
distance float

Perpendicular distance \(d\) between the two parallel axes in m. Must be > 0.

required

Returns:

Name Type Description
M float

Partial mutual inductance in H.

Raises:

Type Description
ValueError

If length or distance is not positive.

Source code in src/groundfield/coupling/inductance.py
def parallel_segments_mutual(length: float, distance: float) -> float:
    r"""Closed-form mutual inductance of two parallel coaxial segments.

    For two segments of equal length $\ell$ that share the same
    axis direction and are placed at perpendicular distance $d$,

    $$
    M_\parallel(\ell, d) \;=\; \frac{\mu_0\,\ell}{2\pi}
    \Bigl[\ln\!\Bigl(\frac{\ell + \sqrt{\ell^2 + d^2}}{d}\Bigr)
          - \frac{\sqrt{\ell^2 + d^2} - d}{\ell}\Bigr].
    $$

    Used both as an internal closed-form fast path (when the segment
    pair geometry matches the assumption) and as a reference in the
    test suite.

    Parameters
    ----------
    length
        Segment length $\ell$ in m (both segments have the same).
    distance
        Perpendicular distance $d$ between the two parallel axes
        in m. Must be > 0.

    Returns
    -------
    M : float
        Partial mutual inductance in H.

    Raises
    ------
    ValueError
        If ``length`` or ``distance`` is not positive.
    """
    if length <= 0.0 or distance <= 0.0:
        raise ValueError("length and distance must be positive")
    s = math.hypot(length, distance)
    return (
        (MU_0 * length)
        / (2.0 * math.pi)
        * (math.log((length + s) / distance) - (s - distance) / length)
    )

perfect_mirror_self_pair_inductance

perfect_mirror_self_pair_inductance(p1: ndarray, p2: ndarray, wire_radius: float, *, include_internal: bool = True, touching: TouchingRule = 'exact') -> float

Self-inductance contribution of a segment plus its earth image.

For a single segment the partial self-inductance against itself uses the thin-wire formula. The image segment (mirrored at the soil surface) is treated as an external segment whose Neumann integral with the original is added to the total (the "additive" image convention of ADR-0004).

Parameters:

Name Type Description Default
p1 ndarray

Endpoints in metres (with \(z > 0\) pointing into the soil).

required
p2 ndarray

Endpoints in metres (with \(z > 0\) pointing into the soil).

required
wire_radius float

Wire radius in m (only used for the thin-wire self term).

required
include_internal bool

Add the DC internal inductance \(\mu_0\ell/(8\pi)\) (default, see thin_wire_self_inductance()).

True
touching TouchingRule

Rule for the segment–image pair when the segment touches the surface with one end point (see neumann_mutual()).

'exact'

Returns:

Name Type Description
L float

Self-inductance plus image contribution, in henries.

Source code in src/groundfield/coupling/inductance.py
def perfect_mirror_self_pair_inductance(
    p1: np.ndarray,
    p2: np.ndarray,
    wire_radius: float,
    *,
    include_internal: bool = True,
    touching: TouchingRule = "exact",
) -> float:
    """Self-inductance contribution of a segment plus its earth image.

    For a single segment the *partial* self-inductance against itself
    uses the thin-wire formula. The image segment (mirrored at the
    soil surface) is treated as an external segment whose Neumann
    integral with the original is added to the total (the
    ``"additive"`` image convention of ADR-0004).

    Parameters
    ----------
    p1, p2
        Endpoints in metres (with $z > 0$ pointing into the soil).
    wire_radius
        Wire radius in m (only used for the thin-wire self term).
    include_internal
        Add the DC internal inductance $\\mu_0\\ell/(8\\pi)$ (default,
        see :func:`thin_wire_self_inductance`).
    touching
        Rule for the segment–image pair when the segment touches the
        surface with one end point (see :func:`neumann_mutual`).

    Returns
    -------
    L : float
        Self-inductance plus image contribution, in henries.
    """
    p1 = np.asarray(p1, dtype=float)
    p2 = np.asarray(p2, dtype=float)
    L_self = thin_wire_self_inductance(
        float(np.linalg.norm(p2 - p1)),
        wire_radius,
        include_internal=include_internal,
    )
    p1_img = _mirror(p1)
    p2_img = _mirror(p2)
    # Image segment runs in the opposite direction (current image of a
    # vertical filament is anti-parallel; for a horizontal filament it
    # is parallel). The general rule is: image of (p1 → p2) is
    # (p1' → p2'), with the *same* tangent direction up to the
    # sign of ẑ. For Neumann the dot product ǔ_a·ǔ_b takes care of
    # the sign automatically — we just feed the mirrored endpoints.
    L_image = neumann_mutual(p1, p2, p1_img, p2_img, touching=touching)
    return L_self + L_image

thin_wire_self_inductance

thin_wire_self_inductance(length: float, wire_radius: float, *, include_internal: bool = True) -> float

Closed-form self-inductance of a straight thin-wire segment.

Decomposed into the external Grover 1946 thin-wire term and the internal contribution from the magnetic field inside the conductor (uniform DC current distribution, non-magnetic material):

\[ L_\text{ext} \;=\; \frac{\mu_0\,\ell}{2\pi} \Bigl[\ln\!\Bigl(\frac{2\ell}{a}\Bigr) - 1\Bigr], \qquad L_\text{int} \;=\; \frac{\mu_0\,\ell}{8\pi}. \]

Adding the internal term reproduces the standard Oeding/Oswald loop-inductance formula (Gl. 9.13c) when used as the diagonal contribution of a two-wire loop. This is the package-wide internal-inductance convention (see the module docstring): a per-unit-length reference consistent with include_internal=True uses \(\mathrm{GMR} = a\,e^{-1/4}\). For the frequency-dependent internal impedance (skin effect) see groundfield.conductors.Conductor.internal_impedance_per_length().

Parameters:

Name Type Description Default
length float

Segment length \(\ell\) in metres.

required
wire_radius float

Wire radius \(a\) in metres.

required
include_internal bool

True (default) — add the internal-field contribution \(\mu_0 \ell / (8\pi)\) (uniform current, the DC limit). False — the pure external-field thin-wire formula.

True

Returns:

Name Type Description
L float

Partial self-inductance in henries.

Raises:

Type Description
ValueError

If length or wire_radius is not positive.

Source code in src/groundfield/coupling/inductance.py
def thin_wire_self_inductance(
    length: float,
    wire_radius: float,
    *,
    include_internal: bool = True,
) -> float:
    r"""Closed-form self-inductance of a straight thin-wire segment.

    Decomposed into the **external** Grover 1946 thin-wire term and
    the **internal** contribution from the magnetic field inside the
    conductor (uniform DC current distribution, non-magnetic
    material):

    $$
    L_\text{ext} \;=\; \frac{\mu_0\,\ell}{2\pi}
    \Bigl[\ln\!\Bigl(\frac{2\ell}{a}\Bigr) - 1\Bigr],
    \qquad
    L_\text{int} \;=\; \frac{\mu_0\,\ell}{8\pi}.
    $$

    Adding the internal term reproduces the standard Oeding/Oswald
    loop-inductance formula (Gl. 9.13c) when used as the diagonal
    contribution of a two-wire loop. This is the package-wide
    internal-inductance convention (see the module docstring): a
    per-unit-length reference consistent with
    ``include_internal=True`` uses $\mathrm{GMR} = a\,e^{-1/4}$.
    For the frequency-dependent internal impedance (skin effect) see
    :meth:`groundfield.conductors.Conductor.internal_impedance_per_length`.

    Parameters
    ----------
    length
        Segment length $\ell$ in metres.
    wire_radius
        Wire radius $a$ in metres.
    include_internal
        ``True`` (default) — add the internal-field contribution
        $\mu_0 \ell / (8\pi)$ (uniform current, the DC limit).
        ``False`` — the pure external-field thin-wire formula.

    Returns
    -------
    L : float
        Partial self-inductance in henries.

    Raises
    ------
    ValueError
        If ``length`` or ``wire_radius`` is not positive.
    """
    if length <= 0.0 or wire_radius <= 0.0:
        raise ValueError("length and wire_radius must be positive")
    L_ext = (
        (MU_0 * length) / (2.0 * math.pi) * (math.log(2.0 * length / wire_radius) - 1.0)
    )
    if not include_internal:
        return L_ext
    L_int = (MU_0 * length) / (8.0 * math.pi)
    return L_ext + L_int

Carson earth return (ADR-0005)

carson

Carson 1926 correction for the earth-return path.

This module implements the earth-return correction described in ADR-0005: the finite-conductivity contribution that Carson 1926 derived for a homogeneous, semi-infinite, conductive half-space. It is defined against the anti-parallel (perfect-electric-conductor) image of the Neumann inductance matrix (build_inductance_matrix(image="antiparallel") in groundfield.coupling.inductance): the complete per-metre series impedance of a wire at height \(h\) is \(j\omega(\mu_0/2\pi)\ln(2h/\mathrm{GMR}) + \Delta Z_\text{Carson}\). Up to 0.15.0 the solver added it on top of the additive ("perfect-mirror") image instead, which double-counts the image (review pass 10, finding 10.20 / F32).

Mathematical background

Carson 1926 (Bell Syst. Tech. J. 5(4)) writes the earth-return correction to the per-unit-length series impedance of a long straight wire above a homogeneous earth as

\[ \Delta Z_\text{Carson}(\omega) \;=\; \frac{\omega\,\mu_0}{\pi}\, \bigl[P(a, \theta) \,+\, j\,Q(a, \theta)\bigr], \]

with the dimensionless Carson parameter

\[ a \;=\; D\,\sqrt{\omega\,\mu_0\,\sigma_\text{earth}} \;=\; \frac{D\sqrt{2}}{\delta(\omega)}, \qquad \delta(\omega) \;=\; \sqrt{2 \,/\, (\omega\mu_0\sigma_\text{earth})} \;[\text{skin depth in soil}], \]

where \(D = 2h_i\) for the self-impedance correction (\(\theta = 0\)) and \(D = \sqrt{(h_i + h_j)^2 + d_{ij}^2}\), \(\theta = \arctan(d_{ij} / (h_i + h_j))\) for the mutual-impedance correction between two parallel wires at heights \(h_i, h_j\) with horizontal separation \(d_{ij}\).

The functions \(P, Q\) are the real and imaginary parts of Carson's infinite integral \(J(p, q)\) (Carson eq. 29, with \(p = a\cos\theta\), \(q = a\sin\theta\)):

\[ J(p, q) \;=\; \int_0^{\infty}\!\bigl(\sqrt{\mu^2 + j}-\mu\bigr)\, e^{-p\mu}\cos(q\mu)\,d\mu \;=\; P(a,\theta) + j\,Q(a,\theta). \]
Three evaluation regimes

We follow Carson's own discussion in section III of the original paper:

  1. Small \(a\) (\(a \le 0.25\)) — Carson's convergent series (eqs. 34/35), summed to order \(a^{12}\) with the exact constants \(c_2 = 5/4 + \ln 2 - \gamma_E\) and \(Q_0 = \tfrac12(\tfrac12 - \gamma_E)\). Closed form, only \(\sin / \cos / \ln\).
  2. Intermediate \(a\) (\(0.25 < a \le 15\)) — direct numerical quadrature of Carson's \(J(p, q)\): a composite, geometrically graded Gauss–Legendre rule for \(\theta \approx 0\) and QUADPACK's Fourier integrator otherwise. The original Carson 1926 series in that range is technically convergent but its recurrence is numerically delicate; quadrature is robust.
  3. Large \(a\) (\(a > 15\)) — Carson eqs. 36/37, asymptotic expansion in inverse powers of \(a\) up to \(a^{-7}\) (for \(\theta \le 1.4\) rad; steeper angles stay on the quadrature).

Accuracy against mpmath (review pass 10): the series and the quadrature are accurate to round-off for \(a \le 0.25\) and \(a > 0.25\) respectively, the asymptote to \(\le 10^{-7}\) above \(a = 15\); both regime boundaries are continuous to those levels. At large \(a\) and steep angles (\(\theta > 1.4\) rad, where the asymptote is not used) QUADPACK's Fourier rule limits the quadrature: 1.5e-9 at \(a = 8.9\) and 1.2e-7 at \(a = 28\), \(\theta = 89.9°\) — two wires 1 km apart at 1 kHz in 10 Ω·m (measured in audit round 3 of the calendar release against an independent quadrature of the \(\lambda\) integral). Until the calendar release 2026.11 the small-\(a\) form kept only the leading terms (no \(a^2\) term \(-(\pi/64)\,a^2\cos 2\theta\) of \(Q\), constant rounded to \(-0.0386\), \(P\) and \(Q\) off by up to \(2.4\cdot 10^{-4}\) and \(3.0\cdot 10^{-3}\) at \(a = 0.25\)) and the \(\theta = 0\) quadrature used 64 nodes on \([0, 30/p]\) (\(6\cdot 10^{-6}\) off at \(a = 0.25\)): the boundary at \(a = 0.25\) jumped by up to \(2.9\cdot 10^{-3}\) in \(Q\) (findings 10.46, 10.20).

Implementation notes
  • All formulas use SI units throughout. Carson's CGS pre-factor \(4\omega\) becomes \(\omega\mu_0 / \pi\) in SI.
  • \(\sigma_\text{earth}\) is an explicit argument; the caller is responsible for selecting the right resistivity (homogeneous \(1/\rho\), or upper-layer \(1/\rho_1\) with a warning).
  • \(\omega = 0\) or \(\sigma = 0\) short-circuit to 0+0j: the prefactor \(\omega\mu_0/\pi\) vanishes, so the (logarithmically diverging) \(Q\)-asymptote is harmless.
  • The complex-depth Deri/Semlyen approximation is provided as an internal sanity check (deri_semlyen_correction()); it is not the production code path.
  • A wire above the surface parallel to a wire below it is not a Carson pair (both wires overhead) nor a buried pair: its mutual impedance is the field transmitted into the soil, carson_mixed_mutual_correction() (Carson's \(J\) plus a bounded remainder for the buried wire's attenuation; audit round 2 of the calendar release, A2C-1).
References
  • Carson, J. R. (1926). Wave propagation in overhead wires with ground return. Bell Syst. Tech. J. 5(4), 539–554.
  • Deri, A.; Tevan, G.; Semlyen, A.; Castanheira, A. (1981). The complex ground return plane. IEEE Trans. PAS 100(8), 3686–3693.
  • Tleis, N. D. (2008). Power Systems Modelling and Fault Analysis, Newnes, ch. 3.

MU_0 module-attribute

MU_0 = 4e-07 * math.pi

Vacuum permeability μ0 = 4π · 10⁻⁷ H/m (the conventional value).

The CODATA 2018 value differs by 5.5 · 10⁻¹⁰ relative.

carson_mixed_mutual_correction

carson_mixed_mutual_correction(omega: float, height: float, depth: float, horizontal_distance: float, sigma_earth: float) -> complex

Mutual impedance of an overhead wire parallel to a buried wire.

Per-unit-length mutual impedance of two long parallel horizontal wires on opposite sides of the soil surface — one at height \(h\) above it, one at depth \(d\) below it, horizontal separation \(x\) — over a homogeneous earth (quasi-static, the regime of Carson's theory):

\[ Z_m(\omega) \;=\; \frac{j\omega\mu_0}{\pi}\int_0^\infty \frac{e^{-\lambda h - u d}}{\lambda + u}\,\cos(\lambda x)\, d\lambda \;=\; \frac{\omega\mu_0}{\pi}\,J_m(p_h, p_d, q), \qquad u = \sqrt{\lambda^2 + j\omega\mu_0\sigma}, \]

the field of the overhead wire transmitted into the soil, with Carson's variables \(\lambda = \mu\sqrt{\omega\mu_0\sigma}\), \(p_h = h\sqrt{\omega\mu_0\sigma}\), \(p_d = d\sqrt{\omega\mu_0\sigma}\), \(q = x\sqrt{\omega\mu_0\sigma}\) and

\[ J_m \;=\; \int_0^\infty \bigl(\sqrt{\mu^2 + j} - \mu\bigr)\, e^{-p_h\mu - p_d\sqrt{\mu^2 + j}}\cos(q\mu)\,d\mu . \]

For \(d \to 0\) this is Carson's \(J\) of two overhead wires at heights \(h\) and \(0\); it is evaluated as Carson's \(J(p_h + p_d, q)\) (carson_p_q(), every regime) plus the bounded remainder of the buried wire's attenuation (_mixed_remainder()). Measured remainder: \(10^{-5}\) to \(4\cdot 10^{-1}\) of \(J\) (shallow conductors at 50 Hz in resistive soil to deep ones at 5 kHz in 10 \(\Omega\)m). The remainder is accurate to round-off; the whole agrees with an independent quadrature of the \(\lambda\) integral to 4.2e-9 for x ≤ 300 m (\(q \le 8.4\); f ≤ 1 kHz, \(\rho \ge 10\,\Omega\)m, h and d from 1 mm to 10 m; 1e-10 at 50 Hz) and to 1.2e-7 at x = 1 km at 1 kHz in 10 \(\Omega\)m (\(q = 28\)), the accuracy of Carson's \(J\) there (carson_p_q(); audit round 3 of the calendar release).

Image baseline. Relative to the anti-parallel (perfect-electric-conductor) image of build_inductance_matrix(image="antiparallel") this is the whole coupling: a perfect conductor screens the soil, so the baseline of a pair on opposite sides of the surface is zero. Treating the buried wire as an overhead wire at height \(d\) (Carson's correction on the mirrored-endpoint image, as the solver did up to audit round 2 of the calendar release) gives 36 % too little mutual reactance for a lead 1 m above a PEN at 0.7 m depth at 1 kHz, 14 % at 1 m offset, 3 % for a lead 0.1 m above it.

Parameters:

Name Type Description Default
omega float

Angular frequency in rad/s.

required
height float

Height \(h\) of the overhead wire above the surface in m (positive).

required
depth float

Depth \(d\) of the buried wire below the surface in m (positive).

required
horizontal_distance float

Horizontal separation \(x\) of the two wires in m.

required
sigma_earth float

Earth conductivity in S/m.

required

Returns:

Name Type Description
Z complex

Per-unit-length mutual impedance in \(\Omega/\text{m}\).

Raises:

Type Description
ValueError

For a non-positive height or depth, or a negative distance.

References
  • Ametani, A.; Yoneda, T.; Baba, Y.; Nagaoka, N. (2009). An investigation of earth-return impedance between overhead and underground conductors and its approximation. IEEE Trans. Electromagn. Compat. 51(3), 860–867, doi:10.1109/TEMC.2009.2019953.
Source code in src/groundfield/coupling/carson.py
def carson_mixed_mutual_correction(
    omega: float,
    height: float,
    depth: float,
    horizontal_distance: float,
    sigma_earth: float,
) -> complex:
    """Mutual impedance of an overhead wire parallel to a buried wire.

    Per-unit-length mutual impedance of two long parallel horizontal
    wires on **opposite sides** of the soil surface — one at height
    $h$ above it, one at depth $d$ below it, horizontal separation
    $x$ — over a homogeneous earth (quasi-static, the regime of
    Carson's theory):

    $$
    Z_m(\\omega) \\;=\\; \\frac{j\\omega\\mu_0}{\\pi}\\int_0^\\infty
    \\frac{e^{-\\lambda h - u d}}{\\lambda + u}\\,\\cos(\\lambda x)\\,
    d\\lambda
    \\;=\\; \\frac{\\omega\\mu_0}{\\pi}\\,J_m(p_h, p_d, q),
    \\qquad u = \\sqrt{\\lambda^2 + j\\omega\\mu_0\\sigma},
    $$

    the field of the overhead wire transmitted into the soil, with
    Carson's variables $\\lambda = \\mu\\sqrt{\\omega\\mu_0\\sigma}$,
    $p_h = h\\sqrt{\\omega\\mu_0\\sigma}$,
    $p_d = d\\sqrt{\\omega\\mu_0\\sigma}$,
    $q = x\\sqrt{\\omega\\mu_0\\sigma}$ and

    $$
    J_m \\;=\\; \\int_0^\\infty \\bigl(\\sqrt{\\mu^2 + j} - \\mu\\bigr)\\,
    e^{-p_h\\mu - p_d\\sqrt{\\mu^2 + j}}\\cos(q\\mu)\\,d\\mu .
    $$

    For $d \\to 0$ this is Carson's $J$ of two overhead wires at
    heights $h$ and $0$; it is evaluated as Carson's
    $J(p_h + p_d, q)$ (:func:`carson_p_q`, every regime) plus the
    bounded remainder of the buried wire's attenuation
    (:func:`_mixed_remainder`). Measured remainder: $10^{-5}$ to
    $4\\cdot 10^{-1}$ of $J$ (shallow conductors at 50 Hz in resistive
    soil to deep ones at 5 kHz in 10 $\\Omega$m). The remainder is accurate
    to round-off; the whole agrees with an independent quadrature of the
    $\\lambda$ integral to 4.2e-9 for x ≤ 300 m ($q \\le 8.4$; f ≤ 1 kHz,
    $\\rho \\ge 10\\,\\Omega$m, h and d from 1 mm to 10 m; 1e-10 at
    50 Hz) and to 1.2e-7 at x = 1 km at 1 kHz in 10 $\\Omega$m
    ($q = 28$), the accuracy of Carson's $J$ there (:func:`carson_p_q`;
    audit round 3 of the calendar release).

    **Image baseline.** Relative to the anti-parallel
    (perfect-electric-conductor) image of
    ``build_inductance_matrix(image="antiparallel")`` this is the
    whole coupling: a perfect conductor screens the soil, so the
    baseline of a pair on opposite sides of the surface is zero.
    Treating the buried wire as an overhead wire at height $d$
    (Carson's correction on the mirrored-endpoint image, as the solver
    did up to audit round 2 of the calendar release) gives 36 % too
    little mutual reactance for a lead 1 m above a PEN at 0.7 m depth
    at 1 kHz, 14 % at 1 m offset, 3 % for a lead 0.1 m above it.

    Parameters
    ----------
    omega
        Angular frequency in rad/s.
    height
        Height $h$ of the overhead wire above the surface in m
        (positive).
    depth
        Depth $d$ of the buried wire below the surface in m
        (positive).
    horizontal_distance
        Horizontal separation $x$ of the two wires in m.
    sigma_earth
        Earth conductivity in S/m.

    Returns
    -------
    Z : complex
        Per-unit-length mutual impedance in $\\Omega/\\text{m}$.

    Raises
    ------
    ValueError
        For a non-positive height or depth, or a negative distance.

    References
    ----------
    - Ametani, A.; Yoneda, T.; Baba, Y.; Nagaoka, N. (2009). An
      investigation of earth-return impedance between overhead and
      underground conductors and its approximation. *IEEE Trans.
      Electromagn. Compat.* **51**(3), 860–867,
      doi:10.1109/TEMC.2009.2019953.
    """
    if height <= 0.0 or depth <= 0.0:
        raise ValueError("height and depth must be positive")
    if horizontal_distance < 0.0:
        raise ValueError("horizontal_distance must be non-negative")
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    base = carson_mutual_correction(
        omega, height, depth, horizontal_distance, sigma_earth
    )
    k = math.sqrt(omega * MU_0 * sigma_earth)
    re, im = _mixed_remainder(k * height, k * depth, k * horizontal_distance)
    pref = omega * MU_0 / math.pi
    return base + complex(pref * re, pref * im)

carson_mutual_correction

carson_mutual_correction(omega: float, height_i: float, height_j: float, horizontal_distance: float, sigma_earth: float) -> complex

Carson earth-return correction between two parallel horizontal wires.

Evaluates the per-unit-length mutual-impedance correction

\[ \Delta Z_\text{mutual}(\omega) \;=\; \frac{\omega\mu_0}{\pi} \bigl[P(a_m, \theta_m) \,+\, j Q(a_m, \theta_m)\bigr], \]

with

\[ a_m \;=\; D_m \sqrt{\omega\mu_0\sigma_\text{earth}}, \quad D_m \;=\; \sqrt{(h_i + h_j)^2 + d^2}, \quad \theta_m \;=\; \arctan(d / (h_i + h_j)), \]

after Carson eq. 31. The parallel-wire assumption is the same as for ADR-0004's Neumann fast path; for non-parallel segments the caller must split into projection components.

Parameters:

Name Type Description Default
omega float

Angular frequency in rad/s.

required
height_i float

Heights above earth surface in metres (both positive).

required
height_j float

Heights above earth surface in metres (both positive).

required
horizontal_distance float

Horizontal separation \(d\) between the two wires in metres.

required
sigma_earth float

Earth conductivity in S/m.

required

Returns:

Name Type Description
Z complex

Per-unit-length mutual correction in \(\Omega/\text{m}\).

Raises:

Type Description
ValueError

If height_i or height_j is not positive, or if horizontal_distance is negative.

Source code in src/groundfield/coupling/carson.py
def carson_mutual_correction(
    omega: float,
    height_i: float,
    height_j: float,
    horizontal_distance: float,
    sigma_earth: float,
) -> complex:
    """Carson earth-return correction between two parallel horizontal wires.

    Evaluates the per-unit-length mutual-impedance correction

    $$
    \\Delta Z_\\text{mutual}(\\omega) \\;=\\; \\frac{\\omega\\mu_0}{\\pi}
    \\bigl[P(a_m, \\theta_m) \\,+\\, j Q(a_m, \\theta_m)\\bigr],
    $$

    with

    $$
    a_m \\;=\\; D_m \\sqrt{\\omega\\mu_0\\sigma_\\text{earth}}, \\quad
    D_m \\;=\\; \\sqrt{(h_i + h_j)^2 + d^2}, \\quad
    \\theta_m \\;=\\; \\arctan(d / (h_i + h_j)),
    $$

    after Carson eq. 31. The parallel-wire assumption is the same
    as for ADR-0004's Neumann fast path; for non-parallel segments
    the caller must split into projection components.

    Parameters
    ----------
    omega
        Angular frequency in rad/s.
    height_i, height_j
        Heights above earth surface in metres (both positive).
    horizontal_distance
        Horizontal separation $d$ between the two wires in metres.
    sigma_earth
        Earth conductivity in S/m.

    Returns
    -------
    Z : complex
        Per-unit-length mutual correction in $\\Omega/\\text{m}$.

    Raises
    ------
    ValueError
        If ``height_i`` or ``height_j`` is not positive, or if
        ``horizontal_distance`` is negative.
    """
    if height_i <= 0.0 or height_j <= 0.0:
        raise ValueError("heights must be positive")
    if horizontal_distance < 0.0:
        raise ValueError("horizontal_distance must be non-negative")
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    h_sum = height_i + height_j
    D = math.hypot(h_sum, horizontal_distance)
    theta = math.atan2(horizontal_distance, h_sum)
    a = carson_parameter(D, omega, sigma_earth)
    P, Q = carson_p_q(a, theta)
    pref = omega * MU_0 / math.pi
    return complex(pref * P, pref * Q)

carson_p_q

carson_p_q(a: float, theta: float) -> tuple[float, float]

Evaluate Carson's \(P(a, \theta)\), \(Q(a, \theta)\).

Dispatches to the appropriate regime based on the magnitude of \(a\):

  • \(a \le 0.25\): Carson's convergent series (eqs. 34/35) to order \(a^{12}\).
  • \(0.25 < a \le 15\): direct numerical quadrature of Carson's \(J(p, q)\) (Gauss–Legendre for \(\theta \approx 0\), QUADPACK Fourier integrator otherwise — audit 2026-07-08, WP-B2).
  • \(a > 15\): asymptotic expansion (Carson eqs. 36/37, \(a^{-7}\) term of \(Q\) with the corrected sign), except for \(\theta > 1.4\) rad where the expansion degrades and the quadrature path is used instead.

The small-\(a\) boundary is continuous to round-off, the large-\(a\) boundary to \(\le 10^{-7}\) (see the module docstring). Results are memoised on (a, theta).

Parameters:

Name Type Description Default
a float

Dimensionless Carson parameter \(a = D \sqrt{\omega \mu_0 \sigma_\text{earth}}\). Must be \(\ge 0\).

required
theta float

Angle of the image-distance vector to the vertical, in radians. \(\theta = 0\) for the self-impedance correction, \(\theta = \arctan(d/(h_i+h_j))\) for the mutual.

required

Returns:

Type Description
P, Q : tuple[float, float]

Real and imaginary parts of Carson's integral \(J\).

Raises:

Type Description
ValueError

If a is negative.

Source code in src/groundfield/coupling/carson.py
def carson_p_q(a: float, theta: float) -> tuple[float, float]:
    """Evaluate Carson's $P(a, \\theta)$, $Q(a, \\theta)$.

    Dispatches to the appropriate regime based on the magnitude of
    $a$:

    - $a \\le 0.25$: Carson's convergent series (eqs. 34/35) to
      order $a^{12}$.
    - $0.25 < a \\le 15$: direct numerical quadrature of Carson's
      $J(p, q)$ (Gauss–Legendre for $\\theta \\approx 0$, QUADPACK
      Fourier integrator otherwise — audit 2026-07-08, WP-B2).
    - $a > 15$: asymptotic expansion (Carson eqs. 36/37, $a^{-7}$
      term of $Q$ with the corrected sign), except for
      $\\theta > 1.4$ rad where the expansion degrades and the
      quadrature path is used instead.

    The small-$a$ boundary is continuous to round-off, the large-$a$
    boundary to $\\le 10^{-7}$ (see the module docstring). Results are
    memoised on ``(a, theta)``.

    Parameters
    ----------
    a : float
        Dimensionless Carson parameter $a = D \\sqrt{\\omega
        \\mu_0 \\sigma_\\text{earth}}$. Must be $\\ge 0$.
    theta : float
        Angle of the image-distance vector to the vertical, in
        radians. $\\theta = 0$ for the self-impedance correction,
        $\\theta = \\arctan(d/(h_i+h_j))$ for the mutual.

    Returns
    -------
    P, Q : tuple[float, float]
        Real and imaginary parts of Carson's integral $J$.

    Raises
    ------
    ValueError
        If ``a`` is negative.
    """
    if a < 0.0:
        raise ValueError(f"Carson parameter a must be non-negative, got {a}")
    return _carson_p_q_cached(float(a), float(theta))

carson_parameter

carson_parameter(distance: float, omega: float, sigma_earth: float) -> float

Dimensionless Carson parameter \(a = D \sqrt{\omega\mu_0\sigma}\).

Parameters:

Name Type Description Default
distance float

Geometric distance \(D\) in metres (\(2h\) for self-impedance, \(\sqrt{(h_i+h_j)^2 + d^2}\) for mutual).

required
omega float

Angular frequency in rad/s.

required
sigma_earth float

Earth conductivity in S/m.

required

Returns:

Name Type Description
a float

Dimensionless Carson parameter \(a\) (0 for a non-positive omega or sigma_earth).

Raises:

Type Description
ValueError

If distance is negative.

Source code in src/groundfield/coupling/carson.py
def carson_parameter(distance: float, omega: float, sigma_earth: float) -> float:
    """Dimensionless Carson parameter $a = D \\sqrt{\\omega\\mu_0\\sigma}$.

    Parameters
    ----------
    distance
        Geometric distance $D$ in metres
        ($2h$ for self-impedance, $\\sqrt{(h_i+h_j)^2 + d^2}$
        for mutual).
    omega
        Angular frequency in rad/s.
    sigma_earth
        Earth conductivity in S/m.

    Returns
    -------
    a : float
        Dimensionless Carson parameter $a$ (0 for a non-positive
        ``omega`` or ``sigma_earth``).

    Raises
    ------
    ValueError
        If ``distance`` is negative.
    """
    if distance < 0.0:
        raise ValueError("distance must be non-negative")
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0
    return distance * math.sqrt(omega * MU_0 * sigma_earth)

carson_self_correction

carson_self_correction(omega: float, height: float, sigma_earth: float) -> complex

Carson earth-return correction for a single horizontal wire.

Evaluates the per-unit-length impedance correction

\[ \Delta Z_\text{self}(\omega) \;=\; \frac{\omega \mu_0}{\pi} \bigl[P(a_s, 0) + j Q(a_s, 0)\bigr], \]

with \(a_s = 2h\sqrt{\omega\mu_0\sigma_\text{earth}}\) and \(\theta = 0\) (Carson eq. 30, ADR-0005).

Parameters:

Name Type Description Default
omega float

Angular frequency \(\omega = 2\pi f\) in rad/s.

required
height float

Height of the wire above the earth surface in metres (positive — for buried wires use the Sunde-equivalent height).

required
sigma_earth float

Earth conductivity in S/m (\(\sigma = 1/\rho\) for a homogeneous earth).

required

Returns:

Name Type Description
Z complex

Per-unit-length earth-return correction in \(\Omega/\text{m}\).

Raises:

Type Description
ValueError

If height is non-positive.

Source code in src/groundfield/coupling/carson.py
def carson_self_correction(
    omega: float,
    height: float,
    sigma_earth: float,
) -> complex:
    """Carson earth-return correction for a single horizontal wire.

    Evaluates the per-unit-length impedance correction

    $$
    \\Delta Z_\\text{self}(\\omega) \\;=\\; \\frac{\\omega \\mu_0}{\\pi}
    \\bigl[P(a_s, 0) + j Q(a_s, 0)\\bigr],
    $$

    with $a_s = 2h\\sqrt{\\omega\\mu_0\\sigma_\\text{earth}}$ and
    $\\theta = 0$ (Carson eq. 30, ADR-0005).

    Parameters
    ----------
    omega
        Angular frequency $\\omega = 2\\pi f$ in rad/s.
    height
        Height of the wire above the earth surface in metres
        (positive — for buried wires use the Sunde-equivalent
        height).
    sigma_earth
        Earth conductivity in S/m
        ($\\sigma = 1/\\rho$ for a homogeneous earth).

    Returns
    -------
    Z : complex
        Per-unit-length earth-return correction in $\\Omega/\\text{m}$.

    Raises
    ------
    ValueError
        If ``height`` is non-positive.
    """
    if height <= 0.0:
        raise ValueError("height must be positive (use |z| of the wire)")
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    a = carson_parameter(2.0 * height, omega, sigma_earth)
    P, Q = carson_p_q(a, 0.0)
    pref = omega * MU_0 / math.pi
    return complex(pref * P, pref * Q)

deri_semlyen_correction

deri_semlyen_correction(omega: float, height_i: float, height_j: float, horizontal_distance: float, sigma_earth: float) -> complex

Deri/Semlyen 1981 complex-depth approximation.

Replaces the Carson integral by the closed-form expression

\[ \Delta Z_\text{Deri-Semlyen} \;=\; \frac{j\omega\mu_0}{2\pi} \ln\!\Bigl(\frac{D'}{D}\Bigr), \]

with \(D = \sqrt{(h_i - h_j)^2 + d^2}\) the direct distance, \(D' = \sqrt{(h_i + h_j + 2p)^2 + d^2}\) the distance to a complex-depth image, and the complex penetration depth

\[ p \;=\; 1 \big/ \sqrt{j\omega\mu_0\sigma_\text{earth}}. \]

The Deri/Semlyen approximation is not the production code path. It is provided as an alternative independent estimator that the test suite can compare against the Carson series — agreement within \(\approx 5\,\%\) over the typical parameter range confirms that neither implementation contains a sign or pre-factor bug.

Parameters:

Name Type Description Default
omega float

Same meaning as in carson_mutual_correction().

required
height_i float

Same meaning as in carson_mutual_correction().

required
height_j float

Same meaning as in carson_mutual_correction().

required
horizontal_distance float

Same meaning as in carson_mutual_correction().

required
sigma_earth float

Same meaning as in carson_mutual_correction().

required

Returns:

Name Type Description
Z complex

Per-unit-length earth-return correction in \(\Omega/\text{m}\) according to Deri/Semlyen 1981.

Notes

The "self" version is recovered by setting height_i = height_j and horizontal_distance = 0: the direct-distance term degenerates to the wire radius, which the caller must substitute manually (the formula does not include a wire-radius regularisation by itself).

Source code in src/groundfield/coupling/carson.py
def deri_semlyen_correction(
    omega: float,
    height_i: float,
    height_j: float,
    horizontal_distance: float,
    sigma_earth: float,
) -> complex:
    """Deri/Semlyen 1981 complex-depth approximation.

    Replaces the Carson integral by the closed-form expression

    $$
    \\Delta Z_\\text{Deri-Semlyen} \\;=\\; \\frac{j\\omega\\mu_0}{2\\pi}
    \\ln\\!\\Bigl(\\frac{D'}{D}\\Bigr),
    $$

    with $D = \\sqrt{(h_i - h_j)^2 + d^2}$ the direct distance,
    $D' = \\sqrt{(h_i + h_j + 2p)^2 + d^2}$ the distance to a
    complex-depth image, and the complex penetration depth

    $$
    p \\;=\\; 1 \\big/ \\sqrt{j\\omega\\mu_0\\sigma_\\text{earth}}.
    $$

    The Deri/Semlyen approximation is **not** the production
    code path. It is provided as an alternative independent
    estimator that the test suite can compare against the Carson
    series — agreement within $\\approx 5\\,\\%$ over the typical
    parameter range confirms that neither implementation contains
    a sign or pre-factor bug.

    Parameters
    ----------
    omega, height_i, height_j, horizontal_distance, sigma_earth
        Same meaning as in :func:`carson_mutual_correction`.

    Returns
    -------
    Z : complex
        Per-unit-length earth-return correction in $\\Omega/\\text{m}$
        according to Deri/Semlyen 1981.

    Notes
    -----
    The "self" version is recovered by setting
    ``height_i = height_j`` and ``horizontal_distance = 0``: the
    direct-distance term degenerates to the wire radius, which the
    caller must substitute manually (the formula does not include
    a wire-radius regularisation by itself).
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    p = 1.0 / np.sqrt(1j * omega * MU_0 * sigma_earth)
    D = math.hypot(height_i - height_j, horizontal_distance)
    if D == 0.0:
        D = 1e-9
    D_prime = np.sqrt((height_i + height_j + 2.0 * p) ** 2 + horizontal_distance**2)
    return complex(1j * omega * MU_0 / (2.0 * math.pi) * np.log(D_prime / D))

skin_depth

skin_depth(omega: float, sigma_earth: float) -> float

Electromagnetic skin depth in soil.

Returns \(\delta = \sqrt{2 / (\omega \mu_0 \sigma)}\) in metres. Diverges at \(\omega = 0\) (purely conductive earth- return path); the caller must handle that case by skipping the Carson correction altogether.

Parameters:

Name Type Description Default
omega float

Angular frequency \(\omega = 2\pi f\) in rad/s.

required
sigma_earth float

Earth conductivity \(\sigma\) in S/m.

required

Returns:

Name Type Description
delta float

Skin depth in metres. +inf when omega or sigma_earth is zero.

Source code in src/groundfield/coupling/carson.py
def skin_depth(omega: float, sigma_earth: float) -> float:
    """Electromagnetic skin depth in soil.

    Returns $\\delta = \\sqrt{2 / (\\omega \\mu_0 \\sigma)}$ in
    metres. Diverges at $\\omega = 0$ (purely conductive earth-
    return path); the caller must handle that case by skipping the
    Carson correction altogether.

    Parameters
    ----------
    omega
        Angular frequency $\\omega = 2\\pi f$ in rad/s.
    sigma_earth
        Earth conductivity $\\sigma$ in S/m.

    Returns
    -------
    delta : float
        Skin depth in metres. ``+inf`` when ``omega`` or
        ``sigma_earth`` is zero.
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return math.inf
    return math.sqrt(2.0 / (omega * MU_0 * sigma_earth))

Sommerfeld / Pollaczek earth return (ADR-0006)

sommerfeld_inductance

Geometric Sommerfeld earth-return Green function (ADR-0006).

This module implements the rigorous geometric formulation of the inductive earth-return coupling described in ADR-0006. Compared to ADR-0005's Carson per-meter scaling, it integrates the actual vector-potential Green's function over the segment-pair geometry, which correctly handles short wires, non-parallel arrangements, and layered earth.

Mathematical background

For a horizontal current element in a stratified, quasi-static medium (\(z > 0\) soil, \(z < 0\) air, layer \(k\) with \(\gamma_k^2 = j\omega\mu_0\sigma_k\) and vertical wavenumber \(u_k = \sqrt{\lambda^2 + \gamma_k^2}\), \(u_0 = \lambda\) in air; time convention \(e^{+j\omega t}\)), the vector-potential Green's function of a source at depth \(z'\) and an observer at depth \(z\) is

\[ G(\rho, z, z') \;=\; \delta_{kj}\,\frac{e^{-\gamma_k R}}{R} \;+\; \int_0^{\infty}\! \lambda\,F_{kj}(\lambda; z, z')\, J_0(\lambda\rho)\,d\lambda , \]

with \(k\) / \(j\) the layers of observer / source. The spectral amplitude \(F\) follows from the continuity of \(A\) and \(\partial A/\partial z\) at every interface. For source and observer in the same layer \(k\) (top at \(z_{k-1}\), thickness \(t\), depths \(h, h'\) measured from its top) it is the closed form

\[ F_{kk} \;=\; \frac{\tilde R_\uparrow e^{-u_k(h+h')} + \tilde R_\downarrow e^{-u_k(2t-h-h')} + \tilde R_\uparrow\tilde R_\downarrow\bigl[e^{-u_k(2t-(h-h'))} + e^{-u_k(2t+(h-h'))}\bigr]} {u_k\,\bigl(1 - \tilde R_\uparrow \tilde R_\downarrow e^{-2u_k t}\bigr)}, \]

where \(\tilde R_\uparrow\), \(\tilde R_\downarrow\) are the generalised reflection coefficients of the stack above and below layer \(k\) (bottom-up / top-down recursions over \(r_{k,m} = (u_k - u_m)/(u_k + u_m)\)). For the homogeneous half-space this is the familiar \((\lambda/u_1)\Gamma e^{-u_1(h+h')}\) with \(\Gamma = (u_1-\lambda)/(u_1+\lambda)\); for two layers it is the four-term buried-in-layer-1 amplitude validated against Tsiamitros (2005) Eq. (8) (WP-D2, 2026-07-20); for \(n \ge 3\) layers the generalised \(\tilde R_\downarrow\) makes it exact as well (review pass 10, finding 10.35 — the historic \(n \ge 3\) path used the single air-image form and was 17–25 % off in \(X'\)). Pairs in different layers (including a buried / overhead pair over a layered earth) use the transmitted amplitude, obtained from the same interface conditions by a small linear solve per \(\lambda\).

The overhead pair keeps Carson's geometry, \(\lambda F_{00} = -\Gamma_s(\lambda) e^{-\lambda(H+H')}\), with the surface reflection coefficient \(\Gamma_s\) of the whole stack.

Earth-return correction and image conventions

The functions here return the earth-return correction \(\Delta Z\) that is added to \(j\omega L\), the Neumann partial-inductance matrix of groundfield.coupling.inductance.build_inductance_matrix(). The correction depends on which image that matrix carries (image=):

  • "none" — \(\Delta G = G - 1/R\), the exact quasi-static correction to free space. At DC the soil is magnetically transparent: no image at all.
  • "additive" (historic default, ADR-0004) — the matrix carries the perfect-magnetic-mirror image \(L_\text{img}\); the correction removes it exactly: \(\Delta Z_\text{additive} = \Delta Z_\text{none} - j\omega L_\text{img}\), with \(L_\text{img}\) computed by the same routine that added it (closed form for parallel pairs, the mirrored orientation for inclined and vertical segments).
  • "antiparallel" — \(\Delta Z_\text{none} + j\omega L_\text{img}\); for a pair on opposite sides of the surface, whose anti-parallel baseline is zero (a perfect conductor screens the soil), \(\Delta Z_\text{none} + j\omega L_\text{dir}\).

Before review pass 10 the image was removed as \(-1/R'\) integrated by the 16x16 outer rule and weighted with the direct orientation: vertical segments kept twice the image in the \(\sigma \to 0\) limit, and segments much longer than twice their depth lost 0.6 % (25 m) to 5.7 % (50 m) of the image term (finding 10.46).

Numerical method

Each segment pair is integrated by 16x16 Gauss–Legendre over the two segments; the closed-form direct term \((e^{-\gamma R}-1)/R\) is evaluated at every node, the spectral part \(S(\rho) = \int \lambda F J_0(\lambda\rho)\,d\lambda\) on 24 log-spaced \(\rho\) nodes and interpolated (segments assumed approximately horizontal, mean depths per segment). Segments that cross the soil surface or a layer interface are split there first.

Along the line of closest approach of a segment with itself, or of two segments that come close (wires beside each other, a core in its shield), the integrand has a kink: the \(\gamma^2 R/2\) term of the direct part and the corresponding term of \(S\), smoothed only over the decay length of the spectral weight. The tensor rule cannot follow it: the self correction of a buried segment was 4.8e-4 off at a quarter skin depth (100 Ω·m), up to 1.5e-3 for two wires 1 mm apart in 30 over 1000 Ω·m. Since user decision Q34

  • the self term of a (sub-)segment is the exact one-dimensional reduction \(2\int_0^L (L - u)\,g(u)\,du\) of its double integral (one spectral plan per segment, so \(g\) depends on \(u = |s - s'|\) only), with graded 16-node panels (_self_values());
  • a close pair (closest distance of the Gauss nodes below half the longer segment) gets a graded rule along the line of closest approach (_close_pair_values()); for two coinciding segments it is the self rule;
  • the other pairs keep the tensor rule (16x16, composite for segments longer than a quarter skin depth).

The self correction is within 1.1e-9 of a refined rule (1024 logarithmic \(\lambda\) nodes) and of an independent reference (closed-form direct part, the \(\mathrm{Ji}_0\) kernel of the spectral part; audit W3B) from 1 m and 0.01 skin depths to 3 km at 50 Hz and 1 kHz and has no step where the rule changes (below 3e-13); close pairs are within about 4e-8 of the same two references (3.5e-8 for two 1 m wires 1 mm apart in 30 over 1000 Ω·m at 1 kHz, 2.7e-9 at a quarter skin depth). Up to audit W3B-01 the logarithmic region of the \(\lambda\) grid had 64 nodes and short segments missed the skin-scale part of \(S\): 1e-5 … 7.4e-5 at 0.01 skin depths, up to 3e-4 at 1 m (9e-9 of the input impedance of a 200 m PEN in 1 m pieces). Both rules cost at most linearly in the length: a lumped conductor of 2 km between a rod and a junction is solved in 1.1 s within 0.21 GB (audit W2B-05: 28 s, 1.6 GB, about \(L^{2.7}\)).

The \(\lambda\) quadrature (review pass 10, finding 10.36) follows the F14 policy of groundfield.coupling.layered_green: a logarithmic region on \([\epsilon, \lambda_\text{b}]\) with \(\lambda_\text{b} \le \pi/(4\rho_\text{max})\) so that it is free of \(J_0\) oscillations, followed by Gauss panels of width \(\le \pi/\rho_\text{max}\) (16 nodes per \(J_0\) period), geometrically graded near the skin and decay scales, up to \(\lambda_\text{max} = 30/z\). Before the fix the log region ended at \(\max(p_\text{skin}, 1/z)\) regardless of the distance, so \(J_0\) went unresolved for distant pairs (Re −24 % at 200 m, +274 % at 400 m), and a 4096-panel cap truncated silently. The node budget is now explicit: beyond a soft limit the density drops to 8 nodes per period, and a SommerfeldResolutionWarning is raised instead of a silent truncation when even that does not fit.

build_sommerfeld_correction_matrices() evaluates several frequencies at once (finding 10.60): geometry, \(\lambda\) grid and the Bessel table are built once per pair and reused for every frequency whose grid is identical (the common case — the grid depends on the frequency only through skin scales above \(1/z\)). Each frequency's matrix equals the single-frequency result bit for bit.

Limit checks (built into the test suite)
  • \(\sigma_e\to 0\): \(\Delta Z_\text{none} \to 0\), and with image="additive" the correction cancels the mirror exactly for every orientation.
  • \(\sigma_e\to\infty\), overhead pair: \(-\Gamma \to -1\), the net image becomes the anti-parallel PEC image (Carson's baseline).
  • \(\sigma_e\to\infty\), buried pair: \(e^{-\gamma R} \to 0\) — the conductor is screened by the surrounding medium.
  • Long parallel buried wires: the per-metre limit reproduces Pollaczek's \(\frac{j\omega\mu_0}{2\pi}\bigl[K_0(\gamma d) - K_0(\gamma D') + J_P\bigr]\).
  • A three-layer earth with \(\rho_2 = \rho_3\) reproduces the two-layer result.
References
  • Stratton, J. A. (1941). Electromagnetic Theory, McGraw-Hill, §9-10 — derivation of the half-space vector potential.
  • Sommerfeld, A. (1909). Über die Ausbreitung der Wellen in der drahtlosen Telegraphie. Ann. Phys. 28(4), 665–736.
  • Wait, J. R. (1972). Electromagnetic Waves in Stratified Media, Pergamon. Ch. 3.
  • Chew, W. C. (1995). Waves and Fields in Inhomogeneous Media, IEEE Press, §2.1 (generalised reflection coefficients).
  • Tsiamitros, D. A. et al. (2005). Earth return path impedances of underground cables for the two-layer earth case. IEEE Trans. Power Delivery 20(3), 2174–2181.

ImageConvention module-attribute

ImageConvention = Literal['none', 'additive', 'antiparallel']

Image convention of an inductance matrix.

  • "none": free space, no image;
  • "additive": perfect magnetic mirror at the soil surface (ADR-0004);
  • "antiparallel": perfect electric mirror, Carson's baseline.

MU_0 module-attribute

MU_0 = 4e-07 * math.pi

Vacuum permeability μ0 = 4π · 10⁻⁷ H/m (the conventional value).

SommerfeldAssembly module-attribute

SommerfeldAssembly = Literal['exact', 'tabulated']

Assembly of the Sommerfeld earth-return correction matrix.

  • "exact": one spectral quadrature per segment pair;
  • "tabulated": shared S(rho) tables per pair of depth groups and frequency (the default of groundfield.Engine.sommerfeld_assembly since 2026.11).

LayeredEarth dataclass

LayeredEarth(rhos: tuple[float, ...], thicknesses: tuple[float, ...])

Frozen layered-earth configuration for the Sommerfeld kernel.

Attributes:

Name Type Description
rhos tuple[float, ...]

Resistivities \(\rho_1, \dots, \rho_n\) of the layers in \(\Omega\,\mathrm{m}\). The last entry is the semi-infinite bottom layer.

thicknesses tuple[float, ...]

Thicknesses \(h_1, \dots, h_{n-1}\) in metres. The bottom layer has no thickness (semi-infinite). For len(thicknesses) == len(rhos) - 1.

Notes

Numerical precision contract. The reflection-coefficient evaluators (reflection_coefficient_homogeneous(), reflection_coefficient_layered()) and every consumer of this dataclass operate in IEEE-754 double precision (FP64). Future hardware-accelerated backends (e.g. an MLX path on Apple silicon) must honour the same precision. np.complex128 is the default at every entry point and is preserved through the Sommerfeld quadrature; do not silently down-cast to FP32 in a derived backend.

interface_depths property
interface_depths: tuple[float, ...]

Depths of the soil-layer interfaces below the surface, in m.

n_layers property
n_layers: int

Number of layers, including the semi-infinite bottom layer.

layer_of
layer_of(depth: float) -> int

Layer index (1-based) that contains depth (m, > 0 in soil).

A point exactly on an interface belongs to the lower layer.

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def layer_of(self, depth: float) -> int:
    """Layer index (1-based) that contains ``depth`` (m, > 0 in soil).

    A point exactly on an interface belongs to the lower layer.
    """
    return 1 + bisect.bisect_right(self.interface_depths, float(depth))

SommerfeldResolutionWarning

Bases: UserWarning

The Sommerfeld quadrature could not resolve the \(J_0\) oscillations.

The linear region of the Hankel grid places one Gauss panel per \(J_0(\lambda s)\) period, so the node count grows like \(\lambda_\text{max}\,s\). A hard node budget (_HANKEL_MAX_LINEAR_NODES) bounds the transient allocation; when that budget forces fewer than _HANKEL_MIN_NODES_PER_OSCILLATION nodes per period the quadrature is no longer converged and this warning is raised instead of returning a silently wrong number (a coarse grid on an oscillatory integrand does not merely lose digits — it can flip the sign of the result).

The remedy is always to lower lambda_max_factor or to reduce the horizontal distance range of the group. Lowering the factor does not lose accuracy: the truncated tail is subtracted in closed form (_reflected_image_terms()), so a smaller \(\lambda_\text{max}\) only moves work from the quadrature into the exact image sum. Silence with warnings.simplefilter("ignore", SommerfeldResolutionWarning) only if the affected entries are known to be negligible.

build_sommerfeld_correction_matrices

build_sommerfeld_correction_matrices(seg_endpoints: ndarray, wire_radii: ndarray | None = None, *, omegas: Sequence[float], earth: LayeredEarth, image: ImageConvention = 'additive', method: SommerfeldAssembly = 'exact') -> np.ndarray

Sommerfeld earth-return correction matrices for several frequencies.

Multi-frequency form of build_sommerfeld_correction_matrix() (finding 10.60): per segment pair the outer geometry, the \(\lambda\) grid and the Bessel table \(J_0(\lambda\rho)\) — about three quarters of the historic per-frequency cost — are built once and reused for every frequency with the same grid. Entry k equals build_sommerfeld_correction_matrix(..., omega=omegas[k]) bit for bit.

Parameters:

Name Type Description Default
seg_endpoints ndarray

Array of shape (M, 2, 3): start and end point (m) of every inductive branch segment.

required
wire_radii ndarray | None

Per-branch wire radii in m. Only used with an image convention: a mirrored partner that interpenetrates a segment is evaluated as a touching wire, as in build_inductance_matrix() (pass the same radii for an exact match in that degenerate case).

None
omegas Sequence[float]

Angular frequencies in rad/s; entries <= 0 give zeros.

required
earth LayeredEarth

Layered-earth configuration.

required
image ImageConvention

Image convention of the inductance matrix the corrections are added to: "additive" (default), "none" (exact baseline, cheapest; what the solver assembles) or "antiparallel".

'additive'
method SommerfeldAssembly

"exact" (default): every segment pair gets its own \(\lambda\) grid and Bessel table, and \(S(\rho)\) is interpolated linearly on 24 nodes per pair. "tabulated" (finding 10.60; what the solver uses by default since 2026.11, groundfield.Engine.sommerfeld_assembly): sub-segments are grouped by depth, every pair of depth groups shares one table of \(S(\rho)\) per frequency (cubic spline in \(\ln(\rho + z)\) on the \(\lambda\) grid of the group's largest distance), and the outer nodes of all pairs are evaluated vectorised; blocks of fewer than 64 sub-segment pairs use the exact rule. In both assemblies the self term of every segment and every close pair get the rules of user decision Q34 (one-dimensional self rule, graded close-pair rule; see the module docstring), which also bound the cost of long conductors.

'exact'

Returns:

Name Type Description
dZ np.ndarray, shape (n_f, M, M), dtype complex

Symmetric correction matrices in Ω.

Raises:

Type Description
ValueError

If image is not one of "none", "additive", "antiparallel", or method is not "exact" or "tabulated".

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def build_sommerfeld_correction_matrices(
    seg_endpoints: np.ndarray,  # shape (M, 2, 3)
    wire_radii: np.ndarray | None = None,
    *,
    omegas: Sequence[float],
    earth: LayeredEarth,
    image: ImageConvention = "additive",
    method: SommerfeldAssembly = "exact",
) -> np.ndarray:
    """Sommerfeld earth-return correction matrices for several frequencies.

    Multi-frequency form of :func:`build_sommerfeld_correction_matrix`
    (finding 10.60): per segment pair the outer geometry, the
    $\\lambda$ grid and the Bessel table $J_0(\\lambda\\rho)$ — about
    three quarters of the historic per-frequency cost — are built once
    and reused for every frequency with the same grid. Entry ``k``
    equals ``build_sommerfeld_correction_matrix(..., omega=omegas[k])``
    bit for bit.

    Parameters
    ----------
    seg_endpoints
        Array of shape ``(M, 2, 3)``: start and end point (m) of every
        inductive branch segment.
    wire_radii
        Per-branch wire radii in m. Only used with an image convention:
        a mirrored partner that interpenetrates a segment is evaluated as
        a touching wire, as in
        :func:`~groundfield.coupling.inductance.build_inductance_matrix`
        (pass the same radii for an exact match in that degenerate case).
    omegas
        Angular frequencies in rad/s; entries ``<= 0`` give zeros.
    earth
        Layered-earth configuration.
    image
        Image convention of the inductance matrix the corrections are
        added to: ``"additive"`` (default), ``"none"`` (exact baseline,
        cheapest; what the solver assembles) or ``"antiparallel"``.
    method
        ``"exact"`` (default): every segment pair gets its own
        $\\lambda$ grid and Bessel table, and $S(\\rho)$ is interpolated
        linearly on 24 nodes per pair. ``"tabulated"`` (finding 10.60;
        what the solver uses by default since 2026.11,
        :attr:`groundfield.Engine.sommerfeld_assembly`): sub-segments are grouped by depth, every pair of depth
        groups shares one table of $S(\\rho)$ per frequency (cubic
        spline in $\\ln(\\rho + z)$ on the $\\lambda$ grid of the
        group's largest distance), and the outer nodes of all pairs are
        evaluated vectorised; blocks of fewer than 64 sub-segment pairs
        use the exact rule. In both assemblies the self term of every
        segment and every close pair get the rules of user decision Q34
        (one-dimensional self rule, graded close-pair rule; see the module
        docstring), which also bound the cost of long conductors.

    Returns
    -------
    dZ : np.ndarray, shape (n_f, M, M), dtype complex
        Symmetric correction matrices in Ω.

    Raises
    ------
    ValueError
        If ``image`` is not one of ``"none"``, ``"additive"``,
        ``"antiparallel"``, or ``method`` is not ``"exact"`` or
        ``"tabulated"``.
    """
    mode = _resolve_image(image, None)
    if method not in _ASSEMBLIES:
        raise ValueError(f"method must be one of {_ASSEMBLIES}, got {method!r}")
    omegas = [float(om) for om in np.atleast_1d(np.asarray(omegas, dtype=float))]
    seg_endpoints = np.asarray(seg_endpoints, dtype=float)
    M = seg_endpoints.shape[0]
    out = np.zeros((len(omegas), M, M), dtype=complex)
    if M == 0 or all(om <= 0.0 for om in omegas):
        return out
    L_img = None
    if mode != "none":
        # The image block of build_inductance_matrix(image=mode); with
        # "antiparallel" a pair on opposite sides of the surface has no
        # baseline, so its correction moves by the direct mutual instead
        # (audit A2C-1).
        L_img = _image_inductance_matrix(seg_endpoints, wire_radii=wire_radii)
        if mode == "antiparallel":
            opposite = _opposite_sides(seg_endpoints[:, 0], seg_endpoints[:, 1])
            if opposite.any():
                L_dir = _direct_mutual_matrix(seg_endpoints, wire_radii)
                L_img[opposite] = L_dir[opposite]
    if method == "tabulated":
        out = _tabulated_values_none(seg_endpoints, omegas, earth)
    else:
        for i in range(M):
            p1_i = seg_endpoints[i, 0]
            p2_i = seg_endpoints[i, 1]
            for j in range(i, M):
                sign = 1.0 if i == j else _same_segment(p1_i, p2_i, *seg_endpoints[j])
                if sign != 0.0:
                    vals = sign * _pair_values_none(
                        p1_i, p2_i, p1_i, p2_i, omegas, earth, same=True
                    )
                else:
                    vals = _pair_values_none(
                        p1_i,
                        p2_i,
                        seg_endpoints[j, 0],
                        seg_endpoints[j, 1],
                        omegas,
                        earth,
                    )
                out[:, i, j] = vals
                out[:, j, i] = vals
    if L_img is not None:
        sign = -1.0 if mode == "additive" else 1.0
        for k, om in enumerate(omegas):
            if om > 0.0:
                out[k] += sign * 1j * om * L_img
    return out

build_sommerfeld_correction_matrix

build_sommerfeld_correction_matrix(seg_endpoints: ndarray, wire_radii: ndarray | None = None, *, omega: float, earth: LayeredEarth, image: ImageConvention = 'additive', method: SommerfeldAssembly = 'exact') -> np.ndarray

Assemble the dense Sommerfeld earth-return correction matrix.

The output is the σ-dependent addition to the Neumann inductance matrix of groundfield.coupling.inductance.build_inductance_matrix() built with the same image convention:

.. code-block:: python

Z_b = jω · L(image=image) + dZ_Sommerfeld(image=image)

For earth.n_layers == 1 this is the homogeneous-earth Pollaczek kernel; for n >= 2 the exact layered kernel is used. Several frequencies at once: build_sommerfeld_correction_matrices().

Parameters:

Name Type Description Default
seg_endpoints ndarray

Array of shape (M, 2, 3) with the start- and end-points (m) of every distributed-conductor longitudinal-branch segment.

required
wire_radii ndarray | None

Per-branch wire radii in m (only used with an image convention, see build_sommerfeld_correction_matrices()).

None
omega float

Angular frequency in rad/s.

required
earth LayeredEarth

Layered-earth configuration.

required
image ImageConvention

"additive" (default), "none" or "antiparallel" — see the module docstring.

'additive'
method SommerfeldAssembly

"exact" (default of this function) or "tabulated" (the solver's default, see build_sommerfeld_correction_matrices()).

'exact'

Returns:

Name Type Description
dZ np.ndarray, shape (M, M), dtype complex

Symmetric Sommerfeld correction matrix in \(\Omega\).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def build_sommerfeld_correction_matrix(
    seg_endpoints: np.ndarray,  # shape (M, 2, 3)
    wire_radii: np.ndarray | None = None,
    *,
    omega: float,
    earth: LayeredEarth,
    image: ImageConvention = "additive",
    method: SommerfeldAssembly = "exact",
) -> np.ndarray:
    """Assemble the dense Sommerfeld earth-return correction matrix.

    The output is the σ-dependent addition to the Neumann inductance
    matrix of
    :func:`groundfield.coupling.inductance.build_inductance_matrix`
    built with the same image convention:

    .. code-block:: python

        Z_b = jω · L(image=image) + dZ_Sommerfeld(image=image)

    For ``earth.n_layers == 1`` this is the homogeneous-earth
    Pollaczek kernel; for ``n >= 2`` the exact layered kernel is used.
    Several frequencies at once: :func:`build_sommerfeld_correction_matrices`.

    Parameters
    ----------
    seg_endpoints
        Array of shape ``(M, 2, 3)`` with the start- and end-points
        (m) of every distributed-conductor longitudinal-branch segment.
    wire_radii
        Per-branch wire radii in m (only used with an image convention,
        see :func:`build_sommerfeld_correction_matrices`).
    omega
        Angular frequency in rad/s.
    earth
        Layered-earth configuration.
    image
        ``"additive"`` (default), ``"none"`` or ``"antiparallel"`` —
        see the module docstring.
    method
        ``"exact"`` (default of this function) or ``"tabulated"`` (the
        solver's default, see :func:`build_sommerfeld_correction_matrices`).

    Returns
    -------
    dZ : np.ndarray, shape (M, M), dtype complex
        Symmetric Sommerfeld correction matrix in $\\Omega$.
    """
    if omega <= 0.0:
        return np.zeros(
            (np.asarray(seg_endpoints).shape[0],) * 2,
            dtype=complex,
        )
    return build_sommerfeld_correction_matrices(
        seg_endpoints,
        wire_radii,
        omegas=[omega],
        earth=earth,
        image=image,
        method=method,
    )[0]

earth_return_correction_homogeneous

earth_return_correction_homogeneous(*, rho: float, z_i: float, z_j: float, omega: float, sigma_earth: float) -> complex

σ-dependent earth-return correction beyond the additive mirror.

Point-kernel form of the buried–buried Pollaczek correction (see the module docstring):

\[ \Delta G \;=\; \frac{e^{-\gamma R} - 1}{R} \;-\; \frac{1}{R'} \;+\; \int_0^\infty \frac{\lambda}{u_1}\, \Gamma(\lambda)\, e^{-u_1 (z + z')}\, J_0(\lambda\rho)\,d\lambda, \]

with \(R = \sqrt{\rho^2 + (z - z')^2}\), \(R' = \sqrt{\rho^2 + (z + z')^2}\). This is the σ-dependent piece to be added to the ADR-0004 result (which carries \(1/R + 1/R'\)): the \(-1/R'\) removes the additive mirror, the attenuated direct term carries the buried-path earth-return resistance, and the \(\lambda/u_1\)-weighted reflection is the genuine soil-side boundary response.

Limit checks:

  • \(\sigma_e \to 0\): \(\gamma \to 0\), \(\Gamma \to 0\) — correction \(\to -1/R'\) → cancels the ADR-0004 image, total → free space \(1/R\).
  • \(\sigma_e \to \infty\): \(e^{-\gamma R} \to 0\), \(\lambda/u_1 \to 0\) — correction \(\to -1/R - 1/R'\), total → 0 (buried conductor screened by the surrounding medium).

Parameters:

Name Type Description Default
rho float

Horizontal distance between source and field point in m. Must be ≥ 0.

required
z_i float

Depths (positive into soil) in m. Must be > 0 for the integral to converge.

required
z_j float

Depths (positive into soil) in m. Must be > 0 for the integral to converge.

required
omega float

Angular frequency in rad/s.

required
sigma_earth float

Earth conductivity in S/m.

required

Returns:

Name Type Description
correction complex

The kernel above in 1/m (the pair integrals multiply by \(j\omega\mu_0/(4\pi)\) and integrate over both segments).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def earth_return_correction_homogeneous(
    *,
    rho: float,
    z_i: float,
    z_j: float,
    omega: float,
    sigma_earth: float,
) -> complex:
    """σ-dependent earth-return correction beyond the additive mirror.

    Point-kernel form of the **buried–buried** Pollaczek correction
    (see the module docstring):

    $$
    \\Delta G \\;=\\; \\frac{e^{-\\gamma R} - 1}{R}
    \\;-\\; \\frac{1}{R'}
    \\;+\\; \\int_0^\\infty \\frac{\\lambda}{u_1}\\,
    \\Gamma(\\lambda)\\, e^{-u_1 (z + z')}\\,
    J_0(\\lambda\\rho)\\,d\\lambda,
    $$

    with $R = \\sqrt{\\rho^2 + (z - z')^2}$,
    $R' = \\sqrt{\\rho^2 + (z + z')^2}$. This is the σ-dependent
    piece *to be added to the ADR-0004 result* (which carries
    $1/R + 1/R'$): the $-1/R'$ removes the additive mirror, the
    attenuated direct term carries the buried-path earth-return
    resistance, and the $\\lambda/u_1$-weighted reflection is the
    genuine soil-side boundary response.

    Limit checks:

    - $\\sigma_e \\to 0$: $\\gamma \\to 0$, $\\Gamma \\to 0$ —
      correction $\\to -1/R'$ → cancels the ADR-0004 image, total
      → free space $1/R$.
    - $\\sigma_e \\to \\infty$: $e^{-\\gamma R} \\to 0$,
      $\\lambda/u_1 \\to 0$ — correction $\\to -1/R - 1/R'$, total
      → 0 (buried conductor screened by the surrounding medium).

    Parameters
    ----------
    rho
        Horizontal distance between source and field point in m.
        Must be ≥ 0.
    z_i, z_j
        Depths (positive into soil) in m. Must be > 0 for the
        integral to converge.
    omega
        Angular frequency in rad/s.
    sigma_earth
        Earth conductivity in S/m.

    Returns
    -------
    correction : complex
        The kernel above in 1/m (the pair integrals multiply by
        $j\\omega\\mu_0/(4\\pi)$ and integrate over both segments).
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    earth = LayeredEarth(rhos=(1.0 / sigma_earth,), thicknesses=())
    return earth_return_correction_layered(
        rho=rho, z_i=z_i, z_j=z_j, omega=omega, earth=earth
    )

earth_return_correction_layered

earth_return_correction_layered(*, rho: float, z_i: float, z_j: float, omega: float, earth: LayeredEarth) -> complex

Layered-earth analogue of earth_return_correction_homogeneous().

Buried–buried point kernel beyond the additive mirror, \(\Delta G = G - 1/R - 1/R'\), with the exact layered Green's function of the module docstring: the generalised-reflection closed form for points in the same layer, the transmitted amplitude otherwise. Review pass 10 (finding 10.46, pass-9 F50): the historic implementation used the single air-image form with the stack's surface reflection coefficient, whose reflected term has the opposite sign of the exact two-layer kernel (e.g. +8.7e-3 instead of −6.3e-3 at \(\rho = 0\) for earth (100, 10) Ω·m, \(h_1\) = 3 m, 1 kHz, \(z = z' = 0.6\) m).

Parameters:

Name Type Description Default
rho float

Horizontal distance in m (≥ 0).

required
z_i float

Depths of observer and source in m (> 0, in the soil).

required
z_j float

Depths of observer and source in m (> 0, in the soil).

required
omega float

Angular frequency in rad/s.

required
earth LayeredEarth

Layered-earth configuration.

required

Returns:

Name Type Description
correction complex

Kernel value in 1/m.

Raises:

Type Description
ValueError

If z_i or z_j is not positive (a point not buried) and omega is positive.

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def earth_return_correction_layered(
    *,
    rho: float,
    z_i: float,
    z_j: float,
    omega: float,
    earth: LayeredEarth,
) -> complex:
    """Layered-earth analogue of :func:`earth_return_correction_homogeneous`.

    Buried–buried point kernel beyond the additive mirror,
    $\\Delta G = G - 1/R - 1/R'$, with the exact layered Green's
    function of the module docstring: the generalised-reflection
    closed form for points in the same layer, the transmitted amplitude
    otherwise. Review pass 10 (finding 10.46, pass-9 F50): the
    historic implementation used the single air-image form with the
    stack's surface reflection coefficient, whose reflected term has
    the **opposite sign** of the exact two-layer kernel (e.g.
    +8.7e-3 instead of −6.3e-3 at $\\rho = 0$ for earth (100, 10)
    Ω·m, $h_1$ = 3 m, 1 kHz, $z = z' = 0.6$ m).

    Parameters
    ----------
    rho
        Horizontal distance in m (≥ 0).
    z_i, z_j
        Depths of observer and source in m (> 0, in the soil).
    omega
        Angular frequency in rad/s.
    earth
        Layered-earth configuration.

    Returns
    -------
    correction : complex
        Kernel value in 1/m.

    Raises
    ------
    ValueError
        If ``z_i`` or ``z_j`` is not positive (a point not buried) and
        ``omega`` is positive.
    """
    if omega <= 0.0:
        return 0.0 + 0.0j
    if z_i <= 0.0 or z_j <= 0.0:
        raise ValueError(
            f"earth_return_correction_layered needs buried points (z > 0); "
            f"got z_i={z_i}, z_j={z_j}"
        )
    rho = float(rho)
    R_dir = math.sqrt(rho * rho + (z_i - z_j) ** 2)
    R_mir = math.sqrt(rho * rho + (z_i + z_j) ** 2)
    k_i = earth.layer_of(z_i)
    k_j = earth.layer_of(z_j)
    plan = _SpectralPlan.buried(earth, z_i, z_j, k_i, k_j)
    lambdas, weights = _build_lambda_grid(
        z_sum=plan.decay,
        rho_max=max(rho, 1e-6),
        omega=omega,
        sigma_top=1.0 / earth.rhos[plan.ref_layer - 1],
        scales=plan.scales(omega, earth),
    )
    spec = plan.weight(lambdas, omega, earth)
    reflected = complex(np.sum(weights * spec * j0(lambdas * rho)))
    if k_i == k_j:
        gamma = complex(np.sqrt(1j * omega * MU_0 / earth.rhos[k_i - 1]))
        if R_dir < 1e-9:
            direct = -gamma
        else:
            direct = (np.exp(-gamma * R_dir) - 1.0) / R_dir
    else:
        direct = 0.0
    return complex(direct) - 1.0 / max(R_mir, 1e-9) + reflected

per_metre_mutual_impedance

per_metre_mutual_impedance(z_i: float, z_j: float, distance: float, *, omega: float, earth: LayeredEarth) -> complex

Mutual impedance per metre of two infinite parallel horizontal wires.

Exact quasi-static earth-return impedance (Ω/m) of two long parallel wires at depths z_i, z_j (m, z > 0 in the soil, z < 0 overhead; both on one side of the surface, buried ones in one layer) at the horizontal distance distance (m) over the layered earth: the line integral of the Green's function of the module docstring, \(\int_{-\infty}^{\infty} J_0(\lambda\sqrt{x^2 + s^2})\,ds = 2\cos(\lambda x)/\lambda\),

\[ Z'(x) \;=\; \frac{j\omega\mu_0}{4\pi}\Bigl[2K_0(\gamma_k R) + \int_0^\infty w(\lambda)\,\frac{2\cos\lambda x}{\lambda}\,d\lambda\Bigr] \]

for wires in layer \(k\) (\(R = \sqrt{x^2 + (z_i - z_j)^2}\), \(w\) the reflected amplitude of the same-layer kernel, exact for any number of layers), and \(\frac{j\omega\mu_0}{4\pi}\int_0^\infty [e^{-\lambda|z_i - z_j|} - \Gamma(\lambda)e^{-\lambda(h_i + h_j)}] \,2\cos(\lambda x)/\lambda\,d\lambda\) for overhead wires (Carson's integral with the surface reflection coefficient of the stack). The self impedance per metre of a wire is the value at distance equal to its radius (or GMR). The \(\lambda\) quadrature is the one of the segment pairs (finding 10.36) with four times the nodes. For a homogeneous earth this is Carson's (overhead) and Pollaczek's (buried) impedance; it agrees with Carson to 2e-9 and with the two-layer Pollaczek integral of groundfield.references.pollaczek to 5e-8 of the impedance (0.1 … 300 m). Against an independent integral (audit W3B-08: composite Gauss, checked against mpmath to 2e-15; one to four layers, 50 Hz and 1 kHz, 1 cm … 1 km) it is within 6e-8 of the earth-return correction up to 300 m and 7e-7 at 1 km for buried pairs, 4e-8 for overhead pairs; the remainder is not the logarithmic region of the \(\lambda\) grid (the same with 256 and 1024 nodes there).

Parameters:

Name Type Description Default
z_i float

Depths of the two wires in m (> 0 buried, < 0 overhead).

required
z_j float

Depths of the two wires in m (> 0 buried, < 0 overhead).

required
distance float

Horizontal distance in m (> 0; for the self impedance the wire radius or GMR).

required
omega float

Angular frequency in rad/s (> 0).

required
earth LayeredEarth

Layered-earth configuration.

required

Returns:

Type Description
complex

Mutual impedance per metre in Ω/m.

Raises:

Type Description
ValueError

For wires on opposite sides of the surface or in different layers, a non-positive distance or frequency.

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def per_metre_mutual_impedance(
    z_i: float,
    z_j: float,
    distance: float,
    *,
    omega: float,
    earth: LayeredEarth,
) -> complex:
    """Mutual impedance per metre of two infinite parallel horizontal wires.

    Exact quasi-static earth-return impedance (Ω/m) of two long parallel
    wires at depths ``z_i``, ``z_j`` (m, ``z > 0`` in the soil, ``z < 0``
    overhead; both on one side of the surface, buried ones in one layer) at
    the horizontal distance ``distance`` (m) over the layered earth: the
    line integral of the Green's function of the module docstring,
    $\\int_{-\\infty}^{\\infty} J_0(\\lambda\\sqrt{x^2 + s^2})\\,ds =
    2\\cos(\\lambda x)/\\lambda$,

    $$
    Z'(x) \\;=\\; \\frac{j\\omega\\mu_0}{4\\pi}\\Bigl[2K_0(\\gamma_k R)
    + \\int_0^\\infty w(\\lambda)\\,\\frac{2\\cos\\lambda x}{\\lambda}\\,d\\lambda\\Bigr]
    $$

    for wires in layer $k$ ($R = \\sqrt{x^2 + (z_i - z_j)^2}$, $w$ the
    reflected amplitude of the same-layer kernel, exact for any number of
    layers), and $\\frac{j\\omega\\mu_0}{4\\pi}\\int_0^\\infty
    [e^{-\\lambda|z_i - z_j|} - \\Gamma(\\lambda)e^{-\\lambda(h_i + h_j)}]
    \\,2\\cos(\\lambda x)/\\lambda\\,d\\lambda$ for overhead wires (Carson's
    integral with the surface reflection coefficient of the stack). The
    self impedance per metre of a wire is the value at ``distance`` equal to
    its radius (or GMR). The $\\lambda$ quadrature is the one of the segment
    pairs (finding 10.36) with four times the nodes. For a homogeneous earth
    this is Carson's (overhead) and Pollaczek's (buried) impedance; it agrees
    with Carson to 2e-9 and with the two-layer Pollaczek integral of
    :mod:`groundfield.references.pollaczek` to 5e-8 of the impedance
    (0.1 … 300 m). Against an independent integral (audit W3B-08: composite
    Gauss, checked against mpmath to 2e-15; one to four layers, 50 Hz and
    1 kHz, 1 cm … 1 km) it is within 6e-8 of the earth-return correction up
    to 300 m and 7e-7 at 1 km for buried pairs, 4e-8 for overhead pairs;
    the remainder is not the logarithmic region of the $\\lambda$ grid (the
    same with 256 and 1024 nodes there).

    Parameters
    ----------
    z_i, z_j
        Depths of the two wires in m (``> 0`` buried, ``< 0`` overhead).
    distance
        Horizontal distance in m (``> 0``; for the self impedance the wire
        radius or GMR).
    omega
        Angular frequency in rad/s (``> 0``).
    earth
        Layered-earth configuration.

    Returns
    -------
    complex
        Mutual impedance per metre in Ω/m.

    Raises
    ------
    ValueError
        For wires on opposite sides of the surface or in different layers,
        a non-positive distance or frequency.
    """
    from scipy.special import kv

    if not (omega > 0.0) or not (distance > 0.0):
        raise ValueError("per_metre_mutual_impedance needs omega > 0 and distance > 0")
    plan = _SpectralPlan.for_pair(earth, float(z_i), float(z_j))
    if plan.kind not in ("same", "air"):
        raise ValueError(
            "per_metre_mutual_impedance: both wires must lie overhead or in one "
            f"soil layer (got z_i = {z_i}, z_j = {z_j})"
        )
    x = float(distance)
    dz = abs(float(z_i) - float(z_j))
    # The segment-pair policy with four times the nodes (1024 in the log
    # region since audit W3B-01, 256 before; at least 256 panels): a
    # reference, 8e-6 off with the pair grid at x = 0.1 m, within 1e-8 of
    # Carson and of the two-layer Pollaczek integral
    # (groundfield.references.pollaczek) with this one.
    p_ref = math.sqrt(omega * MU_0 / earth.rhos[plan.ref_layer - 1])
    lb, lm, rm, gt = _grid_params(
        z_sum=plan.decay, rho_max=x, p_ref=p_ref, scales=plan.scales(omega, earth)
    )
    lambdas, weights, resolved = _build_grid(
        lb, lm, max(rm, 256.0 * math.pi / (lm - lb)), gt, 4 * _N_LOG_NODES
    )
    if not resolved:
        _warn_unresolved((lb, lm, rm, gt))
    w = plan.weight(lambdas, omega, earth)
    if plan.kind == "air":
        # e^{-l dz} - Gamma e^{-l Z} = (e^{-l dz} - e^{-l Z}) + (1 - Gamma) e^{-l Z};
        # the first part is Frullani's integral, ln((Z^2 + x^2) / (dz^2 + x^2)):
        # the free-space part does not decay with lambda (Carson's image term)
        z_sum = plan.h_a + plan.h_b
        w = w + np.exp(-lambdas * z_sum)
    total = complex(np.sum(weights * w * 2.0 * np.cos(lambdas * x) / lambdas))
    if plan.kind == "air":
        total += math.log((z_sum * z_sum + x * x) / (dz * dz + x * x))
    if plan.kind == "same":
        gamma = complex(np.sqrt(1j * omega * MU_0 / earth.rhos[plan.ref_layer - 1]))
        total += 2.0 * complex(kv(0, gamma * math.hypot(x, dz)))
    return 1j * omega * MU_0 / (4.0 * math.pi) * total

reflection_coefficient_homogeneous

reflection_coefficient_homogeneous(lambdas: ndarray, *, omega: float, sigma_earth: float) -> np.ndarray

Magnetic reflection coefficient for a homogeneous half-space.

\[ \Gamma_\text{mag}^{(1)}(\lambda) \;=\; \frac{u_e - \lambda}{u_e + \lambda}, \qquad u_e \;=\; \sqrt{\lambda^2 + j\omega\mu_0\sigma_e}. \]

Parameters:

Name Type Description Default
lambdas ndarray

Spectral variable in 1/m, shape (N_lam,). Must be non-negative.

required
omega float

Angular frequency in rad/s.

required
sigma_earth float

Earth conductivity in S/m.

required

Returns:

Name Type Description
Gamma (ndarray, complex, shape(N_lam))

Reflection coefficient at each \(\lambda\) (dimensionless).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def reflection_coefficient_homogeneous(
    lambdas: np.ndarray,
    *,
    omega: float,
    sigma_earth: float,
) -> np.ndarray:
    """Magnetic reflection coefficient for a homogeneous half-space.

    .. math::

        \\Gamma_\\text{mag}^{(1)}(\\lambda) \\;=\\;
        \\frac{u_e - \\lambda}{u_e + \\lambda},
        \\qquad u_e \\;=\\; \\sqrt{\\lambda^2 + j\\omega\\mu_0\\sigma_e}.

    Parameters
    ----------
    lambdas : np.ndarray
        Spectral variable in 1/m, shape ``(N_lam,)``. Must be
        non-negative.
    omega
        Angular frequency in rad/s.
    sigma_earth
        Earth conductivity in S/m.

    Returns
    -------
    Gamma : np.ndarray, complex, shape (N_lam,)
        Reflection coefficient at each $\\lambda$ (dimensionless).
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return np.zeros_like(lambdas, dtype=complex)
    u_e = np.sqrt(lambdas * lambdas + 1j * omega * MU_0 * sigma_earth)
    return (u_e - lambdas) / (u_e + lambdas)

reflection_coefficient_layered

reflection_coefficient_layered(lambdas: ndarray, *, omega: float, earth: LayeredEarth) -> np.ndarray

Magnetic surface reflection coefficient of an \(n\)-layer earth.

The generalised reflection coefficient of the whole stack seen from the air, in the convention of reflection_coefficient_homogeneous() (so that the air-side reflection of a downward wave is \(-\Gamma\)). It is built from the deepest interface upwards,

\[ \Gamma \leftarrow \frac{r_k + \Gamma\,e^{-2u_{k+1}h_{k+1}}} {1 + r_k\,\Gamma\,e^{-2u_{k+1}h_{k+1}}}, \qquad r_k = \frac{u_{k+1} - u_k}{u_{k+1} + u_k}, \]

with \(u_0 = \lambda\) (air) and \(u_k\) the vertical wavenumber of layer \(k\). It reduces to the homogeneous \(\rho_1\) half-space as \(h_1 \to \infty\) and to the \(\rho_2\) half-space as \(h_1 \to 0\). For \(n = 1\) it is reflection_coefficient_homogeneous().

Parameters:

Name Type Description Default
lambdas ndarray

Spectral variable in 1/m, shape (N_lam,).

required
omega float

Angular frequency in rad/s.

required
earth LayeredEarth

Layered-earth configuration.

required

Returns:

Name Type Description
Gamma (ndarray, complex)

Surface reflection coefficient (dimensionless).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def reflection_coefficient_layered(
    lambdas: np.ndarray,
    *,
    omega: float,
    earth: LayeredEarth,
) -> np.ndarray:
    """Magnetic surface reflection coefficient of an $n$-layer earth.

    The generalised reflection coefficient of the whole stack seen
    from the air, in the convention of
    :func:`reflection_coefficient_homogeneous` (so that the air-side
    reflection of a downward wave is $-\\Gamma$). It is built from the
    deepest interface upwards,

    .. math::

        \\Gamma \\leftarrow \\frac{r_k + \\Gamma\\,e^{-2u_{k+1}h_{k+1}}}
                                  {1 + r_k\\,\\Gamma\\,e^{-2u_{k+1}h_{k+1}}},
        \\qquad r_k = \\frac{u_{k+1} - u_k}{u_{k+1} + u_k},

    with $u_0 = \\lambda$ (air) and $u_k$ the vertical wavenumber of
    layer $k$. It reduces to the homogeneous $\\rho_1$ half-space as
    $h_1 \\to \\infty$ and to the $\\rho_2$ half-space as $h_1 \\to 0$.
    For $n = 1$ it is :func:`reflection_coefficient_homogeneous`.

    Parameters
    ----------
    lambdas : np.ndarray
        Spectral variable in 1/m, shape ``(N_lam,)``.
    omega
        Angular frequency in rad/s.
    earth : LayeredEarth
        Layered-earth configuration.

    Returns
    -------
    Gamma : np.ndarray, complex
        Surface reflection coefficient (dimensionless).
    """
    if omega <= 0.0:
        return np.zeros_like(lambdas, dtype=complex)
    n = earth.n_layers
    if n == 1:
        return reflection_coefficient_homogeneous(
            lambdas,
            omega=omega,
            sigma_earth=1.0 / earth.rhos[0],
        )
    u = _vertical_wavenumbers(lambdas, omega, earth)
    gamma = (u[n] - u[n - 1]) / (u[n] + u[n - 1])  # r_{n-1}, deepest interface
    for k in range(n - 2, -1, -1):
        r_k = (u[k + 1] - u[k]) / (u[k + 1] + u[k])
        phase = np.exp(-2.0 * u[k + 1] * earth.thicknesses[k])
        gamma = (r_k + gamma * phase) / (1.0 + r_k * gamma * phase)
    return gamma

sommerfeld_pair_integral_homogeneous

sommerfeld_pair_integral_homogeneous(p1_a: ndarray, p2_a: ndarray, p1_b: ndarray, p2_b: ndarray, *, omega: float, sigma_earth: float, image: ImageConvention = 'additive') -> complex

Integrate the σ-dependent magnetic Green function over a segment pair.

Computes

\[ \Delta Z^{(i,j)} \;=\; \frac{j\omega\mu_0}{4\pi} \int_{C_i}\!\!\int_{C_j} (\hat{l}_i\cdot\hat{l}_j)\, \Delta G(\vec{r}_i, \vec{r}_j;\,\omega,\sigma_e)\, dl_i\,dl_j, \]

the earth-return correction of a homogeneous earth relative to the image convention image of the inductance matrix it is added to (see the module docstring). Used by build_sommerfeld_correction_matrix().

Parameters:

Name Type Description Default
p1_a ndarray

End points of the two segments in m (\(z > 0\) in the soil).

required
p2_a ndarray

End points of the two segments in m (\(z > 0\) in the soil).

required
p1_b ndarray

End points of the two segments in m (\(z > 0\) in the soil).

required
p2_b ndarray

End points of the two segments in m (\(z > 0\) in the soil).

required
omega float

Angular frequency in rad/s.

required
sigma_earth float

Earth conductivity in S/m.

required
image ImageConvention

"additive" (default, the historic ADR-0004 baseline), "none" or "antiparallel".

'additive'

Returns:

Name Type Description
Z complex

Per-pair earth-return correction in \(\Omega\).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def sommerfeld_pair_integral_homogeneous(
    p1_a: np.ndarray,
    p2_a: np.ndarray,
    p1_b: np.ndarray,
    p2_b: np.ndarray,
    *,
    omega: float,
    sigma_earth: float,
    image: ImageConvention = "additive",
) -> complex:
    """Integrate the σ-dependent magnetic Green function over a segment pair.

    Computes

    $$
    \\Delta Z^{(i,j)} \\;=\\; \\frac{j\\omega\\mu_0}{4\\pi}
    \\int_{C_i}\\!\\!\\int_{C_j}
    (\\hat{l}_i\\cdot\\hat{l}_j)\\,
    \\Delta G(\\vec{r}_i, \\vec{r}_j;\\,\\omega,\\sigma_e)\\,
    dl_i\\,dl_j,
    $$

    the earth-return correction of a homogeneous earth relative to the
    image convention ``image`` of the inductance matrix it is added to
    (see the module docstring). Used by
    :func:`build_sommerfeld_correction_matrix`.

    Parameters
    ----------
    p1_a, p2_a, p1_b, p2_b
        End points of the two segments in m ($z > 0$ in the soil).
    omega
        Angular frequency in rad/s.
    sigma_earth
        Earth conductivity in S/m.
    image
        ``"additive"`` (default, the historic ADR-0004 baseline),
        ``"none"`` or ``"antiparallel"``.

    Returns
    -------
    Z : complex
        Per-pair earth-return correction in $\\Omega$.
    """
    if omega <= 0.0 or sigma_earth <= 0.0:
        return 0.0 + 0.0j
    earth = LayeredEarth(rhos=(1.0 / sigma_earth,), thicknesses=())
    return sommerfeld_pair_integral_layered(
        p1_a, p2_a, p1_b, p2_b, omega=omega, earth=earth, image=image
    )

sommerfeld_pair_integral_layered

sommerfeld_pair_integral_layered(p1_a: ndarray, p2_a: ndarray, p1_b: ndarray, p2_b: ndarray, *, omega: float, earth: LayeredEarth, image: ImageConvention = 'additive') -> complex

Layered-earth analogue of sommerfeld_pair_integral_homogeneous().

Exact layered kernel for any number of layers (generalised reflection coefficients; transmitted amplitudes for pairs in different media). Segments that cross the soil surface or a layer interface are split there.

Parameters:

Name Type Description Default
p1_a ndarray

End points of the two segments in m.

required
p2_a ndarray

End points of the two segments in m.

required
p1_b ndarray

End points of the two segments in m.

required
p2_b ndarray

End points of the two segments in m.

required
omega float

Angular frequency in rad/s.

required
earth LayeredEarth

Layered-earth configuration.

required
image ImageConvention

Image convention of the inductance matrix the correction is added to ("additive" default, "none", "antiparallel"). With an image, a segment that crosses the soil surface raises ValueError (its image is singular).

'additive'

Returns:

Name Type Description
Z complex

Per-pair earth-return correction in \(\Omega\).

Source code in src/groundfield/coupling/sommerfeld_inductance.py
def sommerfeld_pair_integral_layered(
    p1_a: np.ndarray,
    p2_a: np.ndarray,
    p1_b: np.ndarray,
    p2_b: np.ndarray,
    *,
    omega: float,
    earth: LayeredEarth,
    image: ImageConvention = "additive",
) -> complex:
    """Layered-earth analogue of :func:`sommerfeld_pair_integral_homogeneous`.

    Exact layered kernel for any number of layers (generalised
    reflection coefficients; transmitted amplitudes for pairs in
    different media). Segments that cross the soil surface or a layer
    interface are split there.

    Parameters
    ----------
    p1_a, p2_a, p1_b, p2_b
        End points of the two segments in m.
    omega
        Angular frequency in rad/s.
    earth
        Layered-earth configuration.
    image
        Image convention of the inductance matrix the correction is
        added to (``"additive"`` default, ``"none"``,
        ``"antiparallel"``). With an image, a segment that crosses the
        soil surface raises ``ValueError`` (its image is singular).

    Returns
    -------
    Z : complex
        Per-pair earth-return correction in $\\Omega$.
    """
    mode = _resolve_image(image, None)
    if omega <= 0.0:
        return 0.0 + 0.0j
    m_img = 0.0
    if mode != "none":
        m_img = _pair_image_mutual(p1_a, p2_a, p1_b, p2_b, mode)
    p1_a, p2_a, p1_b, p2_b = (
        np.asarray(p, dtype=float) for p in (p1_a, p2_a, p1_b, p2_b)
    )
    sign = _same_segment(p1_a, p2_a, p1_b, p2_b)
    if sign != 0.0:
        # one segment twice: the one-dimensional self rule (user decision Q34)
        vals = sign * _pair_values_none(
            p1_a, p2_a, p1_a, p2_a, [omega], earth, same=True
        )
    else:
        vals = _pair_values_none(p1_a, p2_a, p1_b, p2_b, [omega], earth)
    return complex(_convert_image(vals, [omega], m_img, mode)[0])

Two-layer scalar Green's function (ADR-0007)

layered_green

Cross-layer scalar Green's function for layered soil (ADR-0007).

This module implements the electric (scalar-potential) Green's function for a 2-layer soil where source and observer can be in either layer. It complements the existing image-series solver in groundfield.solver.image_2layer (which assumes both points in the upper layer) and the Sommerfeld kernel in groundfield.solver.mom_sommerfeld (same restriction).

Mathematical background

For a 2-layer soil with upper-layer resistivity \(\rho_1\) and thickness \(h_1\), lower-layer resistivity \(\rho_2\) semi-infinite, the scalar Green's function for a unit point source at depth \(z_s\) observed at depth \(z\) takes the Hankel-transform form

\[ \varphi(s, z, z_s) \;=\; \int_0^{\infty}\! \Phi(\lambda, z, z_s)\,J_0(\lambda s)\,\lambda\,d\lambda, \]

where the spectral kernel \(\Phi(\lambda, z, z_s)\) is determined by the boundary-value problem

  • \(\partial\Phi/\partial z = 0\) at \(z = 0\) (free surface),
  • \(\Phi\) continuous at \(z = h_1\),
  • \(\sigma_k\,\partial\Phi/\partial z\) continuous at \(z = h_1\).

In each layer \(\Phi\) is a sum of \(e^{\pm\lambda z}\) plus a particular solution \(e^{-\lambda|z-z_s|}/(2\lambda\sigma_k)\) in the layer that contains the source. The four layer-pair cases — \(\Phi_{uu}, \Phi_{ul}, \Phi_{lu}, \Phi_{ll}\) — correspond to the four (source-layer, observer-layer) combinations and are related by reciprocity (\(\Phi_{ul} = \Phi_{lu}\)).

Implementation

The boundary-value system is solved once per \((\lambda, z_s)\) pair; in its stable form it has three unknowns, and since 2026.11 it is eliminated in closed form, vectorised over the \(\lambda\) nodes (one LAPACK solve per node before, half the time of a cross-layer solve). Per call the cost is then dominated by the \(J_0\) evaluation.

The implementation focuses on the 2-layer case (groundfield.soil.models.TwoLayerSoil); the n-layer extension follows the same recursion and is deferred to ADR-0007 Phase C.

Numerical strategy

The Hankel inversion is split into an analytic and a numerical part, because the two halves of \(\Phi\) behave completely differently in \(\lambda\):

  1. Primary term — the particular solution \(\rho_k/(2\lambda)\,e^{-\lambda|z-z_s|}\) in the layer that contains the source. It does not decay when \(|z - z_s| \to 0\), and its Hankel inverse is known exactly, \(\rho_k/(2R)\) with \(R = \sqrt{s^2 + (z-z_s)^2}\). It is therefore evaluated in closed form (_primary_term_real_space()). Integrating it numerically instead — as versions up to 0.14.1 did — truncates at \(\lambda_\text{max}\) and leaves an \(O((\lambda_\text{max}R)^{-1/2})\) residue that oscillates in \(s\) with period \(2\pi/\lambda_\text{max}\): up to 4.5 % on the total kernel, and non-monotone in lambda_max_factor.
  2. Reflected remainder — everything generated by the free surface and the interface. It is a superposition of image terms \(c_j/(2\lambda)\,e^{-\lambda d_j}\) (_image_generation() gives the exact coefficients and distances), so it decays like \(e^{-\lambda d_\text{img}}\) with \(d_\text{img} = \min_j d_j\) the smallest image distance — but only in proportion to that distance. Every image distance can degenerate to zero (\(z + z_s \to 0\) for a surface pair, \(|2h_1 - z - z_s| \to 0\) for a pair at the interface, \(z_l - z_u \to 0\) for a cross-layer pair straddling it), and then the remainder does not decay at all and truncating it is not safe. Versions up to 0.15.0.dev sized \(\lambda_\text{max}\) from \(\min(h_1, s + z + z_s)\), which has no relation to \(d_\text{img}\), and were consequently wrong by 0.7 % … 40 % on such pairs with no warning (review pass 9 re-audit). Since 0.15.0 the truncation is guaranteed: every image term with \(\lambda_\text{max} d_j < 30\) is subtracted from the spectral integrand and added back through its exact Hankel inverse \(c_j/(2\sqrt{s^2 + d_j^2})\) (_reflected_image_terms()), so the numerically integrated rest provably decays like \(e^{-\lambda d_\text{rest}}\) with \(\lambda_\text{max} d_\text{rest} \ge 30\) and the discarded tail is bounded by \(e^{-30} \approx 10^{-13}\). The rest goes through the split-grid quadrature (_hankel_lambda_grid()): logarithmic nodes below the first \(J_0\) oscillation, then one Gauss panel per oscillation period, with a documented resolution floor of eight nodes per period and a SommerfeldResolutionWarning when the allocation budget cannot meet it.

Because the tail bound above is analytic, \(\lambda_\text{max}\) no longer has to be large — it only has to be consistent with the set of subtracted image terms. That is what makes the cost of a remote pair bounded: the node count of the oscillation-resolved grid grows like \(\lambda_\text{max}\,s\), so the module caps \(\lambda_\text{max}\) at _HANKEL_PANEL_TARGET panels (scaled by lambda_max_factor / 200) and subtracts as many image terms as that cap requires (_plan_truncation()). A 4 km pair costs the same as a 90 m one, and lambda_max_factor becomes a genuine convergence knob: raising it moves work from the closed form into the quadrature and must not change the answer.

Because the numerically integrated rest is analytic in \(t = \ln(s + c)\) — and, after the image split above, has no scale shorter than \(d_\text{rest}\), which is what \(c\) is set to — reaction blocks with many distance pairs at one \((z, z_s)\) are evaluated on a range-sized log grid and cubic-spline interpolated instead of pair by pair (~1e-6 relative, worst case 3e-5; see two_layer_layered_correction_group()).

Limit checks (in the test suite)
  • \(\rho_2 = \rho_1\): all four pair kernels reduce to the homogeneous Green's function \(\rho/(4\pi r) + \rho/(4\pi r')\).
  • \(\rho_2 \to \infty\) (PEC bottom): for source in upper layer, \(G_{ul} \to 0\) (no penetration into the lower layer); \(G_{uu} \to G_{uu}^{K \to 1}\) — image structure with \(K \to 1\).
  • \(\rho_2 \to 0\) (sink): \(G_{uu} \to G_{uu}^{K \to -1}\), spreading resistance drops dramatically.
  • Source/observer in upper layer: bit-exact match to the Tagg/Sunde image series in groundfield.solver.image_2layer.solve_image_2layer().
References
  • Sunde, E. D. (1968). Earth Conduction Effects in Transmission Systems, Dover, Ch. 3.
  • Tagg, G. F. (1964). Earth Resistances, Newnes.
  • Wait, J. R. (1972). Electromagnetic Waves in Stratified Media, Pergamon.

SommerfeldResolutionWarning

Bases: UserWarning

The Sommerfeld quadrature could not resolve the \(J_0\) oscillations.

The linear region of the Hankel grid places one Gauss panel per \(J_0(\lambda s)\) period, so the node count grows like \(\lambda_\text{max}\,s\). A hard node budget (_HANKEL_MAX_LINEAR_NODES) bounds the transient allocation; when that budget forces fewer than _HANKEL_MIN_NODES_PER_OSCILLATION nodes per period the quadrature is no longer converged and this warning is raised instead of returning a silently wrong number (a coarse grid on an oscillatory integrand does not merely lose digits — it can flip the sign of the result).

The remedy is always to lower lambda_max_factor or to reduce the horizontal distance range of the group. Lowering the factor does not lose accuracy: the truncated tail is subtracted in closed form (_reflected_image_terms()), so a smaller \(\lambda_\text{max}\) only moves work from the quadrature into the exact image sum. Silence with warnings.simplefilter("ignore", SommerfeldResolutionWarning) only if the affected entries are known to be negligible.

SommerfeldTailTruncationWarning

Bases: UserWarning

The \(\lambda\)-truncated tail of the reflected kernel is not bounded.

Sibling of SommerfeldResolutionWarning: that one reports a grid too coarse to follow \(J_0(\lambda s)\), this one a grid too short to have integrated the reflected remainder.

The reflected part of \(\Phi\) is a superposition of image terms \(c_j/(2\lambda)\,e^{-\lambda d_j}\), so truncating the Hankel integral at \(\lambda_\text{max}\) discards \(\sum_j c_j/2 \int_{\lambda_\text{max}}^\infty e^{-\lambda d_j} J_0(\lambda s)\,d\lambda\), bounded by \(\sum_j |c_j| e^{-\lambda_\text{max} d_j}/(2 d_j)\). The bound is only small if \(\lambda_\text{max} d_j\) is large for every retained term, and \(d_j\) has nothing to do with the historic $\lambda_\text{max} = $ lambda_max_factor \(/\min(h_1, s + z + z_s)\): a pair at the air/soil surface (\(z + z_s \to 0\)), at the layer interface (\(|2h_1 - z - z_s| \to 0\)) or straddling it has \(d_j \to 0\) and a tail of order one. Review pass 9 measured −39.5 % on such a pair with no diagnostic; the failure grows as a mesh is refined towards the interface, which is what makes it release-blocking rather than cosmetic.

Every term with $\lambda_\text{max} d_j < $ _HANKEL_TAIL_DECAY_TARGET is therefore taken out of the quadrature and inverted in closed form. This warning fires when that could not be completed — in practice only when the term budget _HANKEL_IMAGE_TERM_BUDGET is exhausted, which needs a very thin top layer, \(|K| \to 1\) and a multi-kilometre span at once. The result is then not bounded by the documented tolerance: lower lambda_max_factor (fewer image terms are needed), reduce the distance range, or raise the budget.

layered_correction_group_plan

layered_correction_group_plan(z: float, z_s: float, *, rho_1: float, rho_2: float, h_1: float, rho_baseline: float | None = None, s_min: float, s_max: float, n_pairs: int, lambda_max_factor: float = 200.0, n_log: int = 32, n_lin: int = 96, min_distance: float | None = None, warn_stacklevel: int = 3) -> _CorrectionGroup | None

Plan of two_layer_layered_correction_group() for one depth group.

The λ-grid, the spectral amplitudes, the closed-form image split and the interpolation of a group depend on its depths, on the range [s_min, s_max] of its horizontal distances and on its size only. The returned callable evaluates the correction at any distances of the group and gives, piece by piece, the values of the one-shot call bit for bit (except the exact branch, see _SmoothContraction), so the cross-layer reaction matrix can be assembled in blocks of bounded memory (review pass 10, 10.56).

Parameters:

Name Type Description Default
z float required
z_s float required
rho_1 float required
rho_2 float required
h_1 float required
rho_baseline float required
lambda_max_factor float required
n_log float required
n_lin float required
min_distance float required
s_min float

Smallest and largest horizontal distance of the group in m.

required
s_max float

Smallest and largest horizontal distance of the group in m.

required
n_pairs int

Number of distance pairs of the group.

required
warn_stacklevel int

Frames between the warning calls and the caller of this function's caller (3: warnings point at the code that calls this function).

3

Returns:

Type Description
callable or None

group(s_values) -> correction (same shape as s_values), or None where the correction vanishes identically (equal resistivities and a matching baseline).

Source code in src/groundfield/coupling/layered_green.py
def layered_correction_group_plan(
    z: float,
    z_s: float,
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
    rho_baseline: float | None = None,
    s_min: float,
    s_max: float,
    n_pairs: int,
    lambda_max_factor: float = 200.0,
    n_log: int = 32,
    n_lin: int = 96,
    min_distance: float | None = None,
    warn_stacklevel: int = 3,
) -> _CorrectionGroup | None:
    """Plan of :func:`two_layer_layered_correction_group` for one depth group.

    The λ-grid, the spectral amplitudes, the closed-form image split and the
    interpolation of a group depend on its depths, on the range
    ``[s_min, s_max]`` of its horizontal distances and on its size only. The
    returned callable evaluates the correction at any distances of the group
    and gives, piece by piece, the values of the one-shot call bit for bit
    (except the exact branch, see :class:`_SmoothContraction`), so the
    cross-layer reaction matrix can be assembled in blocks of bounded memory
    (review pass 10, 10.56).

    Parameters
    ----------
    z, z_s, rho_1, rho_2, h_1, rho_baseline, lambda_max_factor, n_log, n_lin, min_distance
        As in :func:`two_layer_layered_correction_group`.
    s_min, s_max
        Smallest and largest horizontal distance of the group in m.
    n_pairs
        Number of distance pairs of the group.
    warn_stacklevel
        Frames between the warning calls and the caller of this function's
        caller (3: warnings point at the code that calls this function).

    Returns
    -------
    callable or None
        ``group(s_values) -> correction`` (same shape as ``s_values``), or
        ``None`` where the correction vanishes identically (equal
        resistivities and a matching baseline).
    """
    if rho_baseline is None:
        rho_baseline = rho_1
    _validate_depths(z, z_s)
    if abs(rho_2 - rho_1) < 1e-12 * max(rho_1, 1.0) and abs(
        rho_baseline - rho_1
    ) < 1e-12 * max(rho_1, 1.0):
        return None
    return _CorrectionGroup(
        z,
        z_s,
        rho_1=rho_1,
        rho_2=rho_2,
        h_1=h_1,
        rho_baseline=rho_baseline,
        s_min=s_min,
        s_max=s_max,
        n_pairs=n_pairs,
        lambda_max_factor=lambda_max_factor,
        n_log=n_log,
        n_lin=n_lin,
        min_distance=min_distance,
        warn_stacklevel=warn_stacklevel + 1,
    )

two_layer_layered_correction_group

two_layer_layered_correction_group(s_values: ndarray, z: float, z_s: float, *, rho_1: float, rho_2: float, h_1: float, rho_baseline: float | None = None, lambda_max_factor: float = 200.0, n_log: int = 32, n_lin: int = 96, min_distance: float | None = None) -> np.ndarray

Vectorised form of two_layer_layered_correction_real_space().

Evaluates the layered correction for many horizontal distances at one (z, z_s) pair with a single spectral-amplitude solve: the amplitudes depend on (λ, z, z_s) only, so the per-pair cost of the historic scalar loop (one BVP solve per matrix entry — the dominant cost of the ADR-0007 cross-layer reaction-matrix assembly after the WP-B1 oscillation-resolved grids) collapses to one BVP solve per (z, z_s) group plus a J0 contraction.

The shared λ-grid is built for the most demanding radius of the group: the lambda_max_factor bound and the \(1/R\) regularisation from the smallest s (near-field content), oscillation resolution, log-region cap and panel-cost budget from the largest (_plan_truncation()).

Accuracy (review pass 9, finding F15)

Groups above _HANKEL_INTERP_THRESHOLD pairs are sampled on a log-spaced s-grid and interpolated. Three changes make that branch agree with the exact per-pair contraction to ~1e-6 relative (worst case measured 1.1e-5, over ten geometries and every group size from 60 to 129 pairs; previously up to 1 % for a 400 m span and 17 % when rho_baseline did not match the source layer):

  1. the residual primary term \((\rho_\text{src} - \rho_\text{baseline})/(2\lambda)\, e^{-\lambda|z-z_s|}\) — which is not zero unless the caller matches rho_baseline to the source layer, and which carries a \(1/R\) singularity plus a \(2\pi/\lambda_\text{max}\)-periodic truncation ripple in s — is taken out of the quadrature and added back in closed form, leaving a genuinely analytic integrand;
  2. the node count is sized from the actual dynamic range of the group and the interpolant is a cubic spline, so the accuracy no longer depends on the network extent;
  3. every reflected image term short enough for the λ-truncation to matter gets the same treatment as the primary term — closed form, per pair, outside the interpolation (_reflected_image_terms()). This is what removes the 0.7 % … 40 % errors of surface, interface and interface-straddling pairs, and it also smooths what remains: the interpolated function then has no length scale shorter than d_rest, which is what the log-coordinate offset is set to.

Because interpolation is skipped whenever it would need at least as many nodes as the group has pairs, the exact and the interpolated branch also no longer differ observably at the threshold (the historic ~3 % jump between a 64-pair and a 65-pair block is gone; worst deviation over every size from 60 to 129 pairs is 1.1e-5).

Parameters:

Name Type Description Default
s_values ndarray

Horizontal distances in m (any shape, >= 0).

required
z float

Observer / source depth in m (>= 0, positive into the soil).

required
z_s float

Observer / source depth in m (>= 0, positive into the soil).

required
rho_1 float

Resistivities of the upper / lower layer in Ω·m.

required
rho_2 float

Resistivities of the upper / lower layer in Ω·m.

required
h_1 float

Upper-layer thickness in m.

required
rho_baseline float | None

Resistivity of the subtracted homogeneous half-space in Ω·m; None (default) takes rho_1. Solvers pass the resistivity of the source layer (ADR-0007 §"Phase A.1").

None
lambda_max_factor float

Quadrature controls as in two_layer_layered_correction_real_space().

200.0
n_log float

Quadrature controls as in two_layer_layered_correction_real_space().

200.0
n_lin float

Quadrature controls as in two_layer_layered_correction_real_space().

200.0
min_distance float | None

Regularisation length of the closed-form \(1/R\) terms in m, as in two_layer_real_space_kernel(): the clamp becomes \(\min(1/\lambda_\text{clamp},\) min_distance \()\). The solver passes the 1 mm of its own point forms, so the exchange of a point value for a line integral stays consistent for pairs closer than \(h_1/200\) (audit A3S-01). None (default) keeps the clamp.

None

Returns:

Type Description
ndarray

The correction, same shape as s_values; divided by \(2\pi\) it is the potential in V per A.

Source code in src/groundfield/coupling/layered_green.py
def two_layer_layered_correction_group(
    s_values: np.ndarray,
    z: float,
    z_s: float,
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
    rho_baseline: float | None = None,
    lambda_max_factor: float = 200.0,
    n_log: int = 32,
    n_lin: int = 96,
    min_distance: float | None = None,
) -> np.ndarray:
    """Vectorised form of :func:`two_layer_layered_correction_real_space`.

    Evaluates the layered correction for **many horizontal distances
    at one (z, z_s) pair** with a single spectral-amplitude solve:
    the amplitudes depend on (λ, z, z_s) only, so the per-pair cost
    of the historic scalar loop (one BVP solve per matrix entry —
    the dominant cost of the ADR-0007 cross-layer reaction-matrix
    assembly after the WP-B1 oscillation-resolved grids) collapses
    to one BVP solve per (z, z_s) group plus a ``J0`` contraction.

    The shared λ-grid is built for the most demanding radius of the
    group: the ``lambda_max_factor`` bound and the $1/R$ regularisation
    from the smallest ``s`` (near-field content), oscillation
    resolution, log-region cap and panel-cost budget from the largest
    (:func:`_plan_truncation`).

    Accuracy (review pass 9, finding F15)
    -------------------------------------
    Groups above :data:`_HANKEL_INTERP_THRESHOLD` pairs are sampled on
    a log-spaced ``s``-grid and interpolated. Three changes make that
    branch agree with the exact per-pair contraction to ~1e-6 relative
    (worst case measured 1.1e-5, over ten geometries and every group
    size from 60 to 129 pairs; previously up to 1 % for a 400 m span
    and 17 % when ``rho_baseline`` did not match the source layer):

    1. the residual primary term
       $(\\rho_\\text{src} - \\rho_\\text{baseline})/(2\\lambda)\\,
       e^{-\\lambda|z-z_s|}$ — which is *not* zero unless the caller
       matches ``rho_baseline`` to the source layer, and which carries a
       $1/R$ singularity plus a $2\\pi/\\lambda_\\text{max}$-periodic
       truncation ripple in ``s`` — is taken out of the quadrature and
       added back in closed form, leaving a genuinely analytic
       integrand;
    2. the node count is sized from the actual dynamic range of the
       group and the interpolant is a cubic spline, so the accuracy no
       longer depends on the network extent;
    3. every reflected image term short enough for the λ-truncation to
       matter gets the same treatment as the primary term — closed form,
       per pair, outside the interpolation
       (:func:`_reflected_image_terms`). This is what removes the
       0.7 % … 40 % errors of surface, interface and interface-straddling
       pairs, and it also *smooths* what remains: the interpolated
       function then has no length scale shorter than ``d_rest``, which
       is what the log-coordinate offset is set to.

    Because interpolation is skipped whenever it would need at least as
    many nodes as the group has pairs, the exact and the interpolated
    branch also no longer differ observably at the threshold (the
    historic ~3 % jump between a 64-pair and a 65-pair block is gone;
    worst deviation over every size from 60 to 129 pairs is 1.1e-5).

    Parameters
    ----------
    s_values
        Horizontal distances in m (any shape, ``>= 0``).
    z, z_s
        Observer / source depth in m (``>= 0``, positive into the soil).
    rho_1, rho_2
        Resistivities of the upper / lower layer in Ω·m.
    h_1
        Upper-layer thickness in m.
    rho_baseline
        Resistivity of the subtracted homogeneous half-space in Ω·m;
        ``None`` (default) takes ``rho_1``. Solvers pass the resistivity
        of the source layer (ADR-0007 §"Phase A.1").
    lambda_max_factor, n_log, n_lin
        Quadrature controls as in
        :func:`two_layer_layered_correction_real_space`.
    min_distance
        Regularisation length of the closed-form $1/R$ terms in m, as in
        :func:`two_layer_real_space_kernel`: the clamp becomes
        $\\min(1/\\lambda_\\text{clamp},$ ``min_distance`` $)$. The solver
        passes the 1 mm of its own point forms, so the exchange of a point
        value for a line integral stays consistent for pairs closer than
        $h_1/200$ (audit A3S-01). ``None`` (default) keeps the clamp.

    Returns
    -------
    np.ndarray
        The correction, same shape as ``s_values``; divided by
        :math:`2\\pi` it is the potential in V per A.
    """
    s_values = np.asarray(s_values, dtype=float)
    group = layered_correction_group_plan(
        z,
        z_s,
        rho_1=rho_1,
        rho_2=rho_2,
        h_1=h_1,
        rho_baseline=rho_baseline,
        s_min=float(s_values.min()) if s_values.size else 0.0,
        s_max=float(s_values.max()) if s_values.size else 0.0,
        n_pairs=int(s_values.size),
        lambda_max_factor=lambda_max_factor,
        n_log=n_log,
        n_lin=n_lin,
        min_distance=min_distance,
        warn_stacklevel=4,
    )
    if group is None:
        return np.zeros(s_values.shape, dtype=float)
    return group(s_values)

two_layer_layered_correction_real_space

two_layer_layered_correction_real_space(s: float, z: float, z_s: float, *, rho_1: float, rho_2: float, h_1: float, rho_baseline: float | None = None, lambda_max_factor: float = 200.0, n_log: int = 32, n_lin: int = 96, min_distance: float | None = None) -> float

Real-space layered correction over the homogeneous-rho_1 baseline.

Computes $$ \Delta G(s, z, z_s) \;=\; G_{\text{2-layer}}(s, z, z_s; \rho_1, \rho_2, h_1) \;-\; G_{\text{homog}}(s, z, z_s; \rho_1) $$ by subtracting the spectral kernels before the Hankel integration. The singular source term \(\rho_1/(2\lambda)\,e^{-\lambda|z-z_s|}\) is identical in both spectral kernels and cancels exactly, leaving a smooth, exponentially decaying integrand. Two big advantages:

  1. In the homogeneous limit \(\rho_2 = \rho_1\) the spectral difference is identically zero at every \(\lambda\), so the integrator returns 0 to machine precision (no spurious diagonal contribution from finite-Sommerfeld-quadrature error at \(z = z_s\)).
  2. The kernel difference \((a_1 - a_1^{\text{hom}})e^{\lambda z} + (b_1 - b_1^{\text{hom}})e^{-\lambda z}\) has no \(1/(2\lambda)\) piece, so the small-\(\lambda\) region is finite and easy to integrate.

The caller adds this correction on top of the homogeneous potential computed with the existing groundfield.solver.image._self_corrected_kernel() (which correctly handles the line-self diagonal).

The optional rho_baseline parameter selects which homog soil to subtract:

  • None (default): subtract homog with \(\rho_1\). Suitable when the calling solver builds \(\phi_\text{hom}\) uniformly with \(\rho_1\).
  • explicit float: subtract homog with the given resistivity. Use rho_2 for source segments in the lower layer when the calling solver matches its \(\phi_\text{hom}\) baseline to the source layer (recommended for production-grade solver, ADR-0007 §"Phase A.1").

Returns 0 in the homogeneous limit by construction; otherwise a finite real value with the same units as two_layer_real_space_kernel().

Parameters:

Name Type Description Default
s float

Horizontal distance in m (>= 0).

required
z float

Observer / source depth in m (>= 0, positive into the soil).

required
z_s float

Observer / source depth in m (>= 0, positive into the soil).

required
rho_1 float

Resistivities of the upper / lower layer in Ω·m.

required
rho_2 float

Resistivities of the upper / lower layer in Ω·m.

required
h_1 float

Upper-layer thickness in m.

required
rho_baseline float | None

Resistivity of the subtracted homogeneous half-space in Ω·m (see above).

None
lambda_max_factor float

Upper bound on the quadrature truncation and default regularisation wavenumber, as in two_layer_real_space_kernel().

200.0
n_log int

Number of nodes in the logarithmic / linear part of the quadrature grid.

32
n_lin int

Number of nodes in the logarithmic / linear part of the quadrature grid.

32
min_distance float | None

Regularisation length of the closed-form \(1/R\) terms in m: the clamp becomes \(\min(1/\lambda_\text{clamp},\) min_distance \()\). A solver evaluating the reaction-matrix diagonal at the wire radius (\(s = a\)) passes a, so the interface image of a segment that touches the interface keeps its value \(1/\sqrt{a^2 + d^2}\) instead of the 25 mm clamp of \(h_1 = 5\) m (audit A3S-01). None (default) keeps the clamp; values at \(R \ge 1/\lambda_\text{clamp}\) do not depend on it.

None

Returns:

Name Type Description
dG float

Layered correction \(\Delta G\) in the units of two_layer_real_space_kernel() (V/A for a unit current); exactly 0.0 in the homogeneous limit.

Raises:

Type Description
ValueError

If z or z_s is negative or not finite (outside the homogeneous limit, which returns 0.0 first).

Source code in src/groundfield/coupling/layered_green.py
def two_layer_layered_correction_real_space(
    s: float,
    z: float,
    z_s: float,
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
    rho_baseline: float | None = None,
    lambda_max_factor: float = 200.0,
    n_log: int = 32,
    n_lin: int = 96,
    min_distance: float | None = None,
) -> float:
    """Real-space layered *correction* over the homogeneous-rho_1 baseline.

    Computes
    $$
    \\Delta G(s, z, z_s) \\;=\\;
        G_{\\text{2-layer}}(s, z, z_s; \\rho_1, \\rho_2, h_1)
        \\;-\\; G_{\\text{homog}}(s, z, z_s; \\rho_1)
    $$
    by subtracting the spectral kernels **before** the Hankel
    integration. The singular source term
    $\\rho_1/(2\\lambda)\\,e^{-\\lambda|z-z_s|}$ is identical in
    both spectral kernels and **cancels exactly**, leaving a
    smooth, exponentially decaying integrand. Two big advantages:

    1. In the homogeneous limit $\\rho_2 = \\rho_1$ the spectral
       difference is *identically zero* at every $\\lambda$, so the
       integrator returns 0 to machine precision (no spurious
       diagonal contribution from finite-Sommerfeld-quadrature
       error at $z = z_s$).
    2. The kernel difference
       $(a_1 - a_1^{\\text{hom}})e^{\\lambda z} + (b_1 - b_1^{\\text{hom}})e^{-\\lambda z}$
       has no $1/(2\\lambda)$ piece, so the small-$\\lambda$ region is
       finite and easy to integrate.

    The caller adds this correction on top of the homogeneous
    potential computed with the existing
    :func:`groundfield.solver.image._self_corrected_kernel` (which
    correctly handles the line-self diagonal).

    The optional ``rho_baseline`` parameter selects which homog
    soil to subtract:

    - ``None`` (default): subtract homog with $\\rho_1$. Suitable
      when the calling solver builds $\\phi_\\text{hom}$ uniformly
      with $\\rho_1$.
    - explicit float: subtract homog with the given resistivity.
      Use ``rho_2`` for source segments in the lower layer when
      the calling solver matches its $\\phi_\\text{hom}$ baseline
      to the source layer (recommended for production-grade solver,
      ADR-0007 §"Phase A.1").

    Returns 0 in the homogeneous limit by construction; otherwise
    a finite real value with the same units as
    :func:`two_layer_real_space_kernel`.

    Parameters
    ----------
    s
        Horizontal distance in m (``>= 0``).
    z, z_s
        Observer / source depth in m (``>= 0``, positive into the soil).
    rho_1, rho_2
        Resistivities of the upper / lower layer in Ω·m.
    h_1
        Upper-layer thickness in m.
    rho_baseline
        Resistivity of the subtracted homogeneous half-space in Ω·m (see
        above).
    lambda_max_factor
        Upper bound on the quadrature truncation and default
        regularisation wavenumber, as in
        :func:`two_layer_real_space_kernel`.
    n_log, n_lin
        Number of nodes in the logarithmic / linear part of the
        quadrature grid.
    min_distance
        Regularisation length of the closed-form $1/R$ terms in m: the
        clamp becomes $\\min(1/\\lambda_\\text{clamp},$ ``min_distance``
        $)$. A solver evaluating the reaction-matrix diagonal at the wire
        radius ($s = a$) passes ``a``, so the interface image of a segment
        that touches the interface keeps its value $1/\\sqrt{a^2 + d^2}$
        instead of the 25 mm clamp of $h_1 = 5$ m (audit A3S-01).
        ``None`` (default) keeps the clamp; values at
        $R \\ge 1/\\lambda_\\text{clamp}$ do not depend on it.

    Returns
    -------
    dG : float
        Layered correction $\\Delta G$ in the units of
        :func:`two_layer_real_space_kernel` (V/A for a unit current);
        exactly 0.0 in the homogeneous limit.

    Raises
    ------
    ValueError
        If ``z`` or ``z_s`` is negative or not finite (outside the
        homogeneous limit, which returns 0.0 first).
    """
    if rho_baseline is None:
        rho_baseline = rho_1
    if abs(rho_2 - rho_1) < 1e-12 * max(rho_1, 1.0) and abs(
        rho_baseline - rho_1
    ) < 1e-12 * max(rho_1, 1.0):
        return 0.0

    _validate_depths(z, z_s)
    plan = _plan_truncation(
        z=z,
        z_s=z_s,
        rho_1=rho_1,
        rho_2=rho_2,
        h_1=h_1,
        rho_baseline=rho_baseline,
        s_near=s,
        s_far=s,
        lambda_max_factor=lambda_max_factor,
        warn_stacklevel=3,
    )
    lambdas, weights = _hankel_lambda_grid(
        lambda_max=plan.lambda_max,
        char_length=plan.char_length,
        s=s,
        n_log=n_log,
        n_lin=n_lin,
        warn_stacklevel=3,
    )

    # Layered amplitudes
    A, B, _, C = _spectral_amplitudes(
        lambdas,
        z_s,
        rho_1,
        rho_2,
        h_1,
    )
    # Baseline (homog) amplitudes — both layers at rho_baseline.
    A_h, B_h, _, C_h = _spectral_amplitudes(
        lambdas,
        z_s,
        rho_baseline,
        rho_baseline,
        h_1,
    )

    # Evaluate the *reflected* Phi for both and subtract. When the
    # source is in the same layer as the baseline-rho region, the
    # singular particular term cancels identically and the residual is
    # bounded. When the baseline differs from rho_at_source (e.g.,
    # rho_baseline=rho_2 with source in upper at z_s<h_1, where the
    # layered Phi has rho_1/(2λ)·exp() but the baseline-homog Phi has
    # rho_2/(2λ)·exp()), the residual carries a
    # (rho_at_source - rho_baseline)/(2R) divergence. That piece is
    # handled in closed form below rather than by quadrature — it is
    # the only non-decaying part of the spectral difference, so leaving
    # it in the integral produced an O((λ_max·R)^{-1/2}) ripple in s.
    # Callers should still select rho_baseline = rho at the source
    # layer (ADR-0007 §"Phase A.1"), which makes the term vanish.
    Phi_lay = _phi_from_stable_amplitudes(
        lambdas,
        A,
        B,
        C,
        z,
        z_s,
        rho_1,
        rho_2,
        h_1,
        include_primary=False,
    )
    Phi_hom = _phi_from_stable_amplitudes(
        lambdas,
        A_h,
        B_h,
        C_h,
        z,
        z_s,
        rho_baseline,
        rho_baseline,
        h_1,
        include_primary=False,
    )
    delta_Phi = (
        Phi_lay
        - Phi_hom
        - _image_spectral_sum(
            lambdas,
            plan.coeffs,
            plan.dists,
        )
    )

    integrand = delta_Phi * j0(lambdas * s) * lambdas
    total = float(np.sum(weights * integrand))
    lambda_clamp = _regularisation_wavenumber(plan.lambda_clamp, min_distance)
    total += float(_image_real_space_sum(plan.coeffs, plan.dists, s, lambda_clamp))

    d_rho = _primary_rho(z, z_s, rho_1, rho_2, h_1) - _primary_rho(
        z,
        z_s,
        rho_baseline,
        rho_baseline,
        h_1,
    )
    if d_rho == 0.0:
        return total
    return total + float(_primary_term_real_space(d_rho, s, z - z_s, lambda_clamp))

two_layer_probe_matrix

two_layer_probe_matrix(probe_points: ndarray, source_points: ndarray, *, rho_1: float, rho_2: float, h_1: float, min_distance: float = 0.001, lambda_max_factor: float = 200.0) -> np.ndarray

Potential matrix phi = G @ I for arbitrary layer combinations.

Returns the (M, N) matrix with G[m, n] = potential at probe_points[m] per unit current injected at source_points[n], evaluated with the full two-layer spectral kernel (two_layer_real_space_kernel()). Valid for every probe/source layer combination — upper–upper, cross-layer and lower–lower — unlike the Tagg/Sunde uu image series that the fast paths use (audit 2026-07-08, WP-D1: the uu series applied to layer-2 points was measured +7 % at z = 7 m and +25 % at z = 12 m for K = +0.818, h_1 = 5 m).

Cost: one spectral-amplitude solve per (z, z_s) depth group plus a J0 contraction (see "Cost control" below) — reserve for the sub-blocks that the uu series cannot handle.

Parameters:

Name Type Description Default
probe_points ndarray

Observation points, shape (M, 3), in m (z >= 0, positive into the soil).

required
source_points ndarray

Point-source positions, shape (N, 3), in m (z >= 0).

required
rho_1 float

Resistivities of the upper / lower layer in Ω·m.

required
rho_2 float

Resistivities of the upper / lower layer in Ω·m.

required
h_1 float

Upper-layer thickness in m.

required
min_distance float

Regularisation length of the near-singular pairs in m (see Notes).

1e-3
lambda_max_factor float

Upper bound on the quadrature truncation and regularisation wavenumber, as in two_layer_real_space_kernel().

200.0

Returns:

Name Type Description
G ndarray

Real (M, N) matrix of potentials per unit injected current, in V/A (Ω).

Raises:

Type Description
ValueError

If a probe or source point lies above the soil surface (z < 0) or has a non-finite depth.

Notes

The near-singularity is regularised like the image-series paths: the horizontal distance is clamped at min_distance whenever the vertical separation is below min_distance as well, and the closed-form \(1/R\) terms are clamped at no more than min_distance (they were clamped at \(h_1/200\), 25 mm for \(h_1 = 5\) m, up to this release; audit A3S-01).

Cost control: probe/source pairs are grouped by their (z, z_s) depth combination (rounded to 1 µm). Within a group the primary \(1/R\) field is evaluated in closed form at every pair, and the reflected remainder — analytic in \(t = \ln(s + c)\) — is what the interpolation sees. Groups larger than _HANKEL_INTERP_THRESHOLD pairs are sampled on a log-spaced s-grid whose node count is derived from the group's dynamic range (_interp_node_count()) and interpolated with a cubic spline, keeping surface-grid evaluations tractable.

Accuracy (review pass 9, finding F15)

The historic fixed 48-node linear interpolation of the total kernel was documented at "relative error ≲ 1e-4" but measured 2.1e-3, because (a) the node count ignored the dynamic range of s and (b) the total kernel contains the \(1/R\) primary term whose λ-truncated quadrature ripples in s with period \(2\pi/\lambda_\text{max}\) — a ripple no coarse interpolant can follow. With the primary term and the degenerate image terms in closed form and range-sized cubic nodes, the interpolated and the exact per-pair branch agree to 8e-7 relative (measured over surface, equal-depth-in-layer-2 and cross-layer probe/source combinations, 400 probes over a 90 m square), i.e. the documented 1e-4 holds with two orders of margin — not the "four orders" and "~1e-8" that stood here at 0.15.0.dev, which were 2–3 orders optimistic and contradicted both the module header and docs/api/coupling.md.

Source code in src/groundfield/coupling/layered_green.py
def two_layer_probe_matrix(
    probe_points: np.ndarray,  # (M, 3)
    source_points: np.ndarray,  # (N, 3)
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
    min_distance: float = 1e-3,
    lambda_max_factor: float = 200.0,
) -> np.ndarray:
    """Potential matrix ``phi = G @ I`` for arbitrary layer combinations.

    Returns the ``(M, N)`` matrix with ``G[m, n]`` = potential at
    ``probe_points[m]`` per unit current injected at
    ``source_points[n]``, evaluated with the full two-layer spectral
    kernel (:func:`two_layer_real_space_kernel`). Valid for **every**
    probe/source layer combination — upper–upper, cross-layer and
    lower–lower — unlike the Tagg/Sunde uu image series that the
    fast paths use (audit 2026-07-08, WP-D1: the uu series applied to
    layer-2 points was measured +7 % at z = 7 m and +25 % at z = 12 m
    for K = +0.818, h_1 = 5 m).

    Cost: one spectral-amplitude solve per (z, z_s) depth group plus a
    ``J0`` contraction (see "Cost control" below) — reserve for the
    sub-blocks that the uu series cannot handle.

    Parameters
    ----------
    probe_points : numpy.ndarray
        Observation points, shape ``(M, 3)``, in m (``z >= 0``, positive
        into the soil).
    source_points : numpy.ndarray
        Point-source positions, shape ``(N, 3)``, in m (``z >= 0``).
    rho_1, rho_2 : float
        Resistivities of the upper / lower layer in Ω·m.
    h_1 : float
        Upper-layer thickness in m.
    min_distance : float, default 1e-3
        Regularisation length of the near-singular pairs in m (see
        Notes).
    lambda_max_factor : float, default 200.0
        Upper bound on the quadrature truncation and regularisation
        wavenumber, as in :func:`two_layer_real_space_kernel`.

    Returns
    -------
    G : numpy.ndarray
        Real ``(M, N)`` matrix of potentials per unit injected current,
        in V/A (Ω).

    Raises
    ------
    ValueError
        If a probe or source point lies above the soil surface
        (``z < 0``) or has a non-finite depth.

    Notes
    -----
    The near-singularity is regularised like the image-series paths:
    the horizontal distance is clamped at ``min_distance`` whenever
    the vertical separation is below ``min_distance`` as well, and the
    closed-form $1/R$ terms are clamped at no more than ``min_distance``
    (they were clamped at $h_1/200$, 25 mm for $h_1 = 5$ m, up to this
    release; audit A3S-01).

    Cost control: probe/source pairs are grouped by their (z, z_s)
    depth combination (rounded to 1 µm). Within a group the primary
    $1/R$ field is evaluated in closed form at every pair, and the
    *reflected* remainder — analytic in $t = \\ln(s + c)$ — is what the
    interpolation sees. Groups larger than
    :data:`_HANKEL_INTERP_THRESHOLD` pairs are sampled on a log-spaced
    ``s``-grid whose node count is derived from the group's dynamic
    range (:func:`_interp_node_count`) and interpolated with a cubic
    spline, keeping surface-grid evaluations tractable.

    Accuracy (review pass 9, finding F15)
    -------------------------------------
    The historic fixed 48-node linear interpolation of the *total*
    kernel was documented at "relative error ≲ 1e-4" but measured
    2.1e-3, because (a) the node count ignored the dynamic range of
    ``s`` and (b) the total kernel contains the $1/R$ primary term
    whose λ-truncated quadrature ripples in ``s`` with period
    $2\\pi/\\lambda_\\text{max}$ — a ripple no coarse interpolant can
    follow. With the primary term and the degenerate image terms in
    closed form and range-sized cubic nodes, the interpolated and the
    exact per-pair branch agree to **8e-7** relative (measured over
    surface, equal-depth-in-layer-2 and cross-layer probe/source
    combinations, 400 probes over a 90 m square), i.e. the documented
    1e-4 holds with two orders of margin — not the "four orders" and
    "~1e-8" that stood here at 0.15.0.dev, which were 2–3 orders
    optimistic and contradicted both the module header and
    ``docs/api/coupling.md``.
    """
    M = probe_points.shape[0]
    N = source_points.shape[0]
    if M and N:
        _validate_depths(
            float(np.min(probe_points[:, 2])),
            float(np.min(source_points[:, 2])),
            labels=("min(probe_points[:, 2])", "min(source_points[:, 2])"),
        )
    G = np.zeros((M, N), dtype=float)

    def _group_values(
        s_flat: np.ndarray,
        zm: float,
        zn: float,
    ) -> np.ndarray:
        """Vectorised kernel over many s at one (z, z_s) pair.

        The spectral amplitudes depend on (λ-grid, z, z_s) only, so
        they are solved **once per group** on a shared λ-grid built
        for the most demanding radius (λ_max from the smallest s,
        oscillation resolution and log-region cap from the largest);
        all s-values then reduce to one ``J0``-matrix contraction of
        the reflected part plus a closed-form primary term.
        """
        plan = _plan_truncation(
            z=zm,
            z_s=zn,
            rho_1=rho_1,
            rho_2=rho_2,
            h_1=h_1,
            rho_baseline=None,
            s_near=float(s_flat.min()),
            s_far=float(s_flat.max()),
            lambda_max_factor=lambda_max_factor,
            # 4 frames: _plan_truncation -> _group_values ->
            # two_layer_probe_matrix -> user.
            warn_stacklevel=4,
        )
        lambdas, weights = _hankel_lambda_grid(
            lambda_max=plan.lambda_max,
            char_length=plan.char_length,
            s=float(s_flat.max()),
            n_log=32,
            n_lin=96,
            warn_stacklevel=4,
        )
        A, B, _, C = _spectral_amplitudes(lambdas, zn, rho_1, rho_2, h_1)
        Phi_refl = _phi_from_stable_amplitudes(
            lambdas,
            A,
            B,
            C,
            zm,
            zn,
            rho_1,
            rho_2,
            h_1,
            include_primary=False,
        ) - _image_spectral_sum(lambdas, plan.coeffs, plan.dists)
        w_phi = Phi_refl * weights * lambdas
        c = _log_grid_offset(
            zm,
            zn,
            h_1,
            floor=min_distance,
            d_rest=plan.d_rest,
        )
        vals = _hankel_contract_smooth(lambdas, s_flat, w_phi, c=c)
        # The closed-form 1/R terms are regularised at ``min_distance``
        # like the image-series paths, not at the h_1/200 of the
        # truncation plan (audit A3S-01); ``min_distance = 0`` keeps it.
        lambda_clamp = _regularisation_wavenumber(
            plan.lambda_clamp, min_distance if min_distance > 0.0 else None
        )
        vals = vals + _image_real_space_sum(
            plan.coeffs,
            plan.dists,
            s_flat,
            lambda_clamp,
        )
        rho_primary = _primary_rho(zm, zn, rho_1, rho_2, h_1)
        if rho_primary == 0.0:
            return vals
        return vals + _primary_term_real_space(
            rho_primary,
            s_flat,
            zm - zn,
            lambda_clamp,
        )

    # Group by the (z, z_s) pair — the kernel then depends on s only.
    z_keys = np.round(probe_points[:, 2] / 1e-6).astype(np.int64)
    zs_keys = np.round(source_points[:, 2] / 1e-6).astype(np.int64)
    for zk in np.unique(z_keys):
        rows = np.where(z_keys == zk)[0]
        zm = float(probe_points[rows[0], 2])
        for zsk in np.unique(zs_keys):
            cols = np.where(zs_keys == zsk)[0]
            zn = float(source_points[cols[0], 2])
            dxy = probe_points[rows][:, None, 0:2] - source_points[cols][None, :, 0:2]
            s_grid = np.sqrt(np.einsum("mnk,mnk->mn", dxy, dxy))
            if abs(zm - zn) < min_distance:
                np.maximum(s_grid, min_distance, out=s_grid)
            vals = _group_values(s_grid.ravel(), zm, zn)
            G[np.ix_(rows, cols)] = vals.reshape(s_grid.shape)
    # Physical prefactor: phi = G_phys / (2π) per unit current (the
    # spectral kernel carries the rho/2 convention — see
    # solver/mom_sommerfeld.py for the bookkeeping).
    return G / (2.0 * math.pi)

two_layer_real_space_kernel

two_layer_real_space_kernel(s: float, z: float, z_s: float, *, rho_1: float, rho_2: float, h_1: float, lambda_max_factor: float = 200.0, n_log: int = 32, n_lin: int = 96, min_distance: float | None = None) -> float

Cross-layer real-space scalar Green's function \(\varphi(s, z, z_s)\).

Computes \(\varphi(s, z, z_s) / I = \int_0^\infty \Phi(\lambda, z, z_s)\,J_0(\lambda s)\,\lambda\,d\lambda\) for a unit point source at \((0, 0, z_s)\) observed at \((s, 0, z)\). The result already includes the \(1/(4\pi)\)-style prefactor that is conventional in the existing mom_sommerfeld kernel representation.

Numerical strategy: the primary (source-layer particular) term is evaluated in closed form as \(\rho_k/(2R)\) with \(R = \sqrt{s^2 + (z-z_s)^2}\) (_primary_term_real_space()), and so is every reflected image term whose distance is too short for the truncation at \(\lambda_\text{max}\) to be negligible (_reflected_image_terms(), _plan_truncation()); only the provably fast-decaying rest goes through the split-grid Sommerfeld quadrature (logarithmic for small \(\lambda\), oscillation-resolved for large \(\lambda\)) consistent with groundfield.coupling.sommerfeld_inductance (ADR-0006).

Measured against an independently derived closed form (image expansion summed to convergence): ~3e-10 relative for surface pairs, interface pairs, pairs a millimetre below the interface, cross-layer pairs straddling it, and radii from 0 to 20 km — and identical to ten digits for lambda_max_factor anywhere in 30 … 30 000. Up to 0.15.0.dev the same geometries were wrong by 0.7 % … 40 % with no warning, and non-monotone in the knob.

Splitting the primary term off matters because it is the only part of \(\Phi\) that does not decay in \(\lambda\): integrating it numerically up to \(\lambda_\text{max}\) left an \(O((\lambda_\text{max}R)^{-1/2})\) oscillatory residue — measured −4.5 % at \(s = 1\) m and ±4 % swings with period \(2\pi/\lambda_\text{max} \approx 0.03\) m for equal-depth pairs, and non-monotone in lambda_max_factor. In the homogeneous limit \(\rho_2 = \rho_1\) the closed form now reproduces \(\rho/2\,(1/r + 1/r')\) to ~1e-13 instead of ~1e-2.

For s = 0 and z = z_s every \(1/R\) pole is clamped at \(R = 1/\lambda_\text{clamp}\) with \(\lambda_\text{clamp} =\) lambda_max_factor \(/\min(h_1, s + z + z_s)\) — so the return value stays finite and continuous and depends only on the knob and the depths, but it is not a physical potential: the caller must regularise at the wire radius. The same clamp applies to every \(R < 1/\lambda_\text{clamp}\) (25 mm for \(h_1 = 5\) m); a caller that evaluates closer pairs passes its own min_distance.

Parameters:

Name Type Description Default
s float

Cylindrical radius in m, \(\ge 0\).

required
z float

Observer / source depths in m, \(\ge 0\) (positive into the soil). Negative depths raise ValueError — they used to return nan.

required
z_s float

Observer / source depths in m, \(\ge 0\) (positive into the soil). Negative depths raise ValueError — they used to return nan.

required
rho_1 float

Two-layer soil parameters.

required
rho_2 float

Two-layer soil parameters.

required
h_1 float

Two-layer soil parameters.

required
lambda_max_factor float

Upper bound on the quadrature truncation, as a multiple of \(1/\bar h\) with \(\bar h = \min(h_1, s + z + z_s)\), and the regularisation wavenumber of the \(1/R\) poles. It is not the truncation actually used: since 0.15.0 the truncated tail is bounded by a closed-form image split rather than by making \(\lambda_\text{max}\) large, so \(\lambda_\text{max}\) is lowered to whatever that split allows (_plan_truncation()). Consequence: raising this knob is normally a no-op and cannot change the answer, which is the whole point — review pass 9 found the result flipping sign as it was raised. Lowering it below ~30/(smallest image distance) still moves work into the closed form and must likewise leave the answer unchanged; that is the convergence check to run.

200.0
n_log int

Number of nodes in the logarithmic / linear part of the quadrature grid.

32
n_lin int

Number of nodes in the logarithmic / linear part of the quadrature grid.

32
min_distance float | None

Regularisation length of the closed-form \(1/R\) terms in m: they are clamped at \(\min(1/\lambda_\text{clamp},\) min_distance \()\) instead of \(1/\lambda_\text{clamp}\). None (default) keeps \(1/\lambda_\text{clamp}\). Values at \(R \ge 1/\lambda_\text{clamp}\) do not depend on it (see _regularisation_wavenumber()).

None

Returns:

Name Type Description
G float

Real-space scalar Green's function (dimensionless after dividing by \(\rho\)).

Source code in src/groundfield/coupling/layered_green.py
def two_layer_real_space_kernel(
    s: float,
    z: float,
    z_s: float,
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
    lambda_max_factor: float = 200.0,
    n_log: int = 32,
    n_lin: int = 96,
    min_distance: float | None = None,
) -> float:
    """Cross-layer real-space scalar Green's function $\\varphi(s, z, z_s)$.

    Computes $\\varphi(s, z, z_s) / I = \\int_0^\\infty
    \\Phi(\\lambda, z, z_s)\\,J_0(\\lambda s)\\,\\lambda\\,d\\lambda$
    for a unit point source at $(0, 0, z_s)$ observed at $(s, 0, z)$.
    The result already includes the $1/(4\\pi)$-style prefactor that
    is conventional in the existing `mom_sommerfeld` kernel
    representation.

    Numerical strategy: the primary (source-layer particular) term is
    evaluated in **closed form** as $\\rho_k/(2R)$ with
    $R = \\sqrt{s^2 + (z-z_s)^2}$
    (:func:`_primary_term_real_space`), and so is every reflected image
    term whose distance is too short for the truncation at
    $\\lambda_\\text{max}$ to be negligible
    (:func:`_reflected_image_terms`, :func:`_plan_truncation`); only the
    provably fast-decaying rest goes through the split-grid Sommerfeld
    quadrature (logarithmic for small $\\lambda$, oscillation-resolved
    for large $\\lambda$) consistent with
    :mod:`groundfield.coupling.sommerfeld_inductance` (ADR-0006).

    Measured against an independently derived closed form (image
    expansion summed to convergence): ~3e-10 relative for surface
    pairs, interface pairs, pairs a millimetre below the interface,
    cross-layer pairs straddling it, and radii from 0 to 20 km — and
    *identical to ten digits* for ``lambda_max_factor`` anywhere in
    30 … 30 000. Up to 0.15.0.dev the same geometries were wrong by
    0.7 % … 40 % with no warning, and non-monotone in the knob.

    Splitting the primary term off matters because it is the only part
    of $\\Phi$ that does not decay in $\\lambda$: integrating it
    numerically up to $\\lambda_\\text{max}$ left an
    $O((\\lambda_\\text{max}R)^{-1/2})$ oscillatory residue — measured
    −4.5 % at $s = 1$ m and ±4 % swings with period
    $2\\pi/\\lambda_\\text{max} \\approx 0.03$ m for equal-depth pairs,
    and *non-monotone* in ``lambda_max_factor``. In the homogeneous
    limit $\\rho_2 = \\rho_1$ the closed form now reproduces
    $\\rho/2\\,(1/r + 1/r')$ to ~1e-13 instead of ~1e-2.

    For ``s = 0`` and ``z = z_s`` every $1/R$ pole is clamped at
    $R = 1/\\lambda_\\text{clamp}$ with $\\lambda_\\text{clamp} =$
    ``lambda_max_factor`` $/\\min(h_1, s + z + z_s)$ — so the return
    value stays finite and continuous and depends only on the knob and
    the depths, but it is *not* a physical potential: the caller must
    regularise at the wire radius. The same clamp applies to every
    $R < 1/\\lambda_\\text{clamp}$ (25 mm for $h_1 = 5$ m); a caller
    that evaluates closer pairs passes its own ``min_distance``.

    Parameters
    ----------
    s : float
        Cylindrical radius in m, $\\ge 0$.
    z, z_s : float
        Observer / source depths in m, $\\ge 0$ (positive into the
        soil). Negative depths raise :class:`ValueError` — they used to
        return ``nan``.
    rho_1, rho_2, h_1 : float
        Two-layer soil parameters.
    lambda_max_factor
        *Upper bound* on the quadrature truncation, as a multiple of
        $1/\\bar h$ with $\\bar h = \\min(h_1, s + z + z_s)$, and the
        regularisation wavenumber of the $1/R$ poles. It is **not** the
        truncation actually used: since 0.15.0 the truncated tail is
        bounded by a closed-form image split rather than by making
        $\\lambda_\\text{max}$ large, so $\\lambda_\\text{max}$ is
        lowered to whatever that split allows
        (:func:`_plan_truncation`). Consequence: raising this knob is
        normally a no-op and *cannot* change the answer, which is the
        whole point — review pass 9 found the result flipping sign as it
        was raised. Lowering it below ~30/(smallest image distance)
        still moves work into the closed form and must likewise leave
        the answer unchanged; that is the convergence check to run.
    n_log, n_lin
        Number of nodes in the logarithmic / linear part of the
        quadrature grid.
    min_distance
        Regularisation length of the closed-form $1/R$ terms in m: they
        are clamped at $\\min(1/\\lambda_\\text{clamp},$ ``min_distance``
        $)$ instead of $1/\\lambda_\\text{clamp}$. ``None`` (default)
        keeps $1/\\lambda_\\text{clamp}$. Values at
        $R \\ge 1/\\lambda_\\text{clamp}$ do not depend on it (see
        :func:`_regularisation_wavenumber`).

    Returns
    -------
    G : float
        Real-space scalar Green's function (dimensionless after
        dividing by $\\rho$).
    """
    _validate_depths(z, z_s)
    plan = _plan_truncation(
        z=z,
        z_s=z_s,
        rho_1=rho_1,
        rho_2=rho_2,
        h_1=h_1,
        rho_baseline=None,
        s_near=s,
        s_far=s,
        lambda_max_factor=lambda_max_factor,
        warn_stacklevel=3,
    )
    lambda_clamp = _regularisation_wavenumber(plan.lambda_clamp, min_distance)
    lambdas, weights = _hankel_lambda_grid(
        lambda_max=plan.lambda_max,
        char_length=plan.char_length,
        s=s,
        n_log=n_log,
        n_lin=n_lin,
        warn_stacklevel=3,
    )

    A, B, _, C = _spectral_amplitudes(lambdas, z_s, rho_1, rho_2, h_1)
    Phi_refl = _phi_from_stable_amplitudes(
        lambdas,
        A,
        B,
        C,
        z,
        z_s,
        rho_1,
        rho_2,
        h_1,
        include_primary=False,
    ) - _image_spectral_sum(lambdas, plan.coeffs, plan.dists)
    integrand = Phi_refl * j0(lambdas * s) * lambdas
    total = float(np.sum(weights * integrand))
    total += float(_image_real_space_sum(plan.coeffs, plan.dists, s, lambda_clamp))

    rho_primary = _primary_rho(z, z_s, rho_1, rho_2, h_1)
    if rho_primary == 0.0:
        return total
    return total + float(
        _primary_term_real_space(rho_primary, s, z - z_s, lambda_clamp)
    )

two_layer_spectral_kernel

two_layer_spectral_kernel(lambdas: ndarray, z: float, z_s: float, *, rho_1: float, rho_2: float, h_1: float) -> np.ndarray

Spectral Green's function \(\Phi(\lambda, z, z_s)\).

Returns the value of the spectral kernel at every \(\lambda\) in lambdas for given source depth \(z_s\) and observer depth \(z\). Both depths can be in either layer.

Parameters:

Name Type Description Default
lambdas ndarray

1-D array of spectral variable values, \(\lambda > 0\) in units of m⁻¹.

required
z float

Observer / source depth in metres (\(z \ge 0\), positive into the soil).

required
z_s float

Observer / source depth in metres (\(z \ge 0\), positive into the soil).

required
rho_1 float

Resistivities of upper / lower layer in \(\Omega\,\mathrm{m}\).

required
rho_2 float

Resistivities of upper / lower layer in \(\Omega\,\mathrm{m}\).

required
h_1 float

Upper-layer thickness in m.

required

Returns:

Name Type Description
Phi (ndarray, shape(n_lambda))
Source code in src/groundfield/coupling/layered_green.py
def two_layer_spectral_kernel(
    lambdas: np.ndarray,
    z: float,
    z_s: float,
    *,
    rho_1: float,
    rho_2: float,
    h_1: float,
) -> np.ndarray:
    """Spectral Green's function $\\Phi(\\lambda, z, z_s)$.

    Returns the value of the spectral kernel at every $\\lambda$
    in ``lambdas`` for given source depth $z_s$ and observer depth
    $z$. Both depths can be in either layer.

    Parameters
    ----------
    lambdas
        1-D array of spectral variable values, $\\lambda > 0$ in
        units of m⁻¹.
    z, z_s
        Observer / source depth in metres ($z \\ge 0$, positive into
        the soil).
    rho_1, rho_2
        Resistivities of upper / lower layer in $\\Omega\\,\\mathrm{m}$.
    h_1
        Upper-layer thickness in m.

    Returns
    -------
    Phi : np.ndarray, shape (n_lambda,)
    """
    A, B, _, C = _spectral_amplitudes(
        lambdas,
        z_s,
        rho_1,
        rho_2,
        h_1,
    )
    return _phi_from_stable_amplitudes(
        lambdas,
        A,
        B,
        C,
        z,
        z_s,
        rho_1,
        rho_2,
        h_1,
    )

Earth-model resolvers

resolve_earth_conductivity

resolve_earth_conductivity(soil) -> float

Resolve earth conductivity \(\sigma_\text{earth}\) from a soil model.

Used by the Carson earth-return correction (ADR-0005) to get a single scalar conductivity from the (potentially layered) soil model. The mapping is:

  • HomogeneousSoil → \(\sigma = 1/\rho\), exact.
  • TwoLayerSoil → \(\sigma = 1/\rho_1\) (upper layer), with a runtime warning.
  • MultiLayerSoil → \(\sigma = 1/\rho_1\) (top layer), with a runtime warning.

The layered cases are an approximation; the Pollaczek/Sommerfeld kernel (earth_inductive_model="sommerfeld") is the rigorous alternative.

Parameters:

Name Type Description Default
soil

Any concrete soil model from groundfield.soil.models.

required

Returns:

Name Type Description
sigma_earth float

Earth conductivity in S/m.

Raises:

Type Description
TypeError

If the soil model has no resistivity field that can be interpreted as an upper-layer value.

Source code in src/groundfield/coupling/__init__.py
def resolve_earth_conductivity(soil) -> float:
    """Resolve earth conductivity $\\sigma_\\text{earth}$ from a soil model.

    Used by the Carson earth-return correction (ADR-0005) to get a
    single scalar conductivity from the (potentially layered) soil
    model. The mapping is:

    - :class:`~groundfield.soil.models.HomogeneousSoil` →
      $\\sigma = 1/\\rho$, exact.
    - :class:`~groundfield.soil.models.TwoLayerSoil` →
      $\\sigma = 1/\\rho_1$ (upper layer), with a runtime warning.
    - :class:`~groundfield.soil.models.MultiLayerSoil` →
      $\\sigma = 1/\\rho_1$ (top layer), with a runtime warning.

    The layered cases are an *approximation*; the Pollaczek/Sommerfeld
    kernel (``earth_inductive_model="sommerfeld"``) is the rigorous
    alternative.

    Parameters
    ----------
    soil
        Any concrete soil model from
        :mod:`groundfield.soil.models`.

    Returns
    -------
    sigma_earth : float
        Earth conductivity in S/m.

    Raises
    ------
    TypeError
        If the soil model has no resistivity field that can be
        interpreted as an upper-layer value.
    """
    from groundfield.soil.models import (
        HomogeneousSoil,
        MultiLayerSoil,
        TwoLayerSoil,
    )

    if isinstance(soil, HomogeneousSoil):
        return 1.0 / float(soil.resistivity)
    if isinstance(soil, TwoLayerSoil):
        warnings.warn(
            "Carson series uses upper-layer rho_1 for a TwoLayerSoil — "
            "this is an approximation. For a rigorous result on layered "
            "soils use the Pollaczek/Sommerfeld kernel via "
            "earth_inductive_model='sommerfeld'. See ADR-0005 §'Layered earth'.",
            UserWarning,
            stacklevel=2,
        )
        return 1.0 / float(soil.rho_1)
    if isinstance(soil, MultiLayerSoil):
        warnings.warn(
            "Carson series uses top-layer rho for a MultiLayerSoil — "
            "this is an approximation. For a rigorous result on layered "
            "soils use the Pollaczek/Sommerfeld kernel via "
            "earth_inductive_model='sommerfeld'. See ADR-0005 §'Layered earth'.",
            UserWarning,
            stacklevel=2,
        )
        return 1.0 / float(soil.layers[0].resistivity)
    raise TypeError(f"Unsupported soil type for Carson series: {type(soil).__name__}")

resolve_earth_layers

resolve_earth_layers(soil) -> 'LayeredEarth'

Resolve a soil model into a LayeredEarth configuration.

Used by the Sommerfeld earth-return kernel (ADR-0006). Unlike resolve_earth_conductivity(), this preserves the full layered structure — no warning is emitted: the kernel is exact for any number of layers (generalised reflection coefficients, review pass 10, finding 10.35; before that, n >= 3 used a single air-image approximation that was 17–25 % off in the earth-return reactance).

Parameters:

Name Type Description Default
soil

Any concrete soil model from groundfield.soil.models.

required

Returns:

Type Description
LayeredEarth

Frozen layered-earth configuration (resistivities and layer thicknesses) consumable by groundfield.coupling.sommerfeld_inductance.build_sommerfeld_correction_matrix().

Raises:

Type Description
TypeError
Source code in src/groundfield/coupling/__init__.py
def resolve_earth_layers(soil) -> "LayeredEarth":
    """Resolve a soil model into a :class:`LayeredEarth` configuration.

    Used by the Sommerfeld earth-return kernel (ADR-0006). Unlike
    :func:`resolve_earth_conductivity`, this preserves the full
    layered structure — no warning is emitted: the kernel is exact for
    any number of layers (generalised reflection coefficients, review
    pass 10, finding 10.35; before that, ``n >= 3`` used a single
    air-image approximation that was 17–25 % off in the earth-return
    reactance).

    Parameters
    ----------
    soil
        Any concrete soil model from
        :mod:`groundfield.soil.models`.

    Returns
    -------
    LayeredEarth
        Frozen layered-earth configuration (resistivities and layer
        thicknesses) consumable by
        :func:`groundfield.coupling.sommerfeld_inductance.build_sommerfeld_correction_matrix`.

    Raises
    ------
    TypeError
        If ``soil`` is not a :class:`~groundfield.soil.models.HomogeneousSoil`,
        :class:`~groundfield.soil.models.TwoLayerSoil` or
        :class:`~groundfield.soil.models.MultiLayerSoil`.
    """
    from groundfield.coupling.sommerfeld_inductance import LayeredEarth
    from groundfield.soil.models import (
        HomogeneousSoil,
        MultiLayerSoil,
        TwoLayerSoil,
    )

    if isinstance(soil, HomogeneousSoil):
        return LayeredEarth(
            rhos=(float(soil.resistivity),),
            thicknesses=(),
        )
    if isinstance(soil, TwoLayerSoil):
        return LayeredEarth(
            rhos=(float(soil.rho_1), float(soil.rho_2)),
            thicknesses=(float(soil.h_1),),
        )
    if isinstance(soil, MultiLayerSoil):
        rhos = tuple(float(layer.resistivity) for layer in soil.layers)
        thicknesses = tuple(float(layer.thickness) for layer in soil.layers[:-1])
        return LayeredEarth(rhos=rhos, thicknesses=thicknesses)
    raise TypeError(
        f"Unsupported soil type for Sommerfeld kernel: {type(soil).__name__}"
    )