Skip to content

Backend registry

Every numerical backend of Engine is a registered backend (groundfield.solver.registry, ADR-0014). A registration ties a name to its solve function, its declared capabilities, an optional options model for Engine.options, and flags for deprecated aliases, experimental status and the automatic forwarding by soil model. Engine.solve resolves the name, applies the forwarding, checks the capabilities against the world before any backend code runs, calls the solve function and fills the common metadata of the result.

Built-in backends

Name Soils Kernels Concrete shells Two-terminal sources Junctions Voltage sources Status
image homogeneous (forwards two- and multi-layer) line, point yes yes yes yes default
image_2layer two-layer line, point yes yes yes yes
mom homogeneous, two-layer point yes (since 2026.11) yes yes yes
mom_sommerfeld any number of layers point yes (since 2026.11) yes yes yes options: MomSommerfeldOptions
fem any number of layers — yes (since 2026.11) yes (since 2026.11) yes (since 2026.11) yes (since 2026.11) experimental; axisymmetric model for coaxial rods and rings, 3-D model otherwise (fem3d extra); options: FemOptions
cim → image deprecated alias
bem → mom deprecated alias
image_nlayer homogeneous, two-layer line, point yes yes yes yes deprecated name of the image dispatch

Every built-in backend honours every conductor model (lumped, distributed, inductive, skin effect). Since its conforming model of 2026.11 (user decision Q37) fem runs the network of the shared pipeline like the integral backends: its axisymmetric model solves rods on one vertical axis and horizontal rings centred on it, its three-dimensional model (the optional fem3d extra) every other world, galvanic distributed conductors included (FemOptions.model). Up to then it solved distributed and inductive conductors as lumped resistive branches and rejected shells, junctions, two-terminal and voltage sources. The table is checked against the registry:

import groundfield as gf
from groundfield.solver import get_backend

assert gf.available_backends() == ("image", "image_2layer", "mom", "mom_sommerfeld", "fem")
assert set(gf.available_backends(include_deprecated=True)) - set(gf.available_backends()) == {
    "cim", "bem", "image_nlayer"
}

caps = {name: get_backend(name).capabilities for name in gf.available_backends()}
assert caps["image"].kernels == {"line", "point"} and caps["mom"].kernels == {"point"}
assert caps["mom_sommerfeld"].soils == {"homogeneous", "two_layer", "multi_layer"}
assert caps["image"].concrete_shells and caps["mom"].concrete_shells
assert caps["mom_sommerfeld"].concrete_shells and caps["fem"].concrete_shells
assert caps["fem"].two_terminal_sources and caps["fem"].junctions
assert caps["fem"].conductors == {"lumped", "distributed", "inductive", "skin"}
assert all(caps[n].voltage_sources for n in gf.available_backends())
assert get_backend("fem").experimental
assert get_backend("cim").deprecated_alias_of == "image"
assert get_backend("bem").deprecated_alias_of == "mom"

What the capability check does

A world that a backend cannot represent raises BackendCapabilityError (a subclass of ValueError and NotImplementedError) naming the backends that can: an unsupported layer count, electrodes with a concrete-shell coefficient, junction nodes, voltage sources, or an explicitly requested kernel the backend does not have. Adjacent layers of equal resistivity count as one layer.

A world that a backend solves with a documented simplification warns with BackendCapabilityWarning and solves: conductor models the backend reduces (no built-in backend since 2026.11), or a return_to terminal on a backend that returns the current through remote earth.

Solving with a deprecated alias warns with DeprecationWarning; the first solve with an experimental backend in a process warns once with ExperimentalBackendWarning. Options for a backend that will not run warn with BackendOptionsWarning.

Registering a backend

register_backend(name, solve_fn, capabilities=..., options_model=...) adds a backend without changing Engine.solve; the solve function has the signature solve_fn(world, engine, **options) -> FieldResult. A registered name is accepted by Engine(backend=...) and listed by available_backends().

API reference

registry

Backend registry: names, capabilities, options and the solve contract.

Every numerical backend of Engine is a registered backend. A registration ties a name to

  • a solve function solve_fn(world, engine, **options) -> FieldResult;
  • the capabilities of the backend (BackendCapabilities): which soil models, conductor models and source kinds it can represent;
  • an optional options model (a BackendOptions subclass) that validates the backend-specific settings in Engine.options; the validated options are passed to the solve function as keyword arguments;
  • optional aliases, a deprecated-alias target, an experimental flag and an auto-forwarding rule by soil model.

