Skip to content

Generators

The generators package builds complete worlds of TN low-voltage networks (Ortsnetze): a substation earth, the foundation earths of the buildings, cable distribution cabinets, the PEN network that joins them and, optionally, a fall-of-potential measurement set-up. It contains no physics of its own; it decides geometry and topology and hands a World to the solver. Design and validation programme: ADR-0009.

Two front-ends share one data model:

  • TnNetworkGenerator(config, seed=...) draws a network from population parameters (TnNetworkConfig: building counts and types, soil, placement, PEN topology), every numeric field a fixed value or a Distribution;
  • LvNetworkLayout composes one deterministic network step by step, as an engineer draws it: real building footprints (OSM), a hand-placed substation and cabinets, PEN cables routed on a Manhattan grid around the buildings, and the measurement loop.

Both produce a pure-data NetworkPlan; one materialiser, materialise_plan(plan), turns every plan into a World, so both front-ends build foundations, concrete shells, PEN junctions and measurement leads in the same way.

Mathematical and physical context

The generated world is solved like any other: Laplace's equation in the layered soil with the electrodes as equipotential clusters and the PEN network as branches. What the generator controls is the parameter space of the study (AP1):

Axis Config field
building mix (single-family houses, small and medium commercial) building_counts, building_types
grounding system per building type (foundation, ring, rods, strips) BuildingTypeSpec.grounding (GroundingSystemSpec of ElectrodeSpec)
penetration of foundation earths FoundationElectrodeSpec.presence_prob
concrete encasement (moisture) FoundationElectrodeSpec.concrete_rho_ohm_m, concrete_thickness_m
substation earth substation
cable distribution cabinets cabinets
PEN topology and cable data pen_topology, pen
soil \(\rho_1\), \(\rho_2\), \(h_1\) soil (HomogeneousSoilSpec, TwoLayerSoilSpec, MultiLayerSoilSpec)

Reproducibility. All random draws come from one generator seeded by seed (or rng= of build, plan and sample_world), in a canonical order: the same configuration and seed give the same world, independent of the order in which mapping keys were written. sample_world(rng=...) also returns the resolved configuration (every distribution replaced by its drawn value); it replays the world exactly when no per-site draws remain (presence probabilities 0 or 1, no placement jitter), otherwise keep the seed or the plan / world JSON. Successive build() or plan() calls on one generator draw successive realisations from its stream; build() right after plan() (no rng= in either, nothing drawn from generator.rng since, the same configuration) gives the world of that plan — up to audit W3R2B it drew a second realisation, another world with placement jitter. The foundation penetration mask of the layout builder is a stable hash of the building ids and is nested in the penetration rate (a house equipped at 10 % is also equipped at 20 %).

Foundations and PEN cables. A mesh foundation (style="mesh") is one wire electrode per mesh line at every orientation (<name>, <name>_w<j>, bonded into one cluster), bare or encased; an encased foundation (concrete_rho_ohm_m) carries the concrete shell on every wire, its cross-braces included (DIN 18014, see concrete shells). The image family solves one uniform current per straight wire (since user decision Q30 also inside a grid, so a mesh electrode built by hand and the generated foundation of bonded wires are the same model). Against the per-segment mom solution (100 Ω·m, 1 m segments; mom uses the point kernel), one current per wire is +1.1 % with the default line kernel and +0.3 … +0.5 % with kernel="point" for 10 m 2 × 2 to 30 m 4 × 4 meshes; one current for the whole mesh was +2.4 … +3.7 % (point kernel +1.5 … +3.1 %) and depended on the orientation. A rectangle without cross-braces (style="ring", or "mesh" with n_x = n_y = 1) is one strip per side at every orientation (user decision Q38); up to that decision an axis-aligned one was one grid_mesh electrode connected at its centre, and per side its input impedance is lower by less than 1 % up to aspect ratio 4 and 2 % up to 50 for a short side of at least 1 m over the soils of the AP1 grid, equal for a square (scope and numbers on the concrete-shell page). electrode_currents[<name>] and grounding_impedance(<name>) therefore refer to the first wire (the local −y side, whose start, a corner of the rectangle, is the connection point of conductors attached to <name> by name); use cluster_impedance or the sum over the wires for the foundation. A rectangle at a multiple of 90° is rotated exactly (no round-off), so the local −y side stays the first wire. A polygon outline is one closed polyline with one owner per straight side (one current per straight wire, user decisions Q30, Q44). The deprecated concrete_model has no effect (drop the argument, see Deprecations); an outline narrower than MIN_FOUNDATION_SIDE_M (1 m) is widened to it, with a warning, for both foundation_outline="ombr" and "polygon".

Cable cabinets per building group (user decisions Q22 and Q35). In the star topology TnNetworkGenerator places one cable cabinet per building group, at the far end of the houses it feeds (CabinetConfig.placement=None, the default): the buildings are ordered by their bearing around the substation, counter-clockwise from the widest angular gap between two neighbouring bearings, and cut into as many runs of consecutive bearings as there are cabinets (count_per_100_buildings or fixed_count), of sizes that differ by at most one (StarCabinetTopology.group_buildings); the cabinet of a group stands on the ray from the substation through the group's centroid, CabinetConfig.end_clearance_m (1 m, positive) beyond the largest projection on that ray of the group's earth electrodes (horizontal wires and rods) plus the plan extent of the cabinet's own grounding — when it stands there within CabinetConfig.max_far_end_gap_m (20 m, positive, larger than end_clearance_m) of the nearest electrode of its group: a cabinet stands next to the houses it feeds. A wider group, whose centroid ray leads past its houses, has its cabinet on the ray through its far-end building (the largest projection of its position on the direction of the centroid, ties to the one nearest to that direction), end_clearance_m beyond that building's electrodes. The cabinet feeds its group (audits W1B-01, W1B-02). 10 houses and one small commercial building had their cabinet 50.4 m from the nearest building on the centroid ray (drops 527.4 m), now 1.56 m (311.8 m) on the far-end ray; with the far-end ray for every group, six houses of the 50-house grid were fed straight from the substation (up to 116.8 m). The plan records per cabinet which rule placed it, PlannedSite.cabinet_rule ("centroid_ray" / "far_end_ray"), and its distance from the group on the centroid ray, PlannedSite.centroid_ray_gap_m (None for every other site and for cabinets of a given placement or of the radial topology; materialising ignores both).

The threshold is a step, kept for 2026.11 (user decision D7, audit W1R2-02). Groups lie on both sides of it: on the centroid ray the groups of the default 50-house grid stand 8.8 … 12.8 m from their houses, those of the 100-house grid 10.05 … 23.01 m (its two groups beyond 20 m are on the far-end ray; 15 / 25 m put four / none there), and over the 80 AP1 mixes the 118 groups beyond it stand 20.21 … 53.56 m from their houses and the largest gap kept is 18.84 m (19 mixes have a group between 15 and 25 m). A group whose distance crosses the threshold moves its cabinet by up to the width of the group, and the results jump:

layout change (homogeneous 100 Ω·m) cabinet moves drops R at 50 Hz X at 1 kHz, inductive PEN (carson_series / sommerfeld)
50-house grid, house columns 32.0 → 32.2 m apart (one group 19.99 → 20.22 m) 141.8 m 1 788.9 → 1 443.0 m −0.36 % (−0.14 % beyond the smooth trend) −21.6 / −18.9 %
100-house grid, columns across 22.95 m (two groups cross 20 m) 65.6 m each +15.8 % −0.03 % +1.5 / −3.1 %
80 houses + 5 medium commercial (AP1), one group at 20.21 m: max_far_end_gap_m 20 → 20.5 m 31.4 m 1 960.6 → 1 968.2 m −0.02 % +1.5 / +1.1 %

The 100-house row is the difference of straight lines through three spacings on each side of the crossing, at the crossing; R at 50 Hz with the image backend (2 m and 1 m segments agree), Z at 1 kHz with the isolated Neumann PEN in 5 m pieces. A study that varies the layout can read where a group crosses from the plan. A cabinet whose electrodes would come closer than end_clearance_m to those of another site — a building of its own or of another group, the substation, another cabinet — raises a ValueError that names both (3 of 100 random layouts of 200 houses 12 m apart; none of the default grids and AP1 mixes). In the default grid of 30 houses (three rows of ten, 25 m × 30 m, the substation in the middle row) the groups are the western and the eastern half, with their cabinets at (−118.5, 0) m and (118.5, 0) m; each main runs along the middle row, whose houses are joined to it, and the 20 houses of the outer rows tap it with drops of 25 m (before: both cabinets west of the substation, at (−180, 0) m and (−140, 0) m on a strip along the substation row, and 25 drops of 1 140 m, the 15 eastern ones from the substation, 3.5 … 106.5 m). A single group around the substation (one cabinet for a row through it) gets its cabinet beyond its farthest house, ties to the first in bearing order. A given CabinetConfig.placement keeps the former rule — the given positions, every building fed by its nearest cabinet (Manhattan metric) — and a configuration stored before the decision carries the former strip and keeps its cabinets. In RadialTrunkTopology a building in a substation slot that no trunk crosses taps its feeder's trunk at the closest pair, like the buildings of the cabinets, instead of getting its own line from the substation (default 30 houses: drops 1 115 → 778 m, 14 → 4 from the substation, those of the two feeders without a trunk).

