Skip to content

Utilities

groundfield.utils holds the helpers that the other subpackages share: the logger names, the "did you mean …?" suggestions in error messages, and the two warning helpers of the public API — one for deprecated names and one for settings that no backend reads. Read this page when you configure logging or want to know where a warning comes from. What each warning means and what to do about it is on Warnings and errors; the deprecated names and their replacements are listed on Deprecations.

Helper Purpose
get_logger, configure loggers below groundfield; a default stream handler
suggest, did_you_mean closest valid names for an unknown name
warn_deprecated, REMOVAL_VERSION, DEPRECATED_SINCE the deprecation policy of the calendar releases
warn_inert, InertConfigurationWarning a setting is stored, but no backend reads it

Logging

Every module logs through get_logger(__name__), so all messages sit below the logger groundfield. The library installs no handler; configure(level) adds one stream handler to groundfield when it has none and sets its level. Any standard logging set-up works as well, for example logging.getLogger("groundfield.solver").setLevel(logging.DEBUG).

Name suggestions

The factories reject an unknown name with the closest valid one:

import groundfield as gf
from groundfield.utils import did_you_mean, suggest

world = gf.create_world(soil=gf.HomogeneousSoil(rho=100.0))
try:
    gf.create_electrode(world, "rnig", name="a", center=(0.0, 0.0, 0.5), radius=1.0)
except ValueError as error:
    message = str(error)   # "Unknown electrode kind 'rnig'. Did you mean 'ring'? ..."

assert "Did you mean 'ring'?" in message
assert suggest("rnig", ["rod", "ring", "strip", "star"]) == ["ring"]
assert did_you_mean("rnig", ["rod", "ring"]) == " Did you mean 'ring'?"

Deprecation policy

A deprecated name keeps working, emits a DeprecationWarning that names its replacement and is removed no earlier than two releases and six months after the announcement: for the names deprecated in DEPRECATED_SINCE (2026.11) that is REMOVAL_VERSION (2027.5) at the earliest. Both helpers point the warning at the first caller outside groundfield and pydantic, the line the user can change, and stay silent when groundfield's own code is the caller.

API reference

utils

Helper utilities.

Cross-cutting helpers used by several subpackages:

DEPRECATED_SINCE module-attribute

DEPRECATED_SINCE = '2026.11'

First calendar-versioned release; the deprecations listed in its changelog start here.

REMOVAL_VERSION module-attribute

REMOVAL_VERSION = '2027.5'

Earliest release that removes the names deprecated in DEPRECATED_SINCE.

Two releases and six months later.

InertConfigurationWarning

Bases: UserWarning

A public setting is stored, but no backend reads it.

Examples are a non-default BoundaryConditions field or a soil relative_permittivity: every backend uses the quasi-static conduction-current formulation with remote-earth boundary conditions, so these values do not change any result. Filter it like any warning category, e.g. warnings.simplefilter("ignore", InertConfigurationWarning).

configure

configure(level: int = logging.INFO) -> None

Install a simple default logging configuration.

Parameters:

Name Type Description Default
level int

Log level for the root logger groundfield. Default INFO.

INFO
Source code in src/groundfield/utils/logging.py
def configure(level: int = logging.INFO) -> None:
    """Install a simple default logging configuration.

    Parameters
    ----------
    level
        Log level for the root logger ``groundfield``. Default
        ``INFO``.
    """
    root = logging.getLogger("groundfield")
    root.setLevel(level)
    if not root.handlers:
        handler = logging.StreamHandler()
        handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s %(name)s :: %(message)s")
        )
        root.addHandler(handler)

did_you_mean

did_you_mean(name: str, candidates: Iterable[str], *, n: int = 1, cutoff: float = 0.6) -> str

Return a " Did you mean 'x'?" sentence, or "".

Parameters:

Name Type Description Default
name str

See suggest().

required
candidates str

See suggest().

required
n str

See suggest().

required
cutoff str

See suggest().

required

Returns:

Type Description
str

A sentence with a leading space, ready to be appended to an error message, or the empty string when nothing is close.

Examples:

>>> did_you_mean("positon", ["position", "length"])
" Did you mean 'position'?"
Source code in src/groundfield/utils/suggest.py
def did_you_mean(
    name: str,
    candidates: Iterable[str],
    *,
    n: int = 1,
    cutoff: float = 0.6,
) -> str:
    """Return a ``" Did you mean 'x'?"`` sentence, or ``""``.

    Parameters
    ----------
    name, candidates, n, cutoff
        See :func:`suggest`.

    Returns
    -------
    str
        A sentence with a leading space, ready to be appended to an
        error message, or the empty string when nothing is close.

    Examples
    --------
    >>> did_you_mean("positon", ["position", "length"])
    " Did you mean 'position'?"
    """
    hits = suggest(name, candidates, n=n, cutoff=cutoff)
    if not hits:
        return ""
    quoted = [f"'{h}'" for h in hits]
    if len(quoted) == 1:
        return f" Did you mean {quoted[0]}?"
    return f" Did you mean {', '.join(quoted[:-1])} or {quoted[-1]}?"

