Skip to content

Factories

The create_* functions are the notebook-friendly way to build a model: each one constructs an object, registers it in the World and returns it. They are thin wrappers around the model classes (gf.RodElectrode(...) plus world.add_electrode(...) is equivalent), with two additions: the parameters of every electrode kind are typed (IDE completion, type-checker errors for a misspelled kind or keyword), and unknown names raise with the closest valid name ("did you mean …?").

Factory Creates Physical meaning
create_world(soil=...) World container of the physical model; the soil is the conducting half-space
create_electrode(world, kind, ...) electrode (rod, ring, strip, polyline, star, mesh, grid_mesh) metal in contact with the soil; leaks current
create_conductor(world, start=, end=, ...) Conductor connection between two nodes: ideal, lumped resistance, or a distributed line with resistance, inductance and optional leakage
create_junction(world, position=) Junction node without soil contact (cable joint, instrument terminal)
create_source(world, attached_to=, ...) CurrentSource impressed current between a node and remote earth or a second node (return_to)
create_engine(...) Engine the numerics: backend, frequencies, segment length, kernel, earth-return model
run_simulation(world, engine) FieldResult the same as world.solve(engine) and engine.solve(world)

Mathematical and physical context

The factories assemble the boundary-value problem that every backend solves: Laplace's equation \(\nabla\cdot(\sigma\nabla\varphi) = 0\) in the layered soil (soil), the electrode surfaces as equipotential boundaries per galvanic cluster (create_electrode), Kirchhoff's laws for the conductor network between the nodes (create_conductor, create_junction), and the impressed currents as the right-hand side (create_source). The Engine decides how the problem is discretised and solved; the World holds only physics and can be solved by several engines for a cross-check.

Coordinates are \((x, y, z)\) in metres with \(z\) the depth below the soil surface (positive downwards); every other quantity is in SI units (see Units and conventions).

Example

import groundfield as gf

world = gf.create_world(soil=gf.HomogeneousSoil(rho=100.0))
rod = gf.create_electrode(world, "rod", name="g1", position=(0.0, 0.0, 0.0), length=1.5)
ring = gf.create_electrode(world, "ring", name="g2", center=(10.0, 0.0, 0.8), radius=2.0)
joint = gf.create_junction(world, name="J1", position=(5.0, 0.0, 0.7))  # cable joint
gf.create_conductor(world, name="l1", start=rod, end=joint, cross_section=50e-6)
gf.create_conductor(world, name="l2", start=joint, end=ring, cross_section=50e-6)
gf.create_source(world, name="s1", attached_to="g1", magnitude=10.0)
engine = gf.create_engine(backend="image", frequencies=[50.0, 150.0])
result = gf.run_simulation(world, engine)

assert type(ring).__name__ == "RingElectrode"
assert len(result.input_impedance("s1")) == 2   # one value per frequency

create_electrode(world, "rnig", ...) raises ValueError: Unknown electrode kind 'rnig'. Did you mean 'ring'?; a keyword that the chosen kind does not take raises TypeError with the list of valid keywords. A junction that no conductor connects to an electrode has no defined potential and is rejected when the world is solved.

API reference

api

Top-level factory functions.

This module provides the convenient, notebook-friendly API of groundfield. Instead of instantiating each class manually, the caller writes:

import groundfield as gf world = gf.create_world(soil=gf.HomogeneousSoil(rho=100.0)) rod = gf.create_electrode(world, "rod", name="g1", ... position=(0.0, 0.0, 0.0), length=1.5) ring = gf.create_electrode(world, "ring", name="g2", ... center=(10.0, 0.0, 0.8), radius=2.0) conn = gf.create_conductor(world, name="l1", start=rod, end=ring, ... conductor_type="bare_copper") src = gf.create_source(world, name="s1", attached_to="g1", ... magnitude=10.0) j = gf.create_junction(world, name="J1", position=(10.0, 0.0, 0.5)) eng = gf.create_engine(backend="image", frequencies=[50.0]) result = gf.run_simulation(world, eng) # or world.solve(eng)

Conventions
  • Every create_* function registers the new object in the World and returns it.
  • start / end of a conductor may be electrodes, junctions, their names, or coordinate tuples.
  • Names are auto-generated when omitted (electrode_0, conductor_0, source_0, junction_0).
  • Coordinates are in metres with z pointing downwards (z > 0 is in the soil).
Static typing

create_electrode() has one @overload per electrode kind, so an IDE shows the parameters of the chosen kind and a type checker reports a misspelled kind or keyword and infers the concrete return type (create_electrode(w, "ring", ...) is a RingElectrode). The string options are Literal types (ElectrodeKind, SourceKind, KernelKind, and Backend, EarthInductiveModel, ConductorType, SoilCoupling, InductanceModel where they are defined). A kind chosen at run time (a plain str) needs a typing.cast to ElectrodeKind — or build the class directly (gf.RodElectrode(...) plus world.add_electrode). At run time, an unknown kind, keyword or electrode name raises with the closest valid name ("did you mean …?").

ElectrodeKind module-attribute

ElectrodeKind: TypeAlias = Literal['rod', 'ring', 'strip', 'polyline', 'star', 'mesh', 'grid_mesh']

Electrode kinds accepted by create_electrode().