In TnNetworkGenerator every cable cabinet has its own PEN cable, as the topology documents: from the substation (StarCabinetTopology), or one cable per trunk segment (RadialTrunkTopology). A service drop taps the cable path that feeds its own building — the cable of its cabinet, or the trunk from the substation to its tap source, for a building in a substation slot its feeder's whole trunk — at the point nearest to the building: a leakage-free tap junction pen_tap_<k> that splits the cable into sections <cable>_s<k>, or the substation or cabinet at the end of the cable; a building in a substation slot of a feeder without a trunk is connected to the substation. The router guarantees that a drop never starts on another building's drop, never runs along a cable (the one it taps, a trunk, another cabinet's main) farther than one minimum section, and that no cable section is shorter than that minimum section, 1 cm (a tap closer to a node is that node; longer for PEN radii above 7.3 mm, so that every section stays a finite resistance). "Along" means both ends of a cable section within 1 cm of the drop's line; the one overlap left is that 1 cm, where a foundation touches the end node of its cable from beyond and is tapped 1 cm before the node. Drops that leave one tap in one direction — the drops of houses behind each other, such as the five drops of the 5-house radial network from the substation ring along −x, or the five drops of the 10-house star from the substation — lie side by side at the touching distance \(2r\) of the PEN (decision D9 of 2026.11), so that only neighbours touch: sorted by length, shortest first (equal lengths in plan order), and centred on their common axis, drop \(k\) of \(n\) at \((k - (n - 1)/2)\,2r\) along the normal \((-d_y, d_x)/|d|\) of the drop direction \(d\). The plan records the offset as PlannedBranch.axis_offset_m; the materialiser moves both ends of the conductor by it, and the drop stays attached to its tap and its building (it starts up to \((n - 1)/2 \cdot 2r\) off the tap, 2 cm in a row of five). Two drops of one node are in a row when their start points lie within \(2r\) of each other and the end of the shorter one within \(2r\) of the line of the longer one — the overlap criterion — so the rows hold under placement jitter (audit W3R2B-01): drops that are not exactly parallel are shifted along one common normal (recorded as PlannedBranch.axis_offset_normal_xy), each just far enough to lie at least \(2r\) from every shorter one, and a drop that would come closer than touching to a drop of a row — of the same tap, or of a tap 1 … 4 cm away on the same trunk — joins the row. No generated network reports an overlap (star and radial networks of 5 … 200 houses, jitter_m 0 … 0.1 m), and the input impedance is continuous in the jitter: the reactance of the 10-house radial network at 1 kHz moves by −8.5e-10 at 1 nm and −4.5e-4 at 1 mm (carson_series; up to then +2.4 % at 1 nm, where the rows fell apart). Before D9 such drops lay on one axis and the inductance matrix read them as a bundle in which every pair touches, which no cross-section of four or more equal wires realises; gf.diagnose() reported every pair (audit W3B-05). With an inductive PEN (5 m pieces, 100 Ω·m) the input reactance moves at 1 kHz by −2.3 / −2.7 % (carson_series / sommerfeld) in the 5-house radial network, −2.3 / −2.8 % with 10 houses, −1.1 / −1.3 % in the 10-house star, and by at most 1.1e-6 (30 houses) and 5e-4 (80 and 200 houses, both frequencies) in the radial networks; the star networks of 5, 30, 80 and 200 houses have no such drops and build the same world, those of 40, 60, 100, 120, 140 and 180 houses have (the 60-house star: X −1.0e-3 / −6.1e-4 at 50 Hz / 1 kHz under carson_series, −1.3e-3 / −8.1e-4 under sommerfeld; the 40-house star, all 40 drops in rows, 3e-7), and plans written before (no offsets) build the worlds they built. LvNetworkLayout draws no rows. Conductors that overlap otherwise (in a hand-made plan) are evaluated as touching wires. A drop may also pass over other buildings' foundations, 0.2 m above their wires (PEN at 0.6 m, foundations at 0.8 m): the contact of a house lies at the corner of the side facing its cable (the tie rule below), so a drop to a house behind others of its grid column runs above their side wires. In the default grids of 10 to 200 houses that is 0 … 100 % of the drops (star, 30 houses: all 20 drops, each over 5 m above a side wire of the middle-row house it passes on its way from the main, 100 m in all; star 50, 150 and 200: none; radial 150: 87 of 140 drops, 1 805 m, up to 40 m over 4 houses); drops are not routed around foundations (user decision Q42). A drop has no inductive coupling to these wires in the field model (an electrode carries no current along itself), a bare one leaks next to them through the soil; moved 1 m aside as a whole, those drops change the input impedance by at most 0.006 % with an insulated PEN and by up to −0.40 % with a bare one (default grids of 30 and 150 houses, 50 Hz and 1 kHz; see the known limitations). The layout builder merges cable nodes closer than the same length.

Where conductors meet a site (user decisions Q41 and Q43). Every conductor the generators route to a site with a horizontal earth electrode ends at the point of that electrode nearest to it, in TnNetworkGenerator and in the layout builder: at a foundation of every form (rectangles at any orientation, building outlines) since user decision Q41, at a circular ring (RingElectrodeSpec, e.g. the default substation of both generators, a 4 m ring with four rods) and a strip since user decision Q43. A site with horizontal electrodes and rods is met at the nearest point of the horizontal ones, a site with several of them (the large_industry ring, mesh and strips) at the nearest point of all; rods (vertical) keep their head. A circle is met at its exact nearest point (it is searched on an inscribed polygon with a sagitta of at most 1 mm and refined to the circle). The default mains now leave the substation ring at its point nearest to their cabinets — the western ones at (−4, 0) m instead of (4, 0) m, through the ring — and drops from the substation at the point of the ring nearest to the house.

  • a service drop is the shortest connection in plan between its feeding cable and the horizontal wires of the building (their closest pair): the tap on the cable and the end on the foundation, ring or strip, at the PEN depth (layout builder: at the wire's depth), attached to the wire that holds the point (PlannedBranch.end_contact, a PlannedContact);
  • a cable leaving a substation or cabinet with horizontal electrodes starts at their point nearest to its next node;
  • a building that a cable crosses is joined to it and fed by it: a cable of the building's feeding path that crosses or touches its foundation in plan is joined to the wire there, and the building gets no drop; every trunk of the radial topology counts as a cable of the feeding path for this rule (a building in a substation slot has no cable of its own), and in the star topology a building that a main crosses is fed by that main's cabinet (the nearest of the cabinets whose mains cross it, ties to the lower cabinet index) instead of its nearest one; a main that crosses a building it does not feed stays unjoined (no cross-tie between cabinets through a house); where the foundation touches the cable at a node (a cabinet on a wire) and the cable crosses it elsewhere, it is joined where it crosses (audit R5A-03), otherwise the joint lies 1 cm from the node (audits R4A-02, R4B-01);
  • a drop whose closest pair lies at such a joint starts there, on the cable (audit R4A-01); a drop from a node that would run along a trunk or another main (both ends of a section within 1 cm of the drop's line, audit R5A-01) starts where it leaves it, at its node at the end of the shared stretch (audit R4B-01);
  • the layout builder keeps its taps on the layout polyline, where the cable's junctions are. The leading run of waypoints inside the start site's closed electrodes (a rectangle, a building outline, a circle) and the trailing run inside the end site's are part of those sites (audit R6A-01 — a router corner inside a small cabinet ring was a node that houses tapped, 82 of 2 540 drops in 200 random layouts with a 2 m cabinet ring started inside it), and the segment that leaves (enters) the site is clipped at the projection of the site's point nearest to its far waypoint. Every other passage of the cable through the closed electrodes of the substation or a cabinet — another cabinet on its way, or its own start or end site when it comes back through it — is clipped the same way: the cable reaches the site where it enters and leaves it where it leaves, joined to it there, and the waypoints in between are part of it (audits W1B-03, W1B-04; up to then a cable to a far cabinet kept a tap inside a near cabinet's ring, and a leg that left its start site and came back through it, or overshot its cabinet, was merged into the site and lost its taps: 142.8 m instead of 30.0 m of drops in the audit's loop case). So no tap and no corner lies inside the foundation of the substation or a cabinet, also for a rotated, polygon or offset one; a tap at a clip point, or at the site's waypoint, is the site (audits R4A-03, R5A-02). A cable through a house foundation is not joined to it: the house keeps its own drop, of no length in plan where the cable crosses its foundation;
  • ties go to the lowest wire index, then to the smallest arc position along the wire: a cable parallel to the side facing it meets the side at the start of the range of equal distance, for a side it passes along its whole length the corner where that wire starts.

Sites with rods only keep the connection point of their anchor (the head of the first rod), and so does everything attached by name (site_anchor_point, create_conductor(start=<foundation>)). site_contact_wires(site) returns the wires the rule uses (named site_foundation_wires before user decision Q43, foundations only). materialise_plan rejects a PlannedContact that names no horizontal wire (foundation, ring, strip) of the branch's site (a direct materialise_branch call without foundation_wires checks only that it names a strip, polyline or ring electrode; a NetworkPlan rejects another site's electrode when it is validated) or lies farther from its wire — from the exact circle of a ring — than one minimum cable section (1 cm; a joined cable's point may lie that far off the wire it crosses; audit R4A-05). LvNetworkLayout.plot(world=...) draws the drops as built (tap to foundation contact) instead of the layout's centroid stubs.

Coordinates. Both generators build in local coordinates around the origin. SubstationConfig.position moves the substation only: the buildings, cabinets and the measurement stay around (0, 0), so a substation placed at projected coordinates builds a world that mixes projected and local coordinates (10 houses with the substation at the UTM origin: one PEN cable of 33 118 km), which diagnose() reports and the solve warns about with MixedCoordinatesWarning; RadialTrunkTopology then drops every building and fails to build (audit W2R2-07). To place a network at projected coordinates, build it around the origin and translate the whole built world — every electrode, conductor and junction by the same offset; groundfield has no public helper for that, and the solve does not need it, since every result depends on coordinate differences only (the translated network of 10 houses has the input impedance of the local one to twelve digits).

Measurement set-up. A fall-of-potential measurement is a two-terminal source between the earthing system and an auxiliary electrode; the current and probe leads end on leakage-free junctions at the instrument, and measured_impedance(result) returns the reading of the simulated earth tester, probe voltage over source current. The leads can be overhead or buried (overhead_lead, buried_lead); their inductive coupling to the PEN network is part of the solve.

Example

import groundfield as gf

config = gf.TnNetworkConfig(
    soil=gf.TwoLayerSoilSpec(rho_1=gf.Uniform(low=80.0, high=300.0), rho_2=100.0, h_1=5.0),
    building_counts={"residential": 5},
)
world = gf.TnNetworkGenerator(config, seed=42).build()
again = gf.TnNetworkGenerator(config, seed=42).build()
assert gf.world_fingerprint(world) == gf.world_fingerprint(again)   # same seed, same world

stats = gf.world_statistics(world)
# each house has a 2 × 2 mesh foundation, one wire electrode per mesh line
assert stats["n_electrodes_by_kind"]["polyline"] == 5 * 6
result = gf.create_engine(frequencies=[50.0]).solve(world)
assert 1.0 < result.input_impedance()[0].real < 5.0       # Ω, substation with the PEN network

Tutorial T06 builds a network synthetically and from OpenStreetMap data, T07 adds the fall-of-potential measurement. The German names of releases up to 0.15.0 (OrtsnetzLayout, kvs, KvsConfig, …) keep working with a DeprecationWarning; see Deprecations and the glossary.

API reference

generators

World generators for reference networks.

This subpackage hosts the factory layer that turns high-level parameter sets — for example "N single-family houses on a two-layer soil" — into a fully populated groundfield.World that the solver can consume.

The framework is organised in five composable spec layers:

  • distributions — Constant, Uniform, Normal, LogNormal, Weibull, Discrete, Categorical. Each numerical / categorical field of any spec class accepts a fixed value or a Distribution.
  • electrode_specs — single-electrode specs (rod / ring / strip / foundation) with presence_prob and offset_xy_m.
  • grounding — GroundingSystemSpec composes a list of ElectrodeSpec into one cluster.
  • placement — Manhattan-grid and explicit-coordinate placement strategies.
  • soil_specs — homogeneous / two-layer / multi-layer soil specs that resolve to the groundfield.soil.models types.
  • building — BuildingTypeSpec bundles a name with a grounding system and an optional plot size.

Two front-ends compose these layers into a TN low-voltage network: TnNetworkGenerator (stochastic population parameters) and LvNetworkLayout (real footprints and routed PEN cables). Both produce a pure-data NetworkPlan; one materialiser (materialise_plan()) turns every plan into a groundfield.World.

See docs/adr/0009-world-generators.md for the design rationale and the validation programme.

AnyDistribution module-attribute

AnyDistribution = Annotated[Union[Constant, Uniform, Normal, LogNormal, Weibull, Discrete, Categorical], Field(discriminator='kind')]

Any concrete distribution, as a union discriminated by kind.

Used in the field annotations of GeneratorConfig so that Pydantic deserialises the right subclass from JSON by its kind field: "constant", "uniform", "normal", "lognormal", "weibull", "discrete" or "categorical".

ElectrodeSpec module-attribute

ElectrodeSpec = Annotated[Union[RodElectrodeSpec, RingElectrodeSpec, StripElectrodeSpec, FoundationElectrodeSpec], Field(discriminator='kind')]

JSON-serialisable union of electrode specs.

Use this alias as the field type in any GeneratorConfig that holds a list of electrodes (e.g. electrodes: list[ElectrodeSpec]). Pydantic dispatches on kind.

MEASUREMENT_H_TERMINAL module-attribute

MEASUREMENT_H_TERMINAL = 'meas_H'

Name of the instrument's current terminal (a junction).

Created when MeasurementInjectionConfig.feed_lead is set: the feed lead runs from this junction to the auxiliary electrode and the current source of the measurement returns its current here.

MEASUREMENT_S_TERMINAL module-attribute

MEASUREMENT_S_TERMINAL = 'meas_S'

Name of the instrument's voltage terminal (a junction).

Created when MeasurementProbeConfig.lead is set: the probe lead runs from this junction to the voltage probe; the voltmeter reads the potential difference between the earthing system and this junction.

PenTopology module-attribute

PenTopology = Annotated[Union[StarCabinetTopology, RadialTrunkTopology], Field(discriminator='kind')]

JSON-serialisable union of PEN topologies.

Add new topology classes here when a future Ortsnetz layout (meshed-LV, ring, mixed) is implemented; the TnNetworkGenerator dispatches on kind.

PlacementSpec module-attribute

PlacementSpec = Annotated[Union[ManhattanGridPlacement, ExplicitPlacement, OsmBuildingPlacement], Field(discriminator='kind')]

JSON-serialisable union of placement strategies.

SoilSpec module-attribute

SoilSpec = Annotated[Union[HomogeneousSoilSpec, TwoLayerSoilSpec, MultiLayerSoilSpec], Field(discriminator='kind')]

JSON-serialisable union of soil specs (homogeneous / two-layer / multi-layer).

AuxiliaryElectrodePlacement

Bases: BaseModel

Auxiliary current electrode (Hilfserder) for a fall-of- potential measurement of the substation grounding.

The auxiliary electrode closes the test-current loop. It is materialised in LvNetworkLayout.to_world() via GroundingSystemSpec.build_at(), giving the user full control over its geometry (single rod, ring, mesh, foundation, or any combination). The default is a bundle of three 0.5 m rods in a 0.5 m equilateral triangle, parallel-bonded — matching real-world practice and yielding a spreading resistance roughly a third of a single rod.

In LvNetworkLayout.to_world() the substation's current source returns its current through the auxiliary electrode's anchor (Source.return_to), so the potential field develops the expected dipole pattern (positive trumpet at the substation, negative trumpet at the auxiliary electrode). Up to 0.15.0 the solver ignored return_to and a second source with phase_deg=180 on the auxiliary electrode stood in for it.

BuildingConnection

Bases: BaseModel

Stub from one house's foundation centre to its serving cable.

Attributes:

Name Type Description
house_idx int

Index into LvNetworkLayout.footprints.

cable_name str

Name of the PenCable the stub taps into.

stub_waypoints list[tuple[float, float]]

Polyline from the house centroid to the tap point on the cable. [centroid, ..., tap_point]. The interior waypoints (if any) are the Manhattan corners.

tap_point_xy tuple[float, float]

The tap point on the cable polyline nearest to the house centroid (Manhattan), the end of stub_waypoints. The materialised drop of a house with a foundation, ring or strip taps the cable at the closest pair of cable and those wires instead (user decisions Q41, Q43, see LvNetworkLayout.to_world); a house with rods only is tapped here, or at the nearest point where the cable is built when this point lies inside a site foundation (audit R6A-01).

total_length_m

total_length_m() -> float

Route length of the stub in m.

Sums the Manhattan length abs(dx) + abs(dy) of every piece between consecutive stub_waypoints.

Returns:

Type Description
float

Length of the stub in m.

Source code in src/groundfield/generators/layout/routing.py
def total_length_m(self) -> float:
    """Route length of the stub in m.

    Sums the Manhattan length ``abs(dx) + abs(dy)`` of every piece
    between consecutive ``stub_waypoints``.

    Returns
    -------
    float
        Length of the stub in m.
    """
    return sum(
        abs(p1[0] - p0[0]) + abs(p1[1] - p0[1])
        for p0, p1 in zip(
            self.stub_waypoints[:-1],
            self.stub_waypoints[1:],
            strict=True,
        )
    )

BuildingTypeSpec

Bases: GeneratorConfig

Definition of one building type.

Attributes:

Name Type Description
name str

Identifier used as the lookup key in groundfield.generators.tn_network.TnNetworkConfig.building_counts and as a prefix for electrode names.

grounding GroundingSystemSpec

GroundingSystemSpec describing the type's earthing installation. Every electrode in the system is optional via presence_prob and may carry distributions for its geometric parameters.

plot_size_m Optional[tuple[float, float]]

Optional typical plot size \((dx, dy)\) in metres. v1 of the TN network generator does not consume this — it is exposed so future placement strategies (street-grid, OSM-driven) can pack buildings with type-aware footprints.

description Optional[str]

Free-form note describing the type (use case, source of the geometry, …). Stored verbatim, not validated.

CabinetConfig

Bases: GeneratorConfig

Cable-cabinet block (German KVS) — placement, count, grounding.

Attributes:

Name Type Description
placement Optional[PlacementSpec]

Where to place the cabinets (star topology only). None (the default since 2026.11, user decisions Q22 and Q35): one cabinet per building group, at the far end of the houses it feeds — the buildings are grouped by group_buildings() (consecutive bearings around the substation, sizes differing by at most one), and the cabinet of a group stands on the ray from the substation through the group's centroid, end_clearance_m beyond the largest projection on that ray of the group's earth electrodes (horizontal wires and, since audit W1B-02, rods) plus the plan extent of the cabinet's own grounding — when it stands there within max_far_end_gap_m of the nearest electrode of its group; otherwise (a wide group, whose centroid ray leads past its houses) on the ray through the group's far-end building, the largest projection of its position on the direction of the centroid, end_clearance_m beyond that building's electrodes (audit W1B-01). It feeds its group. A cabinet whose electrodes would come closer than end_clearance_m to those of another site (a building of its or another group, the substation, another cabinet) raises a ValueError naming both. A placement places the cabinets as up to 2026.11 (the strip along the substation row of the former default, ManhattanGridPlacement(spacing_x_m=40, spacing_y_m=1, n_per_row=10), reproduces that world bit for bit), and every building is fed by its nearest cabinet (Manhattan metric). In both cases a building that a cabinet's cable crosses is fed by that cable (user decision Q41). A configuration stored before 2026.11 carries the former default placement and keeps its cabinets.

count_per_100_buildings Union[float, AnyDistribution]

Number of cabinets per 100 buildings; the count is ceil(count_per_100_buildings * n_buildings / 100), at least 1 (with building groups at most one per building).

fixed_count Optional[Union[int, AnyDistribution]]

Optional fixed cabinet count (overrides the rate).

grounding GroundingSystemSpec

Grounding system of every cabinet.

end_clearance_m Union[_PositiveDistance, AnyDistribution]

Smallest plan distance in m between the earth electrodes of a cabinet and those of any other site (building groups only), positive, finite and smaller than max_far_end_gap_m — a cabinet on the centroid ray stands at least this far from its group, so a larger value sent every group to the far-end ray, silently (audit W1R2-09); a distribution is checked where it is drawn (audit W1B-05).

max_far_end_gap_m Union[_PositiveDistance, AnyDistribution]

Largest plan distance in m (default 20, positive, finite, larger than end_clearance_m) between a cabinet on the ray through its group's centroid and the nearest electrode of its group; a cabinet farther from the houses it feeds stands on the ray through the group's far-end building instead (building groups only; e.g. 10 houses and one small commercial building: 50.4 m on the centroid ray, 1.6 m on the far-end ray). The plan records per cabinet which rule placed it and that distance (cabinet_rule, centroid_ray_gap_m). The threshold is a step, kept for 2026.11 (user decision D7; audit W1R2-02): a group whose distance crosses it moves its cabinet by up to the width of the group, and the results jump — the 50-house grid with its house columns 32.0 / 32.2 m apart (southern group 19.99 → 20.22 m) moves one cabinet by 141.8 m, its drops by −19 %, the input resistance at 50 Hz by −0.14 % beyond the smooth trend and, with an inductive PEN, the reactance at 1 kHz by −22 / −19 % (carson_series / sommerfeld). Groups lie on both sides of it: on the centroid ray the groups of the default 50-house grid stand 8.8 … 12.8 m from their houses, those of the 100-house grid 10.05 … 23.01 m (two beyond 20 m; 15 / 25 m put four / none of its groups on the far-end ray), and over the 80 AP1 mixes the groups beyond it 20.21 … 53.56 m, the largest one kept 18.84 m.

quote_per_100_buildings property

quote_per_100_buildings: Union[float, Distribution]

Deprecated alias of count_per_100_buildings.

CabinetPlacement

Bases: PickleUpgrade, BaseModel

One user-placed cable cabinet (German KVS).

Attributes:

Name Type Description
name str

Cabinet name; also the name of its grounding site.

position_xy tuple[float, float]

Cabinet position (x, y) in m.

Categorical

Bases: Distribution

Categorical distribution over a finite string set.

Used for non-numeric parameters such as the electrode kind per house (\(\in \{\text{foundation}, \text{rod}, \text{mesh}\}\)). weights biases the choice; uniform if omitted.

sample

sample(rng: Generator) -> str

Draw one entry of values, weighted by weights if given.

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
str

One entry of values.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> str:
    """Draw one entry of ``values``, weighted by ``weights`` if given.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    str
        One entry of ``values``.
    """
    if self.weights is None:
        idx = int(rng.integers(0, len(self.values)))
    else:
        p = np.asarray(self.weights, dtype=float)
        p = p / p.sum()
        idx = int(rng.choice(len(self.values), p=p))
    return str(self.values[idx])

ConductorParameters

Bases: BaseModel

Electrical and discretisation parameters of a branch conductor.

Attributes:

Name Type Description
conductor_type str

Conductor type tag ("pen", "bare_copper", "cable_shield", ...).

wire_radius_m float

Wire radius in m.

cross_section Union[float, Literal['from_radius'], None]

Cross section in m², "from_radius" (π r²) or None (ideal galvanic short).

coupling_to_soil str

"isolated" (no leakage along the wire) or "galvanic".

segment_length_m Optional[float]

Discretisation length in m of the distributed conductor model; None keeps the conductor lumped.

inductance_model Optional[str]

"neumann" or None (resistive branch).

Constant

Bases: Distribution

Degenerate distribution returning value deterministically.

Useful as a placeholder or in code paths that always expect a Distribution instance.

sample

sample(rng: Generator) -> float

Return value; the generator is not used.

Parameters:

Name Type Description Default
rng Generator

Random number generator (ignored; kept for the common interface).

required

Returns:

Type Description
float

value.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Return ``value``; the generator is not used.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator (ignored; kept for the common
        interface).

    Returns
    -------
    float
        ``value``.
    """
    return float(self.value)

Discrete

Bases: Distribution

Discrete numerical distribution over a finite value set.

Mirrors typical parameter axes such as \(n_\text{EFH} \in \{5, 10, 30, 80, 200\}\). weights may be supplied to bias the choice; if omitted the values are sampled uniformly.

sample

sample(rng: Generator) -> float

Draw one entry of values, weighted by weights if given.

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
float

One entry of values.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Draw one entry of ``values``, weighted by ``weights`` if given.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    float
        One entry of ``values``.
    """
    if self.weights is None:
        idx = int(rng.integers(0, len(self.values)))
    else:
        p = np.asarray(self.weights, dtype=float)
        p = p / p.sum()
        idx = int(rng.choice(len(self.values), p=p))
    return float(self.values[idx])

Distribution

Bases: BaseModel

Abstract base for probability distributions.

Subclasses must:

  1. set a literal kind field (used as the JSON discriminator),
  2. implement sample() returning a single draw.

The base class is intentionally a regular Pydantic model rather than an abc.ABC so it composes cleanly with discriminated unions in pydantic.BaseModel field annotations.

sample

sample(rng: Generator) -> Any

Draw one sample.

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
Any

One draw of the distribution (a float or a string in the concrete subclasses).

Raises:

Type Description
NotImplementedError

Always: the base class is abstract, a concrete subclass implements the draw.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> Any:  # pragma: no cover
    """Draw one sample.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    Any
        One draw of the distribution (a float or a string in the
        concrete subclasses).

    Raises
    ------
    NotImplementedError
        Always: the base class is abstract, a concrete subclass
        implements the draw.
    """
    raise NotImplementedError(
        f"{type(self).__name__}.sample is abstract; use a concrete subclass."
    )

ExplicitPlacement

Bases: BaseModel

Explicit caller-supplied list of \((x, y)\) positions.

The list must be at least as long as the requested count; extras are ignored. Order is preserved (so the k-th building from the count list ends up at the k-th position).

generate

generate(n: int, rng: Generator) -> list[tuple[float, float]]

Return the first n of the given positions.

Parameters:

Name Type Description Default
n int

Number of sites.

required
rng Generator

Random number generator (not used; kept for the common interface of the placement strategies).

required

Returns:

Type Description
list of tuple of float

The first n entries of positions, (x, y) in m.

Raises:

Type Description
ValueError

If n exceeds the number of given positions.

Source code in src/groundfield/generators/placement.py
def generate(self, n: int, rng: np.random.Generator) -> list[tuple[float, float]]:
    """Return the first ``n`` of the given positions.

    Parameters
    ----------
    n : int
        Number of sites.
    rng : numpy.random.Generator
        Random number generator (not used; kept for the common
        interface of the placement strategies).

    Returns
    -------
    list of tuple of float
        The first ``n`` entries of ``positions``, ``(x, y)`` in m.

    Raises
    ------
    ValueError
        If ``n`` exceeds the number of given positions.
    """
    if n > len(self.positions):
        raise ValueError(
            f"ExplicitPlacement: requested {n} positions but only "
            f"{len(self.positions)} provided."
        )
    return list(self.positions[:n])

FoundationElectrodeSpec

Bases: _ElectrodeSpecBase

Rectangular foundation electrode (Fundamenterder).

A rectangle of side length size_m (or size_xy_m for an asymmetric footprint) at depth depth_m. The internal structure is selected by style:

  • "ring" — only the rectangle's perimeter is buried (a closed wire loop). No internal cross-bracing. n_x and n_y are ignored. Use this for the Ringerder-style foundation electrode in residential buildings where only the strip foundation is electrically connected.
  • "mesh" (default) — perimeter plus horizontal and vertical cross-braces, dividing the foundation into n_x × n_y cells. The Maschenerder-style foundation electrode found in larger buildings, transformer stations and industrial sites. With n_x = n_y = 2 (the default) the rectangle gets exactly one internal horizontal plus one internal vertical wire.

The image family solves one uniform leakage current per straight wire (an owner; user decisions Q30, Q44): an outline is one owner per straight side. The owners of a foundation depend only on its structure, never on the orientation, on whether a shell is configured (audit A2G-04) or on the deprecated concrete_model, which has no effect (user decision Q38). A "mesh" foundation is one straight wire per mesh line (a polyline split at the crossings), bonded to the first: one owner over perimeter and braces was 2.4 % (2 × 2) to 3.7 % (4 × 4) high against mom (one current per segment) with the default line kernel, one owner per wire is 1.1 % high (0.3–0.5 % with the point kernel, the kernel of mom). A rectangle without cross-braces ("ring", or "mesh" with n_x = n_y = 1) is one straight wire per side, bonded to the first, at every angle (user decision Q38). Up to then an axis-aligned one (also one turned by a multiple of 90°) was one groundfield.geometry.electrodes.GridMeshElectrode (one owner) with the default value; per side its input impedance is lower by less than 1 % up to aspect ratio 4 and 2 % up to 50 for a short side of at least 1 m, and equal for a square (see concrete_model for the scope). A polygon_xy_m outline is one closed polyline, solved as one owner per straight side (user decisions Q30/Q44).

The first wire of a rectangle (the anchor, named after the foundation) is its local \(-y\) side; its connection point, where conductors attached to the foundation by name start, is the corner at the start of that side (a building outline: its first vertex). The generators end their cables and service drops at the point of the foundation nearest to each conductor instead (user decision Q41, see groundfield.generators.materialise).

With a shell (concrete_rho_ohm_m) every wire of the foundation, the cross-braces of a mesh included, is encased (DIN 18014, user decision Q20); see ADR-0012.

For an asymmetric footprint set size_xy_m instead of size_m (when both are given, size_xy_m wins).

model_copy

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

Copy of the spec; validates an update of concrete_model.

Pydantic stores update without validation, so the deprecated concrete_model (user decision Q21) is validated here like in the constructor: a value outside {"lumped", "distributed"} raises the constructor's pydantic.ValidationError (no warning, nothing stored; audit D2B-04), "distributed" emits the constructor's DeprecationWarning at the caller's line and "lumped" is silent. Only that field is validated (on a shallow copy), so the other fields, also the required fields of a subclass, are copied as they are (audit R2B-05). copy.replace (Python >= 3.13) calls this method. Copies that leave the field alone (every copy the generators make) are silent.

Parameters:

Name Type Description Default
update Optional[Mapping[str, Any]]

Field values to change. concrete_model is validated; the other fields are not (as in pydantic).

None
deep bool

Deep copy instead of a shallow one.

False

Returns:

Type Description
FoundationElectrodeSpec

The copy (the receiver is not changed).

Raises:

Type Description
ValidationError

If update sets concrete_model to a value other than "lumped" or "distributed".

Source code in src/groundfield/generators/electrode_specs.py
def model_copy(
    self, *, update: Optional[Mapping[str, Any]] = None, deep: bool = False
) -> Self:
    """Copy of the spec; validates an ``update`` of ``concrete_model``.

    Pydantic stores ``update`` without validation, so the deprecated
    :attr:`concrete_model` (user decision Q21) is validated here like
    in the constructor: a value outside ``{"lumped", "distributed"}``
    raises the constructor's :class:`pydantic.ValidationError` (no
    warning, nothing stored; audit D2B-04), ``"distributed"`` emits
    the constructor's :class:`DeprecationWarning` at the caller's line
    and ``"lumped"`` is silent. Only that field is validated (on a
    shallow copy), so the other fields, also the required fields of a
    subclass, are copied as they are (audit R2B-05).
    ``copy.replace`` (Python >= 3.13) calls this method. Copies that
    leave the field alone (every copy the generators make) are silent.

    Parameters
    ----------
    update
        Field values to change. ``concrete_model`` is validated; the
        other fields are not (as in pydantic).
    deep
        Deep copy instead of a shallow one.

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

    Raises
    ------
    pydantic.ValidationError
        If ``update`` sets ``concrete_model`` to a value other than
        ``"lumped"`` or ``"distributed"``.
    """
    if update and "concrete_model" in update:
        # Only the field is validated, on a shallow copy, so the other
        # fields of a subclass need not be rebuilt (audit R2B-05): the
        # Literal check raises, the field validator warns for the
        # deprecated value.
        probe = super().model_copy()
        type(self).__pydantic_validator__.validate_assignment(
            probe, "concrete_model", update["concrete_model"]
        )
        update = {**update, "concrete_model": probe.concrete_model}
    return super().model_copy(update=update, deep=deep)

GeneratorConfig

Bases: PickleUpgrade, BaseModel

Base class for generator configurations.

Subclasses declare their parameters as Pydantic fields. Numerical fields are typed as T | <distribution alias> so the user can pass a fixed value or a Distribution. Categorical fields use str | Categorical.

Two introspection helpers are provided:

A config pickled by an earlier release unpickles with its renamed fields moved to the current names (_field_renames of the subclass) and fields added since filled with their defaults (PickleUpgrade, audit A2G-07).

has_distributions

has_distributions() -> bool

Return whether any field still carries a Distribution.

Recursive: a nested GeneratorConfig whose own field carries a distribution counts as "has distributions".

Source code in src/groundfield/generators/base.py
def has_distributions(self) -> bool:
    """Return whether any field still carries a :class:`Distribution`.

    Recursive: a nested :class:`GeneratorConfig` whose own field
    carries a distribution counts as "has distributions".
    """
    for value in self.__dict__.values():
        if _has_dist(value):
            return True
    return False

sample

sample(rng: Optional[Union[int, Generator]] = None) -> 'GeneratorConfig'

Return a copy with every Distribution resolved.

Each distribution anywhere in the config tree — fields of this config, of nested generator configs and of the spec models they hold (soil, placement, electrode, measurement specs), list items and dict values (e.g. building_counts) — is replaced by exactly one .sample(rng) draw. Fields are visited in declaration order, lists in order, dicts in sorted key order.

Parameters:

Name Type Description Default
rng Optional[Union[int, Generator]]

Either an integer seed, a numpy.random.Generator, or None (fresh entropy).

None

Returns:

Type Description
GeneratorConfig

A resolved config of the same concrete type; has_distributions() returns False. self is returned when there is nothing to resolve.

Notes

Population parameters that are plain numbers stay as they are: a presence_prob of 0.5 or a positive placement jitter_m still makes per-site draws when the resolved config is built (see WorldGenerator.sample_world()).

Source code in src/groundfield/generators/base.py
def sample(
    self: "GeneratorConfig", rng: Optional[Union[int, np.random.Generator]] = None
) -> "GeneratorConfig":
    """Return a copy with every :class:`Distribution` resolved.

    Each distribution anywhere in the config tree — fields of this
    config, of nested generator configs and of the spec models they
    hold (soil, placement, electrode, measurement specs), list items
    and dict values (e.g. ``building_counts``) — is replaced by
    exactly one ``.sample(rng)`` draw. Fields are visited in
    declaration order, lists in order, dicts in sorted key order.

    Parameters
    ----------
    rng
        Either an integer seed, a :class:`numpy.random.Generator`,
        or ``None`` (fresh entropy).

    Returns
    -------
    GeneratorConfig
        A *resolved* config of the same concrete type;
        ``has_distributions()`` returns ``False``. ``self`` is
        returned when there is nothing to resolve.

    Notes
    -----
    Population parameters that are plain numbers stay as they are:
    a ``presence_prob`` of ``0.5`` or a positive placement
    ``jitter_m`` still makes per-site draws when the resolved config
    is built (see :meth:`WorldGenerator.sample_world`).
    """
    return _sample_value(self, _coerce_rng(rng))

GroundingSystemSpec

Bases: GeneratorConfig

A complete grounding installation.

Attributes:

Name Type Description
electrodes list[ElectrodeSpec]

Ordered list of electrode specs. Order matters only for the choice of anchor (first present electrode) and for the electrode names. All present electrodes are bonded into one cluster.

bond_conductor_type str

Conductor type used to bond the electrodes together. Default "bare_copper" matches the typical bonding strap inside a substation pit; the bond is an ideal galvanic short either way.

build_at

build_at(world: World, site_xy: tuple[float, float], name_prefix: str, rng: Generator) -> Optional[str]

Materialise the grounding system inside world.

Equivalent to plan_site() followed by groundfield.generators.materialise.materialise_site().

Parameters:

Name Type Description Default
world World

The World to populate.

required
site_xy tuple[float, float]

Centre position (x, y) of this site (substation centre, cabinet centre, building centre, …) in m.

required
name_prefix str

Prefix of every created electrode name. The actual name is f"{name_prefix}_{kind}_{i}" with i the electrode's index in electrodes. Should be unique within the world.

required
rng Generator

Random generator used for presence_prob and every distribution field.

required

Returns:

Type Description
str | None

The name of the anchor electrode (the first present one). None if no electrode ended up being placed (every Bernoulli draw failed) — the caller may want to skip this site or raise.

Source code in src/groundfield/generators/grounding.py
def build_at(
    self,
    world: World,
    site_xy: tuple[float, float],
    name_prefix: str,
    rng: np.random.Generator,
) -> Optional[str]:
    """Materialise the grounding system inside ``world``.

    Equivalent to :meth:`plan_site` followed by
    :func:`groundfield.generators.materialise.materialise_site`.

    Parameters
    ----------
    world
        The :class:`World` to populate.
    site_xy
        Centre position ``(x, y)`` of this site (substation centre,
        cabinet centre, building centre, …) in m.
    name_prefix
        Prefix of every created electrode name. The actual name is
        ``f"{name_prefix}_{kind}_{i}"`` with ``i`` the electrode's
        index in :attr:`electrodes`. Should be unique within the
        world.
    rng
        Random generator used for ``presence_prob`` and every
        distribution field.

    Returns
    -------
    str | None
        The name of the *anchor* electrode (the first present one).
        ``None`` if no electrode ended up being placed (every
        Bernoulli draw failed) — the caller may want to skip this
        site or raise.
    """
    from groundfield.generators.materialise import materialise_site

    site = PlannedSite(
        name=name_prefix,
        role="building",
        position_xy=(site_xy[0], site_xy[1]),
        electrodes=self.resolve_electrodes(rng),
        bond_conductor_type=self.bond_conductor_type,
    )
    return materialise_site(world, site)

plan_site

plan_site(name: str, *, role: str, position_xy: tuple[float, float], rng: Generator, footprint: 'Optional[BuildingFootprint]' = None, building_type: Optional[str] = None, outline: FoundationOutline = 'spec') -> PlannedSite

Resolve the system into a PlannedSite.

Parameters:

Name Type Description Default
name str

Site name (electrode-name prefix).

required
role str required
position_xy tuple[float, float]

Site reference point (x, y) in m.

required
rng Generator

Random generator (see resolve_electrodes()).

required
footprint 'Optional[BuildingFootprint]'

Recorded on the site for information.

None
building_type 'Optional[BuildingFootprint]'

Recorded on the site for information.

None
outline FoundationOutline

"spec" (default): the foundations keep the spec geometry. "ombr" / "polygon": after the random draws, the resolved foundations are shaped after footprint (see with_footprint()). Drawing first keeps the random stream independent of the outline, so the same seed puts optional electrodes on the same sites whatever the outline (audit M2).

'spec'

Returns:

Type Description
PlannedSite

The concrete site.

Source code in src/groundfield/generators/grounding.py
def plan_site(
    self,
    name: str,
    *,
    role: str,
    position_xy: tuple[float, float],
    rng: np.random.Generator,
    footprint: "Optional[BuildingFootprint]" = None,
    building_type: Optional[str] = None,
    outline: FoundationOutline = "spec",
) -> PlannedSite:
    """Resolve the system into a :class:`~groundfield.generators.plan.PlannedSite`.

    Parameters
    ----------
    name
        Site name (electrode-name prefix).
    role
        Site role, see :data:`groundfield.generators.plan.SiteRole`.
    position_xy
        Site reference point ``(x, y)`` in m.
    rng
        Random generator (see :meth:`resolve_electrodes`).
    footprint, building_type
        Recorded on the site for information.
    outline
        ``"spec"`` (default): the foundations keep the spec geometry.
        ``"ombr"`` / ``"polygon"``: after the random draws, the
        resolved foundations are shaped after ``footprint`` (see
        :meth:`with_footprint`). Drawing first keeps the random
        stream independent of the outline, so the same seed puts
        optional electrodes on the same sites whatever the outline
        (audit M2).

    Returns
    -------
    PlannedSite
        The concrete site.
    """
    electrodes = self.resolve_electrodes(rng)
    if footprint is not None and outline != "spec" and electrodes:
        shaped = GroundingSystemSpec(
            electrodes=[planned.spec for planned in electrodes],
            bond_conductor_type=self.bond_conductor_type,
        ).with_footprint(footprint, site_xy=position_xy, outline=outline)
        electrodes = [
            PlannedElectrode(index=planned.index, spec=spec)
            for planned, spec in zip(electrodes, shaped.electrodes, strict=True)
        ]
    return PlannedSite(
        name=name,
        role=role,  # type: ignore[arg-type]
        position_xy=(float(position_xy[0]), float(position_xy[1])),
        electrodes=electrodes,
        bond_conductor_type=self.bond_conductor_type,
        footprint=footprint,
        building_type=building_type,
    )

resolve_electrodes

resolve_electrodes(rng: Generator) -> list[PlannedElectrode]

Make every random decision of this grounding system.

For each electrode in list order: one draw for a distributed presence_prob, one Bernoulli draw when the probability is below one, and — for a present electrode — one draw per distribution field (see _resolve_spec() for the order).

Parameters:

Name Type Description Default
rng Generator

Random generator.

required

Returns:

Type Description
list of PlannedElectrode

The present electrodes with concrete values, each tagged with its index in electrodes.

Source code in src/groundfield/generators/grounding.py
def resolve_electrodes(self, rng: np.random.Generator) -> list[PlannedElectrode]:
    """Make every random decision of this grounding system.

    For each electrode in list order: one draw for a distributed
    ``presence_prob``, one Bernoulli draw when the probability is
    below one, and — for a present electrode — one draw per
    distribution field (see :func:`_resolve_spec` for the order).

    Parameters
    ----------
    rng
        Random generator.

    Returns
    -------
    list of PlannedElectrode
        The present electrodes with concrete values, each tagged with
        its index in :attr:`electrodes`.
    """
    out: list[PlannedElectrode] = []
    for i, spec in enumerate(self.electrodes):
        p = _to_float(spec.presence_prob, rng)
        if p < 1.0 and rng.random() >= p:
            continue
        out.append(PlannedElectrode(index=i, spec=_resolve_spec(spec, rng)))
    return out

with_footprint

with_footprint(footprint: 'BuildingFootprint', *, site_xy: Optional[tuple[float, float]] = None, outline: FoundationOutline = 'ombr') -> 'GroundingSystemSpec'

Return a copy whose foundation electrodes follow footprint.

Parameters:

Name Type Description Default
footprint 'BuildingFootprint'

Building outline in the world's local frame (m).

required
site_xy Optional[tuple[float, float]]

Site position the spec will be built at, i.e. the origin of every offset_xy_m. None uses the polygon centroid.

None
outline FoundationOutline

"ombr" (default): every FoundationElectrodeSpec takes the size \((d_x, d_y)\), orientation \(\varphi\) and centre \((c_x, c_y)\) of the outline's oriented minimum bounding rectangle; the centre enters as an extra offset \((c_x, c_y) - \text{site}\) on top of the spec's own offset_xy_m. A side shorter than MIN_FOUNDATION_SIDE_M is widened to it (with a UserWarning). "polygon": every foundation follows the outline itself (polygon_xy_m = exterior ring relative to site_xy); only defined for style="ring". An outline whose OMBR is narrower than MIN_FOUNDATION_SIDE_M is replaced by that OMBR widened to it, as a four-cornered outline (with a UserWarning, as for "ombr"); a polygon foundation along it would run along both faces of a wall, and an outline narrower than MIN_POLYGON_EDGE_M could not be built at all. "spec": return self unchanged.

'ombr'

Returns:

Type Description
GroundingSystemSpec

A new spec (self when nothing changes). Presence probabilities, depths, styles, mesh counts, wire radii and concrete parameters are kept.

Raises:

Type Description
ValueError

For outline="polygon" with a style="mesh" foundation (cross-braces are undefined on a general polygon) or an unknown outline.

ImportError

outline="ombr", and outline="polygon" for an outline narrower than MIN_FOUNDATION_SIDE_M on average, need shapely (geo extra).

Source code in src/groundfield/generators/grounding.py
def with_footprint(
    self,
    footprint: "BuildingFootprint",
    *,
    site_xy: Optional[tuple[float, float]] = None,
    outline: FoundationOutline = "ombr",
) -> "GroundingSystemSpec":
    r"""Return a copy whose foundation electrodes follow ``footprint``.

    Parameters
    ----------
    footprint
        Building outline in the world's local frame (m).
    site_xy
        Site position the spec will be built at, i.e. the origin of
        every ``offset_xy_m``. ``None`` uses the polygon centroid.
    outline
        ``"ombr"`` (default): every
        :class:`~groundfield.generators.electrode_specs.FoundationElectrodeSpec`
        takes the size :math:`(d_x, d_y)`, orientation
        :math:`\varphi` and centre :math:`(c_x, c_y)` of the
        outline's oriented minimum bounding rectangle; the centre
        enters as an extra offset :math:`(c_x, c_y) - \text{site}`
        on top of the spec's own ``offset_xy_m``. A side shorter than
        :data:`MIN_FOUNDATION_SIDE_M` is widened to it (with a
        :class:`UserWarning`). ``"polygon"``: every
        foundation follows the outline itself (``polygon_xy_m`` =
        exterior ring relative to ``site_xy``); only defined for
        ``style="ring"``. An outline whose OMBR is narrower than
        :data:`MIN_FOUNDATION_SIDE_M` is replaced by that OMBR widened
        to it, as a four-cornered outline (with a :class:`UserWarning`,
        as for ``"ombr"``); a polygon foundation along it would run
        along both faces of a wall, and an outline narrower than
        :data:`~groundfield.generators.materialise.MIN_POLYGON_EDGE_M`
        could not be built at all. ``"spec"``: return ``self``
        unchanged.

    Returns
    -------
    GroundingSystemSpec
        A new spec (``self`` when nothing changes). Presence
        probabilities, depths, styles, mesh counts, wire radii and
        concrete parameters are kept.

    Raises
    ------
    ValueError
        For ``outline="polygon"`` with a ``style="mesh"`` foundation
        (cross-braces are undefined on a general polygon) or an
        unknown ``outline``.
    ImportError
        ``outline="ombr"``, and ``outline="polygon"`` for an outline
        narrower than :data:`MIN_FOUNDATION_SIDE_M` on average, need
        :mod:`shapely` (``geo`` extra).
    """
    if outline not in ("spec", "ombr", "polygon"):
        raise ValueError(
            f"outline must be 'spec', 'ombr' or 'polygon', got {outline!r}."
        )
    if outline == "spec" or not any(
        isinstance(spec, FoundationElectrodeSpec) for spec in self.electrodes
    ):
        # Nothing to shape (no foundation): no OMBR, no warning.
        return self
    if site_xy is None:
        site_xy = footprint.centroid_xy_m()
    ring = [(float(x), float(y)) for x, y in footprint.polygon_xy_m]
    if outline == "ombr":
        (cx, cy), (dx, dy), orientation_deg = _widened_ombr(footprint)
        # Recentre on the OMBR centre (F25): the electrode sits at
        # ``site_xy + offset_xy_m``.
        recentre = (cx - site_xy[0], cy - site_xy[1])
    elif footprint.mean_width_m() < MIN_FOUNDATION_SIDE_M:
        # Only thin outlines can have an OMBR side below the minimum
        # (the mean width of a rectangle is below its short side), so
        # ordinary buildings need no shapely here.
        (cx, cy), (dx, dy), orientation_deg = (
            footprint.oriented_bounding_rectangle()
        )
        if min(dx, dy) < MIN_FOUNDATION_SIDE_M:
            ring = _rectangle_ring(*_widened_ombr(footprint))
    rewritten: list[ElectrodeSpec] = []
    changed = False
    for spec in self.electrodes:
        if not isinstance(spec, FoundationElectrodeSpec):
            rewritten.append(spec)
            continue
        if outline == "ombr":
            update: dict[str, object] = {
                "size_xy_m": (dx, dy),
                "orientation_deg": orientation_deg,
                "offset_xy_m": (
                    spec.offset_xy_m[0] + recentre[0],
                    spec.offset_xy_m[1] + recentre[1],
                ),
            }
        else:
            if spec.style != "ring":
                raise ValueError(
                    "outline='polygon' needs style='ring' foundations — the "
                    "cross-braces of style='mesh' are undefined on a general "
                    "polygon. Use outline='ombr' or a ring-style spec."
                )
            sx, sy = site_xy
            update = {"polygon_xy_m": tuple((x - sx, y - sy) for x, y in ring)}
        rewritten.append(spec.model_copy(update=update))
        changed = True
    if not changed:
        return self
    return self.model_copy(update={"electrodes": rewritten})

HomogeneousSoilSpec

Bases: PickleUpgrade, BaseModel

Homogeneous soil with a single resistivity \(\rho\).

Use as a sanity check (every layered backend collapses to this when \(K = 0\)) or for very simple studies.

resistivity property

resistivity: Union[float, Distribution]

Deprecated alias of rho.

to_soil

to_soil(rng: Generator) -> HomogeneousSoil

Draw the distributions and return the soil model.

A non-default relative_permittivity warns with InertConfigurationWarning (no backend reads it).

Source code in src/groundfield/generators/soil_specs.py
def to_soil(self, rng: np.random.Generator) -> HomogeneousSoil:
    """Draw the distributions and return the soil model.

    A non-default ``relative_permittivity`` warns with
    :class:`~groundfield.utils.InertConfigurationWarning` (no backend
    reads it).
    """
    _warn_inert_permittivity(type(self).__name__, [self.relative_permittivity])
    return _homogeneous_soil(
        _to_float(self.rho, rng), relative_permittivity=self.relative_permittivity
    )

KvsConfig

Bases: CabinetConfig

Deprecated alias of CabinetConfig.

KvsPlacement

Bases: CabinetPlacement

Deprecated alias of CabinetPlacement.

LateralCoverageResult

Bases: NamedTuple

Outcome of LvNetworkLayout.connect_all_buildings().

Attributes:

Name Type Description
laterals list[str]

Names of the PEN lateral cables that were added to reach otherwise-unconnected houses, in the order they were created.

islands list[int]

Indices of footprints that still could not be connected -- houses enclosed by other footprints on every side, for which no obstacle-free service stub exists even after adding a lateral. An empty list means full coverage.

connections list['BuildingConnection']

Snapshot of LvNetworkLayout.connections after the pass (the tap from every connected house to its serving cable).

LogNormal

Bases: Distribution

Log-normal distribution.

The default parameterisation matches NumPy's: mu and sigma are the mean and standard deviation of the underlying normal \(Y \sim \mathcal{N}(\mu, \sigma^2)\), and the log-normal sample is \(X = e^{Y}\).

Use from_moments() to construct an instance from the physical mean and standard deviation of \(X\) instead.

from_moments classmethod

from_moments(mean: float, std: float) -> 'LogNormal'

Build a LogNormal from the physical mean and std.

Solves \(\mu = \ln(\text{mean}^2/\sqrt{\text{std}^2 + \text{mean}^2})\) and \(\sigma^2 = \ln(1 + \text{std}^2/\text{mean}^2)\).

Parameters:

Name Type Description Default
mean float

Target physical mean \(\mathbb{E}[X] > 0\).

required
std float

Target physical standard deviation \(\sqrt{\mathrm{Var}(X)} > 0\).

required
Source code in src/groundfield/generators/distributions.py
@classmethod
def from_moments(cls, mean: float, std: float) -> "LogNormal":
    """Build a :class:`LogNormal` from the physical mean and std.

    Solves $\\mu = \\ln(\\text{mean}^2/\\sqrt{\\text{std}^2 + \\text{mean}^2})$
    and $\\sigma^2 = \\ln(1 + \\text{std}^2/\\text{mean}^2)$.

    Parameters
    ----------
    mean
        Target physical mean $\\mathbb{E}[X] > 0$.
    std
        Target physical standard deviation $\\sqrt{\\mathrm{Var}(X)} > 0$.
    """
    if mean <= 0.0:
        raise ValueError(f"LogNormal.from_moments: mean must be > 0 (got {mean}).")
    if std <= 0.0:
        raise ValueError(f"LogNormal.from_moments: std must be > 0 (got {std}).")
    var = std * std
    sigma_sq = math.log(1.0 + var / (mean * mean))
    mu = math.log(mean) - 0.5 * sigma_sq
    return cls(mu=mu, sigma=math.sqrt(sigma_sq))

sample

sample(rng: Generator) -> float

Draw one sample \(X = e^{Y}\) with \(Y \sim \mathcal{N}(\mu, \sigma^2)\).

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
float

One log-normal draw (positive).

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Draw one sample $X = e^{Y}$ with $Y \\sim \\mathcal{N}(\\mu, \\sigma^2)$.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    float
        One log-normal draw (positive).
    """
    return float(rng.lognormal(self.mu, self.sigma))

LvNetworkLayout

Bases: _RoutingMixin, _MeasurementMixin, _PenetrationMixin, _PlotMixin, PickleUpgrade, BaseModel

Imperative LV network layout builder.

The builder is constructed empty (no buildings, no substation, no cables) and filled up by calling its methods in the order a planner would naturally take. Every state-changing method returns the new object (or its key) so the calls can be chained or stored:

layout = LvNetworkLayout.from_footprints(footprints, ... substation_xy=(0, 0)) cabinet_1 = layout.add_cabinet((120, 0)) cable = layout.add_pen_cable(start="substation", ... end_xy=(250, 0)) layout.connect_buildings() ax = layout.plot()

Attributes:

Name Type Description
footprints list[BuildingFootprint]

Building footprints (already projected into the local ENU frame). Their axis-aligned bounding rectangles serve both as house positions and as PEN-routing obstacles.

substation_xy tuple[float, float]

Substation centre in metres.

substation_name str

Substation anchor id used everywhere else (default "substation").

cabinet_placements list[CabinetPlacement]

Optional pre-populated cabinet list. Most callers leave this empty and use add_cabinet().

pen_cables list[PenCable]

Optional pre-populated PEN cables. Most callers leave this empty and use add_pen_cable() / add_pen_trunk().

connections list[BuildingConnection]

Optional pre-populated building connections. Most callers leave this empty and use connect_buildings().

obstacle_clearance_m float

Inflation applied to every footprint AABB before routing. Defaults to 1 m so cables keep a small visible distance from the foundation walls.

kvs_placements property

kvs_placements: list[CabinetPlacement]

Deprecated alias of cabinet_placements.

projector property

projector: Optional[Projector]

Lazy Projector for the layout's ENU frame.

Returns None when frame_origin_lat_lon is not set (the layout is in an anonymous local frame). The projector is reconstructed on every access; pyproj caches the underlying CRS objects so this stays cheap.

add_cabinet

add_cabinet(position_xy: Optional[tuple[float, float]] = None, *, position_lat_lon: Optional[tuple[float, float]] = None, name: Optional[str] = None) -> str

Place a cable cabinet at position_xy or position_lat_lon.

Exactly one of position_xy (local ENU metres) or position_lat_lon (WGS84 degrees) must be set. The lat / lon variant projects through the layout's frame_origin_lat_lon; if no frame origin is set, a RuntimeError is raised.

Returns the assigned cabinet name (auto-generated when name is None). The returned name is what callers pass to add_pen_cable() as start=....

Source code in src/groundfield/generators/layout/model.py
def add_cabinet(
    self,
    position_xy: Optional[tuple[float, float]] = None,
    *,
    position_lat_lon: Optional[tuple[float, float]] = None,
    name: Optional[str] = None,
) -> str:
    """Place a cable cabinet at ``position_xy`` or ``position_lat_lon``.

    Exactly one of ``position_xy`` (local ENU metres) or
    ``position_lat_lon`` (WGS84 degrees) must be set. The lat /
    lon variant projects through the layout's
    :attr:`frame_origin_lat_lon`; if no frame origin is set, a
    :class:`RuntimeError` is raised.

    Returns the assigned cabinet name (auto-generated when ``name``
    is ``None``). The returned name is what callers pass to
    :meth:`add_pen_cable` as ``start=...``.
    """
    if (position_xy is None) == (position_lat_lon is None):
        raise ValueError(
            "LvNetworkLayout.add_cabinet: exactly one of "
            "``position_xy`` and ``position_lat_lon`` must be set."
        )
    if position_lat_lon is not None:
        position_xy = self.lat_lon_to_xy(*position_lat_lon)
    if name is None:
        name = f"kvs_{len(self.cabinet_placements)}"
    if any(k.name == name for k in self.cabinet_placements):
        raise ValueError(
            f"LvNetworkLayout.add_cabinet: name {name!r} is already taken."
        )
    if name == self.substation_name:
        raise ValueError(
            f"LvNetworkLayout.add_cabinet: name {name!r} clashes with "
            "the substation name."
        )
    assert position_xy is not None
    self.cabinet_placements.append(
        CabinetPlacement(name=name, position_xy=tuple(position_xy)),
    )
    return name

add_kvs

add_kvs(position_xy: Optional[tuple[float, float]] = None, *, position_lat_lon: Optional[tuple[float, float]] = None, name: Optional[str] = None) -> str

Deprecated alias of add_cabinet().

Source code in src/groundfield/generators/layout/model.py
def add_kvs(
    self,
    position_xy: Optional[tuple[float, float]] = None,
    *,
    position_lat_lon: Optional[tuple[float, float]] = None,
    name: Optional[str] = None,
) -> str:
    """Deprecated alias of :meth:`add_cabinet`."""
    warn_renamed("LvNetworkLayout.add_kvs", "LvNetworkLayout.add_cabinet")
    return self.add_cabinet(
        position_xy, position_lat_lon=position_lat_lon, name=name
    )

from_footprints classmethod

from_footprints(footprints: list[BuildingFootprint], *, substation_xy: tuple[float, float], substation_name: str = 'substation', obstacle_clearance_m: float = 1.0, frame_origin_lat_lon: Optional[tuple[float, float]] = None) -> 'LvNetworkLayout'

Build an empty layout from a list of footprints.

frame_origin_lat_lon is optional; pass it when the footprints were projected by an external pipeline and you still want to add cabinets / PEN endpoints by lat / lon later.

Source code in src/groundfield/generators/layout/model.py
@classmethod
def from_footprints(
    cls,
    footprints: list[BuildingFootprint],
    *,
    substation_xy: tuple[float, float],
    substation_name: str = "substation",
    obstacle_clearance_m: float = 1.0,
    frame_origin_lat_lon: Optional[tuple[float, float]] = None,
) -> "LvNetworkLayout":
    """Build an empty layout from a list of footprints.

    ``frame_origin_lat_lon`` is optional; pass it when the
    footprints were projected by an external pipeline and you
    still want to add cabinets / PEN endpoints by lat / lon later.
    """
    return cls(
        footprints=list(footprints),
        substation_xy=substation_xy,
        substation_name=substation_name,
        obstacle_clearance_m=obstacle_clearance_m,
        frame_origin_lat_lon=frame_origin_lat_lon,
    )

from_osm classmethod

from_osm(*, center_lat_deg: float, center_lon_deg: float, radius_m: float, substation_lat_lon: Optional[tuple[float, float]] = None, substation_xy: Optional[tuple[float, float]] = None, cabinet_lat_lons: Optional[list[tuple[float, float]]] = None, cabinet_xys: Optional[list[tuple[float, float]]] = None, substation_name: str = 'substation', obstacle_clearance_m: float = 1.0, min_area_m2: float = 16.0, cache_dir=None, force_refresh: bool = False, endpoint: Optional[str] = None, timeout_s: Optional[int] = None, max_retries: int = 1, exclude_building_tags: Optional[Collection[str]] = None, **deprecated: object) -> 'LvNetworkLayout'

One-shot constructor: query OSM and pre-place anchors.

Parameters:

Name Type Description Default
center_lat_deg float

Centre of the buildings-in-radius Overpass query. Also the WGS84 origin of the local ENU frame frame_origin_lat_lon so subsequent position_lat_lon arguments stay consistent.

required
center_lon_deg float

Centre of the buildings-in-radius Overpass query. Also the WGS84 origin of the local ENU frame frame_origin_lat_lon so subsequent position_lat_lon arguments stay consistent.

required
radius_m float

Search radius in metres.

required
substation_lat_lon Optional[tuple[float, float]]

Optional substation location as WGS84 (lat, lon). Mutually exclusive with substation_xy. When both are omitted the substation defaults to the local origin (0, 0).

None
substation_xy Optional[tuple[float, float]]

Substation location in already-projected metres. Mutually exclusive with substation_lat_lon.

None
cabinet_lat_lons Optional[list[tuple[float, float]]]

Optional list of cabinet locations in WGS84 (lat, lon). Each entry is projected and appended to cabinet_placements. Names are auto-generated.

None
cabinet_xys Optional[list[tuple[float, float]]]

Optional list of cabinet locations in already-projected metres. Mutually exclusive with cabinet_lat_lons.

None
substation_name str

Anchor id for the substation. Default "substation".

'substation'
obstacle_clearance_m float

Forwarded to the layout / OSM query respectively.

1.0
min_area_m2 float

Forwarded to the layout / OSM query respectively.

1.0
cache_dir None
force_refresh None
endpoint None
timeout_s None
max_retries None
exclude_building_tags Optional[Collection[str]]

building=* values to drop, e.g. groundfield.geo.osm.NON_SERVICE_BUILDING_TAGS (garages, sheds, carports, ...). None (default) keeps every element with a building tag.

None

Returns:

Type Description
LvNetworkLayout

Layout with footprints loaded, projector seeded, and substation / cabinets pre-placed. Routing and connections are still up to the caller.

Examples:

Build the layout for Mulmke (Heudeber / Nordharz) in a 300 m radius around the village centre, with the substation at a chosen lat / lon and two cabinets along the main road:

>>> layout = LvNetworkLayout.from_osm(
...     center_lat_deg=51.9136, center_lon_deg=10.8432,
...     radius_m=300.0,
...     substation_lat_lon=(51.9138, 10.8418),
...     cabinet_lat_lons=[
...         (51.9133, 10.8445),
...         (51.9140, 10.8460),
...     ],
... )
Source code in src/groundfield/generators/layout/model.py
@classmethod
def from_osm(
    cls,
    *,
    center_lat_deg: float,
    center_lon_deg: float,
    radius_m: float,
    substation_lat_lon: Optional[tuple[float, float]] = None,
    substation_xy: Optional[tuple[float, float]] = None,
    cabinet_lat_lons: Optional[list[tuple[float, float]]] = None,
    cabinet_xys: Optional[list[tuple[float, float]]] = None,
    substation_name: str = "substation",
    obstacle_clearance_m: float = 1.0,
    min_area_m2: float = 16.0,
    cache_dir=None,
    force_refresh: bool = False,
    endpoint: Optional[str] = None,
    timeout_s: Optional[int] = None,
    max_retries: int = 1,
    exclude_building_tags: Optional[Collection[str]] = None,
    **deprecated: object,
) -> "LvNetworkLayout":
    """One-shot constructor: query OSM and pre-place anchors.

    Parameters
    ----------
    center_lat_deg, center_lon_deg
        Centre of the buildings-in-radius Overpass query. Also
        the WGS84 origin of the local ENU frame
        :attr:`frame_origin_lat_lon` so subsequent
        ``position_lat_lon`` arguments stay consistent.
    radius_m
        Search radius in metres.
    substation_lat_lon
        Optional substation location as WGS84 ``(lat, lon)``.
        Mutually exclusive with ``substation_xy``. When both
        are omitted the substation defaults to the local
        origin ``(0, 0)``.
    substation_xy
        Substation location in already-projected metres.
        Mutually exclusive with ``substation_lat_lon``.
    cabinet_lat_lons
        Optional list of cabinet locations in WGS84 ``(lat, lon)``.
        Each entry is projected and appended to
        :attr:`cabinet_placements`. Names are auto-generated.
    cabinet_xys
        Optional list of cabinet locations in already-projected
        metres. Mutually exclusive with ``cabinet_lat_lons``.
    substation_name
        Anchor id for the substation. Default ``"substation"``.
    obstacle_clearance_m, min_area_m2
        Forwarded to the layout / OSM query respectively.
    cache_dir, force_refresh, endpoint, timeout_s, max_retries
        Forwarded to :func:`groundfield.geo.osm.query_and_project`.
    exclude_building_tags
        ``building=*`` values to drop, e.g.
        :data:`groundfield.geo.osm.NON_SERVICE_BUILDING_TAGS`
        (garages, sheds, carports, ...). ``None`` (default) keeps
        every element with a ``building`` tag.

    Returns
    -------
    LvNetworkLayout
        Layout with footprints loaded, projector seeded, and
        substation / cabinets pre-placed. Routing and connections
        are still up to the caller.

    Examples
    --------
    Build the layout for Mulmke (Heudeber / Nordharz) in a
    300 m radius around the village centre, with the
    substation at a chosen lat / lon and two cabinets along the
    main road:

    >>> layout = LvNetworkLayout.from_osm(
    ...     center_lat_deg=51.9136, center_lon_deg=10.8432,
    ...     radius_m=300.0,
    ...     substation_lat_lon=(51.9138, 10.8418),
    ...     cabinet_lat_lons=[
    ...         (51.9133, 10.8445),
    ...         (51.9140, 10.8460),
    ...     ],
    ... )
    """
    from groundfield.geo.osm import query_and_project

    renamed = take_renamed_kwargs(
        "LvNetworkLayout.from_osm",
        deprecated,
        {"kvs_lat_lons": "cabinet_lat_lons", "kvs_xys": "cabinet_xys"},
    )
    cabinet_lat_lons = renamed.get("cabinet_lat_lons", cabinet_lat_lons)  # type: ignore[assignment]
    cabinet_xys = renamed.get("cabinet_xys", cabinet_xys)  # type: ignore[assignment]
    if substation_lat_lon is not None and substation_xy is not None:
        raise ValueError(
            "LvNetworkLayout.from_osm: substation_lat_lon and "
            "substation_xy are mutually exclusive."
        )
    if cabinet_lat_lons is not None and cabinet_xys is not None:
        raise ValueError(
            "LvNetworkLayout.from_osm: cabinet_lat_lons and cabinet_xys "
            "are mutually exclusive."
        )

    query_kwargs: dict = {
        "min_area_m2": min_area_m2,
        "force_refresh": force_refresh,
        "max_retries": max_retries,
    }
    if exclude_building_tags is not None:
        query_kwargs["exclude_building_tags"] = exclude_building_tags
    if cache_dir is not None:
        query_kwargs["cache_dir"] = cache_dir
    if endpoint is not None:
        query_kwargs["endpoint"] = endpoint
    if timeout_s is not None:
        query_kwargs["timeout_s"] = timeout_s

    footprints, projector = query_and_project(
        lat0_deg=center_lat_deg,
        lon0_deg=center_lon_deg,
        radius_m=radius_m,
        **query_kwargs,
    )

    if substation_lat_lon is not None:
        sub_xy = projector.to_xy_m(*substation_lat_lon)
    elif substation_xy is not None:
        sub_xy = tuple(substation_xy)
    else:
        sub_xy = (0.0, 0.0)

    layout = cls(
        footprints=footprints,
        substation_xy=sub_xy,
        substation_name=substation_name,
        obstacle_clearance_m=obstacle_clearance_m,
        frame_origin_lat_lon=(center_lat_deg, center_lon_deg),
    )

    if cabinet_lat_lons:
        for lat, lon in cabinet_lat_lons:
            layout.add_cabinet(position_lat_lon=(lat, lon))
    elif cabinet_xys:
        for xy in cabinet_xys:
            layout.add_cabinet(position_xy=xy)

    return layout

lat_lon_to_xy

lat_lon_to_xy(lat_deg: float, lon_deg: float) -> tuple[float, float]

Project a WGS84 (lat, lon) to the layout's local frame.

Raises RuntimeError when no frame_origin_lat_lon has been set (i.e. the layout was not built via from_osm()).

Source code in src/groundfield/generators/layout/model.py
def lat_lon_to_xy(
    self,
    lat_deg: float,
    lon_deg: float,
) -> tuple[float, float]:
    """Project a WGS84 ``(lat, lon)`` to the layout's local frame.

    Raises :class:`RuntimeError` when no
    :attr:`frame_origin_lat_lon` has been set (i.e. the layout
    was not built via :meth:`from_osm`).
    """
    projector = self.projector
    if projector is None:
        raise RuntimeError(
            "LvNetworkLayout.lat_lon_to_xy: layout has no "
            "frame_origin_lat_lon. Build via ``from_osm`` or "
            "pass ``frame_origin_lat_lon`` to ``from_footprints`` "
            "to enable lat / lon based placement."
        )
    return projector.to_xy_m(lat_deg, lon_deg)

plan

plan(*, name: str = 'ortsnetz_layout', soil: Optional[SoilModel] = None, substation_grounding: Optional[GroundingSystemSpec] = None, cabinet_grounding: Optional[GroundingSystemSpec] = None, house_grounding: Optional[GroundingSystemSpec] = None, pen_wire_radius_m: float = 0.005, pen_segment_length_m: Optional[float] = 5.0, include_source: bool = True, source_magnitude_a: float = 1.0, seed: int = 0, foundation_mask: Optional[list[bool]] = None, foundation_outline: FoundationOutline = 'ombr', **deprecated: object) -> NetworkPlan

Resolve the layout into a NetworkPlan.

Parameters are those of to_world(). Random draws (presence probabilities and distributions in the grounding specs) use numpy.random.default_rng(seed) in the order substation, cabinets, houses, auxiliary electrode. Each house's foundation electrodes are shaped after its footprint once its draws are made (see foundation_outline in to_world()), so the outline does not change which optional electrodes a seed produces.

Returns:

Type Description
NetworkPlan

The concrete network. Every PEN cable becomes a chain of branches between junctions at its corners and tap points; cable ends at the substation or a cabinet attach to that site.

Raises:

Type Description
ValueError

If foundation_mask has the wrong length.

RuntimeError

If the substation, a cabinet or the auxiliary electrode grounding produces zero electrodes.

Source code in src/groundfield/generators/layout/model.py
def plan(
    self,
    *,
    name: str = "ortsnetz_layout",
    soil: Optional[SoilModel] = None,
    substation_grounding: Optional[GroundingSystemSpec] = None,
    cabinet_grounding: Optional[GroundingSystemSpec] = None,
    house_grounding: Optional[GroundingSystemSpec] = None,
    pen_wire_radius_m: float = 0.005,
    pen_segment_length_m: Optional[float] = 5.0,
    include_source: bool = True,
    source_magnitude_a: float = 1.0,
    seed: int = 0,
    foundation_mask: Optional[list[bool]] = None,
    foundation_outline: FoundationOutline = "ombr",
    **deprecated: object,
) -> NetworkPlan:
    """Resolve the layout into a :class:`~groundfield.generators.plan.NetworkPlan`.

    Parameters are those of :meth:`to_world`. Random draws (presence
    probabilities and distributions in the grounding specs) use
    ``numpy.random.default_rng(seed)`` in the order substation,
    cabinets, houses, auxiliary electrode. Each house's foundation
    electrodes are shaped after its footprint once its draws are made
    (see ``foundation_outline`` in :meth:`to_world`), so the outline
    does not change which optional electrodes a seed produces.

    Returns
    -------
    NetworkPlan
        The concrete network. Every PEN cable becomes a chain of
        branches between junctions at its corners and tap points;
        cable ends at the substation or a cabinet attach to that
        site.

    Raises
    ------
    ValueError
        If ``foundation_mask`` has the wrong length.
    RuntimeError
        If the substation, a cabinet or the auxiliary electrode
        grounding produces zero electrodes.
    """
    renamed = take_renamed_kwargs(
        "LvNetworkLayout.plan",
        deprecated,
        {
            "kvs_grounding": "cabinet_grounding",
            "source_magnitude_A": "source_magnitude_a",
        },
    )
    cabinet_grounding = renamed.get("cabinet_grounding", cabinet_grounding)  # type: ignore[assignment]
    source_magnitude_a = renamed.get("source_magnitude_a", source_magnitude_a)  # type: ignore[assignment]
    if foundation_mask is not None and len(foundation_mask) != len(
        self.footprints,
    ):
        raise ValueError(
            "LvNetworkLayout.to_world: foundation_mask length "
            f"{len(foundation_mask)} does not match footprints "
            f"count {len(self.footprints)}."
        )
    rng = np.random.default_rng(seed)

    # 1. Substation grounding.
    substation_spec = substation_grounding or _default_substation_grounding()
    substation = substation_spec.plan_site(
        self.substation_name,
        role="substation",
        position_xy=self.substation_xy,
        rng=rng,
    )
    if substation.anchor is None:
        raise RuntimeError(
            "LvNetworkLayout.to_world: substation grounding "
            "produced zero electrodes."
        )
    sites: list[PlannedSite] = [substation]

    # 2. Cable-cabinet groundings.
    cabinet_spec = cabinet_grounding or _default_cabinet_grounding()
    for k in self.cabinet_placements:
        cabinet = cabinet_spec.plan_site(
            k.name, role="cabinet", position_xy=k.position_xy, rng=rng
        )
        if cabinet.anchor is None:
            raise RuntimeError(
                "LvNetworkLayout.to_world: cabinet "
                f"{k.name!r} grounding produced zero electrodes."
            )
        sites.append(cabinet)

    # 3. House groundings, shaped after the footprint
    #    (``GroundingSystemSpec.with_footprint``). Houses outside
    #    ``foundation_mask`` stay in the layout (plots) but not in the
    #    network.
    house_spec = house_grounding or _default_house_grounding()
    houses: dict[int, PlannedSite] = {}
    for i, fp in enumerate(self.footprints):
        if foundation_mask is not None and not foundation_mask[i]:
            continue
        centroid = fp.centroid_xy_m()
        house = house_spec.plan_site(
            f"house_{i:03d}",
            role="building",
            position_xy=centroid,
            rng=rng,
            footprint=fp,
            outline=foundation_outline,
        )
        sites.append(house)
        houses[i] = house

    # 4. Auxiliary current electrode, if configured.
    measurement: Optional[PlannedMeasurement] = None
    if self.auxiliary_electrode is not None:
        aux = self.auxiliary_electrode
        aux_site = aux.grounding.plan_site(
            aux.name, role="auxiliary", position_xy=aux.position_xy, rng=rng
        )
        if aux_site.anchor is None:
            raise RuntimeError(
                "LvNetworkLayout.to_world: auxiliary electrode "
                "grounding produced zero electrodes "
                f"({aux.name!r}). Increase presence_prob."
            )
        measurement = PlannedMeasurement(auxiliary=aux_site)

    # 5. PEN cables: a junction at every interior corner and tap
    #    point, one branch between consecutive nodes. Nodes closer
    #    than the shortest cable section are merged (a tap a few
    #    millimetres from a corner or from another tap left a section
    #    the Conductor model refuses, audit A3SG-01). A cable or drop
    #    ends at the point of a site's horizontal electrodes nearest to
    #    it (user decisions Q41, Q43): a house with a foundation, ring
    #    or strip is tapped at the closest pair between its cable and
    #    their wires. Corners inside a site's foundation are part of the
    #    site (audit R6A-01), and a cable that passes through the
    #    foundation of the substation or a cabinet is joined to it there
    #    (audits W1B-03, W1B-04).
    conductor = ConductorParameters(
        conductor_type="pen",
        wire_radius_m=pen_wire_radius_m,
        cross_section="from_radius",
        coupling_to_soil="isolated",
        segment_length_m=pen_segment_length_m,
    )
    min_length = min_section_length(conductor)
    geometry = {site.name: _site_geometry(site) for site in sites}
    anchor_points = {
        site.name: geometry[site.name][0]
        for site in sites
        if site.role in ("substation", "cabinet")
    }
    wires = {name: g.wires for name, g in geometry.items() if g.wires}
    outlines = {name: g.outlines for name, g in geometry.items() if g.outlines}
    meet = _Meeting({name: g.point for name, g in geometry.items()}, wires)
    built = {
        cable.name: self._built_segments(
            cable, wires, outlines, passing=list(anchor_points)
        )
        for cable in self.pen_cables
    }
    taps = self._service_taps(houses, wires, min_length, built)
    junctions: list[PlannedJunction] = []
    branches: list[PlannedBranch] = []
    cable_nodes: dict[str, list[tuple[str, tuple[float, float]]]] = {}
    for cable in self.pen_cables:
        nodes = self._merge_close_nodes(
            cable.name,
            self._cable_nodes(
                cable,
                junctions,
                taps,
                built[cable.name].merged,
                built[cable.name].passages,
            ),
            junctions,
            anchor_points,
            min_length,
            meet,
        )
        cable_nodes[cable.name] = nodes
        meet.junctions(junctions)
        for j, ((a0, p0), (a1, p1)) in enumerate(
            zip(nodes[:-1], nodes[1:], strict=True)
        ):
            if a0 == a1:
                continue
            c0, c1 = meet.contacts(a0, p0, a1, p1)
            branches.append(
                PlannedBranch(
                    name=f"{cable.name}_seg_{j}",
                    role="pen",
                    start=a0,
                    end=a1,
                    conductor=conductor,
                    cable=cable.name,
                    start_contact=c0,
                    end_contact=c1,
                )
            )

    # 6. Service drops: tap node on the cable -> house (its foundation
    #    point nearest to the tap node, user decision Q41).
    for c in self.connections:
        house = houses.get(c.house_idx)
        if house is None or house.anchor is None:
            continue
        tap = self._tap_anchor_for(c, cable_nodes, taps.get(c.house_idx))
        if tap is None:
            continue
        tap_xy = dict(cable_nodes[c.cable_name])[tap]
        # A tap at the substation or a cabinet with a foundation leaves
        # it at its point nearest to the house (two foundations: their
        # closest pair).
        start_contact, end_contact = meet.contacts(tap, tap_xy, house.name, None)
        branches.append(
            PlannedBranch(
                name=f"service_{c.house_idx:03d}",
                role="service_drop",
                start=tap,
                end=house.name,
                conductor=conductor,
                cable=c.cable_name,
                start_contact=start_contact,
                end_contact=end_contact,
            )
        )

    # 7. Sources. With an auxiliary electrode the source takes its
    #    current back there (``Source.return_to``, honoured by the
    #    solver since 2026.11, finding 10.16).
    sources: list[PlannedSource] = []
    if include_source:
        sources.append(
            PlannedSource(
                attached_to=substation.name,
                return_to=None
                if measurement is None
                else measurement.auxiliary.name,
                magnitude=source_magnitude_a,
            )
        )

    return NetworkPlan(
        name=name,
        soil=soil or HomogeneousSoil(resistivity=100.0),
        sites=sites,
        junctions=junctions,
        branches=branches,
        measurement=measurement,
        sources=sources,
    )

to_world

to_world(*, name: str = 'ortsnetz_layout', soil: Optional[SoilModel] = None, substation_grounding: Optional[GroundingSystemSpec] = None, cabinet_grounding: Optional[GroundingSystemSpec] = None, house_grounding: Optional[GroundingSystemSpec] = None, pen_wire_radius_m: float = 0.005, pen_segment_length_m: Optional[float] = 5.0, include_source: bool = True, source_magnitude_a: float = 1.0, seed: int = 0, foundation_mask: Optional[list[bool]] = None, foundation_outline: FoundationOutline = 'ombr', **deprecated: object) -> World

Materialise the layout into a groundfield.World.

Equivalent to materialise_plan(self.plan(...)). Each PenCable becomes a chain of straight conductors between junctions at its corners and tap points, so the cable follows its Manhattan polyline; each BuildingConnection becomes one conductor from the tap junction to the house foundation. A conductor routed to a site with a horizontal earth electrode (a foundation, since user decision Q43 also a circular ring or a strip) ends at the point of that electrode nearest to it (user decision Q41): such a house is tapped at the closest pair in plan of its cable and its horizontal wires (not at the tap point of its BuildingConnection, the cable point nearest to the centroid), and its drop ends there, at the wire's depth, attached to that wire; a cable leaves a substation or a cabinet with horizontal electrodes (the default substation ring) at their point nearest to the cable's next node. Taps lie on the layout polyline where the cable is built: the leading run of its waypoints inside the start site's closed electrodes (a rectangle, a building outline, a circle) and the trailing run inside the end site's are part of those sites (audit R6A-01: a router corner inside a small cabinet ring was a node that houses tapped), and the segment that leaves (reaches) the site is clipped at the projection onto it of the site's point nearest to its far waypoint; a cable that passes through the closed electrodes of the substation or a cabinet elsewhere — another cabinet, or its own start or end site again — is clipped there the same way and joined to that site where it enters and where it leaves it (audits W1B-03, W1B-04). So no tap and no corner lies inside the foundation of the substation or a cabinet, and a rotated, polygon or offset site foundation leaves the taps of the houses on the cable (audits R4A-03, R5A-02); a tap at a clip point, or at the site's waypoint, is the site itself. A site with rods only keeps the connection point of its anchor.

Parameters:

Name Type Description Default
name str

World name.

'ortsnetz_layout'
soil Optional[SoilModel]

Soil model; default homogeneous 100 Ω·m.

None
substation_grounding Optional[GroundingSystemSpec]

Grounding specs of the substation, every cabinet and every house (defaults: ring + 4 rods, one 1.5 m rod, 2 × 2 foundation mesh shaped after the footprint).

None
cabinet_grounding Optional[GroundingSystemSpec]

Grounding specs of the substation, every cabinet and every house (defaults: ring + 4 rods, one 1.5 m rod, 2 × 2 foundation mesh shaped after the footprint).

None
house_grounding Optional[GroundingSystemSpec]

Grounding specs of the substation, every cabinet and every house (defaults: ring + 4 rods, one 1.5 m rod, 2 × 2 foundation mesh shaped after the footprint).

None
pen_wire_radius_m float

PEN wire radius in m.

0.005
pen_segment_length_m Optional[float]

Discretisation length in m of the PEN conductors (None: lumped).

5.0
include_source bool

Add the current source at the substation. With an auxiliary electrode it is a two-terminal source that returns its current through that electrode (Source.return_to; up to 0.15.0 a second, 180° source on the auxiliary electrode stood in for it).

True
source_magnitude_a float

Source current in A.

1.0
seed int

Seed of the random draws in the grounding specs.

0
foundation_mask Optional[list[bool]]

Optional per-house bool list. Only houses with True receive a foundation electrode (and a service drop); the others stay in the layout for plotting. Combine with foundation_mask() for a reproducible penetration sweep.

None
foundation_outline FoundationOutline

How each footprint shapes the foundation electrodes of house_grounding (see GroundingSystemSpec.with_footprint): "ombr" (default) — the oriented minimum bounding rectangle of the footprint (size, orientation and centre), the same rule as the OSM placement of TnNetworkGenerator; "polygon" — the real outline as a closed ring (style="ring" foundations only; DIN 18014); "spec" — the spec geometry at the footprint centroid (every house got the same foundation before 2026.11).

'ombr'

Returns:

Type Description
World

The materialised network.

Source code in src/groundfield/generators/layout/model.py
def to_world(
    self,
    *,
    name: str = "ortsnetz_layout",
    soil: Optional[SoilModel] = None,
    substation_grounding: Optional[GroundingSystemSpec] = None,
    cabinet_grounding: Optional[GroundingSystemSpec] = None,
    house_grounding: Optional[GroundingSystemSpec] = None,
    pen_wire_radius_m: float = 0.005,
    pen_segment_length_m: Optional[float] = 5.0,
    include_source: bool = True,
    source_magnitude_a: float = 1.0,
    seed: int = 0,
    foundation_mask: Optional[list[bool]] = None,
    foundation_outline: FoundationOutline = "ombr",
    **deprecated: object,
) -> World:
    """Materialise the layout into a :class:`groundfield.World`.

    Equivalent to ``materialise_plan(self.plan(...))``. Each
    :class:`PenCable` becomes a chain of straight conductors between
    junctions at its corners and tap points, so the cable follows its
    Manhattan polyline; each :class:`BuildingConnection` becomes one
    conductor from the tap junction to the house foundation. A
    conductor routed to a site with a horizontal earth electrode (a
    foundation, since user decision Q43 also a circular ring or a
    strip) ends at the point of that electrode nearest to it (user
    decision Q41): such a house is tapped at the closest pair in plan of
    its cable and its horizontal wires (not at the tap point of its
    :class:`BuildingConnection`, the cable point nearest to the
    centroid), and its drop ends there, at the wire's depth, attached to
    that wire; a cable leaves a substation or a cabinet with horizontal
    electrodes (the default substation ring) at their point nearest to
    the cable's next node. Taps lie on the layout polyline where the
    cable is built: the leading run of its waypoints inside the start
    site's closed electrodes (a rectangle, a building outline, a circle)
    and the trailing run inside the end site's are part of those sites
    (audit R6A-01: a router corner inside a small cabinet ring was a
    node that houses tapped), and the segment that leaves (reaches) the
    site is clipped at the projection onto it of the site's point
    nearest to its far waypoint; a cable that passes through the closed
    electrodes of the substation or a cabinet elsewhere — another
    cabinet, or its own start or end site again — is clipped there the
    same way and joined to that site where it enters and where it
    leaves it (audits W1B-03, W1B-04). So no tap and no corner lies
    inside the foundation of the substation or a cabinet, and a rotated,
    polygon or offset site foundation leaves the taps of the houses on
    the cable (audits R4A-03, R5A-02); a tap at a clip point, or at the
    site's waypoint, is the site itself. A site with rods only keeps the
    connection point of its anchor.

    Parameters
    ----------
    name
        World name.
    soil
        Soil model; default homogeneous 100 Ω·m.
    substation_grounding, cabinet_grounding, house_grounding
        Grounding specs of the substation, every cabinet and every
        house (defaults: ring + 4 rods, one 1.5 m rod, 2 × 2
        foundation mesh shaped after the footprint).
    pen_wire_radius_m
        PEN wire radius in m.
    pen_segment_length_m
        Discretisation length in m of the PEN conductors (``None``:
        lumped).
    include_source
        Add the current source at the substation. With an
        auxiliary electrode it is a two-terminal source that
        returns its current through that electrode
        (``Source.return_to``; up to 0.15.0 a second, 180° source on
        the auxiliary electrode stood in for it).
    source_magnitude_a
        Source current in A.
    seed
        Seed of the random draws in the grounding specs.
    foundation_mask
        Optional per-house bool list. Only houses with ``True``
        receive a foundation electrode (and a service drop); the
        others stay in the layout for plotting. Combine with
        :meth:`foundation_mask` for a reproducible penetration sweep.
    foundation_outline
        How each footprint shapes the foundation electrodes of
        ``house_grounding`` (see
        :meth:`GroundingSystemSpec.with_footprint
        <groundfield.generators.grounding.GroundingSystemSpec.with_footprint>`):
        ``"ombr"`` (default) — the oriented minimum bounding
        rectangle of the footprint (size, orientation and centre),
        the same rule as the OSM placement of
        :class:`~groundfield.generators.tn_network.TnNetworkGenerator`;
        ``"polygon"`` — the real outline as a closed ring
        (``style="ring"`` foundations only; DIN 18014); ``"spec"`` —
        the spec geometry at the footprint centroid (every house got
        the same foundation before 2026.11).

    Returns
    -------
    World
        The materialised network.
    """
    renamed = take_renamed_kwargs(
        "LvNetworkLayout.to_world",
        deprecated,
        {
            "kvs_grounding": "cabinet_grounding",
            "source_magnitude_A": "source_magnitude_a",
        },
    )
    cabinet_grounding = renamed.get("cabinet_grounding", cabinet_grounding)  # type: ignore[assignment]
    source_magnitude_a = renamed.get("source_magnitude_a", source_magnitude_a)  # type: ignore[assignment]
    return materialise_plan(
        self.plan(
            name=name,
            soil=soil,
            substation_grounding=substation_grounding,
            cabinet_grounding=cabinet_grounding,
            house_grounding=house_grounding,
            pen_wire_radius_m=pen_wire_radius_m,
            pen_segment_length_m=pen_segment_length_m,
            include_source=include_source,
            source_magnitude_a=source_magnitude_a,
            seed=seed,
            foundation_mask=foundation_mask,
            foundation_outline=foundation_outline,
        )
    )

xy_to_lat_lon

xy_to_lat_lon(x_m: float, y_m: float) -> tuple[float, float]

Inverse projection: local frame (x, y) → WGS84.

Mirrors lat_lon_to_xy().

Source code in src/groundfield/generators/layout/model.py
def xy_to_lat_lon(
    self,
    x_m: float,
    y_m: float,
) -> tuple[float, float]:
    """Inverse projection: local frame ``(x, y)`` → WGS84.

    Mirrors :meth:`lat_lon_to_xy`.
    """
    projector = self.projector
    if projector is None:
        raise RuntimeError(
            "LvNetworkLayout.xy_to_lat_lon: layout has no "
            "frame_origin_lat_lon. Build via ``from_osm`` first."
        )
    return projector.to_lat_lon(x_m, y_m)

ManhattanGridPlacement

Bases: BaseModel

Regular Manhattan-grid placement.

Houses are placed on a grid centred on centre_xy with n_per_row columns and as many rows as needed to fit n sites (the last row may be partially filled).

Spacings are configurable as fixed values or distributions; they are sampled once per generate() call (one draw used for the whole grid). Per-site jitter_m adds an additional uniform offset in the box \([-\text{jitter}/2, +\text{jitter}/2]^2\) to each grid point — sample once per site. jitter_m may itself be a Distribution; it is then drawn once per site (a draw \(\le 0\) means no jitter for that site).

Notes

The grid is centred so the geometric centroid of a fully filled grid coincides with centre_xy. For a partial last row the centroid drifts slightly; if you need exact symmetry, request a count that is a multiple of n_per_row.

generate

generate(n: int, rng: Generator) -> list[tuple[float, float]]

Place n sites on the grid, row by row.

Parameters:

Name Type Description Default
n int

Number of sites.

required
rng Generator

Random number generator for the spacings (one draw each per call) and the per-site jitter.

required

Returns:

Type Description
list of tuple of float

(x, y) per site in m; empty for n < 1.

Source code in src/groundfield/generators/placement.py
def generate(self, n: int, rng: np.random.Generator) -> list[tuple[float, float]]:
    """Place ``n`` sites on the grid, row by row.

    Parameters
    ----------
    n : int
        Number of sites.
    rng : numpy.random.Generator
        Random number generator for the spacings (one draw each per
        call) and the per-site jitter.

    Returns
    -------
    list of tuple of float
        ``(x, y)`` per site in m; empty for ``n < 1``.
    """
    if n < 1:
        return []
    sx = _to_float(self.spacing_x_m, rng)
    sy = _to_float(self.spacing_y_m, rng)
    n_rows = math.ceil(n / self.n_per_row)
    cx, cy = self.centre_xy
    x_offset = cx - (self.n_per_row - 1) / 2.0 * sx
    y_offset = cy - (n_rows - 1) / 2.0 * sy
    positions: list[tuple[float, float]] = []
    for i in range(n):
        row = i // self.n_per_row
        col = i % self.n_per_row
        x = col * sx + x_offset
        y = row * sy + y_offset
        j = _to_float(self.jitter_m, rng)
        if j > 0.0:
            x += float(rng.uniform(-j / 2.0, j / 2.0))
            y += float(rng.uniform(-j / 2.0, j / 2.0))
        positions.append((x, y))
    return positions

MeasurementInjectionConfig

Bases: GeneratorConfig

Auxiliary current electrode + optional metallic feed lead.

The auxiliary electrode (Hilfserder) is the remote electrode through which the test current returns to the source. Default: a single driven rod at \((200, 0)\) m. For studies that model the measurement against a neighbouring substation, point grounding at neighbour_substation_grounding().

feed_lead is the metallic Stromeinspeiseleitung from the instrument's current terminal MEASUREMENT_H_TERMINAL to the aux electrode; the source drives the test current between the substation and that terminal. None (default) means galvanic-only: the source's return_to is the aux electrode itself, i.e. an ideal return path without impedance or inductive coupling. Setting feed_lead to a MeasurementLeadConfig (often via overhead_lead() or buried_lead()) adds the physical wire and enables the inductive coupling.

MeasurementLeadConfig

Bases: GeneratorConfig

One physical measurement lead (current feed or voltage probe).

A measurement lead is a finite-impedance Conductor that connects two anchor electrodes (typically the substation cluster and the auxiliary or probe cluster). It runs horizontally at \(z\) = depth_m (see lead_axis_z()) between the horizontal positions of the two anchors. Typical variants:

  • depth_m = 0.0 — laid out on the ground (the classical feed lead of a fall-of-potential measurement); modelled SURFACE_LEAD_HEIGHT_M above the surface.
  • depth_m < 0.0 — strung above ground at height -depth_m.
  • depth_m > 0.0 (e.g. 0.6 m) — buried cable. Used when the study models a permanently installed measurement infrastructure or a measurement that uses an existing buried PEN cable as the feed.

The default settings (conductor_type="bare_copper", coupling_to_soil="isolated", inductance_model="neumann") match a bare overhead measurement wire that does not leak current to the soil along its length but does generate a magnetic field that couples to every parallel conductor — exactly the inductive-coupling problem.

MeasurementProbeConfig

Bases: GeneratorConfig

Voltage probe + optional metallic measurement lead.

The voltage probe (Spannungssonde) is the second remote electrode; the post-processing evaluates the potential at its location. Default: a short (0.5 m) driven rod at \((60, 0)\) m — the classical 62 % point in fall-of-potential measurements.

lead is the metallic measurement wire from the instrument's voltage terminal MEASUREMENT_S_TERMINAL to the probe; it carries no current (ideal voltmeter), so its resistance does not enter the reading, but the voltage induced in it does. As with MeasurementInjectionConfig.feed_lead, None is galvanic-only (the voltmeter reads the probe electrode directly); setting it enables inductive coupling.

MeasurementSetupConfig

Bases: GeneratorConfig

Earth-resistance measurement setup.

When TnNetworkConfig.measurement is set, the generator:

  1. builds the auxiliary electrode at injection.position_xy via injection.grounding.build_at(...);
  2. builds the voltage probe at probe.position_xy via probe.grounding.build_at(...);
  3. if injection.feed_lead is set, adds the instrument's current terminal, the junction MEASUREMENT_H_TERMINAL at the substation position, and a Conductor from it to the aux anchor with the configured depth, conductor type, and inductance model;
  4. if probe.lead is set, adds the voltage terminal, the junction MEASUREMENT_S_TERMINAL, and a similar conductor from it to the probe anchor;
  5. attaches the source to the substation anchor with return_to pointing at the end of the current loop (MEASUREMENT_H_TERMINAL with a feed lead, else the aux anchor): the test current flows through the soil from the substation to the auxiliary electrode and back through the feed lead.

The reading of the simulated instrument is measured_impedance() (three-pole, E-S) and result.input_impedance() (two-pole, E-H).

The default factory leaves both leads as None (galvanic only). To enable inductive coupling, set, e.g.,

measurement = MeasurementSetupConfig( ... injection=MeasurementInjectionConfig( ... position_xy=(200.0, 0.0), ... feed_lead=overhead_lead(), ... ), ... probe=MeasurementProbeConfig( ... position_xy=(60.0, 0.0), ... lead=overhead_lead(), ... ), ... )

MultiLayerSoilSpec

Bases: PickleUpgrade, BaseModel

Multi-layer horizontally stratified soil.

The list layers is consumed top-down: the first entry is the surface layer, the last entry must have h=None (semi-infinite). Each layer's resistivity (and finite-layer thickness) may carry a Distribution.

to_soil

to_soil(rng: Generator) -> MultiLayerSoil

Draw the distributions and return the soil model.

Per layer the thickness is drawn before the resistivity. A non-default relative_permittivity of any layer warns with InertConfigurationWarning (no backend reads it).

Source code in src/groundfield/generators/soil_specs.py
def to_soil(self, rng: np.random.Generator) -> MultiLayerSoil:
    """Draw the distributions and return the soil model.

    Per layer the thickness is drawn before the resistivity. A
    non-default ``relative_permittivity`` of any layer warns with
    :class:`~groundfield.utils.InertConfigurationWarning` (no backend
    reads it).
    """
    _warn_inert_permittivity(
        type(self).__name__, [layer.relative_permittivity for layer in self.layers]
    )
    layers: list[SoilLayer] = []
    for spec in self.layers:
        thickness: Optional[float]
        if spec.h is None:
            thickness = None
        else:
            thickness = _to_float(spec.h, rng)
        layers.append(
            _soil_model(  # type: ignore[arg-type]
                SoilLayer,
                rho=_to_float(spec.rho, rng),
                h=thickness,
                relative_permittivity=spec.relative_permittivity,
            )
        )
    return MultiLayerSoil(layers=layers)

NetworkPlan

Bases: BaseModel

Concrete, serialisable description of a generated network.

Attributes:

Name Type Description
name str

World name.

soil SoilModel

Concrete soil model.

sites list[PlannedSite]

Substation, cable cabinets and buildings, in materialisation order.

junctions list[PlannedJunction]

PEN cable junctions, in materialisation order.

branches list[PlannedBranch]

PEN cable sections and service drops, in materialisation order.

measurement Optional[PlannedMeasurement]

Optional measurement set-up.

sources list[PlannedSource]

Sources, in materialisation order.

Notes

materialise_plan() builds the world in a fixed order: sites, measurement sites, junctions, instrument terminals, branches, measurement leads, sources. Electrodes, junctions and conductors therefore appear in the world in that order.

all_branches property

all_branches: list[PlannedBranch]

Branches including the measurement leads, in build order.

all_junctions property

all_junctions: list[PlannedJunction]

PEN junctions and the instrument terminals, in build order.

all_sites property

all_sites: list[PlannedSite]

Sites including the measurement electrodes, in build order.

site

site(name: str) -> PlannedSite

Return the site called name (measurement sites included).

Source code in src/groundfield/generators/plan.py
def site(self, name: str) -> PlannedSite:
    """Return the site called ``name`` (measurement sites included)."""
    for s in self.all_sites:
        if s.name == name:
            return s
    raise KeyError(f"NetworkPlan has no site {name!r}.")

sites_with_role

sites_with_role(role: SiteRole) -> list[PlannedSite]

Return every site of the given role, in build order.

Source code in src/groundfield/generators/plan.py
def sites_with_role(self, role: SiteRole) -> list[PlannedSite]:
    """Return every site of the given role, in build order."""
    return [s for s in self.all_sites if s.role == role]

to_world

to_world() -> 'World'

Materialise the plan (see materialise_plan()).

Source code in src/groundfield/generators/plan.py
def to_world(self) -> "World":
    """Materialise the plan (see :func:`materialise_plan`)."""
    from groundfield.generators.materialise import materialise_plan

    return materialise_plan(self)

Normal

Bases: Distribution

Normal distribution \(\mathcal{N}(\mu, \sigma^2)\) with optional truncation.

Truncation is implemented via rejection sampling. A RuntimeError is raised if more than max_attempts rejections occur in a row, which protects against pathological bound configurations (e.g. truncate_low more than ten standard deviations away from the mean).

sample

sample(rng: Generator) -> float

Draw one sample, rejecting draws outside the truncation bounds.

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draws.

required

Returns:

Type Description
float

One draw of the (truncated) normal distribution.

Raises:

Type Description
RuntimeError

If max_attempts consecutive draws fall outside the truncation bounds.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Draw one sample, rejecting draws outside the truncation bounds.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draws.

    Returns
    -------
    float
        One draw of the (truncated) normal distribution.

    Raises
    ------
    RuntimeError
        If ``max_attempts`` consecutive draws fall outside the
        truncation bounds.
    """
    for _ in range(self.max_attempts):
        x = float(rng.normal(self.mean, self.std))
        if self.truncate_low is not None and x < self.truncate_low:
            continue
        if self.truncate_high is not None and x > self.truncate_high:
            continue
        return x
    raise RuntimeError(
        f"Normal.sample: rejection sampling exhausted {self.max_attempts} "
        f"attempts; check truncation bounds versus (mean, std)."
    )

ObstacleBox

Bases: BaseModel

Axis-aligned bounding box used as a routing obstacle.

Attributes:

Name Type Description
x_min, y_min, x_max, y_max

Lower-left and upper-right corner in metres.

name Optional[str]

Optional label (typically the OSM building id or a human- readable house identifier). Pure metadata; the router does not consume it.

height property

height: float

Extent of the box along y in m (y_max - y_min).

width property

width: float

Extent of the box along x in m (x_max - x_min).

contains_point

contains_point(x: float, y: float, *, tol: float = 0.0) -> bool

Whether the point (x, y) lies in the closed box.

Parameters:

Name Type Description Default
x float

Coordinates of the point in m.

required
y float

Coordinates of the point in m.

required
tol float

Margin in m by which the box is enlarged on every side for the test.

0.0

Returns:

Type Description
bool

True if the point lies inside or on the boundary of the box enlarged by tol.

Source code in src/groundfield/generators/manhattan_routing.py
def contains_point(self, x: float, y: float, *, tol: float = 0.0) -> bool:
    """Whether the point ``(x, y)`` lies in the closed box.

    Parameters
    ----------
    x, y : float
        Coordinates of the point in m.
    tol : float, default 0.0
        Margin in m by which the box is enlarged on every side for
        the test.

    Returns
    -------
    bool
        ``True`` if the point lies inside or on the boundary of the
        box enlarged by ``tol``.
    """
    return (
        self.x_min - tol <= x <= self.x_max + tol
        and self.y_min - tol <= y <= self.y_max + tol
    )

inflated

inflated(padding_m: float) -> 'ObstacleBox'

Return a copy enlarged by padding_m on every side.

Source code in src/groundfield/generators/manhattan_routing.py
def inflated(self, padding_m: float) -> "ObstacleBox":
    """Return a copy enlarged by ``padding_m`` on every side."""
    if padding_m <= 0.0:
        return self
    return ObstacleBox(
        x_min=self.x_min - padding_m,
        y_min=self.y_min - padding_m,
        x_max=self.x_max + padding_m,
        y_max=self.y_max + padding_m,
        name=self.name,
    )

rectangle_overlaps

rectangle_overlaps(cx: float, cy: float, half: float) -> bool

Does the square [cx-half, cx+half]^2 overlap the box?

Source code in src/groundfield/generators/manhattan_routing.py
def rectangle_overlaps(
    self,
    cx: float,
    cy: float,
    half: float,
) -> bool:
    """Does the square ``[cx-half, cx+half]^2`` overlap the box?"""
    return (
        cx + half > self.x_min
        and cx - half < self.x_max
        and cy + half > self.y_min
        and cy - half < self.y_max
    )

OrtsnetzLayout

Bases: LvNetworkLayout

Deprecated alias of LvNetworkLayout.

OsmBuildingPlacement

Bases: BaseModel

Placement driven by a list of pre-projected building footprints.

The class implements the same generate(n, rng) -> list[(x, y)] interface as generators.placement.ManhattanGridPlacement and generators.placement.ExplicitPlacement, so any consumer that accepts a PlacementSpec will accept this placement too (once it has been added to the discriminated union; see Task 3 in ADR-0011's implementation plan).

Attributes:

Name Type Description
footprints list[BuildingFootprint]

Pre-projected building polygons in the local ENU frame. Order is preserved; the k-th footprint corresponds to the k-th building site.

min_area_m2 float

Skip footprints whose area is strictly below this threshold on generate(). The default of 16 m² is roughly a garden shed; everything smaller is almost certainly OSM noise rather than a residential structure with a foundation electrode.

selection Literal['first_n', 'all']

How to choose footprints when the generator requests fewer than are available:

  • "first_n" (default) — take the first n in declared order. Fully deterministic.
  • "all" — return all footprints regardless of n. Useful when the user wants every visible building to appear in the world; n becomes a soft hint.
Notes

The class is intentionally a plain Pydantic BaseModel with a kind discriminator field; it does not inherit from a common PlacementSpec ABC because the existing union uses structural typing via the kind literal. Adding this class to generators.placement.PlacementSpec is a one-line union update tracked as a follow-up task.

n_footprints property

n_footprints: int

Number of footprints surviving the min_area_m2 filter.

Identical to len(placement) and provided as an explicit attribute so consumers can pre-flight an i against footprint_at() without invoking len() on the model instance.

__len__

__len__() -> int

Number of footprints after applying min_area_m2.

Source code in src/groundfield/geo/placement.py
def __len__(self) -> int:
    """Number of footprints after applying ``min_area_m2``."""
    return self.n_footprints

footprint_at

footprint_at(i: int, *, strict: bool = False) -> Optional[BuildingFootprint]

Return the footprint associated with site i.

Parameters:

Name Type Description Default
i int

Site index, matching the order returned by generate().

required
strict bool

If False (default), a out-of-range i returns None so callers can fall back to the spec-defined geometry without special-case logic — the historic v0.6.0 contract that TnNetworkGenerator.build() relies on.

If True, an out-of-range i raises a self-describing IndexError that names the placement, the requested index, the size of the filtered footprint list (after min_area_m2) and the raw list length. Generator pipelines that want a hard failure instead of a silent fall-back can opt in with strict=True and get an actionable traceback at the call site.

False

Returns:

Type Description
BuildingFootprint or None

The footprint at index i (after applying the min_area_m2 filter), or None when i is out of range and strict is False.

Raises:

Type Description
IndexError

If strict=True and i is outside [0, n_footprints).

Source code in src/groundfield/geo/placement.py
def footprint_at(
    self,
    i: int,
    *,
    strict: bool = False,
) -> Optional[BuildingFootprint]:
    """Return the footprint associated with site ``i``.

    Parameters
    ----------
    i
        Site index, matching the order returned by
        :meth:`generate`.
    strict
        If ``False`` (default), a out-of-range ``i`` returns
        ``None`` so callers can fall back to the spec-defined
        geometry without special-case logic — the historic
        v0.6.0 contract that
        :meth:`TnNetworkGenerator.build` relies on.

        If ``True``, an out-of-range ``i`` raises a
        self-describing :class:`IndexError` that names the
        placement, the requested index, the size of the filtered
        footprint list (after ``min_area_m2``) and the raw list
        length. Generator pipelines that want a hard failure
        instead of a silent fall-back can opt in with
        ``strict=True`` and get an actionable traceback at the
        call site.

    Returns
    -------
    BuildingFootprint or None
        The footprint at index ``i`` (after applying the
        ``min_area_m2`` filter), or ``None`` when ``i`` is out of
        range and ``strict`` is ``False``.

    Raises
    ------
    IndexError
        If ``strict=True`` and ``i`` is outside
        ``[0, n_footprints)``.
    """
    filtered = self._filtered()
    n = len(filtered)
    if 0 <= i < n:
        return filtered[i]
    if strict:
        raise IndexError(
            "OsmBuildingPlacement.footprint_at: requested index "
            f"{i} but only {n} footprints are available after "
            f"min_area_m2={self.min_area_m2} filter "
            f"(raw list length {len(self.footprints)}). "
            "Use ``len(placement)`` for the available count, or "
            "pass ``strict=False`` (default) for a None fall-back."
        )
    return None

generate

generate(n: int, rng: 'np.random.Generator') -> list[tuple[float, float]]

Return n site positions as polygon centroids.

Parameters:

Name Type Description Default
n int

Number of sites the generator wants to populate.

required
rng 'np.random.Generator'

Unused. Accepted for interface parity with the other PlacementSpec variants, all of which take an RNG so the generator can call them uniformly.

required

Returns:

Type Description
list[tuple[float, float]]

Polygon centroids in metres. Length is min(n, len(filtered)) when selection == "first_n" and equal to len(filtered) when selection == "all" (n is then ignored, with a soft contract).

Raises:

Type Description
ValueError

If n exceeds the available footprints and selection == "first_n". The generator can decide whether to widen its search radius or lower its n-target.

Notes

The reported site is the polygon's area centroid, not the centre of its oriented minimum bounding rectangle (OMBR); the two coincide only for outlines with a centre of symmetry (an L-shaped house separates them by several metres). Consumers that build OMBR-aligned geometry — i.e. footprint-driven FoundationElectrodeSpec in TnNetworkGenerator — must therefore compensate the centroid-to-OMBR-centre difference themselves via offset_xy_m. The service-drop / PEN routing consumers legitimately use the centroid, which is why generate keeps returning it.

Source code in src/groundfield/geo/placement.py
def generate(
    self,
    n: int,
    rng: "np.random.Generator",  # unused — kept for interface parity
) -> list[tuple[float, float]]:
    """Return ``n`` site positions as polygon centroids.

    Parameters
    ----------
    n
        Number of sites the generator wants to populate.
    rng
        Unused. Accepted for interface parity with the other
        :class:`PlacementSpec` variants, all of which take an
        RNG so the generator can call them uniformly.

    Returns
    -------
    list[tuple[float, float]]
        Polygon centroids in metres. Length is ``min(n,
        len(filtered))`` when ``selection == "first_n"`` and
        equal to ``len(filtered)`` when ``selection == "all"``
        (``n`` is then ignored, with a soft contract).

    Raises
    ------
    ValueError
        If ``n`` exceeds the available footprints **and**
        ``selection == "first_n"``. The generator can decide
        whether to widen its search radius or lower its
        ``n``-target.

    Notes
    -----
    The reported site is the polygon's **area centroid**, not
    the centre of its oriented minimum bounding rectangle
    (OMBR); the two coincide only for outlines with a centre of
    symmetry (an L-shaped house separates them by several
    metres). Consumers that build OMBR-aligned geometry — i.e.
    footprint-driven :class:`FoundationElectrodeSpec` in
    :class:`~groundfield.generators.tn_network.TnNetworkGenerator`
    — must therefore compensate the centroid-to-OMBR-centre
    difference themselves via ``offset_xy_m``. The service-drop
    / PEN routing consumers legitimately use the centroid,
    which is why ``generate`` keeps returning it.
    """
    filtered = self._filtered()
    if self.selection == "all":
        return [fp.centroid_xy_m() for fp in filtered]
    if n > len(filtered):
        raise ValueError(
            f"OsmBuildingPlacement.generate: requested {n} sites "
            f"but only {len(filtered)} footprints are available "
            f"after the min_area_m2={self.min_area_m2} filter."
        )
    return [filtered[i].centroid_xy_m() for i in range(n)]

PenCable

Bases: BaseModel

One PEN cable as a polyline of axis-aligned waypoints.

Attributes:

Name Type Description
name str

Unique cable id used for diagnostics, to_world naming and plot legends.

start_anchor str

Name of the anchor (substation or cable cabinet) the cable roots at.

waypoints list[tuple[float, float]]

Ordered list of \((x, y)\) corners. The first entry equals the start anchor's position and consecutive entries differ in exactly one coordinate (Manhattan).

end_anchor Optional[str]

Optional name of the anchor (cable cabinet) the cable terminates at. None when the cable runs to free coordinates (a :emphasis:stub end used as a tap for nearby houses but not for further trunking).

grid_size_m float

The grid size used when this cable was routed -- kept on the model so LvNetworkLayout.connect_buildings() can align stubs with the trunk.

segments

segments() -> list[tuple[tuple[float, float], tuple[float, float]]]

Straight pieces of the cable between consecutive waypoints.

Returns:

Type Description
list of tuple

((x0, y0), (x1, y1)) per piece in m, in waypoint order.

Source code in src/groundfield/generators/layout/routing.py
def segments(self) -> list[tuple[tuple[float, float], tuple[float, float]]]:
    """Straight pieces of the cable between consecutive waypoints.

    Returns
    -------
    list of tuple
        ``((x0, y0), (x1, y1))`` per piece in m, in waypoint order.
    """
    return list(zip(self.waypoints[:-1], self.waypoints[1:], strict=True))

total_length_m

total_length_m() -> float

Route length of the cable in m.

Sums the Manhattan length abs(dx) + abs(dy) of every piece; for the axis-aligned pieces of a routed cable this is the Euclidean length.

Returns:

Type Description
float

Length of the cable in m.

Source code in src/groundfield/generators/layout/routing.py
def total_length_m(self) -> float:
    """Route length of the cable in m.

    Sums the Manhattan length ``abs(dx) + abs(dy)`` of every piece;
    for the axis-aligned pieces of a routed cable this is the
    Euclidean length.

    Returns
    -------
    float
        Length of the cable in m.
    """
    return sum(
        abs(p1[0] - p0[0]) + abs(p1[1] - p0[1]) for p0, p1 in self.segments()
    )

PenConfig

Bases: GeneratorConfig

PEN cable backbone (distributed conductor, ADR-0003).

Every PEN section (substation to cabinet, trunk) and service drop runs horizontally at z = depth_m between the horizontal positions of the connection points of its two end electrodes, i.e. in the cable trench; the short vertical risers to the electrode heads are not modelled. Up to 0.15.0 depth_m was ignored and the sections ran straight between the connection points (e.g. from the substation ring at 0.6 m to a cabinet rod head at 0 m).

PlannedBranch

Bases: BaseModel

A conductor between two nodes of the plan.

Attributes:

Name Type Description
name str

Conductor name in the world.

role BranchRole

"pen" (cable section), "service_drop" or "measurement_lead".

start, end

Node names: a site (resolved to its anchor electrode) or a junction. A name that is neither is used verbatim as an electrode name.

conductor ConductorParameters

Conductor parameters.

cable Optional[str]

Name of the routed cable the section belongs to (informational).

axis_z_m Optional[float]

None (default): the conductor runs straight between its two end points (see start_contact). A value: the conductor runs horizontally at depth z = axis_z_m (m, positive into the soil, negative above ground) between the horizontal positions of those points; it stays electrically connected to the two end nodes.

start_contact, end_contact

None (default): the end point is the connection point of the node (a site's anchor electrode, or a junction). A PlannedContact (only at a site): the branch ends at that point of a foundation wire of the site, at the wire's depth (or at axis_z_m), and is attached to that wire (user decision Q41).

axis_offset_m float

Horizontal offset in m of the conductor from the straight line between the plan positions of its two end points, perpendicular to it: both ends move by axis_offset_m along the normal \((-d_y, d_x)/|d|\) of the plan direction \(d\) from start to end (rotated by +90° from x towards y). The conductor stays attached to its two end nodes. 0 (default): on the line. The TN generator lays service drops that leave one tap in one direction side by side at the touching distance (decision D9 of 2026.11, groundfield.generators._pen_routing); plans written before have no such entry and keep their geometry.

axis_offset_normal_xy Optional[tuple[Annotated[float, Field(allow_inf_nan=False)], Annotated[float, Field(allow_inf_nan=False)]]]

None (default): axis_offset_m is applied along the normal of the branch's own plan direction (above). A unit vector (n_x, n_y): both ends move by axis_offset_m along it — the common normal of a row of drops that are not exactly parallel (a placement with jitter), so that the offsets of a row lie on one line (audit W3R2B-01). Plans written before have no such entry.

PlannedContact

Bases: BaseModel

Where a branch meets a foundation of a site (user decision Q41).

Attributes:

Name Type Description
electrode str

Name of the electrode (a wire of the site's foundation) that holds the point; the branch is attached to it.

position_xy tuple[float, float]

Plan position (x, y) in m where the branch ends: the point of the foundation nearest to the branch, on that wire — or, where the generator joins a cable to a foundation wire that it crosses or touches (and where a drop starts at such a joint), the cable's point, which lies at most one minimum cable section off the wire (min_section_length(): 1 cm for wire radii up to 7.3 mm).

Notes

New in 2026.11. The generators set it on every branch end at a site with a foundation (FoundationElectrodeSpec): the branch ends at the point of the foundation nearest to it instead of the connection point of the site's anchor electrode (a corner of a rectangular foundation, the first vertex of a building outline). materialise_branch() rejects a contact that names no foundation wire of the site or lies farther than that from it (audit R4A-05).

PlannedElectrode

Bases: BaseModel

One present electrode of a site, with every value resolved.

Attributes:

Name Type Description
index int

Position of the electrode in the GroundingSystemSpec it was drawn from. It is part of the electrode name (f"{site}_{kind}_{index}"), so names stay stable when an earlier electrode of the spec was absent in this realisation.

spec ElectrodeSpec

The electrode specification with concrete values only (no Distribution, presence_prob == 1).

PlannedJunction

Bases: BaseModel

Interior node of a PEN cable (a corner or a tap point).

Attributes:

Name Type Description
name str

Node name, unique among sites and junctions.

position_xy tuple[float, float]

Horizontal position in m.

depth_m float

Burial depth in m (positive into the soil).

Notes

A junction is materialised as a leakage-free Junction node at (x, y, depth_m) (see groundfield.generators.materialise.materialise_junction()); it injects no current into the soil. Up to 0.15.0 it was a 5 cm rod electrode that leaked part of the cable current (review finding 10.38).

PlannedMeasurement

Bases: BaseModel

Fall-of-potential measurement set-up.

Attributes:

Name Type Description
auxiliary PlannedSite

Auxiliary current electrode (role "auxiliary").

probe Optional[PlannedSite]

Voltage probe electrode (role "probe"), or None when the probe is a pure sampling point without an electrode.

feed_lead, probe_lead

Optional metallic leads (role "measurement_lead"). Each runs from an instrument terminal (see terminals) to the remote electrode.

terminals list[PlannedJunction]

Leakage-free junctions at the instrument at which the leads end: the current terminal H (feed lead) and the voltage terminal S (probe lead). The current source of the measurement drives its current between the earthing system and H; the voltmeter reads the potential difference between the earthing system and S. Empty when no lead is configured.

PlannedSite

Bases: BaseModel

A grounding site: bonded electrodes forming one galvanic cluster.

Attributes:

Name Type Description
name str

Site name; every electrode is named f"{name}_{kind}_{index}" and the bonds f"{name}_bond_{k}".

role SiteRole

"substation", "cabinet", "building", "auxiliary" (current return electrode of a measurement) or "probe" (voltage probe electrode).

position_xy tuple[float, float]

Site reference point (x, y) in m; electrode offsets are relative to it.

electrodes list[PlannedElectrode]

Present electrodes in spec order. Empty when every electrode of the spec was absent in this realisation (the site then has no anchor and is not wired).

bond_conductor_type str

Conductor type of the bonds between the anchor and the other electrodes of the site.

footprint Optional[BuildingFootprint]

Building outline the foundation geometry was derived from (buildings with a footprint only; informational).

building_type Optional[str]

Name of the building type the site was drawn from (buildings of TnNetworkGenerator).

cabinet_rule Optional[CabinetRule]

Rule that placed a cable cabinet of a building group (TnNetworkGenerator, star topology, CabinetConfig.placement=None): "centroid_ray" — on the ray from the substation through the group's centroid — or "far_end_ray" — on the ray through the group's far-end building, because on the centroid ray it would have stood farther than CabinetConfig.max_far_end_gap_m from its group (audit W1R2-02, user decision D7). None for every other site, for cabinets of a given placement and of the radial topology. Informational: materialising the plan ignores it.

centroid_ray_gap_m Optional[Annotated[float, Field(ge=0.0, allow_inf_nan=False)]]

Recorded with cabinet_rule: plan distance in m, at least 0, between the cabinet's electrodes at its position on the centroid ray and the nearest electrode of its group — the value compared with max_far_end_gap_m (the centroid ray is kept up to it). A group near the threshold changes rule, and its cabinet jumps by up to the width of the group, under a small change of the layout.

anchor property

anchor: Optional[str]

Name of the anchor electrode (the first present one), or None.

electrode_name

electrode_name(electrode: PlannedElectrode) -> str

Return the world name of one of the site's electrodes.

Source code in src/groundfield/generators/plan.py
def electrode_name(self, electrode: PlannedElectrode) -> str:
    """Return the world name of one of the site's electrodes."""
    return f"{self.name}_{electrode.spec.kind}_{electrode.index}"

PlannedSource

Bases: BaseModel

A current or voltage source.

Attributes:

Name Type Description
name Optional[str]

Source name; None lets groundfield.create_source() number it.

attached_to, return_to

Node names (sites resolve to their anchor electrode); a name that is neither a site nor a junction is used verbatim as an electrode name. return_to=None returns through remote earth.

kind Literal['current', 'voltage']

"current" or "voltage".

magnitude float

Amplitude in A (current source) or V (voltage source).

phase_deg float

Phase angle in degrees.

RadialTrunkTopology

Bases: PickleUpgrade, BaseModel

Radial-feeder PEN topology with finite per-source slot budget.

The substation feeds n_feeders radial feeders. Each feeder runs along its own discrete direction (feeder_directions_deg or — by default — evenly spaced around the substation starting at 0°). Buildings are assigned to the angularly closest feeder, then sorted by distance from the substation along that feeder axis. The first slots_per_substation buildings tap directly to the substation; once the budget is exhausted, a cable cabinet is inserted along the feeder axis and the next slots_per_cabinet buildings tap to that cabinet, and so on.

Attributes:

Name Type Description
n_feeders int

Number of radial feeders emanating from the substation. Default 4 (a typical "north / east / south / west" TN-Ortsnetz).

feeder_directions_deg Optional[list[float]]

Optional explicit feeder angles in degrees (CCW from +x). Length must equal n_feeders. None (default) auto-distributes the feeders evenly: \(\theta_k = 360^\circ\,k/N\) for \(k=0,\ldots,N-1\).

max_feeder_length_m float

Maximum trunk length per feeder. Buildings beyond this distance (measured along the feeder axis) are dropped from the assignment and trigger a UserWarning.

slots_per_substation int

Number of direct building taps each feeder may have at the substation. Once this many buildings have been wired, the next building forces a cabinet extension.

slots_per_cabinet int

Number of direct building taps per cabinet. After the substation budget is exhausted, cabinets are inserted along the feeder until every assigned building is wired or the feeder reaches max_feeder_length_m.

cabinet_spacing_m float

Step length (along the feeder axis) between adjacent cabinets when the topology decides to insert a new one. Default 60 m matches the typical street-section length between cable cabinets in urban LV networks.

name_prefix str

Prefix used to name the inserted cabinets (f"{prefix}_f{feeder_idx}_{k}"). Defaults to "kvs" so the names are consistent with the legacy star topology.

Notes

Trunk segments (substation → cabinet and cabinet → cabinet, one cable each) and service drops are realised as straight conductors at the PEN depth. A building fed by a cabinet taps the trunk from the substation to its cabinet at the point nearest to the building (the closest pair of trunk and foundation, user decision Q41; a leakage-free tap junction, or the cabinet); a building in a substation slot taps its feeder's whole trunk the same way (user decisions Q22, Q35; up to then it was connected to the substation, as it still is on a feeder without a cabinet). A building that a trunk crosses (any trunk) is joined to it there without a drop (audit R4A-02). A drop may run along another drop (one trench), never along a trunk farther than one minimum section (1 cm): a drop from a node that would run along a trunk — both ends of a trunk section within 1 cm of its line (audit R5A-01) — leaves it at the end of the shared stretch (audit R4B-01). The Manhattan-ness of the layout is reflected in (a) the discrete feeder directions which keep the trunk axis-aligned and (b) the angular feeder assignment, which steers buildings toward the geometrically closest street axis. Corner-routed service drops are tracked as a v2 enhancement.

kvs_spacing_m property

kvs_spacing_m: float

Deprecated alias of cabinet_spacing_m.

slots_per_kvs property

slots_per_kvs: int

Deprecated alias of slots_per_cabinet.

assign_buildings_to_feeders

assign_buildings_to_feeders(substation_xy: tuple[float, float], building_positions: list[tuple[float, float]]) -> list[list[int]]

Group building indices by angularly closest feeder.

Parameters:

Name Type Description Default
substation_xy tuple[float, float]

Substation centre in m.

required
building_positions list[tuple[float, float]]

Per-building centres in m. Order is preserved across the assignment.

required

Returns:

Type Description
list of lists of int

out[feeder_idx] is the list of building indices assigned to feeder feeder_idx. Each list is sorted by distance from the substation along the feeder axis (signed projection onto the feeder direction). Buildings with a negative axial projection (behind the substation) are excluded from the feeder.

Source code in src/groundfield/generators/pen_topology.py
def assign_buildings_to_feeders(
    self,
    substation_xy: tuple[float, float],
    building_positions: list[tuple[float, float]],
) -> list[list[int]]:
    """Group building indices by angularly closest feeder.

    Parameters
    ----------
    substation_xy
        Substation centre in m.
    building_positions
        Per-building centres in m. Order is preserved across
        the assignment.

    Returns
    -------
    list of lists of int
        ``out[feeder_idx]`` is the list of building indices
        assigned to feeder ``feeder_idx``. Each list is sorted
        by distance from the substation along the feeder axis
        (signed projection onto the feeder direction). Buildings
        with a *negative* axial projection (behind the
        substation) are excluded from the feeder.
    """
    sx, sy = substation_xy
    feeder_dirs = self.resolved_directions_rad()
    groups: list[list[tuple[float, int]]] = [[] for _ in feeder_dirs]
    for i, (bx, by) in enumerate(building_positions):
        dx, dy = bx - sx, by - sy
        r = math.hypot(dx, dy)
        if r < 1e-9:
            # Building on the substation; assign to first feeder.
            groups[0].append((0.0, i))
            continue
        building_angle = math.atan2(dy, dx)
        # Pick feeder with smallest angular distance.
        best = min(
            range(len(feeder_dirs)),
            key=lambda k: _angle_diff(feeder_dirs[k], building_angle),
        )
        # Signed projection onto feeder direction.
        theta = feeder_dirs[best]
        proj = dx * math.cos(theta) + dy * math.sin(theta)
        if proj <= 0.0:
            # Behind the substation along this feeder axis;
            # cannot be reached without back-tracking. Drop.
            warnings.warn(
                f"RadialTrunkTopology: building at ({bx:.1f}, "
                f"{by:.1f}) projects behind the closest feeder "
                f"axis (theta={math.degrees(theta):.0f}°, "
                f"proj={proj:.2f} m); dropping from the PEN "
                "topology.",
                UserWarning,
                stacklevel=2,
            )
            continue
        if proj > self.max_feeder_length_m:
            warnings.warn(
                f"RadialTrunkTopology: building at ({bx:.1f}, "
                f"{by:.1f}) projects to {proj:.1f} m on its "
                "feeder axis, beyond max_feeder_length_m="
                f"{self.max_feeder_length_m} m; dropping from "
                "the PEN topology.",
                UserWarning,
                stacklevel=2,
            )
            continue
        groups[best].append((proj, i))
    # Sort each group by axial distance from the substation.
    out: list[list[int]] = []
    for g in groups:
        g.sort(key=lambda pair: pair[0])
        out.append([i for _, i in g])
    return out

plan_feeder_cabinet_positions

plan_feeder_cabinet_positions(substation_xy: tuple[float, float], feeder_idx: int, n_buildings_on_feeder: int) -> list[tuple[float, float]]

Compute cabinet positions for a feeder given its building count.

The first slots_per_substation buildings tap directly to the substation. The next batch of up to slots_per_cabinet buildings shares one cabinet, the batch after that shares the next cabinet, and so on. Each cabinet sits on the feeder axis at the smallest multiple of cabinet_spacing_m that is \(\ge\) the projection of the first building it serves — but we don't have that projection here; we approximate by stepping one cabinet_spacing_m per cabinet. This keeps the layout predictable (cabinets are equispaced along the street) and matches typical Ortsnetz cable cabinet spacing.

Positions beyond max_feeder_length_m are clipped to max_feeder_length_m; if multiple cabinets would be clipped to the same maximum distance, only the first is kept and the remaining buildings will trigger a UserWarning from the caller.

Source code in src/groundfield/generators/pen_topology.py
def plan_feeder_cabinet_positions(
    self,
    substation_xy: tuple[float, float],
    feeder_idx: int,
    n_buildings_on_feeder: int,
) -> list[tuple[float, float]]:
    r"""Compute cabinet positions for a feeder given its building count.

    The first :attr:`slots_per_substation` buildings tap directly
    to the substation. The next batch of up to
    :attr:`slots_per_cabinet` buildings shares one cabinet, the batch
    after that shares the next cabinet, and so on. Each cabinet sits on
    the feeder axis at the smallest multiple of
    :attr:`cabinet_spacing_m` that is :math:`\ge` the projection of
    the *first* building it serves — but we don't have that
    projection here; we approximate by stepping one
    :attr:`cabinet_spacing_m` per cabinet. This keeps the layout
    predictable (cabinets are equispaced along the street) and
    matches typical Ortsnetz cable cabinet spacing.

    Positions beyond :attr:`max_feeder_length_m` are clipped to
    :attr:`max_feeder_length_m`; if multiple cabinets would be
    clipped to the same maximum distance, only the first is
    kept and the remaining buildings will trigger a
    :class:`UserWarning` from the caller.
    """
    sx, sy = substation_xy
    theta = self.resolved_directions_rad()[feeder_idx]
    cos_t, sin_t = math.cos(theta), math.sin(theta)
    remaining = max(0, n_buildings_on_feeder - self.slots_per_substation)
    if remaining <= 0:
        return []
    n_cabinets = math.ceil(remaining / self.slots_per_cabinet)
    positions: list[tuple[float, float]] = []
    last_distance: Optional[float] = None
    for k in range(n_cabinets):
        distance = (k + 1) * self.cabinet_spacing_m
        if distance > self.max_feeder_length_m:
            if last_distance is not None and last_distance >= (
                self.max_feeder_length_m - 1e-9
            ):
                break
            distance = self.max_feeder_length_m
        cabinet_xy = (sx + distance * cos_t, sy + distance * sin_t)
        positions.append(cabinet_xy)
        last_distance = distance
    return positions

plan_feeder_kvs_positions

plan_feeder_kvs_positions(substation_xy: tuple[float, float], feeder_idx: int, n_buildings_on_feeder: int) -> list[tuple[float, float]]

Deprecated alias of plan_feeder_cabinet_positions().

Source code in src/groundfield/generators/pen_topology.py
def plan_feeder_kvs_positions(
    self,
    substation_xy: tuple[float, float],
    feeder_idx: int,
    n_buildings_on_feeder: int,
) -> list[tuple[float, float]]:
    """Deprecated alias of :meth:`plan_feeder_cabinet_positions`."""
    warn_renamed(
        "RadialTrunkTopology.plan_feeder_kvs_positions",
        "RadialTrunkTopology.plan_feeder_cabinet_positions",
    )
    return self.plan_feeder_cabinet_positions(
        substation_xy=substation_xy,
        feeder_idx=feeder_idx,
        n_buildings_on_feeder=n_buildings_on_feeder,
    )

resolved_directions_rad

resolved_directions_rad() -> list[float]

Return the feeder directions in radians.

If feeder_directions_deg is None, the directions are auto-distributed evenly around the substation. Otherwise the explicit list is consumed verbatim (after the field_validator() check that the length matches n_feeders).

Source code in src/groundfield/generators/pen_topology.py
def resolved_directions_rad(self) -> list[float]:
    """Return the feeder directions in radians.

    If :attr:`feeder_directions_deg` is ``None``, the directions
    are auto-distributed evenly around the substation. Otherwise
    the explicit list is consumed verbatim (after the
    :func:`field_validator` check that the length matches
    :attr:`n_feeders`).
    """
    if self.feeder_directions_deg is None:
        return [2.0 * math.pi * k / self.n_feeders for k in range(self.n_feeders)]
    if len(self.feeder_directions_deg) != self.n_feeders:
        raise ValueError(
            "feeder_directions_deg length "
            f"({len(self.feeder_directions_deg)}) does not match "
            f"n_feeders ({self.n_feeders})."
        )
    return [math.radians(a) for a in self.feeder_directions_deg]

RingElectrodeSpec

Bases: _ElectrodeSpecBase

Ring earth electrode.

Horizontal circle of radius radius_m at depth depth_m. The classical foundation-ring or substation-ring electrode.

RodElectrodeSpec

Bases: _ElectrodeSpecBase

Driven rod (Tiefenerder).

Modelled as a vertical line conductor of length length_m starting at depth depth_m (rod head, 0 m = ground surface).

SoilLayerSpec

Bases: PickleUpgrade, BaseModel

A single layer used by MultiLayerSoilSpec.

h=None marks the semi-infinite bottom layer (only valid as the last entry in MultiLayerSoilSpec.layers).

resistivity property

resistivity: Union[float, Distribution]

Deprecated alias of rho.

thickness_m property

thickness_m: Optional[Union[float, Distribution]]

Deprecated alias of h.

StarCabinetTopology

Bases: PickleUpgrade, BaseModel

Star PEN topology (default).

The substation feeds each cable cabinet directly, through a cable of its own (cabinets in a line get separate cables in one trench). By default (CabinetConfig.placement None, user decisions Q22 and Q35 of 2026.11) the cabinets stand per building group: the buildings are grouped by group_buildings() (runs of consecutive bearings around the substation, one per cabinet), and the cabinet of a group stands at the group's far end — on the ray from the substation through the group's centroid, CabinetConfig.end_clearance_m beyond the group's earth electrodes along it, rods included, when it stands there within CabinetConfig.max_far_end_gap_m of its houses, otherwise on the ray through the group's far-end building (the largest projection of its position on the direction of the centroid), beyond that building (audits W1B-01, W1B-02) — and feeds the group. With a given placement every building is fed by its nearest cabinet (Manhattan metric between the site positions), as before. A building that a cabinet's cable (main) crosses is joined to that main where it crosses the foundation, without a service drop, and is fed by that main's cabinet — the nearest of the cabinets whose mains cross it, ties to the lower cabinet index (user decision Q41, audit R4A-02; with building groups no house of the default grids of 10 to 200 houses and 58 of 1 000, with the former cabinet strip 1 of 50 and 3 of 150); a main that crosses a building it does not feed stays unjoined. A service drop taps its cabinet's cable at the point nearest to the building — the closest pair of cable and the building's horizontal wires, or the point nearest to the anchor of a building with rods only; a T-joint, or the substation / the cabinet at the cable's ends — never another building's drop, and leaves the main of another cabinet it would run along at that main's node (audit R4B-01); the rules are in groundfield.generators._pen_routing. Cabinet placement and count come from groundfield.generators.tn_network.CabinetConfig.

The JSON tag is kind="star_cabinet"; configurations written with the former tag "star_kvs" still load (with a DeprecationWarning).

group_buildings staticmethod

group_buildings(substation_xy: tuple[float, float], building_positions: list[tuple[float, float]], n_groups: int) -> list[list[int]]

Building groups of the cabinets: consecutive bearings, equal sizes.

The rule of the default cabinet placement (user decisions Q22 and Q35 of 2026.11): the buildings are ordered by their bearing \(\theta = \operatorname{atan2}(y - y_s, x - x_s)\) around the substation, counter-clockwise, starting after the widest angular gap between two neighbouring bearings (so that no group straddles an empty direction; ties to the gap that starts at the smaller bearing from the \(+x\) axis, gaps within \(10^{-9}\) rad tie), and cut into n_groups runs of consecutive buildings whose sizes differ by at most one (the first runs take the extra buildings). Buildings of equal bearing are ordered by their distance to the substation, then by index. In the default grid of 30 houses (three rows of ten, the substation in the middle row) the two groups are the western and the eastern half.

Parameters:

Name Type Description Default
substation_xy tuple[float, float]

Substation position in m.

required
building_positions list[tuple[float, float]]

Building positions in m (one per building, in index order).

required
n_groups int

Number of groups (cabinets), at least 1; at most one group per building.

required

Returns:

Type Description
list of lists of int

Building indices per group, each in bearing order; the groups in the order of their bearings.

Source code in src/groundfield/generators/pen_topology.py
@staticmethod
def group_buildings(
    substation_xy: tuple[float, float],
    building_positions: list[tuple[float, float]],
    n_groups: int,
) -> list[list[int]]:
    r"""Building groups of the cabinets: consecutive bearings, equal sizes.

    The rule of the default cabinet placement (user decisions Q22 and
    Q35 of 2026.11): the buildings are ordered by their bearing
    :math:`\theta = \operatorname{atan2}(y - y_s, x - x_s)` around the
    substation, counter-clockwise, starting after the widest angular gap
    between two neighbouring bearings (so that no group straddles an
    empty direction; ties to the gap that starts at the smaller bearing
    from the :math:`+x` axis, gaps within :math:`10^{-9}` rad tie), and
    cut into ``n_groups`` runs of consecutive buildings whose sizes differ
    by at most one (the first runs take the extra buildings). Buildings
    of equal bearing are ordered by their distance to the substation,
    then by index. In the default grid of 30 houses (three rows of ten,
    the substation in the middle row) the two groups are the western and
    the eastern half.

    Parameters
    ----------
    substation_xy
        Substation position in m.
    building_positions
        Building positions in m (one per building, in index order).
    n_groups
        Number of groups (cabinets), at least 1; at most one group per
        building.

    Returns
    -------
    list of lists of int
        Building indices per group, each in bearing order; the groups in
        the order of their bearings.
    """
    n = len(building_positions)
    if n == 0:
        return []
    n_groups = max(1, min(int(n_groups), n))
    sx, sy = substation_xy
    keyed = []
    for i, (bx, by) in enumerate(building_positions):
        dx, dy = float(bx) - sx, float(by) - sy
        bearing = math.atan2(dy, dx) if (dx or dy) else 0.0
        if bearing < 0.0:
            bearing += 2.0 * math.pi
        keyed.append((bearing, math.hypot(dx, dy), i))
    keyed.sort()
    bearings = [b for b, _, _ in keyed]
    gaps = [
        (bearings[(k + 1) % n] - bearings[k]) % (2.0 * math.pi) for k in range(n)
    ]
    if n == 1 or max(gaps) == 0.0:
        start = 0
    else:
        widest = max(gaps)
        first = next(k for k, g in enumerate(gaps) if g >= widest - 1e-9)
        start = (first + 1) % n
    order = [keyed[(start + k) % n][2] for k in range(n)]
    size, extra = divmod(n, n_groups)
    groups, at = [], 0
    for g in range(n_groups):
        take = size + (1 if g < extra else 0)
        groups.append(order[at : at + take])
        at += take
    return groups

StarKvsTopology

Bases: StarCabinetTopology

Deprecated alias of StarCabinetTopology.

StripElectrodeSpec

Bases: _ElectrodeSpecBase

Horizontal strip earth electrode (Banderder).

Straight buried wire of length length_m at depth depth_m, rotated by orientation_deg around the vertical axis (0° = +x).

SubstationConfig

Bases: GeneratorConfig

Substation block — position + grounding system.

Attributes:

Name Type Description
position tuple[float, float]

Substation centre (x, y) in m, in the local coordinates in which the generator builds the network. It moves the substation only: the buildings, cable cabinets and the measurement set-up are placed around (0, 0) whatever position is. A position at projected coordinates (UTM, Gauss-Krüger) therefore builds a world that mixes projected and local coordinates — with 10 houses at the UTM origin a PEN cable 33 118 km long — reported by diagnose() and warned about at the solve with MixedCoordinatesWarning (user decision D5), and RadialTrunkTopology drops every building and fails to build (audit W2R2-07). To place a network at projected coordinates, build it around the origin and translate the whole built world (every electrode, conductor and junction by the same offset); groundfield has no public helper for that. The solve does not need it: results depend on coordinate differences only.

grounding GroundingSystemSpec

Substation grounding system.

TnNetworkConfig

Bases: GeneratorConfig

Top-level configuration for a TN low-voltage distribution network.

Attributes:

Name Type Description
name str

World name.

soil SoilSpec

Soil-model spec — homogeneous, two-layer, or multi-layer (see SoilSpec).

substation SubstationConfig

Substation block (position + grounding system).

cabinets CabinetConfig

Cable-cabinet block (placement, count, grounding).

placement PlacementSpec

Building placement strategy. Default: Manhattan grid.

building_types list[BuildingTypeSpec]

Catalog of building types available in this run. Each type carries its own grounding system. Defaults to a four-type catalog (residential, small/medium/large industry).

building_counts dict[str, Union[int, AnyDistribution]]

Number of buildings per type. Keys must match a building_types[*].name. Values may be fixed or Distribution. Buildings are placed in catalog order.

pen PenConfig

PEN backbone configuration.

source_magnitude_a Union[float, AnyDistribution]

Driving current at the substation cluster, in A.

kvs property

kvs: CabinetConfig

Deprecated alias of cabinets.

source_magnitude_A property

source_magnitude_A: Union[float, Distribution]

Deprecated alias of source_magnitude_a.

TnNetworkGenerator

TnNetworkGenerator(cfg: C, *, seed: Optional[Union[int, Generator]] = None)

Bases: WorldGenerator[TnNetworkConfig]

Generator for TN low-voltage distribution network reference worlds.

See the module docstring for the full pipeline. In one sentence: resolve soil → substation grounding → place buildings (one per type-and-count) → per-building grounding → cable cabinets → wire the PEN backbone → measurement set-up → source, as a NetworkPlan (plan()), then materialise the plan (build()).

Source code in src/groundfield/generators/base.py
def __init__(
    self,
    cfg: C,
    *,
    seed: Optional[Union[int, np.random.Generator]] = None,
) -> None:
    if not isinstance(cfg, GeneratorConfig):
        raise TypeError(f"cfg must be a GeneratorConfig, got {type(cfg).__name__}.")
    self.cfg = cfg
    self._rng = _coerce_rng(seed)

build

build(cfg: Optional[TnNetworkConfig] = None, *, rng: Optional[Union[int, Generator]] = None) -> World

Materialise one realisation of the configured TN network.

Equivalent to materialise_plan(self.plan(cfg, rng=rng)), with one exception: right after plan() on this generator — without rng in either call, nothing drawn from the generator's RNG since and the same configuration — it materialises the plan that plan() returned (once; the next call draws the next realisation). Before, it drew a second realisation, which differs from the plan with placement jitter or other per-site randomness (audit W3R2B).

Parameters:

Name Type Description Default
cfg TnNetworkConfig

Configuration overriding cfg. When None (default) the generator's own cfg is used.

None
rng int or Generator

Draw the realisation from this seed / generator instead of the generator's own RNG.

None

Returns:

Type Description
World

The assembled world with soil, electrodes, conductors and the configured source.

Raises:

Type Description
ValueError

If the substation grounding resolves to zero electrodes, if the total building count is zero, or if a configured placement returns fewer positions than buildings.

Source code in src/groundfield/generators/tn_network.py
def build(
    self,
    cfg: Optional[TnNetworkConfig] = None,
    *,
    rng: Optional[Union[int, np.random.Generator]] = None,
) -> World:
    """Materialise one realisation of the configured TN network.

    Equivalent to ``materialise_plan(self.plan(cfg, rng=rng))``, with
    one exception: right after :meth:`plan` on this generator — without
    ``rng`` in either call, nothing drawn from the generator's RNG since
    and the same configuration — it materialises the plan that
    :meth:`plan` returned (once; the next call draws the next
    realisation). Before, it drew a second realisation, which differs
    from the plan with placement jitter or other per-site randomness
    (audit W3R2B).

    Parameters
    ----------
    cfg : TnNetworkConfig, optional
        Configuration overriding :attr:`cfg`. When ``None``
        (default) the generator's own ``cfg`` is used.
    rng : int or numpy.random.Generator, optional
        Draw the realisation from this seed / generator instead of
        the generator's own RNG.

    Returns
    -------
    World
        The assembled world with soil, electrodes, conductors and
        the configured source.

    Raises
    ------
    ValueError
        If the substation grounding resolves to zero electrodes,
        if the total building count is zero, or if a configured
        placement returns fewer positions than buildings.
    """
    planned = self._take_last_plan(cfg) if rng is None else None
    if planned is None:
        planned = self.plan(cfg, rng=rng)
        if rng is None:
            # a plan nobody has seen: the next build() draws anew
            self._last_plan = None
    return materialise_plan(planned)

plan

plan(cfg: Optional[TnNetworkConfig] = None, *, rng: Optional[Union[int, Generator]] = None) -> NetworkPlan

Resolve one realisation into a NetworkPlan.

Every random decision is made here, against rng (default: the generator's RNG), in a fixed order: soil, substation grounding, building counts, building positions, per-building grounding, cable cabinets (count, positions, groundings), measurement electrodes and leads, source magnitude. Materialising the returned plan draws no further random numbers. A plan drawn from the generator's RNG is remembered (a copy): build() right after it gives its world (audit W3R2B).

Parameters:

Name Type Description Default
cfg TnNetworkConfig

Configuration overriding cfg.

None
rng int or Generator

Seed / generator of the random draws (default: the generator's own RNG).

None

Returns:

Type Description
NetworkPlan

The concrete network.

Raises:

Type Description
ValueError

See build().

Source code in src/groundfield/generators/tn_network.py
def plan(
    self,
    cfg: Optional[TnNetworkConfig] = None,
    *,
    rng: Optional[Union[int, np.random.Generator]] = None,
) -> NetworkPlan:
    """Resolve one realisation into a :class:`NetworkPlan`.

    Every random decision is made here, against ``rng`` (default:
    the generator's RNG), in a fixed order: soil, substation grounding, building
    counts, building positions, per-building grounding, cable
    cabinets (count, positions, groundings), measurement electrodes
    and leads, source magnitude. Materialising the returned plan
    draws no further random numbers. A plan drawn from the generator's
    RNG is remembered (a copy): :meth:`build` right after it gives its
    world (audit W3R2B).

    Parameters
    ----------
    cfg : TnNetworkConfig, optional
        Configuration overriding :attr:`cfg`.
    rng : int or numpy.random.Generator, optional
        Seed / generator of the random draws (default: the
        generator's own RNG).

    Returns
    -------
    NetworkPlan
        The concrete network.

    Raises
    ------
    ValueError
        See :meth:`build`.
    """
    cfg = cfg or self.cfg
    own_stream = rng is None
    rng = self._rng if rng is None else _coerce_rng(rng)

    soil = materialise_soil(cfg.soil, rng)

    substation = cfg.substation.grounding.plan_site(
        "trafo", role="substation", position_xy=cfg.substation.position, rng=rng
    )
    if substation.anchor is None:
        raise ValueError(
            "TnNetworkGenerator: substation grounding produced zero "
            "electrodes. At least one electrode must have presence_prob > 0."
        )
    sites: list[PlannedSite] = [substation]

    # --- Buildings ---
    building_assignments = self._resolve_building_counts(cfg, rng)
    n_buildings = sum(count for _, count in building_assignments)
    if n_buildings < 1:
        raise ValueError(
            "TnNetworkGenerator: total building count is 0. Populate "
            "building_counts with at least one type."
        )
    positions = cfg.placement.generate(n_buildings, rng)
    if len(positions) != n_buildings:
        raise RuntimeError(
            f"placement.generate returned {len(positions)} positions, "
            f"expected {n_buildings}."
        )
    # Footprint-aware placement (ADR-0011): a placement with a
    # ``footprint_at(i)`` hook (currently :class:`OsmBuildingPlacement`)
    # shapes every foundation of the building after the footprint
    # (``GroundingSystemSpec.with_footprint``, OMBR rule).
    has_footprints = hasattr(cfg.placement, "footprint_at")
    buildings: list[PlannedSite] = []
    idx = 0
    for btype, count in building_assignments:
        for k in range(count):
            site_xy = positions[idx]
            grounding = btype.grounding
            footprint = cfg.placement.footprint_at(idx) if has_footprints else None
            if footprint is not None:
                grounding = grounding.with_footprint(
                    footprint, site_xy=site_xy, outline="ombr"
                )
            buildings.append(
                grounding.plan_site(
                    f"{btype.name}_{k}",
                    role="building",
                    position_xy=site_xy,
                    rng=rng,
                    footprint=footprint,
                    building_type=btype.name,
                )
            )
            idx += 1
    sites.extend(buildings)
    if not any(b.anchor is not None for b in buildings):
        raise ValueError(
            "TnNetworkGenerator: every building's grounding had zero "
            "present electrodes. Increase presence_prob."
        )

    # --- Cable cabinets + PEN backbone ---
    branches: list[PlannedBranch] = []
    junctions: list[PlannedJunction] = []
    if isinstance(cfg.pen_topology, RadialTrunkTopology):
        self._plan_radial_trunk(
            cfg, substation, buildings, sites, branches, junctions, rng
        )
    else:
        n_cabinets = self._resolve_cabinet_count(cfg, n_buildings, rng)
        groups: Optional[list[list[PlannedSite]]] = None
        geometry: dict[str, SiteGeometry] = {}
        cabinets: list[PlannedSite]
        if cfg.cabinets.placement is not None:
            cabinets = [
                cfg.cabinets.grounding.plan_site(
                    f"kvs_{k}", role="cabinet", position_xy=site_xy, rng=rng
                )
                for k, site_xy in enumerate(
                    cfg.cabinets.placement.generate(n_cabinets, rng)
                )
            ]
        else:
            # One cabinet per building group, at the far end of the
            # houses it feeds (user decisions Q22, Q35).
            geometry = {
                site.name: _site_geometry(site) for site in [substation, *buildings]
            }
            groups, cabinets = self._group_cabinets(
                cfg, substation, buildings, n_cabinets, geometry, rng
            )
        sites.extend(cabinets)
        if not any(c.anchor is not None for c in cabinets):
            raise ValueError(
                "TnNetworkGenerator: every cable-cabinet grounding had zero "
                "present electrodes. Increase presence_prob or set "
                "fixed_count > 0."
            )
        self._plan_star_backbone(
            cfg,
            substation,
            cabinets,
            buildings,
            branches,
            junctions,
            groups=groups,
            geometry=geometry,
        )

    # --- Optional measurement set-up ---
    measurement = self._plan_measurement(cfg, substation, rng)

    # --- Source ---
    # With a measurement set-up the source is the earth tester: it
    # drives the test current between the substation (terminal E)
    # and the end of the current loop — the terminal H of the feed
    # lead, or the auxiliary electrode itself without a feed lead.
    # ``cfg.source_return_to`` is the explicit override of the
    # source's ``return_to``; warn when it shadows that terminal.
    return_to: Optional[str] = None
    loop_end: Optional[str] = None
    if measurement is not None:
        if measurement.feed_lead is not None:
            return_to = loop_end = MEASUREMENT_H_TERMINAL
        else:
            return_to = measurement.auxiliary.name
            loop_end = measurement.auxiliary.anchor
    if cfg.source_return_to is not None:
        if loop_end is not None and cfg.source_return_to != loop_end:
            warnings.warn(
                "TnNetworkConfig.source_return_to="
                f"{cfg.source_return_to!r} takes precedence over "
                "the measurement-setup return terminal "
                f"({loop_end!r}). The aux electrode and any "
                "metallic feed/probe leads remain in the world, "
                "but the source's return current is routed to "
                "the user-supplied electrode instead.",
                UserWarning,
                stacklevel=3,
            )
        return_to = cfg.source_return_to
    source = PlannedSource(
        attached_to=substation.name,
        return_to=return_to,
        kind=cfg.source_kind,
        magnitude=_to_float(cfg.source_magnitude_a, rng),
    )
    plan = NetworkPlan(
        name=cfg.name,
        soil=soil,
        sites=sites,
        junctions=junctions,
        branches=branches,
        measurement=measurement,
        sources=[source],
    )
    if own_stream:
        # build() right after this call materialises this plan instead
        # of drawing another realisation (audit W3R2B); copies, so that
        # changing the returned plan or the configuration in place
        # cannot change what build() gives
        self._last_plan = (
            rng,
            rng.bit_generator.state,
            cfg.model_copy(deep=True),
            plan.model_copy(deep=True),
        )
    return plan

TwoLayerSoilSpec

Bases: PickleUpgrade, BaseModel

Two-layer model — the default.

Upper layer of resistivity \(\rho_1\) and thickness \(h_1\) over a semi-infinite lower layer of resistivity \(\rho_2\).

to_soil

to_soil(rng: Generator) -> TwoLayerSoil

Draw the distributions and return the soil model.

A non-default relative_permittivity warns with InertConfigurationWarning (no backend reads it).

Source code in src/groundfield/generators/soil_specs.py
def to_soil(self, rng: np.random.Generator) -> TwoLayerSoil:
    """Draw the distributions and return the soil model.

    A non-default ``relative_permittivity`` warns with
    :class:`~groundfield.utils.InertConfigurationWarning` (no backend
    reads it).
    """
    _warn_inert_permittivity(type(self).__name__, [self.relative_permittivity])
    return TwoLayerSoil(
        rho_1=_to_float(self.rho_1, rng),
        rho_2=_to_float(self.rho_2, rng),
        h_1=_to_float(self.h_1, rng),
        relative_permittivity=self.relative_permittivity,
    )

Uniform

Bases: Distribution

Continuous uniform on \([\text{low}, \text{high})\).

The bounds are stored as Pydantic fields low and high; the model validator enforces high > low.

sample

sample(rng: Generator) -> float

Draw one sample from the interval [low, high).

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
float

One uniform draw.

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Draw one sample from the interval ``[low, high)``.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    float
        One uniform draw.
    """
    return float(rng.uniform(self.low, self.high))

VoltageProbePlacement

Bases: BaseModel

Voltage probe (Spannungssonde) used during the simulated fall-of-potential measurement.

Unlike the AuxiliaryElectrodePlacement, the probe is modelled as a pure sampling point in 3-D space: an ideal voltmeter has infinite input impedance, so a physical probe rod would carry zero current and therefore must not perturb the engine's potential field. In LvNetworkLayout.to_world() no rod electrode is created for the probe; in LvNetworkLayout.measured_grounding_impedance() the field is sampled at position_xy via FieldResult.potential().

Weibull

Bases: Distribution

Weibull distribution with shape \(k\) and scale \(\lambda\).

pdf \(f(x) = (k/\lambda)\,(x/\lambda)^{k-1}\,e^{-(x/\lambda)^k}\) on \(x \ge 0\). NumPy's rng.weibull(k) returns a sample from the Weibull with scale 1; we multiply by scale to obtain the desired scale parameter.

sample

sample(rng: Generator) -> float

Draw one sample with shape shape and scale scale.

Parameters:

Name Type Description Default
rng Generator

Random number generator that supplies the draw.

required

Returns:

Type Description
float

One Weibull draw (non-negative).

Source code in src/groundfield/generators/distributions.py
def sample(self, rng: np.random.Generator) -> float:
    """Draw one sample with shape ``shape`` and scale ``scale``.

    Parameters
    ----------
    rng : numpy.random.Generator
        Random number generator that supplies the draw.

    Returns
    -------
    float
        One Weibull draw (non-negative).
    """
    return float(self.scale * rng.weibull(self.shape))

WorldGenerator

WorldGenerator(cfg: C, *, seed: Optional[Union[int, Generator]] = None)

Bases: Generic[C]

Abstract base for World-producing generators.

Subclasses parameterise themselves on a concrete GeneratorConfig subclass C and implement build(), which constructs a World from a resolved config (one with no remaining Distribution fields).

The base class supplies:

  • RNG wiring via the seed constructor argument;
  • sample_world() that resolves any distributions and hands the resolved config to build();
  • a guard in _assert_resolved() that surfaces a clear error if build() is called with an unresolved config.

Parameters:

Name Type Description Default
cfg GeneratorConfig

Configuration of the generator; may still contain Distribution fields, which sample_world() resolves.

required
seed int or Generator

Seed or generator of the random draws. None (default) draws a fresh, unseeded generator; an int seeds a new generator; a Generator is used as it is.

None

Raises:

Type Description
TypeError

If cfg is not a GeneratorConfig or seed is neither None, an integer nor a numpy.random.Generator.

Source code in src/groundfield/generators/base.py
def __init__(
    self,
    cfg: C,
    *,
    seed: Optional[Union[int, np.random.Generator]] = None,
) -> None:
    if not isinstance(cfg, GeneratorConfig):
        raise TypeError(f"cfg must be a GeneratorConfig, got {type(cfg).__name__}.")
    self.cfg = cfg
    self._rng = _coerce_rng(seed)

rng property

rng: Generator

The generator's numpy.random.Generator.

build abstractmethod

build(cfg: Optional[C] = None) -> World

Build a World from a resolved config.

Subclasses must implement this method. They may assume that cfg (or self.cfg if cfg is None) has no remaining Distribution fields and may call _assert_resolved() defensively.

Parameters:

Name Type Description Default
cfg Optional[C]

Optional override for self.cfg. Useful in sweeps that compute many resolved configs upfront and feed them into the same generator instance.

None
Source code in src/groundfield/generators/base.py
@abstractmethod
def build(self, cfg: Optional[C] = None) -> World:
    """Build a :class:`World` from a *resolved* config.

    Subclasses must implement this method. They may assume that
    ``cfg`` (or ``self.cfg`` if ``cfg is None``) has no remaining
    :class:`Distribution` fields and may call
    :meth:`_assert_resolved` defensively.

    Parameters
    ----------
    cfg
        Optional override for ``self.cfg``. Useful in sweeps that
        compute many resolved configs upfront and feed them into
        the same generator instance.
    """

sample_world

sample_world(rng: Optional[Union[int, Generator]] = None) -> tuple[World, C]

Resolve any distributions in self.cfg and build a world.

Parameters:

Name Type Description Default
rng Optional[Union[int, Generator]]

Optional seed or generator. When given, every random number of the realisation is drawn from it: first the config resolution, then the per-site draws of the build (presence Bernoullis, placement jitter). The generator's construction seed then has no influence. None uses the generator's own RNG (self.rng) for both.

None

Returns:

Type Description
tuple[World, GeneratorConfig]

The constructed world and the resolved config (same type as self.cfg, without distributions).

Notes

Reproducing a realisation: sample_world(rng=seed) with the same config and seed always gives the same world. The resolved config alone replays the world bit-exactly with any seed when it has no per-site randomness (every presence_prob 0 or 1, no placement jitter); otherwise persist the seed, or the network plan / world JSON.

Source code in src/groundfield/generators/base.py
def sample_world(
    self,
    rng: Optional[Union[int, np.random.Generator]] = None,
) -> tuple[World, C]:
    """Resolve any distributions in ``self.cfg`` and build a world.

    Parameters
    ----------
    rng
        Optional seed or generator. When given, **every** random
        number of the realisation is drawn from it: first the config
        resolution, then the per-site draws of the build (presence
        Bernoullis, placement jitter). The generator's construction
        seed then has no influence. ``None`` uses the generator's own
        RNG (``self.rng``) for both.

    Returns
    -------
    tuple[World, GeneratorConfig]
        The constructed world and the resolved config (same type
        as ``self.cfg``, without distributions).

    Notes
    -----
    Reproducing a realisation: ``sample_world(rng=seed)`` with the
    same config and seed always gives the same world. The resolved
    config alone replays the world bit-exactly with any seed when it
    has no per-site randomness (every ``presence_prob`` 0 or 1, no
    placement jitter); otherwise persist the seed, or the network
    plan / world JSON.
    """
    rng_obj = self._rng if rng is None else _coerce_rng(rng)
    resolved = self.cfg.sample(rng_obj)
    # ``build`` draws from ``self._rng``; route it to ``rng_obj`` for
    # this call (also works for subclasses whose ``build`` has no
    # ``rng`` parameter).
    saved = self._rng
    self._rng = rng_obj
    try:
        world = self.build(resolved)
    finally:
        self._rng = saved
    return world, resolved

buried_lead

buried_lead(*, depth_m: float = 0.6, wire_radius_m: float = 0.005, inductance_model: Optional[str] = 'neumann', segment_length_m: Optional[float] = 5.0) -> MeasurementLeadConfig

Convenience factory for a buried-cable measurement lead.

Default depth 0.6 m (typical NS cable trench). Insulated cable (no soil leakage along the lead), Neumann inductance enabled.

The lead is built as a cable shield (conductor_type="cable_shield", user decisions Q32 and Q33 of 2026.11): a thin-walled tube, so its self inductance carries no internal inductance of a solid wire, μ₀/(8π) = 50 nH/m less than the same lead as a solid wire (a 150 m lead: 7.5 µH, 2.4 mΩ of reactance at 50 Hz), and a thinner conductor drawn on its axis is read as its core, coupled at the lead radius (a filament inside a tube). Its skin effect is not modelled (resistance_model="skin" is rejected for a shield). For a lead that is a solid wire, build a MeasurementLeadConfig with conductor_type="bare_copper".

Parameters:

Name Type Description Default
depth_m float

Depth of the lead axis in m (positive into the soil).

0.6
wire_radius_m float

Radius of the lead in m.

0.005
inductance_model Optional[str]

"neumann" (default) or None for a resistive lead.

'neumann'
segment_length_m Optional[float]

Sub-piece length in m; None keeps the lead lumped.

5.0

Returns:

Type Description
MeasurementLeadConfig

The lead configuration.

Source code in src/groundfield/generators/measurement.py
def buried_lead(
    *,
    depth_m: float = 0.6,
    wire_radius_m: float = 0.005,
    inductance_model: Optional[str] = "neumann",
    segment_length_m: Optional[float] = 5.0,
) -> MeasurementLeadConfig:
    """Convenience factory for a buried-cable measurement lead.

    Default depth 0.6 m (typical NS cable trench). Insulated cable
    (no soil leakage along the lead), Neumann inductance enabled.

    The lead is built as a cable shield (``conductor_type="cable_shield"``,
    user decisions Q32 and Q33 of 2026.11): a thin-walled tube, so its self
    inductance carries no internal inductance of a solid wire,
    μ₀/(8π) = 50 nH/m less than the same lead as a solid
    wire (a 150 m lead: 7.5 µH, 2.4 mΩ of reactance at 50 Hz), and a
    thinner conductor drawn on its axis is read as its core, coupled at the
    lead radius (a filament inside a tube). Its skin effect is not modelled
    (``resistance_model="skin"`` is rejected for a shield). For a lead that
    is a solid wire, build a :class:`MeasurementLeadConfig` with
    ``conductor_type="bare_copper"``.

    Parameters
    ----------
    depth_m
        Depth of the lead axis in m (positive into the soil).
    wire_radius_m
        Radius of the lead in m.
    inductance_model
        ``"neumann"`` (default) or ``None`` for a resistive lead.
    segment_length_m
        Sub-piece length in m; ``None`` keeps the lead lumped.

    Returns
    -------
    MeasurementLeadConfig
        The lead configuration.
    """
    return MeasurementLeadConfig(
        depth_m=depth_m,
        wire_radius_m=wire_radius_m,
        conductor_type="cable_shield",
        coupling_to_soil="isolated",
        segment_length_m=segment_length_m,
        inductance_model=inductance_model,
    )

default_building_catalog

default_building_catalog() -> list[BuildingTypeSpec]

Return a sensible starting catalog of four building types.

Returns:

Type Description
list[BuildingTypeSpec]

Four entries: residential, small_industry, medium_industry, large_industry. Geometries follow rough European-LV practice; tune via copy + edit before running serious studies.

Source code in src/groundfield/generators/building.py
def default_building_catalog() -> list[BuildingTypeSpec]:
    """Return a sensible starting catalog of four building types.

    Returns
    -------
    list[BuildingTypeSpec]
        Four entries: ``residential``, ``small_industry``,
        ``medium_industry``, ``large_industry``. Geometries follow
        rough European-LV practice; tune via copy + edit before
        running serious studies.
    """
    return [
        BuildingTypeSpec(
            name="residential",
            description="Single-family house — foundation electrode only.",
            plot_size_m=(15.0, 15.0),
            grounding=GroundingSystemSpec(
                electrodes=[
                    FoundationElectrodeSpec(
                        size_m=10.0,
                        depth_m=0.8,
                        n_x=2,
                        n_y=2,
                    ),
                ],
            ),
        ),
        BuildingTypeSpec(
            name="small_industry",
            description="Small commercial — foundation plus one driven rod.",
            plot_size_m=(20.0, 20.0),
            grounding=GroundingSystemSpec(
                electrodes=[
                    FoundationElectrodeSpec(
                        size_m=12.0,
                        depth_m=0.8,
                        n_x=2,
                        n_y=2,
                    ),
                    RodElectrodeSpec(
                        length_m=2.0,
                        depth_m=0.0,
                        offset_xy_m=(7.0, 0.0),
                    ),
                ],
            ),
        ),
        BuildingTypeSpec(
            name="medium_industry",
            description="Medium commercial — larger foundation plus four rods.",
            plot_size_m=(30.0, 30.0),
            grounding=GroundingSystemSpec(
                electrodes=[
                    FoundationElectrodeSpec(
                        size_m=20.0,
                        depth_m=0.8,
                        n_x=3,
                        n_y=3,
                    ),
                    *rod_circle(n=4, radius_m=12.0, length_m=2.5),
                ],
            ),
        ),
        BuildingTypeSpec(
            name="large_industry",
            description=(
                "Large industrial site — perimeter ring, internal grid mesh, "
                "and eight driven rods spaced around the ring."
            ),
            plot_size_m=(60.0, 60.0),
            grounding=GroundingSystemSpec(
                electrodes=[
                    RingElectrodeSpec(radius_m=25.0, depth_m=0.8),
                    FoundationElectrodeSpec(
                        size_m=30.0,
                        depth_m=0.8,
                        n_x=4,
                        n_y=4,
                    ),
                    *rod_circle(n=8, radius_m=25.0, length_m=3.0),
                    StripElectrodeSpec(
                        length_m=40.0,
                        depth_m=0.8,
                        orientation_deg=0.0,
                        offset_xy_m=(0.0, 28.0),
                    ),
                    StripElectrodeSpec(
                        length_m=40.0,
                        depth_m=0.8,
                        orientation_deg=0.0,
                        offset_xy_m=(0.0, -28.0),
                    ),
                ],
            ),
        ),
    ]

materialise_plan

materialise_plan(plan: NetworkPlan) -> World

Build the World described by plan.

Parameters:

Name Type Description Default
plan NetworkPlan

A concrete network plan.

required

Returns:

Type Description
World

The world, ready for world.solve(engine).

Notes

Construction order: sites, measurement sites, junctions, instrument terminals, branches, measurement leads, sources (each in plan order). No random numbers are drawn, so the same plan always gives the same world.

Source code in src/groundfield/generators/materialise.py
def materialise_plan(plan: NetworkPlan) -> World:
    """Build the :class:`~groundfield.World` described by ``plan``.

    Parameters
    ----------
    plan
        A concrete network plan.

    Returns
    -------
    World
        The world, ready for ``world.solve(engine)``.

    Notes
    -----
    Construction order: sites, measurement sites, junctions, instrument
    terminals, branches, measurement leads, sources (each in plan order).
    No random numbers are drawn, so the same plan always gives the same
    world.
    """
    world = create_world(name=plan.name, soil=plan.soil)
    nodes: dict[str, str] = {}
    foundation_wires: dict[str, set[str]] = {}
    for site in plan.all_sites:
        anchor, foundation_wires[site.name] = _materialise_site(world, site)
        if anchor is not None:
            nodes[site.name] = anchor
    for junction in plan.all_junctions:
        nodes[junction.name] = materialise_junction(world, junction)
    index: dict[str, Any] = {e.name: e for e in world.electrodes}
    index.update((j.name, j) for j in world.junctions)
    for branch in plan.all_branches:
        materialise_branch(
            world, branch, nodes, index=index, foundation_wires=foundation_wires
        )
    for source in plan.sources:
        kwargs: dict = {}
        if source.name is not None:
            kwargs["name"] = source.name
        create_source(
            world,
            attached_to=nodes.get(source.attached_to, source.attached_to),
            return_to=(
                None
                if source.return_to is None
                else nodes.get(source.return_to, source.return_to)
            ),
            kind=source.kind,
            magnitude=source.magnitude,
            phase_deg=source.phase_deg,
            **kwargs,
        )
    return world

materialise_soil

materialise_soil(spec: Union[HomogeneousSoilSpec, TwoLayerSoilSpec, MultiLayerSoilSpec], rng: Generator) -> SoilModel

Convenience dispatcher: spec.to_soil(rng).

Provided so callers can write materialise_soil(cfg.soil, rng) without having to discriminate by isinstance themselves.

Parameters:

Name Type Description Default
spec (HomogeneousSoilSpec, TwoLayerSoilSpec or MultiLayerSoilSpec)

Soil spec; its fields may be fixed values or distributions.

required
rng Generator

Random number generator for the draws of the distribution fields.

required

Returns:

Type Description
SoilModel

The concrete soil model (HomogeneousSoil, TwoLayerSoil or MultiLayerSoil).

Source code in src/groundfield/generators/soil_specs.py
def materialise_soil(
    spec: Union[HomogeneousSoilSpec, TwoLayerSoilSpec, MultiLayerSoilSpec],
    rng: np.random.Generator,
) -> SoilModel:
    """Convenience dispatcher: ``spec.to_soil(rng)``.

    Provided so callers can write ``materialise_soil(cfg.soil, rng)``
    without having to discriminate by ``isinstance`` themselves.

    Parameters
    ----------
    spec : HomogeneousSoilSpec, TwoLayerSoilSpec or MultiLayerSoilSpec
        Soil spec; its fields may be fixed values or distributions.
    rng : numpy.random.Generator
        Random number generator for the draws of the distribution
        fields.

    Returns
    -------
    SoilModel
        The concrete soil model (:class:`~groundfield.HomogeneousSoil`,
        :class:`~groundfield.TwoLayerSoil` or
        :class:`~groundfield.MultiLayerSoil`).
    """
    return spec.to_soil(rng)

measured_impedance

measured_impedance(result: 'FieldResult', probe: Optional[str] = None, *, source: Optional[str] = None) -> list[complex]

Reading of a simulated fall-of-potential measurement.

\[ Z_\text{meas}(f) = \frac{\varphi_E(f) - \varphi_S(f)}{I(f)} \]

with \(\varphi_E\) the potential of the earthing system the test current is fed into (the galvanic cluster of the source's attached_to node, length-weighted as in input_impedance()), \(\varphi_S\) the potential of the voltage terminal and \(I\) the source current. This is the three-pole reading of an earth tester. The two-pole reading, the voltage across the current source (terminals E and H) over \(I\), is input_impedance().

The source is the current source of the measurement or, since 2026.11, a voltage source (audit W2A-10): \(I\) is then its solved current, and the reading is the same as with a current source at the same terminals (the problem is linear; an internal impedance of the source changes \(I\), not the reading).

Parameters:

Name Type Description Default
result 'FieldResult'

Solved result of a world with a current or voltage source.

required
probe Optional[str]

Node the voltmeter reads against the earthing system: the name of a junction or of an electrode (an electrode stands for its galvanic cluster). Default: the instrument terminal MEASUREMENT_S_TERMINAL when the result has it (a network built with a probe lead), else the voltage-probe electrode (probe_<kind>_<i>) of a TnNetworkGenerator network.

None
source Optional[str]

Name of the measurement's source. Omitted, the reading takes the result's single current source, or, when it has no current source, its single voltage source (audit W2R2-05: a result with one current source and voltage sources besides reads the current source, as up to 2026.11); several current sources, or several voltage sources and no current source, need the name.

None

Returns:

Type Description
list of complex

\(Z_\text{meas}\) in Ω per frequency (nan where the source current is zero).

Raises:

Type Description
ValueError

If the result carries no source snapshot (hand-built results), no current or voltage source, or, with source omitted, several current sources or no current and several voltage sources; if the record of the source carries no current per frequency (a voltage record without its solved current); if no probe is given and none can be found.

KeyError

If source or probe is unknown.

Notes

With metallic leads (MeasurementInjectionConfig.feed_lead, MeasurementProbeConfig.lead) the voltage terminal carries the voltage induced in the probe lead by the feed loop and the other conductors (inductive coupling, ADR-0004); without a probe lead the reading is the galvanic one. A non-inductive lead does not change the reading: the feed lead is in series with an ideal current source and the probe lead carries no current.

Source code in src/groundfield/generators/measurement.py
def measured_impedance(
    result: "FieldResult",
    probe: Optional[str] = None,
    *,
    source: Optional[str] = None,
) -> list[complex]:
    r"""Reading of a simulated fall-of-potential measurement.

    .. math::

       Z_\text{meas}(f) = \frac{\varphi_E(f) - \varphi_S(f)}{I(f)}

    with :math:`\varphi_E` the potential of the earthing system the test
    current is fed into (the galvanic cluster of the source's
    ``attached_to`` node, length-weighted as in
    :meth:`~groundfield.solver.result.FieldResult.input_impedance`),
    :math:`\varphi_S` the potential of the voltage terminal and :math:`I`
    the source current. This is the three-pole reading of an earth
    tester. The two-pole reading, the voltage across the current source
    (terminals E and H) over :math:`I`, is
    :meth:`~groundfield.solver.result.FieldResult.input_impedance`.

    The source is the current source of the measurement or, since
    2026.11, a voltage source (audit W2A-10): :math:`I` is then its solved
    current, and the reading is the same as with a current source at the
    same terminals (the problem is linear; an internal impedance of the
    source changes :math:`I`, not the reading).

    Parameters
    ----------
    result
        Solved result of a world with a current or voltage source.
    probe
        Node the voltmeter reads against the earthing system: the name of
        a junction or of an electrode (an electrode stands for its
        galvanic cluster). Default: the instrument terminal
        :data:`MEASUREMENT_S_TERMINAL` when the result has it (a network
        built with a probe lead), else the voltage-probe electrode
        (``probe_<kind>_<i>``) of a
        :class:`~groundfield.generators.tn_network.TnNetworkGenerator`
        network.
    source
        Name of the measurement's source. Omitted, the reading takes the
        result's single current source, or, when it has no current
        source, its single voltage source (audit W2R2-05: a result with
        one current source and voltage sources besides reads the current
        source, as up to 2026.11); several current sources, or several
        voltage sources and no current source, need the name.

    Returns
    -------
    list of complex
        :math:`Z_\text{meas}` in Ω per frequency (``nan`` where the source
        current is zero).

    Raises
    ------
    ValueError
        If the result carries no source snapshot (hand-built results), no
        current or voltage source, or, with ``source`` omitted, several
        current sources or no current and several voltage sources;
        if the record of the source carries no current per frequency (a
        voltage record without its solved current); if no probe is given
        and none can be found.
    KeyError
        If ``source`` or ``probe`` is unknown.

    Notes
    -----
    With metallic leads (:attr:`MeasurementInjectionConfig.feed_lead`,
    :attr:`MeasurementProbeConfig.lead`) the voltage terminal carries the
    voltage induced in the probe lead by the feed loop and the other
    conductors (inductive coupling, ADR-0004); without a probe lead the
    reading is the galvanic one. A non-inductive lead does not change the
    reading: the feed lead is in series with an ideal current source and
    the probe lead carries no current.
    """
    if not result.sources:
        raise ValueError(
            "measured_impedance needs the source snapshot of the solve; this "
            "result carries none (hand-built FieldResult?)."
        )
    if source is None:
        record = _measurement_record(result.sources)
    else:
        by_name = {s.name: s for s in result.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 reading is "
                "defined for the current or voltage source of the measurement."
            )
    n_freq = len(result.frequencies)
    if len(record.current) != n_freq:
        # A voltage record without its solved current (audit W2A-10).
        raise ValueError(
            f"{record.kind.capitalize()} source {record.name!r}: the result "
            "carries no solved source current (the backend did not report "
            f"it), or not one per frequency ({len(record.current)} currents, "
            f"{n_freq} frequencies)."
        )
    if probe is None:
        probe = _default_probe(result)
    u_e = _node_potential(result, record.attached_to)
    u_s = _node_potential(result, probe)
    return [
        (ue - us) / ik if ik != 0 else complex("nan")
        for ue, us, ik in zip(u_e, u_s, record.current, strict=False)
    ]

merge_collinear_waypoints

merge_collinear_waypoints(waypoints: list[tuple[float, float]]) -> list[tuple[float, float]]

Drop interior waypoints that lie on the line of their neighbours.

The result keeps the polyline's geometric shape (every actual corner) but discards the artificial mid-cell stops that the A* search produced. Endpoints are always kept.

Parameters:

Name Type Description Default
waypoints list of tuple of float

Axis-aligned polyline as (x, y) points in m. A waypoint is dropped when the pieces before and after it run along the same axis in the same direction.

required

Returns:

Type Description
list of tuple of float

The reduced waypoint list; a copy of the input when it has fewer than three points.

Source code in src/groundfield/generators/manhattan_routing.py
def merge_collinear_waypoints(
    waypoints: list[tuple[float, float]],
) -> list[tuple[float, float]]:
    """Drop interior waypoints that lie on the line of their neighbours.

    The result keeps the polyline's geometric shape (every actual
    corner) but discards the artificial mid-cell stops that the
    A\\* search produced. Endpoints are always kept.

    Parameters
    ----------
    waypoints : list of tuple of float
        Axis-aligned polyline as ``(x, y)`` points in m. A waypoint is
        dropped when the pieces before and after it run along the same
        axis in the same direction.

    Returns
    -------
    list of tuple of float
        The reduced waypoint list; a copy of the input when it has
        fewer than three points.
    """
    if len(waypoints) < 3:
        return list(waypoints)
    out: list[tuple[float, float]] = [waypoints[0]]
    for i in range(1, len(waypoints) - 1):
        prev = out[-1]
        cur = waypoints[i]
        nxt = waypoints[i + 1]
        dx1, dy1 = cur[0] - prev[0], cur[1] - prev[1]
        dx2, dy2 = nxt[0] - cur[0], nxt[1] - cur[1]
        # Both segments must be along the same axis with the same sign
        # to be collinear and absorbable.
        same_x = math.isclose(dx1, 0.0) and math.isclose(dx2, 0.0)
        same_y = math.isclose(dy1, 0.0) and math.isclose(dy2, 0.0)
        if same_x and dy1 * dy2 > 0.0:
            continue
        if same_y and dx1 * dx2 > 0.0:
            continue
        out.append(cur)
    out.append(waypoints[-1])
    return out

neighbour_substation_grounding

neighbour_substation_grounding() -> GroundingSystemSpec

A neighbour substation's typical grounding (ring + 4 rods).

Used as the auxiliary electrode in measurements where the current returns through a remote, well-grounded substation instead of a single driven rod.

Returns:

Type Description
GroundingSystemSpec

A ring of radius 4 m at 0.6 m depth and four 2.5 m rods on a circle of radius 2 m (rod_circle()), bonded into one grounding system.

Source code in src/groundfield/generators/measurement.py
def neighbour_substation_grounding() -> GroundingSystemSpec:
    """A neighbour substation's typical grounding (ring + 4 rods).

    Used as the auxiliary electrode in measurements where the
    current returns through a remote, well-grounded substation
    instead of a single driven rod.

    Returns
    -------
    GroundingSystemSpec
        A ring of radius 4 m at 0.6 m depth and four 2.5 m rods on a
        circle of radius 2 m (:func:`rod_circle`), bonded into one
        grounding system.
    """
    # Imported here to avoid a top-level circular import:
    # tn_network depends on this module.
    from groundfield.generators.electrode_specs import (
        RingElectrodeSpec,
        rod_circle,
    )

    return GroundingSystemSpec(
        electrodes=[
            RingElectrodeSpec(radius_m=4.0, depth_m=0.6),
            *rod_circle(n=4, radius_m=2.0, length_m=2.5),
        ],
    )

overhead_lead

overhead_lead(*, wire_radius_m: float = 0.005, inductance_model: Optional[str] = 'neumann', segment_length_m: Optional[float] = 5.0) -> MeasurementLeadConfig

Convenience factory for an overhead bare-copper measurement lead.

Laid out on the ground (depth_m=0, modelled SURFACE_LEAD_HEIGHT_M above the surface), bare copper, isolated soil coupling, Neumann inductance enabled.

Parameters:

Name Type Description Default
wire_radius_m float

Radius of the lead in m.

0.005
inductance_model str or None

"neumann" or None for a resistive lead.

"neumann"
segment_length_m float or None

Sub-piece length in m; None keeps the lead lumped.

5.0

Returns:

Type Description
MeasurementLeadConfig

The lead configuration.

Source code in src/groundfield/generators/measurement.py
def overhead_lead(
    *,
    wire_radius_m: float = 0.005,
    inductance_model: Optional[str] = "neumann",
    segment_length_m: Optional[float] = 5.0,
) -> MeasurementLeadConfig:
    """Convenience factory for an overhead bare-copper measurement lead.

    Laid out on the ground (``depth_m=0``, modelled
    :data:`SURFACE_LEAD_HEIGHT_M` above the surface), bare copper,
    isolated soil coupling, Neumann inductance enabled.

    Parameters
    ----------
    wire_radius_m : float, default 0.005
        Radius of the lead in m.
    inductance_model : str or None, default "neumann"
        ``"neumann"`` or ``None`` for a resistive lead.
    segment_length_m : float or None, default 5.0
        Sub-piece length in m; ``None`` keeps the lead lumped.

    Returns
    -------
    MeasurementLeadConfig
        The lead configuration.
    """
    return MeasurementLeadConfig(
        depth_m=0.0,
        wire_radius_m=wire_radius_m,
        conductor_type="bare_copper",
        coupling_to_soil="isolated",
        segment_length_m=segment_length_m,
        inductance_model=inductance_model,
    )

resolve_value

resolve_value(value: Any, rng: Generator) -> Any

Resolve a T | Distribution field to a concrete value.

Parameters:

Name Type Description Default
value Any

Either a fixed Python value (passed through unchanged) or a Distribution instance (sampled via Distribution.sample()).

required
rng Generator

Random generator forwarded to Distribution.sample.

required

Returns:

Type Description
object

The fixed value, or one sample from the distribution.

Source code in src/groundfield/generators/base.py
def resolve_value(value: Any, rng: np.random.Generator) -> Any:
    """Resolve a ``T | Distribution`` field to a concrete value.

    Parameters
    ----------
    value
        Either a fixed Python value (passed through unchanged) or a
        :class:`Distribution` instance (sampled via
        :meth:`Distribution.sample`).
    rng
        Random generator forwarded to ``Distribution.sample``.

    Returns
    -------
    object
        The fixed value, or one sample from the distribution.
    """
    if isinstance(value, Distribution):
        return value.sample(rng)
    return value

rod_circle

rod_circle(n: int, radius_m: float, *, length_m: Union[float, AnyDistribution] = 1.5, depth_m: Union[float, AnyDistribution] = 0.0, wire_radius_m: float = 0.008, presence_prob: Union[float, AnyDistribution] = 1.0, angle_offset_deg: float = 0.0) -> list[RodElectrodeSpec]

Build n RodElectrodeSpec arranged on a circle.

Typical use case: the four (or eight) driven rods inside the substation ring earth electrode. Each rod's offset_xy_m is set so the rods sit at angles \(\theta_k = \text{angle\_offset} + 2\pi k / n\) on a circle of radius radius_m centred on the site.

Parameters:

Name Type Description Default
n int

Number of rods.

required
radius_m float

Circle radius in m.

required
length_m Union[float, AnyDistribution]

Forwarded to every RodElectrodeSpec. Each rod carries the same value (a single Distribution passed in is shared and resampled per rod by the build machinery — pass independent copies if you want independent draws).

1.5
depth_m Union[float, AnyDistribution]

Forwarded to every RodElectrodeSpec. Each rod carries the same value (a single Distribution passed in is shared and resampled per rod by the build machinery — pass independent copies if you want independent draws).

1.5
wire_radius_m Union[float, AnyDistribution]

Forwarded to every RodElectrodeSpec. Each rod carries the same value (a single Distribution passed in is shared and resampled per rod by the build machinery — pass independent copies if you want independent draws).

1.5
presence_prob Union[float, AnyDistribution]

Forwarded to every RodElectrodeSpec. Each rod carries the same value (a single Distribution passed in is shared and resampled per rod by the build machinery — pass independent copies if you want independent draws).

1.5
angle_offset_deg float

Phase offset in degrees so the first rod can be rotated from the +x axis.

0.0

Returns:

Type Description
list[RodElectrodeSpec]

Length n. Drop straight into a GroundingSystemSpec.electrodes list.

Raises:

Type Description
ValueError

If n < 1 or radius_m < 0.

Source code in src/groundfield/generators/electrode_specs.py
def rod_circle(
    n: int,
    radius_m: float,
    *,
    length_m: Union[float, AnyDistribution] = 1.5,
    depth_m: Union[float, AnyDistribution] = 0.0,
    wire_radius_m: float = 0.008,
    presence_prob: Union[float, AnyDistribution] = 1.0,
    angle_offset_deg: float = 0.0,
) -> list[RodElectrodeSpec]:
    """Build *n* :class:`RodElectrodeSpec` arranged on a circle.

    Typical use case: the four (or eight) driven rods inside the
    substation ring earth electrode. Each rod's ``offset_xy_m`` is
    set so the rods sit at angles
    $\\theta_k = \\text{angle\\_offset} + 2\\pi k / n$ on a circle
    of radius ``radius_m`` centred on the site.

    Parameters
    ----------
    n
        Number of rods.
    radius_m
        Circle radius in m.
    length_m, depth_m, wire_radius_m, presence_prob
        Forwarded to every :class:`RodElectrodeSpec`. Each rod
        carries the same value (a single :class:`Distribution`
        passed in is shared and *resampled per rod* by the build
        machinery — pass independent copies if you want
        independent draws).
    angle_offset_deg
        Phase offset in degrees so the first rod can be rotated
        from the +x axis.

    Returns
    -------
    list[RodElectrodeSpec]
        Length ``n``. Drop straight into a
        :class:`GroundingSystemSpec.electrodes` list.

    Raises
    ------
    ValueError
        If ``n < 1`` or ``radius_m < 0``.
    """
    if n < 1:
        raise ValueError(f"rod_circle: n must be >= 1, got {n}.")
    if radius_m < 0:
        raise ValueError(f"rod_circle: radius_m must be >= 0, got {radius_m}.")
    out: list[RodElectrodeSpec] = []
    for k in range(n):
        angle = math.radians(angle_offset_deg) + 2.0 * math.pi * k / n
        offset = (radius_m * math.cos(angle), radius_m * math.sin(angle))
        out.append(
            RodElectrodeSpec(
                length_m=length_m,
                depth_m=depth_m,
                wire_radius_m=wire_radius_m,
                presence_prob=presence_prob,
                offset_xy_m=offset,
            )
        )
    return out

route_manhattan

route_manhattan(start: tuple[float, float], end: tuple[float, float], obstacles: Iterable[ObstacleBox] = (), *, grid_size: float = 10.0, clearance_m: float = 0.5, escape_radius_m: Optional[float] = None, max_iterations: int = 200000) -> list[tuple[float, float]]

Route a Manhattan polyline from start to end.

Parameters:

Name Type Description Default
start tuple[float, float]

Endpoint coordinates in metres. The grid origin is locked to start so the first waypoint is exactly start; an axis-aligned bridge from the last grid cell to end is appended.

required
end tuple[float, float]

Endpoint coordinates in metres. The grid origin is locked to start so the first waypoint is exactly start; an axis-aligned bridge from the last grid cell to end is appended.

required
obstacles Iterable[ObstacleBox]

Building obstacle boxes the cable must avoid.

()
grid_size float

Cell size in metres. The minimum segment length of the returned polyline (after merging collinear segments) is at least grid_size() for any leg interior to the path; the trailing bridge may be shorter when end does not align with the grid.

10.0
clearance_m float

Additional padding around each obstacle. Defaults to 0.5 m so the cable keeps a small safety distance from every foundation wall.

0.5
escape_radius_m Optional[float]

Inside a disk of this radius around start and around end, obstacles are not enforced. This is the "release valve" for real-OSM layouts where the substation or a KVS lat/lon lands inside or very near a foundation polygon and every neighbouring grid cell would otherwise be blocked -- the cable physically has to exit the substation cubicle somehow, so allowing a short blind-spot around each anchor models reality and prevents spurious RuntimeError from A* exhausted. None (default) maps to grid_size (i.e. exactly one cell of slack around each anchor). Pass 0.0 to restore the strict pre-v0.7 behaviour, or a larger value when an anchor lands inside a dense city block.

The escape zone applies to the A* grid cells and to the trailing bridge from the last cell centre to end (since 0.15.0): a bridge segment whose two endpoints both lie inside one anchor's escape disk is exempt from obstacle testing, and any obstacle that contains an anchor is ignored by the bridge altogether — a cable whose endpoint is inside a foundation polygon cannot avoid that polygon, so enforcing it there would only turn a solvable route into a hard error. Before 0.15.0 the bridge ignored escape_radius_m entirely, so an end anchor inside a footprint raised regardless of how large the escape radius was set.

None
max_iterations int

Upper bound on the A* loop body. Increase for very large layouts (hundreds of obstacles spread across kilometres).

200000

Returns:

Type Description
list of (float, float)

Polyline waypoints. len(out) >= 2; the first entry is start and the last entry is end. Consecutive entries differ in exactly one coordinate (Manhattan).

Raises:

Type Description
RuntimeError

When no path exists (obstacle field encloses the substation or KVS), or when neither candidate bridge from the last grid cell to end clears the obstacles that the escape zone does not exempt.

Source code in src/groundfield/generators/manhattan_routing.py
def route_manhattan(
    start: tuple[float, float],
    end: tuple[float, float],
    obstacles: Iterable[ObstacleBox] = (),
    *,
    grid_size: float = 10.0,
    clearance_m: float = 0.5,
    escape_radius_m: Optional[float] = None,
    max_iterations: int = 200_000,
) -> list[tuple[float, float]]:
    r"""Route a Manhattan polyline from ``start`` to ``end``.

    Parameters
    ----------
    start, end
        Endpoint coordinates in metres. The grid origin is locked
        to ``start`` so the first waypoint is *exactly* ``start``;
        an axis-aligned bridge from the last grid cell to ``end``
        is appended.
    obstacles
        Building obstacle boxes the cable must avoid.
    grid_size
        Cell size in metres. The minimum segment length of the
        returned polyline (after merging collinear segments) is at
        least :func:`grid_size` for any leg interior to the path;
        the trailing bridge may be shorter when ``end`` does not
        align with the grid.
    clearance_m
        Additional padding around each obstacle. Defaults to
        ``0.5`` m so the cable keeps a small safety distance from
        every foundation wall.
    escape_radius_m
        Inside a disk of this radius around ``start`` *and* around
        ``end``, obstacles are *not* enforced. This is the "release
        valve" for real-OSM layouts where the substation or a KVS
        lat/lon lands inside or very near a foundation polygon and
        every neighbouring grid cell would otherwise be blocked --
        the cable physically has to exit the substation cubicle
        somehow, so allowing a short blind-spot around each anchor
        models reality and prevents spurious
        :class:`RuntimeError` from
        ``A* exhausted``. ``None`` (default) maps to
        ``grid_size`` (i.e. exactly one cell of slack around each
        anchor). Pass ``0.0`` to restore the strict pre-v0.7
        behaviour, or a larger value when an anchor lands inside a
        dense city block.

        The escape zone applies to the A\* grid cells *and* to the
        trailing bridge from the last cell centre to ``end`` (since
        0.15.0): a bridge segment whose two endpoints both lie
        inside one anchor's escape disk is exempt from obstacle
        testing, and any obstacle that *contains* an anchor is
        ignored by the bridge altogether — a cable whose endpoint
        is inside a foundation polygon cannot avoid that polygon,
        so enforcing it there would only turn a solvable route into
        a hard error. Before 0.15.0 the bridge ignored
        ``escape_radius_m`` entirely, so an ``end`` anchor inside a
        footprint raised regardless of how large the escape radius
        was set.
    max_iterations
        Upper bound on the A\* loop body. Increase for very large
        layouts (hundreds of obstacles spread across kilometres).

    Returns
    -------
    list of (float, float)
        Polyline waypoints. ``len(out) >= 2``; the first entry is
        ``start`` and the last entry is ``end``. Consecutive
        entries differ in exactly one coordinate (Manhattan).

    Raises
    ------
    RuntimeError
        When no path exists (obstacle field encloses the
        substation or KVS), or when neither candidate bridge from
        the last grid cell to ``end`` clears the obstacles that the
        escape zone does not exempt.
    """
    if grid_size <= 0.0:
        raise ValueError(
            f"route_manhattan: grid_size must be positive, got {grid_size}."
        )
    if escape_radius_m is None:
        escape_radius_m = grid_size
    if escape_radius_m < 0.0:
        raise ValueError(
            f"route_manhattan: escape_radius_m must be >= 0, got {escape_radius_m}."
        )

    obstacles = [o.inflated(clearance_m) for o in obstacles]

    # Grid origin locked to start so cell (0, 0) is exactly ``start``.
    ox, oy = start
    half = grid_size / 2.0

    # Bounding cells: include end and every obstacle, with margin.
    margin_cells = 3
    xs = (
        [start[0], end[0]] + [o.x_min for o in obstacles] + [o.x_max for o in obstacles]
    )
    ys = (
        [start[1], end[1]] + [o.y_min for o in obstacles] + [o.y_max for o in obstacles]
    )
    i_min = int(math.floor((min(xs) - ox) / grid_size)) - margin_cells
    i_max = int(math.ceil((max(xs) - ox) / grid_size)) + margin_cells
    j_min = int(math.floor((min(ys) - oy) / grid_size)) - margin_cells
    j_max = int(math.ceil((max(ys) - oy) / grid_size)) + margin_cells

    def cell_center(i: int, j: int) -> tuple[float, float]:
        return (ox + i * grid_size, oy + j * grid_size)

    def world_to_cell(x: float, y: float) -> tuple[int, int]:
        return (
            int(round((x - ox) / grid_size)),
            int(round((y - oy) / grid_size)),
        )

    start_cell = (0, 0)
    end_cell = world_to_cell(*end)

    # Snap end into the valid range (paranoia).
    end_cell = (
        max(i_min, min(i_max, end_cell[0])),
        max(j_min, min(j_max, end_cell[1])),
    )

    # Pre-compute the "escape" cell sets: every cell whose centre
    # is within ``escape_radius_m`` of the start (or end) endpoint
    # is exempt from obstacle blocking, no matter how dense the
    # surrounding building cluster is.
    escape_r2 = escape_radius_m * escape_radius_m

    def _near_anchor(
        p: tuple[float, float],
        anchor: tuple[float, float],
    ) -> bool:
        """Is ``p`` inside ``anchor``'s escape disk?"""
        dx = p[0] - anchor[0]
        dy = p[1] - anchor[1]
        return dx * dx + dy * dy <= escape_r2

    def _in_escape_zone(i: int, j: int) -> bool:
        if escape_radius_m <= 0.0:
            return False
        center = cell_center(i, j)
        return any(_near_anchor(center, a) for a in (start, end))

    def is_blocked(i: int, j: int) -> bool:
        if (i, j) == start_cell or (i, j) == end_cell:
            return False
        if _in_escape_zone(i, j):
            return False
        cx, cy = cell_center(i, j)
        for o in obstacles:
            if o.rectangle_overlaps(cx, cy, half):
                return True
        return False

    # A*
    open_heap: list[tuple[int, int, tuple[int, int]]] = []
    counter = 0  # tie-breaker for the heap (stable order, no compare on tuples)
    heapq.heappush(
        open_heap,
        (abs(end_cell[0]) + abs(end_cell[1]), counter, start_cell),
    )
    g_score: dict[tuple[int, int], int] = {start_cell: 0}
    came_from: dict[tuple[int, int], tuple[int, int]] = {}
    iterations = 0
    found = False
    current = start_cell
    while open_heap:
        if iterations > max_iterations:
            raise RuntimeError(
                "route_manhattan: A* exceeded "
                f"{max_iterations} iterations before reaching end "
                f"= {end}. Increase max_iterations or grid_size, or "
                "relax clearance_m."
            )
        iterations += 1
        _, _, current = heapq.heappop(open_heap)
        if current == end_cell:
            found = True
            break
        i0, j0 = current
        for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            i, j = i0 + di, j0 + dj
            if not (i_min <= i <= i_max and j_min <= j <= j_max):
                continue
            if is_blocked(i, j):
                continue
            tentative = g_score[current] + 1
            if tentative < g_score.get((i, j), 10**18):
                g_score[(i, j)] = tentative
                came_from[(i, j)] = current
                f = tentative + abs(end_cell[0] - i) + abs(end_cell[1] - j)
                counter += 1
                heapq.heappush(open_heap, (f, counter, (i, j)))

    if not found:
        # Diagnose which side is enclosed so the caller gets an
        # actionable suggestion (move that anchor, widen the
        # escape_radius_m, or drop clearance_m).
        start_neighbours_open = sum(
            not is_blocked(start_cell[0] + di, start_cell[1] + dj)
            and i_min <= start_cell[0] + di <= i_max
            and j_min <= start_cell[1] + dj <= j_max
            for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1))
        )
        end_neighbours_open = sum(
            not is_blocked(end_cell[0] + di, end_cell[1] + dj)
            and i_min <= end_cell[0] + di <= i_max
            and j_min <= end_cell[1] + dj <= j_max
            for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1))
        )
        offender = (
            "start"
            if start_neighbours_open == 0
            else ("end" if end_neighbours_open == 0 else "both endpoints")
        )
        raise RuntimeError(
            "route_manhattan: no Manhattan path from "
            f"{start} to {end}. The {offender} anchor is enclosed "
            f"by obstacles (start has {start_neighbours_open}/4 free "
            f"neighbours, end has {end_neighbours_open}/4). "
            "Suggested fixes (in order of safety): "
            "(1) increase ``escape_radius_m`` (currently "
            f"{escape_radius_m:.1f} m -- raise to e.g. "
            f"{2 * escape_radius_m:.1f} m); "
            "(2) reduce ``clearance_m`` (currently "
            f"{clearance_m:.2f} m); "
            "(3) move the offending anchor by a few metres so it "
            "lands clearly outside any foundation footprint."
        )

    # Reconstruct path of cell centres.
    path_cells: list[tuple[int, int]] = [current]
    while current in came_from:
        current = came_from[current]
        path_cells.append(current)
    path_cells.reverse()
    waypoints = [cell_center(*c) for c in path_cells]

    # Anchor first waypoint at the *actual* start (cell (0,0) == start).
    waypoints[0] = start

    # Bridge from last cell centre to ``end`` (axis-aligned).
    last = waypoints[-1]
    if last != end:
        dx = end[0] - last[0]
        dy = end[1] - last[1]
        if math.isclose(dx, 0.0) or math.isclose(dy, 0.0):
            waypoints.append(end)
        else:
            # The trailing bridge honours the same escape zone as
            # ``is_blocked`` does inside the A* loop. Two exemptions,
            # both active only for ``escape_radius_m > 0``:
            #
            # 1. An obstacle that *contains* an anchor is dropped for
            #    the whole bridge. The cable ends inside that
            #    foundation polygon, so no axis-aligned bridge can
            #    avoid it -- enforcing it would turn the escape valve
            #    into a guaranteed failure (the situation the valve
            #    exists for).
            # 2. A bridge segment whose *both* endpoints lie inside
            #    one anchor's escape disk is exempt from every
            #    obstacle, mirroring the per-cell blind spot.
            if escape_radius_m > 0.0:
                bridge_obstacles = [
                    o
                    for o in obstacles
                    if not (o.contains_point(*start) or o.contains_point(*end))
                ]
            else:
                bridge_obstacles = obstacles

            def _bridge_crosses(
                a: tuple[float, float],
                b: tuple[float, float],
            ) -> bool:
                """Does bridge segment ``a -> b`` hit an enforced box?"""
                if escape_radius_m > 0.0 and any(
                    _near_anchor(a, anc) and _near_anchor(b, anc)
                    for anc in (start, end)
                ):
                    return False
                return any(segment_intersects_box(a, b, o) for o in bridge_obstacles)

            # Choose the bridge corner that does not cross an
            # obstacle. Two options: go-x-first or go-y-first.
            corner_x_first = (end[0], last[1])
            corner_y_first = (last[0], end[1])
            for corner in (corner_x_first, corner_y_first):
                if not (_bridge_crosses(last, corner) or _bridge_crosses(corner, end)):
                    waypoints.append(corner)
                    waypoints.append(end)
                    break
            else:
                # Neither bridge works without an obstacle -- give up.
                raise RuntimeError(
                    "route_manhattan: cannot bridge final cell "
                    f"{last} to end {end} without crossing an "
                    f"obstacle (escape_radius_m = {escape_radius_m:.1f} m). "
                    "Suggested fixes: reduce grid_size (currently "
                    f"{grid_size:.1f} m), increase escape_radius_m so the "
                    "bridge fits inside the anchor's blind spot, or reduce "
                    f"clearance_m (currently {clearance_m:.2f} m)."
                )

    return merge_collinear_waypoints(waypoints)

segment_intersects_box

segment_intersects_box(p0: tuple[float, float], p1: tuple[float, float], box: ObstacleBox, *, tol: float = 1e-09) -> bool

True if the axis-aligned segment \(p_0 \to p_1\) enters box.

The segment is assumed axis-aligned (one of x or y coincides on both endpoints). Touching the box on the open boundary is not considered an intersection -- that is what makes the router happy when the cable runs along a street that is exactly tangent to a foundation.

Parameters:

Name Type Description Default
p0 tuple[float, float]

Segment endpoints.

required
p1 tuple[float, float]

Segment endpoints.

required
box ObstacleBox

Obstacle box.

required
tol float

Small slack so a segment running on the boundary of the box does not count as intersecting.

1e-09

Returns:

Type Description
bool

True if the segment passes through the interior of the box.

Raises:

Type Description
ValueError

If the segment is not axis-aligned (neither its x nor its y coordinates agree within tol).

Source code in src/groundfield/generators/manhattan_routing.py
def segment_intersects_box(
    p0: tuple[float, float],
    p1: tuple[float, float],
    box: ObstacleBox,
    *,
    tol: float = 1e-9,
) -> bool:
    r"""True if the *axis-aligned* segment $p_0 \to p_1$ enters ``box``.

    The segment is assumed axis-aligned (one of ``x`` or ``y``
    coincides on both endpoints). Touching the box on the open
    boundary is *not* considered an intersection -- that is what
    makes the router happy when the cable runs along a street
    that is exactly tangent to a foundation.

    Parameters
    ----------
    p0, p1
        Segment endpoints.
    box
        Obstacle box.
    tol
        Small slack so a segment running on the boundary of the
        box does not count as intersecting.

    Returns
    -------
    bool
        ``True`` if the segment passes through the interior of the box.

    Raises
    ------
    ValueError
        If the segment is not axis-aligned (neither its ``x`` nor its
        ``y`` coordinates agree within ``tol``).
    """
    x0, y0 = p0
    x1, y1 = p1
    if math.isclose(y0, y1, abs_tol=tol):
        # Horizontal segment at y = y0
        if y0 <= box.y_min + tol or y0 >= box.y_max - tol:
            return False
        x_low, x_high = (x0, x1) if x0 <= x1 else (x1, x0)
        return x_low < box.x_max - tol and x_high > box.x_min + tol
    if math.isclose(x0, x1, abs_tol=tol):
        # Vertical segment at x = x0
        if x0 <= box.x_min + tol or x0 >= box.x_max - tol:
            return False
        y_low, y_high = (y0, y1) if y0 <= y1 else (y1, y0)
        return y_low < box.y_max - tol and y_high > box.y_min + tol
    raise ValueError(
        f"segment_intersects_box: segment ({p0}, {p1}) is not axis-aligned."
    )

single_rod_grounding

single_rod_grounding(*, length_m: Union[float, AnyDistribution] = 1.5, depth_m: Union[float, AnyDistribution] = 0.0) -> GroundingSystemSpec

One driven rod — a typical Erdungsspieß used as an aux electrode.

Parameters:

Name Type Description Default
length_m float or Distribution

Rod length in m.

1.5
depth_m float or Distribution

Depth of the rod head in m below the surface.

0.0

Returns:

Type Description
GroundingSystemSpec

A grounding system with one RodElectrodeSpec at the site position.

Source code in src/groundfield/generators/measurement.py
def single_rod_grounding(
    *,
    length_m: Union[float, AnyDistribution] = 1.5,
    depth_m: Union[float, AnyDistribution] = 0.0,
) -> GroundingSystemSpec:
    """One driven rod — a typical *Erdungsspieß* used as an aux electrode.

    Parameters
    ----------
    length_m : float or Distribution, default 1.5
        Rod length in m.
    depth_m : float or Distribution, default 0.0
        Depth of the rod head in m below the surface.

    Returns
    -------
    GroundingSystemSpec
        A grounding system with one :class:`RodElectrodeSpec` at the
        site position.
    """
    return GroundingSystemSpec(
        electrodes=[
            RodElectrodeSpec(length_m=length_m, depth_m=depth_m),
        ],
    )

triangle_rod_grounding

triangle_rod_grounding(rod_length_m: float = 0.5, triangle_side_m: float = 0.5) -> GroundingSystemSpec

Default auxiliary-electrode geometry: three parallel vertical rods in an equilateral triangle.

Real-world fall-of-potential test sets use a bundle of rods rather than a single driven rod so the auxiliary's own spreading resistance stays well below the substation's. Three 0.5 m rods at the corners of a 0.5 m equilateral triangle give roughly a third of the single-rod impedance.

Parameters:

Name Type Description Default
rod_length_m float

Length of each rod in m; the rod heads lie at the soil surface.

0.5
triangle_side_m float

Side length of the equilateral triangle in m; the centroid lies at the origin of the electrode's local frame.

0.5

Returns:

Type Description
GroundingSystemSpec

Three RodElectrodeSpec at the triangle corners, bonded into one grounding system.

Source code in src/groundfield/generators/layout/measurement.py
def triangle_rod_grounding(
    rod_length_m: float = 0.5,
    triangle_side_m: float = 0.5,
) -> GroundingSystemSpec:
    r"""Default auxiliary-electrode geometry: three parallel vertical rods in
    an equilateral triangle.

    Real-world fall-of-potential test sets use a *bundle* of rods
    rather than a single driven rod so the auxiliary's own
    spreading resistance stays well below the substation's. Three
    0.5 m rods at the corners of a 0.5 m equilateral triangle give
    roughly a third of the single-rod impedance.

    Parameters
    ----------
    rod_length_m : float, default 0.5
        Length of each rod in m; the rod heads lie at the soil surface.
    triangle_side_m : float, default 0.5
        Side length of the equilateral triangle in m; the centroid lies
        at the origin of the electrode's local frame.

    Returns
    -------
    GroundingSystemSpec
        Three :class:`RodElectrodeSpec` at the triangle corners, bonded
        into one grounding system.
    """
    # Equilateral triangle, centroid at the origin: corners are at
    # angles 90 deg, 210 deg, 330 deg from the centre at a radius
    # ``triangle_side_m / sqrt(3)``.
    r = triangle_side_m / math.sqrt(3.0)
    offsets = [
        (r * math.cos(math.radians(a)), r * math.sin(math.radians(a)))
        for a in (90.0, 210.0, 330.0)
    ]
    return GroundingSystemSpec(
        electrodes=[
            RodElectrodeSpec(
                length_m=rod_length_m,
                depth_m=0.0,
                offset_xy_m=off,
            )
            for off in offsets
        ],
    )

Materialisation building blocks

materialise_plan turns a NetworkPlan into the objects of a World; it is the only place where generated networks become worlds. The functions below are its steps, one per kind of object, and are public for a custom generator that builds part of a world itself. They draw no random numbers: every value of a plan is already concrete.

materialise_site

materialise_site(world: World, site: PlannedSite) -> Optional[str]

Create the electrodes of one site and bond them.

Parameters:

Name Type Description Default
world World

Target world.

required
site PlannedSite

The planned site.

required

Returns:

Type Description
str or None

The anchor electrode name, or None for a site without present electrodes.

Notes

Every non-anchor electrode is bonded to the anchor by a conductor of type site.bond_conductor_type (an ideal galvanic short), so the site is one cluster. A concrete shell lives on the encased wires of its foundation (materialise_electrode()), so the current of a bonded rod does not pass through it; nothing is written to World.concrete_shell_corrections (up to 0.15.0 the lumped shells of a site were folded there for the PEN service drop to carry, review findings 10.12 / 10.13).

Source code in src/groundfield/generators/materialise.py
def materialise_site(world: World, site: PlannedSite) -> Optional[str]:
    """Create the electrodes of one site and bond them.

    Parameters
    ----------
    world
        Target world.
    site
        The planned site.

    Returns
    -------
    str or None
        The anchor electrode name, or ``None`` for a site without
        present electrodes.

    Notes
    -----
    Every non-anchor electrode is bonded to the anchor by a conductor of
    type ``site.bond_conductor_type`` (an ideal galvanic short), so the
    site is one cluster. A concrete shell lives on the encased wires of
    its foundation (:func:`materialise_electrode`), so the current of a
    bonded rod does not pass through it; nothing is written to
    ``World.concrete_shell_corrections`` (up to 0.15.0 the lumped shells
    of a site were folded there for the PEN service drop to carry,
    review findings 10.12 / 10.13).
    """
    return _materialise_site(world, site)[0]

materialise_electrode

materialise_electrode(world: World, spec: ElectrodeSpec, *, centre_xy: tuple[float, float], name: str, bond_conductor_type: str = 'bare_copper') -> None

Create one resolved electrode spec in world.

Parameters:

Name Type Description Default
world World

Target world.

required
spec ElectrodeSpec

Resolved electrode spec (concrete values only).

required
centre_xy tuple[float, float]

Electrode reference point (x, y) in m (site position plus the spec's offset_xy_m).

required
name str

Electrode name; a foundation built from several primitives uses it for its anchor primitive.

required
bond_conductor_type str

Conductor type of the internal bonds of a multi-primitive foundation.

'bare_copper'

Raises:

Type Description
TypeError

If spec is not a rod, ring, strip or foundation electrode spec.

ValueError

If a rectangular foundation has a side that is not positive (after the draws of a distribution).

Source code in src/groundfield/generators/materialise.py
def materialise_electrode(
    world: World,
    spec: ElectrodeSpec,
    *,
    centre_xy: tuple[float, float],
    name: str,
    bond_conductor_type: str = "bare_copper",
) -> None:
    """Create one resolved electrode spec in ``world``.

    Parameters
    ----------
    world
        Target world.
    spec
        Resolved electrode spec (concrete values only).
    centre_xy
        Electrode reference point ``(x, y)`` in m (site position plus
        the spec's ``offset_xy_m``).
    name
        Electrode name; a foundation built from several primitives uses
        it for its anchor primitive.
    bond_conductor_type
        Conductor type of the internal bonds of a multi-primitive
        foundation.

    Raises
    ------
    TypeError
        If ``spec`` is not a rod, ring, strip or foundation electrode
        spec.
    ValueError
        If a rectangular foundation has a side that is not positive
        (after the draws of a distribution).
    """
    ex, ey = centre_xy
    if isinstance(spec, RodElectrodeSpec):
        create_electrode(
            world,
            "rod",
            name=name,
            position=(ex, ey, float(spec.depth_m)),
            length=float(spec.length_m),
            wire_radius=spec.wire_radius_m,
        )
        return
    if isinstance(spec, RingElectrodeSpec):
        create_electrode(
            world,
            "ring",
            name=name,
            center=(ex, ey, float(spec.depth_m)),
            radius=float(spec.radius_m),
            wire_radius=spec.wire_radius_m,
        )
        return
    if isinstance(spec, StripElectrodeSpec):
        length = float(spec.length_m)
        angle = math.radians(float(spec.orientation_deg))
        depth = float(spec.depth_m)
        sx = ex - 0.5 * length * math.cos(angle)
        sy = ey - 0.5 * length * math.sin(angle)
        tx = ex + 0.5 * length * math.cos(angle)
        ty = ey + 0.5 * length * math.sin(angle)
        create_electrode(
            world,
            "strip",
            name=name,
            start=(sx, sy, depth),
            end=(tx, ty, depth),
            wire_radius=spec.wire_radius_m,
        )
        return
    if isinstance(spec, FoundationElectrodeSpec):
        _materialise_foundation(
            world,
            spec,
            centre_xy=(ex, ey),
            name=name,
            bond_conductor_type=bond_conductor_type,
        )
        return
    raise TypeError(
        f"materialise_electrode: unknown electrode spec {type(spec).__name__}."
    )

materialise_junction

materialise_junction(world: World, junction: PlannedJunction) -> str

Create a PEN cable joint and return its node name.

The joint is a leakage-free Junction at (x, y, depth_m): a node of the conductor network with Kirchhoff's current law and no soil contact. Up to 0.15.0 it was a 5 cm driven rod, which leaked 3 to 7 % of a test current through the nominally isolated cable (review finding 10.38).

Parameters:

Name Type Description Default
world World

Target world.

required
junction PlannedJunction

The planned joint: its name, plan position position_xy in m and depth depth_m in m.

required

Returns:

Type Description
str

The name of the created junction (junction.name).

Source code in src/groundfield/generators/materialise.py
def materialise_junction(world: World, junction: PlannedJunction) -> str:
    """Create a PEN cable joint and return its node name.

    The joint is a leakage-free :class:`~groundfield.geometry.junction.Junction`
    at ``(x, y, depth_m)``: a node of the conductor network with
    Kirchhoff's current law and no soil contact. Up to 0.15.0 it was a
    5 cm driven rod, which leaked 3 to 7 % of a test current through the
    nominally isolated cable (review finding 10.38).

    Parameters
    ----------
    world
        Target world.
    junction
        The planned joint: its name, plan position ``position_xy`` in m
        and depth ``depth_m`` in m.

    Returns
    -------
    str
        The name of the created junction (``junction.name``).
    """
    create_junction(
        world,
        position=(junction.position_xy[0], junction.position_xy[1], junction.depth_m),
        name=junction.name,
    )
    return junction.name

materialise_branch

materialise_branch(world: World, branch: PlannedBranch, nodes: dict[str, str], *, index: Optional[dict[str, Any]] = None, foundation_wires: Optional[Mapping[str, Collection[str]]] = None) -> Conductor

Create the conductor of one branch.

Parameters:

Name Type Description Default
world World

Target world.

required
branch PlannedBranch

The planned branch.

required
nodes dict[str, str]

Map from node name (site or junction) to electrode name; a name missing from the map is used verbatim.

required
index Optional[dict[str, Any]]

Optional map from electrode / junction name to the object in world; saves a search through the world per end (the materialiser of a large network passes it).

None
foundation_wires Optional[Mapping[str, Collection[str]]]

Optional map from site name to the names of its horizontal wires (foundations, rings, strips; materialise_plan() passes it); a contact must name one of the wires of the site the branch ends at. Without it the check is weaker: the contact must name a strip, polyline or ring electrode, which need not belong to that site (a NetworkPlan rejects a contact on another site's electrode when it is validated).

None

Returns:

Type Description
Conductor

The created conductor.

Notes

An end with a PlannedContact is the contact's point on the wire it names, and the conductor is attached to that wire (user decisions Q41, Q43); an end without one is the connection point of the node (the site's anchor electrode, or the junction). With axis_z_m both ends are moved to that depth, with axis_offset_m both ends move by that distance along the normal of the plan direction (decision D9: service drops in a row), or along axis_offset_normal_xy when the plan gives one (the common normal of a row of drops that are not exactly parallel, audit W3R2B-01).

Raises:

Type Description
ValueError

If a contact names an electrode that is not a horizontal wire (foundation, ring, strip) of the site the branch ends at (with foundation_wires; without it, an electrode that is no strip, polyline or ring), or lies farther from that wire in plan (from the exact circle of a ring) than one minimum cable section (min_section_length() of the branch's conductor: 1 cm for wire radii up to 7.3 mm; audit R4A-05); or if a branch with axis_offset_m has no horizontal extent.

Source code in src/groundfield/generators/materialise.py
def materialise_branch(
    world: World,
    branch: PlannedBranch,
    nodes: dict[str, str],
    *,
    index: Optional[dict[str, Any]] = None,
    foundation_wires: Optional[Mapping[str, Collection[str]]] = None,
) -> Conductor:
    """Create the conductor of one branch.

    Parameters
    ----------
    world
        Target world.
    branch
        The planned branch.
    nodes
        Map from node name (site or junction) to electrode name; a
        name missing from the map is used verbatim.
    index
        Optional map from electrode / junction name to the object in
        ``world``; saves a search through the world per end (the
        materialiser of a large network passes it).
    foundation_wires
        Optional map from site name to the names of its horizontal wires
        (foundations, rings, strips; :func:`materialise_plan` passes it); a
        contact must name one of the wires of the site the branch ends at.
        Without it the check is weaker: the contact must name a strip,
        polyline or ring electrode, which need not belong to that site (a
        :class:`~groundfield.generators.plan.NetworkPlan` rejects a contact
        on another site's electrode when it is validated).

    Returns
    -------
    Conductor
        The created conductor.

    Notes
    -----
    An end with a :class:`~groundfield.generators.plan.PlannedContact` is
    the contact's point on the wire it names, and the conductor is attached
    to that wire (user decisions Q41, Q43); an end without one is the connection
    point of the node (the site's anchor electrode, or the junction). With
    ``axis_z_m`` both ends are moved to that depth, with ``axis_offset_m``
    both ends move by that distance along the normal of the plan direction
    (decision D9: service drops in a row), or along
    ``axis_offset_normal_xy`` when the plan gives one (the common normal of
    a row of drops that are not exactly parallel, audit W3R2B-01).

    Raises
    ------
    ValueError
        If a contact names an electrode that is not a horizontal wire
        (foundation, ring, strip) of the site the branch ends at (with
        ``foundation_wires``; without it, an electrode that is no strip,
        polyline or ring), or lies farther from that wire in plan (from the
        exact circle of a ring) than one minimum cable section
        (:func:`~groundfield.generators._pen_routing.min_section_length` of
        the branch's conductor: 1 cm for wire radii up to 7.3 mm; audit
        R4A-05); or if a branch with ``axis_offset_m`` has no horizontal
        extent.
    """
    start = nodes.get(branch.start, branch.start)
    end = nodes.get(branch.end, branch.end)
    if index is not None:
        start_node, end_node = index.get(start, start), index.get(end, end)
    else:
        start_node, end_node = start, end
    p = branch.conductor
    if (
        branch.axis_z_m is None
        and branch.start_contact is None
        and branch.end_contact is None
        and branch.axis_offset_m == 0.0
    ):
        return create_conductor(
            world,
            name=branch.name,
            start=start_node,
            end=end_node,
            conductor_type=p.conductor_type,
            wire_radius=p.wire_radius_m,
            cross_section=p.cross_section,
            discretize_segment_length=p.segment_length_m,
            coupling_to_soil=p.coupling_to_soil,
            inductance_model=p.inductance_model,
        )
    (sx, sy, sz), start = _branch_end(
        world,
        start_node,
        start,
        branch.start_contact,
        index,
        branch=branch,
        site=branch.start,
        foundation_wires=foundation_wires,
    )
    (ex, ey, ez), end = _branch_end(
        world,
        end_node,
        end,
        branch.end_contact,
        index,
        branch=branch,
        site=branch.end,
        foundation_wires=foundation_wires,
    )
    if branch.axis_z_m is not None:
        sz = ez = float(branch.axis_z_m)
    if branch.axis_offset_m != 0.0 and branch.axis_offset_normal_xy is not None:
        # a drop in a row that is not exactly parallel (audit W3R2B-01): both
        # ends along the row's common normal
        nx, ny = branch.axis_offset_normal_xy
        offset = float(branch.axis_offset_m)
        sx, sy = sx + offset * nx, sy + offset * ny
        ex, ey = ex + offset * nx, ey + offset * ny
    elif branch.axis_offset_m != 0.0:
        # a drop in a row (decision D9): both ends along the left normal of
        # the plan direction; the conductor stays attached to its nodes
        dx, dy = ex - sx, ey - sy
        length = math.hypot(dx, dy)
        if length == 0.0:
            raise ValueError(
                f"materialise_branch: branch {branch.name!r} has "
                f"axis_offset_m = {branch.axis_offset_m!r} but no horizontal "
                "extent (its ends coincide in plan), so the offset has no "
                "direction."
            )
        shift = float(branch.axis_offset_m) / length
        sx, sy = sx - dy * shift, sy + dx * shift
        ex, ey = ex - dy * shift, ey + dx * shift
    cond = Conductor(
        name=branch.name,
        start=(sx, sy, sz),
        end=(ex, ey, ez),
        start_electrode=start,
        end_electrode=end,
        conductor_type=p.conductor_type,
        wire_radius=p.wire_radius_m,
        cross_section=p.cross_section,
        discretize_segment_length=p.segment_length_m,
        coupling_to_soil=p.coupling_to_soil,
        inductance_model=p.inductance_model,
    )
    world.add_conductor(cond)
    return cond

site_anchor_point

site_anchor_point(site: PlannedSite) -> Optional[tuple[float, float, float]]

Connection point in m of the anchor electrode of site.

The site is materialised into a scratch world, so the point is exactly the one a branch without a contact attaches to (None for a site without present electrodes). For a rectangular foundation it is a corner — the start of its local \(-y\) side (meshes since audit A2G-04, rectangles without cross-braces since user decision Q38) — and for a building outline its first vertex, for a circular ring its \(+x\) point, for a strip its start, for a rod its head. The generators connect their cables to a site with a horizontal electrode (a foundation, a ring, a strip) at the point of those electrodes nearest to each cable instead (site_contact_wires(), user decisions Q41, Q43); this point stays the end of everything attached to the site by name, and of the generators' conductors at a site with rods only.

Parameters:

Name Type Description Default
site PlannedSite

A planned site.

required

Returns:

Type Description
tuple of float or None

(x, y, z) in m of the anchor electrode's connection point, or None for a site without present electrodes.

Source code in src/groundfield/generators/materialise.py
def site_anchor_point(site: PlannedSite) -> Optional[tuple[float, float, float]]:
    """Connection point in m of the anchor electrode of ``site``.

    The site is materialised into a scratch world, so the point is exactly
    the one a branch without a contact attaches to (``None`` for a site
    without present electrodes). For a rectangular foundation it is a
    corner — the start of its local :math:`-y` side (meshes since audit
    A2G-04, rectangles without cross-braces since user decision Q38) — and
    for a building outline its first vertex, for a circular ring its
    :math:`+x` point, for a strip its start, for a rod its head. The
    generators connect their cables to a site with a horizontal electrode (a
    foundation, a ring, a strip) at the point of those electrodes nearest to
    each cable instead (:func:`site_contact_wires`, user decisions Q41,
    Q43); this point stays the end of everything attached to the site by
    name, and of the generators' conductors at a site with rods only.

    Parameters
    ----------
    site
        A planned site.

    Returns
    -------
    tuple of float or None
        ``(x, y, z)`` in m of the anchor electrode's connection point, or
        ``None`` for a site without present electrodes.
    """
    if site.anchor is None:
        return None
    scratch = create_world(soil=HomogeneousSoil(rho=100.0))
    anchor = materialise_site(scratch, site)
    return tuple(float(v) for v in _node_point(scratch, anchor))  # type: ignore[return-value]

site_contact_wires

site_contact_wires(site: PlannedSite) -> list[FoundationWire]

The horizontal wires of site, in plan (user decisions Q41, Q43).

Parameters:

Name Type Description Default
site PlannedSite

A planned site.

required

Returns:

Type Description
list of FoundationWire

One entry per electrode built from a FoundationElectrodeSpec (every side or mesh line of a rectangle, the closed outline of a building), a RingElectrodeSpec (the circle; circle holds its centre and radius, xy the inscribed search polygon of circle_polygon()) or a StripElectrodeSpec of the site, in world order: its name, its index in this list, its plan vertices from its connection point and its depth. Empty for a site with rods only.

Notes

New in 2026.11 (as site_foundation_wires with the foundations only, user decision Q41; renamed and extended to rings and strips by user decision Q43). The generators end every conductor they route to a site with horizontal electrodes at the point of these wires nearest to the conductor (groundfield.generators._contact); a site with rods only keeps the connection point of its anchor, the head of its first rod (site_anchor_point()). The site is materialised into a scratch world, so the wires are exactly those of the materialised plan.

Source code in src/groundfield/generators/materialise.py
def site_contact_wires(site: PlannedSite) -> list[FoundationWire]:
    """The horizontal wires of ``site``, in plan (user decisions Q41, Q43).

    Parameters
    ----------
    site
        A planned site.

    Returns
    -------
    list of FoundationWire
        One entry per electrode built from a
        :class:`~groundfield.generators.electrode_specs.FoundationElectrodeSpec`
        (every side or mesh line of a rectangle, the closed outline of a
        building), a
        :class:`~groundfield.generators.electrode_specs.RingElectrodeSpec`
        (the circle; ``circle`` holds its centre and radius, ``xy`` the
        inscribed search polygon of
        :func:`~groundfield.generators._contact.circle_polygon`) or a
        :class:`~groundfield.generators.electrode_specs.StripElectrodeSpec`
        of the site, in world order: its name, its index in this list, its
        plan vertices from its connection point and its depth. Empty for a
        site with rods only.

    Notes
    -----
    New in 2026.11 (as ``site_foundation_wires`` with the foundations only,
    user decision Q41; renamed and extended to rings and strips by user
    decision Q43). The generators end every conductor they route to a site
    with horizontal electrodes at the point of these wires nearest to the
    conductor (:mod:`groundfield.generators._contact`); a site with rods only
    keeps the connection point of its anchor, the head of its first rod
    (:func:`site_anchor_point`). The site is materialised into a scratch
    world, so the wires are exactly those of the materialised plan.
    """
    return _site_geometry(site, anchor=False).wires

clean_polygon

clean_polygon(polygon_xy: 'tuple[tuple[float, float], ...] | list[tuple[float, float]]', *, min_edge_m: float = MIN_POLYGON_EDGE_M) -> list[tuple[float, float]]

Drop duplicate and sub-min_edge_m vertices from a closed ring.

Walks the ring once and keeps a vertex only when it is at least min_edge_m away from the last kept one; finally drops trailing vertices whose closing edge (last → first) would be too short. An explicitly repeated closing vertex is removed first.

Parameters:

Name Type Description Default
polygon_xy 'tuple[tuple[float, float], ...] | list[tuple[float, float]]'

Ring vertices (x, y) in m.

required
min_edge_m float

Shortest edge in m that is kept.

MIN_POLYGON_EDGE_M

Returns:

Type Description
list of tuple

The cleaned, open ring.

Source code in src/groundfield/generators/materialise.py
def clean_polygon(
    polygon_xy: "tuple[tuple[float, float], ...] | list[tuple[float, float]]",
    *,
    min_edge_m: float = MIN_POLYGON_EDGE_M,
) -> list[tuple[float, float]]:
    """Drop duplicate and sub-``min_edge_m`` vertices from a closed ring.

    Walks the ring once and keeps a vertex only when it is at least
    ``min_edge_m`` away from the last kept one; finally drops trailing
    vertices whose closing edge (last → first) would be too short. An
    explicitly repeated closing vertex is removed first.

    Parameters
    ----------
    polygon_xy
        Ring vertices ``(x, y)`` in m.
    min_edge_m
        Shortest edge in m that is kept.

    Returns
    -------
    list of tuple
        The cleaned, open ring.
    """
    pts = [(float(x), float(y)) for x, y in polygon_xy]
    if len(pts) > 1 and math.dist(pts[0], pts[-1]) < 1e-9:
        pts = pts[:-1]
    kept: list[tuple[float, float]] = []
    for p in pts:
        if not kept or math.dist(kept[-1], p) >= min_edge_m:
            kept.append(p)
    while len(kept) >= 3 and math.dist(kept[-1], kept[0]) < min_edge_m:
        kept.pop()
    return kept

concrete_shell

concrete_shell(spec: FoundationElectrodeSpec, *, encased_length_m: float) -> tuple[float, float, float]

Effective radius, lumped resistance and coefficient of a shell.

Parameters:

Name Type Description Default
spec FoundationElectrodeSpec

Resolved foundation spec (concrete values only).

required
encased_length_m float

Total length \(L\) in m of the encased wire: every wire of the foundation — the perimeter of a ring or of a building outline, the perimeter plus the cross-braces of a mesh (user decision Q20).

required

Returns:

Name Type Description
effective_radius_m float

\(r_b = r_a + t\) in m when a shell is configured, else the bare wire radius \(r_a\).

shell_total_ohm float

\(R_\text{shell} = C / L\) in Ω (0 without shell): the shell resistance of the whole foundation under a uniform leakage current, equal to the per-wire shells \(C / L_j\) in parallel. Informational; the solver sees the coefficient.

shell_coefficient_ohm_m float

\(C = \rho_c/(2\pi)\,\ln(r_b/r_a)\) in Ω·m (0 without shell), concrete_shell_coefficient().

Notes

New in 2026.11. Before the user decision Q20 the development line kept the braces of a mesh bare and took the perimeter as the length (keyword perimeter_m); 0.15.0 had no such function (its private grounding._maybe_concrete_shell divided by the perimeter).

Source code in src/groundfield/generators/materialise.py
def concrete_shell(
    spec: FoundationElectrodeSpec, *, encased_length_m: float
) -> tuple[float, float, float]:
    r"""Effective radius, lumped resistance and coefficient of a shell.

    Parameters
    ----------
    spec
        Resolved foundation spec (concrete values only).
    encased_length_m
        Total length :math:`L` in m of the encased wire: every wire of the
        foundation — the perimeter of a ring or of a building outline,
        the perimeter plus the cross-braces of a mesh (user decision Q20).

    Returns
    -------
    effective_radius_m : float
        :math:`r_b = r_a + t` in m when a shell is configured, else the
        bare wire radius :math:`r_a`.
    shell_total_ohm : float
        :math:`R_\text{shell} = C / L` in Ω (0 without shell): the shell
        resistance of the whole foundation under a uniform leakage
        current, equal to the per-wire shells :math:`C / L_j` in
        parallel. Informational; the solver sees the coefficient.
    shell_coefficient_ohm_m : float
        :math:`C = \rho_c/(2\pi)\,\ln(r_b/r_a)` in Ω·m (0 without shell),
        :func:`~groundfield.geometry.electrodes.concrete_shell_coefficient`.

    Notes
    -----
    New in 2026.11. Before the user decision Q20 the development line kept
    the braces of a mesh bare and took the perimeter as the length (keyword
    ``perimeter_m``); 0.15.0 had no such function (its private
    ``grounding._maybe_concrete_shell`` divided by the perimeter).
    """
    if spec.concrete_rho_ohm_m is None:
        return float(spec.wire_radius_m), 0.0, 0.0
    rho_c = float(spec.concrete_rho_ohm_m)
    t = float(spec.concrete_thickness_m)
    if rho_c <= 0.0 or t <= 0.0:
        return float(spec.wire_radius_m), 0.0, 0.0
    r_a = float(spec.wire_radius_m)
    coefficient = concrete_shell_coefficient(rho_c, r_a, t)
    length = float(encased_length_m)
    r_shell = coefficient / length if length > 0.0 else 0.0
    return r_a + t, float(r_shell), float(coefficient)

MIN_POLYGON_EDGE_M module-attribute

MIN_POLYGON_EDGE_M = 0.5

Shortest polygon edge (m) kept in a foundation along a building outline.

Shorter edges are merged away: a segment shorter than the (concrete-inflated) wire radius would trip the solver's thin-wire guard, and OSM footprints routinely carry centimetre-scale edges without physical meaning for the strip foundation.

footprint_mask_key

footprint_mask_key(footprint: BuildingFootprint) -> object

Key of a footprint in LvNetworkLayout.foundation_mask().

Parameters:

Name Type Description Default
footprint BuildingFootprint

The building footprint.

required

Returns:

Type Description
int or str

footprint.osm_id when set; otherwise "outline:" followed by the exterior-ring vertices in millimetres, starting at the lexicographically smallest vertex. The outline key depends only on the geometry, never on the position of the footprint in a list or on the Python hash seed.

Source code in src/groundfield/generators/layout/penetration.py
def footprint_mask_key(footprint: BuildingFootprint) -> object:
    """Key of a footprint in :meth:`LvNetworkLayout.foundation_mask`.

    Parameters
    ----------
    footprint
        The building footprint.

    Returns
    -------
    int or str
        ``footprint.osm_id`` when set; otherwise ``"outline:"`` followed
        by the exterior-ring vertices in millimetres, starting at the
        lexicographically smallest vertex. The outline key depends only
        on the geometry, never on the position of the footprint in a
        list or on the Python hash seed.
    """
    if footprint.osm_id is not None:
        return footprint.osm_id
    pts = [
        (int(round(x * 1000.0)), int(round(y * 1000.0)))
        for x, y in footprint.polygon_xy_m
    ]
    start = pts.index(min(pts))
    pts = pts[start:] + pts[:start]
    return "outline:" + ";".join(f"{x},{y}" for x, y in pts)

Plan vocabulary and constants

The literal types of the plan records and the geometric limits the generators apply.

SiteRole module-attribute

SiteRole = Literal['substation', 'cabinet', 'building', 'auxiliary', 'probe']

Role of a PlannedSite in the network.

  • "substation" — the secondary substation (Ortsnetzstation).
  • "cabinet" — a cable distribution cabinet.
  • "building" — a building of the network (a house or a commercial building).
  • "auxiliary" — the current return electrode of a measurement.
  • "probe" — the voltage probe electrode of a measurement.

BranchRole module-attribute

BranchRole = Literal['pen', 'service_drop', 'measurement_lead']

Role of a PlannedBranch in the network.

  • "pen" — a section of a PEN cable.
  • "service_drop" — the connection of a building to its cable.
  • "measurement_lead" — a metallic lead of a measurement set-up.

CabinetRule module-attribute

CabinetRule = Literal['centroid_ray', 'far_end_ray']

Rule that placed the cable cabinet of a building group (PlannedSite.cabinet_rule, audit W1R2-02).

  • "centroid_ray" — on the ray from the substation through the group's centroid.
  • "far_end_ray" — on the ray through the group's far-end building, because on the centroid ray the cabinet would have stood farther than CabinetConfig.max_far_end_gap_m from its group.

FoundationOutline module-attribute

FoundationOutline = Literal['spec', 'ombr', 'polygon']

How a building footprint shapes a foundation electrode.

  • "ombr" — oriented minimum bounding rectangle of the outline (size, orientation and centre).
  • "polygon" — the outline itself (closed ring; style="ring" foundations only).
  • "spec" — ignore the footprint; keep the spec geometry.

MIN_FOUNDATION_SIDE_M module-attribute

MIN_FOUNDATION_SIDE_M = 1.0

Shortest side (m) of a foundation rectangle taken from a footprint's OMBR.

A narrower outline — a mapped wall or fence, e.g. 10 m x 5 mm — is widened to this side with a UserWarning; as a 5 mm wide mesh it could not even be built (the mesh span is shorter than the wire radius, audit L5). The AP1 pipeline applied the same 1 m floor to its OMBR foundations.

SURFACE_LEAD_HEIGHT_M module-attribute

SURFACE_LEAD_HEIGHT_M = 0.1

Distance in m of a lead "on the surface" (depth_m = 0) from the ground plane.

A wire exactly in the soil-surface plane is singular for the image kernels (source and image coincide), and the Sommerfeld earth-return kernel degrades for \(|z|\) below about ten wire radii. 0.1 m keeps a 5 mm lead clear of both; the earth-return impedance of a surface lead is insensitive to the exact height while it is small against the skin depth (hundreds of metres below 1 kHz).

lead_axis_z

lead_axis_z(depth_m: float, coupling_to_soil: str = 'isolated') -> float

\(z\) coordinate in m of a measurement lead's axis.

Parameters:

Name Type Description Default
depth_m float

Configured depth in m: positive into the soil, negative above ground, 0 on the surface.

required
coupling_to_soil str

"isolated" or "galvanic".

'isolated'

Returns:

Type Description
float

depth_m; for depth_m == 0 the lead lies SURFACE_LEAD_HEIGHT_M above the ground (isolated) or below it (galvanic: the bare wire touches the soil).

Source code in src/groundfield/generators/measurement.py
def lead_axis_z(depth_m: float, coupling_to_soil: str = "isolated") -> float:
    """:math:`z` coordinate in m of a measurement lead's axis.

    Parameters
    ----------
    depth_m
        Configured depth in m: positive into the soil, negative above
        ground, ``0`` on the surface.
    coupling_to_soil
        ``"isolated"`` or ``"galvanic"``.

    Returns
    -------
    float
        ``depth_m``; for ``depth_m == 0`` the lead lies
        :data:`SURFACE_LEAD_HEIGHT_M` above the ground (isolated) or
        below it (galvanic: the bare wire touches the soil).
    """
    if depth_m != 0.0:
        return float(depth_m)
    if coupling_to_soil == "galvanic":
        return SURFACE_LEAD_HEIGHT_M
    return -SURFACE_LEAD_HEIGHT_M