Skip to content

Diagnostics

groundfield.diagnostics checks a world before a long solve: its size, the discretisation quality, wires that are too close for the thin-wire model, settings that have no effect, and — given a result — truncated series. diagnose(world, engine) returns one aggregated DiagnosticsReport with one line per cause (not per electrode); the solve emits the same findings as warnings. The post-solve counterpart, a comparison of several engines, is Validation.

Function Answers
world_statistics(world) counts by kind, wire and conductor lengths, footprint
expected_segments(world, engine) segments the discretiser will produce, per electrode and in total, the size of the nodal system and the engine's limit ("limit")
check_segment_resolution(world, engine) thin-wire ratio, electrodes smaller than a segment, size budget (strings)
check_segment_budget(world, engine) raises ResourceLimitError above the engine's limit Engine.max_segments (default HARD_LIMIT; used by the solver)
diagnose(world, engine, result=None) all of the above plus mixed local and projected coordinates, close wires, rod ends at a layer interface, inert settings, series truncation

Mathematical and physical context

The checks guard the assumptions of the thin-wire model (see Geometry):

  • Coordinates. A world whose points lie both within 10 km of the origin and beyond 1 000 km from it (horizontal distance) mixes local and projected coordinates: electrodes at UTM coordinates and a node given in a local system, almost always by mistake. It is solved as given, its two groups some 33 000 km apart (a return rod at local (80, 15) m for an outline and a rod at UTM coordinates: \(Z_{in}\) +0.43 %; a PEN cable to a cabinet at local coordinates: a 33 118 km conductor; audit W2B-04). Category coordinates, a warning that names both groups and the conductors between them; the solve warns with MixedCoordinatesWarning too (user decision D5). A world that does not mix but whose horizontal extent exceeds 100 km is reported as information (two UTM zones, a zone prefix on some eastings only, a geometry in millimetres). See Units and conventions.

  • Thin-wire ratio. The self term of a segment of length \(L\) and radius \(a\) behaves like \(2\ln(L/a)/L\) and loses dominance as \(L\) approaches \(a\); the check asks for \(L/a \ge 5\) (MIN_THINWIRE_RATIO).

  • Resolution. An electrode feature shorter than one segment is represented only by the discretiser's floor (one segment per wire, eight per ring).
  • Proximity. Two wires of different owners closer than five times the sum of their radii violate the point-source assumption that a source sees another wire only through its midpoint; the exact line-source kernel stays physical there.
  • Interface contact. The thin-wire model has no end face. A rod whose head or tip lies within one wire radius of a layer interface is either entirely on one side of it (end at the interface) or touches the other layer through a part shorter than its radius; the solid rod is continuous in between. Against an axisymmetric 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 and −4.6 % 1 mm past it. A horizontal wire within a few wire radii of a contrasting interface carries its current on the axis while the solid wire's current crowds to the near side: +3.6 % at two radii over a layer 33 times more conductive (audits W4A-07, W4B-02; the reach per contrast is tabulated under InterfaceContactWarning in the warnings reference). Category interface_contact, also InterfaceContactWarning at the solve.
  • Size. The dense reaction matrix of \(N\) segments has \(N^2\) entries (\(8N^2\) bytes, 3.0 GiB at \(N\) = 20 000); the work per excitation grows like \(N^2\) and the direct solve like \(N^3\). The dense nodal system of \(n\) unknowns (current owners, nodes and branches, every conductor sub-piece included) takes \(16n^2\) bytes. At or above the engine's notice size the report informs that a solve takes minutes (an info finding; every Engine.solve, with any backend, emits it as a UserWarning — solve_mutual_matrix and solve_mutual_field do not); above the engine's limit the solver refuses to start with ResourceLimitError, before anything of that size is allocated (every segment backend and solve_mutual_*). Both are set per engine and count both sizes: the limit with Engine(max_segments=...), the notice with Engine(warn_segments=...) (positive integers; user decisions Q17 and Q31 of 2026.11). An engine that leaves them at None uses the module constants HARD_LIMIT (20 000) and SOFT_LIMIT (5 000), read at solve time. The two are not checked against each other: a notice above the hard limit never appears, because such a world is refused first. expected_segments(...)["limit"], report.context["max_segments"] and FieldResult.metadata ["max_segments"] show the limit that applies, report.context["warn_segments"] the notice size; the provenance block of a result keeps both requests.

The segment counts follow the discretisation of the image and MoM families; for fem they do not predict the cost. fem does not use those segments: its problem is the mesh of each driven cluster (2 400 nodes at the default resolution in homogeneous soil, growing with the depth of the layer stack to about 4 100 at 30 m and 6 200 at 1 km, independent of segment_length), so its Engine.solve still emits the notice from the segment count but does not refuse a world above Engine.max_segments.

Example

import groundfield as gf

world = gf.create_world(soil=gf.HomogeneousSoil(rho=100.0))
gf.create_electrode(world, "rod", name="a", position=(0.0, 0.0, 0.0), length=3.0, wire_radius=0.008)
gf.create_electrode(world, "rod", name="b", position=(0.018, 0.0, 0.0), length=3.0, wire_radius=0.008)
gf.create_source(world, attached_to="a", magnitude=1.0)
engine = gf.create_engine(segment_length=0.5)

budget = gf.expected_segments(world, engine)
report = gf.diagnose(world, engine)
print(report)    # proximity: 'a'–'b' close, axis distance 18 mm (clearance 2 mm) ...

assert budget["total"] == 12                      # two rods of six 0.5 m segments
assert "proximity" in report.categories()

The limit is a property of the engine: a smaller one refuses this world before the solve allocates anything, a larger one admits worlds beyond HARD_LIMIT.

from groundfield.diagnostics import HARD_LIMIT, ResourceLimitError, check_segment_budget

try:
    check_segment_budget(world, gf.create_engine(segment_length=0.5, max_segments=10))
except ResourceLimitError as error:
    print(error)    # ... discretises into 12 segments ..., more than Engine.max_segments = 10 ...
print(budget["limit"], gf.expected_segments(world, gf.create_engine(max_segments=50_000))["limit"])

The notice "solve time may run from seconds to minutes" works the same way: SOFT_LIMIT is the default, Engine(warn_segments=...) moves it for one engine, for instance down to a size that is already slow on a small machine.