Engine.solve resolves the requested name, applies the auto-forwarding, checks the capabilities against the world before any backend code runs, calls the solve function and fills the common metadata core of the result. Adding a backend therefore needs one register_backend() call and no change to Engine.solve.

Capability checks

A world that a backend cannot represent raises BackendCapabilityError naming the backends that can solve it:

  • the soil: homogeneous (one layer), two-layer, or n-layer (\(n \ge 3\)). Adjacent layers of equal resistivity are one layer physically, so a stack is acceptable to a backend that supports any layer count between the merged and the declared one (the check is conservative: it never rejects a world the backend could solve);
  • electrodes with a concrete-shell correction (ADR-0012);
  • leakage-free junction nodes (World.junctions) on a backend that does not build its nodal system through the shared pipeline;
  • a source kernel requested explicitly that the backend does not implement.

A world that a backend solves with a documented simplification emits BackendCapabilityWarning and solves:

  • conductor models the backend reduces (no built-in backend since 2026.11; fem treated distributed conductors as lumped branches and ignored inductance and the skin effect up to its conforming model, user decision Q37);
  • sources with a return_to electrode on a backend that returns the current through remote earth instead.
Backend options

The validated options of the backend that runs are passed as keyword arguments. Settings that several backends and the post-solve layer share are common Engine fields, not backend options: segment_length, earth_inductive_model and the Tagg / Sunde image-series controls image_max_terms / image_series_tol (consumed by image_2layer, image_nlayer, mom, mom_sommerfeld on its delegated two-layer path and solve_mutual_*, and recorded in FieldResult.metadata["series"], from which FieldResult.potential() takes them for the post-solve field evaluation; the deprecated names cim and bem run image and mom). Their single documented defaults are DEFAULT_IMAGE_MAX_TERMS and DEFAULT_IMAGE_SERIES_TOL. image_far_field (the form of the far images of the line kernel, "quadrupole" or "point") is read by the image family in two-layer soil and solve_mutual_* and recorded in the same place.

Deprecated aliases and experimental backends

Solving with a deprecated alias emits a DeprecationWarning that names the replacement and the earliest removal (DEPRECATION_REMOVAL). The first solve with an experimental backend in a process emits ExperimentalBackendWarning once. Neither is emitted for the internal auto-forwarding.

Since review pass 10 (10.76) cim and bem are pure deprecated aliases of image and mom (both assembled the same system as their target), image_nlayer is a deprecated name of the image auto-dispatch that keeps its own solve function, so the forwarding of image to it stays silent, and fem is experimental.

DEFAULT_IMAGE_MAX_TERMS module-attribute

DEFAULT_IMAGE_MAX_TERMS = 300

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

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

DEFAULT_IMAGE_SERIES_TOL module-attribute

DEFAULT_IMAGE_SERIES_TOL = 1e-06

Default stop tolerance of the Tagg / Sunde image series.

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

DEPRECATION_REMOVAL module-attribute

DEPRECATION_REMOVAL = '2027.5'

Earliest calendar version in which deprecated names are removed.

BackendCapabilities dataclass

BackendCapabilities(soils: Set[str], conductors: Set[str] = frozenset(_CONDUCTOR_FEATURES), concrete_shells: bool = False, two_terminal_sources: bool = False, kernels: Set[str] = frozenset({'point'}), junctions: bool = False, voltage_sources: bool = False)

What a backend can represent.

Parameters:

Name Type Description Default
soils Set[str]

Soil layer counts the backend solves: "homogeneous" (one layer), "two_layer", "multi_layer" (three or more). Any set of names is accepted ({"homogeneous"}); the collections are stored as frozenset.

required
conductors Set[str]

Conductor models the backend honours: "lumped" (a single series branch), "distributed" (discretize_segment_length set), "inductive" (inductance_model set) and "skin" (resistance_model="skin", the frequency-dependent resistance of review pass 10, 10.37; audit round 2, A2C-4). A world using a model outside this set solves with a BackendCapabilityWarning.

frozenset(_CONDUCTOR_FEATURES)
concrete_shells bool

Whether the backend consumes the per-electrode concrete-shell coefficient concrete_shell_coefficient_ohm_m (ADR-0012).

False
two_terminal_sources bool

Whether the backend returns a source current through Source.return_to. If not, a world with a return electrode solves with a BackendCapabilityWarning and the current returns through remote earth.

False
junctions bool

Whether the backend represents leakage-free junction nodes (World.junctions): conductors ending on them and sources attached to them. A world with junctions is rejected by a backend without this capability.

False
voltage_sources bool

