Skip to content

Solver

The solver layer holds the numerics: the Engine (configuration and solve), the FieldResult (potentials, currents, impedances, metadata) and the multi-port functions solve_mutual_matrix / solve_mutual_field. The backends themselves are registered in the backend registry; their theory is on the engine pages.

Mathematical and physical context

Every backend solves the same problem — the quasi-static potential of the electrodes in layered soil, coupled to the conductor network — for each frequency of Engine.frequencies. The electrodes are cut into \(N\) segments (length at most segment_length) carrying leakage currents \(I_k\); the potential of segment \(i\) is

\[ \varphi_i = \sum_{k=1}^{N} G_{ik}\, I_k , \]

with \(G_{ik}\) the potential at segment \(i\) per unit current on segment \(k\) (the Green's function of the layered half-space integrated over the segments). The galvanic clusters are equipotential, the conductor branches add Kirchhoff's laws, and the source currents are the right-hand side of the augmented system. The backends differ in how they evaluate \(G\) and which current ansatz they use:

Backend Green's function Current ansatz
image free space + surface image, closed form uniform current per unit length on each straight wire of an electrode (one unknown per wire line of a grid, arm of a star, straight run of a polyline, and soil layer; user decision Q30); exact line-source kernel by default
image_2layer Tagg/Sunde image series, closed form; layered Sommerfeld correction for wires through the interface as image
mom the same closed-form kernels point matching: one unknown current per segment, midpoint point sources
mom_sommerfeld numerical Sommerfeld quadrature of the layered Green's function, any number of layers as mom
fem (experimental) none: conforming finite elements of the soil, axisymmetric for coaxial rods and rings, three-dimensional otherwise (fem3d extra) volume solution (axisymmetric: the electrodes as solid bodies; 3-D: smoothed line sources)

The uniform-current ansatz gives accurate impedances at low cost; near grids, stars, strip ends and bonded multi-electrode clusters its surface potentials are impedance-grade, not field-grade (see Known limitations).

Engine(backend="image"), the default, forwards a TwoLayerSoil to image_2layer and a MultiLayerSoil with at most two distinct layers to the image dispatcher; three or more layers need mom_sommerfeld. FieldResult.metadata["effective_backend"] and ["kernel"] record what ran.

Engine settings

Field Default Meaning
backend "image" registered backend name (see registry)
frequencies [50.0] Hz; the given order is kept (a non-monotonic list warns with EngineFrequencyOrderWarning, with_frequencies(..., preserve_order=True) silences it)
segment_length 0.5 maximum segment length in m
kernel None None: the backend's preferred kernel ("line" for the image family); "line" or "point" explicitly; "point" reproduces the numbers of releases up to 0.15.0
earth_inductive_model "sommerfeld" earth return of inductive conductors: "sommerfeld", "carson_series", "perfect_mirror" (see Coupling)
sommerfeld_assembly "tabulated" assembly of the Sommerfeld correction of inductive conductors: "tabulated" (one table of the spectral integral per pair of depth groups and frequency; default since 2026.11) or "exact" (one quadrature per segment pair, the default up to 0.15.0)
max_segments None resource limit of this engine: the largest number of leakage segments and of nodal unknowns it solves, ResourceLimitError above it before anything is allocated; None takes groundfield.diagnostics.HARD_LIMIT (20 000); recorded in metadata["max_segments"]
warn_segments None size of the soft notice of this engine, counted like max_segments: at or above it the solve warns that it may take minutes (an info finding of diagnose); None takes groundfield.diagnostics.SOFT_LIMIT (5 000); not checked against max_segments (a notice above the hard limit never appears)
image_max_terms, image_series_tol 300, 10⁻⁶ cap and stop tolerance of the Tagg/Sunde series (tail bound \(\lvert K\rvert^{n+1}/(1-\lvert K\rvert)\))
image_far_field "quadrupole" form of the far images of the line kernel in two-layer soil (Tagg/Sunde images and images of the cross-layer correction): "quadrupole" (point value plus the quadrupole term of the segment average) or "point" (point sources beyond the near-pair reach: the dense far term is left out, the near image pairs stay Galerkin integrals on both paths, audit W3R2A-01; faster; networks move by 3 · 10⁻⁶ … 4.3 · 10⁻⁴, not the result before wave 3 of the 2026.11 work); any other value raises ValueError; recorded in metadata["series"], used by FieldResult.potential and solve_mutual_*; no effect with kernel="point" or in homogeneous soil (the author's decision of 2026-11-15)
options {} backend-specific settings, e.g. {"mom_sommerfeld": {"epsrel": 1e-9}} (see the backend pages for the options of each backend)

tolerance and max_iterations have no effect and are deprecated (see Deprecations).

Example

import groundfield as gf

world = gf.create_world(soil=gf.TwoLayerSoil(rho_1=100.0, rho_2=300.0, h_1=2.0))
gf.create_electrode(world, "rod", name="a", position=(0.0, 0.0, 0.0), length=3.0)
gf.create_electrode(world, "ring", name="b", center=(20.0, 0.0, 0.8), radius=2.0)
engine = gf.create_engine(frequencies=[50.0])

# Mutual grounding-impedance matrix of the two earths in one assembly:
# Z[i, j] = potential of cluster i per ampere leaking from cluster j.
Z = gf.solve_mutual_matrix(world, engine, anchors=["a", "b"])   # Ω

# The same entries from an ordinary solve with 1 A at "a":
gf.create_source(world, attached_to="a", magnitude=1.0)
result = engine.solve(world)
assert abs(Z[0, 0] - result.cluster_impedance("a")[0]) < 1e-9    # 51.40 Ω
assert abs(Z[1, 0] - result.electrode_potentials["b"][0]) < 1e-9  # 2.26 Ω
assert result.metadata["effective_backend"] == "image_2layer"

solve_mutual_matrix returns the galerkin off-diagonal (the reaction of the leakage distributions: reciprocal, and the matrix that reproduces a solve of the clusters joined by branches) for every call since 2026.11. offdiag="probe" with probe_points samples the potential at one point per cluster instead, the definition up to 0.15.0; probe points passed without it are ignored with a ProbePointsIgnoredWarning.

FieldResult.potential(points, frequency_index=0) evaluates the potential in V at arbitrary points of shape (M, 3) (homogeneous and two-layer soil), to_dataframe() returns the per-electrode table, to_dataframe("sources") the per-source table (impressed or solved current, the voltage and internal impedance of a voltage source, the input impedance), and metadata["provenance"] records the package and library versions, the engine configuration, a fingerprint of the world and the solve time stamp. Results are saved and loaded with save_result / load_result.

API reference

engine

Numerical computation core (Engine).

An Engine bundles everything that is purely numerical: the chosen backend (image, MoM, FEM, ...), the frequency list, the discretisation and the backend settings. It is deliberately separated from the World, so that the same physical configuration can be run against different backends.

Backends are registered in groundfield.solver.registry, which records for each name the solve function, the declared capabilities (soil layer counts, conductor models, concrete shells, two-terminal sources, source kernels) and the backend-specific options model. The built-in backends fall into three families:

Closed-form / image-charge. image is the homogeneous-soil image-charge sum (closed form, uniform current per unit length, cheapest backend). image_2layer implements the Tagg / Sunde geometric series for two-layer soil with convergence \(|K|^n\). Both use the exact line-source kernel by default (Engine.kernel). image_nlayer (deprecated name) routes a layered soil with one or two distinct layers to image / image_2layer and rejects three or more; cim is a deprecated name of the image auto-dispatch.

Integral equation. mom solves for the segment currents by point matching (collocation) with the closed-form kernels above; mom_sommerfeld does the same with direct numerical Sommerfeld quadrature of the layered Green's function and is the only integral backend for \(n \ge 3\) layers. bem is a deprecated name of mom.

Volume PDE. fem (experimental) solves the field in the soil by conforming finite elements: an axisymmetric model for rods on one axis and rings around it, a three-dimensional one for every other world (the optional fem3d extra), described in groundfield.solver.fem.

Notes

Engine.solve() performs an automatic dispatch when backend="image" is requested: the call is forwarded to "image_2layer" if the world holds a TwoLayerSoil, and to "image_nlayer" if it holds a MultiLayerSoil. Notebooks written for the homogeneous case therefore keep working when the soil is replaced by a layered one.

Every result carries the metadata core CORE_METADATA_KEYS, filled here for all backends, next to the backend-specific keys.

Backend module-attribute

Backend = Literal['image', 'image_2layer', 'image_nlayer', 'cim', 'mom', 'mom_sommerfeld', 'bem', 'fem']

Names of the built-in backends, for type hints.

The registry is the authority at runtime and also accepts registered third-party names (available_backends()). "cim", "bem" and "image_nlayer" are deprecated aliases of "image" and "mom".

CORE_METADATA_KEYS module-attribute

CORE_METADATA_KEYS: tuple[str, ...] = ('backend', 'effective_backend', 'kernel', 'groundfield_version', 'frequencies', 'n_segments', 'soil_kind', 'earth_inductive_model', 'solve_time_s', 'series', 'max_segments', 'provenance')

Metadata keys that Engine.solve() writes into every result.

  • backend: Backend name as requested (Engine.backend).
  • effective_backend: Registered backend that ran, after alias resolution and the auto-forwarding by soil model.
  • kernel: Source kernel used ("point" / "line"); fem reports the kernel of the point sources of its result (the engine's, default "line"), which the field evaluation uses.
  • groundfield_version: Version of the package that solved.
  • frequencies: Frequencies in Hz, in solve order.
  • n_segments: Number of current-carrying source segments (for fem the display segments that carry the point sources of its result).
  • soil_kind: kind of the soil model ("homogeneous", "two_layer", "multi_layer").
  • earth_inductive_model: Earth model of the inductive coupling.
  • solve_time_s: Wall time of the backend call in s.
  • series: Image-series controls of the engine, {"max_terms", "tol", "far_field"}, for the post-solve field evaluation.
  • max_segments: Problem-size limit the solve was checked against (Engine.max_segments, or groundfield.diagnostics.HARD_LIMIT when the engine leaves it at None); fem checks its display segments against it and limits its mesh by FemOptions.max_nodes / max_nodes_3d.
  • provenance: Versions, platform, engine configuration, world fingerprint and UTC timestamp (see groundfield.solver.result.solve_provenance()).

DEFAULT_IMAGE_MAX_TERMS module-attribute

DEFAULT_IMAGE_MAX_TERMS = 300

Default cap on the number of Tagg / Sunde image-series terms.

One value for the engine, every layered backend and the post-solve field evaluation. The geometric tail bound |K|^(n+1)/(1-|K|) falls below the default tolerance after 277 terms for the AP1 corner soil rho_1 = 1000, rho_2 = 30 Ohm m (|K| = 0.9417), so the cap stays unused there.

DEFAULT_IMAGE_SERIES_TOL module-attribute

DEFAULT_IMAGE_SERIES_TOL = 1e-06

Default stop tolerance of the Tagg / Sunde image series.

Summation ends when the geometric tail bound |K|^(n+1)/(1-|K|) falls below this value.

DEFAULT_KERNEL module-attribute

DEFAULT_KERNEL = 'line'

Kernel an engine requests when it leaves the choice to the backend.

Applies to Engine.kernel = None, the default since 2026.11 (review pass 10, 10.28): the exact line-source kernel wherever a backend implements it (the image family), the backend's own kernel elsewhere.

EarthInductiveModel module-attribute

EarthInductiveModel = Literal['perfect_mirror', 'carson_series', 'sommerfeld']

Earth-return models of the inductive coupling.

The values of Engine.earth_inductive_model:

  • "perfect_mirror": the earth as a perfect magnetic mirror (ADR-0004), a fast diagnostic baseline;
  • "carson_series": Carson's (1926) per-metre series correction for long parallel wires over homogeneous earth (ADR-0005);
  • "sommerfeld": the geometric Sommerfeld / Pollaczek integral for any geometry and any number of layers (ADR-0006), the engine's default.

Engine

Bases: BaseModel

Configuration of the numerical kernel.

Attributes:

Name Type Description
backend str

Numerical method, a name registered in groundfield.solver.registry. Built in: image, image_2layer, image_nlayer, cim, mom, mom_sommerfeld, bem, fem. See the module docstring above for the family overview, and ADR-0002 for the selection heuristic. An unknown name raises with the closest registered one as suggestion.

frequencies list[float]

Frequency list in Hz. Default [50.0].

segment_length float

Maximum segment length used to discretise the geometry, in m.

max_segments int | None

Resource limit of this engine: the largest problem size it solves, counted as the number of leakage segments and as the number of unknowns of the dense nodal system (current owners, nodes and branches, every conductor sub-piece included). A world above it raises ResourceLimitError before anything of that size is allocated, in every segment backend and in solve_mutual_matrix() / solve_mutual_field. None (default) takes groundfield.diagnostics.HARD_LIMIT (20 000), read at solve time; a positive integer raises or lowers the limit for this engine only (user decision Q17 of 2026.11, finding 10.06). The dense reaction matrix of \(N\) segments takes \(8N^2\) bytes (3.0 GiB at 20 000), the nodal system of \(n\) unknowns \(16n^2\) bytes; expected_segments() predicts both. The limit is recorded in FieldResult.metadata ["max_segments"]; fem checks the display segments of its result against it and limits its volume mesh by FemOptions.max_nodes / max_nodes_3d.

warn_segments int | None

Size of the soft notice of this engine, counted like max_segments: at or above it every solve emits a UserWarning that the solve time may run from seconds to minutes ("budget: ..."), and diagnose() reports it as an info finding. None (default) takes groundfield.diagnostics.SOFT_LIMIT (5 000), read at solve time; a positive integer moves the notice for this engine only, for instance up to the size a workstation solves in seconds (user decision Q31 of 2026.11). It is not checked against max_segments: a notice above the hard limit never appears, because such a world is refused first. Kept by JSON round trips, with_frequencies() and model_copy(); the provenance block of a result records the request.

tolerance, max_iterations

Deprecated, no effect (no backend reads them). A non-default value warns; both fields will be removed no earlier than 2027.5.

earth_inductive_model EarthInductiveModel

How the earth contributes to the inductive coupling between distributed-conductor segments (only effective when at least one conductor sets inductance_model = "neumann"):

  • "perfect_mirror" (ADR-0004, the pre-0.13 default) — the earth is a perfect magnetic mirror. Cheap, frequency-independent inductance assembly, but its additive image is far from the f < 1 kHz physics of buried conductors (audit finding F5); kept as a fast diagnostic baseline.
  • "carson_series" (ADR-0005) — the earth has finite conductivity. Carson 1926's per-metre earth-return correction \(\Delta Z'_\text{Carson}(\omega)\) is added to the Neumann matrix built on Carson's own baseline, the anti-parallel image (since 2026.11; up to 0.15.0 it was added to the additive perfect-mirror matrix, which roughly doubled the reactance, review pass 10, 10.20). It is tiled per metre of axial overlap, and only inside its validity domain: near-parallel pairs (\(|\cos\varphi| > 0.99\)) of near-horizontal segments (inclination below 8.1°) on one side of the surface; two conductors overlapping on one axis get the correction of touching wires. A pair across the surface has no anti-parallel baseline and couples through the field transmitted into the soil (carson_mixed_mutual_correction()). Oblique pairs and every pair and self term of a segment inclined by more than 8.1° get the Sommerfeld correction of a homogeneous earth of the same conductivity; at that boundary the result steps by the error of the per-metre model (13 % for two 1 km leads 2 m apart at 1 kHz; audit rounds 2 and 3). Asymptotically correct for long parallel wires over homogeneous earth; an approximation for short wires and for layered soil (the top layer's conductivity is used).
  • "sommerfeld" (ADR-0006, Pollaczek kernel since the 2026-07-08 audit, WP-C1) — geometric integration of the σ-dependent vector-potential Green's function over the actual segment-pair geometry, dispatched by conductor side: buried pairs carry the in-soil attenuation \(e^{-\gamma R}\) (and with it the positive earth-return resistance \(\approx \omega\mu_0/8\) per metre in the long-wire limit), overhead pairs use the air-side reflection (Carson's geometry). The Neumann matrix carries no image: the correction holds the whole earth effect, so conductors in or crossing the surface plane are solved too (since 2026.11). Supports layered earth; see sommerfeld_assembly for the assembly (tabulated by default). Limits: \(\sigma \to 0\) → free space (no image); \(\sigma \to \infty\) → screened (buried) / anti-parallel PEC image (overhead). Validated against Pollaczek's analytic \(K_0\) mutual and Carson's line impedance (tests/test_earth_return_benchmark.py). The default since 0.13.0 — the rigorous choice whenever a quantitative Z(f) matters.
image_max_terms, image_series_tol

Controls of the Tagg / Sunde image-charge series (maximum number of terms; stop tolerance on the geometric tail bound \(|K|^{n+1}/(1-|K|)\), dimensionless). Common to every layered backend that evaluates the series (image_2layer, mom, the delegated two-layer path of mom_sommerfeld; the deprecated names run these) and to solve_mutual_*; recorded in FieldResult.metadata["series"], which FieldResult.potential() uses for the post-solve field evaluation. Defaults: DEFAULT_IMAGE_MAX_TERMS (300) and DEFAULT_IMAGE_SERIES_TOL (1e-6).

image_far_field Literal['quadrupole', 'point']