from groundfield.diagnostics import SOFT_LIMIT

early = gf.Engine(segment_length=0.5, warn_segments=10)
notice = gf.diagnose(world, early).by_category("budget")
print(notice[0].severity, notice[0].message)    # info predicted total segment count 12 is at or above Engine.warn_segments = 10 — ...
print(gf.diagnose(world, engine).context["warn_segments"])    # 5000: SOFT_LIMIT

API reference

diagnostics

Pre-solve world diagnostics — counts, mesh budget, resolution, proximity.

This module collects structural diagnostics that work directly on a World (and optionally an Engine and a solved FieldResult). It is the typical counterpart to groundfield.validation (a post-solve cross-engine check):

  • diagnose() — one structured, aggregated report (DiagnosticsReport) of everything that limits the accuracy or the meaning of a solve: coordinates that mix local and projected systems, discretisation quality, segment budget, close or interpenetrating wires, inert configuration and, after the solve, series truncation. One line per cause, not per electrode (review finding 10.70).
  • world_statistics() — aggregate counts and lengths, bounding box, footprint area, conductor-length statistics.
  • expected_segments() — predicts the number of point-source segments that the image-family discretiser will produce per electrode kind, plus a total. Useful for budgeting wall-clock cost before kicking off a 200-EFH run.
  • check_segment_resolution() — the discretisation part of the report as plain strings (thin-wire ratio, electrode size vs. segment length, segment budget), one string per cause. The solve emits each of them as one warning.
  • check_segment_budget() — the hard resource guard of the solver pipeline: a world whose predicted segment count, or whose dense nodal system (every conductor sub-piece included), exceeds the engine's limit raises ResourceLimitError before anything of that size is allocated (finding 10.06; audit round 2, A2S-02). The limit is Engine.max_segments, or HARD_LIMIT for an engine that leaves it at None (user decision Q17, 2026-11-08).
Validity envelope
  • The segment counts follow the electrodes' own discretisation (segments() and siblings) including the split at the soil-layer interfaces, i.e. the image-family discretiser that image, image_2layer, image_nlayer, mom, mom_sommerfeld, cim and bem share. FEM does not use it; for FEM the segment count is not predictive of cost.
  • Wire-length / segment computations follow the physical geometry. Sub-segment overheads from cluster-bonding, KCL pseudo-nodes and lumped-conductor branches are not double-counted.
Mathematical background of the checks

The image family represents every wire segment of length \(L\) and radius \(a\) by a line (or point) source with uniform current and evaluates the potential on its axis (thin-wire approximation). The self term of the reaction matrix behaves like \(2\ln(L/a)/L\); it loses dominance when \(L\) approaches \(a\), so the thin-wire check asks for \(L \ge 5a\) (MIN_THINWIRE_RATIO). An electrode feature shorter than one segment is represented by the discretiser's lower floor only (one segment per wire, eight per ring), which the resolution check reports. Two different wires closer than a few radii violate the assumption of the point-source kernel that a source sees another wire only through its midpoint: two bonded 3 m rods of radius 8 mm, 2 mm apart, solve to 5.7 times the impedance of one rod with the point kernel and to 0.998 times with the exact line kernel (review finding 10.44); the proximity check uses groundfield.conductors.find_close_wires() on the segments the solver assembles. The dense reaction matrix of \(N\) segments has \(N^2\) entries (8 bytes each); above MATRIX_BUDGET_BYTES it is applied in row blocks, so memory stays bounded but the work keeps growing like \(N^2\) per excitation — the reason for the hard segment limit. The dense augmented nodal system of \(n\) unknowns (current owners, nodes and branches) is allocated whole, \(16 n^2\) bytes complex.

Resource limit

The limit is set per engine with Engine(max_segments=...), a positive integer that bounds both sizes, the leakage segments and the unknowns of the dense nodal system; None (the default) takes HARD_LIMIT (20 000), read at call time, so a changed module constant still acts as the default of every engine. Every function here that takes an engine (check_segment_budget(), expected_segments(), check_segment_resolution(), diagnose()) and every segment backend, solve_mutual_matrix and solve_mutual_field included, check against the same limit; FieldResult.metadata["max_segments"] records it.

The soft notice is set per engine as well, Engine(warn_segments=...), counted like max_segments (user decision Q31, 2026-11-08); None (the default) takes SOFT_LIMIT (5 000), read at call time. At or above this size every Engine.solve, with any backend, warns that it may take from seconds to minutes on a laptop, and diagnose() reports it as an info finding; solve_mutual_matrix and solve_mutual_field check the hard limit but emit no notice. For fem the segment count is not its problem size (its volume mesh is, limited by FemOptions.max_nodes and max_nodes_3d); it counts the display segments that carry the point sources of its result, which fem checks against the limit too. The two sizes are not checked against each other: a notice above the engine's hard limit never appears, because such a world is refused first. check_segment_resolution() and diagnose() (report.context ["warn_segments"]) use the engine's value.

References
  • ADR-0003 (docs/adr/0003-distributed-conductor-model.md) — distributed-conductor topology used by expected_segments() for conductors with finite discretize_segment_length.

HARD_LIMIT module-attribute

HARD_LIMIT: int = 20000

Default problem size above which the solver refuses to start.

The image-family pipeline, the mom family and solve_mutual_* raise ResourceLimitError for a world whose predicted segment count, or whose dense nodal system (current owners, nodes and branches, every sub-piece of a distributed conductor included), exceeds the engine's limit, before anything of that size is allocated (finding 10.06: a ring entered in millimetres predicts 62 832 segments; audit round 2, A2S-02: an isolated conductor in mm-long sub-pieces). The limit of one engine is Engine(max_segments=...); this constant is the default of every engine that leaves max_segments at None and is read at solve time, so setting groundfield.diagnostics.HARD_LIMIT changes the default for the whole process.

MIN_THINWIRE_RATIO module-attribute

MIN_THINWIRE_RATIO: float = 5.0

Minimum recommended ratio of segment_length to wire_radius.

Below this, the thin-wire approximation that underpins the average-potential method becomes increasingly biased: the self-action integral is computed under the assumption segment_length >> wire_radius.

OVERLAP_FRACTION module-attribute

OVERLAP_FRACTION: float = 0.05

Shortest reported overlap, as a fraction of the shorter conductor.