get_logger

get_logger(name: str) -> logging.Logger

Return a logger with the consistent naming scheme.

Parameters:

Name Type Description Default
name str

Usually __name__ of the calling module.

required

Returns:

Type Description
Logger

The standard-library logger of that name.

Source code in src/groundfield/utils/logging.py
def get_logger(name: str) -> logging.Logger:
    """Return a logger with the consistent naming scheme.

    Parameters
    ----------
    name
        Usually ``__name__`` of the calling module.

    Returns
    -------
    logging.Logger
        The standard-library logger of that name.
    """
    return logging.getLogger(name)

warn_deprecated

warn_deprecated(old: str, new: str) -> None

Emit a DeprecationWarning for a renamed or replaced name.

Parameters:

Name Type Description Default
old str

What the caller used, e.g. "HomogeneousSoil: 'resistivity'".

required
new str

Its replacement, e.g. "'rho'".

required
Notes

The message states the replacement and the earliest removal release (REMOVAL_VERSION). See the module docstring for who is warned.

Source code in src/groundfield/utils/deprecation.py
def warn_deprecated(old: str, new: str) -> None:
    """Emit a :class:`DeprecationWarning` for a renamed or replaced name.

    Parameters
    ----------
    old
        What the caller used, e.g. ``"HomogeneousSoil: 'resistivity'"``.
    new
        Its replacement, e.g. ``"'rho'"``.

    Notes
    -----
    The message states the replacement and the earliest removal
    release (:data:`REMOVAL_VERSION`). See the module docstring for who
    is warned.
    """
    _emit(
        f"{old} is deprecated since groundfield {DEPRECATED_SINCE}; use {new} "
        f"instead. The old name will be removed in groundfield "
        f"{REMOVAL_VERSION} at the earliest.",
        DeprecationWarning,
    )

warn_inert

warn_inert(message: str) -> None

Emit an InertConfigurationWarning with message.

Parameters:

Name Type Description Default
message str

Complete sentence(s) naming the setting, its value and why it has no effect.

required
Source code in src/groundfield/utils/deprecation.py
def warn_inert(message: str) -> None:
    """Emit an :class:`InertConfigurationWarning` with ``message``.

    Parameters
    ----------
    message
        Complete sentence(s) naming the setting, its value and why it
        has no effect.
    """
    _emit(message, InertConfigurationWarning)

groundfield.utils.suggest is also the name of the submodule that defines the function, so the function is rendered here separately:

suggest

suggest(name: str, candidates: Iterable[str], *, n: int = 3, cutoff: float = 0.6) -> list[str]

Return the candidates closest to name, best match first.

Parameters:

Name Type Description Default
name str

The name that was not found.

required
candidates Iterable[str]

Valid names. Duplicates are ignored; the original spelling of a candidate is returned.

required
n int

Maximum number of suggestions.

3
cutoff float

Similarity threshold in [0, 1] of difflib.get_close_matches(); candidates below it are not suggested.

0.6

Returns:

Type Description
list of str

Up to n candidates, ordered by decreasing similarity and alphabetically among equally similar ones (so messages are reproducible). A case-insensitive exact match comes first; an empty list means nothing is close enough.

Source code in src/groundfield/utils/suggest.py
def suggest(
    name: str,
    candidates: Iterable[str],
    *,
    n: int = 3,
    cutoff: float = 0.6,
) -> list[str]:
    """Return the candidates closest to ``name``, best match first.

    Parameters
    ----------
    name
        The name that was not found.
    candidates
        Valid names. Duplicates are ignored; the original spelling of a
        candidate is returned.
    n
        Maximum number of suggestions.
    cutoff
        Similarity threshold in ``[0, 1]`` of
        :func:`difflib.get_close_matches`; candidates below it are not
        suggested.

    Returns
    -------
    list of str
        Up to ``n`` candidates, ordered by decreasing similarity and
        alphabetically among equally similar ones (so messages are
        reproducible). A case-insensitive exact match comes first; an
        empty list means nothing is close enough.
    """
    by_lower: dict[str, str] = {}
    for cand in candidates:
        by_lower.setdefault(str(cand).lower(), str(cand))
    key = str(name).lower()
    matcher = difflib.SequenceMatcher(b=key)
    scored: list[tuple[float, str]] = []
    for low, original in by_lower.items():
        matcher.set_seq1(low)
        ratio = 2.0 if low == key else matcher.ratio()
        if ratio >= cutoff:
            scored.append((-ratio, original))
    scored.sort()
    return [original for _, original in scored[:n]]