Generators¶
The generators subpackage is the factory layer that converts
high-level parameter sets into a fully populated
:class:groundfield.World. It is the bridge between parameter
studies (typical, future Monte-Carlo runs) and the physics layer
(soil, electrodes, conductors, solver).
Mathematical / physical context¶
For typical the relevant physics is
with two-layer soil \(\sigma(z)\) and Dirichlet conditions on the metallic surfaces. Below 1 kHz the inductive correction is added on top via Carson (ADR-0005) or Sommerfeld (ADR-0006). The role of a generator is purely topological: it produces a concrete electrode-and-conductor layout the solver can integrate over. No physics happens in this subpackage.
The typical parameter axes that map directly onto
:class:TnNetworkConfig fields are summarised below. TnNetworkConfig has been
refactored onto a composable spec layer (ADR-0009 v2); building
mixes are now declared via building_types (a catalog of
:class:BuildingTypeSpec) and building_counts (per-type
quantities), and every grounding system is built from a list of
:class:ElectrodeSpec entries:
| Axis | default grid | Config field |
|---|---|---|
| Single-family houses \(n_\text{EFH}\) | 5, 10, 30, 80, 200 | building_counts["residential"] |
| Small commercial buildings | 0, 1, 5, 10 | building_counts["small_industry"] |
| Medium commercial buildings | 0, 1, 2, 5 | building_counts["medium_industry"] |
| Cable cabinets | placement spec | kvs.electrodes + placement |
| Substation grounding | ring / rod-circle / strip / foundation | substation.electrodes |
| Upper-layer resistivity \(\rho_1\) | 30, 100, 200, 500, 1000 Ω·m | soil.rho_1 |
| Lower-layer resistivity \(\rho_2\) | 30, 100, 200 Ω·m | soil.rho_2 |
| Layer thickness \(h_1\) | 5, 10, 30 m | soil.h_1 |
Module rename
The module was originally called groundfield.generators.tn_ortsnetz
and exposed the classes TnOrtsnetzGenerator /
TnOrtsnetzConfig. The English-only naming convention renamed
the module to groundfield.generators.tn_network with
:class:TnNetworkGenerator / :class:TnNetworkConfig. The old
module path still works as a deprecated re-export and emits a
DeprecationWarning. Prefer importing from the top-level
groundfield namespace.
Every numeric field accepts either a fixed value or a
:class:Distribution (continuous: Uniform, Normal, LogNormal,
Weibull; discrete: Discrete, Categorical, plus the trivial
Constant). cfg.sample(rng) resolves every distribution
reproducibly given a fixed seed.
Validity envelope¶
- Frequency: \(f \le 1\,\mathrm{kHz}\) (quasi-static).
- Soil: linear, isotropic, layered. Saturation / ionisation are not modelled.
- Topology of :class:
TnNetworkGenerator: radial-with-trunk via cable cabinets — every house connects to its nearest cable cabinet, every cable cabinet connects to the substation. Real street layouts are now supported via :class:~groundfield.geo.placement.OsmBuildingPlacement(see ADR-0011 and the geo API). - Per-building-type grounding is now type-driven via
:class:
BuildingTypeSpecand supports multi-electrode systems (foundation + extra rod, ring + grid + strips, …) with per-electrodepresence_probfor stochastic fleets.
Foundation electrodes: orientation and concrete shell¶
Two extensions to :class:FoundationElectrodeSpec since 0.6.0 round
out the foundation modelling envelope:
orientation_deg: float | None = Nonerotates the foundation rectangle around its centre.Noneand0.0both keep the historic axis-aligned :class:GridMeshElectrodefast path; any other value synthesises the foundation from rotated :class:StripElectrodes and bonds them internally. Set automatically from the OMBR of an OSM polygon when the configured placement is :class:~groundfield.geo.placement.OsmBuildingPlacement.concrete_rho_ohm_m: float | AnyDistribution | None = Noneandconcrete_thickness_mactivate the concrete-encasement model (ADR-0012).Nonekeeps the wire-in-soil baseline; settingconcrete_rho_ohm_mswitches to the cylindrical Sunde-shell model with the chosen radial thickness. Theconcrete_model: Literal["lumped", "distributed"]discriminator selects between a lumped series resistance on the PEN service drop (V1, default — zero solver-side change, exact for the cluster impedance when current distributes uniformly) and a per-segment diagonal augmentation in theimage/image_2layerbackends (V2 — correct for non-uniform current distributions and for the surface potential right at the building wall). Stochastic moisture is supported viaconcrete_rho_ohm_m=Discrete(values=[50, 150, 500, 2000], weights=[0.25, 0.40, 0.25, 0.10]).
The other electrode kinds (Rod, Ring, Strip, Mesh,
GridMesh) do not carry the concrete fields by design — they
correspond to electrodes that sit in trenches or driven holes,
never in a concrete strip foundation.
Architecture¶
GeneratorConfig (Pydantic v2)
└── per-generator subclass (TnNetworkConfig, MvStrandConfig, ...)
├── numeric fields: T | AnyDistribution
├── categorical: str | Categorical
└── nested configs (composable):
├── SoilSpec (Homogeneous | TwoLayer | MultiLayer)
├── PlacementSpec (Manhattan | Explicit)
├── GroundingSystemSpec (list[ElectrodeSpec])
│ └── ElectrodeSpec (Rod | Ring | Strip | Foundation)
└── BuildingTypeSpec (name + grounding + plot_size)
WorldGenerator[Generic[C]] (ABC)
└── per-generator subclass (TnNetworkGenerator, ...)
└── .build(cfg) -> World
strict mode: guarded by ._assert_resolved(cfg)
lazy mode: resolves Distribution fields on demand
(TnNetworkGenerator chooses lazy mode)
WorldGenerator.sample_world(rng) -> tuple[World, ResolvedConfig]
Reproducibility: persist the resolved config alongside the
result. With the same seed and the same library version the
World is bit-exactly reproducible.
Lazy vs. up-front resolution¶
:class:TnNetworkGenerator deliberately supports two patterns:
gen.build(cfg)— lazy. Top-level numeric distributions get one draw per call. Per-instance distributions like a :class:Categoricalhouse_electrode.kindget a fresh draw per house, producing a real mix.gen.sample_world(rng)— up-front.cfg.samplecollapses every distribution to a single value, including the Categorical; all houses then share the resolved kind. Use this when you need a persistable resolved config for one Monte-Carlo realisation.
Distribution catalogue¶
| Class | Backend | Typical use |
|---|---|---|
Constant |
trivial | placeholder |
Uniform(low, high) |
numpy | bounded continuous parameters |
Normal(mean, std, truncate_low?, truncate_high?) |
rejection sampling | engineering tolerances |
LogNormal(mu, sigma) (or LogNormal.from_moments) |
numpy | resistivities, sizes |
Weibull(shape, scale) |
numpy | wear / lifetime |
Discrete(values, weights?) |
numpy choice | n_efh ∈ {5,10,30,80,200} |
Categorical(values, weights?) |
numpy choice | electrode-kind mix per house |
All seven distributions are JSON-serialisable through a
discriminator field kind. Persisting a stochastic config
preserves every distribution exactly; replaying with the same
seed yields the same world.
See ADR-0009 for the full design rationale, validation programme, and roadmap for follow-up generators.
Example¶
Two equivalent ways to drive :class:TnNetworkGenerator. Both
build a fully wired :class:World ready for world.solve(engine).
import numpy as np
import groundfield as gf
# 1. Deterministic build — every parameter fixed.
cfg = gf.TnNetworkConfig(
soil=gf.TwoLayerSoilSpec(rho_1=100.0, rho_2=500.0, h_1=2.0),
building_counts={"residential": 10}, # 10 single-family houses
source_magnitude_A=1.0,
)
gen = gf.TnNetworkGenerator()
world = gen.build(cfg)
# 2. Stochastic build — Categorical electrode kind per house,
# Uniform soil resistivity, reproducible under a fixed seed.
cfg_stoch = gf.TnNetworkConfig(
soil=gf.TwoLayerSoilSpec(
rho_1=gf.Uniform(low=80.0, high=300.0),
rho_2=500.0,
h_1=2.0,
),
building_counts={"residential": 30},
source_magnitude_A=1.0,
)
rng = np.random.default_rng(seed=42)
# Lazy resolution — Categorical fields draw once per house,
# producing a real electrode-kind mix across the fleet.
world_lazy = gen.build(cfg_stoch, rng=rng)
# Strict / up-front resolution — every distribution collapses to a
# single value before build, so all houses share the same kind.
# Returns the resolved config too, which can be persisted alongside
# the result for bit-exact replay.
world_strict, resolved_cfg = gen.sample_world(rng=np.random.default_rng(seed=42))
Persist the resolved config (cfg.model_dump_json()) or the
seed alongside the simulation output to guarantee reproducibility.
PEN backbone topology¶
The PEN backbone of a :class:TnNetworkGenerator run is selected
via the new :class:TnNetworkConfig.pen_topology field
(discriminated union, default :class:StarKvsTopology):
- :class:
StarKvsTopology(default) — legacy v0.6 behaviour: every KVS is wired directly to the substation, every building taps to its nearest KVS by Manhattan distance. - :class:
RadialTrunkTopology— the substation feedsn_feedersaxis-aligned LV feeders (default 4, evenly spaced) each with a finite slot budget at the substation; once exhausted, additional KVS are inserted along the trunk axis. Buildings are assigned to the angularly-closest feeder; buildings beyondmax_feeder_length_mare dropped with a :class:UserWarning. See the radial trunk example in the docs for a bus-topology demonstration.
OrtsnetzLayout — imperative builder¶
Where :class:TnNetworkGenerator produces stochastic reference
worlds from population-level parameters,
:class:OrtsnetzLayout composes a single deterministic network
piece by piece — in the order an engineer would draw it on a plan.
It is the recommended entry point when the network is known from a
real OSM extract plus a hand-placed substation, and the
statistical sweep approach is too rigid.
Workflow¶
import groundfield as gf
from groundfield.generators import OrtsnetzLayout
# 1. OSM ingest + anchor placement, all in one call.
layout = OrtsnetzLayout.from_osm(
center_lat_deg=51.9136, center_lon_deg=10.8432, # Mulmke
radius_m=200.0,
substation_xy=(0.0, -12.0), # ENU metres relative to centre
kvs_xys=[(40.0, -12.0), (80.0, -12.0)],
obstacle_clearance_m=1.0,
min_area_m2=20.0,
)
# 2. PEN cables in strict Manhattan geometry. Endpoints can be
# anchor names, free ENU metres, or WGS84 lat/lon -- pick
# whichever style matches your map source.
layout.add_pen_cable(start='substation', end='kvs_0',
min_segment_length_m=8.0)
layout.add_pen_cable(start='kvs_0', end='kvs_1',
min_segment_length_m=8.0)
layout.add_pen_cable(start='substation',
end_xy=(0.0, 60.0),
min_segment_length_m=8.0)
# 3. Tap every house to its closest cable.
layout.connect_buildings()
# 4. Simulated fall-of-potential measurement.
layout.add_auxiliary_electrode(distance_m=200.0, direction_deg=0.0)
layout.add_voltage_probe(inline_fraction=0.5)
# 5. Reproducible foundation-electrode penetration.
mask = layout.foundation_mask(0.30) # always returns the same houses
# 6. Materialise + solve.
world = layout.to_world(foundation_mask=mask,
source_magnitude_A=1.0)
engine = gf.create_engine(backend='image',
segment_length=0.5, frequencies=[50.0])
result = engine.solve(world)
# 7. Read the simulated meter reading + Kirchhoff plausibility.
Z = layout.measured_grounding_impedance(result)
balance = layout.verify_current_balance(result)
assert balance['ok']
# 8. Render: layout view + surface-potential plot.
ax = layout.plot(foundation_mask=mask)
fig = layout.plot_surface_potential(result, world) # TwoSlopeNorm
Routing semantics¶
PEN cables are routed by
:func:groundfield.generators.manhattan_routing.route_manhattan, a
4-connected A on a Manhattan grid of cell size
min_segment_length_m that avoids every building's bounding
rectangle (inflated by obstacle_clearance_m). When an anchor
lands inside or right next to a foundation polygon — typical in
real OSM extracts — the escape_radius_m parameter defines a
disk around the anchor inside which obstacle blocking is not*
enforced. Default: one grid cell; pass a larger value when the
anchor is wedged into a dense city block.
Foundation-electrode penetration mask¶
:meth:OrtsnetzLayout.foundation_mask(penetration, salt=0) is the
project-wide answer to "which houses have a Fundamenterder at
this penetration rate \(p\)?". The decision is derived from a stable
MD5 hash of each footprint's osm_id (with the footprint index
as a fall-back for synthetic footprints), so the mask is:
- Reproducible. Calling with the same
(p, salt)always returns the bit-identical mask, across runs, processes and Python versions. - Nested in \(p\). Every house with a foundation at \(p_1\) also has one at any \(p_2 > p_1\) — increasing the penetration only grows the equipped subset.
salt lets the user draw several independent Monte-Carlo
realisations at the same nominal penetration.
Measurement-loop semantics¶
When an :class:AuxiliaryElectrodePlacement is configured,
:meth:OrtsnetzLayout.to_world adds a second
:class:CurrentSource at the auxiliary anchor with
phase_deg=180. The engine's net injected charge is then zero
and the potential field develops the expected dipole pattern:
positive trumpet at the substation, negative trumpet at the
Hilfserder. Source.return_to on the substation-side source is
preserved (it documents the planner's intent and will be honoured
natively once the solver grows return-current support); the
extra source is the v0.7 workaround for the image backend
ignoring return_to.
The voltage probe is not materialised as an electrode in the
world. :meth:measured_grounding_impedance samples the field at
the probe location via :meth:FieldResult.potential — exactly
what an ideal voltmeter would measure, with no perturbation of
the field by a finite-impedance probe rod.
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 :class:groundfield.World that the
solver can consume.
The framework is organised in five composable spec layers:
- :mod:
~groundfield.generators.distributions— Constant, Uniform, Normal, LogNormal, Weibull, Discrete, Categorical. Each numerical / categorical field of any spec class accepts a fixed value or a :class:Distribution. - :mod:
~groundfield.generators.electrode_specs— single-electrode specs (rod / ring / strip / foundation) withpresence_probandoffset_xy_m. - :mod:
~groundfield.generators.grounding— :class:GroundingSystemSpeccomposes a list of :data:ElectrodeSpecinto one cluster. - :mod:
~groundfield.generators.placement— Manhattan-grid and explicit-coordinate placement strategies. - :mod:
~groundfield.generators.soil_specs— homogeneous / two-layer / multi-layer soil specs that resolve to the :mod:groundfield.soil.modelstypes. - :mod:
~groundfield.generators.building— :class:BuildingTypeSpecbundles a name with a grounding system and an optional plot size.
The first concrete generator,
:class:~groundfield.generators.tn_network.TnNetworkGenerator,
composes all of the above into a TN low-voltage network.
See docs/adr/0009-world-generators.md for the design rationale
and the validation programme.
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 :class:GeneratorConfig
that holds a list of electrodes (e.g. electrodes:
list[ElectrodeSpec]). Pydantic dispatches on kind.
PenTopology
module-attribute
¶
PenTopology = Annotated[
Union[StarKvsTopology, 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
:class:~groundfield.generators.tn_network.TnNetworkGenerator
dispatches on :attr: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 :meth:OrtsnetzLayout.to_world via
:meth: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 Hilfserder practice and yielding a
spreading resistance roughly a third of a single rod.
During :meth:OrtsnetzLayout.to_world the layout adds a
second :class:CurrentSource with phase_deg=180 at the
anchor electrode so the engine's potential field develops the
expected dipole pattern (positive trumpet at the substation,
negative trumpet at the Hilfserder).
BuildingConnection ¶
Bases: BaseModel
Stub from one house's foundation centre to its serving cable.
Attributes:
| Name | Type | Description |
|---|---|---|
house_idx |
int
|
Index into :attr: |
cable_name |
str
|
Name of the :class: |
stub_waypoints |
list[tuple[float, float]]
|
Polyline from the house centroid to the tap point on the
cable. |
tap_point_xy |
tuple[float, float]
|
The actual tap point on the cable polyline. |
BuildingTypeSpec ¶
Bases: GeneratorConfig
Definition of one building type.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Identifier used as the lookup key in
:attr: |
grounding |
GroundingSystemSpec
|
:class: |
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. |
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.
Constant ¶
Bases: Distribution
Degenerate distribution returning value deterministically.
Useful as a placeholder or in code paths that always expect a
:class:Distribution instance.
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.
Distribution ¶
Bases: BaseModel
Abstract base for probability distributions.
Subclasses must:
- set a literal
kindfield (used as the JSON discriminator), - implement :meth:
samplereturning a single draw.
The base class is intentionally a regular Pydantic model rather
than an :class:abc.ABC so it composes cleanly with discriminated
unions in :class:pydantic.BaseModel field annotations.
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).
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 :attr:style:
"ring"— only the rectangle's perimeter is buried (a closed wire loop). No internal cross-bracing.n_xandn_yare 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 inton_x × n_ycells. The Maschenerder-style foundation electrode found in larger buildings, transformer stations and industrial sites. Withn_x = n_y = 2(the default) the rectangle gets exactly one internal horizontal plus one internal vertical wire.
Both styles materialise as a
:class:groundfield.geometry.electrodes.GridMeshElectrode;
the "ring" style is just the special case n_x = n_y = 1
of that primitive (one mesh = perimeter only).
For an asymmetric footprint set size_xy_m instead of
size_m (when both are given, size_xy_m wins).
GeneratorConfig ¶
Bases: 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 :class:Distribution. Categorical
fields use str | Categorical.
Two introspection helpers are provided:
- :meth:
has_distributionsreturnsTrueif any field still carries a :class:Distributioninstance — useful as a guard before passing the config to :meth:WorldGenerator.build. - :meth:
samplereturns a copy of the config with every :class:Distributionfield resolved to a concrete value via its.sample(rng)method. Nested :class:GeneratorConfigsub-fields are recursed into; lists are processed element-wise.
has_distributions ¶
Return whether any field still carries a :class:Distribution.
Recursive: a nested :class:GeneratorConfig whose own field
carries a distribution counts as "has distributions".
Source code in src/groundfield/generators/base.py
sample ¶
Return a copy with every :class:Distribution field resolved.
Each distribution is replaced by exactly one .sample(rng)
draw. Non-distribution fields are passed through unchanged.
Nested :class:GeneratorConfig instances are recursed into.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng
|
Optional[Union[int, Generator]]
|
Either an integer seed, a :class: |
None
|
Returns:
| Type | Description |
|---|---|
GeneratorConfig
|
A resolved config of the same concrete type, in which
|
Source code in src/groundfield/generators/base.py
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). All present electrodes are bonded into one cluster. |
bond_conductor_type |
str
|
Conductor type used to bond the electrodes together. Default
|
build_at ¶
build_at(
world: World,
site_xy: tuple[float, float],
name_prefix: str,
rng: np.random.Generator,
) -> Optional[str]
Materialise the grounding system inside world.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
World
|
The :class: |
required |
site_xy
|
tuple[float, float]
|
Centre position |
required |
name_prefix
|
str
|
Prefix used for every created electrode name. The actual
name is |
required |
rng
|
Generator
|
Random generator used to sample |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The name of the anchor electrode (the first present
one). |
Source code in src/groundfield/generators/grounding.py
HomogeneousSoilSpec ¶
Bases: 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.
KvsConfig ¶
KvsPlacement ¶
Bases: BaseModel
One user-placed cable cabinet.
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 :meth:from_moments to construct an instance from the
physical mean and standard deviation of \(X\) instead.
from_moments
classmethod
¶
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:
| 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
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 :meth: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.
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.
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 :func:neighbour_substation_grounding.
feed_lead is the metallic Stromeinspeiseleitung between
the substation cluster and the aux electrode. None (default)
means galvanic-only: the source's return_to is set to the
aux electrode but no metallic wire closes the loop — the return
current flows entirely through the soil. Setting feed_lead
to a :class:MeasurementLeadConfig (often via
:func:overhead_lead or :func: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 :class:Conductor that
connects two anchor electrodes (typically the substation cluster
and the auxiliary or probe cluster). Two routing variants are
common in typical studies and selectable via :attr:depth_m:
depth_m = 0.0— overhead at the surface. The classical default case for the Stromeinspeiseleitung of a fall-of-potential measurement.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 probe back
to the measurement device near the substation. As with
:class:MeasurementInjectionConfig.feed_lead, None is
galvanic-only; setting it enables inductive coupling.
MeasurementSetupConfig ¶
Bases: GeneratorConfig
Earth-resistance measurement setup.
When TnNetworkConfig.measurement is set, the generator:
- builds the auxiliary electrode at
:attr:
injection.position_xyviainjection.grounding.build_at(...); - builds the voltage probe at :attr:
probe.position_xyviaprobe.grounding.build_at(...); - if :attr:
injection.feed_leadis set, adds a :class:Conductorfrom the substation anchor to the aux anchor with the configured depth, conductor type, and inductance model; - if :attr:
probe.leadis set, adds a similar conductor from the substation anchor to the probe anchor; - attaches the source to the substation anchor with
return_topointing at the aux anchor — the test current physically returns through the auxiliary electrode (and, if the metallic feed lead is present, mostly through it).
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: 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 thickness_m=None
(semi-infinite). Each layer's resistivity (and finite-layer
thickness) may carry a :class:Distribution.
Normal ¶
Bases: Distribution
Normal distribution \(\mathcal{N}(\mu, \sigma^2)\) with optional truncation.
Truncation is implemented via rejection sampling. A
:class: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).
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. |
inflated ¶
Return a copy enlarged by padding_m on every side.
Source code in src/groundfield/generators/manhattan_routing.py
rectangle_overlaps ¶
Does the square [cx-half, cx+half]^2 overlap the box?
Source code in src/groundfield/generators/manhattan_routing.py
OrtsnetzLayout ¶
Bases: BaseModel
Imperative TN-Ortsnetz 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 = OrtsnetzLayout.from_footprints(footprints, ... substation_xy=(0, 0)) kvs_1 = layout.add_kvs((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
|
kvs_placements |
list[KvsPlacement]
|
Optional pre-populated KVS list. Most callers leave this
empty and use :meth: |
pen_cables |
list[PenCable]
|
Optional pre-populated PEN cables. Most callers leave
this empty and use :meth: |
connections |
list[BuildingConnection]
|
Optional pre-populated building connections. Most callers
leave this empty and use :meth: |
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. |
projector
property
¶
Lazy :class:Projector for the layout's ENU frame.
Returns None when :attr: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_auxiliary_electrode ¶
add_auxiliary_electrode(
*,
distance_m: Optional[float] = None,
direction_deg: float = 0.0,
position_xy: Optional[tuple[float, float]] = None,
position_lat_lon: Optional[tuple[float, float]] = None,
name: str = "aux",
grounding: Optional[GroundingSystemSpec] = None,
length_m: Optional[float] = None,
depth_m: float = 0.0
) -> str
Place the auxiliary current electrode (Hilfserder).
Exactly one of the three position kinds must be set:
distance_m(with optionaldirection_deg) places the electrode at :math:\mathbf{r}_\text{aux} = \mathbf{r}_\text{sub} + d\,(\cos\theta,\,\sin\theta), with :math:\thetameasured CCW from the local +x axis.direction_deg = 0corresponds to east,90to north. This is the convenient form for a controlled sensitivity sweep over distance, mimicking the fall-of-potential test geometry.position_xysets the electrode at an explicit ENU coordinate.position_lat_lonprojects through the layout's :attr:frame_origin_lat_lon(raises if no frame origin is set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distance_m
|
Optional[float]
|
Manhattan-radius from the substation in metres. Must be positive. |
None
|
direction_deg
|
float
|
Direction in degrees CCW from +x (east). Default 0. |
0.0
|
position_xy
|
Optional[tuple[float, float]]
|
See above; mutually exclusive with |
None
|
position_lat_lon
|
Optional[tuple[float, float]]
|
See above; mutually exclusive with |
None
|
name
|
str
|
Anchor id of the auxiliary electrode (defaults to
|
'aux'
|
grounding
|
Optional[GroundingSystemSpec]
|
:class: |
None
|
length_m
|
Optional[float]
|
Convenience override: when |
None
|
depth_m
|
float
|
Depth of the rod head when |
0.0
|
Returns:
| Type | Description |
|---|---|
str
|
The auxiliary anchor's name, identical to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no positioning kind is given, if more than one is
given, or if |
RuntimeError
|
From :meth: |
Notes
The placement replaces any previously configured auxiliary electrode (there is only one per layout in v1). Call this method again with different parameters to sweep the auxiliary-electrode distance without rebuilding the entire layout.
Source code in src/groundfield/generators/ortsnetz_builder.py
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 | |
add_kvs ¶
add_kvs(
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 KVS name (auto-generated when name
is None). The returned name is what callers pass to
:meth:add_pen_cable as start=....
Source code in src/groundfield/generators/ortsnetz_builder.py
add_pen_cable ¶
add_pen_cable(
*,
start: str,
end_xy: Optional[tuple[float, float]] = None,
end_lat_lon: Optional[tuple[float, float]] = None,
end: Optional[str] = None,
name: Optional[str] = None,
min_segment_length_m: float = 10.0,
clearance_m: Optional[float] = None,
escape_radius_m: Optional[float] = None
) -> PenCable
Add a PEN cable routed Manhattan-style.
Exactly one of end, end_xy or end_lat_lon must
be set. When end is the name of another anchor (KVS)
the cable terminates there and the receiving cabinet is
recorded as :attr:PenCable.end_anchor. When end_xy or
end_lat_lon is set, the cable's last waypoint is the
free coordinate and houses near it can still tap into the
trunk. end_lat_lon is projected through the layout's
:attr:frame_origin_lat_lon (raises if no frame origin is
set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str
|
Name of an anchor present in this layout
( |
required |
end_xy
|
Optional[tuple[float, float]]
|
Free \((x, y)\) endpoint coordinate in metres. |
None
|
end
|
Optional[str]
|
Name of the destination anchor. Mutually exclusive
with |
None
|
name
|
Optional[str]
|
Optional cable id. Auto-generated when |
None
|
min_segment_length_m
|
float
|
Grid size of the Manhattan A* router. Defaults to 10 m -- a reasonable street-segment length and an order of magnitude longer than a typical foundation footprint. |
10.0
|
clearance_m
|
Optional[float]
|
Per-call override for :attr: |
None
|
escape_radius_m
|
Optional[float]
|
Radius around the start and end anchor inside which
obstacles are not enforced. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
PenCable
|
The freshly-routed cable. Already registered in
:attr: |
Source code in src/groundfield/generators/ortsnetz_builder.py
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 | |
add_voltage_probe ¶
add_voltage_probe(
*,
inline_fraction: Optional[float] = None,
perpendicular_fraction: Optional[float] = None,
perpendicular_side: str = "left",
position_xy: Optional[tuple[float, float]] = None,
position_lat_lon: Optional[tuple[float, float]] = None,
name: str = "probe",
depth_m: float = 0.0
) -> str
Place the voltage probe (Spannungssonde).
The voltage probe replaces the "remote earth" reference of
a simple U_sub / I measurement with the actual
ground potential at a chosen point — exactly what a
field-deployed grounding-impedance meter does.
Four positioning kinds are accepted:
inline_fraction— along the substation → aux axis, at a fraction :math:fof the aux distance (:math:f = 0is the substation, :math:f = 1is the Hilfserder, :math:f = 0.5is the midpoint, which is the standard "50 % rule"). Requires :meth:add_auxiliary_electrodeto have been called.perpendicular_fraction(withperpendicular_side"left"or"right") — 90° rotated from the substation → aux axis (left = CCW = north when aux runs east, right = CW = south). The probe distance from the substation is :math:f \cdot D_\text{aux}. This matches the senkrecht zur Hilfserdertrasse setup commonly used to suppress inductive coupling between the current-feed loop and the voltage-probe lead.position_xy— explicit ENU metres.position_lat_lon— WGS84 (projects through :attr:frame_origin_lat_lon).
Examples:
Classic 50 % inline probe between substation and a 200 m east Hilfserder:
>>> layout.add_auxiliary_electrode(distance_m=200.0,
... direction_deg=0.0)
>>> layout.add_voltage_probe(inline_fraction=0.5)
# probe ends up at (100, 0) relative to the substation
90° perpendicular probe at the same fraction, on the "left" (= north) side:
>>> layout.add_voltage_probe(perpendicular_fraction=0.5,
... perpendicular_side="left")
# probe ends up at (0, 100) relative to the substation
Source code in src/groundfield/generators/ortsnetz_builder.py
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 | |
connect_all_buildings ¶
connect_all_buildings(
*,
source_anchors: Optional[list[str]] = None,
max_passes: int = 4,
margin_m: float = 3.0,
lateral_clearance_m: Optional[float] = None,
min_segment_length_m: float = 10.0,
escape_radius_m: Optional[float] = None,
clearance_m: Optional[float] = None
) -> "LateralCoverageResult"
Connect every house to the LV network, adding laterals as needed.
:meth:connect_buildings only taps each house to the nearest
existing cable with a short (at most two-segment) stub and skips
houses whose stub would cross another footprint -- typically houses
with no cable in reach. This method closes that gap so the layout
models a real LV network in which every customer is served.
Strategy ("laterals from the nearest node" model):
- Tap whatever is already reachable via :meth:
connect_buildings. - For every still-unconnected house (farthest from any source node
first), route an obstacle-avoiding PEN lateral
(:meth:
add_pen_cable, full Manhattan A*) from the nearest connected source node (substation or a KVS) to a free point just outside the house, then re-tap. Re-tapping frequently connects neighbouring houses to the same new lateral for free. - Repeat until no house remains or no further progress is made.
Houses enclosed by other footprints on every side stay unconnected
and are reported in :attr:LateralCoverageResult.islands rather
than raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_anchors
|
Optional[list[str]]
|
Names of the nodes laterals may originate from. |
None
|
max_passes
|
int
|
Maximum number of tap/lateral rounds. Each round adds at most one lateral per still-unconnected house. |
4
|
margin_m
|
float
|
Extra distance, beyond the house's bounding-box half-diagonal, at which the lateral end point is placed outside the footprint. |
3.0
|
lateral_clearance_m
|
Optional[float]
|
Obstacle inflation used when searching for a free lateral end
point. Defaults to :attr: |
None
|
min_segment_length_m
|
float
|
Forwarded to :meth: |
10.0
|
escape_radius_m
|
float
|
Forwarded to :meth: |
10.0
|
clearance_m
|
float
|
Forwarded to :meth: |
10.0
|
Returns:
| Type | Description |
|---|---|
LateralCoverageResult
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/groundfield/generators/ortsnetz_builder.py
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 | |
connect_buildings ¶
connect_buildings(
*,
only_unconnected: bool = True,
clearance_m: Optional[float] = None
) -> list[BuildingConnection]
Attach every house to the closest PEN cable.
For each footprint not yet listed in :attr:connections
(when only_unconnected=True, the default), this method:
- Computes the Manhattan-shortest tap point on every cable.
- Picks the cable whose tap point is closest to the
house centroid and whose stub does not cross another
foundation (after the same
clearance_minflation used for cable routing). - Builds the stub polyline (at most two segments) and
records a :class:
BuildingConnection.
Houses that cannot be connected to any cable (e.g.
surrounded by foundations on all sides) are reported via
a :class:UserWarning and skipped; they remain
unconnected and can be revisited after the user adds
another cable.
Source code in src/groundfield/generators/ortsnetz_builder.py
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 | |
foundation_mask ¶
Deterministic per-house Bernoulli mask for foundation
electrodes (Fundamenterder).
For each footprint a stable pseudo-random number
:math:r_i \in [0, 1) is derived from the footprint's
osm_id (or its index as a fallback) and the user-
supplied salt. The mask entry is True iff
:math:r_i < p where :math:p = penetration. Two
properties hold:
- Reproducible. Calling
layout.foundation_mask(0.15)always returns the same mask for the same set of footprints, regardless of when or in which process you call it. - Nested in p. For a fixed
salt, every house with a foundation at :math:p_1also has one at :math:p_2 > p_1— increasing the penetration only grows the foundation-equipped subset. This is the natural property for penetration-rate sweep studies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
penetration
|
float
|
Penetration rate :math: |
required |
salt
|
int
|
Optional integer that shifts the mask deterministically into a different realisation. Useful for Monte-Carlo studies where the user wants several independent runs at the same penetration rate. |
0
|
Returns:
| Type | Description |
|---|---|
list of bool
|
One entry per footprint, in the layout's declared
order. Length equals |
Examples:
>>> mask_15 = layout.foundation_mask(0.15)
>>> mask_30 = layout.foundation_mask(0.30)
>>> all(b1 <= b2 for b1, b2 in zip(mask_15, mask_30)) # nested
True
>>> layout.foundation_mask(0.15) == layout.foundation_mask(0.15)
True
Source code in src/groundfield/generators/ortsnetz_builder.py
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
) -> "OrtsnetzLayout"
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 KVS / PEN endpoints by lat / lon later.
Source code in src/groundfield/generators/ortsnetz_builder.py
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,
kvs_lat_lons: Optional[
list[tuple[float, float]]
] = None,
kvs_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
) -> "OrtsnetzLayout"
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
:attr: |
required |
center_lon_deg
|
float
|
Centre of the buildings-in-radius Overpass query. Also
the WGS84 origin of the local ENU frame
:attr: |
required |
radius_m
|
float
|
Search radius in metres. |
required |
substation_lat_lon
|
Optional[tuple[float, float]]
|
Optional substation location as WGS84 |
None
|
substation_xy
|
Optional[tuple[float, float]]
|
Substation location in already-projected metres.
Mutually exclusive with |
None
|
kvs_lat_lons
|
Optional[list[tuple[float, float]]]
|
Optional list of KVS locations in WGS84 |
None
|
kvs_xys
|
Optional[list[tuple[float, float]]]
|
Optional list of KVS locations in already-projected
metres. Mutually exclusive with |
None
|
substation_name
|
str
|
Anchor id for the substation. Default |
'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
|
Forwarded to :func: |
None
|
|
force_refresh
|
Forwarded to :func: |
None
|
|
endpoint
|
Forwarded to :func: |
None
|
|
timeout_s
|
Forwarded to :func: |
None
|
|
max_retries
|
Forwarded to :func: |
None
|
Returns:
| Type | Description |
|---|---|
OrtsnetzLayout
|
Layout with footprints loaded, projector seeded, and substation / KVS 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 KVS along the main road:
>>> layout = OrtsnetzLayout.from_osm(
... center_lat_deg=51.9136, center_lon_deg=10.8432,
... radius_m=300.0,
... substation_lat_lon=(51.9138, 10.8418),
... kvs_lat_lons=[
... (51.9133, 10.8445),
... (51.9140, 10.8460),
... ],
... )
Source code in src/groundfield/generators/ortsnetz_builder.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
lat_lon_to_xy ¶
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).
Source code in src/groundfield/generators/ortsnetz_builder.py
measured_grounding_impedance ¶
measured_grounding_impedance(
result: object,
*,
frequency_index: int = 0,
source_magnitude_A: float = 1.0,
probe_xy: Optional[tuple[float, float]] = None,
probe_depth_m: float = 0.0
) -> complex
Compute the simulated fall-of-potential measurement reading.
Returns:
| Name | Type | Description |
|---|---|---|
complex
|
:math: |
|
When neither ``probe_xy`` nor :attr:`voltage_probe` is set,
|
|
|
the reference falls back to remote earth, i.e. the method
|
|
|
returns |
math:`\varphi_\text{sub} / I_\text{src}`.
|
|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
object
|
:class: |
required |
frequency_index
|
int
|
Pick the frequency and the test-current normalisation. |
0
|
source_magnitude_A
|
int
|
Pick the frequency and the test-current normalisation. |
0
|
probe_xy
|
Optional[tuple[float, float]]
|
Optional explicit probe position in local ENU metres
(overrides :attr: |
None
|
probe_depth_m
|
float
|
Sampling depth for the override (default 0 = surface).
Ignored when |
0.0
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no auxiliary electrode is configured (the measurement loop is then physically open). |
Source code in src/groundfield/generators/ortsnetz_builder.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 | |
plot ¶
plot(
*,
ax: Optional["_mpl_axes.Axes"] = None,
show_unconnected: bool = True,
annotate_houses: bool = False,
foundation_mask: Optional[list[bool]] = None,
figsize: tuple[float, float] = (12.0, 8.0)
) -> "_mpl_axes.Axes"
Render the layout with matplotlib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foundation_mask
|
Optional[list[bool]]
|
Optional per-house bool list (one entry per footprint).
When supplied, houses with |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes the layout was drawn on. The figure can be
retrieved via |
Source code in src/groundfield/generators/ortsnetz_builder.py
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 | |
plot_surface_potential ¶
plot_surface_potential(
result: object,
world: World,
*,
frequency_index: int = 0,
padding_m: float = 50.0,
n: int = 150,
levels: int = 41,
log: bool = False,
symmetric: bool = False,
two_slope: bool = True,
cmap: str = "RdBu_r",
show_electrodes: bool = True,
figsize: tuple[float, float] = (11.0, 8.5),
title: Optional[str] = None
)
Surface-potential pseudo-colour plot with measurement markers (substation + Hilfserder + Spannungssonde).
Renders \(\varphi(x, y, z=0)\) on a regular grid sized to the
world bounding box plus padding_m and overlays the
substation, Hilfserder and Spannungssonde markers plus a
dotted return-current line. Three colour-axis modes are
supported:
two_slope=True(default) -- uses :class:matplotlib.colors.TwoSlopeNormcentred at \(\varphi = 0\) so the colour resolution above and below zero is balanced regardless of the actual range. Ideal for the fall-of-potential setup, where the Hilfserder sits at a strongly negative potential (e.g. -10 V) and the substation + foundations together rise to only a few volts -- on a single linear scale the positive trumpet collapses into a single colour. The colourbar uses non-uniform contour levels so each half of the scale carries the same number of fills.symmetric=True-- the classic :math:[-|\varphi|_\text{max}, +|\varphi|_\text{max}]range. Equivalent toTwoSlopeNormonly when the extremes are symmetric; otherwise large negative potentials clip the positive side. Settingsymmetric=Trueimplicitly turns offtwo_slope.log=True-- log-scale on \(|\varphi|\). Useful when the potential decays across several decades toward remote earth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
object
|
:class: |
required |
world
|
World
|
Companion world used to derive the plot extent and
(when |
required |
frequency_index
|
int
|
Index into :attr: |
0
|
padding_m
|
float
|
Extra space around the world bounding box in m. |
50.0
|
n
|
int
|
Grid resolution per axis ( |
150
|
levels
|
int
|
Number of contour-fill levels. Split half-and-half
between the negative and positive ranges when
|
41
|
log
|
bool
|
Mutually-influencing scaling modes (see above). |
False
|
symmetric
|
bool
|
Mutually-influencing scaling modes (see above). |
False
|
two_slope
|
bool
|
Mutually-influencing scaling modes (see above). |
False
|
cmap
|
str
|
Matplotlib colormap (diverging recommended). |
'RdBu_r'
|
show_electrodes
|
bool
|
Overlay the electrode geometry (small markers + lines). |
True
|
figsize
|
tuple[float, float]
|
Figure size and optional title override. |
(11.0, 8.5)
|
title
|
tuple[float, float]
|
Figure size and optional title override. |
(11.0, 8.5)
|
Returns:
| Type | Description |
|---|---|
Figure
|
The figure the plot was drawn on. Use |
Source code in src/groundfield/generators/ortsnetz_builder.py
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 | |
to_world ¶
to_world(
*,
name: str = "ortsnetz_layout",
soil: Optional[SoilModel] = None,
substation_grounding: Optional[
GroundingSystemSpec
] = None,
kvs_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
) -> World
Materialise the layout into a :class:groundfield.World.
Each :class:PenCable becomes a chain of straight-line
:class:Conductor segments between PEN junction
electrodes (tiny rods at every corner and tap point) so
the resulting cable physically follows the Manhattan
polyline. Each :class:BuildingConnection becomes one
additional conductor from the house foundation anchor to
the nearest PEN junction on the serving cable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foundation_mask
|
Optional[list[bool]]
|
Optional per-house bool list. When given, only houses
with a |
None
|
Notes
Other parameters follow the v0.7 :meth:to_world defaults.
When :attr:auxiliary_electrode is set (i.e.
:meth:add_auxiliary_electrode was called), the source's
return_to is wired to the auxiliary anchor so the
engine treats it as the test-current return path. Without
an auxiliary electrode the source returns through the
remote-earth boundary (= the historical pre-v0.7
behaviour).
Source code in src/groundfield/generators/ortsnetz_builder.py
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 | |
verify_current_balance ¶
verify_current_balance(
result: object,
*,
frequency_index: int = 0,
source_magnitude_A: float = 1.0,
tolerance: float = 0.02
) -> dict
Plausibility check: sum of leakage currents must close the measurement loop.
With the v0.7 closed-loop wiring the engine sees:
- a positive
+Iinjection at the substation cluster, which distributes itself across the substation grounding and the PEN-bonded foundations (because the PEN cables are finite-impedance branches that share the substation potential); - a negative
-Iinjection at the Hilfserder cluster.
Per Kirchhoff the total leakage current at every other electrode must vanish:
.. math:: \sum_e I_e^\text{(positive side)} \approx +I_\text{src} ,\qquad \sum_e I_e^\text{(aux side)} \approx -I_\text{src}
Returns a dict with the two sums and a boolean ok flag
indicating that both sums match :math:\pm I_\text{src}
within tolerance (default 2 % of the test current).
The "positive side" is every electrode whose name does not start with the auxiliary's name prefix; the "aux side" is every electrode whose name does start with that prefix.
Source code in src/groundfield/generators/ortsnetz_builder.py
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 | |
xy_to_lat_lon ¶
Inverse projection: local frame (x, y) → WGS84.
Mirrors :meth:lat_lon_to_xy.
Source code in src/groundfield/generators/ortsnetz_builder.py
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 :class:generators.placement.ManhattanGridPlacement
and :class:generators.placement.ExplicitPlacement, so any
consumer that accepts a :class: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 :meth: |
selection |
Literal['first_n', 'all']
|
How to choose footprints when the generator requests fewer than are available:
|
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
¶
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
:meth:footprint_at without invoking len() on the model
instance.
__len__ ¶
footprint_at ¶
Return the footprint associated with site i.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
int
|
Site index, matching the order returned by
:meth: |
required |
strict
|
bool
|
If If |
False
|
Returns:
| Type | Description |
|---|---|
BuildingFootprint or None
|
The footprint at index |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
Source code in src/groundfield/geo/placement.py
generate ¶
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
:class: |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[float, float]]
|
Polygon centroids in metres. Length is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundfield/geo/placement.py
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, |
start_anchor |
str
|
Name of the anchor (substation or KVS) 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 (KVS) the cable terminates at.
|
grid_size_m |
float
|
The grid size used when this cable was routed -- kept on
the model so :meth: |
PenConfig ¶
RadialTrunkTopology ¶
Bases: BaseModel
Radial-feeder PEN topology with finite per-source slot budget.
The substation feeds :attr:n_feeders radial feeders. Each
feeder runs along its own discrete direction (:attr: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 :attr:slots_per_substation buildings tap
directly to the substation; once the budget is exhausted, a KVS
is inserted along the feeder axis and the next
:attr:slots_per_kvs buildings tap to that KVS, 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 :attr: |
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 :class: |
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 KVS extension. |
slots_per_kvs |
int
|
Number of direct building taps per KVS. After the substation
budget is exhausted, KVSes are inserted along the feeder
until every assigned building is wired or the feeder reaches
:attr: |
kvs_spacing_m |
float
|
Step length (along the feeder axis) between adjacent KVSes 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 KVSes
( |
Notes
Trunk segments (substation → KVS and KVS → KVS) and service drops (tap anchor → building anchor) are realised as straight 3D conductors between the corresponding anchor electrodes. 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.
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
|
|
Source code in src/groundfield/generators/pen_topology.py
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]]
Compute KVS 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_kvs buildings shares one KVS, the batch
after that shares the next KVS, and so on. Each KVS sits on
the feeder axis at the smallest multiple of
:attr:kvs_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:kvs_spacing_m per KVS. This keeps the layout
predictable (KVSes 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 KVSes 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.
Source code in src/groundfield/generators/pen_topology.py
resolved_directions_rad ¶
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).
Source code in src/groundfield/generators/pen_topology.py
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: BaseModel
A single layer used by :class:MultiLayerSoilSpec.
thickness_m=None marks the semi-infinite bottom layer (only
valid as the last entry in :class:MultiLayerSoilSpec.layers).
StarKvsTopology ¶
Bases: BaseModel
Legacy star PEN topology.
Substation feeds each KVS directly, every building taps to its
nearest KVS (Manhattan metric). KVS placement and count come from
:class:groundfield.generators.tn_network.KvsConfig.
This is the default for backward compatibility — pre-v0.7 generator configurations behave bit-identically.
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 ¶
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 :data: |
substation |
SubstationConfig
|
Substation block (position + grounding system). |
kvs |
KvsConfig
|
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
|
pen |
PenConfig
|
PEN backbone configuration. |
source_magnitude_A |
Union[float, AnyDistribution]
|
Driving current at the substation cluster, in A. |
TnNetworkGenerator ¶
Bases: WorldGenerator[TnNetworkConfig]
Generator for TN low-voltage distribution network reference worlds.
See the module docstring for the full pipeline. In one sentence: build soil → build substation grounding → place buildings (one per type-and-count) → build per-building grounding → place cable cabinets → build per-KVS grounding → wire the PEN backbone → attach the source.
Source code in src/groundfield/generators/base.py
build ¶
Materialise one realisation of the configured TN network.
Resolves all stochastic fields against the generator's RNG,
builds the substation grounding, places the configured number
of buildings (with per-type electrode systems), routes the PEN
backbone via the configured
:class:~groundfield.generators.placement.Placement strategy,
optionally adds a measurement setup, and returns the assembled
:class:~groundfield.World ready for world.solve(engine).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
TnNetworkConfig
|
Configuration overriding :attr: |
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
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | |
TwoLayerSoilSpec ¶
Bases: 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\).
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.
VoltageProbePlacement ¶
Bases: BaseModel
Voltage probe (Spannungssonde) used during the simulated fall-of-potential measurement.
Unlike the :class: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 :meth:OrtsnetzLayout.to_world
no rod electrode is created for the probe; in
:meth:OrtsnetzLayout.measured_grounding_impedance the field
is sampled at :attr:position_xy via
:meth: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.
WorldGenerator ¶
Bases: Generic[C]
Abstract base for World-producing generators.
Subclasses parameterise themselves on a concrete
:class:GeneratorConfig subclass C and implement
:meth:build, which constructs a :class:World from a
resolved config (one with no remaining
:class:Distribution fields).
The base class supplies:
- RNG wiring via the
seedconstructor argument; - :meth:
sample_worldthat resolves any distributions and hands the resolved config to :meth:build; - a guard in :meth:
_assert_resolvedthat surfaces a clear error if :meth:buildis called with an unresolved config.
Source code in src/groundfield/generators/base.py
build
abstractmethod
¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
Optional[C]
|
Optional override for |
None
|
Source code in src/groundfield/generators/base.py
sample_world ¶
Resolve any distributions in self.cfg and build a world.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng
|
Optional[Union[int, Generator]]
|
Optional RNG override. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[World, GeneratorConfig]
|
The constructed world and the resolved config (same type
as |
Source code in src/groundfield/generators/base.py
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.
Source code in src/groundfield/generators/measurement.py
default_building_catalog ¶
Return a sensible starting catalog of four building types.
Returns:
| Type | Description |
|---|---|
list[BuildingTypeSpec]
|
Four entries: |
Source code in src/groundfield/generators/building.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
materialise_soil ¶
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.
Source code in src/groundfield/generators/soil_specs.py
merge_collinear_waypoints ¶
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.
Source code in src/groundfield/generators/manhattan_routing.py
neighbour_substation_grounding ¶
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.
Source code in src/groundfield/generators/measurement.py
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.
Surface routing (depth_m=0), bare copper, isolated soil
coupling, Neumann inductance enabled.
Source code in src/groundfield/generators/measurement.py
resolve_value ¶
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
:class: |
required |
rng
|
Generator
|
Random generator forwarded to |
required |
Returns:
| Type | Description |
|---|---|
object
|
The fixed value, or one sample from the distribution. |
Source code in src/groundfield/generators/base.py
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 :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:
| 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 :class: |
1.5
|
depth_m
|
Union[float, AnyDistribution]
|
Forwarded to every :class: |
1.5
|
wire_radius_m
|
Union[float, AnyDistribution]
|
Forwarded to every :class: |
1.5
|
presence_prob
|
Union[float, AnyDistribution]
|
Forwarded to every :class: |
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 |
Source code in src/groundfield/generators/electrode_specs.py
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 |
required |
end
|
tuple[float, float]
|
Endpoint coordinates in metres. The grid origin is locked
to |
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 :func: |
10.0
|
clearance_m
|
float
|
Additional padding around each obstacle. Defaults to
|
0.5
|
escape_radius_m
|
Optional[float]
|
Inside a disk of this radius around |
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. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When no path exists (obstacle field encloses the substation or KVS). |
Source code in src/groundfield/generators/manhattan_routing.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
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
|
Source code in src/groundfield/generators/manhattan_routing.py
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.
Source code in src/groundfield/generators/measurement.py
triangle_rod_grounding ¶
triangle_rod_grounding(
rod_length_m: float = 0.5, triangle_side_m: float = 0.5
) -> GroundingSystemSpec
Default Hilfserder 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 Tiefenerder 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.