Whether the backend solves impressed voltage sources (VoltageSource, modified nodal analysis; 2026.11). A world with a voltage source is rejected by a backend without this capability.

False
kernels Set[str]

Source kernels the backend implements ("point", "line"). Empty for backends without a source kernel (volume methods); those accept any kernel setting.

frozenset({'point'})

BackendCapabilityError

Bases: ValueError, NotImplementedError

The selected backend cannot represent the world.

Raised by Engine.solve() before any backend code runs. The message names the missing capability and the registered backends that can solve the world. The backend functions raise it as well when they are called directly with a soil model they cannot solve (solve_image with a layered soil, solve_image_2layer with a homogeneous soil, solve_image_nlayer and solve_mom with three or more distinct layers), and so does the concrete-shell guard of the backends without the shell correction: one error type for one situation (audit A1-08). TypeError is left for a world.soil that is no soil model at all.

Subclasses both ValueError and NotImplementedError, the types image_nlayer, cim, bem and the concrete-shell guard raised for the same situations in 0.15.0. Changed in 2026.11: image_2layer (homogeneous soil, layer stack) and mom (three or more layers) raised TypeError, which does not catch this error; catch BackendCapabilityError (or ValueError).

BackendCapabilityWarning

Bases: UserWarning

The backend solves the world with a documented simplification.

BackendOptions

Bases: BaseModel

Base class of the backend-specific option models.

Subclasses declare the keyword arguments of one backend's solve function as validated, immutable fields. Unknown keys are rejected.

BackendOptionsWarning

Bases: UserWarning

Engine.options configures a backend that will not run.

BackendSpec dataclass

BackendSpec(name: str, solve_fn: SolveFunction | str | None, capabilities: BackendCapabilities | None, options_model: type[BackendOptions] | None = None, aliases: tuple[str, ...] = (), deprecated_alias_of: str | None = None, experimental: bool = False, forward: tuple[tuple[str, str], ...] = (), summary: str = '')

Registration record of one backend name.

Attributes:

Name Type Description
name str

Registered name.

solve_fn SolveFunction | str | None

Solve function, or a lazy "module:function" reference that is imported on every call (so monkeypatching the module works). None for a pure deprecated alias, which runs its target.

capabilities BackendCapabilities | None

Declared capabilities; None only for a pure alias.

options_model type[BackendOptions] | None

BackendOptions subclass validating Engine.options for this backend, or None.

aliases tuple[str, ...]

Further accepted names (resolved silently).

deprecated_alias_of str | None

Replacement name if this name is deprecated.

experimental bool

Whether solving with the backend emits ExperimentalBackendWarning (once per process).

forward tuple[tuple[str, str], ...]

Auto-forwarding rule: pairs (soil model kind, backend name).

summary str

One-line description.

is_pure_alias property

is_pure_alias: bool

Whether the name only forwards to deprecated_alias_of.

forward_target

forward_target(soil_kind: str) -> str | None

Backend the call is forwarded to for a soil model kind, if any.

Source code in src/groundfield/solver/registry.py
def forward_target(self, soil_kind: str) -> str | None:
    """Backend the call is forwarded to for a soil model kind, if any."""
    for kind, target in self.forward:
        if kind == soil_kind:
            return target
    return None

resolve_solve_fn

resolve_solve_fn() -> SolveFunction

Return the callable solve function (imports lazy references).

Returns:

Type Description
Callable

solve_fn(world, engine, **options) -> FieldResult.

Raises:

Type Description
TypeError

For a pure alias, which has no solve function of its own.

Source code in src/groundfield/solver/registry.py
def resolve_solve_fn(self) -> SolveFunction:
    """Return the callable solve function (imports lazy references).

    Returns
    -------
    Callable
        ``solve_fn(world, engine, **options) -> FieldResult``.

    Raises
    ------
    TypeError
        For a pure alias, which has no solve function of its own.
    """
    fn = self.solve_fn
    if fn is None:
        raise TypeError(f"Backend '{self.name}' is a pure alias.")
    if isinstance(fn, str):
        module_name, _, attr = fn.partition(":")
        return getattr(importlib.import_module(module_name), attr)
    return fn

ExperimentalBackendWarning

Bases: UserWarning

An experimental backend was used (emitted once per process).

FemOptions

Bases: BackendOptions

Mesh, extrapolation and truncation controls of the fem backend.