"rod", "ring", "strip", "polyline", "star", "mesh" and "grid_mesh" create a RodElectrode, RingElectrode, StripElectrode, PolylineElectrode, StarElectrode, MeshElectrode and GridMeshElectrode.

SourceKind module-attribute

SourceKind: TypeAlias = Literal['current', 'voltage']

Source kinds accepted by create_source().

"current" creates a CurrentSource (impressed current), "voltage" a VoltageSource (impressed voltage, ideal or behind an internal impedance).

KernelKind module-attribute

KernelKind: TypeAlias = Literal['point', 'line']

Source kernels accepted by create_engine().

The kernel is used for the reaction matrix and the field evaluation: "point" (one point source per segment) or "line" (the exact uniform line source per segment). kernel=None leaves the choice to the backend.

PointLike module-attribute

PointLike: TypeAlias = Sequence[float] | npt.NDArray[Any]

A point (x, y, z) in m: a tuple, a list or a numpy array.

ConductorEnd module-attribute

ConductorEnd: TypeAlias = PointLike | Electrode | Junction | str

One end of a conductor in create_conductor().

An electrode or junction, the name of a registered electrode or junction, or a point (x, y, z) in m.

create_world

create_world(*, name: str = 'world', soil: SoilModel | None = None, boundary: BoundaryConditions | None = None) -> World

Create an empty World.

Parameters:

Name Type Description Default
name str

Human-readable name (used in logs and result metadata).

'world'
soil SoilModel | None

Optional pre-built soil model. Can also be set later via world.soil = ....

None
boundary BoundaryConditions | None

Optional pre-built boundary configuration. No backend reads it (see BoundaryConditions).

None

Returns:

Type Description
World

The new, empty world.

Source code in src/groundfield/api.py
def create_world(
    *,
    name: str = "world",
    soil: SoilModel | None = None,
    boundary: BoundaryConditions | None = None,
) -> World:
    """Create an empty :class:`World`.

    Parameters
    ----------
    name
        Human-readable name (used in logs and result metadata).
    soil
        Optional pre-built soil model. Can also be set later via
        ``world.soil = ...``.
    boundary
        Optional pre-built boundary configuration. No backend reads it
        (see :class:`~groundfield.BoundaryConditions`).

    Returns
    -------
    World
        The new, empty world.
    """
    kwargs: dict[str, Any] = {"name": name}
    if soil is not None:
        kwargs["soil"] = soil
    if boundary is not None:
        kwargs["boundary"] = boundary
    return World(**kwargs)

create_electrode