The second threshold of the overlap check of diagnose(); see OVERLAP_REL_LENGTH.

OVERLAP_REL_LENGTH module-attribute

OVERLAP_REL_LENGTH: float = 10.0

Shortest reported overlap of two inductive conductors, in touching distances.

Overlap of inductive conductors (check overlap of diagnose()): two conductors closer than touching (axis distance below the sum of their radii, d_t) lie beside each other when that stretch is longer than OVERLAP_REL_LENGTH * d_t and OVERLAP_FRACTION of the shorter conductor. Two conductors leaving a common point at an angle phi stay closer than touching over about d_t / phi; the touching rule changes their mutual inductance over that stretch by about (mu0 / 2 pi) d_t / phi (the mean of ln(d_t / d) along a linear divergence is 1), against a self inductance of about (mu0 / 2 pi) l (ln(2 l / r) - 1), ten times (mu0 / 2 pi) l for the cables of an LV network. A stretch of 5 % of the shorter conductor therefore moves the coupling by about 0.5 % of a self inductance; a branch is reported only below about d_t / (0.05 l): 0.46 deg for 12 mm touching and a 30 m drop, 0.1 rad at most.

SOFT_LIMIT module-attribute

SOFT_LIMIT: int = 5000

Problem size above which the user should be aware of cost.

Compared with the segment count and with the size of the dense nodal system (expected_segments(), key nodal_unknowns).

The reaction matrix scales as \(O(N^2)\) in memory (bounded by row blocks above the kernel budget) and the multi-port assembly as \(O(N^2)\) per excitation, so ~ 5 000 segments is roughly where solve time becomes minutes rather than seconds on a typical laptop.

The default of every engine that leaves Engine.warn_segments at None (user decision Q31), read at call time; an engine moves the notice with Engine(warn_segments=...).

Diagnostic dataclass

Diagnostic(category: str, severity: Severity, subjects: tuple[str, ...], message: str, data: dict[str, Any] = dict())

One finding of diagnose().

Attributes:

Name Type Description
category str

Cause: "coordinates", "thin_wire", "resolution", "budget", "proximity", "overlap", "interface_contact", "inert" or "series".

severity Severity

"warning" (the result is likely biased or the setting has no effect) or "info" (worth knowing, usually harmless).

subjects tuple[str, ...]

Names the finding is about (electrodes, conductors, the world, a setting).

message str

One sentence for this subject.

data dict[str, Any]

Machine-readable values (units in the key names).

DiagnosticsReport dataclass

DiagnosticsReport(findings: list[Diagnostic] = list(), context: dict[str, Any] = dict())

Aggregated result of diagnose().

Attributes:

Name Type Description
findings list[Diagnostic]

All findings, in the order the checks ran.

context dict[str, Any]

Values the aggregated text refers to (segment_length_m, min_thinwire_ratio, ...).

by_category

by_category(category: str) -> list[Diagnostic]

Findings of one cause.

Source code in src/groundfield/diagnostics.py
def by_category(self, category: str) -> list[Diagnostic]:
    """Findings of one cause."""
    return [d for d in self.findings if d.category == category]

categories

categories() -> list[str]

Causes present in the report, in check order.

Source code in src/groundfield/diagnostics.py
def categories(self) -> list[str]:
    """Causes present in the report, in check order."""
    seen: list[str] = []
    for d in self.findings:
        if d.category not in seen:
            seen.append(d.category)
    return seen

lines

lines(*, min_severity: Severity = 'info') -> list[str]

One aggregated line per cause.

Parameters:

Name Type Description Default
min_severity Severity

"info" (default) lists every cause, "warning" only the causes with at least one warning.

'info'
Source code in src/groundfield/diagnostics.py
def lines(self, *, min_severity: Severity = "info") -> list[str]:
    """One aggregated line per cause.

    Parameters
    ----------
    min_severity
        ``"info"`` (default) lists every cause, ``"warning"`` only the
        causes with at least one warning.
    """
    out = []
    for cat in self.categories():
        items = self.by_category(cat)
        if min_severity == "warning" and not any(
            d.severity == "warning" for d in items
        ):
            continue
        out.append(self._line(cat, items))
    return out

summary

summary() -> str

The aggregated text (one paragraph per cause).

Source code in src/groundfield/diagnostics.py
def summary(self) -> str:
    """The aggregated text (one paragraph per cause)."""
    return str(self)

to_records

to_records() -> list[dict[str, Any]]

The findings as plain dictionaries (for tables and JSON).

Source code in src/groundfield/diagnostics.py
def to_records(self) -> list[dict[str, Any]]:
    """The findings as plain dictionaries (for tables and JSON)."""
    return [
        {
            "category": d.category,
            "severity": d.severity,
            "subjects": list(d.subjects),
            "message": d.message,
            **d.data,
        }
        for d in self.findings
    ]

warn

warn(*, min_severity: Severity = 'warning', stacklevel: int = 2) -> None

Emit the report as one DiagnosticsWarning (if not empty).

Parameters:

Name Type Description Default
min_severity Severity

Lowest severity that is included (default "warning").

'warning'
stacklevel int

Passed to warnings.warn().

2
Source code in src/groundfield/diagnostics.py
def warn(self, *, min_severity: Severity = "warning", stacklevel: int = 2) -> None:
    """Emit the report as one :class:`DiagnosticsWarning` (if not empty).

    Parameters
    ----------
    min_severity
        Lowest severity that is included (default ``"warning"``).
    stacklevel
        Passed to :func:`warnings.warn`.
    """
    text = self.lines(min_severity=min_severity)
    if text:
        warnings.warn(
            "groundfield diagnostics:\n" + "\n".join(text),
            DiagnosticsWarning,
            stacklevel=stacklevel,
        )

DiagnosticsWarning

Bases: UserWarning

One aggregated warning with the findings of diagnose().

MixedCoordinatesWarning

Bases: UserWarning

The world mixes local and projected coordinates (user decision D5).