Forwarded to groundfield.solver.fem.solve_fem(). The defaults reproduce the backend's own signature defaults. Since 2026.11 fem is a conforming finite-element model (user decision Q37): axisymmetric for rods on one axis and rings around it, three-dimensional for every other world (model, source_radius, growth, concrete_resistivity, max_nodes_3d, max_ports_3d; the optional fem3d extra). The controls of the equivalent-hemisphere mesh (n_radial, n_axial, z_far_factor) are gone.

MomSommerfeldOptions

Bases: BackendOptions

Accuracy controls of the mom_sommerfeld backend.

Forwarded to groundfield.solver.mom_sommerfeld.solve_mom_sommerfeld(). The defaults reproduce the backend's own signature defaults.

ResolvedBackend dataclass

ResolvedBackend(requested: str, spec: BackendSpec, deprecated: BackendSpec | None)

Outcome of resolve_backend() for one world.

Attributes:

Name Type Description
requested str

Name as given in Engine.backend.

spec BackendSpec

Record of the backend that runs (after alias resolution and auto-forwarding).

deprecated BackendSpec | None

Record of the requested deprecated alias, or None.

available_backends

available_backends(*, include_deprecated: bool = False) -> tuple[str, ...]

Registered backend names in registration order.

Parameters:

Name Type Description Default
include_deprecated bool

Also list deprecated aliases.

False

Returns:

Type Description
tuple of str

Backend names (aliases from aliases= are not listed).

Source code in src/groundfield/solver/registry.py
def available_backends(*, include_deprecated: bool = False) -> tuple[str, ...]:
    """Registered backend names in registration order.

    Parameters
    ----------
    include_deprecated
        Also list deprecated aliases.

    Returns
    -------
    tuple of str
        Backend names (aliases from ``aliases=`` are not listed).
    """
    return tuple(
        name
        for name, spec in _REGISTRY.items()
        if include_deprecated or spec.deprecated_alias_of is None
    )

check_capabilities

check_capabilities(resolved: ResolvedBackend, world: World, *, kernel: str | None = None, kernel_explicit: bool = False) -> None

Check that the resolved backend can represent world.

Parameters:

Name Type Description Default
resolved ResolvedBackend

Outcome of resolve_backend().

required
world World

World to be solved.

required
kernel str | None

Source kernel requested by the engine, if the engine has one.

None
kernel_explicit bool