create_electrode(world: World, kind: Literal['rod'] = ..., *, name: str | None = ..., position: PointLike, length: float, wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> RodElectrode
create_electrode(world: World, kind: Literal['ring'], *, name: str | None = ..., center: PointLike, radius: float, wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> RingElectrode
create_electrode(world: World, kind: Literal['strip'], *, name: str | None = ..., start: PointLike, end: PointLike, wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> StripElectrode
create_electrode(world: World, kind: Literal['polyline'], *, name: str | None = ..., vertices: Sequence[PointLike] | NDArray[Any], closed: bool = ..., wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> PolylineElectrode
create_electrode(world: World, kind: Literal['star'], *, name: str | None = ..., center: PointLike, n_arms: int, arm_length: float, orientation_deg: float = ..., wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> StarElectrode
create_electrode(world: World, kind: Literal['mesh'], *, name: str | None = ..., corner: PointLike, size: Sequence[float] | NDArray[Any], spacing: float = ..., wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> MeshElectrode
create_electrode(world: World, kind: Literal['grid_mesh'], *, name: str | None = ..., corner: PointLike, size: Sequence[float] | NDArray[Any], n_x: int, n_y: int, wire_radius: float = ..., concrete_shell_coefficient_ohm_m: float = ...) -> GridMeshElectrode
create_electrode(world: World, kind: str = 'rod', *, name: str | None = None, **params: Any) -> _ElectrodeBase

Create an electrode and register it with world.

Parameters:

Name Type Description Default
world World

Target world that will own the new electrode.

required
kind str

Geometry type (ElectrodeKind). The keyword parameters of each kind (lengths in m, angles in degrees, z > 0 in the soil; wire_radius defaults to 0.005 m and the concrete-shell coefficient concrete_shell_coefficient_ohm_m (Ω·m, ADR-0012) to 0 for every kind):

  • "rod" — position (top end), length.
  • "ring" — center, radius.
  • "strip" — start, end.
  • "polyline" — vertices, closed (default True).
  • "star" — center, n_arms, arm_length, orientation_deg (default 0).
  • "mesh" — corner, size (x, y), spacing (default 1 m).
  • "grid_mesh" — corner, size (x, y), n_x, n_y.

See groundfield.geometry.electrodes for the geometry of each class.

'rod'
name str | None

Optional unique name. Auto-generated (electrode_<n>) when None.

None
**params Any

The parameters of kind listed above.

{}

Returns:

Type Description
Electrode

The registered electrode, of the class that belongs to kind (RodElectrode for "rod", RingElectrode for "ring", …); type checkers infer the concrete class from the overloads.

Raises:

Type Description
ValueError

Unknown kind (with the closest valid kind), or a parameter value the electrode model rejects.

TypeError

A keyword that kind does not have (with the closest valid keyword, or the kinds that do have it).

Source code in src/groundfield/api.py
def create_electrode(
    world: World,
    kind: str = "rod",
    *,
    name: str | None = None,
    **params: Any,
) -> _ElectrodeBase:
    """Create an electrode and register it with ``world``.

    Parameters
    ----------
    world
        Target world that will own the new electrode.
    kind
        Geometry type (:data:`ElectrodeKind`). The keyword parameters of
        each kind (lengths in m, angles in degrees, ``z > 0`` in the
        soil; ``wire_radius`` defaults to 0.005 m and the concrete-shell
        coefficient ``concrete_shell_coefficient_ohm_m`` (Ω·m, ADR-0012)
        to 0 for every kind):

        - ``"rod"`` — ``position`` (top end), ``length``.
        - ``"ring"`` — ``center``, ``radius``.
        - ``"strip"`` — ``start``, ``end``.
        - ``"polyline"`` — ``vertices``, ``closed`` (default ``True``).
        - ``"star"`` — ``center``, ``n_arms``, ``arm_length``,
          ``orientation_deg`` (default 0).
        - ``"mesh"`` — ``corner``, ``size`` ``(x, y)``, ``spacing``
          (default 1 m).
        - ``"grid_mesh"`` — ``corner``, ``size`` ``(x, y)``, ``n_x``,
          ``n_y``.

        See :mod:`groundfield.geometry.electrodes` for the geometry of
        each class.
    name
        Optional unique name. Auto-generated (``electrode_<n>``) when
        ``None``.
    **params
        The parameters of ``kind`` listed above.

    Returns
    -------
    Electrode
        The registered electrode, of the class that belongs to ``kind``
        (:class:`RodElectrode` for ``"rod"``, :class:`RingElectrode` for
        ``"ring"``, …); type checkers infer the concrete class from the
        overloads.

    Raises
    ------
    ValueError
        Unknown ``kind`` (with the closest valid kind), or a parameter
        value the electrode model rejects.
    TypeError
        A keyword that ``kind`` does not have (with the closest valid
        keyword, or the kinds that do have it).
    """
    cls = _ELECTRODE_CLASSES.get(kind)
    if cls is None:
        raise ValueError(
            f"Unknown electrode kind {kind!r}."
            f"{did_you_mean(str(kind), _ELECTRODE_CLASSES)} "
            f"Valid kinds: {', '.join(repr(k) for k in _ELECTRODE_CLASSES)}."
        )
    allowed = _parameters_of(cls)
    unknown = [key for key in params if key not in allowed]
    if unknown:
        raise TypeError(_unknown_keyword_message(kind, unknown, allowed))
    if name is None:
        name = _auto_name(world, "electrodes", "electrode")
    electrode = cls(name=name, **params)
    world.add_electrode(electrode)
    return electrode

create_conductor

create_conductor(world: World, *, start: ConductorEnd, end: ConductorEnd, name: str | None = None, conductor_type: ConductorType = 'generic', wire_radius: float = 0.005, resistivity: float = 1.68e-08, cross_section: float | Literal['from_radius'] | None = None, discretize_segment_length: float | None = None, coupling_to_soil: SoilCoupling = 'isolated', inductance_model: InductanceModel | None = None, lumped_series_resistance_ohm: float | None = None, resistance_model: ResistanceModel = 'dc') -> Conductor

Create a conductor and register it with world.

Parameters:

Name Type Description Default
world World

Target world.

required
start ConductorEnd

Start and end point. Each may be an electrode or a junction (create_junction()), the name of a registered electrode or junction, or a coordinate tuple (x, y, z) in m. A conductor joins the network only if both ends are nodes.

required
end ConductorEnd

Start and end point. Each may be an electrode or a junction (create_junction()), the name of a registered electrode or junction, or a coordinate tuple (x, y, z) in m. A conductor joins the network only if both ends are nodes.

required
name str | None

Optional unique name. Auto-generated (conductor_<n>) when None.

None
conductor_type ConductorType

Conductor type (ConductorType).

'generic'
wire_radius float

Wire radius in m.

0.005
resistivity float

Material resistivity of the conductor in Ω·m (default: copper, 1.68e-8 Ω·m).

1.68e-08
cross_section float | Literal['from_radius'] | None

Conductor cross section in \(\mathrm{m}^2\). None (default) keeps the historic ideal-galvanic-short behaviour: both end electrodes are fused into one cluster with a common potential. A finite value activates the finite-impedance branch model with \(R_\text{ser} = \rho_\text{mat}\, L / A\). The string "from_radius" resolves to \(\pi\, r_\text{wire}^2\).

None
discretize_segment_length float | None

Maximum sub-segment length in m for the distributed-conductor model (see ADR-0003). None (default) keeps the conductor lumped (single segment, leakage only at the end electrodes). A galvanic conductor leaks along its length also with a single sub-piece (a value at least the conductor length).

None
coupling_to_soil SoilCoupling

"isolated" (default) — the conductor does not exchange current with the soil along its length. "galvanic" — every segment leaks current into the soil. For an insulated cable keep "isolated"; for buried bare copper or an exposed shield use "galvanic".

'isolated'
inductance_model InductanceModel | None

None (default) keeps the longitudinal-branch impedance purely resistive (DC behaviour). "neumann" activates the Neumann self- and mutual-inductance integral between the branches of every inductive conductor — the segments of a distributed conductor, or one branch from start to end for a lumped one (ADR-0004, review pass 10, 10.24) — and the system becomes frequency-dependent and complex per frequency.

None
lumped_series_resistance_ohm float | None

Optional additional lumped series resistance in Ω.

None
resistance_model ResistanceModel

"dc" (default): the series resistance is the DC value. "skin": the AC resistance of a solid round wire with skin effect, opt-in (review pass 10, 10.37); needs a finite cross_section (see Conductor).

'dc'

Returns:

Type Description
Conductor

The registered conductor.

Raises:

Type Description
KeyError

start or end names an electrode or junction that does not exist (with the closest names).

Source code in src/groundfield/api.py
def create_conductor(
    world: World,
    *,
    start: ConductorEnd,
    end: ConductorEnd,
    name: str | None = None,
    conductor_type: ConductorType = "generic",
    wire_radius: float = 0.005,
    resistivity: float = 1.68e-8,
    cross_section: float | Literal["from_radius"] | None = None,
    discretize_segment_length: float | None = None,
    coupling_to_soil: SoilCoupling = "isolated",
    inductance_model: InductanceModel | None = None,
    lumped_series_resistance_ohm: float | None = None,
    resistance_model: ResistanceModel = "dc",
) -> Conductor:
    """Create a conductor and register it with ``world``.

    Parameters
    ----------
    world
        Target world.
    start, end
        Start and end point. Each may be an electrode or a junction
        (:func:`create_junction`), the name of a registered electrode or
        junction, or a coordinate tuple ``(x, y, z)`` in m. A conductor
        joins the network only if both ends are nodes.
    name
        Optional unique name. Auto-generated (``conductor_<n>``) when
        ``None``.
    conductor_type
        Conductor type (:data:`~groundfield.conductors.conductor.ConductorType`).
    wire_radius
        Wire radius in m.
    resistivity
        Material resistivity of the conductor in Ω·m (default: copper,
        1.68e-8 Ω·m).
    cross_section
        Conductor cross section in $\\mathrm{m}^2$. ``None`` (default)
        keeps the historic ideal-galvanic-short behaviour: both end
        electrodes are fused into one cluster with a common potential.
        A finite value activates the finite-impedance branch model
        with $R_\\text{ser} = \\rho_\\text{mat}\\, L / A$. The string
        ``"from_radius"`` resolves to $\\pi\\, r_\\text{wire}^2$.
    discretize_segment_length
        Maximum sub-segment length in m for the distributed-conductor
        model (see ADR-0003). ``None`` (default) keeps the conductor
        lumped (single segment, leakage only at the end electrodes). A
        galvanic conductor leaks along its length also with a single
        sub-piece (a value at least the conductor length).
    coupling_to_soil
        ``"isolated"`` (default) — the conductor does not exchange
        current with the soil along its length. ``"galvanic"`` — every
        segment leaks current into the soil. For an insulated cable
        keep ``"isolated"``; for buried bare copper or an exposed
        shield use ``"galvanic"``.
    inductance_model
        ``None`` (default) keeps the longitudinal-branch impedance
        purely resistive (DC behaviour). ``"neumann"`` activates the
        Neumann self- and mutual-inductance integral between the
        branches of every inductive conductor — the segments of a
        distributed conductor, or one branch from start to end for a
        lumped one (ADR-0004, review pass 10, 10.24) — and the system
        becomes frequency-dependent and complex per frequency.
    lumped_series_resistance_ohm
        Optional additional lumped series resistance in Ω.
    resistance_model
        ``"dc"`` (default): the series resistance is the DC value.
        ``"skin"``: the AC resistance of a solid round wire with skin
        effect, opt-in (review pass 10, 10.37); needs a finite
        ``cross_section`` (see :class:`~groundfield.conductors.Conductor`).

    Returns
    -------
    Conductor
        The registered conductor.

    Raises
    ------
    KeyError
        ``start`` or ``end`` names an electrode or junction that does
        not exist (with the closest names).
    """
    if name is None:
        name = _auto_name(world, "conductors", "conductor")
    s = _resolve_point(world, start)
    e = _resolve_point(world, end)

    def _electrode_name(p: ConductorEnd) -> str | None:
        if isinstance(p, (_ElectrodeBase, Junction)):
            return p.name
        if isinstance(p, str):
            return _get_node(world, p).name
        return None

    cond = Conductor(
        name=name,
        start=s,
        end=e,
        start_electrode=_electrode_name(start),
        end_electrode=_electrode_name(end),
        conductor_type=conductor_type,
        wire_radius=wire_radius,
        resistivity=resistivity,
        cross_section=cross_section,
        discretize_segment_length=discretize_segment_length,
        coupling_to_soil=coupling_to_soil,
        inductance_model=inductance_model,
        lumped_series_resistance_ohm=lumped_series_resistance_ohm,
        resistance_model=resistance_model,
    )
    world.add_conductor(cond)
    return cond

create_junction

create_junction(world: World, *, position: PointLike, name: str | None = None) -> Junction

Create a leakage-free junction node and register it with world.

A junction is a node of the conductor network without soil contact: conductors can start or end there (create_conductor()) and sources can attach to it (create_source()), but it injects no current into the soil. Its potential follows from Kirchhoff's current law and Ohm's law along the conductors; solved results report it in result.metadata["junction_potentials"][name] (V per frequency). Use it for cable joints and for the terminals of a measuring instrument (see Junction).

Parameters:

Name Type Description Default
world World

Target world.

required
position PointLike

Location (x, y, z) in m (z positive downwards; a point above the surface is allowed). Conductors ending on the junction use it as their end point.

required
name str | None

Optional unique node name (electrodes and junctions share one namespace). Auto-generated (junction_<n>) when None.

None

Returns:

Type Description
Junction

The registered junction.

Raises:

Type Description
ValueError

The name is already taken by an electrode or junction, or the position is not finite.

Notes

A junction must be connected through conductors to an electrode or to a galvanically coupled conductor; a subnetwork without soil contact has an undefined potential and is rejected when solved. Only backends that declare the junctions capability (the image family) accept worlds with junctions.

Source code in src/groundfield/api.py
def create_junction(
    world: World,
    *,
    position: PointLike,
    name: str | None = None,
) -> Junction:
    """Create a leakage-free junction node and register it with ``world``.

    A junction is a node of the conductor network without soil contact:
    conductors can start or end there (:func:`create_conductor`) and
    sources can attach to it (:func:`create_source`), but it injects no
    current into the soil. Its potential follows from Kirchhoff's
    current law and Ohm's law along the conductors; solved results
    report it in ``result.metadata["junction_potentials"][name]`` (V per
    frequency). Use it for cable joints and for the terminals of a
    measuring instrument (see :class:`~groundfield.geometry.junction.Junction`).

    Parameters
    ----------
    world
        Target world.
    position
        Location ``(x, y, z)`` in m (``z`` positive downwards; a point
        above the surface is allowed). Conductors ending on the junction
        use it as their end point.
    name
        Optional unique node name (electrodes and junctions share one
        namespace). Auto-generated (``junction_<n>``) when ``None``.

    Returns
    -------
    Junction
        The registered junction.

    Raises
    ------
    ValueError
        The name is already taken by an electrode or junction, or the
        position is not finite.

    Notes
    -----
    A junction must be connected through conductors to an electrode or
    to a galvanically coupled conductor; a subnetwork without soil
    contact has an undefined potential and is rejected when solved.
    Only backends that declare the ``junctions`` capability (the image
    family) accept worlds with junctions.
    """
    if name is None:
        taken = {e.name for e in world.electrodes} | {j.name for j in world.junctions}
        n = 0
        while f"junction_{n}" in taken:
            n += 1
        name = f"junction_{n}"
    p = tuple(position)
    if len(p) != 3:
        raise ValueError(f"position must be (x, y, z), got {p!r} of length {len(p)}.")
    junction = Junction(name=name, position=(float(p[0]), float(p[1]), float(p[2])))
    world.add_junction(junction)
    return junction

create_source

create_source(world: World, *, attached_to: str | Electrode | Junction, name: str | None = ..., kind: Literal['current'] = ..., magnitude: float = ..., phase_deg: float = ..., return_to: str | Electrode | Junction | None = ...) -> CurrentSource
create_source(world: World, *, attached_to: str | Electrode | Junction, name: str | None = ..., kind: Literal['voltage'], magnitude: float = ..., phase_deg: float = ..., return_to: str | Electrode | Junction | None = ..., internal_resistance_ohm: float | None = ..., internal_inductance_h: float | None = ...) -> VoltageSource
create_source(world: World, *, attached_to: str | Electrode | Junction, name: str | None = None, kind: SourceKind = 'current', magnitude: float = 1.0, phase_deg: float = 0.0, return_to: str | Electrode | Junction | None = None, internal_resistance_ohm: float | None = None, internal_inductance_h: float | None = None) -> Source

Create a source and register it with world.

Parameters:

Name Type Description Default
world World

Target world.

required
attached_to str | Electrode | Junction

Node the source feeds: an electrode or a junction (create_junction()), or its name.

required
name str | None

Optional unique name. Auto-generated (source_<n>) when None.

None
kind SourceKind

"current" (default) or "voltage" (SourceKind). A voltage source fixes attached_to at magnitude volts above return_to (or remote earth); its current is solved for (VoltageSource; every built-in backend solves it).

'current'
magnitude float

Amplitude in A (current source) or V (voltage source), RMS; finite. A current source of magnitude 0 is rejected when the world is solved; a voltage source of 0 V is an ideal short.

1.0
phase_deg float

Phase angle in degrees; finite.

0.0
return_to str | Electrode | Junction | None

Optional second terminal (electrode or junction, or its name): the source injects \(+I\) at attached_to and \(-I\) at return_to (auxiliary electrode of a fall-of-potential measurement, return conductor end); a voltage source holds attached_to at \(U\) above it. None (default) returns the current through remote earth.

None
internal_resistance_ohm float | None

Internal series impedance \(Z_q = R + j\omega L\) of a voltage source, in Ω and H (finite, ≥ 0; None: 0, the ideal source). The source then holds attached_to at \(U - Z_q I\) above return_to. A current source has no internal impedance.

None
internal_inductance_h float | None

Internal series impedance \(Z_q = R + j\omega L\) of a voltage source, in Ω and H (finite, ≥ 0; None: 0, the ideal source). The source then holds attached_to at \(U - Z_q I\) above return_to. A current source has no internal impedance.

None

Returns:

Type Description
CurrentSource or VoltageSource

The registered source.

Raises:

Type Description
ValueError

Unknown kind (with the closest valid kind); attached_to names a conductor (a conductor is not a node — put a junction at its end); attached_to and return_to are the same node; non-finite magnitude / phase_deg; a negative or non-finite internal impedance, or one given for a current source.

KeyError

attached_to / return_to names no electrode or junction of world (with the closest names).

Source code in src/groundfield/api.py
def create_source(
    world: World,
    *,
    attached_to: str | Electrode | Junction,
    name: str | None = None,
    kind: SourceKind = "current",
    magnitude: float = 1.0,
    phase_deg: float = 0.0,
    return_to: str | Electrode | Junction | None = None,
    internal_resistance_ohm: float | None = None,
    internal_inductance_h: float | None = None,
) -> Source:
    """Create a source and register it with ``world``.

    Parameters
    ----------
    world
        Target world.
    attached_to
        Node the source feeds: an electrode or a junction
        (:func:`create_junction`), or its name.
    name
        Optional unique name. Auto-generated (``source_<n>``) when
        ``None``.
    kind
        ``"current"`` (default) or ``"voltage"`` (:data:`SourceKind`).
        A voltage source fixes ``attached_to`` at ``magnitude`` volts
        above ``return_to`` (or remote earth); its current is solved for
        (:class:`~groundfield.sources.VoltageSource`; every built-in
        backend solves it).
    magnitude
        Amplitude in A (current source) or V (voltage source), RMS;
        finite. A current source of magnitude 0 is rejected when the
        world is solved; a voltage source of 0 V is an ideal short.
    phase_deg
        Phase angle in degrees; finite.
    return_to
        Optional second terminal (electrode or junction, or its name):
        the source injects $+I$ at ``attached_to`` and $-I$ at
        ``return_to`` (auxiliary electrode of a fall-of-potential
        measurement, return conductor end); a voltage source holds
        ``attached_to`` at $U$ above it. ``None`` (default) returns
        the current through remote earth.
    internal_resistance_ohm, internal_inductance_h
        Internal series impedance $Z_q = R + j\\omega L$ of a voltage
        source, in Ω and H (finite, ≥ 0; ``None``: 0, the ideal source).
        The source then holds ``attached_to`` at $U - Z_q I$ above
        ``return_to``. A current source has no internal impedance.

    Returns
    -------
    CurrentSource or VoltageSource
        The registered source.

    Raises
    ------
    ValueError
        Unknown ``kind`` (with the closest valid kind); ``attached_to``
        names a conductor (a conductor is not a node — put a junction
        at its end); ``attached_to`` and ``return_to`` are the same
        node; non-finite ``magnitude`` / ``phase_deg``; a negative or
        non-finite internal impedance, or one given for a current
        source.
    KeyError
        ``attached_to`` / ``return_to`` names no electrode or junction
        of ``world`` (with the closest names).
    """
    cls = _SOURCE_CLASSES.get(kind)
    if cls is None:
        raise ValueError(
            f"Unknown source kind {kind!r}.{did_you_mean(str(kind), _SOURCE_CLASSES)} "
            f"Valid kinds: {', '.join(repr(k) for k in _SOURCE_CLASSES)}."
        )
    if name is None:
        name = _auto_name(world, "sources", "source")

    def _name_of(obj: Any) -> str:
        if isinstance(obj, str):
            return obj
        if hasattr(obj, "name"):
            return str(obj.name)
        raise TypeError(
            "attached_to / return_to must be a string or an object with "
            f".name, got {type(obj).__name__}."
        )

    impedance = {
        key: value
        for key, value in (
            ("internal_resistance_ohm", internal_resistance_ohm),
            ("internal_inductance_h", internal_inductance_h),
        )
        if value is not None
    }
    if impedance and kind != "voltage":
        raise ValueError(
            f"{', '.join(impedance)}: a current source has no internal "
            "impedance (it impresses its current whatever it drives); pass "
            "kind='voltage' for a source behind an internal impedance."
        )
    src = cls(
        name=name,
        attached_to=_name_of(attached_to),
        return_to=_name_of(return_to) if return_to is not None else None,
        magnitude=magnitude,
        phase_deg=phase_deg,
        **impedance,
    )
    world.add_source(src)
    return src

create_engine

create_engine(*, backend: Backend = 'image', frequencies: Sequence[float] | NDArray[Any] | None = None, segment_length: float | None = None, tolerance: float | None = None, max_iterations: int | None = None, earth_inductive_model: EarthInductiveModel | None = None, image_max_terms: int | None = None, image_series_tol: float | None = None, kernel: KernelKind | None = None, image_far_field: Literal['quadrupole', 'point'] | None = None, options: Mapping[str, Any] | None = None, sommerfeld_assembly: Literal['exact', 'tabulated'] | None = None, max_segments: int | None = None, warn_segments: int | None = None) -> Engine

Create a configured Engine.

Only the arguments you pass are forwarded; every argument left at None takes the Engine default, so the engine is the single source of its defaults and option-level warnings of the engine concern only options you actually set. Backend-specific settings, such as the accuracy controls of mom_sommerfeld (epsabs, epsrel, lambda_max_factor, max_osc_panels) or the mesh of fem, go into options.

The Engine performs an automatic backend dispatch inside Engine.solve(): when backend="image" (the default) is combined with a TwoLayerSoil the call is forwarded to "image_2layer", and with a MultiLayerSoil to "image_nlayer". Notebooks written for the homogeneous case therefore keep working when the soil model is replaced by a layered one.

Parameters:

Name Type Description Default
backend Backend

Numerical method (Backend). Leaving the default "image" lets the engine pick the matching layered image backend from the world's soil model.

'image'
frequencies Sequence[float] | NDArray[Any] | None

Frequencies in Hz (order preserved). Default: [50.0].

None
segment_length float | None

Maximum segment length used to discretise the geometry, in m. Default: the engine default (0.5 m).

None
tolerance float | None

Convergence parameters for iterative solvers. No backend reads them; they are forwarded only when given.

None
max_iterations float | None

Convergence parameters for iterative solvers. No backend reads them; they are forwarded only when given.

None
earth_inductive_model EarthInductiveModel | None

Earth model for the inductive coupling between distributed conductor segments, effective only when a conductor sets inductance_model="neumann" (EarthInductiveModel): "sommerfeld" (engine default since 0.13.0; geometric integration of the σ-dependent vector-potential Green's function, validated against Pollaczek and Carson), "carson_series" (Carson 1926 per-metre correction × length on the anti-parallel image baseline) or "perfect_mirror" (frequency-independent Neumann baseline with an additive image).

None
image_max_terms int | None

Maximum number of image-charge series terms of the layered backends; a truncated series emits a SeriesTruncationWarning.

None
image_series_tol float | None

Series stop tolerance: iteration ends when the geometric tail bound |K|^(n+1)/(1-|K|) falls below this value.

None
kernel KernelKind | None

Field / reaction-matrix kernel (KernelKind): "point" reproduces the results of earlier releases, "line" integrates each segment as a uniform line source. None keeps the engine default.

None
image_far_field Literal['quadrupole', 'point'] | None

Form of the far images of the line kernel in two-layer soil, "quadrupole" (engine default) or "point" (faster) (Engine.image_far_field).

None
options Mapping[str, Any] | None

Backend-specific settings, keyed by backend name, e.g. {"mom_sommerfeld": {"epsabs": 1e-8}} or option models such as MomSommerfeldOptions; forwarded to Engine.options.

None
sommerfeld_assembly Literal['exact', 'tabulated'] | None

"tabulated" (engine default since 2026.11) or "exact" (per segment pair, the default up to 0.15.0) assembly of the Sommerfeld earth-return correction of inductive conductors (Engine.sommerfeld_assembly).

None
max_segments int | None

Resource limit of the engine: the largest number of leakage segments and of nodal unknowns it solves (Engine.max_segments). Default: the module constant groundfield.diagnostics.HARD_LIMIT (20 000).

None
warn_segments int | None

Size of the soft notice of the engine: at or above this number of leakage segments or nodal unknowns the solve warns that it may take minutes (Engine.warn_segments). Default: the module constant groundfield.diagnostics.SOFT_LIMIT (5 000).

None

Returns:

Type Description
Engine

The configured engine.

Raises:

Type Description
TypeError

An unknown keyword argument.

ValueError

A value the engine rejects.

Source code in src/groundfield/api.py
def create_engine(
    *,
    backend: Backend = "image",
    frequencies: Sequence[float] | npt.NDArray[Any] | None = None,
    segment_length: float | None = None,
    tolerance: float | None = None,
    max_iterations: int | None = None,
    earth_inductive_model: EarthInductiveModel | None = None,
    image_max_terms: int | None = None,
    image_series_tol: float | None = None,
    kernel: KernelKind | None = None,
    image_far_field: Literal["quadrupole", "point"] | None = None,
    options: Mapping[str, Any] | None = None,
    sommerfeld_assembly: Literal["exact", "tabulated"] | None = None,
    max_segments: int | None = None,
    warn_segments: int | None = None,
) -> Engine:
    """Create a configured :class:`~groundfield.Engine`.

    Only the arguments you pass are forwarded; every argument left at
    ``None`` takes the :class:`~groundfield.Engine` default, so the engine
    is the single source of its defaults and option-level warnings of the
    engine concern only options you actually set. Backend-specific
    settings, such as the accuracy controls of ``mom_sommerfeld``
    (``epsabs``, ``epsrel``, ``lambda_max_factor``, ``max_osc_panels``) or
    the mesh of ``fem``, go into ``options``.

    The :class:`Engine` performs an automatic backend dispatch inside
    :meth:`Engine.solve`: when ``backend="image"`` (the default) is
    combined with a :class:`TwoLayerSoil` the call is forwarded to
    ``"image_2layer"``, and with a :class:`MultiLayerSoil` to
    ``"image_nlayer"``. Notebooks written for the homogeneous case
    therefore keep working when the soil model is replaced by a
    layered one.

    Parameters
    ----------
    backend
        Numerical method (:data:`~groundfield.solver.engine.Backend`).
        Leaving the default ``"image"`` lets the engine pick the
        matching layered image backend from the world's soil model.
    frequencies
        Frequencies in Hz (order preserved). Default: ``[50.0]``.
    segment_length
        Maximum segment length used to discretise the geometry, in m.
        Default: the engine default (0.5 m).
    tolerance, max_iterations
        Convergence parameters for iterative solvers. No backend reads
        them; they are forwarded only when given.
    earth_inductive_model
        Earth model for the inductive coupling between distributed
        conductor segments, effective only when a conductor sets
        ``inductance_model="neumann"``
        (:data:`~groundfield.solver.engine.EarthInductiveModel`):
        ``"sommerfeld"`` (engine default since 0.13.0; geometric
        integration of the σ-dependent vector-potential Green's function,
        validated against Pollaczek and Carson), ``"carson_series"``
        (Carson 1926 per-metre correction × length on the anti-parallel
        image baseline) or ``"perfect_mirror"`` (frequency-independent
        Neumann baseline with an additive image).
    image_max_terms
        Maximum number of image-charge series terms of the layered
        backends; a truncated series emits a
        :class:`~groundfield.solver.image_2layer.SeriesTruncationWarning`.
    image_series_tol
        Series stop tolerance: iteration ends when the geometric tail
        bound ``|K|^(n+1)/(1-|K|)`` falls below this value.
    kernel
        Field / reaction-matrix kernel (:data:`KernelKind`):
        ``"point"`` reproduces the results of earlier releases,
        ``"line"`` integrates each segment as a uniform line source.
        ``None`` keeps the engine default.
    image_far_field
        Form of the far images of the line kernel in two-layer soil,
        ``"quadrupole"`` (engine default) or ``"point"`` (faster)
        (:attr:`Engine.image_far_field <groundfield.Engine.image_far_field>`).
    options
        Backend-specific settings, keyed by backend name, e.g.
        ``{"mom_sommerfeld": {"epsabs": 1e-8}}`` or option models such as
        :class:`~groundfield.solver.MomSommerfeldOptions`; forwarded to
        :attr:`Engine.options <groundfield.Engine.options>`.
    sommerfeld_assembly
        ``"tabulated"`` (engine default since 2026.11) or ``"exact"``
        (per segment pair, the default up to 0.15.0) assembly of the
        Sommerfeld earth-return correction of inductive conductors
        (:attr:`Engine.sommerfeld_assembly
        <groundfield.Engine.sommerfeld_assembly>`).
    max_segments
        Resource limit of the engine: the largest number of leakage
        segments and of nodal unknowns it solves (:attr:`Engine.max_segments
        <groundfield.Engine.max_segments>`). Default: the module constant
        ``groundfield.diagnostics.HARD_LIMIT`` (20 000).
    warn_segments
        Size of the soft notice of the engine: at or above this number of
        leakage segments or nodal unknowns the solve warns that it may take
        minutes (:attr:`Engine.warn_segments
        <groundfield.Engine.warn_segments>`). Default: the module constant
        ``groundfield.diagnostics.SOFT_LIMIT`` (5 000).

    Returns
    -------
    Engine
        The configured engine.

    Raises
    ------
    TypeError
        An unknown keyword argument.
    ValueError
        A value the engine rejects.
    """
    engine_kwargs: dict[str, Any] = {"backend": backend}
    if options is not None:
        engine_kwargs["options"] = dict(options)
    if frequencies is not None:
        # Only a numpy array is converted; anything else (list, tuple, but
        # also a mistaken str or scalar) is validated by the Engine itself.
        if isinstance(frequencies, np.ndarray):
            engine_kwargs["frequencies"] = frequencies.tolist()
        else:
            engine_kwargs["frequencies"] = frequencies
    explicit = {
        "segment_length": segment_length,
        "tolerance": tolerance,
        "max_iterations": max_iterations,
        "earth_inductive_model": earth_inductive_model,
        "image_max_terms": image_max_terms,
        "image_series_tol": image_series_tol,
        "image_far_field": image_far_field,
        "sommerfeld_assembly": sommerfeld_assembly,
        "max_segments": max_segments,
        "warn_segments": warn_segments,
    }
    engine_kwargs.update({k: v for k, v in explicit.items() if v is not None})
    if kernel is not None:
        if "kernel" in Engine.model_fields:
            engine_kwargs["kernel"] = kernel
        elif kernel != "point":
            # Transitional: an engine without the ``kernel`` option only
            # has the point kernel.
            raise ValueError(
                f"kernel={kernel!r} is not available in this build; only "
                "the point kernel is."
            )
    return Engine(**engine_kwargs)

run_simulation

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

Solve world with engine; identical to world.solve(engine).

The call goes through World.solve() and therefore has exactly its semantics, including the source snapshot: the world's sources are restored after the solve even if a backend changes them in flight, and the handles returned by create_source() stay attached to the world.

Parameters:

Name Type Description Default
world World

The world to solve.

required
engine Engine

The engine configuration.

required

Returns:

Type Description
FieldResult

The solution.

Source code in src/groundfield/api.py
def run_simulation(world: World, engine: Engine) -> FieldResult:
    """Solve ``world`` with ``engine``; identical to ``world.solve(engine)``.

    The call goes through :meth:`World.solve` and therefore has exactly
    its semantics, including the source snapshot: the world's sources
    are restored after the solve even if a backend changes them in
    flight, and the handles returned by :func:`create_source` stay
    attached to the world.

    Parameters
    ----------
    world
        The world to solve.
    engine
        The engine configuration.

    Returns
    -------
    FieldResult
        The solution.
    """
    return world.solve(engine)