Emitted once per solve by every solve in a local frame (the image family, mom, mom_sommerfeld and solve_mutual_*), before anything is discretised, when points of the world lie both within 10 km of the origin and beyond 1000 km from it: electrodes at UTM or Gauss-Krüger coordinates and a node or electrode near (0, 0), almost always given in the wrong system by mistake. The world is solved as given, its two groups some 33 000 km apart (audit W2B-04, measured with a 12 m × 7 m outline and a 3 m rod at UTM coordinates: a return rod given at local (80, 15) m raises Z_in by 0.43 %, a PEN cable to a cabinet at local coordinates becomes a 33 118 km conductor, Z_in 7494 + j25396 Ω instead of 5.39 + j0.19 Ω at 50 Hz with Carson's earth return, and the Sommerfeld earth return does not finish). diagnose() reports the same world under coordinates.

Remedy: give every point in one coordinate system.

ResourceLimitError

Bases: ValueError

The predicted problem size exceeds the configured limit.

Raised before any array of the problem size is allocated. Check the units of the geometry (metres) and Engine.segment_length; to solve a large world on purpose, raise the limit of the engine, Engine(max_segments=...) (default groundfield.diagnostics.HARD_LIMIT).

check_budget_ok

check_budget_ok(world: 'World', engine: 'Engine') -> bool

Whether the world is within the engine's limit (no exception).

The limit is engine.max_segments, or HARD_LIMIT if the engine leaves it at None (see check_segment_budget()).

Source code in src/groundfield/diagnostics.py
def check_budget_ok(world: "World", engine: "Engine") -> bool:
    """Whether the world is within the engine's limit (no exception).

    The limit is ``engine.max_segments``, or :data:`HARD_LIMIT` if the
    engine leaves it at ``None`` (see :func:`check_segment_budget`).
    """
    try:
        check_segment_budget(world, engine, _layer_interfaces(world.soil))
    except ResourceLimitError:
        return False
    return True

check_segment_budget

check_segment_budget(world: 'World', engine: 'Engine', layer_interfaces: Sequence[float] | None = None) -> int

Hard resource guard of the solver pipeline (finding 10.06).

Predicts the problem size from the geometry and raises before anything of that size is allocated. Two sizes are checked against the engine's limit, engine.max_segments (user decision Q17), or HARD_LIMIT (read at call time) if the engine leaves it at None:

  • the leakage segments (reaction matrix): first the closed-form lower bound \(\sum_e \lceil L_e/ds \rceil\), then, if that is within the limit, the exact count;
  • the unknowns of the dense augmented nodal system (owners, nodes and branches, including every sub-piece and interior node of a conductor chain), in closed form (audit round 2, A2S-02: up to then an isolated conductor of 2000 sub-pieces counted as zero).

Parameters:

Name Type Description Default
world 'World'

World to be solved.

required
engine 'Engine'

Engine carrying segment_length (m) and max_segments.

required
layer_interfaces Sequence[float] | None

Interface depths in m at which the backend splits wires.

None

Returns:

Type Description
int

The predicted segment count (electrodes plus galvanic conductor segments).

Raises:

Type Description
ResourceLimitError

If either size exceeds the limit.

Source code in src/groundfield/diagnostics.py
def check_segment_budget(
    world: "World",
    engine: "Engine",
    layer_interfaces: Sequence[float] | None = None,
) -> int:
    """Hard resource guard of the solver pipeline (finding 10.06).

    Predicts the problem size from the geometry and raises before
    anything of that size is allocated. Two sizes are checked against
    the engine's limit, ``engine.max_segments`` (user decision Q17), or
    :data:`HARD_LIMIT` (read at call time) if the engine leaves it at
    ``None``:

    * the leakage segments (reaction matrix): first the closed-form
      lower bound $\\sum_e \\lceil L_e/ds \\rceil$, then, if that is
      within the limit, the exact count;
    * the unknowns of the dense augmented nodal system (owners, nodes
      and branches, including every sub-piece and interior node of a
      conductor chain), in closed form (audit round 2, A2S-02: up to
      then an isolated conductor of 2000 sub-pieces counted as zero).

    Parameters
    ----------
    world
        World to be solved.
    engine
        Engine carrying ``segment_length`` (m) and ``max_segments``.
    layer_interfaces
        Interface depths in m at which the backend splits wires.

    Returns
    -------
    int
        The predicted segment count (electrodes plus galvanic
        conductor segments).

    Raises
    ------
    ResourceLimitError
        If either size exceeds the limit.
    """
    ds = _check_ds(engine)
    limit = _hard_limit(engine)
    label = _limit_label(engine, limit)
    unknowns = _nodal_unknowns(world, layer_interfaces)
    if unknowns > limit:
        raise ResourceLimitError(
            f"World {world.name!r} needs a nodal system of {unknowns} unknowns "
            "(current owners, nodes and branches, among them every sub-piece "
            "and interior node of the distributed conductors), more than "
            f"{label}: its dense matrix has {unknowns * unknowns:.3g} "
            f"entries ({16.0 * unknowns * unknowns / 2**30:.3g} GiB complex). "
            "Check discretize_segment_length of the conductors (metres); "
            f"{_RAISE_THE_LIMIT}."
        )
    conductors = sum(_conductor_segment_count(c) for c in world.conductors)
    lower = conductors + sum(_segment_lower_bound(e, ds) for e in world.electrodes)
    if lower > limit:
        n, exact = lower, False
    else:
        n = conductors + sum(
            int(e.segment_count(ds, layer_interfaces)) for e in world.electrodes
        )
        exact = True
    if n > limit:
        what = "" if exact else "at least "
        raise ResourceLimitError(
            f"World {world.name!r} discretises into {what}{n} segments at "
            f"segment_length = {ds:g} m, more than {label} "
            f"(a dense reaction matrix of {n} segments has {n * n:.3g} "
            f"entries, {8.0 * n * n / 2**30:.3g} GiB). Check the units of the "
            f"geometry (metres) and Engine.segment_length; {_RAISE_THE_LIMIT}."
        )
    return n

check_segment_resolution

check_segment_resolution(world: 'World', engine: 'Engine') -> list[str]

Heuristic discretisation-quality check, one string per cause.

Inspects the world / engine pair for common modelling pitfalls and returns one human-readable string per cause (review finding 10.70: up to 0.15.0 one string per electrode, so a layout with 81 joint rods emitted 81 warnings per solve). The empty list means no concerns detected. Causes:

  1. Thin-wire ratio ("thin-wire: ..."). Each electrode must satisfy segment_length >= MIN_THINWIRE_RATIO * wire_radius so that the thin-wire average-potential self-action remains valid; a distributed conductor's discretize_segment_length likewise.
  2. Electrode feature shorter than one segment ("resolution: ..."), using each electrode's min_feature_length() — every kind, including polyline and star electrodes (F53 / F54, listed as fixed in 0.15.0 but skipped until 2026.11).
  3. Total segment budget ("budget: ..."): the segment count or the size of the dense nodal system (every conductor sub-piece included) at or above the engine's notice size Engine.warn_segments (default SOFT_LIMIT), or above the engine's limit Engine.max_segments (default HARD_LIMIT; the solve then refuses with ResourceLimitError).

The function never raises (except for a non-positive segment_length) — it only reports. The full report with proximity and inert-setting checks is diagnose().

Parameters:

Name Type Description Default
world 'World'

World to inspect.

required
engine 'Engine'

Engine carrying segment_length, max_segments and warn_segments.

required

Returns:

Type Description
list[str]

Zero to three diagnostic strings, in the order thin-wire, resolution, budget; each names up to five electrodes or conductors and the number of further ones.

Source code in src/groundfield/diagnostics.py
def check_segment_resolution(world: "World", engine: "Engine") -> list[str]:
    """Heuristic discretisation-quality check, one string per cause.

    Inspects the world / engine pair for common modelling pitfalls and
    returns one human-readable string per cause (review finding 10.70:
    up to 0.15.0 one string per electrode, so a layout with 81 joint
    rods emitted 81 warnings per solve). The empty list means *no
    concerns detected*. Causes:

    1. **Thin-wire ratio** (``"thin-wire: ..."``). Each electrode must
       satisfy ``segment_length >= MIN_THINWIRE_RATIO * wire_radius``
       so that the thin-wire average-potential self-action remains
       valid; a distributed conductor's ``discretize_segment_length``
       likewise.
    2. **Electrode feature shorter than one segment**
       (``"resolution: ..."``), using each electrode's
       :meth:`min_feature_length` — every kind, including polyline and
       star electrodes (F53 / F54, listed as fixed in 0.15.0 but
       skipped until 2026.11).
    3. **Total segment budget** (``"budget: ..."``): the segment count or
       the size of the dense nodal system (every conductor sub-piece
       included) at or above the engine's notice size
       ``Engine.warn_segments`` (default :data:`SOFT_LIMIT`), or above the
       engine's limit ``Engine.max_segments`` (default :data:`HARD_LIMIT`;
       the solve then refuses with :class:`ResourceLimitError`).

    The function never raises (except for a non-positive
    ``segment_length``) — it only reports. The full report with
    proximity and inert-setting checks is :func:`diagnose`.

    Parameters
    ----------
    world
        World to inspect.
    engine
        Engine carrying ``segment_length``, ``max_segments`` and
        ``warn_segments``.

    Returns
    -------
    list[str]
        Zero to three diagnostic strings, in the order thin-wire,
        resolution, budget; each names up to five electrodes or
        conductors and the number of further ones.
    """
    report = DiagnosticsReport(
        findings=_resolution_findings(world, engine),
        context={
            "min_thinwire_ratio": MIN_THINWIRE_RATIO,
            "segment_length_m": _check_ds(engine),
        },
    )
    return report.lines()

diagnose

diagnose(world: 'World', engine: 'Engine | None' = None, *, result: 'FieldResult | None' = None, proximity: bool = True) -> DiagnosticsReport

Aggregated diagnostics of a world (review finding 10.70).

Parameters:

Name Type Description Default
world 'World'

World to inspect.

required
engine 'Engine | None'

Engine of the solve. Needed for the discretisation checks (thin wire, resolution, budget against the engine's limit max_segments and its notice size warn_segments); the proximity check then runs on the segments the solver assembles. Without an engine only the geometry-only checks run.

None
result 'FieldResult | None'

Solved result; adds the post-solve checks (series truncation).

None
proximity bool

Run the close / interpenetrating wire check (groundfield.conductors.find_close_wires()) on the leakage wires of different owners (default True).

True

Returns:

Type Description
DiagnosticsReport

Findings with category, severity, subjects and data; str() gives one aggregated line per cause, DiagnosticsReport.warn() emits them as one DiagnosticsWarning.

Notes

Categories:

coordinates The world mixes local and projected coordinates: points lie both within 10 km of the origin and beyond 1000 km from it (horizontal distance; warning, user decision D5, audit W2B-04). The world is solved as given, its two groups some 33 000 km apart, and the solve warns with MixedCoordinatesWarning. A world that does not mix but whose horizontal extent (the diagonal of its bounding box) exceeds 100 km is reported as information (two UTM zones, a zone prefix on some eastings only, a geometry in millimetres). The data name the elements of each group (near, far), the conductors between them (spanning, spanning_lengths_m) and the extent (extent_m, bounds_xy_m). thin_wire segment_length / wire_radius below MIN_THINWIRE_RATIO (electrodes; discretize_segment_length for distributed conductors). resolution An electrode feature shorter than segment_length (min_feature_length(): rod and strip length, ring circumference, shortest polyline edge, star arm, mesh span). budget Predicted segment count or nodal system at or above the engine's notice size, Engine.warn_segments or by default SOFT_LIMIT (info: the solve may take minutes), or above the engine's limit, Engine.max_segments or by default HARD_LIMIT (warning: the solve refuses). report.context["max_segments"] and report.context["warn_segments"] hold the two sizes. proximity Leakage wires of different owners closer than PROXIMITY_REL_THRESHOLD times the sum of their radii. Two wires of one generated foundation (<name> and <name>_w<j>, bonded by <name>_bond_<k>) are reported only away from the vertices they share: they meet at its corners and crossings by design (audit D3A-04), but the opposite sides of a narrow encased ring or the parallel wires of a fine mesh are close wires like any other (audit R4A-04); findings between foundations name their anchors: interpenetrating / close are warnings with the point kernel and information with the exact line kernel (which integrates near pairs), crossing / touching (wires that meet without a bond in the model) are information. overlap Two conductors with an inductance_model (insulated or bare) that lie beside each other closer than touching — axis distance below the sum of their radii by more than 1e-9 of it, or by more than 16 units in the last place of the largest coordinate of the pair, whichever is larger (round-off of a drawing at the touching distance is not an overlap, also at projected coordinates; audits W3B-03, W3R2B-02) — over more than OVERLAP_REL_LENGTH times that distance and OVERLAP_FRACTION of the shorter conductor (warning): a service drop drawn on its PEN main, two cables on one axis. The inductance matrix evaluates them as touching wires (since 2026.11), so their coupling over the stretch follows their radii instead of the drawn spacing. A thinner conductor inside a "cable_shield" conductor is its concentric core (user decision Q32) and not reported; conductors that meet at a point (a crossing, a T-contact, a branch: two drops leaving a cabinet 1.7 deg apart run within touching for 0.4 m of their 180 m) are not overlaps (thresholds: comment of OVERLAP_FRACTION). The data give the length of the stretch (overlap_m), its ends, the smallest axis distance and the touching distance. interface_contact A rod head or tip within one wire radius of a physical layer interface, where the thin-wire model (no end face) deviates from the solid rod by up to +21 % (audit A3S-05), and a horizontal wire (every electrode but a rod, the leaking pieces of a galvanic distributed conductor) within the reach of a contrasting interface, where the thin wire deviates from the solid wire by more than about 1 % (3.9 wire radii over a layer 33 times more conductive; audits W4A-07, W4B-02, W4R2A-04); the segment backends and the 3-D fem warn with InterfaceContactWarning too. With an fem engine there is no such finding for a world that its axisymmetric model takes (FemOptions.model "auto" or "axisymmetric"): that model resolves the rod end faces and the ring wires as the solid bodies they are and its solve does not warn (audit W4R2A-05). inert Settings the solve ignores: conductors not attached at both ends, the deprecated concrete-shell registry, non-default boundary conditions, a non-default soil permittivity. series After the solve: a backend that reports converged=False.

Source code in src/groundfield/diagnostics.py
def diagnose(
    world: "World",
    engine: "Engine | None" = None,
    *,
    result: "FieldResult | None" = None,
    proximity: bool = True,
) -> DiagnosticsReport:
    """Aggregated diagnostics of a world (review finding 10.70).

    Parameters
    ----------
    world
        World to inspect.
    engine
        Engine of the solve. Needed for the discretisation checks
        (thin wire, resolution, budget against the engine's limit
        ``max_segments`` and its notice size ``warn_segments``); the
        proximity check then runs on the segments
        the solver assembles. Without an engine only the geometry-only
        checks run.
    result
        Solved result; adds the post-solve checks (series truncation).
    proximity
        Run the close / interpenetrating wire check
        (:func:`groundfield.conductors.find_close_wires`) on the leakage
        wires of different owners (default ``True``).

    Returns
    -------
    DiagnosticsReport
        Findings with category, severity, subjects and data; ``str()``
        gives one aggregated line per cause, :meth:`DiagnosticsReport.warn`
        emits them as one :class:`DiagnosticsWarning`.

    Notes
    -----
    Categories:

    ``coordinates``
        The world mixes local and projected coordinates: points lie both
        within 10 km of the origin and beyond 1000 km from it (horizontal
        distance; warning, user decision D5, audit W2B-04). The world is
        solved as given, its two groups some 33 000 km apart, and the solve
        warns with :class:`MixedCoordinatesWarning`. A world that does not
        mix but whose horizontal extent (the diagonal of its bounding box)
        exceeds 100 km is reported as information (two UTM zones, a zone
        prefix on some eastings only, a geometry in millimetres). The data
        name the elements of each group (``near``, ``far``), the conductors
        between them (``spanning``, ``spanning_lengths_m``) and the extent
        (``extent_m``, ``bounds_xy_m``).
    ``thin_wire``
        ``segment_length / wire_radius`` below :data:`MIN_THINWIRE_RATIO`
        (electrodes; ``discretize_segment_length`` for distributed
        conductors).
    ``resolution``
        An electrode feature shorter than ``segment_length``
        (:meth:`~groundfield.geometry.electrodes.RodElectrode.min_feature_length`:
        rod and strip length, ring circumference, shortest polyline
        edge, star arm, mesh span).
    ``budget``
        Predicted segment count or nodal system at or above the engine's
        notice size, ``Engine.warn_segments`` or by default
        :data:`SOFT_LIMIT` (info: the solve may take minutes), or above the
        engine's limit, ``Engine.max_segments`` or by default
        :data:`HARD_LIMIT` (warning: the solve refuses).
        ``report.context["max_segments"]`` and
        ``report.context["warn_segments"]`` hold the two sizes.
    ``proximity``
        Leakage wires of different owners closer than
        :data:`PROXIMITY_REL_THRESHOLD` times the sum of their radii. Two
        wires of one generated foundation (``<name>`` and ``<name>_w<j>``,
        bonded by ``<name>_bond_<k>``) are reported only away from the
        vertices they share: they meet at its corners and crossings by
        design (audit D3A-04), but the opposite sides of a narrow encased
        ring or the parallel wires of a fine mesh are close wires like any
        other (audit R4A-04); findings between foundations name their
        anchors:
        ``interpenetrating`` / ``close`` are warnings with the point
        kernel and information with the exact line kernel (which
        integrates near pairs), ``crossing`` / ``touching`` (wires that
        meet without a bond in the model) are information.
    ``overlap``
        Two conductors with an ``inductance_model`` (insulated or bare) that
        lie beside each other closer than touching — axis distance below
        the sum of their radii by more than 1e-9 of it, or by more than 16
        units in the last place of the largest coordinate of the pair,
        whichever is larger (round-off of a drawing at the touching
        distance is not an overlap, also at projected coordinates; audits
        W3B-03, W3R2B-02) — over more than :data:`OVERLAP_REL_LENGTH`
        times that distance and :data:`OVERLAP_FRACTION` of the shorter
        conductor (warning): a service drop drawn on its PEN main, two
        cables on one axis. The inductance matrix evaluates them
        as touching wires (since 2026.11), so their coupling over the
        stretch follows their radii instead of the drawn spacing. A
        thinner conductor inside a ``"cable_shield"`` conductor is its
        concentric core (user decision Q32) and not reported; conductors
        that meet at a point (a crossing, a T-contact, a branch: two drops
        leaving a cabinet 1.7 deg apart run within touching for 0.4 m of
        their 180 m) are not overlaps (thresholds: comment of
        :data:`OVERLAP_FRACTION`). The data give the length of the
        stretch (``overlap_m``), its ends, the smallest axis distance and
        the touching distance.
    ``interface_contact``
        A rod head or tip within one wire radius of a physical layer
        interface, where the thin-wire model (no end face) deviates from
        the solid rod by up to +21 % (audit A3S-05), and a horizontal wire
        (every electrode but a rod, the leaking pieces of a galvanic
        distributed conductor) within the reach of a contrasting interface,
        where the thin wire deviates from the solid wire by more than about
        1 % (3.9 wire radii over a layer 33 times more conductive; audits
        W4A-07, W4B-02, W4R2A-04); the segment backends and the 3-D ``fem`` warn with
        :class:`~groundfield.solver.InterfaceContactWarning` too. With an
        ``fem`` engine there is no such finding for a world that its
        axisymmetric model takes (``FemOptions.model`` ``"auto"`` or
        ``"axisymmetric"``): that model resolves the rod end faces and the
        ring wires as the solid bodies they are and its solve does not warn
        (audit W4R2A-05).
    ``inert``
        Settings the solve ignores: conductors not attached at both ends,
        the deprecated concrete-shell registry, non-default boundary
        conditions, a non-default soil permittivity.
    ``series``
        After the solve: a backend that reports ``converged=False``.
    """
    report = DiagnosticsReport(
        context={
            "min_thinwire_ratio": MIN_THINWIRE_RATIO,
            "proximity_rel_threshold": PROXIMITY_REL_THRESHOLD,
            "overlap_rel_length": OVERLAP_REL_LENGTH,
            "overlap_fraction": OVERLAP_FRACTION,
        }
    )
    report.findings.extend(_coordinate_findings(world))
    if engine is not None:
        report.context["segment_length_m"] = _check_ds(engine)
        report.context["max_segments"] = _hard_limit(engine)
        report.context["warn_segments"] = _soft_limit(engine)
        report.findings.extend(_resolution_findings(world, engine))
    if proximity and (engine is None or check_budget_ok(world, engine)):
        report.findings.extend(_proximity_findings(world, engine))
    report.findings.extend(_overlap_findings(world))
    report.findings.extend(_interface_contact_findings(world, engine))
    report.findings.extend(_inert_findings(world))
    if result is not None:
        report.findings.extend(_series_findings(result))
    return report

expected_segments

expected_segments(world: 'World', engine: 'Engine', *, layer_interfaces: Sequence[float] | None = None) -> dict[str, Any]

Predict the number of point-source segments after discretisation.

Uses the electrodes' own discretisation (segment_count() and siblings), so the prediction is exact for the image family, including the split of wires at the soil-layer interfaces. An electrode whose closed-form lower bound \(\lceil L_\text{total}/ds \rceil\) already exceeds the engine's limit (Engine.max_segments, default HARD_LIMIT) is counted by that bound instead, so that a unit error does not allocate a huge discretisation just to count it. The fem backend (groundfield.solver.fem) solves a volume mesh that is unrelated to segment_length (FemOptions.max_nodes, max_nodes_3d); for it the prediction counts only the display segments of its result.

Parameters:

Name Type Description Default
world 'World'

World to inspect.

required
engine 'Engine'

Engine carrying segment_length (in metres) and the limit max_segments.

required
layer_interfaces Sequence[float] | None

Interface depths in m at which wires are split. None (default) takes them from world.soil (h_1 of a two-layer soil, the layer boundaries of a layered soil).

None

Returns:

Type Description
dict

Keys:

  • per_electrode: dict[name, int] with the segment count of every named electrode,
  • per_kind: dict[kind, int] aggregated counts per electrode kind,
  • electrode_total (int),
  • per_conductor: dict[name, int] (only listed for distributed conductors; lumped conductors contribute 0 and are omitted),
  • conductor_total (int),
  • total (int) — sum of electrode and conductor segments,
  • nodal_unknowns (int) — size of the dense augmented nodal system (owners, nodes and branches, including every conductor sub-piece), an upper bound; checked against the limit like total,
  • limit (int) — the limit the solve checks both sizes against: engine.max_segments, or HARD_LIMIT if the engine leaves it at None.

Raises:

Type Description
ValueError

If engine.segment_length is not strictly positive.

Source code in src/groundfield/diagnostics.py
def expected_segments(
    world: "World",
    engine: "Engine",
    *,
    layer_interfaces: Sequence[float] | None = None,
) -> dict[str, Any]:
    """Predict the number of point-source segments after discretisation.

    Uses the electrodes' own discretisation
    (:meth:`~groundfield.geometry.electrodes.RodElectrode.segment_count`
    and siblings), so the prediction is *exact* for the image family,
    including the split of wires at the soil-layer interfaces. An
    electrode whose closed-form lower bound
    $\\lceil L_\\text{total}/ds \\rceil$ already exceeds the engine's
    limit (``Engine.max_segments``, default :data:`HARD_LIMIT`) is
    counted by that bound instead, so that a unit error does not
    allocate a huge discretisation just to count it. The ``fem`` backend
    (:mod:`groundfield.solver.fem`) solves a volume mesh that is unrelated
    to ``segment_length`` (``FemOptions.max_nodes``, ``max_nodes_3d``); for
    it the prediction counts only the display segments of its result.

    Parameters
    ----------
    world
        World to inspect.
    engine
        Engine carrying ``segment_length`` (in metres) and the limit
        ``max_segments``.
    layer_interfaces
        Interface depths in m at which wires are split. ``None``
        (default) takes them from ``world.soil`` (``h_1`` of a two-layer
        soil, the layer boundaries of a layered soil).

    Returns
    -------
    dict
        Keys:

        * ``per_electrode``: ``dict[name, int]`` with the segment
          count of every named electrode,
        * ``per_kind``: ``dict[kind, int]`` aggregated counts per
          electrode kind,
        * ``electrode_total`` (int),
        * ``per_conductor``: ``dict[name, int]`` (only listed for
          distributed conductors; lumped conductors contribute 0
          and are omitted),
        * ``conductor_total`` (int),
        * ``total`` (int) — sum of electrode and conductor segments,
        * ``nodal_unknowns`` (int) — size of the dense augmented nodal
          system (owners, nodes and branches, including every conductor
          sub-piece), an upper bound; checked against the limit like
          ``total``,
        * ``limit`` (int) — the limit the solve checks both sizes
          against: ``engine.max_segments``, or :data:`HARD_LIMIT` if the
          engine leaves it at ``None``.

    Raises
    ------
    ValueError
        If ``engine.segment_length`` is not strictly positive.
    """
    ds = _check_ds(engine)
    limit = _hard_limit(engine)
    if layer_interfaces is None:
        layer_interfaces = _layer_interfaces(world.soil)

    per_electrode: dict[str, int] = {}
    per_kind: Counter[str] = Counter()
    e_total = 0
    for e in world.electrodes:
        n = _electrode_segment_count(e, ds, layer_interfaces, limit)
        per_electrode[e.name] = n
        per_kind[e.kind] += n
        e_total += n

    per_conductor: dict[str, int] = {}
    c_total = 0
    for c in world.conductors:
        n = _conductor_segment_count(c)
        if n > 0:
            per_conductor[c.name] = n
        c_total += n

    return {
        "per_electrode": per_electrode,
        "per_kind": dict(per_kind),
        "electrode_total": e_total,
        "per_conductor": per_conductor,
        "conductor_total": c_total,
        "total": e_total + c_total,
        "nodal_unknowns": _nodal_unknowns(world, layer_interfaces),
        "limit": limit,
    }

world_statistics

world_statistics(world: 'World') -> dict[str, Any]

Return a structural snapshot of a world.

Aggregates counts, lengths and the bounding box; complements World.summary() (one-line text) with a richer machine-readable dictionary that scales to production-grade networks.

Parameters:

Name Type Description Default
world 'World'

World to inspect.

required

Returns:

Type Description
dict

Keys:

  • n_electrodes (int),
  • n_electrodes_by_kind (dict[str, int]: rod / ring / strip / polyline / star / mesh / grid_mesh),
  • n_junctions (int),
  • n_conductors (int),
  • n_conductors_by_type (dict[str, int]),
  • n_distributed_conductors / n_lumped_conductors,
  • n_galvanic_conductors / n_isolated_conductors,
  • n_sources (int),
  • total_electrode_wire_length_m (float),
  • total_conductor_length_m (float),
  • conductor_length_stats: {min, median, max, mean} in metres (empty dict when no conductors),
  • bounds_3d: (x_min, x_max, y_min, y_max, z_min, z_max) in metres,
  • footprint_xy: (x_min, x_max, y_min, y_max),
  • footprint_area_m2 (float),
  • depth_range_m: (z_min, z_max),
  • has_layered_soil (bool — diagnostic flag set when the soil model is TwoLayerSoil or MultiLayerSoil).
Source code in src/groundfield/diagnostics.py
def world_statistics(world: "World") -> dict[str, Any]:
    """Return a structural snapshot of a world.

    Aggregates counts, lengths and the bounding box; complements
    :meth:`World.summary` (one-line text) with a richer
    machine-readable dictionary that scales to production-grade networks.

    Parameters
    ----------
    world
        World to inspect.

    Returns
    -------
    dict
        Keys:

        * ``n_electrodes`` (int),
        * ``n_electrodes_by_kind`` (``dict[str, int]``: rod / ring
          / strip / polyline / star / mesh / grid_mesh),
        * ``n_junctions`` (int),
        * ``n_conductors`` (int),
        * ``n_conductors_by_type`` (``dict[str, int]``),
        * ``n_distributed_conductors`` / ``n_lumped_conductors``,
        * ``n_galvanic_conductors`` / ``n_isolated_conductors``,
        * ``n_sources`` (int),
        * ``total_electrode_wire_length_m`` (float),
        * ``total_conductor_length_m`` (float),
        * ``conductor_length_stats``: ``{min, median, max, mean}``
          in metres (empty dict when no conductors),
        * ``bounds_3d``: ``(x_min, x_max, y_min, y_max, z_min,
          z_max)`` in metres,
        * ``footprint_xy``: ``(x_min, x_max, y_min, y_max)``,
        * ``footprint_area_m2`` (float),
        * ``depth_range_m``: ``(z_min, z_max)``,
        * ``has_layered_soil`` (bool — diagnostic flag set when
          the soil model is :class:`TwoLayerSoil` or
          :class:`MultiLayerSoil`).
    """
    from groundfield.postprocess.geometry_plot import world_bounds_3d
    from groundfield.soil.models import MultiLayerSoil, TwoLayerSoil

    by_kind: Counter[str] = Counter()
    total_e_wire = 0.0
    for e in world.electrodes:
        by_kind[str(e.kind)] += 1
        total_e_wire += _electrode_wire_length(e)

    by_type: Counter[str] = Counter(c.conductor_type for c in world.conductors)
    n_distributed = sum(1 for c in world.conductors if c.is_distributed)
    n_galvanic = sum(1 for c in world.conductors if c.coupling_to_soil == "galvanic")
    cond_lengths = [float(c.length) for c in world.conductors]
    total_c_length = float(sum(cond_lengths))
    if cond_lengths:
        cond_stats = {
            "min": float(min(cond_lengths)),
            "median": float(median(cond_lengths)),
            "max": float(max(cond_lengths)),
            "mean": float(sum(cond_lengths) / len(cond_lengths)),
        }
    else:
        cond_stats = {}

    x_min, x_max, y_min, y_max, z_min, z_max = world_bounds_3d(world)
    footprint = (x_min, x_max, y_min, y_max)
    area = (x_max - x_min) * (y_max - y_min)

    has_layered = isinstance(world.soil, (TwoLayerSoil, MultiLayerSoil))

    return {
        "n_electrodes": len(world.electrodes),
        "n_electrodes_by_kind": dict(by_kind),
        "n_junctions": len(world.junctions),
        "n_conductors": len(world.conductors),
        "n_conductors_by_type": dict(by_type),
        "n_distributed_conductors": n_distributed,
        "n_lumped_conductors": len(world.conductors) - n_distributed,
        "n_galvanic_conductors": n_galvanic,
        "n_isolated_conductors": len(world.conductors) - n_galvanic,
        "n_sources": len(world.sources),
        "total_electrode_wire_length_m": float(total_e_wire),
        "total_conductor_length_m": total_c_length,
        "conductor_length_stats": cond_stats,
        "bounds_3d": (x_min, x_max, y_min, y_max, z_min, z_max),
        "footprint_xy": footprint,
        "footprint_area_m2": float(area),
        "depth_range_m": (z_min, z_max),
        "has_layered_soil": has_layered,
    }