Whether the kernel was set explicitly (a default kernel that the backend does not implement is replaced by the backend's own).

False

Raises:

Type Description
BackendCapabilityError

If the backend cannot represent the world.

Warns:

Type Description
BackendCapabilityWarning

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

Source code in src/groundfield/solver/registry.py
def check_capabilities(
    resolved: ResolvedBackend,
    world: World,
    *,
    kernel: str | None = None,
    kernel_explicit: bool = False,
) -> None:
    """Check that the resolved backend can represent ``world``.

    Parameters
    ----------
    resolved
        Outcome of :func:`resolve_backend`.
    world
        World to be solved.
    kernel
        Source kernel requested by the engine, if the engine has one.
    kernel_explicit
        Whether the kernel was set explicitly (a default kernel that the
        backend does not implement is replaced by the backend's own).

    Raises
    ------
    BackendCapabilityError
        If the backend cannot represent the world.

    Warns
    -----
    BackendCapabilityWarning
        If the backend solves the world with a documented
        simplification (reduced conductor model, ignored
        ``return_to``).
    """
    spec = resolved.spec
    caps = _capabilities(spec)
    label = f"'{resolved.requested}'"
    if resolved.requested != spec.name:
        label += f" (running '{spec.name}')"
    problems = _hard_problems(spec, world, kernel, kernel_explicit)
    if problems:
        capable = _capable_backends(world, kernel, kernel_explicit)
        alternatives = (
            f"Backends that can: {', '.join(capable)}."
            if capable
            else "No registered backend supports this combination."
        )
        raise BackendCapabilityError(
            f"Backend {label} cannot solve this world: "
            f"{'; '.join(problems)}. {alternatives}"
        )

    reduced = sorted(_conductor_features(world) - caps.conductors)
    if reduced:
        able = [
            f"'{n}'"
            for n in available_backends()
            if set(reduced) <= _capabilities(_REGISTRY[n]).conductors
        ]
        dc = (
            " at their DC resistance (the skin effect of resistance_model="
            "'skin' is ignored)"
            if "skin" in reduced
            else ""
        )
        warn_external(
            f"Backend '{spec.name}' does not implement the {', '.join(reduced)} "
            "conductor model(s) of this world and solves them as lumped, "
            f"purely resistive branches{dc}. Backends that implement them: "
            f"{', '.join(able)}.",
            BackendCapabilityWarning,
        )
    two_terminal = [s.name for s in world.sources if getattr(s, "return_to", None)]
    if two_terminal and not caps.two_terminal_sources:
        warn_external(
            f"Backend '{spec.name}' ignores Source.return_to (source(s) "
            f"{two_terminal}): the current returns through remote earth, not "
            "through the return electrode.",
            BackendCapabilityWarning,
        )

effective_kernel

effective_kernel(spec: BackendSpec, requested: str | None) -> str | None

Kernel a backend uses when the engine requests requested.

Parameters:

Name Type Description Default
spec BackendSpec

Record of the backend that runs.

required
requested str | None

Kernel requested by the engine, or None.

required

Returns:

Type Description
str or None

None for backends without a source kernel; otherwise the requested kernel if implemented, else the backend's own ("point" when available).

Source code in src/groundfield/solver/registry.py
def effective_kernel(spec: BackendSpec, requested: str | None) -> str | None:
    """Kernel a backend uses when the engine requests ``requested``.

    Parameters
    ----------
    spec
        Record of the backend that runs.
    requested
        Kernel requested by the engine, or ``None``.

    Returns
    -------
    str or None
        ``None`` for backends without a source kernel; otherwise the
        requested kernel if implemented, else the backend's own
        (``"point"`` when available).
    """
    kernels = spec.capabilities.kernels if spec.capabilities else frozenset()
    if not kernels:
        return None
    if requested in kernels:
        return requested
    return "point" if "point" in kernels else sorted(kernels)[0]

emit_resolution_warnings

emit_resolution_warnings(resolved: ResolvedBackend) -> None

Deprecation warning for a requested alias; experimental warning once.

Source code in src/groundfield/solver/registry.py
def emit_resolution_warnings(resolved: ResolvedBackend) -> None:
    """Deprecation warning for a requested alias; experimental warning once."""
    if resolved.deprecated is not None:
        warn_external(
            f"Backend name '{resolved.deprecated.name}' is deprecated; use "
            f"'{resolved.deprecated.deprecated_alias_of}' instead. The alias "
            f"will be removed no earlier than {DEPRECATION_REMOVAL}.",
            DeprecationWarning,
        )
    spec = resolved.spec
    if spec.experimental and spec.name not in _EXPERIMENTAL_WARNED:
        warn_external(
            f"Backend '{spec.name}' is experimental: its results are not "
            "validated as a cross-check and may change between releases.",
            ExperimentalBackendWarning,
        )
        # Marked after the warning, so an "error" filter raises on every
        # solve instead of only the first one.
        _EXPERIMENTAL_WARNED.add(spec.name)

get_backend

get_backend(name: str) -> BackendSpec

Look up a backend by name or alias.

Parameters:

Name Type Description Default
name str

Backend name or alias.

required

Returns:

Type Description
BackendSpec

The registration record (for a deprecated alias: the alias's own record, whose BackendSpec.deprecated_alias_of names the replacement).

Raises:

Type Description
ValueError

If the name is unknown; the message suggests the closest registered name.

Source code in src/groundfield/solver/registry.py
def get_backend(name: str) -> BackendSpec:
    """Look up a backend by name or alias.

    Parameters
    ----------
    name
        Backend name or alias.

    Returns
    -------
    BackendSpec
        The registration record (for a deprecated alias: the alias's
        own record, whose :attr:`BackendSpec.deprecated_alias_of` names
        the replacement).

    Raises
    ------
    ValueError
        If the name is unknown; the message suggests the closest
        registered name.
    """
    key = _ALIASES.get(name, name)
    spec = _REGISTRY.get(key)
    if spec is None:
        known = list(_REGISTRY) + list(_ALIASES)
        close = difflib.get_close_matches(str(name), known, n=1)
        hint = f" Did you mean '{close[0]}'?" if close else ""
        raise ValueError(
            f"Unknown backend '{name}'.{hint} Registered backends: "
            f"{', '.join(available_backends())}."
        )
    return spec

options_key

options_key(name: str) -> str

Canonical Engine.options key of a backend name or alias.

Source code in src/groundfield/solver/registry.py
def options_key(name: str) -> str:
    """Canonical ``Engine.options`` key of a backend name or alias."""
    return _implementation(get_backend(name)).name

reachable_backends

reachable_backends(name: str) -> frozenset[str]

Backends that can run when name is requested (any soil).

Source code in src/groundfield/solver/registry.py
def reachable_backends(name: str) -> frozenset[str]:
    """Backends that can run when ``name`` is requested (any soil)."""
    spec = _implementation(get_backend(name))
    names = {spec.name}
    for _, target in spec.forward:
        if target in _REGISTRY or target in _ALIASES:
            names.add(_implementation(get_backend(target)).name)
    return frozenset(names)

register_backend

register_backend(name: str, solve_fn: SolveFunction | str | None, *, capabilities: BackendCapabilities | None = None, options_model: type[BackendOptions] | None = None, aliases: Iterable[str] = (), deprecated_alias_of: str | None = None, experimental: bool = False, forward: Mapping[str, str] | None = None, summary: str = '', replace: bool = False) -> BackendSpec

Register a backend name.

Parameters:

Name Type Description Default
name str

Backend name as used in Engine(backend=name).

required
solve_fn SolveFunction | str | None

solve_fn(world, engine, **options) -> FieldResult, or a lazy "package.module:function" reference. None registers a pure deprecated alias that runs deprecated_alias_of.

required
capabilities BackendCapabilities | None

What the backend can represent. Required unless solve_fn is None (a pure alias inherits its target's capabilities).

None
options_model type[BackendOptions] | None

BackendOptions subclass for Engine.options[name]. Its fields must be keyword arguments of solve_fn.

None
aliases Iterable[str]

Further accepted names, resolved without a warning.

()
deprecated_alias_of str | None

Registered replacement name. Solving with name then emits a DeprecationWarning naming the replacement and DEPRECATION_REMOVAL. With a solve_fn the old implementation keeps running; without, the replacement runs.

None
experimental bool

Emit ExperimentalBackendWarning on the first solve in a process.

False
forward Mapping[str, str] | None

Auto-forwarding by soil model kind, e.g. {"two_layer": "image_2layer"}. Targets are resolved at solve time.

None
summary str

One-line description.

''
replace bool

Allow replacing an existing registration of name; the name keeps its position in available_backends().

False

Returns:

Type Description
BackendSpec

The stored registration record.

Raises:

Type Description
ValueError

If the name is taken (and replace is false), the alias target is unknown or itself deprecated, or the arguments are inconsistent.

Source code in src/groundfield/solver/registry.py
def register_backend(
    name: str,
    solve_fn: SolveFunction | str | None,
    *,
    capabilities: BackendCapabilities | None = None,
    options_model: type[BackendOptions] | None = None,
    aliases: Iterable[str] = (),
    deprecated_alias_of: str | None = None,
    experimental: bool = False,
    forward: Mapping[str, str] | None = None,
    summary: str = "",
    replace: bool = False,
) -> BackendSpec:
    """Register a backend name.

    Parameters
    ----------
    name
        Backend name as used in ``Engine(backend=name)``.
    solve_fn
        ``solve_fn(world, engine, **options) -> FieldResult``, or a lazy
        ``"package.module:function"`` reference. ``None`` registers a
        pure deprecated alias that runs ``deprecated_alias_of``.
    capabilities
        What the backend can represent. Required unless ``solve_fn`` is
        ``None`` (a pure alias inherits its target's capabilities).
    options_model
        :class:`BackendOptions` subclass for ``Engine.options[name]``.
        Its fields must be keyword arguments of ``solve_fn``.
    aliases
        Further accepted names, resolved without a warning.
    deprecated_alias_of
        Registered replacement name. Solving with ``name`` then emits a
        :class:`DeprecationWarning` naming the replacement and
        :data:`DEPRECATION_REMOVAL`. With a ``solve_fn`` the old
        implementation keeps running; without, the replacement runs.
    experimental
        Emit :class:`ExperimentalBackendWarning` on the first solve in a
        process.
    forward
        Auto-forwarding by soil model kind, e.g. ``{"two_layer":
        "image_2layer"}``. Targets are resolved at solve time.
    summary
        One-line description.
    replace
        Allow replacing an existing registration of ``name``; the name
        keeps its position in :func:`available_backends`.

    Returns
    -------
    BackendSpec
        The stored registration record.

    Raises
    ------
    ValueError
        If the name is taken (and ``replace`` is false), the alias
        target is unknown or itself deprecated, or the arguments are
        inconsistent.
    """
    if not isinstance(name, str) or not name or name != name.strip():
        raise ValueError(f"Backend name must be a non-empty string, got {name!r}.")
    alias_names = tuple(aliases)
    taken = [n for n in (name, *alias_names) if n in _REGISTRY or n in _ALIASES]
    if replace and name in _REGISTRY:
        own = {name, *_REGISTRY[name].aliases}
        taken = [n for n in taken if n not in own]
    if taken:
        raise ValueError(
            f"Backend name(s) {taken} already registered; pass replace=True "
            "to replace a registration."
        )
    if deprecated_alias_of is not None:
        target = _REGISTRY.get(deprecated_alias_of)
        if target is None:
            raise ValueError(
                f"deprecated_alias_of={deprecated_alias_of!r} is not a "
                "registered backend."
            )
        if target.deprecated_alias_of is not None:
            raise ValueError(
                f"Backend '{deprecated_alias_of}' is itself deprecated; "
                "point the alias at its replacement."
            )
    if solve_fn is None:
        if deprecated_alias_of is None:
            raise ValueError("solve_fn=None is only allowed for a deprecated alias.")
        if capabilities is not None or options_model is not None or forward:
            raise ValueError(
                "A pure deprecated alias inherits capabilities, options and "
                "forwarding from its target; do not pass them."
            )
    elif capabilities is None:
        raise ValueError(f"Backend '{name}' needs capabilities.")
    if options_model is not None and not (
        isinstance(options_model, type) and issubclass(options_model, BackendOptions)
    ):
        raise TypeError("options_model must be a BackendOptions subclass.")
    forward_pairs = tuple((forward or {}).items())
    bad_kinds = sorted({k for k, _ in forward_pairs} - set(_SOIL_KINDS))
    if bad_kinds:
        raise ValueError(f"forward: unknown soil model kind(s) {bad_kinds}.")

    if deprecated_alias_of is not None:
        dependants = [
            s.name for s in _REGISTRY.values() if s.deprecated_alias_of == name
        ]
        if dependants:
            raise ValueError(
                f"Backend(s) {dependants} are deprecated aliases of '{name}'; it "
                "cannot become a deprecated alias itself."
            )
    if replace and name in _REGISTRY:
        # Re-assigning the key below keeps the registration order.
        for alias in _REGISTRY[name].aliases:
            _ALIASES.pop(alias, None)
        _EXPERIMENTAL_WARNED.discard(name)
    spec = BackendSpec(
        name=name,
        solve_fn=solve_fn,
        capabilities=capabilities,
        options_model=options_model,
        aliases=alias_names,
        deprecated_alias_of=deprecated_alias_of,
        experimental=bool(experimental),
        forward=forward_pairs,
        summary=summary,
    )
    _REGISTRY[name] = spec
    for alias in alias_names:
        _ALIASES[alias] = name
    return spec

resolve_backend

resolve_backend(requested: str, world: World) -> ResolvedBackend

Resolve aliases and the auto-forwarding for world.

Parameters:

Name Type Description Default
requested str

Backend name as given in Engine.backend.

required
world World

World to be solved (its soil model kind drives the forwarding).

required

Returns:

Type Description
ResolvedBackend

The backend that runs; emits no warning.

Source code in src/groundfield/solver/registry.py
def resolve_backend(requested: str, world: World) -> ResolvedBackend:
    """Resolve aliases and the auto-forwarding for ``world``.

    Parameters
    ----------
    requested
        Backend name as given in ``Engine.backend``.
    world
        World to be solved (its soil model kind drives the forwarding).

    Returns
    -------
    ResolvedBackend
        The backend that runs; emits no warning.
    """
    first = get_backend(requested)
    deprecated = first if first.deprecated_alias_of is not None else None
    spec = _implementation(first)
    soil_kind = getattr(world.soil, "kind", None)
    target = spec.forward_target(soil_kind) if soil_kind else None
    if target is not None:
        spec = _implementation(get_backend(target))
    return ResolvedBackend(requested=requested, spec=spec, deprecated=deprecated)

soil_kinds

soil_kinds(soil: SoilModel) -> frozenset[str]

Layer-count kinds a soil model can be solved as.

A stack whose adjacent layers share a resistivity can be solved with any layer count between the merged and the declared one.

Parameters:

Name Type Description Default
soil SoilModel

Soil model of the world.

required

Returns:

Type Description
frozenset of str

Subset of {"homogeneous", "two_layer", "multi_layer"}.

Source code in src/groundfield/solver/registry.py
def soil_kinds(soil: SoilModel) -> frozenset[str]:
    """Layer-count kinds a soil model can be solved as.

    A stack whose adjacent layers share a resistivity can be solved with
    any layer count between the merged and the declared one.

    Parameters
    ----------
    soil
        Soil model of the world.

    Returns
    -------
    frozenset of str
        Subset of ``{"homogeneous", "two_layer", "multi_layer"}``.
    """
    merged, declared = _layer_counts(soil)
    return frozenset(_kind_of(n) for n in range(merged, declared + 1))

unregister_backend

unregister_backend(name: str) -> BackendSpec

Remove a registration together with its aliases.

Parameters:

Name Type Description Default
name str

Registered name (not an alias).

required

Returns:

Type Description
BackendSpec

The removed record.

Raises:

Type Description
KeyError

If name is not registered.

Source code in src/groundfield/solver/registry.py
def unregister_backend(name: str) -> BackendSpec:
    """Remove a registration together with its aliases.

    Parameters
    ----------
    name
        Registered name (not an alias).

    Returns
    -------
    BackendSpec
        The removed record.

    Raises
    ------
    KeyError
        If ``name`` is not registered.
    """
    spec = _REGISTRY.pop(name)
    for alias in spec.aliases:
        _ALIASES.pop(alias, None)
    _EXPERIMENTAL_WARNED.discard(name)
    return spec

validate_options_entry

validate_options_entry(key: str, value: Any) -> tuple[str, BackendOptions]

Validate one Engine.options entry.

Parameters:

Name Type Description Default
key str

Backend name or alias.

required
value Any

Options model instance or mapping of option values.

required

Returns:

Type Description
tuple

(canonical backend name, options model instance).

Raises:

Type Description
ValueError

For an unknown backend, a backend without options, an unknown option name (with a suggestion) or a wrong value type.

Source code in src/groundfield/solver/registry.py
def validate_options_entry(key: str, value: Any) -> tuple[str, BackendOptions]:
    """Validate one ``Engine.options`` entry.

    Parameters
    ----------
    key
        Backend name or alias.
    value
        Options model instance or mapping of option values.

    Returns
    -------
    tuple
        ``(canonical backend name, options model instance)``.

    Raises
    ------
    ValueError
        For an unknown backend, a backend without options, an unknown
        option name (with a suggestion) or a wrong value type.
    """
    canonical = options_key(key)
    model = _REGISTRY[canonical].options_model
    if model is None:
        raise ValueError(
            f"Backend '{canonical}' has no backend-specific options. Settings "
            "shared by several backends are Engine fields: segment_length, "
            "earth_inductive_model, image_max_terms, image_series_tol."
        )
    if isinstance(value, model):
        return canonical, value
    if isinstance(value, BackendOptions):
        raise ValueError(
            f"Engine.options['{canonical}'] must be a {model.__name__}, got "
            f"{type(value).__name__}."
        )
    if not isinstance(value, Mapping):
        raise ValueError(
            f"Engine.options['{canonical}'] must be a {model.__name__} or a "
            f"mapping, got {type(value).__name__}."
        )
    unknown = [k for k in value if k not in model.model_fields]
    if unknown:
        hints = []
        for k in unknown:
            close = difflib.get_close_matches(str(k), list(model.model_fields), n=1)
            hints.append(f"'{k}'" + (f" (did you mean '{close[0]}'?)" if close else ""))
        raise ValueError(
            f"Unknown option(s) {', '.join(hints)} for backend '{canonical}'. "
            f"Valid options: {_describe_options(model)}."
        )
    return canonical, model.model_validate(dict(value))

warn_external

warn_external(message: str, category: type[Warning]) -> None

Emit a warning attributed to the first frame outside the package.

Frames inside groundfield and pydantic (model validators) and in the standard library's copy module (copy.replace on Python >= 3.13 calls pydantic's __replace__; audit R2B-06) are skipped, so the warning points at the user's line. This matters most for DeprecationWarning, which Python only shows by default when it is attributed to __main__.

Parameters:

Name Type Description Default
message str

Warning text.

required
category type[Warning]

Warning class.

required
Source code in src/groundfield/solver/registry.py
def warn_external(message: str, category: type[Warning]) -> None:
    """Emit a warning attributed to the first frame outside the package.

    Frames inside ``groundfield`` and ``pydantic`` (model validators) and
    in the standard library's :mod:`copy` module (``copy.replace`` on
    Python >= 3.13 calls pydantic's ``__replace__``; audit R2B-06) are
    skipped, so the warning points at the user's line. This matters most
    for :class:`DeprecationWarning`, which Python only shows by default
    when it is attributed to ``__main__``.

    Parameters
    ----------
    message
        Warning text.
    category
        Warning class.
    """
    warnings.warn(
        message,
        category,
        skip_file_prefixes=(_PACKAGE_DIR, _PYDANTIC_DIR, _COPY_STEM),
    )