Form of the far images of the line kernel in two-layer soil — the Tagg/Sunde images (n >= 1) and the images of the cross-layer correction beyond the near-pair reach (the author's decision of 2026-11-15):

  • "quadrupole" (default) — the far form of direct pairs: the point value plus the quadrupole term of the segment average, tapered off between 60 and 120 segment lengths of vertical distance (wave 3 of the 2026.11 work, finding 10.28).
  • "point" — point sources: the dense far term is left out. The near image pairs (within 7.5 segment lengths, a segment's own images included) stay Galerkin integrals blended into the point form, on the series and the cross-layer path alike, and so do the continuous switch (user decision D2) and the transverse distance of near image pairs. It is therefore not the result before wave 3: within the upper layer it differs from it by up to 2.3e-4 (16 house grids in 1000 / 30 Ω·m with \(h_1\) = 1.5 m, the blend of D2). Up to audit W3R2A-01 the cross-layer path kept the line form of the interface image only, so a long segment below the interface saw its own images as point sources: a 75 m strip below a 0.5 m top layer read -1.0e-3 at a segment length of 2.5 m and -58 % at 37.5 m; it is now within 1.1e-5 of its exact value at every segment length (500 / 100 and 1000 / 30 Ω·m).

Against the default, "point" moves networks by 3e-6 … 4.3e-4 (16 house grids 0.4 m above a 1000 / 10 Ω·m interface: 4.3e-4), a straight wire 0.5 m above the interface by 4e-4 and the surface potential above it by up to 0.8 %. With numba it takes 1.1 … 1.3 times the solve before wave 3 on house grids within the upper layer. On the cross-layer path it takes 0.49 … 0.94 of the default's time (0.25 … 0.54 without numba), because the Galerkin near image pairs stay: 1.5 … 2.4 times the solve before wave 3 below thin top layers, 4.3 … 4.5 times with long pieces there, and 0.91 times (0.90 without numba) on a 40-house network in 1000 / 30 Ω·m with \(h_1\) = 1.5 m, whose transformer rods reach below \(h_1\) (performance page). Any other value raises ValueError (audit W3R2A-02). No effect with kernel="point", in homogeneous soil or on backends without the line kernel. Read by the image family and solve_mutual_*, recorded in FieldResult.metadata["series"] ("far_field") and used by FieldResult.potential(); kept by JSON round trips, with_frequencies(), model_copy() and the provenance block. The name follows image_max_terms / image_series_tol, the other controls of how the image series is evaluated.

options Mapping[str, SerializeAsAny[BackendOptions] | Mapping[str, Any]]

Backend-specific settings, keyed by backend name and validated against the backend's options model: {"mom_sommerfeld": MomSommerfeldOptions(...)} (quadrature accuracy) and {"fem": FemOptions(...)} (mesh and truncation). Plain mappings are accepted and validated into the options models; unknown option names raise with a suggestion. Options for a backend other than the selected one (or one it forwards to) emit BackendOptionsWarning. Entries put into the mapping in place (engine.options["fem"] = {...}) bypass that validation; they are validated when they are read (backend_options(), solve()). The 0.15.0 flat fields sommerfeld_lambda_max_factor, sommerfeld_epsabs, sommerfeld_epsrel and sommerfeld_max_osc_panels are still accepted (constructor, JSON, attribute access and model_copy()) and mapped onto options["mom_sommerfeld"] with a DeprecationWarning (the constructor drops a value equal to the default silently, so engine JSON of 0.15.0 loads without warnings).

sommerfeld_assembly Literal['exact', 'tabulated']

Assembly of the Sommerfeld earth-return correction of inductive conductors (earth_inductive_model="sommerfeld"):

  • "tabulated" (default since 2026.11, user decision Q16) — one table of the spectral integral \(S(\rho)\) per pair of depth groups and frequency (cubic spline, 100 nodes), the outer quadrature of all segment pairs vectorised. Blocks of fewer than 64 sub-segment pairs and blocks whose \(\lambda\) grid cannot resolve their largest distance (conductors in the surface plane) keep the per-pair rule.
  • "exact" — every segment pair with its own quadrature and 24 interpolation nodes of \(S(\rho)\); the default up to 0.15.0.

On a TN network of 8 houses with an inductive PEN (78 inductive branches, four frequencies) the tabulated solve took 1.0 s CPU instead of 16.6 s, and its input impedance is within 2e-10 of two independent refined references (per-pair rule with 200 nodes, tables of 400 nodes, both with a refined \(\lambda\) grid; they agree to 2e-10), the per-pair rule within 1.2e-8. Read by every backend that assembles the inductive branches through the shared pipeline (the image family, mom, mom_sommerfeld) and by solve_mutual_*; see build_sommerfeld_correction_matrices(), method. The Sommerfeld fallback of carson_series for oblique pairs is always tabulated.

kernel Literal['point', 'line'] | None

Green's-function kernel of the image family (image, image_2layer and image_nlayer for one or two layers), also used by FieldResult.potential() and solve_mutual_matrix() / solve_mutual_field:

  • None (default since 2026.11) — the backend's preferred kernel: "line" for the image family, the backend's own kernel ("point") for every other backend. FieldResult.metadata["kernel"] records the kernel that ran.
  • "line" — every segment is a uniform line current (Galerkin form of the exact line-source potential, see groundfield.solver._line_kernel). In homogeneous soil it is exact for straight wires at any segment length. In two-layer soil the Tagg/Sunde images and the images of the cross-layer correction get the same treatment: near image pairs exact (with the transverse distance of the wire from the image, audit W3A-02), blended into the far form between six and 7.5 segment lengths, far images with the quadrupole term (image_far_field). A straight 10 m strip is within 3.6e-6 of its uniform-current resistance for ds = 0.125–2 m, not monotonically (point kernel: up to 22 %), a ring 1 cm above a 1000 / 30 Ω·m interface within 0.004 % of its exact thin-ring value, and a rod through the layer interface within 1.4e-6 of its exact two-owner value. Cost: a solve of 16 house grids (N = 1920 segments) takes 3.8 times as long as with "point" in homogeneous soil and 1.6 times in two-layer soil (\(h_1\) = 5 m) when numba is installed (it is used automatically), 5.8 and 1.4 times without it; the extra time grows with \(N^2\). The far images of a high contrast cost more: a 40-house network in 1000 / 30 Ω·m with \(h_1\) = 1.5 m takes 1.8 times the solve before wave 3 of the 2026.11 work with numba, 3.6 times without (image_far_field="point": 0.8 times).
  • "point" — each segment's current sits at its midpoint; reproduces the results of releases up to 0.15.0. Its row sums carry an error of about \(-0.23/L\), so the grounding resistance converges to a value 0.9–1.9 % below the exact uniform-current solution (review pass 10, 10.28).

An explicit "line" on a backend without the line kernel raises BackendCapabilityError. The request is carried in the value: an engine rebuilt from its JSON, from with_frequencies or from a result's provenance block runs exactly like the original.

Notes

Every field is validated on construction, on assignment (engine.frequencies = [] raises) and in model_copy() (unlike pydantic's default model_copy, which stores update unchecked). Lists mutated in place are checked when the engine solves.

Examples:

>>> eng = Engine(backend="mom_sommerfeld", options={"mom_sommerfeld": {"epsabs": 1e-8}})
>>> eng.backend_options().epsabs
1e-08

backend_options

backend_options(name: str | None = None) -> BackendOptions | None

Options a backend runs with: the stored entry or the defaults.

Parameters:

Name Type Description Default
name str | None

Backend name or alias. Default: backend.

None

Returns:

Type Description
BackendOptions or None

The validated options model of the backend, or None for a backend without backend-specific options.

Raises:

Type Description
ValueError

If an entry put into options in place does not validate (unknown backend or option name, wrong value).

Source code in src/groundfield/solver/engine.py
def backend_options(self, name: str | None = None) -> BackendOptions | None:
    """Options a backend runs with: the stored entry or the defaults.

    Parameters
    ----------
    name
        Backend name or alias. Default: :attr:`backend`.

    Returns
    -------
    BackendOptions or None
        The validated options model of the backend, or ``None`` for
        a backend without backend-specific options.

    Raises
    ------
    ValueError
        If an entry put into :attr:`options` in place does not
        validate (unknown backend or option name, wrong value).
    """
    key = _registry.options_key(self.backend if name is None else name)
    model = _registry.get_backend(key).options_model
    if model is None:
        return None
    stored = self._checked_options().get(key)
    return stored if stored is not None else model()

model_copy

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self

Copy of the engine with update validated like the constructor.

pydantic's model_copy stores update without validation; a deprecated flat name such as sommerfeld_epsrel was then shadowed by its property and silently ignored (audit A1-02), and an empty frequency list or a raw option mapping went through (A1-04).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Field values to change. Validated together with the unchanged fields; the deprecated flat sommerfeld_* names are mapped onto options["mom_sommerfeld"] with a DeprecationWarning.

None
deep bool

Deep copy instead of a shallow one.

False

Returns:

Type Description
Engine

The copy (the receiver is not changed).

Raises:

Type Description
ValueError

If a key of update is not a field (with a suggestion), a value does not validate, or a flat name contradicts update["options"].

Notes

Only warnings that the update introduces are emitted; those of the unchanged fields (e.g. a non-monotonic frequency list) were emitted when the engine was built.

Source code in src/groundfield/solver/engine.py
def model_copy(
    self, *, update: Mapping[str, Any] | None = None, deep: bool = False
) -> Self:
    """Copy of the engine with ``update`` validated like the constructor.

    pydantic's ``model_copy`` stores ``update`` without validation; a
    deprecated flat name such as ``sommerfeld_epsrel`` was then
    shadowed by its property and silently ignored (audit A1-02), and
    an empty frequency list or a raw option mapping went through
    (A1-04).

    Parameters
    ----------
    update
        Field values to change. Validated together with the unchanged
        fields; the deprecated flat ``sommerfeld_*`` names are mapped
        onto ``options["mom_sommerfeld"]`` with a
        :class:`DeprecationWarning`.
    deep
        Deep copy instead of a shallow one.

    Returns
    -------
    Engine
        The copy (the receiver is not changed).

    Raises
    ------
    ValueError
        If a key of ``update`` is not a field (with a suggestion), a
        value does not validate, or a flat name contradicts
        ``update["options"]``.

    Notes
    -----
    Only warnings that the update introduces are emitted; those of
    the unchanged fields (e.g. a non-monotonic frequency list) were
    emitted when the engine was built.
    """
    if not update:
        return super().model_copy(deep=deep)
    fields = type(self).model_fields
    unknown = [
        k for k in update if k not in fields and k not in _LEGACY_SOMMERFELD_FIELDS
    ]
    if unknown:
        key = str(unknown[0])
        raise ValueError(
            f"Engine.model_copy: {key!r} is not a field."
            f"{did_you_mean(key, fields)} Fields: {', '.join(fields)}."
        )
    changes = dict(update)
    flat = {
        _LEGACY_SOMMERFELD_FIELDS[k]: changes.pop(k)
        for k in list(changes)
        if k in _LEGACY_SOMMERFELD_FIELDS
    }
    if flat:
        changes["options"] = self._options_with_flat(
            changes.get("options", self.options), flat, explicit="options" in update
        )
    # The unchanged fields as set on this engine (not the defaults), so
    # the copy keeps pydantic's ``model_fields_set`` semantics.
    base = {name: self.__dict__[name] for name in self.model_fields_set}
    with warnings.catch_warnings(record=True) as before:
        warnings.simplefilter("always")
        type(self).model_validate(base)
    with warnings.catch_warnings(record=True) as after:
        warnings.simplefilter("always")
        copy = type(self).model_validate({**base, **changes})
    seen = {(w.category, str(w.message)) for w in before}
    for w in after:
        if (w.category, str(w.message)) not in seen:
            warn_external(str(w.message), w.category)
    return super(Engine, copy).model_copy(deep=True) if deep else copy

solve

solve(world: 'World') -> FieldResult

Run the simulation with the configured backend.

Resolves backend in the registry, checks the backend's declared capabilities against world and runs it. When backend == "image" the backend is auto-forwarded to "image_2layer" for a TwoLayerSoil and to "image_nlayer" for a MultiLayerSoil, so notebooks written for the homogeneous case keep working when the soil model is replaced.

The sources of world are snapshotted before the backend runs and restored afterwards onto the caller's objects, exactly as in World.solve: solving never rewrites the input world, whichever entry point is used.

Parameters:

Name Type Description Default
world World

The assembled world (soil, electrodes, conductors and at least one source) the backend should solve.

required

Returns:

Type Description
FieldResult

Container with per-frequency potentials, currents, cluster impedances, the source snapshot and metadata: the core keys CORE_METADATA_KEYS (including the provenance block) plus the backend-specific keys.

Raises:

Type Description
ValueError

If world.soil is unset, world contains no electrodes, fails World.check (no current source, short-circuited source, zero or non-finite magnitude; the same for every backend and for World.solve), backend is not registered, frequencies was emptied or given a non-finite or negative entry in place, or an entry put into options in place does not validate.

KeyError

If a source terminal or conductor end names no node of world (World.check).

BackendCapabilityError

If the backend cannot represent the world (soil layer count, concrete-shell electrodes, explicitly requested kernel). The message names the registered backends that can.

ResourceLimitError

If the predicted number of segments or of nodal unknowns exceeds max_segments (default groundfield.diagnostics.HARD_LIMIT); raised before anything of that size is allocated (subclass of ValueError).

Warns:

Type Description
BackendCapabilityWarning

If the backend solves the world with a documented simplification (reduced conductor model, ignored return_to).

DeprecationWarning

If backend is a deprecated alias.

ExperimentalBackendWarning

On the first solve with an experimental backend in a process.

Source code in src/groundfield/solver/engine.py
def solve(self, world: "World") -> FieldResult:
    """Run the simulation with the configured backend.

    Resolves :attr:`backend` in the registry, checks the backend's
    declared capabilities against ``world`` and runs it. When
    ``backend == "image"`` the backend is auto-forwarded to
    ``"image_2layer"`` for a
    :class:`~groundfield.soil.models.TwoLayerSoil` and to
    ``"image_nlayer"`` for a
    :class:`~groundfield.soil.models.MultiLayerSoil`, so notebooks
    written for the homogeneous case keep working when the soil
    model is replaced.

    The sources of ``world`` are snapshotted before the backend runs
    and restored afterwards onto the caller's objects, exactly as in
    :meth:`World.solve <groundfield.world.World.solve>`: solving
    never rewrites the input world, whichever entry point is used.

    Parameters
    ----------
    world : World
        The assembled world (soil, electrodes, conductors and at
        least one source) the backend should solve.

    Returns
    -------
    FieldResult
        Container with per-frequency potentials, currents, cluster
        impedances, the source snapshot and metadata: the core keys
        :data:`CORE_METADATA_KEYS` (including the provenance block)
        plus the backend-specific keys.

    Raises
    ------
    ValueError
        If ``world.soil`` is unset, ``world`` contains no electrodes,
        fails :meth:`World.check <groundfield.world.World.check>`
        (no current source, short-circuited source, zero or non-finite
        magnitude; the same for every backend and for
        :meth:`World.solve <groundfield.world.World.solve>`),
        :attr:`backend` is not registered, :attr:`frequencies` was
        emptied or given a non-finite or negative entry in place, or
        an entry put into :attr:`options` in place does not validate.
    KeyError
        If a source terminal or conductor end names no node of
        ``world`` (:meth:`World.check <groundfield.world.World.check>`).
    BackendCapabilityError
        If the backend cannot represent the world (soil layer count,
        concrete-shell electrodes, explicitly requested kernel). The
        message names the registered backends that can.
    ResourceLimitError
        If the predicted number of segments or of nodal unknowns
        exceeds :attr:`max_segments` (default
        :data:`groundfield.diagnostics.HARD_LIMIT`); raised before
        anything of that size is allocated (subclass of
        ``ValueError``).

    Warns
    -----
    BackendCapabilityWarning
        If the backend solves the world with a documented
        simplification (reduced conductor model, ignored
        ``return_to``).
    DeprecationWarning
        If :attr:`backend` is a deprecated alias.
    ExperimentalBackendWarning
        On the first solve with an experimental backend in a process.
    """
    if world.soil is None:
        raise ValueError("World has no soil model. Set one before calling solve().")
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    # Assignments are validated; a list mutated in place is not (A1-04).
    _check_frequency_values(self.frequencies)
    # Central validation of references and excitation (10.66) for
    # every backend and entry point, a current source included: a world
    # without one solved to zeros in fem only and raised in every other
    # backend (audit round 2, A2S-05).
    world.check()

    resolved = _registry.resolve_backend(self.backend, world)
    _log.info(
        "Engine.solve: backend=%s (running %s), n_electrodes=%d, n_freq=%d",
        self.backend,
        resolved.spec.name,
        len(world.electrodes),
        len(self.frequencies),
    )
    with _guarded_sources(world):
        return self._run(world, resolved)

with_frequencies

with_frequencies(*frequencies: float, preserve_order: bool = False) -> 'Engine'

Return a copy of this engine with a new frequencies list.

Parameters:

Name Type Description Default
*frequencies float

One or more frequencies in Hz. Variadic to make the common case readable: engine.with_frequencies(50, 5000).

()
preserve_order bool

If True, the frequencies are stored verbatim and no non-monotonic warning is raised even for a decreasing or duplicate-bearing list. This is the explicit opt-in for sweeps that require a specific iteration order. If False (default) the standard _validate_frequencies() checks run.

False

Returns:

Type Description
Engine

A new Engine instance — the receiver is not mutated.

Examples:

>>> eng = Engine(backend="image").with_frequencies(50, 5000,
...                                                preserve_order=True)
>>> eng.frequencies
[50.0, 5000.0]
Source code in src/groundfield/solver/engine.py
def with_frequencies(
    self,
    *frequencies: float,
    preserve_order: bool = False,
) -> "Engine":
    """Return a copy of this engine with a new ``frequencies`` list.

    Parameters
    ----------
    *frequencies
        One or more frequencies in Hz. Variadic to make the
        common case readable: ``engine.with_frequencies(50, 5000)``.
    preserve_order
        If ``True``, the frequencies are stored verbatim and no
        non-monotonic warning is raised even for a decreasing or
        duplicate-bearing list. This is the explicit opt-in for
        sweeps that require a specific iteration order. If ``False``
        (default) the standard :func:`_validate_frequencies` checks
        run.

    Returns
    -------
    Engine
        A new :class:`Engine` instance — the receiver is **not**
        mutated.

    Examples
    --------
    >>> eng = Engine(backend="image").with_frequencies(50, 5000,
    ...                                                preserve_order=True)
    >>> eng.frequencies
    [50.0, 5000.0]
    """
    freqs = [float(f) for f in frequencies]
    # The scalar contract holds for *both* paths. Checking it here
    # as well as in the validator keeps the error attributable to
    # ``with_frequencies()`` rather than to a nested model rebuild.
    _check_frequency_values(freqs)
    data = self.model_dump()
    data["frequencies"] = freqs
    if preserve_order:
        # Re-validate the rest, but suppress the field validator's
        # monotone warning — a deliberately ordered sweep is the
        # documented opt-in.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", EngineFrequencyOrderWarning)
            return self.__class__.model_validate(data)
    # Default path: run the full field validation, including the
    # monotone-order warning. ``model_copy(update=...)`` would skip
    # every validator (pydantic v2 semantics), which is the
    # pre-0.14.1 defect. Re-emit any warning at the caller's frame
    # so the notebook line that built the engine is the one shown.
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        engine = self.__class__.model_validate(data)
    for entry in caught:
        warnings.warn(entry.message, entry.category, stacklevel=2)
    return engine

EngineFrequencyOrderWarning

Bases: UserWarning

Engine.frequencies is not strictly monotonically increasing.

A dedicated category for the monotonic-order warning emitted by Engine._validate_frequencies(). Using a dedicated class lets notebook authors silence the diagnostic with a stable warnings.simplefilter("once", EngineFrequencyOrderWarning) — the default UserWarning filter deduplicates by message text, and because the message embeds the offending list literal, every distinct non-monotonic list triggers a fresh warning even when the underlying convention is the same.

result

Result object of a simulation run.

A FieldResult is the unified return value of Engine.solve() and World.solve(). It contains:

  • electrode_potentials / electrode_currents — node values per frequency, used to derive input and transfer impedances.
  • point_sources — the discretised current distribution. The post-processing layer can use these to evaluate the potential at arbitrary field points (contour plots, profiles, touch and step voltages).
  • soil_resistivity and soil — provide the parameters needed to evaluate the appropriate Green's function (homogeneous or 2-layer) inside potential().
  • sources — the source snapshot of the solve, read by FieldResult.input_impedance(): the impressed current of every current source; the impressed voltage and the solved current of every voltage source.
  • metadata — the core keys every backend reports (see groundfield.solver.engine.CORE_METADATA_KEYS), including the provenance block, plus backend-specific keys.
Serialisation

model_dump_json / model_validate_json round-trip a result losslessly and produce standard JSON (no NaN / Infinity tokens). Values that JSON cannot express in metadata are written as single-key tagged objects and restored on validation:

  • {"$float": "inf" | "-inf" | "nan"} — non-finite float;
  • {"$complex": [re, im]} — complex number;
  • {"$tuple": [...]} — tuple;
  • {"$dict": [[key, value], ...]} — mapping with non-string keys (e.g. penetration_depth keyed by frequency) or with a key that looks like a tag;
  • {"$ndarray": {"dtype": ..., "shape": [...], "data": [...]}} — numpy array (bool, integer, float, complex or string dtype).

numpy scalars are stored as the equal Python scalar. The tag names are reserved: a metadata value that is a single-key mapping with one of the keys above is decoded on validation. The versioned file format around this JSON is groundfield.io.save_result() / groundfield.io.load_result().

The decoder reads only what the encoder writes, so a result file from an untrusted source cannot allocate more memory than a small multiple of its own size: $ndarray dtypes are limited to bool, integer, float16 … float64, complex64 / complex128 and unicode strings (no object, datetime, void, structured or sub-array dtypes); the shape must match the number of items before anything is allocated; every item must be a scalar of the dtype's kind; a string array may take at most 64 bytes per character of its items (plus 4 KiB); and metadata may nest at most MAX_METADATA_DEPTH levels. A tag that breaks these rules raises ValueError naming the metadata key (a pydantic.ValidationError when it is read through validation). The encoder applies the same limits, so every file it writes loads.

MAX_METADATA_DEPTH module-attribute

MAX_METADATA_DEPTH = 100

Deepest nesting of containers the metadata codec writes and reads.

Containers are lists, mappings, tuples and tagged objects.

FieldResult

Bases: BaseModel

Result of a field computation.

cluster_impedance

cluster_impedance(electrode_name: str) -> list[complex]

Grounding impedance of the galvanic cluster containing an electrode.

Definition: \(Z_{\text{cluster}}(f) = \varphi_{\text{cluster}}/\sum_{e \in c} I_e\). For a stand-alone electrode this is identical to grounding_impedance(). For connected electrodes it corresponds to the parallel combination of the individual grounding admittances.

Parameters:

Name Type Description Default
electrode_name str

Name of any electrode in the target cluster. The cluster members are looked up in clusters; if the electrode does not appear there it is treated as a stand-alone cluster [electrode_name].

required

Returns:

Type Description
list[complex]

Complex cluster impedance per frequency in ohms, one entry per entry in frequencies. Frequencies for which the summed cluster current is exactly zero return nan.

Raises:

Type Description
KeyError

If the resolved cluster is empty, or if none of its members carries potential and current data.

Notes

The cluster potential is the length-weighted (Galerkin) average over all members,

\[ \varphi_c \;=\; \frac{\sum_{e \in c} L_e\, \varphi_e} {\sum_{e \in c} L_e}, \qquad L_e = \sum_{k \in e} L_k , \]

with the per-electrode lengths taken from point_sources. Since every member potential \(\varphi_e\) is itself the length-weighted average over that electrode's segments, \(\varphi_c\) is exactly the length-weighted average over the whole cluster surface — the quantity the augmented system constrains to one value (see solver/image.py, block 1 of the multi-port system).

Up to 0.14.1 this method read members[0], i.e. the alphabetically first member name. Because the reported member potentials were unweighted segment means they did not agree with each other, so renaming an electrode changed the reported cluster impedance of an unchanged geometry (19.4393 Ω → 19.2314 Ω in the audit case, 2026-07-28, F11). With the weighted reduction the members agree to round-off for the image family and the result is invariant under renaming for every backend.

Numerator and denominator run over different member sets, deliberately:

  • \(\varphi_c\) averages over members that carry both potential and current data — a member with no potential cannot contribute a term to the average.
  • \(\sum_e I_e\) sums over every member that carries current data, whether or not its potential was stored, because its injected current is part of the cluster total regardless.

Every backend in this package populates both mappings for every member, so the two sets coincide in practice. They differ only for hand-built FieldResult instances, where restricting the current sum to the potential-carrying members would silently under-count the cluster current (audit 2026-07-29).

Source code in src/groundfield/solver/result.py
def cluster_impedance(self, electrode_name: str) -> list[complex]:
    """Grounding impedance of the galvanic cluster containing an electrode.

    Definition: $Z_{\\text{cluster}}(f) =
    \\varphi_{\\text{cluster}}/\\sum_{e \\in c} I_e$. For a
    stand-alone electrode this is identical to
    :meth:`grounding_impedance`. For connected electrodes it
    corresponds to the parallel combination of the individual
    grounding admittances.

    Parameters
    ----------
    electrode_name : str
        Name of any electrode in the target cluster. The cluster
        members are looked up in :attr:`clusters`; if the
        electrode does not appear there it is treated as a
        stand-alone cluster ``[electrode_name]``.

    Returns
    -------
    list[complex]
        Complex cluster impedance per frequency in ohms, one entry
        per entry in :attr:`frequencies`. Frequencies for which
        the summed cluster current is exactly zero return ``nan``.

    Raises
    ------
    KeyError
        If the resolved cluster is empty, or if none of its members
        carries potential *and* current data.

    Notes
    -----
    The cluster potential is the **length-weighted (Galerkin)
    average** over all members,

    .. math::
        \\varphi_c \\;=\\;
        \\frac{\\sum_{e \\in c} L_e\\, \\varphi_e}
              {\\sum_{e \\in c} L_e},
        \\qquad
        L_e = \\sum_{k \\in e} L_k ,

    with the per-electrode lengths taken from
    :attr:`point_sources`. Since every member potential
    :math:`\\varphi_e` is itself the length-weighted average over
    that electrode's segments, :math:`\\varphi_c` is exactly the
    length-weighted average over the whole cluster surface — the
    quantity the augmented system constrains to one value (see
    ``solver/image.py``, block 1 of the multi-port system).

    Up to 0.14.1 this method read ``members[0]``, i.e. the
    *alphabetically first* member name. Because the reported
    member potentials were unweighted segment means they did not
    agree with each other, so renaming an electrode changed the
    reported cluster impedance of an unchanged geometry (19.4393 Ω
    → 19.2314 Ω in the audit case, 2026-07-28, F11). With the
    weighted reduction the members agree to round-off for the
    image family and the result is invariant under renaming for
    every backend.

    Numerator and denominator run over **different** member sets,
    deliberately:

    * :math:`\\varphi_c` averages over members that carry *both*
      potential and current data — a member with no potential
      cannot contribute a term to the average.
    * :math:`\\sum_e I_e` sums over every member that carries
      current data, whether or not its potential was stored,
      because its injected current is part of the cluster total
      regardless.

    Every backend in this package populates both mappings for
    every member, so the two sets coincide in practice. They
    differ only for hand-built :class:`FieldResult` instances,
    where restricting the current sum to the potential-carrying
    members would silently under-count the cluster current
    (audit 2026-07-29).
    """
    members, u = self._cluster_potential(electrode_name)
    n_freq = len(u)
    # The *denominator* runs over every member that has current
    # data, not over ``usable``: a member without potential data
    # cannot contribute to the weighted average, but its injected
    # current is still part of the cluster's total. Restricting the
    # sum to ``usable`` (0.15.0 development state) silently dropped
    # it and returned a too-large impedance instead of the
    # ``KeyError`` v0.14.1 raised — e.g. potentials {"a"} with
    # currents {"a": 1 A, "b": 1 A} and cluster ["a", "b"] gave
    # 10 V / 1 A = 10 Ω where 10 V / 2 A = 5 Ω is meant
    # (audit 2026-07-29). Not reachable through any shipped
    # backend, but ``FieldResult`` is public and user-constructible.
    current_members = [
        m
        for m in members
        if m in self.electrode_currents
        and len(self.electrode_currents[m]) >= n_freq
    ]
    i_sum = [
        sum(self.electrode_currents[m][k] for m in current_members)
        for k in range(n_freq)
    ]
    return [
        (uk / ik) if ik != 0 else complex("nan")
        for uk, ik in zip(u, i_sum, strict=False)
    ]

grounding_impedance

grounding_impedance(electrode_name: str) -> list[complex]

Input impedance \(Z(f) = U/I\) of an electrode.

Parameters:

Name Type Description Default
electrode_name str

Name of the electrode whose input impedance is requested. Must be present in both electrode_potentials and electrode_currents.

required

Returns:

Type Description
list[complex]

Complex impedance per frequency in ohms, one entry per entry in frequencies. Frequencies for which the electrode current is exactly zero return nan.

Raises:

Type Description
KeyError

If electrode_name is unknown to the result.

Notes

For galvanically connected electrodes (cluster with more than one member) this quantity is the cluster potential divided by the electrode's share of the total current. The physically meaningful quantity is the cluster impedance (see cluster_impedance()).

Source code in src/groundfield/solver/result.py
def grounding_impedance(self, electrode_name: str) -> list[complex]:
    """Input impedance $Z(f) = U/I$ of an electrode.

    Parameters
    ----------
    electrode_name : str
        Name of the electrode whose input impedance is requested.
        Must be present in both :attr:`electrode_potentials` and
        :attr:`electrode_currents`.

    Returns
    -------
    list[complex]
        Complex impedance per frequency in ohms, one entry per
        entry in :attr:`frequencies`. Frequencies for which the
        electrode current is exactly zero return ``nan``.

    Raises
    ------
    KeyError
        If ``electrode_name`` is unknown to the result.

    Notes
    -----
    For galvanically connected electrodes (cluster with more than
    one member) this quantity is the cluster potential divided by
    the electrode's share of the total current. The physically
    meaningful quantity is the **cluster impedance** (see
    :meth:`cluster_impedance`).
    """
    if electrode_name not in self.electrode_potentials:
        raise KeyError(f"No potential data for '{electrode_name}'.")
    if electrode_name not in self.electrode_currents:
        raise KeyError(f"No current data for '{electrode_name}'.")
    u = self.electrode_potentials[electrode_name]
    i = self.electrode_currents[electrode_name]
    return [
        (uk / ik) if ik != 0 else complex("nan")
        for uk, ik in zip(u, i, strict=False)
    ]

input_impedance

input_impedance(source: str | None = None) -> list[complex]

Driving-point impedance seen by a source.

Definition:

\[ Z_\text{in}(f) \;=\; \frac{\varphi_a(f) - \varphi_r(f)}{I_s(f)}, \]

with \(\varphi_a\) the potential of the galvanic cluster the source feeds (attached_to), \(\varphi_r\) the potential of the return cluster (return_to; zero for a return through remote earth) and \(I_s\) the source current. Cluster potentials are the length-weighted averages used by cluster_impedance().

  • Current source: \(I_s\) is the impressed current.
  • Voltage source (since 2026.11): the solve fixes \(\varphi_a - \varphi_r = U - Z_q I_s\), so \(Z_\text{in} = U / I_s - Z_q\) with the impressed voltage \(U\), the solved source current \(I_s\) and the internal impedance \(Z_q = R + j\omega L\) of the source (SourceRecord.voltage, SourceRecord.current, SourceRecord.internal_impedance()). It is the impedance the source sees at its terminals, without its own \(Z_q\) (the current is \(U / (Z_q + Z_\text{in})\)). For a world with this one source it equals the impedance a 1 A current source at the same terminals reports, to round-off; with several sources it is an apparent impedance (see Notes).

This is the impedance a measurement instrument or a fault sees at the feeding point. It differs from cluster_impedance() (cluster potential over the cluster's own leakage current) as soon as part of the injected current leaves the cluster through conductors (PEN, cable shields, measurement leads): then the cluster impedance describes the local electrode only, the input impedance the whole connected system.

Parameters:

Name Type Description Default
source str | None

Name of the source. May be omitted when the result carries exactly one source.

None

Returns:

Type Description
list[complex]

Complex input impedance per frequency in ohms. Frequencies with zero source current return nan.

Raises:

Type Description
ValueError

If the result carries no source snapshot (hand-built results), no source, or several sources and source is omitted; if the record of a voltage source carries no solved current (a backend that does not report it).

KeyError

If source is unknown, or the feeding / return electrode has no potential data in this result.

Notes

With several simultaneous sources the potential difference includes the contribution of the other sources, so the ratio is an apparent impedance of the named source. Two 230 V sources on two 3 m rods 5 m apart (100 Ω·m, image) report 38.90 Ω each, against 35.99 Ω of the 1 A solve of one rod (+8.1 %).

Source code in src/groundfield/solver/result.py
def input_impedance(self, source: str | None = None) -> list[complex]:
    """Driving-point impedance seen by a source.

    Definition:

    $$
    Z_\\text{in}(f) \\;=\\;
    \\frac{\\varphi_a(f) - \\varphi_r(f)}{I_s(f)},
    $$

    with $\\varphi_a$ the potential of the galvanic cluster the
    source feeds (``attached_to``), $\\varphi_r$ the potential of
    the return cluster (``return_to``; zero for a return through
    remote earth) and $I_s$ the source current. Cluster potentials
    are the length-weighted averages used by
    :meth:`cluster_impedance`.

    * **Current source:** $I_s$ is the impressed current.
    * **Voltage source** (since 2026.11): the solve fixes
      $\\varphi_a - \\varphi_r = U - Z_q I_s$, so
      $Z_\\text{in} = U / I_s - Z_q$ with the impressed voltage $U$,
      the solved source current $I_s$ and the internal impedance
      $Z_q = R + j\\omega L$ of the source
      (:attr:`SourceRecord.voltage`, :attr:`SourceRecord.current`,
      :meth:`SourceRecord.internal_impedance`). It is the impedance
      the source sees at its terminals, **without** its own $Z_q$
      (the current is $U / (Z_q + Z_\\text{in})$). For a world with
      this one source it equals the impedance a 1 A current source
      at the same terminals reports, to round-off; with several
      sources it is an apparent impedance (see *Notes*).

    This is the impedance a measurement instrument or a fault sees
    at the feeding point. It differs from :meth:`cluster_impedance`
    (cluster potential over the cluster's own *leakage* current)
    as soon as part of the injected current leaves the cluster
    through conductors (PEN, cable shields, measurement leads):
    then the cluster impedance describes the local electrode only,
    the input impedance the whole connected system.

    Parameters
    ----------
    source
        Name of the source. May be omitted when the result carries
        exactly one source.

    Returns
    -------
    list[complex]
        Complex input impedance per frequency in ohms. Frequencies
        with zero source current return ``nan``.

    Raises
    ------
    ValueError
        If the result carries no source snapshot (hand-built
        results), no source, or several sources and ``source`` is
        omitted; if the record of a voltage source carries no solved
        current (a backend that does not report it).
    KeyError
        If ``source`` is unknown, or the feeding / return electrode
        has no potential data in this result.

    Notes
    -----
    With several simultaneous sources the potential difference
    includes the contribution of the other sources, so the ratio is
    an *apparent* impedance of the named source. Two 230 V sources
    on two 3 m rods 5 m apart (100 Ω·m, ``image``) report 38.90 Ω
    each, against 35.99 Ω of the 1 A solve of one rod (+8.1 %).
    """
    if not self.sources:
        raise ValueError(
            "input_impedance needs the source snapshot of the solve; "
            "this result carries none (hand-built FieldResult?)."
        )
    candidates = [s for s in self.sources if s.kind in _SOURCE_KINDS]
    if source is None:
        if not candidates:
            raise ValueError("The result carries no current source.")
        if len(candidates) > 1:
            kinds = {s.kind for s in candidates}
            label = f"{kinds.pop()} sources" if len(kinds) == 1 else "sources"
            names = ", ".join(s.name for s in candidates)
            raise ValueError(
                f"The result carries several {label} ({names}); pass source=<name>."
            )
        record = candidates[0]
    else:
        by_name = {s.name: s for s in self.sources}
        if source not in by_name:
            known = ", ".join(sorted(by_name)) or "none"
            raise KeyError(f"Unknown source {source!r} (known: {known}).")
        record = by_name[source]
        if record.kind not in _SOURCE_KINDS:
            raise ValueError(
                f"Source {source!r} is a {record.kind!r} source; the input "
                "impedance is defined for current and voltage sources."
            )
    if record.kind == "voltage":
        n_freq = len(self.frequencies)
        if len(record.current) != n_freq or len(record.voltage) != n_freq:
            raise ValueError(
                f"Voltage source {record.name!r}: the result carries no "
                "solved source current (the backend did not report it), "
                f"or not one per frequency ({len(record.current)} currents, "
                f"{len(record.voltage)} voltages, {n_freq} frequencies)."
            )
        z_in = [
            u / i if i != 0 else complex("nan")
            for u, i in zip(record.voltage, record.current, strict=True)
        ]
        if record.internal_resistance_ohm or record.internal_inductance_h:
            # The impedance seen by the source, without its own Z_q.
            z_in = [
                z - record.internal_impedance(f)
                for z, f in zip(z_in, self.frequencies, strict=True)
            ]
        return z_in
    u_a = self._terminal_potential(record.name, "feeds", record.attached_to)
    if record.return_to is None:
        u_r = [0j] * len(u_a)
    else:
        u_r = self._terminal_potential(record.name, "returns to", record.return_to)
    return [
        (ua - ur) / ik if ik != 0 else complex("nan")
        for ua, ur, ik in zip(u_a, u_r, record.current, strict=False)
    ]

potential

potential(points: ndarray, frequency_index: int = 0, min_distance: float = 0.001) -> np.ndarray

Evaluate the potential at field points (image-charge sum).

Picks the appropriate Green's-function kernel automatically:

  • homogeneous (HomogeneousSoil or no self.soil set but soil_resistivity available): classic image-charge sum \(1/r + 1/r_{\text{img}}\).
  • 2-layer (TwoLayerSoil, or MultiLayerSoil with exactly two layers): Tagg/Sunde series truncated with the controls of the solve, metadata["series"] (the engine's image_max_terms and image_series_tol; defaults 300 and 1e-6 for results without the record).
  • 1-layer (MultiLayerSoil with a single layer): degenerate case, dispatched to the homogeneous kernel.

The dispatch reads the canonical layer stack of self.soil (adjacent layers of one resistivity merged, review pass 10, 10.48): TwoLayerSoil(rho, rho, h) and a MultiLayerSoil of one resistivity are evaluated like homogeneous soil, exactly as they are solved (before audit A3S-04 their sources below h took the point form of the two-layer kernel, +2.7 % next to a rod), and a MultiLayerSoil with at most two distinct layers like the two-layer soil.

Parameters:

Name Type Description Default
points ndarray

Field points, array of shape (M, 3) in metres.

required
frequency_index int

Index into frequencies. Default 0.

0
min_distance float

Numerical cutoff for 1/r singularities, in metres.

0.001

Returns:

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

Complex potential in V.

Warns:

Type Description
SeriesTruncationWarning

If the two-layer series reaches max_terms before its tail bound falls below tol.

Raises:

Type Description
NotImplementedError

If self.soil is a MultiLayerSoil with three or more distinct layers. The post-solve potential path does not yet carry an n-layer Green's-function kernel. The solve itself is still correct via the cim / mom_sommerfeld / bem backends — only the explicit potential() evaluation is unavailable for n ≥ 3. Cluster impedances, electrode currents and potentials stored in electrode_potentials / cluster_impedance remain accessible.

Notes

Prior to 0.2.0 a MultiLayerSoil with n ≥ 3 silently fell through to the homogeneous kernel, returning incorrect potentials, profiles, touch / step voltages and VTK exports. The error is now raised explicitly so the regime is visible rather than silent.

Point sources at projected (UTM) coordinates, beyond 10 km from the origin, are evaluated in a local frame: points and sources are shifted by the rounded centre of the sources' bounding box (exact for nearby doubles) before the kernel runs (since 2026.11; see Units and conventions in the reference).

Source code in src/groundfield/solver/result.py
def potential(
    self,
    points: np.ndarray,
    frequency_index: int = 0,
    min_distance: float = 1e-3,
) -> np.ndarray:
    """Evaluate the potential at field points (image-charge sum).

    Picks the appropriate Green's-function kernel automatically:

    - **homogeneous** (:class:`HomogeneousSoil` or no ``self.soil``
      set but ``soil_resistivity`` available): classic image-charge
      sum $1/r + 1/r_{\\text{img}}$.
    - **2-layer** (:class:`TwoLayerSoil`, or :class:`MultiLayerSoil`
      with exactly two layers): Tagg/Sunde series truncated with the
      controls of the solve, ``metadata["series"]`` (the engine's
      ``image_max_terms`` and ``image_series_tol``; defaults 300 and
      ``1e-6`` for results without the record).
    - **1-layer** (:class:`MultiLayerSoil` with a single layer):
      degenerate case, dispatched to the homogeneous kernel.

    The dispatch reads the canonical layer stack of ``self.soil``
    (adjacent layers of one resistivity merged, review pass 10,
    10.48): ``TwoLayerSoil(rho, rho, h)`` and a ``MultiLayerSoil`` of
    one resistivity are evaluated like homogeneous soil, exactly as
    they are solved (before audit A3S-04 their sources below ``h``
    took the point form of the two-layer kernel, +2.7 % next to a
    rod), and a ``MultiLayerSoil`` with at most two distinct layers
    like the two-layer soil.

    Parameters
    ----------
    points
        Field points, array of shape ``(M, 3)`` in metres.
    frequency_index
        Index into :attr:`frequencies`. Default 0.
    min_distance
        Numerical cutoff for 1/r singularities, in metres.

    Returns
    -------
    phi : np.ndarray, shape (M,)
        Complex potential in V.

    Warns
    -----
    SeriesTruncationWarning
        If the two-layer series reaches ``max_terms`` before its tail
        bound falls below ``tol``.

    Raises
    ------
    NotImplementedError
        If ``self.soil`` is a :class:`MultiLayerSoil` with three or
        more distinct layers. The post-solve potential path does not yet
        carry an n-layer Green's-function kernel. The solve itself
        is still correct via the ``cim`` / ``mom_sommerfeld`` /
        ``bem`` backends — only the explicit
        :meth:`potential` evaluation is unavailable for n ≥ 3.
        Cluster impedances, electrode currents and potentials
        stored in :attr:`electrode_potentials` /
        :attr:`cluster_impedance` remain accessible.

    Notes
    -----
    Prior to 0.2.0 a :class:`MultiLayerSoil` with n ≥ 3 silently
    fell through to the homogeneous kernel, returning incorrect
    potentials, profiles, touch / step voltages and VTK exports.
    The error is now raised explicitly so the regime is visible
    rather than silent.

    Point sources at projected (UTM) coordinates, beyond 10 km from
    the origin, are evaluated in a local frame: points and sources are
    shifted by the rounded centre of the sources' bounding box (exact
    for nearby doubles) before the kernel runs (since 2026.11; see
    *Units and conventions* in the reference).
    """
    if not self.point_sources:
        raise RuntimeError(
            "FieldResult has no point_sources — the backend did not "
            "populate the post-processing data (stub?)."
        )

    pts = np.asarray(points, dtype=float)
    if pts.ndim == 1:
        pts = pts[None, :]
    if pts.shape[1] != 3:
        raise ValueError(f"points must have shape (M, 3), got {pts.shape}.")

    sources, all_currents = self._point_source_arrays()
    # Contiguous, as before the cache: the real/imaginary views then
    # have the stride the BLAS calls of v0.15.0 saw.
    currents = np.ascontiguousarray(all_currents[:, frequency_index])
    line = self._line_sources()
    # Sources at projected (UTM) coordinates: evaluate in a local frame
    # of the sources, exactly shifted (2026.11, see solver._frame); a
    # result within 10 km of the origin is evaluated as before.
    from groundfield.solver._frame import points_origin

    origin = points_origin(sources)
    if origin is not None:
        pts = pts - origin
        sources = sources - origin
        if line is not None:
            from groundfield.solver._line_kernel import LineSegments

            line = LineSegments(
                line.mid - origin, line.length, line.tangent, line.radius
            )

    # Dispatch to the kernel that matches the effective number of
    # soil layers: that of the canonical layer stack, the soil the
    # backends actually solve (review pass 10, 10.48). A
    # ``TwoLayerSoil(rho, rho, h)`` or a ``MultiLayerSoil`` of one
    # resistivity is homogeneous soil — its sources below h took the
    # point form of the two-layer spectral kernel here instead of the
    # line sources of the homogeneous result (+2.7 % next to a rod,
    # audit A3S-04); a ``MultiLayerSoil`` with one or two distinct
    # layers is cast on the fly. For n ≥ 3 there is no closed-form
    # image-charge series (Γ_1(λ) is no longer constant in λ — see
    # ``solver/image_nlayer.py``), so the call is rejected explicitly
    # rather than silently falling back to the homogeneous kernel.
    soil = self.soil
    if soil is not None and not isinstance(soil, HomogeneousSoil):
        from groundfield.solver._layered import canonical_soil

        soil = canonical_soil(soil)
    if isinstance(soil, TwoLayerSoil):
        return self._potential_two_layer(
            pts, sources, currents, soil, min_distance, line=line
        )
    if isinstance(soil, MultiLayerSoil):
        n = len(soil.layers)
        raise NotImplementedError(
            f"FieldResult.potential: MultiLayerSoil with n={n} ≥ 3 "
            "layers is not supported on the post-solve potential "
            "path. The solve itself is correct (use the "
            "'mom_sommerfeld' or 'fem' backend), but a closed-form "
            "n-layer Green's-function kernel is not yet wired into "
            "FieldResult.potential. Access cluster impedances and "
            "electrode potentials directly via "
            "result.electrode_potentials / result.cluster_impedance "
            "instead, or reduce the soil model to "
            "TwoLayerSoil / HomogeneousSoil for explicit field "
            "evaluation."
        )
    if isinstance(soil, HomogeneousSoil) and soil is not self.soil:
        # A layered declaration of one resistivity (see above).
        return self._potential_homogeneous(
            pts,
            sources,
            currents,
            min_distance,
            rho_override=float(soil.rho),
            line=line,
        )
    return self._potential_homogeneous(
        pts, sources, currents, min_distance, line=line
    )

summary

summary() -> str

Compact one-line description of the result.

Returns:

Type Description
str

Human-readable summary listing the backend name, the number of frequencies, the number of electrodes for which potentials were stored and the number of discretised point sources. Intended for logging and notebook output; the format is informational and not stable across versions.

Source code in src/groundfield/solver/result.py
def summary(self) -> str:
    """Compact one-line description of the result.

    Returns
    -------
    str
        Human-readable summary listing the backend name, the
        number of frequencies, the number of electrodes for which
        potentials were stored and the number of discretised
        point sources. Intended for logging and notebook output;
        the format is informational and not stable across
        versions.
    """
    return (
        f"FieldResult(backend='{self.backend}', "
        f"n_freq={len(self.frequencies)}, "
        f"n_electrodes={len(self.electrode_potentials)}, "
        f"n_segments={len(self.point_sources)})"
    )

to_dataframe

to_dataframe(table: str = 'electrodes') -> pd.DataFrame

Tidy table of the result, one row per frequency and object.

Parameters:

Name Type Description Default
table str

"electrodes" (default): one row per frequency and electrode with the columns

  • frequency_hz — frequency in Hz;
  • electrode — electrode name;
  • cluster — galvanic cluster, labelled by its alphabetically first member (see clusters);
  • potential_v — electrode potential in V (complex);
  • current_a — leakage current of the electrode into the soil in A (complex);
  • cluster_impedance_ohm — cluster_impedance() of the electrode's cluster in Ω (complex), the cluster potential over the cluster's own leakage current.

"sources": one row per frequency and recorded source with frequency_hz, source, kind, attached_to, return_to, current_a (source current in A, complex: impressed, or solved for a voltage source), voltage_v (impressed voltage in V of a voltage source, complex; nan for a current source), internal_resistance_ohm and internal_inductance_h (internal impedance of a voltage source in Ω and H, float; nan for a current source) and input_impedance_ohm (input_impedance() in Ω, complex), the impedance seen at the feeding point (without the internal impedance).

'electrodes'

Returns:

Type Description
DataFrame

The table; rows ordered by frequency, then by electrode / source in result order. Values that the result does not carry (hand-built results) are nan.

Raises:

Type Description
ValueError

If table is not "electrodes" or "sources".

ImportError

If pandas is not installed (it is imported on first use).

Examples:

>>> df = result.to_dataframe()
>>> df.pivot(index="frequency_hz", columns="electrode",
...          values="potential_v").abs()
Source code in src/groundfield/solver/result.py
def to_dataframe(self, table: str = "electrodes") -> pd.DataFrame:
    """Tidy table of the result, one row per frequency and object.

    Parameters
    ----------
    table
        ``"electrodes"`` (default): one row per frequency and
        electrode with the columns

        * ``frequency_hz`` — frequency in Hz;
        * ``electrode`` — electrode name;
        * ``cluster`` — galvanic cluster, labelled by its
          alphabetically first member (see :attr:`clusters`);
        * ``potential_v`` — electrode potential in V (complex);
        * ``current_a`` — leakage current of the electrode into the
          soil in A (complex);
        * ``cluster_impedance_ohm`` — :meth:`cluster_impedance` of
          the electrode's cluster in Ω (complex), the cluster
          potential over the cluster's own leakage current.

        ``"sources"``: one row per frequency and recorded source
        with ``frequency_hz``, ``source``, ``kind``,
        ``attached_to``, ``return_to``, ``current_a`` (source
        current in A, complex: impressed, or solved for a voltage
        source), ``voltage_v`` (impressed voltage in V of a voltage
        source, complex; ``nan`` for a current source),
        ``internal_resistance_ohm`` and ``internal_inductance_h``
        (internal impedance of a voltage source in Ω and H, float;
        ``nan`` for a current source) and ``input_impedance_ohm``
        (:meth:`input_impedance` in Ω, complex), the impedance seen
        at the feeding point (without the internal impedance).

    Returns
    -------
    pandas.DataFrame
        The table; rows ordered by frequency, then by electrode /
        source in result order. Values that the result does not
        carry (hand-built results) are ``nan``.

    Raises
    ------
    ValueError
        If ``table`` is not ``"electrodes"`` or ``"sources"``.
    ImportError
        If pandas is not installed (it is imported on first use).

    Examples
    --------
    >>> df = result.to_dataframe()                       # doctest: +SKIP
    >>> df.pivot(index="frequency_hz", columns="electrode",
    ...          values="potential_v").abs()             # doctest: +SKIP
    """
    if table not in ("electrodes", "sources"):
        raise ValueError(
            f"Unknown table {table!r}; choose 'electrodes' or 'sources'."
        )
    try:
        import pandas as pd
    except ImportError as exc:  # pragma: no cover - pandas is a dependency
        raise ImportError(
            "FieldResult.to_dataframe needs pandas (pip install pandas)."
        ) from exc
    if table == "sources":
        return self._source_frame(pd)
    return self._electrode_frame(pd)

PointSource

Bases: BaseModel

A discretised current source (segment midpoint, length, direction).

Filled by the backend; not instantiated directly by the user. With the point kernel the current sits at position; with the line kernel (FieldResult.metadata["kernel"] == "line") it is spread uniformly along the segment given by length and direction.

SourceRecord

Bases: BaseModel

Snapshot of one source as it was solved.

Filled by Engine.solve() (and, for a world with voltage sources, by the backend); not instantiated directly by the user. FieldResult.input_impedance() reads it, so the result stays self-contained after the world has changed.

For a current source current is the impressed current and voltage is empty. For a voltage source voltage is the impressed voltage \(U\) and current the source current \(I\) the solve returned — the current the source drives into attached_to (and takes back from return_to), the same sign convention as a current source; internal_resistance_ohm and internal_inductance_h are its internal impedance \(Z_q = R + j\omega L\) (0 for an ideal source and for current sources), so the terminal voltage is \(U - Z_q I\).

A record pickled before 2026.11 lacks the two fields of the internal impedance and unpickles with 0 / 0, as its JSON loads (audit W2R2-01).

internal_impedance

internal_impedance(frequency: float) -> complex

Internal impedance \(Z_q = R + j\omega L\) in Ω at frequency (Hz).

0j for a current source and an ideal voltage source.

Source code in src/groundfield/solver/result.py
def internal_impedance(self, frequency: float) -> complex:
    """Internal impedance $Z_q = R + j\\omega L$ in Ω at ``frequency`` (Hz).

    ``0j`` for a current source and an ideal voltage source.
    """
    return _internal_impedance(
        self.internal_resistance_ohm,
        self.internal_inductance_h,
        2.0 * np.pi * float(frequency),
    )

solve_provenance

solve_provenance(world: World, engine: Engine) -> dict[str, Any]

Provenance block of a solve (without the timestamp).

Engine.solve calls this before the backend runs and adds solved_at_utc when it returns; the block is stored as FieldResult.metadata["provenance"].

Parameters:

Name Type Description Default
world World

The world as built by the caller.

required
engine Engine

The engine configuration.

required

Returns:

Type Description
dict

groundfield_version, python, numpy, scipy, pydantic, platform, engine (the JSON dump of the engine) and world_fingerprint (see world_fingerprint()).

Source code in src/groundfield/solver/result.py
def solve_provenance(world: World, engine: Engine) -> dict[str, Any]:
    """Provenance block of a solve (without the timestamp).

    :meth:`Engine.solve <groundfield.solver.engine.Engine.solve>` calls
    this before the backend runs and adds ``solved_at_utc`` when it
    returns; the block is stored as ``FieldResult.metadata["provenance"]``.

    Parameters
    ----------
    world
        The world as built by the caller.
    engine
        The engine configuration.

    Returns
    -------
    dict
        ``groundfield_version``, ``python``, ``numpy``, ``scipy``,
        ``pydantic``, ``platform``, ``engine`` (the JSON dump of the
        engine) and ``world_fingerprint`` (see :func:`world_fingerprint`).
    """
    block: dict[str, Any] = dict(_environment())
    block["engine"] = engine.model_dump(mode="json")
    block["world_fingerprint"] = world_fingerprint(world)
    return block

world_fingerprint

world_fingerprint(world: World) -> str

SHA-256 fingerprint of the canonical JSON of a world.

The canonical form is json.dumps(world.model_dump(mode="json"), sort_keys=True, separators=(",", ":")). Pydantic writes floats in their shortest round-trip form, so equal worlds give equal fingerprints, also after a JSON round trip of the world. The fingerprint depends on the world schema of the installed version: renamed or added model fields change it.

Parameters:

Name Type Description Default
world World

The world to fingerprint.

required

Returns:

Type Description
str

"sha256:" followed by 64 hexadecimal digits.

Source code in src/groundfield/solver/result.py
def world_fingerprint(world: World) -> str:
    """SHA-256 fingerprint of the canonical JSON of a world.

    The canonical form is ``json.dumps(world.model_dump(mode="json"),
    sort_keys=True, separators=(",", ":"))``. Pydantic writes floats in
    their shortest round-trip form, so equal worlds give equal
    fingerprints, also after a JSON round trip of the world. The
    fingerprint depends on the world schema of the installed version:
    renamed or added model fields change it.

    Parameters
    ----------
    world
        The world to fingerprint.

    Returns
    -------
    str
        ``"sha256:"`` followed by 64 hexadecimal digits.
    """
    canonical = json.dumps(
        world.model_dump(mode="json"), sort_keys=True, separators=(",", ":")
    )
    return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()

mutual

Mutual grounding-impedance matrix and field matrix in one assembly.

solve_mutual_matrix() computes the full nG × nG mutual grounding-impedance matrix Z_G of a set of grounding clusters ("gnodes"), solve_mutual_field() the potential at arbitrary points per unit excitation, each in one matrix assembly instead of one Engine.solve per excitation.

Motivation

The AP1 catalogue builds Z_G for every site and soil. The historic loop (one world per excitation, cluster_impedance on the diagonal, FieldResult.potential at a probe point off the diagonal) assembled the N × N segment reaction matrix nG times. Here:

  1. The segment reaction matrix is assembled once, directly (the kernel operators' matrix method; v0.15.0 applied the kernel to an N × N identity, one O(N³) product per image term — review pass 10, 10.59), including the ADR-0012 V2 concrete shell.
  2. The leakage distribution of every excitation is a solve of the same augmented nodal system as Engine.solve(), with one owner per straight wire of an electrode (a wire line of a grid, an arm of a star, an edge of a polyline; user decision Q30) and per soil layer for electrodes through the layer interface (10.15).
  3. The off-diagonal entries are either the reaction of the leakage columns (offdiag="galerkin", the default, no further kernel evaluation) or the probe-point potentials (offdiag="probe", one probe kernel for all columns).

Discretisation, topology and the branch block come from the shared image-family pipeline (groundfield.solver._pipeline); only the image family is accepted (10.34).

Consistency with Engine.solve

The diagonal equals FieldResult.cluster_impedance() of a per-excitation solve with the same engine to round-off (10.26), probe off-diagonals equal FieldResult.potential() at the probe point, and the columns of solve_mutual_field() equal FieldResult.potential at the field points (tests/test_mutual_matrix.py, tests/test_mutual_field.py).

OffDiagonal module-attribute

OffDiagonal = Literal['probe', 'galerkin']

Off-diagonal definitions of solve_mutual_matrix() (10.34).

"galerkin" (the default since 2026.11): the reaction of the leakage distributions, reciprocal; "probe": the potential at one probe point per cluster, the definition up to 0.15.0.

ProbePointsIgnoredWarning

Bases: UserWarning

solve_mutual_matrix was given probe points it does not use.

Since the user decision Q15 of 2026.11 the off-diagonal of solve_mutual_matrix() is offdiag="galerkin" whatever the call. Up to 0.15.0 passing probe_points selected the potential at those points as the off-diagonal; such a call now returns the galerkin matrix, ignores the points and emits this warning. Pass offdiag="probe" to keep the 0.15.0 definition, or drop the probe points.

solve_mutual_field

solve_mutual_field(world: 'World', engine: 'Engine', anchors: list[str], field_points: ndarray, *, frequency_index: int = 0, matrix_min_distance: float = 0.001, matrix_max_terms: int | None = None, matrix_tol: float | None = None) -> np.ndarray

Galvanic Green-function matrix: potential at arbitrary field points per node.

Returns R of shape (M, nG) with R[i, j] = potential at field_points[i] (x, y, depth) under unit current (1 A) injected into anchors[j] while all other clusters stay floating. This is the off-diagonal field evaluation of solve_mutual_matrix(), generalised to an arbitrary number of field points (decoupled from nG) and without the self/diagonal term — the building block for the frequency-dependent surface-potential distribution by superposition::

phi(field_points, f) = R @ I_leak(f)

with I_leak(f) = Y_G @ u(f) from the reduced network (Y_L(f) + Y_G) u = i. Uses the same one-shot assembly as solve_mutual_matrix() (reaction matrix and per-excitation leakage columns built once); only the field-point evaluation is generalised. The expensive 3D part is therefore frequency-independent and computed once, so a frequency sweep over I_leak(f) is cheap.

world must already carry all nG grounding clusters (every anchor in anchors must be a real electrode in world) and the soil model. Any current source is ignored — the excitations are applied internally, one cluster at a time, exactly as the historic per-excitation loop did.

Parameters:

Name Type Description Default
world 'World'

Assembled world holding all nG grounding clusters and the soil model. Sources, if any, are ignored.

required
engine 'Engine'

Engine configuration. segment_length controls the discretisation; frequencies selects the solved frequency via frequency_index; image_max_terms / image_series_tol feed the 2-layer self-kernel (the reaction-matrix assembly), exactly as Engine.solve would.

required
anchors list[str]

Length-nG list of electrode names, one per node. Anchor j receives the unit current of excitation j and fills column j of R.

required
field_points ndarray

(M, 3) array of (x, y, depth) evaluation points, decoupled from nG: M may differ from nG and the points are arbitrary (surface or buried). Row i becomes row i of R.

required
frequency_index int

Index into engine.frequencies. Default 0. Only relevant when distributed conductors make the assembled system frequency-dependent.

0
matrix_min_distance float

Clamp distance in m and series controls of the field evaluation. None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001
matrix_max_terms float

Clamp distance in m and series controls of the field evaluation. None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001
matrix_tol float

Clamp distance in m and series controls of the field evaluation. None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001

Returns:

Name Type Description
R (ndarray, shape(M, nG), complex)

Galvanic Green-function matrix; R[i, j] is the potential at field_points[i] under unit excitation of cluster j.

Raises:

Type Description
ValueError

If world has no soil model, holds no electrodes, or field_points does not have shape (M, 3).

KeyError

If an entry of anchors is not an electrode in world.

NotImplementedError

If the soil is a MultiLayerSoil with three or more layers (only homogeneous and 2-layer soils are supported).

TypeError

If the soil model type is not supported.

See Also

solve_mutual_matrix : Full nG × nG mutual grounding-impedance matrix.

Source code in src/groundfield/solver/mutual.py
def solve_mutual_field(
    world: "World",
    engine: "Engine",
    anchors: list[str],
    field_points: np.ndarray,
    *,
    frequency_index: int = 0,
    matrix_min_distance: float = 1e-3,
    matrix_max_terms: int | None = None,
    matrix_tol: float | None = None,
) -> np.ndarray:
    """Galvanic Green-function matrix: potential at arbitrary field points per node.

    Returns ``R`` of shape ``(M, nG)`` with ``R[i, j]`` = potential at
    ``field_points[i]`` (``x, y, depth``) under unit current (1 A) injected
    into ``anchors[j]`` while all other clusters stay floating. This is the
    off-diagonal field evaluation of :func:`solve_mutual_matrix`, generalised
    to an **arbitrary** number of field points (decoupled from ``nG``) and
    without the self/diagonal term — the building block for the
    frequency-dependent surface-potential distribution by superposition::

        phi(field_points, f) = R @ I_leak(f)

    with ``I_leak(f) = Y_G @ u(f)`` from the reduced network
    ``(Y_L(f) + Y_G) u = i``. Uses the same one-shot assembly as
    :func:`solve_mutual_matrix` (reaction matrix and per-excitation leakage
    columns built once); only the field-point evaluation is generalised. The
    expensive 3D part is therefore frequency-independent and computed once, so
    a frequency sweep over ``I_leak(f)`` is cheap.

    ``world`` must already carry **all** ``nG`` grounding clusters (every
    anchor in ``anchors`` must be a real electrode in ``world``) and the soil
    model. Any current source is ignored — the excitations are applied
    internally, one cluster at a time, exactly as the historic per-excitation
    loop did.

    Parameters
    ----------
    world
        Assembled world holding all ``nG`` grounding clusters and the soil
        model. Sources, if any, are ignored.
    engine
        Engine configuration. ``segment_length`` controls the
        discretisation; ``frequencies`` selects the solved frequency via
        ``frequency_index``; ``image_max_terms`` / ``image_series_tol`` feed
        the 2-layer **self**-kernel (the reaction-matrix assembly), exactly
        as ``Engine.solve`` would.
    anchors
        Length-``nG`` list of electrode names, one per node. Anchor ``j``
        receives the unit current of excitation ``j`` and fills column ``j``
        of ``R``.
    field_points
        ``(M, 3)`` array of ``(x, y, depth)`` evaluation points, decoupled
        from ``nG``: ``M`` may differ from ``nG`` and the points are
        arbitrary (surface or buried). Row ``i`` becomes row ``i`` of ``R``.
    frequency_index
        Index into ``engine.frequencies``. Default 0. Only relevant when
        distributed conductors make the assembled system
        frequency-dependent.
    matrix_min_distance, matrix_max_terms, matrix_tol
        Clamp distance in m and series controls of the field evaluation.
        ``None`` (default) for the series controls takes
        ``engine.image_max_terms`` / ``engine.image_series_tol``, the
        controls :meth:`FieldResult.potential` uses after a solve with the
        same engine (before 2026.11 they were hard-coded to 100 /
        ``1e-6``, review pass 10, 10.25).

    Returns
    -------
    R : np.ndarray, shape (M, nG), complex
        Galvanic Green-function matrix; ``R[i, j]`` is the potential at
        ``field_points[i]`` under unit excitation of cluster ``j``.

    Raises
    ------
    ValueError
        If ``world`` has no soil model, holds no electrodes, or
        ``field_points`` does not have shape ``(M, 3)``.
    KeyError
        If an entry of ``anchors`` is not an electrode in ``world``.
    NotImplementedError
        If the soil is a ``MultiLayerSoil`` with three or more layers
        (only homogeneous and 2-layer soils are supported).
    TypeError
        If the soil model type is not supported.

    See Also
    --------
    solve_mutual_matrix : Full ``nG × nG`` mutual grounding-impedance matrix.
    """
    if world.soil is None:
        raise ValueError("World has no soil model.")
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")

    nG = len(anchors)
    field_points = np.asarray(field_points, dtype=float)
    if field_points.ndim != 2 or field_points.shape[1] != 3:
        raise ValueError(
            f"field_points must have shape (M, 3), got {field_points.shape}."
        )

    problem = _prepare(world, engine, frequency_index, where="solve_mutual_field")
    n_segments = len(problem.disc.segments)

    # Per-excitation leakage columns T (no diagonal/self term needed).
    T = np.zeros((n_segments, nG), dtype=complex)
    for j, (_, sc) in enumerate(_unit_excitations(world, problem, list(anchors))):
        T[:, j] = sc

    # Potential at the M field points per excitation (nG) — one kernel pass.
    return _field_of_columns(
        problem,
        field_points,
        T,
        min_distance=matrix_min_distance,
        max_terms=matrix_max_terms,
        tol=matrix_tol,
    )

solve_mutual_matrix

solve_mutual_matrix(world: 'World', engine: 'Engine', anchors: list[str], probe_points: ndarray | None = None, *, frequency_index: int = 0, symmetrize: bool = True, offdiag: OffDiagonal = 'galerkin', matrix_min_distance: float = 0.001, matrix_max_terms: int | None = None, matrix_tol: float | None = None) -> np.ndarray

Full mutual grounding-impedance matrix Z_G in one assembly.

Column j belongs to 1 A injected into anchors[j]; the other clusters float (zero net current, review pass 10, 10.29), exactly as in Engine.solve() with one source. The segment reaction matrix and the leakage distribution of every excitation are computed once and reused for all entries.

  • Diagonal. Z[j, j] is the cluster impedance of anchors[j], the length-weighted (Galerkin) potential average over every member of its cluster divided by the cluster current — the same reduction as FieldResult.cluster_impedance() after a per-excitation Engine.solve() (equal to round-off). Up to 2026.11 the diagonal was the unweighted mean over the alphabetically first member: +0.150 % for an L-shaped footprint at ds = 2 m, -3.8 … -9.1 % for a rod split at the layer interface (review pass 10, 10.26).
  • Off-diagonal, offdiag="galerkin" (default): the reaction Z[i, j] = T_iᵀ (K + S) T_j of the leakage columns T with the reaction matrix K and the concrete-shell diagonal S. It is the current-weighted potential of cluster i under excitation j — the off-diagonal counterpart of the diagonal, reciprocal to round-off, and the matrix that reproduces a solve of the clusters joined by branches (see Notes).
  • Off-diagonal, offdiag="probe": the potential at probe_points[i] under excitation j, as FieldResult.potential() returns it after a per-excitation solve — the definition of releases up to 0.15.0. A point potential is not the potential of cluster i: the matrix is not reciprocal (Z[i, j] and Z[j, i] differ by up to 35 % in two-layer soil, review pass 10, 10.34), and symmetrize=True averages that asymmetry away. On an AP1-like site (a station and twelve house foundations, ds = 2 m, five soils) the symmetrised probe matrix misses the input impedance of the joined network by -0.15 … -0.88 %, and its off-diagonal entries differ from the galerkin ones by 0.15 … 1.1 % (median) and up to 41 %; the galerkin matrix reproduces the network solve to 1e-12.

The galerkin off-diagonal is the default of every call since the user decision Q15 of 2026.11. Up to 0.15.0 passing probe_points selected the probe definition; such a call now returns the galerkin matrix and ignores the points with a ProbePointsIgnoredWarning — pass offdiag="probe" to keep the 0.15.0 definition.

Parameters:

Name Type Description Default
world 'World'

Assembled world holding all nG grounding clusters and the soil model (homogeneous or two-layer, also as a MultiLayerSoil of at most two distinct layers). Sources, if any, are ignored.

required
engine 'Engine'

Engine of the image family (backend="image" and its aliases); segment_length, kernel, image_max_terms and image_series_tol act exactly as in Engine.solve(). frequencies[frequency_index] is the solved frequency.

required
anchors list[str]

Length-nG list of electrode names, one per cluster ("gnode").

required
probe_points ndarray | None

(nG, 3) array of (x, y, depth) points in m, one per anchor, used by offdiag="probe" only (required there). With offdiag="galerkin" they are ignored, not validated, with a ProbePointsIgnoredWarning.

None
frequency_index int

Index into engine.frequencies. Default 0.

0
symmetrize bool

If True (default) return 0.5 · (Z + Zᵀ).

True
offdiag OffDiagonal

"galerkin" (default) or "probe", see above.

'galerkin'
matrix_min_distance float

Clamp distance in m and series controls of the probe-point evaluation (offdiag="probe" only; the galerkin off-diagonal evaluates no field). None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001
matrix_max_terms float

Clamp distance in m and series controls of the probe-point evaluation (offdiag="probe" only; the galerkin off-diagonal evaluates no field). None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001
matrix_tol float

Clamp distance in m and series controls of the probe-point evaluation (offdiag="probe" only; the galerkin off-diagonal evaluates no field). None (default) for the series controls takes engine.image_max_terms / engine.image_series_tol, the controls FieldResult.potential() uses after a solve with the same engine (before 2026.11 they were hard-coded to 100 / 1e-6, review pass 10, 10.25).

0.001

Returns:

Name Type Description
Z (ndarray, shape(nG, nG), complex)

Mutual grounding-impedance matrix in Ω.

Raises:

Type Description
ValueError

If world has no soil model or no electrodes, if offdiag="probe" comes without probe_points of shape (nG, 3), or if offdiag is unknown.

BackendCapabilityError

If the engine's backend is not the image family (a subclass of ValueError; up to 2026.11 the backend was ignored, 10.34).

ResourceLimitError

If the problem exceeds engine.max_segments (default groundfield.diagnostics.HARD_LIMIT).

KeyError

If an entry of anchors is not an electrode in world.

Warns:

Type Description
ProbePointsIgnoredWarning

If probe_points are given with offdiag="galerkin" (the default), the call of releases up to 0.15.0.

Notes

With the uniform current per owner of the image family, the potential of a cluster is the current-weighted average of its segment potentials. With every other cluster floating, T_iᵀ (K + S) T_j therefore equals the potential of cluster i under excitation j exactly (reciprocity of the reaction matrix), bonded groups and rods through the layer interface included, and (Y_L + Z_G⁻¹) u = i reproduces the solve of the clusters joined by the branches Y_L. With probe off-diagonals it does not (evidence in the 2026.11 changelog).

Source code in src/groundfield/solver/mutual.py
def solve_mutual_matrix(
    world: "World",
    engine: "Engine",
    anchors: list[str],
    probe_points: np.ndarray | None = None,
    *,
    frequency_index: int = 0,
    symmetrize: bool = True,
    offdiag: OffDiagonal = "galerkin",
    matrix_min_distance: float = 1e-3,
    matrix_max_terms: int | None = None,
    matrix_tol: float | None = None,
) -> np.ndarray:
    """Full mutual grounding-impedance matrix ``Z_G`` in one assembly.

    Column ``j`` belongs to 1 A injected into ``anchors[j]``; the other
    clusters float (zero net current, review pass 10, 10.29), exactly as
    in :meth:`Engine.solve` with one source. The segment reaction matrix and the
    leakage distribution of every excitation are computed once and
    reused for all entries.

    * **Diagonal.** ``Z[j, j]`` is the cluster impedance of ``anchors[j]``,
      the length-weighted (Galerkin) potential average over every
      member of its cluster divided by the cluster current — the same
      reduction as :meth:`FieldResult.cluster_impedance` after a
      per-excitation :meth:`Engine.solve` (equal to round-off). Up to
      2026.11 the diagonal was the unweighted mean over the
      alphabetically first member: +0.150 % for an L-shaped footprint
      at ds = 2 m, -3.8 … -9.1 % for a rod split at the layer interface
      (review pass 10, 10.26).
    * **Off-diagonal**, ``offdiag="galerkin"`` (default): the reaction
      ``Z[i, j] = T_iᵀ (K + S) T_j`` of the leakage columns ``T`` with
      the reaction matrix ``K`` and the concrete-shell diagonal ``S``.
      It is the current-weighted potential of cluster ``i`` under
      excitation ``j`` — the off-diagonal counterpart of the diagonal,
      reciprocal to round-off, and the matrix that reproduces a solve
      of the clusters joined by branches (see Notes).
    * **Off-diagonal**, ``offdiag="probe"``: the potential at
      ``probe_points[i]`` under excitation ``j``, as
      :meth:`FieldResult.potential` returns it after a per-excitation
      solve — the definition of releases up to 0.15.0. A point potential
      is not the potential of cluster ``i``: the matrix is not reciprocal
      (``Z[i, j]`` and ``Z[j, i]`` differ by up to 35 % in two-layer soil,
      review pass 10, 10.34), and ``symmetrize=True`` averages that
      asymmetry away. On an AP1-like site (a station and twelve house
      foundations, ds = 2 m, five soils) the symmetrised probe matrix
      misses the input impedance of the joined network by -0.15 …
      -0.88 %, and its off-diagonal entries differ from the galerkin
      ones by 0.15 … 1.1 % (median) and up to 41 %; the galerkin matrix
      reproduces the network solve to 1e-12.

    The galerkin off-diagonal is the default of every call since the
    user decision Q15 of 2026.11. Up to 0.15.0 passing ``probe_points``
    selected the probe definition; such a call now returns the galerkin
    matrix and ignores the points with a :class:`ProbePointsIgnoredWarning`
    — pass ``offdiag="probe"`` to keep the 0.15.0 definition.

    Parameters
    ----------
    world
        Assembled world holding all ``nG`` grounding clusters and the
        soil model (homogeneous or two-layer, also as a
        :class:`~groundfield.soil.MultiLayerSoil` of at most two distinct
        layers). Sources, if any, are ignored.
    engine
        Engine of the image family (``backend="image"`` and its
        aliases); ``segment_length``, ``kernel``, ``image_max_terms`` and
        ``image_series_tol`` act exactly as in :meth:`Engine.solve`.
        ``frequencies[frequency_index]`` is the solved frequency.
    anchors
        Length-``nG`` list of electrode names, one per cluster ("gnode").
    probe_points
        ``(nG, 3)`` array of ``(x, y, depth)`` points in m, one per
        anchor, used by ``offdiag="probe"`` only (required there). With
        ``offdiag="galerkin"`` they are ignored, not validated, with a
        :class:`ProbePointsIgnoredWarning`.
    frequency_index
        Index into ``engine.frequencies``. Default 0.
    symmetrize
        If ``True`` (default) return ``0.5 · (Z + Zᵀ)``.
    offdiag
        ``"galerkin"`` (default) or ``"probe"``, see above.
    matrix_min_distance, matrix_max_terms, matrix_tol
        Clamp distance in m and series controls of the probe-point
        evaluation (``offdiag="probe"`` only; the galerkin off-diagonal
        evaluates no field). ``None`` (default) for the series controls
        takes ``engine.image_max_terms`` / ``engine.image_series_tol``,
        the controls :meth:`FieldResult.potential` uses after a solve with
        the same engine (before 2026.11 they were hard-coded to 100 /
        ``1e-6``, review pass 10, 10.25).

    Returns
    -------
    Z : np.ndarray, shape (nG, nG), complex
        Mutual grounding-impedance matrix in Ω.

    Raises
    ------
    ValueError
        If ``world`` has no soil model or no electrodes, if
        ``offdiag="probe"`` comes without ``probe_points`` of shape
        ``(nG, 3)``, or if ``offdiag`` is unknown.
    BackendCapabilityError
        If the engine's backend is not the image family (a subclass of
        ``ValueError``; up to 2026.11 the backend was ignored, 10.34).
    ResourceLimitError
        If the problem exceeds ``engine.max_segments`` (default
        :data:`groundfield.diagnostics.HARD_LIMIT`).
    KeyError
        If an entry of ``anchors`` is not an electrode in ``world``.

    Warns
    -----
    ProbePointsIgnoredWarning
        If ``probe_points`` are given with ``offdiag="galerkin"`` (the
        default), the call of releases up to 0.15.0.

    Notes
    -----
    With the uniform current per owner of the image family, the
    potential of a cluster is the current-weighted average of its
    segment potentials. With every other cluster floating,
    ``T_iᵀ (K + S) T_j`` therefore equals the potential of cluster ``i``
    under excitation ``j`` exactly (reciprocity of the reaction matrix),
    bonded groups and rods through the layer interface included, and
    ``(Y_L + Z_G⁻¹) u = i`` reproduces the solve of the clusters joined
    by the branches ``Y_L``. With probe off-diagonals it does not
    (evidence in the 2026.11 changelog).
    """
    if world.soil is None:
        raise ValueError("World has no soil model.")
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    if offdiag not in _OFFDIAG_CHOICES:
        raise ValueError(f"offdiag must be 'probe' or 'galerkin', got {offdiag!r}.")

    nG = len(anchors)
    if offdiag == "probe":
        if probe_points is None:
            raise ValueError("offdiag='probe' needs probe_points of shape (nG, 3).")
        probe_points = np.asarray(probe_points, dtype=float)
        if probe_points.shape != (nG, 3):
            raise ValueError(
                f"probe_points must have shape ({nG}, 3), got {probe_points.shape}."
            )
    elif probe_points is not None:
        # user decision Q15 (2026-11-08): the galerkin off-diagonal is the
        # default whatever the call; the probe points of a 0.15.0 call are
        # ignored, not rejected, so the call keeps running.
        from groundfield.solver.registry import warn_external

        warn_external(
            "solve_mutual_matrix: probe_points are ignored. The off-diagonal "
            "is offdiag='galerkin' (the default since 2026.11): the reaction "
            "of the leakage distributions, reciprocal, the matrix that "
            "reproduces a solve of the clusters joined by branches. Up to "
            "0.15.0 probe points selected the potential at them instead; "
            "pass offdiag='probe' to keep that definition, or drop "
            "probe_points.",
            ProbePointsIgnoredWarning,
        )
        probe_points = None

    problem = _prepare(world, engine, frequency_index, where="solve_mutual_matrix")
    disc, topo, arrays = problem.disc, problem.topo, problem.arrays
    n_segments = len(disc.segments)
    seg_lengths = arrays.lengths
    Z_seg_full = problem.Z_seg_full

    # ADR-0012 V2 shell augmentation (added to the *diagonal* of the
    # reaction matrix exactly as in ``_solve_cluster_currents`` and the
    # post-solve ``ph`` step).
    shell_diag: np.ndarray | None = None
    if np.any(arrays.shell_coefficients > 0.0):
        with np.errstate(divide="ignore", invalid="ignore"):
            shell_diag = np.where(
                seg_lengths > 0.0,
                arrays.shell_coefficients / seg_lengths,
                0.0,
            )

    # Cluster members per real electrode (== FieldResult.clusters).
    real_set = {e.name for e in world.electrodes}
    cluster_id = topo.cluster_id
    cluster_members: dict[str, list[str]] = {}
    for ename in (e.name for e in world.electrodes):
        cluster_members[ename] = sorted(
            n
            for n in cluster_id
            if cluster_id[n] == cluster_id[ename] and n in real_set
        )

    T = np.zeros((n_segments, nG), dtype=complex)  # leakage column per excitation
    PH = np.zeros((n_segments, nG), dtype=complex)  # segment potentials per excitation
    Z = np.zeros((nG, nG), dtype=complex)
    excitations = _unit_excitations(world, problem, list(anchors))
    for j, anchor_j in enumerate(anchors):
        elec_total, sc = excitations[j]
        T[:, j] = sc
        if sc.any():
            # Segment potentials as in the post-solve step of the live
            # solver: bulk reaction matrix on the real and imaginary
            # leakage, then the shell augmentation.
            phi_re = Z_seg_full @ sc.real
            phi_im = Z_seg_full @ sc.imag
            if shell_diag is not None:
                phi_re = phi_re + shell_diag * sc.real
                phi_im = phi_im + shell_diag * sc.imag
            PH[:, j] = phi_re + 1j * phi_im
        members = cluster_members.get(anchor_j, [anchor_j])
        Z[j, j] = _cluster_impedance(problem, members, elec_total, PH[:, j])

    if offdiag == "galerkin":
        # Reaction of every pair of leakage columns (bilinear, no
        # conjugation: reciprocity holds for the complex system too).
        Phi = T.T @ PH
    else:
        Phi = _field_of_columns(
            problem,
            probe_points,
            T,
            min_distance=matrix_min_distance,
            max_terms=matrix_max_terms,
            tol=matrix_tol,
        )  # (nG, nG): row i = probe i, column j = excitation j
    off = ~np.eye(nG, dtype=bool)
    Z[off] = Phi[off]

    if symmetrize:
        return 0.5 * (Z + Z.T)
    return Z

Backend solve functions

Each built-in backend is one solve function, solve_<name>(world, engine), registered in the backend registry. Engine.solve resolves the backend name, checks the capabilities against the world, calls the function and fills the common metadata of the result (CORE_METADATA_KEYS); call the functions directly only to bypass that dispatch, for example in a test. The theory of each backend is on its engine page.

solve_image

solve_image(world: 'World', engine: 'Engine') -> FieldResult

Image-charge solver for homogeneous soil.

Runs the shared image-family pipeline (groundfield.solver._pipeline) with the half-space Green's function.

Parameters:

Name Type Description Default
world 'World'

World whose soil must be a HomogeneousSoil.

required
engine 'Engine'

Engine configuration; relevant fields are segment_length, frequencies and earth_inductive_model.

required

Returns:

Type Description
FieldResult

Node potentials and leakage currents per frequency, point sources and metadata.

Raises:

Type Description
BackendCapabilityError

If the soil is a layered model (Engine.solve forwards those to image_2layer). Before 2026.11 this was a TypeError.

TypeError

If world.soil is no soil model.

ValueError

If the world has no electrodes, or the geometry fails a discretisation guard (thin wire, burial depth).

Source code in src/groundfield/solver/image.py
def solve_image(world: "World", engine: "Engine") -> FieldResult:
    """Image-charge solver for homogeneous soil.

    Runs the shared image-family pipeline
    (:mod:`groundfield.solver._pipeline`) with the half-space Green's
    function.

    Parameters
    ----------
    world
        World whose ``soil`` must be a :class:`HomogeneousSoil`.
    engine
        Engine configuration; relevant fields are ``segment_length``,
        ``frequencies`` and ``earth_inductive_model``.

    Returns
    -------
    FieldResult
        Node potentials and leakage currents per frequency, point
        sources and metadata.

    Raises
    ------
    BackendCapabilityError
        If the soil is a layered model (:meth:`Engine.solve
        <groundfield.solver.engine.Engine.solve>` forwards those to
        ``image_2layer``). Before 2026.11 this was a :class:`TypeError`.
    TypeError
        If ``world.soil`` is no soil model.
    ValueError
        If the world has no electrodes, or the geometry fails a
        discretisation guard (thin wire, burial depth).
    """
    if isinstance(world.soil, (TwoLayerSoil, MultiLayerSoil)):
        from groundfield.solver.registry import BackendCapabilityError

        raise BackendCapabilityError(
            f"Backend 'image' solves homogeneous soil; got a "
            f"{type(world.soil).__name__}. Engine(backend='image').solve "
            "forwards layered soils to image_2layer (at most two distinct "
            "layers); use backend='mom_sommerfeld' for three or more."
        )
    if not isinstance(world.soil, HomogeneousSoil):
        raise TypeError(
            "Backend 'image' requires a HomogeneousSoil. "
            f"Got: {type(world.soil).__name__}."
        )
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    if engine.kernel is None:
        # A direct call resolves the default like Engine.solve (10.28).
        engine = engine._with(kernel=DEFAULT_KERNEL)
    green = _HalfSpaceGreen(world.soil.rho, engine.kernel)
    return solve_image_family(world, engine, green, stacklevel=3)

solve_image_2layer

solve_image_2layer(world: 'World', engine: 'Engine', *, max_terms: int | None = None, tol: float | None = None, far_field: str | None = None) -> FieldResult

Image-charge solver for 2-layer soil (Tagg / Sunde).

Runs the shared image-family pipeline (groundfield.solver._pipeline) with the two-layer Green's function.

Parameters:

Name Type Description Default
world 'World'

World whose soil is a TwoLayerSoil. Electrodes in the upper layer use the Tagg/Sunde series; geometries reaching the interface use the ADR-0007 Sommerfeld path.

required
engine 'Engine'

Engine configuration. engine.segment_length controls the discretisation as in the homogeneous backend.

required
max_terms int | None

Maximum number of series terms; None (default) takes engine.image_max_terms.

None
tol float | None

Series truncation: stop as soon as the geometric tail bound \(|K|^{n+1}/(1-|K|)\) falls below tol (dimensionless); None (default) takes engine.image_series_tol.

None
far_field str | None

Form of the far images with the line kernel, "quadrupole" or "point"; None (default) takes engine.image_far_field.

None

Returns:

Type Description
FieldResult

Result object. FieldResult.metadata exposes diagnostic fields (K, rho_1, rho_2, h_1, n_terms_used, converged, series_used, series).

Raises:

Type Description
BackendCapabilityError

If the soil is a HomogeneousSoil or a MultiLayerSoil with three or more distinct layers (a stack with at most two is solved as the equivalent two-layer soil). Before 2026.11 both raised TypeError.

TypeError

If world.soil is no soil model.

ValueError

If the world has no electrodes, if far_field is not one of "quadrupole" and "point" (audit W3R2A-02; before, every other value ran the point form and was recorded as given), or if the geometry fails a discretisation guard (thin wire, burial depth).

Warns:

Type Description
SeriesTruncationWarning

If the series is used and reaches max_terms before tol.

Source code in src/groundfield/solver/image_2layer.py
def solve_image_2layer(
    world: "World",
    engine: "Engine",
    *,
    max_terms: int | None = None,
    tol: float | None = None,
    far_field: str | None = None,
) -> FieldResult:
    """Image-charge solver for 2-layer soil (Tagg / Sunde).

    Runs the shared image-family pipeline
    (:mod:`groundfield.solver._pipeline`) with the two-layer Green's
    function.

    Parameters
    ----------
    world
        World whose ``soil`` is a :class:`TwoLayerSoil`. Electrodes in
        the upper layer use the Tagg/Sunde series; geometries reaching
        the interface use the ADR-0007 Sommerfeld path.
    engine
        Engine configuration. ``engine.segment_length`` controls the
        discretisation as in the homogeneous backend.
    max_terms
        Maximum number of series terms; ``None`` (default) takes
        ``engine.image_max_terms``.
    tol
        Series truncation: stop as soon as the geometric tail bound
        $|K|^{n+1}/(1-|K|)$ falls below ``tol`` (dimensionless);
        ``None`` (default) takes ``engine.image_series_tol``.
    far_field
        Form of the far images with the line kernel, ``"quadrupole"`` or
        ``"point"``; ``None`` (default) takes ``engine.image_far_field``.

    Returns
    -------
    FieldResult
        Result object. :attr:`FieldResult.metadata` exposes diagnostic
        fields (``K``, ``rho_1``, ``rho_2``, ``h_1``, ``n_terms_used``,
        ``converged``, ``series_used``, ``series``).

    Raises
    ------
    BackendCapabilityError
        If the soil is a :class:`HomogeneousSoil` or a
        :class:`~groundfield.soil.models.MultiLayerSoil` with three or
        more distinct layers (a stack with at most two is solved as the
        equivalent two-layer soil). Before 2026.11 both raised
        :class:`TypeError`.
    TypeError
        If ``world.soil`` is no soil model.
    ValueError
        If the world has no electrodes, if ``far_field`` is not one of
        ``"quadrupole"`` and ``"point"`` (audit W3R2A-02; before, every other
        value ran the point form and was recorded as given), or if the
        geometry fails a discretisation guard (thin wire, burial depth).

    Warns
    -----
    SeriesTruncationWarning
        If the series is used and reaches ``max_terms`` before ``tol``.
    """
    if isinstance(world.soil, MultiLayerSoil):
        # Audit round 1, A1-numerics F09: the registry accepts a layer
        # stack that merges to at most two layers; solve it as the
        # equivalent TwoLayerSoil instead of raising a bare TypeError.
        world = world.model_copy(update={"soil": _as_two_layer(world.soil)})
    if isinstance(world.soil, HomogeneousSoil):
        from groundfield.solver.registry import BackendCapabilityError

        raise BackendCapabilityError(
            "Backend 'image_2layer' solves two-layer soil; got a "
            "HomogeneousSoil. Use backend='image' (Engine(backend='image')"
            ".solve dispatches by soil model)."
        )
    if not isinstance(world.soil, TwoLayerSoil):
        raise TypeError(
            "Backend 'image_2layer' requires a TwoLayerSoil. "
            f"Got: {type(world.soil).__name__}."
        )
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")

    soil: TwoLayerSoil = world.soil
    _log.info(
        "image_2layer: rho_1=%.1f, rho_2=%.1f, h_1=%.2f, K=%.4f",
        soil.rho_1,
        soil.rho_2,
        soil.h_1,
        soil.reflection_coefficient,
    )
    if max_terms is None:
        max_terms = engine.image_max_terms
    if tol is None:
        tol = engine.image_series_tol
    if far_field is None:
        far_field = engine.image_far_field
    if engine.kernel is None:
        # The backend's preferred kernel (Engine.kernel = None, 10.28).
        engine = engine._with(kernel=DEFAULT_KERNEL)
    green = _TwoLayerGreen(
        soil, max_terms, tol, engine.segment_length, engine.kernel, far_field
    )
    owner_interfaces = None
    if _crosses_interface(world, _owner_interfaces(soil)):
        # One owner per (electrode, layer) for rods through h_1 (10.15), on
        # top of the one owner per straight wire of every world (Q30).
        owner_interfaces = _owner_interfaces(soil)
    return solve_image_family(
        world, engine, green, stacklevel=3, owner_interfaces=owner_interfaces
    )

solve_mom

solve_mom(world: World, engine: Engine, *, two_layer_max_terms: int | None = None, two_layer_tol: float | None = None) -> FieldResult

Point-matching method-of-moments backend.

Supports HomogeneousSoil, TwoLayerSoil and a MultiLayerSoil whose canonical stack has at most two layers (10.48). The Green's-function kernel is taken from the matching image backend; only the resolution scheme (one current per segment, point matching at the segment midpoints, instead of one uniform current per straight wire of an electrode) differs. Clusters without a source float (zero net current, 10.29). Concrete-encased electrodes carry the per-segment shell term of ADR-0012 (since 2026.11). See the module docstring for the accuracy of the scheme and the shared solve flow.

Parameters:

Name Type Description Default
world World

World to evaluate.

required
engine Engine

Engine configuration; engine.segment_length (m) controls the discretisation.

required
two_layer_max_terms int | None

Truncation parameters for the Tagg/Sunde series (term count, dimensionless tail bound), only used for two-layer soil. None (default) takes engine.image_max_terms / engine.image_series_tol, so the engine knob reaches this backend consistently with image_2layer.

None
two_layer_tol int | None

Truncation parameters for the Tagg/Sunde series (term count, dimensionless tail bound), only used for two-layer soil. None (default) takes engine.image_max_terms / engine.image_series_tol, so the engine knob reaches this backend consistently with image_2layer.

None

Returns:

Type Description
FieldResult

Result object compatible with FieldResult from the image backends. metadata['solver'] is 'point_matching' ('galerkin' up to 0.15.0, although the scheme was the same).

Raises:

Type Description
ValueError

If the world has no electrodes, or a segment lies partly above the soil surface.

BackendCapabilityError

For a MultiLayerSoil with three or more distinct layers (a TypeError before 2026.11).

TypeError

If world.soil is no soil model.

Source code in src/groundfield/solver/mom.py
def solve_mom(
    world: World,
    engine: Engine,
    *,
    two_layer_max_terms: int | None = None,
    two_layer_tol: float | None = None,
) -> FieldResult:
    """Point-matching method-of-moments backend.

    Supports :class:`HomogeneousSoil`, :class:`TwoLayerSoil` and a
    :class:`MultiLayerSoil` whose canonical stack has at most two layers
    (10.48). The Green's-function kernel is taken from the matching
    image backend; only the resolution scheme (one current per segment,
    point matching at the segment midpoints, instead of one uniform
    current per straight wire of an electrode) differs. Clusters without a source float
    (zero net current, 10.29). Concrete-encased electrodes carry the
    per-segment shell term of ADR-0012 (since 2026.11). See the module
    docstring for the accuracy of the scheme and the shared solve flow.

    Parameters
    ----------
    world
        World to evaluate.
    engine
        Engine configuration; ``engine.segment_length`` (m) controls the
        discretisation.
    two_layer_max_terms, two_layer_tol
        Truncation parameters for the Tagg/Sunde series (term count,
        dimensionless tail bound), only used for two-layer soil.
        ``None`` (default) takes ``engine.image_max_terms`` /
        ``engine.image_series_tol``, so the engine knob reaches this
        backend consistently with ``image_2layer``.

    Returns
    -------
    FieldResult
        Result object compatible with :class:`FieldResult` from the
        image backends. ``metadata['solver']`` is ``'point_matching'``
        (``'galerkin'`` up to 0.15.0, although the scheme was the
        same).

    Raises
    ------
    ValueError
        If the world has no electrodes, or a segment lies partly above
        the soil surface.
    BackendCapabilityError
        For a :class:`MultiLayerSoil` with three or more distinct layers
        (a :class:`TypeError` before 2026.11).
    TypeError
        If ``world.soil`` is no soil model.
    """
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    if not isinstance(world.soil, (HomogeneousSoil, TwoLayerSoil, MultiLayerSoil)):
        raise TypeError(
            "Backend 'mom' supports HomogeneousSoil, TwoLayerSoil and "
            "MultiLayerSoil stacks with at most two distinct layers. "
            f"Got: {type(world.soil).__name__}."
        )
    # Review pass 10, 10.48: solve the canonical soil — a MultiLayerSoil
    # whose adjacent layers share a resistivity is a two-layer (or
    # homogeneous) soil, and a TwoLayerSoil without contrast is
    # homogeneous.
    soil = canonical_soil(world.soil)
    if isinstance(soil, MultiLayerSoil):
        from groundfield.solver.registry import BackendCapabilityError

        raise BackendCapabilityError(
            "Backend 'mom' supports at most two distinct soil layers; this "
            f"MultiLayerSoil has {len(soil.layers)}. Use "
            "backend='mom_sommerfeld' for n >= 3 soils."
        )
    if two_layer_max_terms is None:
        two_layer_max_terms = engine.image_max_terms
    if two_layer_tol is None:
        two_layer_tol = engine.image_series_tol
    _log.info(
        "mom: soil=%s, segment_length=%.3f",
        type(soil).__name__,
        engine.segment_length,
    )
    green = _MomGreen(soil, two_layer_max_terms, two_layer_tol)
    return solve_point_matching(world, engine, green, stacklevel=3)

solve_mom_sommerfeld

solve_mom_sommerfeld(world: World, engine: Engine, *, lambda_max_factor: float = 200.0, epsabs: float = 1e-09, epsrel: float = 1e-07, max_osc_panels: int = _MAX_OSC_PANELS, tabulate: bool = True) -> FieldResult

Point-matching MoM with direct Sommerfeld quadrature for layered soil.

The discretisation and the linear solve are those of mom (point matching at the segment midpoints, point-source near field, source-free clusters floating), run through the shared solve pipeline (10.75). Every off-diagonal reaction-matrix entry is the Sommerfeld kernel of sommerfeld_kernel_value(), i.e. the closed-form direct pair plus a numerically integrated reflected remainder; no image series and no fit enter the off-diagonal kernel. For \(n = 2\) the diagonal is the Tagg/Sunde series diagonal of mom, so on two-layer soil this backend reproduces mom and checks the kernel, not the scheme; for \(n \ge 3\) distinct layers it is the only integral-equation backend.

Cost (review pass 10, 10.61): pairs that share a depth pair and a horizontal distance share one quadrature, which halves the work of every world and collapses it for regular geometries. For \(n \ge 3\) the reflected remainder of a depth group with many distinct distances is tabulated on log-spaced nodes and interpolated (tabulate=True, the default): about \(10^{-7}\) relative error of the kernel at the verification points and below \(10^{-6}\) on the reaction matrix of the benchmark grid B12, for a cost that no longer grows with the number of pairs. tabulate=False evaluates every distinct pair by quadrature (the kernel reference). For \(n = 2\) every pair is evaluated by quadrature: this backend is the kernel check of the closed-form series there.

Parameters:

Name Type Description Default
world World

World to evaluate.

required
engine Engine

Engine configuration.

required
lambda_max_factor float

Truncation of the remainder quadrature in units of the remainder decay length \(1 / d_{\text{rem}}\); saturates at 60. See sommerfeld_kernel_value() for the delegated \(n = 2\) cross-layer path.

200.0
epsabs float

Convergence thresholds of the remainder quadrature (absolute in 1/m, relative).

1e-09
epsrel float

Convergence thresholds of the remainder quadrature (absolute in 1/m, relative).

1e-09
max_osc_panels int

Budget for the \(J_0\) half-period panel family.

_MAX_OSC_PANELS
tabulate bool

Depth-group tabulation of the reflected kernel for \(n \ge 3\) (see above).

True

Returns:

Type Description
FieldResult

metadata['converged'] (one bool) and metadata['converged_per_frequency'] report the quadrature and series convergence (10.47); metadata['kernel_tabulation'] the tabulation counters and the largest relative error at its verification points.

Warns:

Type Description
SommerfeldConvergenceWarning

Once per solve, if any reaction-matrix entry's remainder quadrature failed to converge.

Notes

The quadrature keywords are reachable through Engine.options["mom_sommerfeld"] (MomSommerfeldOptions); the signature defaults equal the option defaults, so a direct call without keywords behaves exactly like solve().

Raises:

Type Description
TypeError

If the soil is not a HomogeneousSoil, TwoLayerSoil or MultiLayerSoil.

ValueError

If the world has no electrodes.

Source code in src/groundfield/solver/mom_sommerfeld.py
def solve_mom_sommerfeld(
    world: World,
    engine: Engine,
    *,
    lambda_max_factor: float = 200.0,
    epsabs: float = 1e-9,
    epsrel: float = 1e-7,
    max_osc_panels: int = _MAX_OSC_PANELS,
    tabulate: bool = True,
) -> FieldResult:
    """Point-matching MoM with direct Sommerfeld quadrature for layered soil.

    The discretisation and the linear solve are those of ``mom`` (point
    matching at the segment midpoints, point-source near field,
    source-free clusters floating), run through the shared solve
    pipeline (10.75). Every off-diagonal reaction-matrix entry is the
    Sommerfeld kernel of :func:`sommerfeld_kernel_value`, i.e. the
    closed-form direct pair plus a numerically integrated reflected
    remainder; no image series and no fit enter the off-diagonal
    kernel. For $n = 2$ the diagonal is the Tagg/Sunde series diagonal
    of ``mom``, so on two-layer soil this backend reproduces ``mom`` and
    checks the kernel, not the scheme; for $n \\ge 3$ distinct layers it
    is the only integral-equation backend.

    Cost (review pass 10, 10.61): pairs that share a depth pair and a
    horizontal distance share one quadrature, which halves the work of
    every world and collapses it for regular geometries. For
    $n \\ge 3$ the reflected remainder of a depth group with many
    distinct distances is tabulated on log-spaced nodes and interpolated
    (``tabulate=True``, the default): about $10^{-7}$ relative error of
    the kernel at the verification points and below $10^{-6}$ on the
    reaction matrix of the benchmark grid B12, for a cost that no longer
    grows with the number of pairs. ``tabulate=False`` evaluates every
    distinct pair by quadrature (the kernel reference). For $n = 2$
    every pair is evaluated by quadrature: this backend is the kernel
    check of the closed-form series there.

    Parameters
    ----------
    world
        World to evaluate.
    engine
        Engine configuration.
    lambda_max_factor
        Truncation of the remainder quadrature in units of the
        remainder decay length $1 / d_{\\text{rem}}$; saturates at
        60. See :func:`sommerfeld_kernel_value` for the delegated
        $n = 2$ cross-layer path.
    epsabs, epsrel
        Convergence thresholds of the remainder quadrature (absolute
        in 1/m, relative).
    max_osc_panels
        Budget for the $J_0$ half-period panel family.
    tabulate
        Depth-group tabulation of the reflected kernel for $n \\ge 3$
        (see above).

    Returns
    -------
    FieldResult
        ``metadata['converged']`` (one bool) and
        ``metadata['converged_per_frequency']`` report the quadrature
        and series convergence (10.47);
        ``metadata['kernel_tabulation']`` the tabulation counters and
        the largest relative error at its verification points.

    Warns
    -----
    SommerfeldConvergenceWarning
        Once per solve, if any reaction-matrix entry's remainder
        quadrature failed to converge.

    Notes
    -----
    The quadrature keywords are reachable through
    ``Engine.options["mom_sommerfeld"]``
    (:class:`~groundfield.solver.registry.MomSommerfeldOptions`); the
    signature defaults equal the option defaults, so a direct call
    without keywords behaves exactly like
    :meth:`~groundfield.solver.engine.Engine.solve`.

    Raises
    ------
    TypeError
        If the soil is not a :class:`HomogeneousSoil`,
        :class:`TwoLayerSoil` or :class:`MultiLayerSoil`.
    ValueError
        If the world has no electrodes.
    """
    if not isinstance(world.soil, (HomogeneousSoil, TwoLayerSoil, MultiLayerSoil)):
        raise TypeError(
            "Backend 'mom_sommerfeld' supports HomogeneousSoil, "
            "TwoLayerSoil, and MultiLayerSoil. "
            f"Got: {type(world.soil).__name__}."
        )
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    green = _SommerfeldGreen(
        world.soil,
        lambda_max_factor=lambda_max_factor,
        epsabs=epsabs,
        epsrel=epsrel,
        max_osc_panels=max_osc_panels,
        max_terms=engine.image_max_terms,
        tol=engine.image_series_tol,
        tabulate=tabulate,
    )
    _log.info(
        "mom_sommerfeld: n_layers=%d, segment_length=%.3f, lam_max_fac=%.1f",
        green.stack.n_layers,
        engine.segment_length,
        lambda_max_factor,
    )
    return solve_point_matching(world, engine, green, stacklevel=3)

sommerfeld_kernel_value

sommerfeld_kernel_value(stack: LayerStack, s: float, z: float, z_s: float, *, lambda_max_factor: float = 200.0, epsabs: float = 1e-09, epsrel: float = 1e-07, max_osc_panels: int = _MAX_OSC_PANELS, issues: list[_QuadratureIssue] | None = None) -> float

Evaluate the layered-soil Sommerfeld kernel at one point.

Returns the full top-layer kernel $$ G(s, z, z_s) \;=\; \int_0^{\infty} \frac{e^{-\lambda |z - z_s|} + \Gamma_1 e^{-\lambda (2 h_1 - |z - z_s|)} + e^{-\lambda (z + z_s)} + \Gamma_1 e^{-\lambda (2 h_1 - z - z_s)}} {1 - \Gamma_1(\lambda)\, e^{-2 \lambda h_1}} J_0(\lambda s)\, d\lambda , $$ i.e. both image families plus the full multiple-reflection multiplier between the free surface (\(R_{\text{air}} = +1\)) and the layer interface. The potential of a point source \(I\) is then ρ_1 · I · G / (4 π).

The integral is not evaluated by a bare real-axis quadrature: the two \(\Gamma_1 \to 0\) terms (which converge only through the oscillation of \(J_0\) and are the reason the pre-0.15.0 implementation could return a negative value) are taken from Lipschitz' integral \(\int_0^\infty e^{-\lambda d} J_0(\lambda s) d\lambda = (s^2 + d^2)^{-1/2}\), so that $$ G = \frac{1}{\sqrt{s^2 + (z - z_s)^2}} + \frac{1}{\sqrt{s^2 + (z + z_s)^2}} + G_{\text{refl}}, $$ and only the exponentially decaying reflected remainder \(G_{\text{refl}}\) is integrated numerically — see _reflected_integral().

Parameters:

Name Type Description Default
stack LayerStack

Layer stack.

required
s float

Cylindrical radius \(s = \sqrt{(x - x_s)^2 + (y - y_s)^2}\) in metres.

required
z float

Field-point depth and source depth (positive into the soil).

required
z_s float

Field-point depth and source depth (positive into the soil).

required
lambda_max_factor float

Truncation of the remainder quadrature, in units of \(1 / d_{\text{rem}}\), where \(d_{\text{rem}}\) is the decay length of the remainder (not, as before 0.15.0, a characteristic length of the geometry). The discarded tail is bounded by \(e^{-\texttt{lambda\_max\_factor}}\); the factor saturates at 60 (\(\sim 10^{-26}\)), so raising it beyond the default cannot change the result.

On the delegated \(n = 2\) cross-layer path (\(z > h_1\) or \(z_s > h_1\), forwarded to groundfield.coupling.layered_green.two_layer_real_space_kernel()) the keyword is measured in units of a geometric characteristic length instead. Since the F14 fix of 0.15.0 that kernel adds every image term it does not resolve back in closed form, so the factor is only an upper bound there as well: values from 30 to 20 000 change the delegated kernel by at most 1.3e-8 and raise no warning (review pass 10; the pre-0.15.0 advice to lower the factor on that path is obsolete).

200.0
epsabs float

Absolute / relative thresholds of the grid-refinement convergence test of the remainder quadrature. epsrel is measured against the magnitude of the whole kernel. They are not forwarded to the delegated \(n = 2\) cross-layer path, which carries its own fixed-order grid.

1e-09
epsrel float

Absolute / relative thresholds of the grid-refinement convergence test of the remainder quadrature. epsrel is measured against the magnitude of the whole kernel. They are not forwarded to the delegated \(n = 2\) cross-layer path, which carries its own fixed-order grid.

1e-09
max_osc_panels int

Budget for the half-period panel family that resolves the \(J_0(\lambda s)\) oscillation, default 200 000 panels (× 12 Gauss nodes). Only binds for \(s / d_{\text{rem}} \gtrsim 1.9 \cdot 10^{4}\), i.e. a centimetre-thin intermediate layer combined with a kilometre-scale horizontal separation; there the coverage is incomplete, a SommerfeldConvergenceWarning is raised and raising this budget is the remedy (cost grows linearly).

_MAX_OSC_PANELS
issues list[_QuadratureIssue] | None

Optional collector for non-convergence diagnostics; see _reflected_integral(). Used by _build_Z_sommerfeld() to aggregate \(O(N^2)\) warnings into one.

None

Returns:

Name Type Description
G float

Raises:

Type Description
ValueError

For \(n \ge 3\) with \(z > h_1\) or \(z_s > h_1\): the expression above is a top-layer form, so the kernel refuses instead of silently returning a diverging number (before 0.15.0 it returned \(\approx -2 \cdot 10^{127}\) there).

Warns:

Type Description
SommerfeldConvergenceWarning

If the remainder quadrature does not reach the requested tolerance. The returned value is then not converged and its sign may be wrong.

Notes

Limits and special cases:

  • stack.n_layers == 1 (homogeneous, \(\Gamma_1 \equiv 0\)): short-circuited to \(1/r + 1/r_{\text{img}}\), bit-exact.
  • \(\rho_1 = \rho_2\) in a declared 2-layer stack (\(K_1 = 0\), hence \(\Gamma_1 \equiv 0\)): the reflected remainder is identically zero, so the same closed form is returned bit-exact. This is the strongest available accuracy test of the backend.
  • stack.n_layers == 2 with \(z > h_1\) or \(z_s > h_1\): delegated to groundfield.coupling.layered_green.two_layer_real_space_kernel(), which solves the cross-layer spectral matching.

Distances are floored at 1 mm (_MIN_DISTANCE), consistently with the homogeneous image backend, so the coincident-point limit stays finite.

Source code in src/groundfield/solver/mom_sommerfeld.py
def sommerfeld_kernel_value(
    stack: LayerStack,
    s: float,
    z: float,
    z_s: float,
    *,
    lambda_max_factor: float = 200.0,
    epsabs: float = 1e-9,
    epsrel: float = 1e-7,
    max_osc_panels: int = _MAX_OSC_PANELS,
    issues: list[_QuadratureIssue] | None = None,
) -> float:
    """Evaluate the layered-soil Sommerfeld kernel at one point.

    Returns the full top-layer kernel
    $$
    G(s, z, z_s) \\;=\\; \\int_0^{\\infty}
    \\frac{e^{-\\lambda |z - z_s|}
         + \\Gamma_1 e^{-\\lambda (2 h_1 - |z - z_s|)}
         + e^{-\\lambda (z + z_s)}
         + \\Gamma_1 e^{-\\lambda (2 h_1 - z - z_s)}}
         {1 - \\Gamma_1(\\lambda)\\, e^{-2 \\lambda h_1}}
    J_0(\\lambda s)\\, d\\lambda ,
    $$
    i.e. both image families plus the full multiple-reflection
    multiplier between the free surface ($R_{\\text{air}} = +1$)
    and the layer interface. The potential of a point source $I$
    is then ``ρ_1 · I · G / (4 π)``.

    The integral is **not** evaluated by a bare real-axis quadrature:
    the two $\\Gamma_1 \\to 0$ terms (which converge only through
    the oscillation of $J_0$ and are the reason the pre-0.15.0
    implementation could return a negative value) are taken from
    Lipschitz' integral
    $\\int_0^\\infty e^{-\\lambda d} J_0(\\lambda s) d\\lambda
    = (s^2 + d^2)^{-1/2}$, so that
    $$
    G = \\frac{1}{\\sqrt{s^2 + (z - z_s)^2}}
      + \\frac{1}{\\sqrt{s^2 + (z + z_s)^2}}
      + G_{\\text{refl}},
    $$
    and only the exponentially decaying reflected remainder
    $G_{\\text{refl}}$ is integrated numerically — see
    :func:`_reflected_integral`.

    Parameters
    ----------
    stack
        Layer stack.
    s
        Cylindrical radius $s = \\sqrt{(x - x_s)^2 + (y - y_s)^2}$
        in metres.
    z, z_s
        Field-point depth and source depth (positive into the soil).
    lambda_max_factor
        Truncation of the *remainder* quadrature, in units of
        $1 / d_{\\text{rem}}$, where $d_{\\text{rem}}$ is the
        decay length of the remainder (not, as before 0.15.0, a
        characteristic length of the geometry). The discarded tail is
        bounded by $e^{-\\texttt{lambda\\_max\\_factor}}$; the factor
        saturates at 60 ($\\sim 10^{-26}$), so raising it beyond
        the default cannot change the result.

        On the delegated $n = 2$ cross-layer path ($z > h_1$ or
        $z_s > h_1$, forwarded to
        :func:`groundfield.coupling.layered_green.two_layer_real_space_kernel`)
        the keyword is measured in units of a *geometric*
        characteristic length instead. Since the F14 fix of 0.15.0
        that kernel adds every image term it does not resolve back in
        closed form, so the factor is only an upper bound there as
        well: values from 30 to 20 000 change the delegated kernel by
        at most 1.3e-8 and raise no warning (review pass 10; the
        pre-0.15.0 advice to *lower* the factor on that path is
        obsolete).
    epsabs, epsrel
        Absolute / relative thresholds of the grid-refinement
        convergence test of the remainder quadrature. ``epsrel`` is
        measured against the magnitude of the *whole* kernel. They are
        **not** forwarded to the delegated $n = 2$ cross-layer path,
        which carries its own fixed-order grid.
    max_osc_panels
        Budget for the half-period panel family that resolves the
        $J_0(\\lambda s)$ oscillation, default 200 000 panels
        (× 12 Gauss nodes). Only binds for
        $s / d_{\\text{rem}} \\gtrsim 1.9 \\cdot 10^{4}$, i.e. a
        centimetre-thin intermediate layer combined with a
        kilometre-scale horizontal separation; there the coverage is
        incomplete, a :class:`SommerfeldConvergenceWarning` is raised
        and raising this budget is the remedy (cost grows linearly).
    issues
        Optional collector for non-convergence diagnostics; see
        :func:`_reflected_integral`. Used by
        :func:`_build_Z_sommerfeld` to aggregate $O(N^2)$ warnings
        into one.

    Returns
    -------
    G : float

    Raises
    ------
    ValueError
        For $n \\ge 3$ with $z > h_1$ or $z_s > h_1$: the
        expression above is a top-layer form, so the kernel refuses
        instead of silently returning a diverging number (before
        0.15.0 it returned $\\approx -2 \\cdot 10^{127}$ there).

    Warns
    -----
    SommerfeldConvergenceWarning
        If the remainder quadrature does not reach the requested
        tolerance. The returned value is then not converged and its
        sign may be wrong.

    Notes
    -----
    Limits and special cases:

    - ``stack.n_layers == 1`` (homogeneous, $\\Gamma_1 \\equiv 0$):
      short-circuited to $1/r + 1/r_{\\text{img}}$, bit-exact.
    - $\\rho_1 = \\rho_2$ in a declared 2-layer stack
      ($K_1 = 0$, hence $\\Gamma_1 \\equiv 0$): the reflected
      remainder is identically zero, so the same closed form is
      returned bit-exact. This is the strongest available accuracy
      test of the backend.
    - ``stack.n_layers == 2`` with $z > h_1$ or $z_s > h_1$:
      delegated to
      :func:`groundfield.coupling.layered_green.two_layer_real_space_kernel`,
      which solves the cross-layer spectral matching.

    Distances are floored at 1 mm (``_MIN_DISTANCE``), consistently
    with the homogeneous ``image`` backend, so the coincident-point
    limit stays finite.
    """
    # Homogeneous shortcut.
    if stack.n_layers <= 1:
        r = np.sqrt(s**2 + (z - z_s) ** 2)
        r_img = np.sqrt(s**2 + (z + z_s) ** 2)
        return float(1.0 / max(r, _MIN_DISTANCE) + 1.0 / max(r_img, _MIN_DISTANCE))

    # ADR-0006 Phase B: 2-layer soil with cross-layer source/observer.
    # Delegate to coupling.layered_green which solves the full 2-layer
    # spectral matching for any (z_layer, z_s_layer) combination. The
    # caller multiplies by rho_1/(4π); the layered_green kernel
    # internally carries the source-layer rho factor, so we divide
    # out rho_1 here to match the existing convention.
    if stack.n_layers == 2 and (z > stack.h[0] or z_s > stack.h[0]):
        from groundfield.coupling.layered_green import (
            two_layer_real_space_kernel,
        )

        # ``lambda_max_factor`` is measured in units of a geometric
        # length here (1/d_rem on the top-layer path below). It is
        # forwarded verbatim: since F14 (0.15.0) the delegated kernel
        # adds the unresolved image terms back in closed form, so the
        # factor is an upper bound only (30 ... 20 000 change the
        # kernel by <= 1.3e-8, review pass 10).
        rho_1_local = float(stack.rhos[0])
        rho_2_local = float(stack.rhos[1])
        h_1_local = float(stack.h[0])
        # Distances floored at 1 mm like every other branch here: the
        # closed-form 1/R terms of the delegated kernel are clamped at
        # min(h_1/200, 1 mm) instead of h_1/200 (audit A3S-01).
        G_phys = two_layer_real_space_kernel(
            s=s,
            z=z,
            z_s=z_s,
            rho_1=rho_1_local,
            rho_2=rho_2_local,
            h_1=h_1_local,
            lambda_max_factor=lambda_max_factor,
            min_distance=_MIN_DISTANCE,
        )
        # G_phys has rho/2·(1/r + ...) structure; the existing caller
        # forms Z = rho_1/(4π)·G_old, so we want G_old = 2·G_phys/rho_1.
        return float(2.0 * G_phys / rho_1_local)

    # Layered case — full top-layer Sommerfeld form.
    #
    # The complete Green's function of a top-layer source observed in the
    # top layer combines four exponentials, each propagated through the
    # multiple-reflection multiplier 1/(1 - Γ_1(λ)·e^{-2λh_1}):
    #
    #   ξ(λ) = (e^{-λ|z-z_s|} + Γ_1·e^{-λ(2h_1-|z-z_s|)}
    #         + e^{-λ(z+z_s)}  + Γ_1·e^{-λ(2h_1-z-z_s)})
    #          / (1 - Γ_1(λ)·e^{-2λh_1})
    #
    # In the limits Γ_1 → 0 this reduces to the homogeneous form
    # e^{-λ|z-z_s|} + e^{-λ(z+z_s)}; for Γ_1 = K_1 = const it expands
    # into the classical Tagg/Sunde geometric series in K_1^n at images
    # ±2nh_1 ± z_s.
    #
    # The two Γ_1 → 0 terms are the conditionally convergent part of
    # the integral and are taken from Lipschitz' integral in closed
    # form; only the decaying reflected remainder is quadratured.
    h_top = float(stack.h[0])
    z_tol = 1e-9 * max(h_top, 1.0)
    if z > h_top + z_tol or z_s > h_top + z_tol:
        # Only reachable for n >= 3 (n == 2 is handled above). The
        # top-layer form is not valid below the interface; before
        # 0.15.0 it silently returned a diverging number (≈ -2e127).
        raise ValueError(
            "mom_sommerfeld: the n>=3 top-layer Sommerfeld kernel "
            "requires both the field point and the source inside the "
            f"upper layer (got z = {z:.4f} m, z_s = {z_s:.4f} m, "
            f"h_1 = {h_top:.4f} m). Use backend='image_2layer' for "
            "cross-layer geometries on a 2-layer soil."
        )
    abs_dz = abs(z - z_s)
    z_plus = z + z_s
    r = float(np.hypot(s, abs_dz))
    r_img = float(np.hypot(s, z_plus))
    G_direct = 1.0 / max(r, _MIN_DISTANCE) + 1.0 / max(r_img, _MIN_DISTANCE)

    G_refl = _reflected_integral(
        stack,
        s,
        abs_dz,
        z_plus,
        lambda_max_factor=lambda_max_factor,
        epsabs=epsabs,
        epsrel=epsrel,
        reference=G_direct,
        max_osc_panels=max_osc_panels,
        issues=issues,
    )
    return float(G_direct + G_refl)

solve_fem

solve_fem(world: 'World', engine: 'Engine', *, refinement: int = 0, extrapolate: bool = True, r_far_factor: float = 1000.0, far_field: str = 'robin', max_nodes: int = 2000000, max_nodes_3d: int = 2000000, max_ports_3d: int = 100, model: str = 'auto', source_radius: float | None = None, growth: float = 0.5, concrete_resistivity: float | None = None, _concrete_mesh: float | None = None, n_radial: int | None = None, n_axial: int | None = None, z_far_factor: float | None = None) -> FieldResult

Conforming finite-element solve (see the module docstring).

Parameters:

Name Type Description Default
world 'World'

World to solve, any horizontally layered soil, bare or encased electrodes (see model).

required
engine 'Engine'

Engine; its frequencies, earth_inductive_model (conductor branches) and segment_length (the display segments that carry the leakage distribution of the result) are used.

required
refinement int

Refinement level of the coarser of the two meshes (axisymmetric model: each level bisects every interval of the graded mesh lines, about four times the nodes; 3-D model: about eight times). 0 (default) gives a port resistance within about 1e-4 of the converged value for coaxial rods and rings. A ring wire that an interface cuts or comes within 1.05 radii of: within 5.1e-5 of an independent boundary-element model of the solid torus at layer contrasts of 3 ... 1000, on either side, cut or touching (60 cases of audit W4R2A's sweep, estimates 3.9e-4 ... 1.5e-3), and -8.5e-4 touching a layer 10 000 times more conductive (estimate 5.3e-3); refinement=1 within 1.9e-5 and 3.3e-4 (evidence fw4r2a/e05, e08).

0
extrapolate bool

Solve at refinement and refinement + 1 and extrapolate the port conductance matrix with the second order (default). False solves the level refinement alone; its resistance usually lies below the converged value (see Notes) and metadata["fem_error_estimate"] is NaN (one level has no estimate).

True
r_far_factor float

Size of the truncation box in characteristic lengths (the electrodes' size, or the depth of the deepest interface times the layer contrast if larger); dimensionless, default 1000.

1000.0
far_field str

"robin" (default): the exact Dirichlet-to-Neumann map of the monopole far field on the box. "dirichlet": the box grounded, which biases the resistance low by about \(\rho_n/(2\pi R)\) (for truncation studies).

'robin'
max_nodes int

Resource limit of the axisymmetric model: the node count of the finer mesh, estimated before anything is assembled (the estimate errs high). Default 2 million: the solve needs about 4 GB per million nodes of the finer mesh, so about 8 GB at the limit.

2000000
max_nodes_3d int

Resource limit of the three-dimensional model: the node count of its finer mesh, predicted before meshing and counted before the finer level is built. The solve adds about 2.9 GB per million nodes to the peak memory of the process (3.0 ... 3.1 GB with the process itself).

2000000
max_ports_3d int

Resource limit of the three-dimensional model: the number of ports (every electrode and every leaking piece of a galvanic distributed conductor), checked before meshing. Default 100: every port costs one conjugate-gradient solve per mesh level, about 0.9 s per port and level at 600 000 nodes of the finer mesh.

100
model str

"auto" (default): the axisymmetric model where it applies (rods on one axis, rings around it, no galvanic distributed conductor), the three-dimensional model otherwise; "axisymmetric" refuses every other world; "3d" forces the three-dimensional model.

'auto'
source_radius float | None

3-D model: radius in m of the disc over which each wire's leakage is smoothed; None (default) takes 0.06 m (at least 2.2 bare wire radii, at most what the depth of the wires, their gap to the interfaces and the distance of wires that run beside each other — kept 1.5 source radii apart — allow).

None
growth float

3-D model: growth of the element size per metre away from the wires (default 0.5; smaller is finer and slower).

0.5
concrete_resistivity float | None

3-D model: None (default) applies every encased wire's own shell coefficient; a resistivity in Ω·m resolves the concrete as square prisms of conformal radius wire_radius around the encased (axis-aligned, straight) wires, shared where they meet (user decision Q40).

None
_concrete_mesh float | None

Private, for the overlap study of user decision Q40 (see solid_earth()).

None
n_radial int | None

Deprecated: the mesh controls of the equivalent-hemisphere mesh (0.15.0); a value has no effect and warns.

None
n_axial int | None

Deprecated: the mesh controls of the equivalent-hemisphere mesh (0.15.0); a value has no effect and warns.

None
z_far_factor int | None

Deprecated: the mesh controls of the equivalent-hemisphere mesh (0.15.0); a value has no effect and warns.

None

Returns:

Type Description
FieldResult

Electrode potentials and currents (every electrode an equipotential port), point sources with the leakage distribution of the model, and metadata with fem_port_resistance (the extrapolated port resistance matrix in Ω, ports in world order, fem_ports), fem_port_resistance_levels (per mesh level), fem_error_estimate (largest relative difference of a diagonal entry between the extrapolated and the finer level; NaN with extrapolate=False), fem_error_estimate_transfer (3-D model: the same for the transfer entries; NaN for one port or one level), fem_model ("axisymmetric" or "3d": the model that ran), fem_mesh (size and time per level) and fem_r_far (box size in m).

Raises:

Type Description
BackendCapabilityError

With model="axisymmetric": if the world is not axisymmetric (an electrode other than a rod or a ring, a rod or ring off the common axis by more than 1e-3 of the smallest wire radius or gap, a galvanic distributed conductor), its electrodes touch, a ring wire reaches within 5 % of its radius to the soil surface, or a ring has no room for its mesh block (within about a wire radius, diagonally, of a rod's end edge); model="auto" solves these worlds with the three-dimensional model. 3-D model, before meshing: a wire too close to the soil surface or an interface for its smoothed source; wires that do not meet but run beside each other (side by side within 30° of parallel, a folded arm, a small ring around a rod head, two wires that meet at less than 10° or touch along their length) closer than 1.5 times the smallest source radius, and wires end to end in line with a gap, such as stacked rods, closer than 5 times it (the smallest source radius is 2.2 radii of the thickest bare wire of the world, so 3.3 and 11 such radii, axis to axis); wires that meet at 10° or more are left alone; resolved concrete around a wire that is not straight along x, y or z, or whose cover is so thin that the smoothed source does not reach beyond the metal. After meshing: conjugate gradients that do not converge (layer contrasts above about 300). The message names the backends that solve the world. A subclass of ValueError and NotImplementedError.

ImportError

If the world needs the three-dimensional model and the fem3d extra (scikit-fem, pyamg) is not installed.

ValueError

If an electrode or a galvanic distributed conductor lies at or above the soil surface (as every backend), or the world fails World.check.

ResourceLimitError

If the finer mesh would exceed max_nodes nodes (the 3-D model: max_nodes_3d, a prediction before meshing and the exact count before the finer level), or the 3-D model would solve more than max_ports_3d ports; where wires that run beside each other limited the source radius, the message says so.

TypeError

If world.soil is no soil model.

Warns:

Type Description
MixedCoordinatesWarning

For a world that mixes local and projected coordinates (user decision D5), as every backend.

InterfaceContactWarning

3-D model: for a rod end within one wire radius of a layer interface (audit W4R2A-03: a rod tip on 1000/30 Ohm m read +43 % against the solid rod, with an estimate of 6e-3) and for a horizontal wire within the reach of a contrasting one (audits W4A-07, W4B-02), where the smoothed line source shares the thin-wire error of the integral engines; once per rule and solve, as there. The axisymmetric model resolves rod end faces and ring wires and does not warn.

DeprecationWarning

For n_radial, n_axial or z_far_factor.

Notes

Without extrapolation the resistance of the axisymmetric model converges at second order and, in every case tested away from interfaces, from below; this is not guaranteed (the O-grid of a ring is not nested between levels), and next to an interface cut into a ring's mesh block it did not hold before that block was refined (audit W4A-01) and graded towards the points where the interface meets the wire (audit W4R2A-02: touching a 1000 times more conductive layer the levels converged at about first order, the default read -1.6e-2 with an estimate of 1.1e-2). The error estimate bounds the error of the extrapolated value while both levels lie on the same side of the converged value and the finer level's error is at most 1/2.5 of the coarser level's (about 1/3.9 is observed for rods and rings, 1/3.9 ... 1/4.0 for a ring touching a 100 or 1000 times more conductive layer).

Source code in src/groundfield/solver/fem/__init__.py
def solve_fem(
    world: "World",
    engine: "Engine",
    *,
    refinement: int = 0,
    extrapolate: bool = True,
    r_far_factor: float = 1000.0,
    far_field: str = "robin",
    max_nodes: int = 2_000_000,
    max_nodes_3d: int = 2_000_000,
    max_ports_3d: int = 100,
    model: str = "auto",
    source_radius: float | None = None,
    growth: float = 0.5,
    concrete_resistivity: float | None = None,
    _concrete_mesh: float | None = None,
    n_radial: int | None = None,
    n_axial: int | None = None,
    z_far_factor: float | None = None,
) -> FieldResult:
    """Conforming finite-element solve (see the module docstring).

    Parameters
    ----------
    world
        World to solve, any horizontally layered soil, bare or encased
        electrodes (see ``model``).
    engine
        Engine; its ``frequencies``, ``earth_inductive_model`` (conductor
        branches) and ``segment_length`` (the display segments that carry
        the leakage distribution of the result) are used.
    refinement
        Refinement level of the coarser of the two meshes (axisymmetric
        model: each level bisects every interval of the graded mesh lines,
        about four times the nodes; 3-D model: about eight times). ``0``
        (default) gives a port resistance within about 1e-4 of the
        converged value for coaxial rods and rings. A ring wire that an
        interface cuts or comes within 1.05 radii of: within 5.1e-5 of an
        independent boundary-element model of the solid torus at layer
        contrasts of 3 ... 1000, on either side, cut or touching (60 cases
        of audit W4R2A's sweep, estimates 3.9e-4 ... 1.5e-3), and -8.5e-4
        touching a layer 10 000 times more conductive (estimate 5.3e-3);
        ``refinement=1`` within 1.9e-5 and 3.3e-4 (evidence ``fw4r2a/e05``,
        ``e08``).
    extrapolate
        Solve at ``refinement`` and ``refinement + 1`` and extrapolate the
        port conductance matrix with the second order (default). ``False``
        solves the level ``refinement`` alone; its resistance usually lies
        below the converged value (see *Notes*) and
        ``metadata["fem_error_estimate"]`` is ``NaN`` (one level has no
        estimate).
    r_far_factor
        Size of the truncation box in characteristic lengths (the
        electrodes' size, or the depth of the deepest interface times the
        layer contrast if larger); dimensionless, default 1000.
    far_field
        ``"robin"`` (default): the exact Dirichlet-to-Neumann map of the
        monopole far field on the box. ``"dirichlet"``: the box grounded,
        which biases the resistance low by about $\\rho_n/(2\\pi R)$ (for
        truncation studies).
    max_nodes
        Resource limit of the axisymmetric model: the node count of the
        finer mesh, estimated before anything is assembled (the estimate
        errs high). Default 2 million: the solve needs about 4 GB per
        million nodes of the finer mesh, so about 8 GB at the limit.
    max_nodes_3d
        Resource limit of the three-dimensional model: the node count of
        its finer mesh, predicted before meshing and counted before the
        finer level is built. The solve adds about 2.9 GB per million nodes
        to the peak memory of the process (3.0 ... 3.1 GB with the process
        itself).
    max_ports_3d
        Resource limit of the three-dimensional model: the number of ports
        (every electrode and every leaking piece of a galvanic distributed
        conductor), checked before meshing. Default 100: every port costs
        one conjugate-gradient solve per mesh level, about 0.9 s per port
        and level at 600 000 nodes of the finer mesh.
    model
        ``"auto"`` (default): the axisymmetric model where it applies (rods
        on one axis, rings around it, no galvanic distributed conductor),
        the three-dimensional model otherwise; ``"axisymmetric"`` refuses
        every other world; ``"3d"`` forces the three-dimensional model.
    source_radius
        3-D model: radius in m of the disc over which each wire's leakage
        is smoothed; ``None`` (default) takes 0.06 m (at least 2.2 bare
        wire radii, at most what the depth of the wires, their gap to the
        interfaces and the distance of wires that run beside each other —
        kept 1.5 source radii apart — allow).
    growth
        3-D model: growth of the element size per metre away from the
        wires (default 0.5; smaller is finer and slower).
    concrete_resistivity
        3-D model: ``None`` (default) applies every encased wire's own
        shell coefficient; a resistivity in Ω·m resolves the concrete as
        square prisms of conformal radius ``wire_radius`` around the
        encased (axis-aligned, straight) wires, shared where they meet
        (user decision Q40).
    _concrete_mesh
        Private, for the overlap study of user decision Q40 (see
        :func:`~groundfield.solver.fem._solid.solid_earth`).
    n_radial, n_axial, z_far_factor
        Deprecated: the mesh controls of the equivalent-hemisphere mesh
        (0.15.0); a value has no effect and warns.

    Returns
    -------
    FieldResult
        Electrode potentials and currents (every electrode an
        equipotential port), point sources with the leakage distribution of
        the model, and ``metadata`` with ``fem_port_resistance`` (the
        extrapolated port resistance matrix in Ω, ports in world order,
        ``fem_ports``), ``fem_port_resistance_levels`` (per mesh level),
        ``fem_error_estimate`` (largest relative difference of a diagonal
        entry between the extrapolated and the finer level; ``NaN`` with
        ``extrapolate=False``), ``fem_error_estimate_transfer`` (3-D model:
        the same for the transfer entries; ``NaN`` for one port or one
        level), ``fem_model`` (``"axisymmetric"`` or
        ``"3d"``: the model that ran), ``fem_mesh`` (size and time per
        level) and ``fem_r_far`` (box size in m).

    Raises
    ------
    BackendCapabilityError
        With ``model="axisymmetric"``: if the world is not axisymmetric (an
        electrode other than a rod or a ring, a rod or ring off the common
        axis by more than 1e-3 of the smallest wire radius or gap, a
        galvanic distributed conductor), its electrodes touch, a ring wire
        reaches within 5 % of its radius to the soil surface, or a ring has
        no room for its mesh block (within about a wire radius, diagonally,
        of a rod's end edge); ``model="auto"`` solves these worlds with the
        three-dimensional model.
        3-D model, before meshing: a wire too close to the soil surface or
        an interface for its smoothed source; wires that do not meet but
        run beside each other (side by side within 30° of parallel, a
        folded arm, a small ring around a rod head, two wires that meet at
        less than 10° or touch along their length) closer than 1.5 times
        the smallest source radius, and wires end to end in line with a
        gap, such as stacked rods, closer than 5 times it (the smallest
        source radius is 2.2 radii of the thickest bare wire of the world,
        so 3.3 and 11 such radii, axis to axis); wires that meet at 10° or
        more are left alone; resolved concrete around a wire that is not straight along x, y or
        z, or whose cover is so thin that the smoothed source does not
        reach beyond the metal. After meshing: conjugate gradients that do
        not converge (layer contrasts above about 300). The message names
        the backends that solve the world. A subclass of ``ValueError`` and
        ``NotImplementedError``.
    ImportError
        If the world needs the three-dimensional model and the ``fem3d``
        extra (scikit-fem, pyamg) is not installed.
    ValueError
        If an electrode or a galvanic distributed conductor lies at or
        above the soil surface (as every backend), or the world fails
        :meth:`World.check <groundfield.world.World.check>`.
    groundfield.diagnostics.ResourceLimitError
        If the finer mesh would exceed ``max_nodes`` nodes (the 3-D model:
        ``max_nodes_3d``, a prediction before meshing and the exact count
        before the finer level), or the 3-D model would solve more than
        ``max_ports_3d`` ports; where wires that run beside each other
        limited the source radius, the message says so.
    TypeError
        If ``world.soil`` is no soil model.

    Warns
    -----
    MixedCoordinatesWarning
        For a world that mixes local and projected coordinates (user
        decision D5), as every backend.
    InterfaceContactWarning
        3-D model: for a rod end within one wire radius of a layer
        interface (audit W4R2A-03: a rod tip on 1000/30 Ohm m read +43 %
        against the solid rod, with an estimate of 6e-3) and for a
        horizontal wire within the reach of a contrasting one (audits
        W4A-07, W4B-02), where the smoothed line source shares the
        thin-wire error of the integral engines; once per rule and solve,
        as there. The axisymmetric model resolves rod end faces and ring
        wires and does not warn.
    DeprecationWarning
        For ``n_radial``, ``n_axial`` or ``z_far_factor``.

    Notes
    -----
    Without extrapolation the resistance of the axisymmetric model
    converges at second order and, in every case tested away from
    interfaces, from below; this is not guaranteed (the O-grid of a ring
    is not nested between levels), and next to an interface cut into a
    ring's mesh block it did not hold before that block was refined (audit
    W4A-01) and graded towards the points where the interface meets the
    wire (audit W4R2A-02: touching a 1000 times more conductive layer the
    levels converged at about first order, the default read -1.6e-2 with
    an estimate of 1.1e-2). The error estimate bounds the error of the
    extrapolated value while both levels lie on the same side of the
    converged value and the finer level's error is at most 1/2.5 of the
    coarser level's (about 1/3.9 is observed for rods and rings, 1/3.9 ...
    1/4.0 for a ring touching a 100 or 1000 times more conductive layer).
    """
    from groundfield.soil.models import HomogeneousSoil, MultiLayerSoil, TwoLayerSoil
    from groundfield.solver import _frame

    _warn_deprecated_mesh_arguments(
        n_radial=n_radial, n_axial=n_axial, z_far_factor=z_far_factor
    )
    if far_field not in _FAR_FIELDS:
        raise ValueError(
            "far_field must be 'robin' (monopole DtN) or 'dirichlet' "
            f"(grounded truncation box), got {far_field!r}."
        )
    if int(refinement) != refinement or refinement < 0:
        raise ValueError(f"refinement must be an integer >= 0, got {refinement!r}.")
    if not r_far_factor > 1.0:
        raise ValueError(f"r_far_factor must be > 1, got {r_far_factor!r}.")
    if not isinstance(world.soil, (HomogeneousSoil, TwoLayerSoil, MultiLayerSoil)):
        raise TypeError(
            "Backend 'fem' supports HomogeneousSoil, TwoLayerSoil, "
            f"and MultiLayerSoil. Got: {type(world.soil).__name__}."
        )
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")
    if model not in _MODELS:
        raise ValueError(
            f"model must be one of {', '.join(repr(m) for m in _MODELS)}, got {model!r}."
        )
    if source_radius is not None and not (
        math.isfinite(float(source_radius)) and float(source_radius) > 0.0
    ):
        raise ValueError(
            f"source_radius must be a positive length in m, got {source_radius!r}."
        )
    if not (math.isfinite(float(growth)) and 0.05 <= float(growth) <= 2.0):
        raise ValueError(f"growth must lie in [0.05, 2], got {growth!r}.")
    if concrete_resistivity is not None and not (
        math.isfinite(float(concrete_resistivity)) and float(concrete_resistivity) > 0.0
    ):
        raise ValueError(
            "concrete_resistivity must be a positive resistivity in Ohm m or None, "
            f"got {concrete_resistivity!r}."
        )
    frame = _frame.LocalFrame.of(world)
    with frame.active():
        result = _solve(
            frame.world,
            engine,
            refinement=int(refinement),
            extrapolate=bool(extrapolate),
            r_far_factor=float(r_far_factor),
            far_field=far_field,
            max_nodes=int(max_nodes),
            model=model,
            solid={
                "source_radius_m": None
                if source_radius is None
                else float(source_radius),
                "growth": float(growth),
                "concrete_resistivity": None
                if concrete_resistivity is None
                else float(concrete_resistivity),
                "concrete_mesh": _concrete_mesh,
                "max_nodes_3d": int(max_nodes_3d),
                "max_ports_3d": int(max_ports_3d),
            },
        )
    return frame.to_user(result)

Deprecated backend names

cim, bem and image_nlayer are deprecated names of image and mom (see Deprecations); their solve functions forward to the current backends. The complex-image fit of the cim module (fit_complex_images, ComplexImageFit) is a stand-alone tool that no backend evaluates. equivalent_hemisphere_radius is deprecated: it belongs to the hemisphere reduction that fem no longer uses.

solve_cim

solve_cim(world: World, engine: Engine) -> FieldResult

Run the image auto-dispatch under the deprecated backend name cim.

cim never evaluated a complex-image fit on a reachable path: for \(n = 1\) it used the homogeneous image kernel and for \(n = 2\) the exact Tagg/Sunde series, i.e. it reproduced image and image_2layer (bit for bit since the length-weighted read-back of 10.30). Since review pass 10 (10.76) the name is a deprecated alias: this function runs the backend image would run for the soil model — solve_image() for a HomogeneousSoil, solve_image_2layer() for a TwoLayerSoil and the layered router for a MultiLayerSoil — with the engine's series controls, so a two-layer world also gets the cross-layer treatment of image_2layer. fit_complex_images() stays available as a spectral helper.

Parameters:

Name Type Description Default
world World

World to evaluate.

required
engine Engine

Engine configuration; engine.segment_length (m) controls the discretisation, engine.image_max_terms / engine.image_series_tol the Tagg/Sunde truncation at \(n = 2\).

required

Returns:

Type Description
FieldResult

The result of the image backend, labelled backend="cim" with metadata['dispatched_to'] naming the backend that ran.

Raises:

Type Description
NotImplementedError

For three or more distinct soil layers (use mom_sommerfeld).

Warns:

Type Description
DeprecationWarning

Always: use backend="image" (image_2layer for two-layer soil) instead; the alias is removed no earlier than groundfield 2027.5.

Source code in src/groundfield/solver/cim.py
def solve_cim(world: World, engine: Engine) -> FieldResult:
    """Run the image auto-dispatch under the deprecated backend name ``cim``.

    ``cim`` never evaluated a complex-image fit on a reachable path: for
    $n = 1$ it used the homogeneous image kernel and for $n = 2$ the
    exact Tagg/Sunde series, i.e. it reproduced ``image`` and
    ``image_2layer`` (bit for bit since the length-weighted read-back of
    10.30). Since review pass 10 (10.76) the name is a deprecated alias:
    this function runs the backend ``image`` would run for the soil
    model — :func:`~groundfield.solver.image.solve_image` for a
    :class:`HomogeneousSoil`,
    :func:`~groundfield.solver.image_2layer.solve_image_2layer` for a
    :class:`TwoLayerSoil` and the layered router for a
    :class:`MultiLayerSoil` — with the engine's series controls, so a
    two-layer world also gets the cross-layer treatment of
    ``image_2layer``. :func:`fit_complex_images` stays available as a
    spectral helper.

    Parameters
    ----------
    world
        World to evaluate.
    engine
        Engine configuration; ``engine.segment_length`` (m) controls the
        discretisation, ``engine.image_max_terms`` /
        ``engine.image_series_tol`` the Tagg/Sunde truncation at
        $n = 2$.

    Returns
    -------
    FieldResult
        The result of the image backend, labelled ``backend="cim"`` with
        ``metadata['dispatched_to']`` naming the backend that ran.

    Raises
    ------
    NotImplementedError
        For three or more distinct soil layers (use ``mom_sommerfeld``).

    Warns
    -----
    DeprecationWarning
        Always: use ``backend="image"`` (``image_2layer`` for two-layer
        soil) instead; the alias is removed no earlier than groundfield
        2027.5.
    """
    from groundfield.solver.image import solve_image
    from groundfield.solver.image_2layer import solve_image_2layer
    from groundfield.solver.image_nlayer import solve_image_nlayer
    from groundfield.solver.registry import DEPRECATION_REMOVAL, warn_external

    warn_external(
        "Backend name 'cim' (groundfield.solver.cim.solve_cim) is deprecated; "
        "use 'image' instead, which runs 'image_2layer' for two-layer soil "
        "(the series 'cim' evaluated). The alias will be removed no earlier "
        f"than {DEPRECATION_REMOVAL}.",
        DeprecationWarning,
    )
    soil = world.soil
    if not isinstance(soil, (HomogeneousSoil, TwoLayerSoil, MultiLayerSoil)):
        raise TypeError(
            "Backend 'cim' supports HomogeneousSoil, TwoLayerSoil, "
            f"and MultiLayerSoil. Got: {type(soil).__name__}."
        )
    n_layers = as_layer_stack(soil).n_layers
    if n_layers >= 3:
        raise NotImplementedError(
            f"cim: n_layers = {n_layers} >= 3 is not supported — the "
            "historic complex-image kernel was structurally incomplete "
            "(audit 2026-07-08). Use backend='mom_sommerfeld' (full layered "
            "Green's function) for n >= 3 soils."
        )
    # The forwarding rules of backend 'image' (registry): by soil model.
    if isinstance(soil, HomogeneousSoil):
        res = solve_image(world, engine)
    elif isinstance(soil, TwoLayerSoil):
        res = solve_image_2layer(
            world, engine, max_terms=engine.image_max_terms, tol=engine.image_series_tol
        )
    else:
        res = solve_image_nlayer(
            world, engine, max_terms=engine.image_max_terms, tol=engine.image_series_tol
        )
    return res.model_copy(
        update={
            "backend": "cim",
            "metadata": {**res.metadata, "dispatched_to": res.backend},
        }
    )

fit_complex_images

fit_complex_images(stack: LayerStack, *, n_images: int = 8, n_samples: int = 64, lambda_min_factor: float = 0.001, lambda_max_factor: float = 50.0, rms_tol: float = _DEFAULT_RMS_TOL, warn: bool = True) -> ComplexImageFit

Fit Γ_1(λ) of an n-layer stack by n_images complex exponentials.

Physical / mathematical context

The upward-looking reflection coefficient of a stratified half-space (see groundfield.solver._layered.reflection_gamma()) is a rational function of the interface attenuations \(e^{-2 \lambda h_i}\). It is not a decaying function: it tends to the top-interface Fresnel coefficient

\[ \lim_{\lambda \to \infty} \Gamma_1(\lambda) \;=\; K_1 \;=\; \frac{\rho_2 - \rho_1}{\rho_2 + \rho_1}, \]

while a sum \(\sum_k a_k e^{-2\lambda\beta_k}\) with \(\Re\{\beta_k\} > 0\) tends to 0. The asymptote is hence split off analytically and carried by an image at \(\beta_0 = 0\) (weight \(K_1\); in the spatial domain an image at the air-mirror position \(z = -z_s\), integrable through the Sommerfeld identity because \(d = z + z_s > 0\)), and the matrix pencil only sees the genuinely decaying remainder \(\Gamma_1(\lambda) - K_1\).

Steps:

  1. Build a uniform sampling grid \(\lambda_j = \lambda_{\min} + j \Delta\). Only the thicknesses \(h_2, \dots, h_{n-1}\) enter \(\Gamma_1\) (the recursion never uses \(h_1\)), so the structure scale is \(h_{\max} = \max_i h_{i\ge2}\) and the decay scale is \(h_{\min} = \min_i h_{i\ge2}\): the step is capped at \(\Delta \le 1/(8 h_{\max})\) so the slowest exponential is resolved, and the window reaches up to \(\lambda_{\max} = \lambda_{\max,\text{factor}}/h_{\min}\) where the fastest one has died.
  2. Sample \(g_j = \Gamma_1(\lambda_j)\) and subtract \(K_1\).
  3. Apply the matrix-pencil method to the remainder to recover the poles \(p_k = e^{-2 \Delta \beta_k}\), filtered to \(|p_k| < 0.999\) and \(\Re\{\beta_k\} > 0\).
  4. Re-solve the least-squares coefficients \(a_k\) for the surviving \(\{\beta_k\} \cup \{0\}\) on the original samples of \(\Gamma_1\) — the filtered model is therefore self-consistent (up to 0.14.1 the coefficients were solved before the filter and then merely sliced, so the reported weights belonged to a different model).

Special cases:

  • stack.n_layers <= 1 → empty fit (\(\Gamma_1 \equiv 0\)).
  • stack.n_layers == 2 → \(\Gamma_1 \equiv K_1\) exactly; the single \(\beta = 0\) image reproduces it with rms = 0 (up to 0.14.1 this returned P = 0 and rms = nan).
  • \(\rho_1 = \dots = \rho_n\) → empty fit.
Notes

No solver path calls this function: the backend name cim is a deprecated alias of the closed-form image backends (see the module docstring). It is kept public as the spectral building block for a future complete \(n \ge 3\) complex-image kernel, and it reports failure instead of hiding it.

Parameters:

Name Type Description Default
stack LayerStack

Layer stack to fit.

required
n_images int

Target number of decaying complex images. Sensible range 4–12; the returned \(P\) is one larger when the asymptote image is present, and may be smaller when the SVD truncates poles.

8
n_samples int

Number of samples drawn from Γ_1(λ).

64
lambda_min_factor float

Lower grid bound as a multiple of \(1/h_{\max}\).

0.001
lambda_max_factor float

Upper grid bound as a multiple of \(1/h_{\min}\) (an upper bound only — the step cap of item 1 above may stop the grid earlier).

50.0
rms_tol float

Error bound (dimensionless, \(|\Gamma_1| \le 1\)): the RMS residual on the fitting grid, the RMS residual on the verification grid and the maximum error on the verification grid including \(\lambda = 0\) must not exceed it, otherwise the fit counts as failed (converged=False plus a ComplexImageFitWarning). The maximum-error gate was added in review pass 10 (10.49).

_DEFAULT_RMS_TOL
warn bool

Set to False to suppress the warning in bulk sweeps; converged / rms / rms_extrapolated / max_error still report the failure.

True

Returns:

Type Description
ComplexImageFit

Warns:

Type Description
ComplexImageFitWarning

If rms or rms_extrapolated exceeds rms_tol, or the pencil produced no usable pole for a non-flat remainder.

Source code in src/groundfield/solver/cim.py
def fit_complex_images(
    stack: LayerStack,
    *,
    n_images: int = 8,
    n_samples: int = 64,
    lambda_min_factor: float = 1e-3,
    lambda_max_factor: float = 50.0,
    rms_tol: float = _DEFAULT_RMS_TOL,
    warn: bool = True,
) -> ComplexImageFit:
    """Fit Γ_1(λ) of an n-layer stack by ``n_images`` complex exponentials.

    Physical / mathematical context
    ------------------------------
    The upward-looking reflection coefficient of a stratified
    half-space (see :func:`groundfield.solver._layered.reflection_gamma`)
    is a rational function of the interface attenuations
    $e^{-2 \\lambda h_i}$. It is **not** a decaying function: it
    tends to the top-interface Fresnel coefficient

    $$
    \\lim_{\\lambda \\to \\infty} \\Gamma_1(\\lambda)
    \\;=\\; K_1 \\;=\\; \\frac{\\rho_2 - \\rho_1}{\\rho_2 + \\rho_1},
    $$

    while a sum $\\sum_k a_k e^{-2\\lambda\\beta_k}$ with
    $\\Re\\{\\beta_k\\} > 0$ tends to 0. The asymptote is hence
    split off analytically and carried by an image at
    $\\beta_0 = 0$ (weight $K_1$; in the spatial domain an image
    at the air-mirror position $z = -z_s$, integrable through the
    Sommerfeld identity because $d = z + z_s > 0$), and the matrix
    pencil only sees the genuinely decaying remainder
    $\\Gamma_1(\\lambda) - K_1$.

    Steps:

    1. Build a uniform sampling grid
       $\\lambda_j = \\lambda_{\\min} + j \\Delta$. Only the
       thicknesses $h_2, \\dots, h_{n-1}$ enter $\\Gamma_1$
       (the recursion never uses $h_1$), so the *structure* scale is
       $h_{\\max} = \\max_i h_{i\\ge2}$ and the *decay* scale is
       $h_{\\min} = \\min_i h_{i\\ge2}$: the step is capped at
       $\\Delta \\le 1/(8 h_{\\max})$ so the slowest exponential is
       resolved, and the window reaches up to
       $\\lambda_{\\max} = \\lambda_{\\max,\\text{factor}}/h_{\\min}$
       where the fastest one has died.
    2. Sample $g_j = \\Gamma_1(\\lambda_j)$ and subtract $K_1$.
    3. Apply the matrix-pencil method to the remainder to recover the
       poles $p_k = e^{-2 \\Delta \\beta_k}$, filtered to
       $|p_k| < 0.999$ and $\\Re\\{\\beta_k\\} > 0$.
    4. Re-solve the least-squares coefficients $a_k$ for the
       *surviving* $\\{\\beta_k\\} \\cup \\{0\\}$ on the original
       samples of $\\Gamma_1$ — the filtered model is therefore
       self-consistent (up to 0.14.1 the coefficients were solved
       before the filter and then merely sliced, so the reported
       weights belonged to a different model).

    Special cases:

    - ``stack.n_layers <= 1`` → empty fit ($\\Gamma_1 \\equiv 0$).
    - ``stack.n_layers == 2`` → $\\Gamma_1 \\equiv K_1$ exactly;
      the single $\\beta = 0$ image reproduces it with ``rms = 0``
      (up to 0.14.1 this returned ``P = 0`` and ``rms = nan``).
    - $\\rho_1 = \\dots = \\rho_n$ → empty fit.

    Notes
    -----
    No solver path calls this function: the backend name ``cim`` is a
    deprecated alias of the closed-form image backends (see the module
    docstring). It is kept public as the spectral building block for a
    future complete $n \\ge 3$ complex-image kernel, and it reports
    failure instead of hiding it.

    Parameters
    ----------
    stack
        Layer stack to fit.
    n_images
        Target number of *decaying* complex images. Sensible range
        4–12; the returned $P$ is one larger when the asymptote
        image is present, and may be smaller when the SVD truncates
        poles.
    n_samples
        Number of samples drawn from Γ_1(λ).
    lambda_min_factor
        Lower grid bound as a multiple of $1/h_{\\max}$.
    lambda_max_factor
        Upper grid bound as a multiple of $1/h_{\\min}$ (an upper
        bound only — the step cap of item 1 above may stop the grid
        earlier).
    rms_tol
        Error bound (dimensionless, $|\\Gamma_1| \\le 1$): the RMS
        residual on the fitting grid, the RMS residual on the
        verification grid *and* the maximum error on the verification
        grid including $\\lambda = 0$ must not exceed it, otherwise the
        fit counts as failed (``converged=False`` plus a
        :class:`ComplexImageFitWarning`). The maximum-error gate was
        added in review pass 10 (10.49).
    warn
        Set to ``False`` to suppress the warning in bulk sweeps;
        ``converged`` / ``rms`` / ``rms_extrapolated`` / ``max_error``
        still report the
        failure.

    Returns
    -------
    ComplexImageFit

    Warns
    -----
    ComplexImageFitWarning
        If ``rms`` or ``rms_extrapolated`` exceeds ``rms_tol``, or the
        pencil produced no usable pole for a non-flat remainder.
    """
    if stack.n_layers <= 1:
        return _empty_fit()

    k_inf = float(stack.K[0])

    # Only h_2 … h_{n-1} enter Γ_1 — the recursion in
    # `reflection_gamma` never touches h_1.
    h_rel = np.asarray(stack.h[1:], dtype=float)

    if h_rel.size == 0:
        # n == 2: Γ_1 ≡ K_1, a constant. Exactly one image, at β = 0.
        if abs(k_inf) < _FLAT_TOL:
            return _empty_fit()
        return ComplexImageFit(
            a=np.array([k_inf + 0j]),
            beta=np.zeros(1, dtype=complex),
            rms=0.0,
            k_inf=k_inf,
            converged=True,
        )

    h_struct = float(np.max(h_rel))
    h_decay = float(np.min(h_rel))
    lam_min = lambda_min_factor / h_struct
    lam_max = lambda_max_factor / h_decay

    # Uniform spacing required by the matrix-pencil method; capped so
    # the slowest exponential (scale 1/(2 h_struct)) is resolved.
    delta = min(
        (lam_max - lam_min) / (n_samples - 1),
        1.0 / (_SAMPLES_PER_STRUCTURE_SCALE * h_struct),
    )
    lam = lam_min + delta * np.arange(n_samples)
    g = reflection_gamma(stack, lam).astype(complex)

    # Degenerate case ρ_1 = ρ_2 = … = ρ_n: nothing to fit.
    if np.max(np.abs(g)) < _FLAT_TOL:
        return _empty_fit()

    resid = g - k_inf
    if np.max(np.abs(resid)) < _FLAT_TOL:
        # Γ_1 is constant on the whole window (e.g. ρ_2 = … = ρ_n).
        return ComplexImageFit(
            a=np.array([k_inf + 0j]),
            beta=np.zeros(1, dtype=complex),
            rms=float(np.sqrt(np.mean(np.abs(resid) ** 2))),
            k_inf=k_inf,
            converged=True,
        )

    beta_decay = _matrix_pencil_beta(resid, delta, n_images)
    pencil_failed = beta_decay.size == 0

    # β = 0 (the analytic asymptote) plus the decaying images.
    beta = np.concatenate([np.zeros(1, dtype=complex), beta_decay])

    # Coefficients a_k by linear least squares on the original samples
    # of Γ_1 — solved *after* all pole filtering.
    A = np.exp(-2.0 * lam[:, None] * beta[None, :])  # (n_samples, P)
    a, *_ = np.linalg.lstsq(A, g, rcond=None)
    rms = float(np.sqrt(np.mean(np.abs(A @ a - g) ** 2)))

    # Independent verification on a log-spaced grid over the *full*
    # requested λ range: the uniform fitting window may stop well
    # below λ_max when the thickness spread is large, and a residual
    # measured on the fitting grid alone cannot see that.
    lam_v = np.logspace(np.log10(lam_min), np.log10(lam_max), _N_VERIFY)
    g_v = reflection_gamma(stack, lam_v).astype(complex)
    model_v = np.exp(-2.0 * lam_v[:, None] * beta[None, :]) @ a
    rms_wide = float(np.sqrt(np.mean(np.abs(model_v - g_v) ** 2)))
    # Max-norm on the same grid plus lambda = 0, where the static
    # Green's function is most sensitive (review pass 10, 10.49): an RMS
    # gate let localised misses between the fitting samples through.
    err_0 = abs(complex(np.sum(a)) - complex(reflection_gamma(stack, np.zeros(1))[0]))
    max_err = float(max(np.max(np.abs(model_v - g_v)), err_0))

    converged = (
        bool(rms <= rms_tol)
        and bool(rms_wide <= rms_tol)
        and bool(max_err <= rms_tol)
        and not pencil_failed
    )

    _log.info(
        "cim.fit: n_images_used=%d (P_decay=%d), rms=%.2e, "
        "rms_extrapolated=%.2e, K_1=%.4f, n_layers=%d, "
        "lam=[%.3g, %.3g], delta=%.3g",
        beta.size,
        beta_decay.size,
        rms,
        rms_wide,
        k_inf,
        stack.n_layers,
        lam[0],
        lam[-1],
        delta,
    )
    if not converged and warn:
        if pencil_failed:
            reason = (
                "the matrix pencil returned no usable pole for a "
                "non-flat remainder Γ_1 - K_1"
            )
        elif rms > rms_tol:
            reason = f"RMS residual {rms:.3e} > rms_tol {rms_tol:.3e}"
        elif rms_wide > rms_tol:
            reason = (
                f"RMS residual on the verification grid "
                f"{rms_wide:.3e} > rms_tol {rms_tol:.3e}"
            )
        else:
            reason = (
                f"maximum error on the verification grid incl. lambda = 0 "
                f"{max_err:.3e} > rms_tol {rms_tol:.3e}"
            )
        warnings.warn(
            f"fit_complex_images: unreliable fit for an "
            f"{stack.n_layers}-layer stack ({reason}). Grid: "
            f"lambda in [{lam[0]:.3g}, {lam[-1]:.3g}], delta="
            f"{delta:.3g}, structure scale 1/(2*h_max)="
            f"{1.0 / (2.0 * h_struct):.3g}, decay scale "
            f"1/(2*h_min)={1.0 / (2.0 * h_decay):.3g}. Raise "
            "n_samples / n_images, or widen lambda_max_factor when the "
            "thickness spread h_max/h_min is large. Do not use these "
            "images in a Green's function.",
            ComplexImageFitWarning,
            stacklevel=2,
        )
    return ComplexImageFit(
        a=a,
        beta=beta,
        rms=rms,
        k_inf=k_inf,
        rms_extrapolated=rms_wide,
        converged=converged,
        max_error=max_err,
    )

ComplexImageFit dataclass

ComplexImageFit(a: ndarray, beta: ndarray, rms: float, k_inf: float = 0.0, rms_extrapolated: float = 0.0, converged: bool = True, max_error: float = 0.0)

Result of fit_complex_images().

The fit represents \(\Gamma_1(\lambda) \approx \sum_k a_k e^{-2 \lambda \beta_k}\). Index 0 is the analytic asymptote image (\(\beta_0 = 0\), \(a_0 \approx K_1\)) whenever the stack has one; the remaining entries are the decaying images recovered by the matrix pencil.

Attributes:

Name Type Description
a (ndarray, shape(P), complex)

Image weights \(a_k\).

beta (ndarray, shape(P), complex)

Image depths \(\beta_k\) (units of metres).

rms float

RMS of the residual \(|\text{fit} - \Gamma_1|\) on the sample grid. Always finite: a failed fit reports the residual it actually achieved (and warns) instead of nan.

k_inf float

The \(\lambda \to \infty\) asymptote \(K_1 = (\rho_2 - \rho_1)/(\rho_2 + \rho_1)\) that the \(\beta = 0\) image carries. 0.0 for a homogeneous stack.

rms_extrapolated float

RMS of the same residual on an independent log-spaced verification grid covering the full requested \(\lambda\) range. Larger than rms when the uniform fitting window did not reach the decay band of the thinnest layer (large thickness spread) or when the pencil overfitted.

converged bool

Both residuals and max_error are <= rms_tol, and the decaying remainder was either numerically flat or successfully fitted. False means a ComplexImageFitWarning was emitted.

max_error float

Maximum of \(|\text{fit} - \Gamma_1|\) over \(\lambda = 0\) and the verification grid. The RMS values average a localised miss away: between the uniform fitting samples the model can be off by more than rms_tol while both RMS values stay below it (review pass 10, 10.49: 2.4e-3 against an RMS of 9.3e-4).

solve_bem

solve_bem(world: World, engine: Engine) -> FieldResult

Run the point-matching mom solver under the deprecated name bem.

Runs groundfield.solver.mom.solve_mom() (review pass 10, 10.76); bem assembled the identical point-matching system, see the module docstring.

Parameters:

Name Type Description Default
world World

World to evaluate.

required
engine Engine

Engine configuration; engine.segment_length (m) controls the discretisation, engine.image_max_terms / engine.image_series_tol the Tagg/Sunde truncation for two layers.

required

Returns:

Type Description
FieldResult

The mom result, labelled backend="bem" with metadata['dispatched_to'] = 'mom'.

Warns:

Type Description
DeprecationWarning

Always: use backend="mom" (solve_mom()) instead; the alias is removed no earlier than groundfield 2027.5.

Source code in src/groundfield/solver/bem.py
def solve_bem(world: World, engine: Engine) -> FieldResult:
    """Run the point-matching ``mom`` solver under the deprecated name ``bem``.

    Runs :func:`groundfield.solver.mom.solve_mom` (review pass 10,
    10.76); ``bem`` assembled the identical point-matching system, see
    the module docstring.

    Parameters
    ----------
    world
        World to evaluate.
    engine
        Engine configuration; ``engine.segment_length`` (m) controls the
        discretisation, ``engine.image_max_terms`` /
        ``engine.image_series_tol`` the Tagg/Sunde truncation for two
        layers.

    Returns
    -------
    FieldResult
        The ``mom`` result, labelled ``backend="bem"`` with
        ``metadata['dispatched_to'] = 'mom'``.

    Warns
    -----
    DeprecationWarning
        Always: use ``backend="mom"`` (:func:`solve_mom`) instead; the
        alias is removed no earlier than groundfield 2027.5.
    """
    warn_external(
        "Backend name 'bem' (groundfield.solver.bem.solve_bem) is deprecated; "
        "use 'mom' (solve_mom) instead — it assembles the identical "
        "point-matching system. The alias will be removed no earlier than "
        f"{DEPRECATION_REMOVAL}.",
        DeprecationWarning,
    )
    res = solve_mom(world, engine)
    return res.model_copy(
        update={
            "backend": "bem",
            "metadata": {**res.metadata, "dispatched_to": res.backend},
        }
    )

solve_image_nlayer

solve_image_nlayer(world: 'World', engine: 'Engine', *, max_terms: int | None = None, tol: float | None = None) -> FieldResult

Image-charge dispatcher for n-layer soil.

Routes to image for n = 1 and to image_2layer for n = 2. For n \ge 3 raises a clear ValueError pointing the caller to the engines that actually support that regime.

Parameters:

Name Type Description Default
world 'World'

World whose soil is any layered soil model.

required
engine 'Engine'

Engine configuration; engine.segment_length controls the discretisation.

required
max_terms int | None

Series controls forwarded to solve_image_2layer() for n = 2 (None, the default, takes engine.image_max_terms / engine.image_series_tol); ignored otherwise.

None
tol int | None

Series controls forwarded to solve_image_2layer() for n = 2 (None, the default, takes engine.image_max_terms / engine.image_series_tol); ignored otherwise.

None

Returns:

Type Description
FieldResult

backend is rewritten to "image_nlayer" so that cross-engine reports use one unified label.

Raises:

Type Description
TypeError

If the soil is not a HomogeneousSoil, TwoLayerSoil or MultiLayerSoil.

ValueError

If the world has no electrodes.

BackendCapabilityError

If the soil has three or more layers (a ValueError subclass).

Source code in src/groundfield/solver/image_nlayer.py
def solve_image_nlayer(
    world: "World",
    engine: "Engine",
    *,
    max_terms: int | None = None,
    tol: float | None = None,
) -> FieldResult:
    """Image-charge dispatcher for n-layer soil.

    Routes to ``image`` for ``n = 1`` and to ``image_2layer`` for
    ``n = 2``. For ``n \\ge 3`` raises a clear :class:`ValueError`
    pointing the caller to the engines that actually support that
    regime.

    Parameters
    ----------
    world
        World whose soil is any layered soil model.
    engine
        Engine configuration; ``engine.segment_length`` controls the
        discretisation.
    max_terms, tol
        Series controls forwarded to :func:`solve_image_2layer` for
        ``n = 2`` (``None``, the default, takes ``engine.image_max_terms``
        / ``engine.image_series_tol``); ignored otherwise.

    Returns
    -------
    FieldResult
        ``backend`` is rewritten to ``"image_nlayer"`` so that
        cross-engine reports use one unified label.

    Raises
    ------
    TypeError
        If the soil is not a :class:`HomogeneousSoil`,
        :class:`TwoLayerSoil` or :class:`MultiLayerSoil`.
    ValueError
        If the world has no electrodes.
    BackendCapabilityError
        If the soil has three or more layers (a :class:`ValueError`
        subclass).
    """
    if not isinstance(world.soil, (HomogeneousSoil, TwoLayerSoil, MultiLayerSoil)):
        raise TypeError(
            "Backend 'image_nlayer' supports HomogeneousSoil, "
            "TwoLayerSoil, and MultiLayerSoil. "
            f"Got: {type(world.soil).__name__}."
        )
    if not world.electrodes:
        raise ValueError("World contains no electrodes.")

    stack = as_layer_stack(world.soil)
    n = stack.n_layers
    _log.info("image_nlayer: dispatching for n_layers=%d", n)

    if n == 1:
        # Forward to the homogeneous backend; HomogeneousSoil is the
        # only soil it accepts. If the user supplied a degenerate
        # MultiLayerSoil with one layer, build an equivalent
        # HomogeneousSoil on the fly.
        if isinstance(world.soil, HomogeneousSoil):
            res = solve_image(world, engine)
        else:
            # A copy keeps every other field of the world (junctions too).
            tmp = world.model_copy(
                update={"soil": HomogeneousSoil(rho=float(stack.rhos[0]))}
            )
            res = solve_image(tmp, engine)
    elif n == 2:
        # Forward to the closed-form Tagg/Sunde series.
        if isinstance(world.soil, TwoLayerSoil):
            res = solve_image_2layer(world, engine, max_terms=max_terms, tol=tol)
        else:
            # MultiLayerSoil with exactly two layers: cast to TwoLayerSoil.
            two = TwoLayerSoil(
                rho_1=float(stack.rhos[0]),
                rho_2=float(stack.rhos[1]),
                h_1=float(stack.h[0]),
            )
            tmp = world.model_copy(update={"soil": two})
            res = solve_image_2layer(tmp, engine, max_terms=max_terms, tol=tol)
    else:
        from groundfield.solver.registry import BackendCapabilityError

        raise BackendCapabilityError(
            f"image_nlayer: layer count {n} ≥ 3 is not supported by "
            "the real image-charge series (Γ_1(λ) is no longer "
            "constant in λ). Use 'mom_sommerfeld' (direct Sommerfeld "
            "quadrature of the full layered Green's function) or "
            "'fem' — the 'cim'/'bem' n ≥ 3 kernels were found "
            "structurally incomplete in the 2026-07-08 audit and "
            "are rejected as well."
        )

    # Rewrite backend tag so that cross-engine reports use the unified label.
    res = res.model_copy(
        update={
            "backend": "image_nlayer",
            "metadata": {
                **res.metadata,
                "n_layers": int(n),
                "dispatched_to": res.backend,
            },
        }
    )
    return res

equivalent_hemisphere_radius

equivalent_hemisphere_radius(electrode: '_ElectrodeBase', rho_top: float) -> float

Radius of the hemisphere with an electrode's closed-form resistance.

.. deprecated:: 2026.11 fem no longer reduces electrodes to a hemisphere (user decision Q37); the function is kept for scripts that use the closed forms. Compute \(a_\text{eq} = \rho/(2\pi R)\) from the formulas of groundfield.references.dwight1936 instead. Removal no earlier than 2027.5.

The hemisphere radius \(a_\text{eq} = \rho/(2\pi R)\) with \(R\) the closed form of Dwight (1936) for a rod, a ring and a strip, Sverak's formula for a GridMeshElectrode and one strip along the diagonal for a MeshElectrode (the formulas of 0.15.0, unchanged, valid only for shallow electrodes: a strip down to half its length, a ring down to its diameter).

Parameters:

Name Type Description Default
electrode '_ElectrodeBase'

Single electrode primitive.

required
rho_top float

Resistivity in Ω·m used inside the formula.

required

Returns:

Type Description
float

Hemisphere radius \(a_\text{eq}\) in m.

Raises:

Type Description
TypeError

If the electrode is of a kind without a closed form here (a polyline or a star).

Warns:

Type Description
DeprecationWarning

On every call.

Source code in src/groundfield/solver/fem/_legacy.py
def equivalent_hemisphere_radius(electrode: "_ElectrodeBase", rho_top: float) -> float:
    """Radius of the hemisphere with an electrode's closed-form resistance.

    .. deprecated:: 2026.11
        ``fem`` no longer reduces electrodes to a hemisphere (user decision
        Q37); the function is kept for scripts that use the closed forms.
        Compute $a_\\text{eq} = \\rho/(2\\pi R)$ from the formulas of
        :mod:`groundfield.references.dwight1936` instead. Removal no earlier
        than 2027.5.

    The hemisphere radius $a_\\text{eq} = \\rho/(2\\pi R)$ with $R$ the
    closed form of Dwight (1936) for a rod, a ring and a strip, Sverak's
    formula for a ``GridMeshElectrode`` and one strip along the diagonal for
    a ``MeshElectrode`` (the formulas of 0.15.0, unchanged, valid only for
    shallow electrodes: a strip down to half its length, a ring down to
    its diameter).

    Parameters
    ----------
    electrode
        Single electrode primitive.
    rho_top
        Resistivity in Ω·m used inside the formula.

    Returns
    -------
    float
        Hemisphere radius $a_\\text{eq}$ in m.

    Raises
    ------
    TypeError
        If the electrode is of a kind without a closed form here (a
        polyline or a star).

    Warns
    -----
    DeprecationWarning
        On every call.
    """
    from groundfield.solver.registry import DEPRECATION_REMOVAL, warn_external

    warn_external(
        "groundfield.solver.fem.equivalent_hemisphere_radius is deprecated: fem "
        "no longer reduces electrodes to an equivalent hemisphere since 2026.11 "
        "(user decision Q37; it solves rods and rings as they are). Compute "
        "a_eq = rho / (2 pi R) from groundfield.references.dwight1936 instead. "
        f"It will be removed no earlier than {DEPRECATION_REMOVAL}.",
        DeprecationWarning,
    )
    if isinstance(electrode, RodElectrode):
        R = dw.rod(rho=rho_top, length=electrode.length, radius=electrode.wire_radius)
    elif isinstance(electrode, RingElectrode):
        R = dw.buried_ring(
            rho=rho_top,
            ring_diameter=2.0 * electrode.radius,
            wire_diameter=2.0 * electrode.wire_radius,
            depth=max(electrode.center[2], 1e-3),
        )
    elif isinstance(electrode, StripElectrode):
        # Straight horizontal wire — Dwight's classic ``horizontal_wire``
        # formula expects the *half-length* L (total = 2 L).
        L = electrode.length
        depth = max(electrode.start[2], 1e-3)
        R = dw.horizontal_wire(
            rho=rho_top,
            length=L / 2.0,
            radius=electrode.wire_radius,
            depth=depth,
        )
    elif isinstance(electrode, GridMeshElectrode):
        # Schwarz / Sverak / IEEE Std 80 (Sverak 1981) formula for a
        # buried rectangular meshed grid:
        #
        #     R ≈ ρ / L_C + ρ / sqrt(20 A) · (1 + 1 / (1 + h sqrt(20/A)))
        #
        # with L_C the total buried wire length, A the grid footprint
        # area and h the burial depth. Captures the dependence on the
        # inner mesh density, which the simple strip-along-diagonal
        # approximation used for the legacy ``MeshElectrode`` misses.
        dx, dy = electrode.size
        depth = max(electrode.corner[2], 1e-3)
        A = dx * dy
        n_long = electrode.n_y + 1  # longitudinal wires (one per y-row)
        n_tran = electrode.n_x + 1  # transverse wires (one per x-column)
        L_C = n_long * dx + n_tran * dy
        R = rho_top / L_C + (rho_top / math.sqrt(20.0 * A)) * (
            1.0 + 1.0 / (1.0 + depth * math.sqrt(20.0 / A))
        )
    elif isinstance(electrode, MeshElectrode):
        # Use the strip approximation along the diagonal as a rough
        # proxy for a mesh ground electrode. The FEM result for a
        # mesh is dominated by its overall extent, not the inner
        # spacing, so this is acceptable for the cross-check role.
        dx, dy = electrode.size
        diag = float(np.hypot(dx, dy))
        # horizontal_strip expects half-length L (total length 2*L),
        # a strip cross-section width and thickness. We model the
        # mesh as one equivalent strip of width ≈ wire_radius and
        # thickness ≈ wire_radius / 9 (so the b<a/8 guard passes).
        a = max(2.0 * electrode.wire_radius, 0.01)
        b = a / 9.0
        R = dw.horizontal_strip(
            rho=rho_top,
            length=diag / 2.0,
            width=a,
            thickness=b,
            depth=max(electrode.corner[2], 1e-3),
        )
    else:
        raise TypeError(
            f"FEM backend cannot reduce {type(electrode).__name__} to a "
            "hemisphere — extend equivalent_hemisphere_radius()."
        )
    return float(rho_top / (2.0 * np.pi * R))

Solver warnings

The warning categories of the solve. Each one can be filtered on its own, e.g. warnings.simplefilter("ignore", ShallowSegmentWarning); Warnings and errors explains what each one means and what to do.

ShallowSegmentWarning

Bases: UserWarning

A leakage segment is shallow compared with its own length.

The diagonal self-image entry of the reaction matrix uses the point image at distance \(2z\) instead of the image line of the segment, i.e. the \(L \ll 4 z\) limit

\[ \frac{1}{2 z} \;=\; \lim_{L \to 0} \frac{2}{L}\,\operatorname{arsinh}\!\frac{L}{4 z}. \]

For \(L \gtrsim 4 z\) the point form overestimates that entry by more than 13 % (and unboundedly as \(z \to 0\)), so the reported grounding impedance is biased high and keeps moving under mesh refinement. Typical triggers: a counterpoise or PEN conductor discretised with segments much longer than its burial depth, surface-near tapes, and rings or meshes whose arc/wire segments are longer than four times the burial depth (a ring of radius 25 m at \(z = 0.8\) m with segment_length = 5 m gives 4.909 m arc segments and warns "by 26 %") — the warning is not restricted to distributed conductors.

Scope of the quantified bias

The percentage quoted in the message is the horizontal-segment figure \(\bigl(L/(4z)\bigr)/\operatorname{arsinh} \bigl(L/(4z)\bigr) - 1\). That is the applicable figure for every segment that can still reach the warning: a segment inclined by more than \(30°\) to the horizontal and satisfying \(L > 4 z\) would have its upper end above \(z = 0\), which _check_segment_depths() rejects with a ValueError first (proof: \(L > 4 z\) together with \(L\,|e_z| \le 2 z\) forces \(|e_z| < 1/2\)). The message states the inclination it assumed so the reader can check that reasoning.

Emission scope

The bias belongs to the point form of the self image. The warning is raised wherever a solve uses it: by the image family (image, image_2layer; cim is an alias) with kernel="point", and by the point-matching family (mom, mom_sommerfeld; bem is an alias), whose self image is always the point form. It is not raised for the exact line kernel (kernel="line", the default of the image family since 2026.11), whose Galerkin self image has no such bias: a 10 m strip at 0.1 m depth gives 17.37863 Ω with 2 m segments and 17.37859 Ω with 0.25 m segments, where the point kernel gives 21.57 Ω and 17.23 Ω (audit A1-numerics F08). solve_mutual_* assemble the same reaction matrix without this advisory.

Silence with warnings.simplefilter("ignore", ShallowSegmentWarning) once the bias has been accepted, or refine Engine.segment_length / Conductor.discretize_segment_length until the impedance stabilises.

InterfaceContactWarning

Bases: UserWarning

A wire lies too close to a layer interface for the thin-wire model.

The thin-wire model carries the current on the wire axis. Two limits follow next to a layer interface:

Rod ends (audit A3S-05). A rod head or tip within one wire radius of an interface: the thin wire has no end face, so a rod that ends exactly at the interface \(h_1\) is a wire entirely on one side of it, and a rod that reaches past the interface by a few micrometres touches the other layer only through a part much shorter than its radius. The solid rod with a flat end face is continuous in between: its end face carries the contact. Against an axisymmetric finite-volume model of the solid rod (4.5 m, \(a\) = 8 mm, 1000/30 Ω·m) the thin wire reads +21 % with its tip at the interface, +7 % 1 mm above it and −4.6 % 1 mm below it; beyond two radii it is within a few per cent, like anywhere else (+0.9 % in homogeneous soil). An end that meets the end of another rod has no free end face and is not reported.

Horizontal wires (audits W4A-07, W4B-02). A horizontal wire (every electrode but a rod, and the leaking pieces of a galvanic distributed conductor) whose axis lies within the reach wire_contact_reach() of an interface: next to a more conductive layer the current crowds to the wire's near side, which a current on the axis cannot follow. Against the solid torus (the axisymmetric fem, confirmed by a Hankel thin ring plus the exact 2-D proximity correction to 5.2e-4, to 2e-4 from two radii on) a ring (a = 5 mm) over a layer 33 times more conductive reads +0.59 % at 4 radii, +1.2 % at 3, +3.6 % at 2, +8.6 % at 1.5 and +32 % at 1.1 radii, and +89 % when the interface cuts the wire 0.99 radii below its axis; under a more resistive layer up to +2.6 % (a 55 mm wire on a 1 m ring at 1.01 radii, contrast 1000). The reach is the largest distance at which the thin wire (converged in its segment length) is 1 % off, in five ring geometries (r0 / a = 18 ... 400: rings of 0.5 ... 5 m at 0.3 ... 2 m, a = 5 ... 55 mm; the more conductive layer below the wire, for the 2 m ring also above it; the more resistive layer below and above every one; the thick wire on the 1 m ring is the widest everywhere), rounded up to 0.1 a, plus 0.1 a for the contrasts between the nodes (the conductive side from the thin wire at one segment length, its node at 1000 raised so that the converged distances lie inside; audits W4R2A-04, W4R3A-02; up to W4R2A-04 four geometries, 0.2 ... 0.4 a short of the thick wire; up to W4R3A-02 the resistive side measured above the wire for the thin ring only, the thick wire 1 % off up to 0.74 a beyond it):

====================== ===== ===== ===== ===== ===== ===== ===== ===== ===== contrast 1.4 2 3 5.5 10 18 33 100 1000 more conductive beyond 1.0 a 1.3 a 1.9 a 2.7 a 3.3 a 3.7 a 3.9 a 4.1 a 4.3 a ====================== ===== ===== ===== ===== ===== ===== ===== ===== =====

====================== ===== ===== ===== ===== ===== ===== contrast 1.4 3 10 33 100 1000 more resistive beyond 1.0 a 1.3 a 1.9 a 2.2 a 2.2 a 2.3 a ====================== ===== ===== ===== ===== ===== =====

(log-linear in the contrast between the nodes, held beyond the last and at 1.0 a down to the contrast 1.3; 1.0 a: only a wire that the interface cuts.) Checked against every distance measured at the nodes and between them (conductive 1.3 ... 1.9, 2.5, 4, 7, 14, 25, 50, 300; resistive 2, 5.5, 18, 300): no thin wire 1 % or more off lies outside the reach (2348 conductive points at one segment length, the largest outside +0.94 %; 2470 resistive points converged in it, +0.93 %). The thick wire's conductive 1 % distances, converged in the segment length, lie 0.004 ... 0.17 a inside the reach; the node at 1000 is 4.3 a (it was 4.2) for the 4.15 a at 300. Below a contrast of 1.3 nothing is reported: a cut wire reads at most +0.96 % off at 1.3 and +1.06 % at 1.35 (the thick wire cut 0.5 a below its axis by a more resistive layer above it; up to audit W4R3A-02 the limit was 1.4, where it reads +1.16 %, and up to W4R2A-04 2, where a wire cut at a contrast of 1.9 read -1.46 %). Pieces of a galvanic distributed conductor count as horizontal while their slope |e_z| is at most 0.1 (5.7 deg): a steeper piece passes the reach of an interface over at most 2 reach / |e_z| wire radii of its length, like a rod through an interface, and is not reported (a step in reporting at the cutoff, kept as documented). The image family, mom, mom_sommerfeld and the three-dimensional fem share this limit (the 3-D model's smoothed line source lies between the thin wire and the solid torus); the axisymmetric fem resolves the wire and does not warn.

Remedy: keep rod ends and horizontal wires a few wire radii from a contrasting interface; bracket a rod end by moving it by \(\pm 2a\); check a ring with fem's axisymmetric model (FemOptions.model="axisymmetric"), which solves the wire as the solid torus it is.

PointKernelInterfaceWarning

Bases: UserWarning

A horizontal segment lies close to a layer interface (point form).

The point form of the reaction matrix (kernel="point" of the image family, the mom family and solve_mutual_* with the point kernel) cannot represent a horizontal wire next to a layer interface, on either side of it:

  • on the cross-layer path of a two-layer soil (an electrode reaches the interface \(h_1\)) it averages the layered correction on the diagonal over a 3-point rule along the depth axis, \(\pm 0.387 L\) around the segment midpoint, whatever the segment's orientation;
  • with every segment above \(h_1\) (the Tagg/Sunde series, and the Sommerfeld diagonal of mom_sommerfeld) it takes the image of a segment in the interface as a point source \(2|z - h_1|\) away, where the image line of a horizontal segment is much closer to the wire than that point (audit A3S-02).

A horizontal segment within \(0.6 L\) of \(h_1\) draws this warning: measured −3 % … −17 % against the exact line kernel on the cross-layer path (a 20 m strip and a ring r = 3 m in 300/50 and 100/1000 Ω·m), −2.5 % and −0.4 % above \(h_1\) (a ring r = 3 m, segment_length = 0.5 m, 0.2 m above \(h_1\) = 5 m in 1000/30 and 30/1000 Ω·m). Closer still (\(|z - h_1| < 0.387 L\)), or where the 3-point rule reaches above the soil surface, the solve raises BackendCapabilityError instead (negative impedances: −552 % on the cross-layer path; −1931 Ω instead of 4.18 Ω for the ring 1 µm above \(h_1\)). The exact line kernel, the default of the image family, integrates these segments exactly.

SeriesTruncationWarning

Bases: UserWarning

The Tagg/Sunde image series hit max_terms before tol.

Emitted (in addition to the logger record) whenever a backend truncates the two-layer image-charge series without reaching the requested tail tolerance — typically at high layer contrast (\(|K| \to 1\)). Silence with warnings.simplefilter("ignore", SeriesTruncationWarning) or raise Engine.image_max_terms.

SommerfeldConvergenceWarning

Bases: UserWarning

The reflected-remainder quadrature did not reach epsrel.

Emitted (in addition to the logger record) whenever the grid refinement ladder of _reflected_integral() exhausts all of _REFINEMENTS without two successive grids agreeing within max(epsabs, epsrel · |G|). The returned value is then not converged, and because the integrand is oscillatory (\(J_0(\lambda s)\)) a non-converged panel grid does not merely lose digits — it can return a Green's function with the wrong sign (the pre-0.15.0 failure mode of this backend, review-pass-9 finding F04). Up to 0.15.0 the same situation was only logged at DEBUG level and the least accurate of the four grid values was returned silently.

Two mechanisms reach this branch:

  • Oscillation budget. max_osc_panels (default 200 000, i.e. Engine.sommerfeld_max_osc_panels) bounds the half-period panel family \(\pi / s\) that resolves \(J_0(\lambda s)\) on \([0, 34 / d_{\text{rem}}]\). The budget binds when \(s / d_{\text{rem}} \gtrsim 1.9 \cdot 10^4\) — a centimetre-thin intermediate layer (\(d_{\text{rem}} = 2\min(h_1,h_2)\)) combined with a kilometre-scale horizontal separation. Remedy: raise max_osc_panels (runtime and memory grow linearly with it).
  • Layer contrast. For \(|K_1| \to 1\) the multiple-reflection multiplier \(1/(1 - \Gamma_1 e^{-2\lambda h_1})\) develops a \(\lambda\)-scale \((1 - \Gamma_1(0)) / 2 h_1\) that the graded base grid has to resolve. Since 0.15.0 a geometric panel family covers that scale explicitly, which removed the historic \(-12.9\,\%\) error at \(\rho_2/\rho_1 = 10^8\); if the warning still appears here the contrast is outside the validated envelope \(\rho_2/\rho_1 \in [10^{-2}, 10^{2}]\) and no knob fixes it — use image_2layer (exact geometric series) instead.

Silence with warnings.simplefilter("ignore", SommerfeldConvergenceWarning) only if the affected entries are known to be negligible.

ComplexImageFitWarning

Bases: UserWarning

The complex-image fit of \(\Gamma_1(\lambda)\) is unreliable.

Emitted by fit_complex_images() when the RMS residual on the sample grid or on the independent verification grid exceeds rms_tol, or when the matrix pencil returned no usable pole for a remainder that is not numerically flat. All three situations mean the returned images do not represent \(\Gamma_1\) and must not be fed into a Green's function.

Up to 0.14.1 the same situations were silent: the pole filters (|p| < 0.999, Re β > 0) discarded the constant term that carries the \(\lambda \to \infty\) asymptote \(K_1\), so the residual was of order \(|K_1|\) for every stack, and a two-layer stack (where that constant is the whole function) returned P = 0 with rms = nan (review pass 9, F39).

A dedicated category lets callers opt in / out with warnings.simplefilter("error", ComplexImageFitWarning).

FemReductionWarning

Bases: UserWarning

The equivalent-hemisphere reduction did not represent the world.

Emitted by fem up to 2026.11, when it reduced every cluster to an equivalent hemisphere. Since the conforming model (user decision Q37) fem solves the electrodes as they are and never emits it; the class is kept so that filters and pytest.warns written against it still import.