Skip to content

Core models

Pydantic v2 data classes describing the physical network elements, the configured faults and sources, the per-frequency results and the ComplexNumber helper used throughout the package.

Physical / modelling context

groundinsight represents a grounding network as a labelled, undirected graph. The model layer owns four kinds of objects:

  • Types — BusType, BranchType — carry the SymPy formula strings that are compiled to vectorised callables and evaluated per (f, rho, l) triple. Optional lumped RLC formulas (R_formula, L_formula, C_formula, R_self_formula, L_self_formula, C_self_formula, R_mutual_formula, M_mutual_formula) parameterise the state-space transient solver in groundinsight.simulation.transient.
  • Instances — Bus, Branch — carry concrete numerical values (specific_earth_resistance, length, parallel_coefficient) plus the per-frequency impedance dict \(Z(f) \in \mathbb{C}\) that is built from the formulas at network-build time.
  • Excitation — Source (current or voltage source per bus) and Fault (which bus, which scaling per frequency).
  • Results — Result, ResultBus, ResultBranch, ResultReductionFactor, ResultGroundingImpedance — the outcome of run_fault. Both per-frequency components and the RMS over all frequencies (computed as \(\sqrt{\sum_f |X(f)|^2}\)) are stored.

ComplexNumber is a small Pydantic wrapper over the native complex type. It exists because complex is not natively JSON-serialisable; the wrapper exposes overloaded arithmetic and serialises as a {"real": ..., "imag": ...} dict.

Example

import groundinsight as gi
from groundinsight.models.core_models import (
    Bus, BusType, Branch, BranchType, Source, Fault,
    Network, ComplexNumber,
)

# Build a model directly (notebook style)
bt = BusType(name="GroundRod", system_type="Substation",
             voltage_level=20.0,
             impedance_formula="rho/(2*3.14159*1.5)*(1 + j*0.01*f)")
brt = BranchType(name="ShieldCable", grounding_conductor=True,
                 self_impedance_formula="(0.2 + j*0.4*f/50)*l",
                 mutual_impedance_formula="(0.0 + j*0.4*f/50)*l")

net = Network(name="demo", frequencies=[50.0, 150.0])
b1 = Bus(name="b1", type=bt, impedance={},
         specific_earth_resistance=100.0)
b2 = Bus(name="b2", type=bt, impedance={},
         specific_earth_resistance=100.0)
ln = Branch(name="ln", type=brt, from_bus="b1", to_bus="b2",
            length=2.0, self_impedance={}, mutual_impedance={})
src = Source(name="s1", bus="b1", values={50.0: 1.0, 150.0: 0.05})
flt = Fault(name="f1", bus="b2",
            scalings={50.0: 1.0, 150.0: 0.05})

# JSON round-trip — ComplexNumber serialises as {real, imag}
payload = net.model_dump_json(indent=2)
restored = Network.model_validate_json(payload)

Polars accessors net.res_buses(), net.res_branches() and net.res_all_impedances() produce DataFrames suitable for plotting and reporting. All three pin their column layout, so an empty result is an empty frame with the documented columns rather than a 0×0 one.

frequency_Hz is Float64 in all three. res_buses() and res_branches() add one RMS row per element, marked by the boolean column is_rms; that row carries null in frequency_Hz, because it belongs to no single frequency. Filter per frequency with

# fragment: assumes a solved network `net`
per_50_hz = net.res_buses().filter(pl.col("frequency_Hz") == 50.0)
rms       = net.res_buses().filter(pl.col("is_rms"))

Changed after 0.6.0

Up to 0.6.0 the RMS row carried the literal string "RMS" in frequency_Hz, which forced the whole column to Utf8 — filter(pl.col("frequency_Hz") == 50.0) then matched nothing, and gi.summarize refused the column. Replace pl.col("frequency_Hz") == "RMS" with pl.col("is_rms") and == "50" with == 50.0.

res_buses() also reports I_inj_A / I_inj_degree, the current carried by the earthing conductor at a source or fault bus. That is a different current from I_bus_A, the share dissipated into the soil through the electrode — see ResultBus for why mixing the two is the classic sizing error.

Key figures of a fault

net.res_fault(fault) puts the numbers an assessment starts from side by side — read from the stored result, nothing is solved. One row per network frequency and one RMS row (is_rms true, frequency_Hz null); the schema is pinned in gi.RES_FAULT_SCHEMA:

Column Type Meaning
fault Utf8 the fault
fault_bus Utf8 the bus the result was computed for
frequency_Hz Float64 the frequency; null on the RMS row
is_rms Boolean true on the RMS row
I_F_A Float64 magnitude of the fault current I_F (ResultReductionFactor.i_fault)
I_F_degree Float64 its angle
EPR_fault_V Float64 earth potential rise at the fault bus
EPR_fault_degree Float64 its angle
EPR_max_V Float64 the largest EPR in the network
EPR_max_bus Utf8 the bus it occurs at
r_epr Float64 EPR-based reduction factor (value)
r_current Float64 current-based reduction factor, magnitude of I_E / I_F (value_current)
I_E_A Float64 magnitude of the earth-return current I_E (i_earth)
U_E_V Float64 earthing voltage of EN 50522, the EPR at the fault bus (u_earthing)
Z_E_Ohm Float64 earthing impedance of EN 50522, the driving point at the fault bus (z_earthing)
Z_E_degree Float64 its angle
n_diagnostics Int64 records in Result.diagnostics, the same on every row

A value the result marks as undefined is null — for example r_current and I_E_A at a frequency without fault current. The RMS row carries the stored RMS EPR of the fault bus and the largest one of any bus, and the root sum of squares of I_F, I_E and U_E over the frequencies; ratios, impedances and angles are null there.

# fragment: assumes a network `net` with the fault "F1"
import polars as pl

gi.run_fault(net, "F1")                     # or keep a result from gi.solve
figures = net.res_fault("F1")
at_50_hz = figures.filter(pl.col("frequency_Hz") == 50.0).row(0, named=True)
print(at_50_hz["EPR_fault_V"], at_50_hz["r_current"], at_50_hz["Z_E_Ohm"])
if at_50_hz["n_diagnostics"]:
    print(net.results["F1"].diagnostics)    # what qualifies these numbers

res_fault raises a ValueError for a name that is not a fault of the network and a RuntimeError for a fault without stored result. It reports the stored numbers also when the network was edited since — net.stale_results() says whether that is the case.

Active subset / cache invalidation

Bus.active and Branch.active are plain Pydantic fields that flip an instance in or out of the topology. run_fault reads them on every solve: the default phase_current_mode="auto" needs no paths and drops a path set that no longer matches the active topology; the legacy mode "paths" enumerates the paths again. Enumerated paths are kept in two places that mirror the previous topology when a flag is flipped in-place after define_paths() has populated them:

  • network.paths itself.
  • The network's path-search memo (network.path_cache(), see groundinsight.pathfinder), which is keyed on the same topology fingerprint for fast re-use.

Network.invalidate_paths() is the explicit hook that drops both:

# fragment: assumes a network `net` with the branch "LN_main" and the fault "F1"
net.branches["LN_main"].active = False   # take a branch out of service
net.invalidate_paths()                   # drop the paths of the old topology
gi.run_fault(net, "F1")                  # solves the new topology

Paths of the new topology, as data, come from the enumeration on the Pathfinder page.

The invalidation is scoped to the calling Network instance: cache entries belonging to other live networks in the same process are preserved, so dashboards iterating over a set of feeders do not pay a global cache eviction every time a single network mutates.

Since 0.5.0 the invalidation is also an atomic rebind (self.paths = {} instead of self.paths.clear()), so an external snapshot saved = dict(network.paths) taken before the call keeps its entries:

# fragment: assumes a network `network`
saved = dict(network.paths)        # external snapshot
network.invalidate_paths()
# saved still holds the previously-enumerated paths.

Frequency validation and order warning

Network.frequencies is validated at construction time:

  • Empty / nan / inf / strictly-negative inputs are rejected with a clear ValueError. DC (f = 0) is permitted because the FFT transient solver in groundinsight.simulation.transient uses the zero-frequency bin to carry the steady-state offset.
  • Duplicate frequencies are rejected — the same f twice in the list silently doubled the work in solve_network and doubled the amplitude of the corresponding spectral bin in the FFT transient solver.
  • Non-strictly-monotone-increasing inputs accept the order but emit a NetworkFrequencyOrderWarning(UserWarning) (added in 0.5.0). The FFT transient solver maps spectral bins by position in Network.frequencies, so a shuffled or descending list is almost always a user error. Mirrors groundfield.solver.engine.EngineFrequencyOrderWarning so the three earthing-platform packages share one convention.
import warnings
import groundinsight as gi

with warnings.catch_warnings():
    warnings.simplefilter("error", gi.NetworkFrequencyOrderWarning)
    # Raises instead of just warning — use during validation.
    try:
        gi.create_network(name="net", frequencies=[100.0, 50.0])
    except gi.NetworkFrequencyOrderWarning as refused:
        print(f"refused: {refused}")

Top-level set_active_fault factory

The keep_results= keyword on Network.set_active_fault is also reachable via the top-level factory wrapper:

# fragment: assumes a solved network `net` with the fault "F1"
import groundinsight as gi

# Re-plot the previously cached Result without recomputing it.
gi.set_active_fault(net, "F1", keep_results=True)

Editing a network and stale results

A Bus or Branch stores impedances derived from its type, its specific_earth_resistance and — for a branch — its length, at the network's frequencies. The network keeps them consistent while you edit, and every stored result knows whether it still matches:

import groundinsight as gi

net = gi.create_network(name="demo", frequencies=[50.0, 250.0])
rod = gi.BusType(name="rod", system_type="Tower", voltage_level=20.0,
                 impedance_formula="rho * 0.01 + j*f*1e-4")
cable = gi.BranchType(name="cable", grounding_conductor=True,
                      self_impedance_formula="(0.25 + j*f*0.012)*l",
                      mutual_impedance_formula="(j*f*0.012)*l")
for name in ("a", "b", "c"):
    gi.create_bus(name=name, type=rod, network=net)
gi.create_branch(name="ab", type=cable, from_bus="a", to_bus="b",
                 length=1.0, network=net)
gi.create_branch(name="bc", type=cable, from_bus="b", to_bus="c",
                 length=1.0, network=net)
gi.create_source(name="s", bus="a", values={50.0: 1000.0, 250.0: 100.0},
                 network=net)
gi.create_fault(name="F", bus="c", scalings={50.0: 1.0, 250.0: 1.0},
                network=net)
gi.run_fault(net, "F")

# An input assignment re-derives the element at once ...
net.buses["b"].specific_earth_resistance = 250.0
# ... and the stored result knows that it no longer matches.
print(net.stale_results())          # ['F']

# Several fields at once, all or nothing:
net.update_branch("bc", length=2.5, specific_earth_resistance=200.0)

gi.run_fault(net, "F")
print(net.is_result_stale("F"))     # False
  • Assignment re-derives. Bus.type, Bus.specific_earth_resistance, Branch.type, Branch.length and Branch.specific_earth_resistance on an element that belongs to a network re-derive it through the same code path as Network.add_*; assigning Network.frequencies re-derives every element. A failing derivation raises and leaves the element (or the network) exactly as it was. On an element that belongs to no network an assignment only stores the value.
  • update_bus / update_branch change several fields of one element: every value is validated, the bus references are checked and the impedances derived before anything is written. The derived fields (impedance, self_impedance, …) cannot be updated — assign them directly to override a value for a study; the next input change recomputes them.
  • remove_bus refuses while a branch, source or fault refers to the bus and names all of them; remove_branch, remove_source and remove_fault (which also drops that fault's stored result) complete the set. Unknown names raise ValueError, as everywhere else.
  • Names are keys. Renaming an element that belongs to a network is refused — remove it and add a renamed copy. Rewiring a branch, source or fault to a bus the network does not have is refused. An element belongs to one network at a time; add element.model_copy(deep=True) to another one.
  • Types are read-only. A type has been evaluated into every element that uses it, so it cannot be changed in place. Create a changed type and assign it per element:

    rod_2 = rod.model_copy(update={"impedance_formula": "rho * 0.02 + j*f*1e-4"})
    for name, bus in net.buses.items():
        if bus.type == rod:
            net.update_bus(name, type=rod_2)
    

What makes a result stale. Network.stale_results() lists the faults whose stored result no longer matches the network: Network.frequencies, any bus, branch or source as the solver reads it (impedances, active, the wiring, parallel_coefficient, the source data), or the definition of the result's own fault (bus, scalings). Metadata — description, Fault.t_k_s/n_factor, the IEC 60909 characteristics of a source — and other faults do not count. The check compares a digest of the inputs (Result.input_digest, written by run_fault) with the network's current inputs, so it is a statement about content: undoing an edit makes the result current again, and outage_context, run_sweep and the rho searches, which restore the network, leave the flags as they found them. The one result a study leaves behind computed under modified inputs — the last scenario of run_outage_study, the last point of run_sweep — is reported stale, because it is. The digest is saved with the result to JSON and to the database; results written by an older version carry none and are never reported stale.

Formula symbols and resource limits

A formula of a BusType is evaluated with f (frequency in Hz) and rho (specific earth resistance in Ohm·m), a formula of a BranchType with f, rho and l (length in km). j and I (imaginary unit), pi and E are available in both, together with the functions sqrt, exp, log/ln, Abs, sign, conjugate, re, im, arg, the trigonometric and hyperbolic functions and their inverses, Min, Max, floor and ceiling. Any other name is rejected when the type is created, with the case-insensitive match as a suggestion (L → l).

SymPy computes with the numbers of a formula exactly while it parses it, so a short string could cost unbounded CPU time. The formula guard therefore bounds the work before SymPy runs:

Limit Value
digits of a number literal 100 (decimal notation only)
exponent of a power, written out or computed 12
digits of an exact intermediate result 10 000
digits of the integer floor/ceiling builds 100
magnitude of an argument of exp, sinh, cosh 1e100
terms (numbers, names, operations, calls) 512
function calls / arguments per call 8 / 3

The longest formula in this documentation, the reduced phase-conductor impedance \(Z_\text{red}\) of Bus and branch types from data sheets, has 99 terms and 6 calls, number literals of at most 9 digits and no exponent above 2 — well inside the limits. Write very small or large factors with an exponent part — 1e-15 rather than 10**-15.

check_formula_symbols

check_formula_symbols(
    formula: str,
    allowed: Iterable[str],
    *,
    context: str = "formula",
) -> str

Reject a formula that uses symbols the evaluator does not bind.

A bus formula is evaluated with f and rho, a branch formula with f, rho and l (see :data:BUS_FORMULA_SYMBOLS, :data:BRANCH_FORMULA_SYMBOLS); :data:FORMULA_CONSTANTS are available in both. Any other name stays a free SymPy symbol, and the formula then fails only when an element is created -- with "Cannot convert expression to float", which names neither the symbol nor the field. The typical cause is the wrong case (L, F, Rho), so the message suggests the case-insensitive match when there is one.

The open-end sentinel "nan" is not a formula and passes unchanged.

Parameters:

Name Type Description Default
formula str

The formula, already accepted by :func:assert_safe_formula.

required
allowed Iterable[str]

The parameters the evaluator binds for this formula; f must be among them. :data:FORMULA_CONSTANTS are added automatically.

required
context str

How to name the formula in the message, e.g. "BranchType 'cable': self_impedance_formula".

'formula'

Returns:

Type Description
str

formula, unchanged.

Raises:

Type Description
ValueError

If the formula uses a name outside the allowed set. The message names every unknown symbol, the allowed symbols with their meaning, and the case-insensitive match where one exists.

Examples:

>>> check_formula_symbols("(0.25 + j*f*0.012)*l", BRANCH_FORMULA_SYMBOLS)
'(0.25 + j*f*0.012)*l'
>>> check_formula_symbols("rho*L", BRANCH_FORMULA_SYMBOLS)
Traceback (most recent call last):
...
ValueError: formula uses the unknown symbol 'L' (did you mean 'l'?). ...
Source code in src/groundinsight/utils/validations.py
def check_formula_symbols(
    formula: str, allowed: Iterable[str], *, context: str = "formula"
) -> str:
    """
    Reject a formula that uses symbols the evaluator does not bind.

    A bus formula is evaluated with ``f`` and ``rho``, a branch formula with
    ``f``, ``rho`` and ``l`` (see :data:`BUS_FORMULA_SYMBOLS`,
    :data:`BRANCH_FORMULA_SYMBOLS`); :data:`FORMULA_CONSTANTS` are available
    in both. Any other name stays a free SymPy symbol, and the formula then
    fails only when an element is created -- with "Cannot convert expression
    to float", which names neither the symbol nor the field. The typical
    cause is the wrong case (``L``, ``F``, ``Rho``), so the message suggests
    the case-insensitive match when there is one.

    The open-end sentinel ``"nan"`` is not a formula and passes unchanged.

    Parameters
    ----------
    formula : str
        The formula, already accepted by :func:`assert_safe_formula`.
    allowed : Iterable[str]
        The parameters the evaluator binds for this formula; ``f`` must be
        among them. :data:`FORMULA_CONSTANTS` are added automatically.
    context : str, optional
        How to name the formula in the message, e.g.
        ``"BranchType 'cable': self_impedance_formula"``.

    Returns
    -------
    str
        ``formula``, unchanged.

    Raises
    ------
    ValueError
        If the formula uses a name outside the allowed set. The message names
        every unknown symbol, the allowed symbols with their meaning, and the
        case-insensitive match where one exists.

    Examples
    --------
    >>> check_formula_symbols("(0.25 + j*f*0.012)*l", BRANCH_FORMULA_SYMBOLS)
    '(0.25 + j*f*0.012)*l'
    >>> check_formula_symbols("rho*L", BRANCH_FORMULA_SYMBOLS)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
    ...
    ValueError: formula uses the unknown symbol 'L' (did you mean 'l'?). ...
    """
    if not isinstance(formula, str):
        return formula
    parameters = tuple(allowed)
    unknown = _unknown_symbols(formula, parameters)
    if not unknown:
        return formula
    permitted = set(parameters) | set(FORMULA_CONSTANTS)

    hints = []
    for name in unknown:
        matches = sorted(a for a in permitted if a.lower() == name.lower())
        if matches:
            hints.append(f"'{name}' (did you mean '{matches[0]}'?)")
        elif name in BRANCH_FORMULA_SYMBOLS and name not in parameters:
            hints.append(
                f"'{name}' (the {_SYMBOL_MEANING[name]} is only defined in "
                "branch formulas)"
            )
        else:
            hints.append(f"'{name}'")
    noun = "symbol" if len(unknown) == 1 else "symbols"
    described = ", ".join(
        f"{name} ({_SYMBOL_MEANING.get(name, 'parameter')})" for name in parameters
    )
    raise ValueError(
        f"{context} uses the unknown {noun} {', '.join(hints)}. This formula "
        f"is evaluated with {described}; the constants "
        f"{', '.join(FORMULA_CONSTANTS[:2])} (imaginary unit), "
        f"{', '.join(FORMULA_CONSTANTS[2:])} are available as well. Names are "
        "case-sensitive."
    )

Field-level validation guards are documented inline (frequency duplicate / NaN / negative rejection on Network.frequencies, int-vs-float key coercion on Fault.scalings, …). See the mkdocstrings dump below for the authoritative list.

API reference

core_models

Pydantic models of a grounding network and the :class:Network container.

Types, elements, faults, sources and results are models of their own.

Types (:class:BusType, :class:BranchType) carry formula strings; elements (:class:Bus, :class:Branch) carry the impedance dictionaries derived from those formulas at the network's frequencies. Derived data is only worth having while it matches its inputs, so the models keep three invariants:

  • Derived data follows its inputs. Assigning an input of an element that belongs to a network (specific_earth_resistance, length, type) re-derives the element through the same code path as Network.add_*; assigning Network.frequencies re-derives every element. A failing derivation leaves everything as it was. Types are read-only, because a type is evaluated into every element that uses it -- a changed type is a new type, assigned per element.
  • Stored results know whether they are current. Every result carries a digest of the inputs it was computed from (:attr:Result.input_digest); :meth:Network.stale_results compares it with the inputs the network has now. The comparison is by content, so undoing an edit -- or a study that restores the network -- makes a result current again, and the digest survives JSON and the database.
  • Names are keys. An element belongs to one network and is found by its name; renaming an attached element, rewiring it to a bus the network does not have, or removing a bus that is still referenced is refused. :meth:Network.update_bus / :meth:Network.update_branch and the remove_* methods change a network consistently.

Elements know their network through a weak back-reference that compares equal to every other (:class:_NetworkLink), so it changes neither equality nor serialisation, and copies or pickles of a network point at the copy.

RES_FAULT_SCHEMA module-attribute

RES_FAULT_SCHEMA: Dict[str, Any] = {
    "fault": pl.Utf8,
    "fault_bus": pl.Utf8,
    "frequency_Hz": pl.Float64,
    "is_rms": pl.Boolean,
    "I_F_A": pl.Float64,
    "I_F_degree": pl.Float64,
    "EPR_fault_V": pl.Float64,
    "EPR_fault_degree": pl.Float64,
    "EPR_max_V": pl.Float64,
    "EPR_max_bus": pl.Utf8,
    "r_epr": pl.Float64,
    "r_current": pl.Float64,
    "I_E_A": pl.Float64,
    "U_E_V": pl.Float64,
    "Z_E_Ohm": pl.Float64,
    "Z_E_degree": pl.Float64,
    "n_diagnostics": pl.Int64,
}

Column layout of :meth:Network.res_fault, in output order.

The key figures of one fault at the fault location, one row per network frequency plus one RMS row (is_rms true, frequency_Hz null). Pinned for the same reason as the other result tables, and because a GUI or a report template binds to the names: I_F the fault current, EPR_fault the earth potential rise at the fault bus, EPR_max the largest one in the network and its bus, r_epr and r_current the EPR-based and the current-based reduction factor, I_E the earth-return current, U_E and Z_E the earthing voltage and impedance of EN 50522, n_diagnostics the number of records in Result.diagnostics.

Bus

Bases: _NetworkElement

Represents a grounding bus within the network.

Attributes:

Name Type Description
name str

The name of the bus.

description (str, optional)

A brief description of the bus.

type BusType

The type of the bus.

impedance dict of float to ComplexNumber

Mapping of frequency to grounding impedance values.

specific_earth_resistance float

The specific earth resistance associated with the bus (Ohm * m).

active bool

Whether the bus participates in the solve. Inactive buses are removed from the admittance matrix; paths traversing them are dropped. Defaults to True. Used by the outage / what-if machinery in :mod:groundinsight.simulation.outage.

R dict of float to float, optional

Evaluated lumped resistance per frequency in Ohm. Populated only if type.R_formula is set. Consumed by the transient solvers.

L dict of float to float, optional

Evaluated lumped inductance per frequency in Henry. Populated only if type.L_formula is set.

C dict of float to float, optional

Evaluated lumped capacitance to remote earth per frequency in Farad. Populated only if type.C_formula is set.

Examples:

>>> import groundinsight as gi
>>> station = gi.BusType(name="station", system_type="Substation",
...                      voltage_level=20.0, impedance_formula="rho * 0.01")
>>> net = gi.create_network(name="n", frequencies=[50.0])
>>> bus = gi.create_bus(name="B1", type=station, network=net,
...                     specific_earth_resistance=200.0)
>>> bus.impedance
{50.0: ComplexNumber(real=2.0, imag=0.0)}

calculate_impedance

calculate_impedance(frequencies: List[float])

Calculate the impedance and, where the type asks for them, R, L and C.

Both are evaluated at each frequency; R, L and C are the lumped parameters of the type's optional formulas.

impedance is always recomputed from type.impedance_formula. Each of R, L and C is computed from the matching formula of the type, and set to None when the type has none. Utilizes the external impedance_calculator to avoid storing non-pickleable functions.

The update is atomic: every value is computed first and only then written, so a formula that fails to evaluate leaves the bus exactly as it was.

Parameters:

Name Type Description Default
frequencies List[float]

A list of frequencies at which to evaluate the formulas.

required

Raises:

Type Description
ValueError

If a formula cannot be evaluated or yields a grounding impedance that cannot be inverted into an admittance.

Source code in src/groundinsight/models/core_models.py
def calculate_impedance(self, frequencies: List[float]):
    """
    Calculate the impedance and, where the type asks for them, R, L and C.

    Both are evaluated at each frequency; R, L and C are the lumped
    parameters of the type's optional formulas.

    ``impedance`` is always recomputed from ``type.impedance_formula``.
    Each of ``R``, ``L`` and ``C`` is computed from the matching formula
    of the type, and set to ``None`` when the type has none. Utilizes the
    external ``impedance_calculator`` to avoid storing non-pickleable
    functions.

    The update is atomic: every value is computed first and only then
    written, so a formula that fails to evaluate leaves the bus exactly as
    it was.

    Parameters
    ----------
    frequencies : List[float]
        A list of frequencies at which to
        evaluate the formulas.

    Raises
    ------
    ValueError
        If a formula cannot be evaluated or yields a grounding impedance
        that cannot be inverted into an admittance.
    """
    self._apply_derived(self._derive(frequencies))

validate_impedance

validate_impedance(value)

Coerce the keys to float and every value to a ComplexNumber.

Source code in src/groundinsight/models/core_models.py
@field_validator("impedance", mode="before")
def validate_impedance(cls, value):
    """Coerce the keys to ``float`` and every value to a ``ComplexNumber``."""
    if not isinstance(value, dict):
        raise TypeError(
            "Impedance must be a dictionary of frequency to impedance values."
        )
    new_value = {}
    for freq, imp in value.items():
        freq = float(freq)
        new_value[freq] = ComplexNumber.validate_complex(imp)
    return new_value

BusType

Bases: _ReadOnlyType

Represents the type of a bus, including its default impedance formula.

The mandatory impedance_formula is used by the frequency-domain solver (Y(f) u = i) and is the only required parameter for stationary studies.

For transient simulations the type can additionally carry an explicit lumped-element decomposition R_formula / L_formula / C_formula. These are parallel to impedance_formula: the frequency-domain solver ignores them, the FFT- and state-space-based transient solvers consume them. The duplication is intentional so that the stationary model and the transient equivalent can be parameterised independently — a substation grounding, for example, may be modelled as a constant R in the stationary formula while the transient model uses the full R + j*omega*L plus an HF capacitance to remote earth.

Attributes:

Name Type Description
name str

The name of the bus type.

description (str, optional)

A brief description of the bus type.

system_type str

The system type associated with the bus, e.g. 'Tower' or 'Substation'.

voltage_level float

The voltage level of the bus, in kV.

impedance_formula str

SymPy formula for the frequency-domain grounding impedance Z(f, rho). Mandatory.

R_formula (str, optional)

SymPy formula for the lumped resistance R(rho, f) in Ohm. Used only by the transient solvers.

L_formula (str, optional)

SymPy formula for the lumped inductance L(rho, f) in Henry. Used only by the transient solvers.

C_formula (str, optional)

SymPy formula for the lumped capacitance to remote earth C(rho, f) in Farad. Used only by the transient solvers (typically only relevant for HF studies).

earthing_conductor_material ({Cu, Al, Steel}, optional)

Material of the earthing conductor (Erdungsleiter) — the lumped connection that carries the earth-fault current from the installation into the grounding system. Consumed only by :func:groundinsight.check_node_limits.

earthing_conductor_cross_section_mm2 (float, optional)

Cross-section of the earthing conductor in mm². Must be strictly positive when given.

earthing_conductor_theta_initial_C float

Initial earthing-conductor temperature in °C. Defaults to 20.0 (ambient).

earthing_conductor_theta_final_C (float, optional)

Maximum permissible earthing-conductor temperature in °C. Defaults to the material value in :data:groundinsight.analysis.thermal.IEC60949_MATERIALS.

earthing_conductor_current_split float

Share of the bus injection this conductor carries, in (0, 1]. 1.0 (default) is a single conductor carrying everything; 1/N splits the current across N equal parallel conductors. See :func:groundinsight.check_node_limits.

electrode_material ({Cu, Al, Steel}, optional)

Material of the earth electrode (Erder) — the part buried in the soil, which only carries the share of the current that is actually dissipated to earth at this bus.

electrode_cross_section_mm2 (float, optional)

Cross-section of the earth electrode in mm². Must be strictly positive when given.

electrode_theta_initial_C float

Initial electrode temperature in °C. Defaults to 20.0.

electrode_theta_final_C (float, optional)

Maximum permissible electrode temperature in °C. Buried electrodes are usually limited well below a free-air conductor to protect the surrounding soil and any coating; EN 50522 Table 2 is the reference.

electrode_current_split float

Share of the dissipated current a single electrode carries, in (0, 1]. Use 1/N for N equal parallel electrodes at the same bus.

Notes

The thermal fields are optional throughout. A bus is only assessed by :func:groundinsight.check_node_limits once both the material and the cross-section of the respective element are set; the two elements are independent, so a bus may declare only its electrode or only its earthing conductor.

Formula symbols. Every formula of a bus type is evaluated with f (frequency in Hz) and rho (specific earth resistance in Ohm*m); the constants j/I (imaginary unit), pi and E are available as well. Any other name -- F, Rho, or the branch length l -- is rejected when the type is created, with the case-insensitive match as a suggestion (see :func:~groundinsight.utils.validations.check_formula_symbols).

Read-only. A bus type cannot be changed after construction: it has been evaluated into the impedances of the buses that use it. Create a changed type with model_copy(update=...) and assign it per bus with :meth:Network.update_bus, which re-derives the bus.

Examples:

>>> import groundinsight as gi
>>> station = gi.BusType(name="station", system_type="Substation",
...                      voltage_level=20.0,
...                      impedance_formula="rho * 0.01 + j * f * 0.002")
>>> station.impedance_formula
'rho * 0.01 + j * f * 0.002'

validate_impedance_formula

validate_impedance_formula(value, info: ValidationInfo)

Validate the SymPy impedance_formula string.

Runs the security guard and the SymPy parse, then checks that the formula only uses the symbols a bus formula is evaluated with (:data:~groundinsight.utils.validations.BUS_FORMULA_SYMBOLS).

Source code in src/groundinsight/models/core_models.py
@field_validator("impedance_formula")
def validate_impedance_formula(cls, value, info: ValidationInfo):
    """Validate the SymPy ``impedance_formula`` string.

    Runs the security guard and the SymPy parse, then checks that the
    formula only uses the symbols a bus formula is evaluated with
    (:data:`~groundinsight.utils.validations.BUS_FORMULA_SYMBOLS`).
    """
    value = validate_impedance_formula_value(value)
    return check_formula_symbols(
        value, BUS_FORMULA_SYMBOLS, context=_formula_context("BusType", info)
    )

validate_rlc_formula

validate_rlc_formula(value, info: ValidationInfo)

Validate the optional lumped RLC formula strings; None is allowed.

Source code in src/groundinsight/models/core_models.py
@field_validator("R_formula", "L_formula", "C_formula")
def validate_rlc_formula(cls, value, info: ValidationInfo):
    """Validate the optional lumped RLC formula strings; ``None`` is allowed."""
    if value is None:
        return value
    value = validate_impedance_formula_value(value)
    return check_formula_symbols(
        value, BUS_FORMULA_SYMBOLS, context=_formula_context("BusType", info)
    )

Branch

Bases: _NetworkElement

Represents a branch (conductor) connecting two buses in the network.

Attributes:

Name Type Description
name str

The name of the branch.

description (str, optional)

A brief description of the branch.

type BranchType

The type of the branch.

length float

The length of the branch in km. Must be finite and strictly positive; it is checked on construction and on assignment.

from_bus str

The name of the originating bus.

to_bus str

The name of the destination bus.

self_impedance dict of float to ComplexNumber

Self-impedance values mapped by frequency.

mutual_impedance dict of float to ComplexNumber

Mutual-impedance values mapped by frequency.

specific_earth_resistance float

The specific earth resistance associated with the branch (Ohm * m).

parallel_coefficient (float, optional)

The parallel coefficient between 0 and 1, if any. Defaults to 1.0.

active bool

Whether the branch participates in the solve. An inactive branch behaves like an open circuit: it contributes neither to the admittance matrix nor to the mutual-coupling injection, paths traversing it are dropped, and its branch current in the result is forced to zero. Defaults to True. Used by the outage / what-if machinery in :mod:groundinsight.simulation.outage.

phase_impedance dict of float to ComplexNumber, optional

Phase-conductor impedance per frequency, evaluated from BranchType.phase_impedance_formula; None without that formula. Read by the phase-current solve (phase_current_mode= "auto").

R_self, L_self, C_self dict of float to float, optional

Series resistance (Ohm), series inductance (H) and shunt capacitance to remote earth (F) per frequency, from the matching *_formula of the type; None without it. Read only by the state-space transient solver.

R_mutual, M_mutual dict of float to float, optional

Mutual resistance (Ohm) and mutual inductance (H) per frequency, from the matching *_formula of the type; None without it. Read only by the state-space transient solver.

Examples:

>>> from groundinsight.api.examples import build_minimal
>>> branch = build_minimal().branches["b12"]
>>> branch.from_bus, branch.to_bus, branch.length
('bus1', 'bus2', 1.0)
>>> branch.self_impedance[50.0], branch.mutual_impedance[50.0]
(ComplexNumber(real=0.25, imag=0.6), ComplexNumber(real=0.0, imag=0.6))

calculate_impedance

calculate_impedance(frequencies: List[float])

Calculate the self and mutual impedance and the optional quantities.

The phase impedance and the lumped RLCM parameters are evaluated at each frequency where the type specifies them.

self_impedance and mutual_impedance are always recomputed. Each of phase_impedance, R_self, L_self, C_self, R_mutual, M_mutual is computed from the matching formula of the branch type, and set to None when the type has none.

The update is atomic: every value is computed first and only then written, so a formula that fails to evaluate -- in any of the steps -- leaves the branch exactly as it was.

Parameters:

Name Type Description Default
frequencies List[float]

A list of frequencies at which to evaluate the formulas.

required

Raises:

Type Description
ValueError

If a formula cannot be evaluated, if the self impedance of a grounding conductor cannot be inverted into an admittance, or if an RLCM formula yields a non-real value.

Source code in src/groundinsight/models/core_models.py
def calculate_impedance(self, frequencies: List[float]):
    """
    Calculate the self and mutual impedance and the optional quantities.

    The phase impedance and the lumped RLCM parameters are evaluated at
    each frequency where the type specifies them.

    ``self_impedance`` and ``mutual_impedance`` are always recomputed.
    Each of ``phase_impedance``, ``R_self``, ``L_self``, ``C_self``,
    ``R_mutual``, ``M_mutual`` is computed from the matching formula of
    the branch type, and set to ``None`` when the type has none.

    The update is atomic: every value is computed first and only then
    written, so a formula that fails to evaluate -- in any of the steps --
    leaves the branch exactly as it was.

    Parameters
    ----------
    frequencies : List[float]
        A list of frequencies at which to
        evaluate the formulas.

    Raises
    ------
    ValueError
        If a formula cannot be evaluated, if the self impedance of a
        grounding conductor cannot be inverted into an admittance, or if
        an RLCM formula yields a non-real value.
    """
    self._apply_derived(self._derive(frequencies))

validate_mutual_impedance

validate_mutual_impedance(value)

Coerce the keys to float and every value to a ComplexNumber.

Source code in src/groundinsight/models/core_models.py
@field_validator("mutual_impedance", mode="before")
def validate_mutual_impedance(cls, value):
    """Coerce the keys to ``float`` and every value to a ``ComplexNumber``."""
    if not isinstance(value, dict):
        raise TypeError(
            "Impedance must be a dictionary of frequency to impedance values."
        )
    new_value = {}
    for freq, imp in value.items():
        freq = float(freq)
        new_value[freq] = ComplexNumber.validate_complex(imp)
    return new_value

validate_phase_impedance

validate_phase_impedance(value)

Accept None or the same shapes as the other impedance dicts.

Source code in src/groundinsight/models/core_models.py
@field_validator("phase_impedance", mode="before")
def validate_phase_impedance(cls, value):
    """Accept ``None`` or the same shapes as the other impedance dicts."""
    if value is None:
        return None
    if not isinstance(value, dict):
        raise TypeError(
            "Impedance must be a dictionary of frequency to impedance values."
        )
    new_value = {}
    for freq, imp in value.items():
        freq = float(freq)
        new_value[freq] = ComplexNumber.validate_complex(imp)
    return new_value

validate_self_impedance

validate_self_impedance(value)

Coerce the keys to float and every value to a ComplexNumber.

Source code in src/groundinsight/models/core_models.py
@field_validator("self_impedance", mode="before")
def validate_self_impedance(cls, value):
    """Coerce the keys to ``float`` and every value to a ``ComplexNumber``."""
    if not isinstance(value, dict):
        raise TypeError(
            "Impedance must be a dictionary of frequency to impedance values."
        )
    new_value = {}
    for freq, imp in value.items():
        freq = float(freq)
        new_value[freq] = ComplexNumber.validate_complex(imp)
    return new_value

BranchType

Bases: _ReadOnlyType

Represents the type of a branch, including its impedance formulas.

The mandatory self_impedance_formula and mutual_impedance_formula drive the frequency-domain solver.

The optional phase_impedance_formula describes the phase conductor -- the faulted conductor whose current induces the longitudinal EMF on the shield -- and is what the automatic phase-current distribution solves on. It is only needed when the network contains rings, meshes or parallel branches, because only then does the source current have more than one way to reach the fault. Without it the distribution falls back to a documented proxy and warns; see :meth:~groundinsight.electrical_network. ElectricalNetwork._compute_phase_currents_auto.

For transient simulations the type can additionally carry a lumped RLCM decomposition: R_self_formula, L_self_formula, C_self_formula (shunt-to-ground capacitance per branch, only relevant for HF studies), R_mutual_formula (Carson earth-return resistance term) and M_mutual_formula (mutual inductance to the parallel phase conductor). These are parallel to the impedance formulas: the frequency-domain solver ignores them, the state-space and FFT-based transient solvers consume them. The duplication is intentional so the stationary and transient parameterisations can be maintained independently.

Attributes:

Name Type Description
name str

The name of the branch type.

description (str, optional)

A brief description of the branch type.

grounding_conductor bool

Indicates whether the branch has a grounding wire or cable shield.

self_impedance_formula str

SymPy formula used to calculate self-impedance per branch.

mutual_impedance_formula str

SymPy formula used to calculate mutual impedance.

phase_impedance_formula (str, optional)

SymPy formula for the series impedance of the phase conductor of this branch, in the same symbols f, rho, l as the other formulas. Consumed only by the automatic phase-current distribution; the admittance matrix never sees it.

R_self_formula (str, optional)

Per-branch series resistance in Ohm. Used only by the transient solvers.

L_self_formula (str, optional)

Per-branch series inductance in Henry. Used only by the transient solvers.

C_self_formula (str, optional)

Per-branch shunt capacitance to remote earth in Farad. Used only by the transient solvers.

R_mutual_formula (str, optional)

Per-branch mutual resistance (Carson earth-return) in Ohm. Used only by the transient solvers.

M_mutual_formula (str, optional)

Per-branch mutual inductance in Henry. Used only by the transient solvers.

conductor_material ({Cu, Al, Steel}, optional)

Material of the shield or earth wire, for the adiabatic thermal check of :func:groundinsight.check_conductor_limits.

cross_section_mm2 (float, optional)

Cross-section of that conductor in mm². A branch is assessed only when both the material and the cross-section are given.

theta_initial_C float

Initial conductor temperature in °C. Defaults to 20.0.

theta_final_C (float, optional)

Maximum permissible conductor temperature in °C. Defaults to the material value in :data:groundinsight.analysis.thermal.IEC60949_MATERIALS.

Notes

Formula symbols. Every formula of a branch type is evaluated with f (frequency in Hz), rho (specific earth resistance in Ohm*m) and l (branch length in km); the constants j/I (imaginary unit), pi and E are available as well. Any other name -- L, F, Rho -- is rejected when the type is created, with the case-insensitive match as a suggestion (see :func:~groundinsight.utils.validations.check_formula_symbols).

Read-only. A branch type cannot be changed after construction: it has been evaluated into the impedances of the branches that use it. Create a changed type with model_copy(update=...) and assign it per branch with :meth:Network.update_branch, which re-derives the branch.

Examples:

>>> import groundinsight as gi
>>> cable = gi.BranchType(name="cable", grounding_conductor=True,
...                       self_impedance_formula="(0.25 + j * f * 0.012) * l",
...                       mutual_impedance_formula="j * f * 0.012 * l")
>>> cable.grounding_conductor, cable.phase_impedance_formula is None
(True, True)

validate_impedance_formula

validate_impedance_formula(value, info: ValidationInfo)

Validate the SymPy self / mutual impedance formula strings.

Runs the security guard and the SymPy parse, then checks that the formula only uses the symbols a branch formula is evaluated with (:data:~groundinsight.utils.validations.BRANCH_FORMULA_SYMBOLS).

Source code in src/groundinsight/models/core_models.py
@field_validator("self_impedance_formula", "mutual_impedance_formula")
def validate_impedance_formula(cls, value, info: ValidationInfo):
    """Validate the SymPy self / mutual impedance formula strings.

    Runs the security guard and the SymPy parse, then checks that the
    formula only uses the symbols a branch formula is evaluated with
    (:data:`~groundinsight.utils.validations.BRANCH_FORMULA_SYMBOLS`).
    """
    value = validate_impedance_formula_value(value)
    return check_formula_symbols(
        value, BRANCH_FORMULA_SYMBOLS, context=_formula_context("BranchType", info)
    )

validate_rlc_formula

validate_rlc_formula(value, info: ValidationInfo)

Validate the optional phase / lumped RLCM formula strings; None is allowed.

Source code in src/groundinsight/models/core_models.py
@field_validator(
    "phase_impedance_formula",
    "R_self_formula",
    "L_self_formula",
    "C_self_formula",
    "R_mutual_formula",
    "M_mutual_formula",
)
def validate_rlc_formula(cls, value, info: ValidationInfo):
    """Validate the optional phase / lumped RLCM formula strings; ``None`` is allowed."""
    if value is None:
        return value
    value = validate_impedance_formula_value(value)
    return check_formula_symbols(
        value, BRANCH_FORMULA_SYMBOLS, context=_formula_context("BranchType", info)
    )

Source

Bases: _NetworkElement

Represents a current or Thevenin (voltage) source within the network.

For stationary grounding analyses the default is a current source with a fixed injected current per frequency (source_type="current"). This is equivalent to a Norton source with infinite parallel impedance and matches the conventional planning practice of grounding engineering, where the prospective fault current is treated as a constant input.

For transient simulations the source can alternatively be expressed as a Thevenin equivalent (source_type="voltage") with a frequency-dependent EMF voltage and a finite source_impedance. In that case the grounding network sees the loop impedance Z_src + Z_loop and the effective fault current results from the solution rather than being prescribed.

Attributes:

Name Type Description
name str

The name of the source.

description (str, optional)

A brief description of the source.

bus str

The name of the bus where the source is located.

source_type {current, voltage}

"current" (default) for a classic current-source injection; "voltage" for a Thevenin equivalent (EMF in series with source_impedance).

values dict of float to ComplexNumber, optional

Frequency-dependent current injection, one phasor per frequency. Required when source_type == "current" and must be None otherwise. The phasors are RMS amplitudes, not peak values -- see the RMS convention in the Notes.

voltage dict of float to ComplexNumber, optional

Frequency-dependent Thevenin EMF, one phasor per frequency, again as RMS amplitudes. Required when source_type == "voltage" and must be None otherwise.

source_impedance dict of float to ComplexNumber, optional

Frequency-dependent internal impedance of the Thevenin source. Required when source_type == "voltage" and must be None otherwise. Must be non-zero at every frequency in order to be invertible into a Norton equivalent.

i_k_a (float, optional)

Initial symmetrical short-circuit current I_k'' at the fault location as seen from this source, in amperes. Provenance metadata for the IEC 60909 characteristics — the solve always uses values / voltage. Typically filled by :func:groundinsight.io.apply_shortcircuit_characteristics from a pandapower calc_sc run.

r_to_x (float, optional)

Ratio R/X of the short-circuit loop feeding this source, used to derive kappa when the latter is not given explicitly. For a single line-to-earth fault the relevant loop is 2*Z1 + Z0, so r_to_x = (2*R1 + R0) / (2*X1 + X0).

kappa (float, optional)

IEC 60909-0 peak factor kappa of this source. Takes precedence over r_to_x when both are set, which lets a topology-aware value (e.g. pandapower's method C) override the closed-form 1.02 + 0.98 * exp(-3 * R/X). Physically bounded to (1, 2].

Notes

i_k_a, r_to_x and kappa are characteristic quantities. They do not enter the linear solve at all: the network equations superpose the RMS injections in values as before. The non-linear IEC 60909 factors are applied afterwards, to the aggregated branch current, by :func:groundinsight.analysis.shortcircuit.resolve_fault_sc_characteristics. Superposing i_p or I_th of individual sources directly would be wrong; see that module's docstring for the derivation.

RMS convention. Every phasor in values, voltage and every phasor the solver derives from them is an RMS amplitude, not a peak amplitude. The convention is package-wide and it is what makes the RMS columns of the results correct: the total RMS of a quantity with several frequency components is

.. math::

X_{\mathrm{RMS}} = \sqrt{\sum_f |X(f)|^2}

with the 0 Hz term entering as |X_dc| -- a DC component contributes its own magnitude, not |X_dc|/sqrt(2). Peak-valued phasors would make that sum too large by sqrt(2) for every AC component while leaving the DC term right, so the two conventions cannot be mixed. If a data source gives peak amplitudes, divide the AC components by sqrt(2) before filling values. See :meth:groundinsight.electrical_network.ElectricalNetwork._calculate_rms.

Examples:

>>> import groundinsight as gi
>>> source = gi.Source(name="S1", bus="B1", values={50.0: 1000.0, 250.0: 50.0})
>>> source.source_type, source.values[250.0]
('current', ComplexNumber(real=50.0, imag=0.0))

Fault

Bases: _NetworkElement

Represents a fault within the network.

Attributes:

Name Type Description
name str

The name of the fault.

description (str, optional)

A brief description of the fault.

bus str

The name of the bus where the fault occurs.

scalings dict of float to float, optional

Factor applied to every source current, per frequency. A frequency without a key is scaled with 1.0 -- full contribution -- and an empty or omitted mapping (None is accepted and stored as {}) means 1.0 at every frequency. Give 0.0 to exclude a frequency bin from this fault. A non-empty mapping that leaves out some network frequencies is announced once per run with an InputWarning SCALINGS_INCOMPLETE. :meth:scaling_at is the one place that applies the default.

t_k_s (float, optional)

Short-circuit duration (clearing time) T_k in seconds, as defined in IEC 60909-0. Drives both the DC heat factor m of the thermally equivalent short-circuit current I_th and the adiabatic conductor rating I_adm = k * S / sqrt(t_k). None means "not specified"; the thermal check then requires an explicit t_k argument.

n_factor float, default 1.0

AC heat factor n of IEC 60909-0. 1.0 is the far-from-generator case (no AC decay), which is the normal situation for grounding studies. Values below 1.0 apply when the fault is near a generator and the AC component decays during T_k.

Notes

The private _active attribute indicates whether the fault is the currently active one in the network and is exposed read-only through the :attr:active computed property.

t_k_s and n_factor live on the fault, not on the sources, because the clearing time is a property of the protection scheme reacting to that fault. The IEC 60909 quantities that describe the feeding side (I_k'', R/X, kappa) live on :class:Source instead.

Examples:

>>> import groundinsight as gi
>>> fault = gi.Fault(name="F1", bus="B3", scalings={50.0: 1.0}, t_k_s=0.5)
>>> fault.scaling_at(50.0), fault.t_k_s, fault.active
(1.0, 0.5, False)

active property

active: bool

Whether this fault is currently the active one in the network.

Returns:

Type Description
bool

True while Network.active_fault names this fault.

mark_active

mark_active(value: bool) -> None

Set the flag behind :attr:active.

Internal API: used by :class:Network, the database loader and the inverse-rho searches to keep the flag in step with :attr:Network.active_fault; not exported from groundinsight and free to change in any release. Application code activates a fault with :meth:Network.set_active_fault.

Parameters:

Name Type Description Default
value bool

Whether this fault is the active fault of its network.

required
Source code in src/groundinsight/models/core_models.py
def mark_active(self, value: bool) -> None:
    """
    Set the flag behind :attr:`active`.

    Internal API: used by :class:`Network`, the database loader and the
    inverse-rho searches to keep the flag in step with
    :attr:`Network.active_fault`; not exported from ``groundinsight`` and
    free to change in any release. Application code activates a fault with
    :meth:`Network.set_active_fault`.

    Parameters
    ----------
    value : bool
        Whether this fault is the active fault of its network.
    """
    self._active = value

scaling_at

scaling_at(frequency: float) -> float

The factor this fault applies to the source currents at a frequency.

Parameters:

Name Type Description Default
frequency float

Frequency in Hz (an int key is looked up as float, the way the validator stores it).

required

Returns:

Type Description
float

scalings[frequency], or 1.0 -- full contribution -- when the frequency has no key.

Examples:

>>> import groundinsight as gi
>>> fault = gi.Fault(name="F1", bus="B", scalings={50.0: 0.5})
>>> fault.scaling_at(50.0), fault.scaling_at(250.0)
(0.5, 1.0)
Source code in src/groundinsight/models/core_models.py
def scaling_at(self, frequency: float) -> float:
    """
    The factor this fault applies to the source currents at a frequency.

    Parameters
    ----------
    frequency : float
        Frequency in Hz (an ``int`` key is looked up as ``float``, the way
        the validator stores it).

    Returns
    -------
    float
        ``scalings[frequency]``, or ``1.0`` -- full contribution -- when
        the frequency has no key.

    Examples
    --------
    >>> import groundinsight as gi
    >>> fault = gi.Fault(name="F1", bus="B", scalings={50.0: 0.5})
    >>> fault.scaling_at(50.0), fault.scaling_at(250.0)
    (0.5, 1.0)
    """
    return float(self.scalings.get(float(frequency), 1.0))

Network

Bases: ValidatedAssignmentModel

Top-level container for an entire grounding network.

Holds every physical element (buses, branches, sources, faults), the enumerated source-to-fault paths, the per-fault result objects and a private :class:ElectricalNetwork helper that owns the numerical working arrays.

Attributes:

Name Type Description
name str

The name of the network.

description (str, optional)

A brief description of the network.

frequencies list of float

Frequencies (in Hz) used in calculations.

buses dict of str to Bus

Buses keyed by name.

branches dict of str to Branch

Branches keyed by name.

faults dict of str to Fault

Faults keyed by name.

sources dict of str to Source

Sources keyed by name.

results dict of str to Result

Per-fault calculation results keyed by fault name.

paths dict of str to Path

Source-to-fault paths keyed by path name.

active_fault (str, optional)

Name of the currently active fault.

Notes

Editing. Assigning an input of an element that belongs to the network -- Bus.specific_earth_resistance/type, Branch.length/specific_earth_resistance/type -- re-derives its impedances at once, and assigning :attr:frequencies re-derives every element; a failing derivation leaves everything unchanged and raises. :meth:update_bus and :meth:update_branch change several fields at once (all or nothing); the remove_* methods refuse to leave a dangling reference. Renaming an element that belongs to the network is refused -- remove it and add a renamed copy. An element belongs to one network at a time.

Stale results. :meth:stale_results lists the faults whose stored result no longer matches the network's inputs; :meth:is_result_stale asks for one fault. A result is stale when the frequencies, a bus, a branch or a source changed as the solver sees them, or the definition of its own fault -- adding or editing another fault leaves it current, and so do metadata such as description or Fault.t_k_s. The comparison is by content (see :attr:Result.input_digest): restoring an input restores the result's status, which is how outage_context and the studies leave the flags as they found them.

Examples:

>>> import groundinsight as gi
>>> import polars as pl
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> sorted(net.buses), list(net.faults)
(['bus1', 'bus2', 'bus3'], ['fault'])
>>> _ = gi.run_fault(net, "fault")
>>> net.stale_results()
[]
>>> rms = net.res_fault("fault").filter(pl.col("is_rms"))
>>> round(rms["EPR_fault_V"].item(), 2)
18.03

electrical_network property writable

electrical_network

The solver workspace of the last build, or None.

Returns:

Type Description
ElectricalNetwork or None

The :class:~groundinsight.electrical_network.ElectricalNetwork that :func:~groundinsight.build_electrical_network (and so :func:~groundinsight.run_fault) attached; never saved with the network.

pathfinder_settings property writable

pathfinder_settings: PathfinderSettings

Settings of the path search on this network.

Runtime configuration, not part of the saved model: a copy keeps it, a file or a database does not. Without settings of its own the network uses :func:groundinsight.pathfinder.default_pathfinder_settings, which only the deprecated module-level switches change. Assign None to return to the defaults.

Returns:

Type Description
PathfinderSettings

The network's settings, or the process-wide defaults.

Raises:

Type Description
TypeError

On assignment of anything but a PathfinderSettings or None.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="grid", frequencies=[50.0])
>>> net.pathfinder_settings = gi.PathfinderSettings(max_paths=10**6)
>>> net.pathfinder_settings.max_paths
1000000

__setstate__

__setstate__(state: Dict[Any, Any]) -> None

Restore a pickled network and re-attach its elements.

The element links are not pickled (they hold a weak reference), so the elements of an unpickled network are attached here.

Parameters:

Name Type Description Default
state Dict[Any, Any]

The state produced by BaseModel.__getstate__.

required
Source code in src/groundinsight/models/core_models.py
def __setstate__(self, state: Dict[Any, Any]) -> None:
    """
    Restore a pickled network and re-attach its elements.

    The element links are not pickled (they hold a weak reference), so
    the elements of an unpickled network are attached here.

    Parameters
    ----------
    state : Dict[Any, Any]
        The state produced by ``BaseModel.__getstate__``.
    """
    super().__setstate__(state)
    self._link_elements()

add_branch

add_branch(branch: Branch, overwrite: bool = False)

Adds a branch to the network.

Parameters:

Name Type Description Default
branch Branch

The branch instance to add.

required
overwrite bool

If True, overwrites an existing branch with the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If a branch with the same name already exists, if the connected buses are not in the network, or if the impedances cannot be derived from the branch type. In every case neither the network nor branch is changed.

Source code in src/groundinsight/models/core_models.py
def add_branch(self, branch: Branch, overwrite: bool = False):
    """
    Adds a branch to the network.

    Parameters
    ----------
    branch : Branch
        The branch instance to add.
    overwrite : bool, optional
        If True, overwrites an existing branch with the same name. Defaults to False.

    Raises
    ------
    ValueError
        If a branch with the same name already exists, if the connected
        buses are not in the network, or if the impedances cannot be
        derived from the branch type. In every case neither the network
        nor ``branch`` is changed.
    """
    replacing = branch.name in self.branches
    if replacing and not overwrite:
        raise ValueError(
            f"Branch with name '{branch.name}' already exists in the network '{self.name}'. If you want to overwrite, set overwrite=True."
        )
    self._claim(branch)

    # Validate that the from_bus and to_bus are in the network
    if branch.from_bus not in self.buses:
        raise ValueError(
            f"from_bus '{branch.from_bus}' is not in the network '{self.name}'"
        )
    if branch.to_bus not in self.buses:
        raise ValueError(
            f"to_bus '{branch.to_bus}' is not in the network '{self.name}'"
        )
    # Derive first, insert second -- see add_bus (ARC9).
    derived = branch._derive(self.frequencies)
    branch._apply_derived(derived)
    self.branches[branch.name] = branch
    self._adopt(branch)
    if replacing:
        logger.warning(
            "Branch '%s' already exists in the network. Overwriting.",
            branch.name,
        )

add_bus

add_bus(bus: Bus, overwrite: bool = False)

Adds a bus to the network.

Parameters:

Name Type Description Default
bus Bus

The bus instance to add.

required
overwrite bool

If True, overwrites an existing bus with the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If a bus with the same name already exists and overwrite is False, or if the impedances cannot be derived from the bus type. In both cases neither the network nor bus is changed.

Source code in src/groundinsight/models/core_models.py
def add_bus(self, bus: Bus, overwrite: bool = False):
    """
    Adds a bus to the network.

    Parameters
    ----------
    bus : Bus
        The bus instance to add.
    overwrite : bool, optional
        If True, overwrites an existing bus with the same name. Defaults to False.

    Raises
    ------
    ValueError
        If a bus with the same name already exists and overwrite is False,
        or if the impedances cannot be derived from the bus type. In both
        cases neither the network nor ``bus`` is changed.
    """
    replacing = bus.name in self.buses
    if replacing and not overwrite:
        raise ValueError(
            f"Bus with name '{bus.name}' already exists in the network '{self.name}'. If you want to overwrite, set overwrite=True."
        )
    self._claim(bus)

    # Derive first, insert second: a formula that fails to evaluate must
    # leave the network as it was (ARC9). Inserting before deriving would
    # leave a bus without impedances behind, which the next run_fault
    # would report as "bus 'x' carries no impedance".
    derived = bus._derive(self.frequencies)
    bus._apply_derived(derived)
    self.buses[bus.name] = bus
    self._adopt(bus)
    if replacing:
        logger.warning(
            "Bus '%s' already exists in the network. Overwriting.",
            bus.name,
        )

add_fault

add_fault(fault: Fault, overwrite: bool = False)

Adds a fault to the network.

Parameters:

Name Type Description Default
fault Fault

The fault instance to add.

required
overwrite bool

If True, overwrites an existing fault with the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If a fault with the same name already exists, or if the associated bus is not in the network.

Source code in src/groundinsight/models/core_models.py
def add_fault(self, fault: Fault, overwrite: bool = False):
    """
    Adds a fault to the network.

    Parameters
    ----------
    fault : Fault
        The fault instance to add.
    overwrite : bool, optional
        If True, overwrites an existing fault with the same name. Defaults to False.

    Raises
    ------
    ValueError
        If a fault with the same name already exists, or if the associated bus is not in the network.
    """
    if fault.bus not in self.buses:
        raise ValueError(f"bus '{fault.bus}' is not in the network '{self.name}'")

    replacing = fault.name in self.faults
    if replacing and not overwrite:
        raise ValueError(
            f"Fault with name '{fault.name}' already exists in the network '{self.name}'. If you want to overwrite, set overwrite=True."
        )
    self._claim(fault)

    self.faults[fault.name] = fault
    self._adopt(fault)
    if replacing:
        logger.warning(
            "Fault '%s' already exists in the network. Overwriting.",
            fault.name,
        )

add_path

add_path(path: Path)

Adds a path to the network.

Parameters:

Name Type Description Default
path Path

The path instance to add.

required
Source code in src/groundinsight/models/core_models.py
def add_path(self, path: Path):
    """
    Adds a path to the network.

    Parameters
    ----------
    path : Path
        The path instance to add.
    """
    self.paths[path.name] = path

add_source

add_source(source: Source, overwrite: bool = False)

Adds a source to the network.

Parameters:

Name Type Description Default
source Source

The source instance to add.

required
overwrite bool

If True, overwrites an existing source with the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If a source with the same name already exists, or if the associated bus is not in the network.

Warns:

Type Description
InputWarning

SOURCE_FREQUENCY_OUTSIDE_NETWORK if the source carries values at frequencies the network is not solved at; the solve ignores them.

Source code in src/groundinsight/models/core_models.py
def add_source(self, source: Source, overwrite: bool = False):
    """
    Adds a source to the network.

    Parameters
    ----------
    source : Source
        The source instance to add.
    overwrite : bool, optional
        If True, overwrites an existing source with the same name. Defaults to False.

    Raises
    ------
    ValueError
        If a source with the same name already exists, or if the associated bus is not in the network.

    Warns
    -----
    InputWarning
        ``SOURCE_FREQUENCY_OUTSIDE_NETWORK`` if the source carries values
        at frequencies the network is not solved at; the solve ignores
        them.
    """
    if source.bus not in self.buses:
        raise ValueError(f"bus '{source.bus}' is not in the network '{self.name}'")

    replacing = source.name in self.sources
    if replacing and not overwrite:
        raise ValueError(
            f"Source with name '{source.name}' already exists in the network '{self.name}'. If you want to overwrite, set overwrite=True."
        )
    self._claim(source)
    # Said before the source is inserted, so that the warning turned into
    # an error (``-W error``) leaves the network unchanged (ARC9).
    self._warn_source_frequencies_outside(source)
    self.sources[source.name] = source
    self._adopt(source)
    if replacing:
        logger.warning(
            "Source '%s' already exists in the network. Overwriting.",
            source.name,
        )

define_paths

define_paths()

Identifies all paths from all sources to all faults in the network and adds them to the network's paths.

This method utilizes the PathFinder to locate paths and ensures that each path is unique before adding it to the network.

Source code in src/groundinsight/models/core_models.py
def define_paths(self):
    """
    Identifies all paths from all sources to all faults in the network and adds them to the network's paths.

    This method utilizes the `PathFinder` to locate paths and ensures that each path is unique
    before adding it to the network.
    """
    from groundinsight.pathfinder import PathFinder  # Import locally

    pathfinder = PathFinder(self)
    path_counter = 1  # To create unique path names
    seen_paths = set()  # To track unique paths

    for source_name, source in self.sources.items():
        source_bus_name = source.bus
        for fault_name, fault in self.faults.items():
            fault_bus_name = fault.bus
            # Find all paths between this source and fault
            paths = pathfinder.find_paths(source_bus_name, fault_bus_name)
            for path in paths:
                # Create a hashable representation of the path to check for duplicates
                path_signature = (
                    source_name,
                    fault_name,
                    tuple(branch.name for branch in path.segments),
                )
                if path_signature not in seen_paths:
                    seen_paths.add(path_signature)
                    # Assign a unique name to each path
                    path.name = f"path_{path_counter}"
                    path.description = f"Path from {source_name} to {fault_name}"
                    path.source = source_name
                    path.fault = fault_name
                    path_counter += 1
                    # Add the path to the network
                    self.add_path(path)

    # Record the active-topology fingerprint the paths were built for so
    # ``run_fault`` can detect stale paths after an in-place ``active``
    # flip or a rewiring and rebuild them instead of silently reusing them.
    self._paths_fingerprint = self._active_topology_fingerprint()

input_digest

input_digest(
    fault: str, common: Optional[bytes] = None
) -> Optional[str]

Digest of everything the result of fault depends on.

Internal API: used by :func:groundinsight.run_fault to stamp :attr:Result.input_digest; not exported from groundinsight and free to change in any release.

Parameters:

Name Type Description Default
fault str

Name of the fault.

required
common bytes

:meth:_input_digest_common, when the caller already has it.

None

Returns:

Type Description
Optional[str]

"<scheme>:<hex>", or None if fault is not a fault of this network.

Source code in src/groundinsight/models/core_models.py
def input_digest(self, fault: str, common: Optional[bytes] = None) -> Optional[str]:
    """
    Digest of everything the result of ``fault`` depends on.

    Internal API: used by :func:`groundinsight.run_fault` to stamp
    :attr:`Result.input_digest`; not exported from ``groundinsight`` and
    free to change in any release.

    Parameters
    ----------
    fault : str
        Name of the fault.
    common : bytes, optional
        :meth:`_input_digest_common`, when the caller already has it.

    Returns
    -------
    Optional[str]
        ``"<scheme>:<hex>"``, or ``None`` if ``fault`` is not a fault of
        this network.
    """
    definition = self.faults.get(fault)
    if definition is None:
        return None
    if common is None:
        common = self._input_digest_common()
    strings = [definition.name, definition.bus]
    floats: List[float] = []
    _impedance_record(definition.scalings, strings, floats)
    digest = hashlib.blake2b(common, digest_size=16)
    _digest_update(digest, strings, floats)
    return f"{_DIGEST_SCHEME}:{digest.hexdigest()}"

invalidate_paths

invalidate_paths() -> None

Drop the cached pathfinder results for this network.

Rebinds self.paths to a fresh empty dictionary (atomic) and clears this network's path-search memo (:meth:path_cache). Other networks keep theirs -- every network has its own memo.

The rebind is atomic (self.paths = {}, not an in-place self.paths.clear()): a mapping a caller saved with saved = dict(network.paths) before the call keeps its entries. :func:groundinsight.analysis.inverse_rho_f.evaluate_max_epr_under_k follows the same pattern.

Call this whenever the user has flipped Bus.active / Branch.active flags or added / removed branches outside of a context manager that performs its own rollback.

Source code in src/groundinsight/models/core_models.py
def invalidate_paths(self) -> None:
    """Drop the cached pathfinder results *for this network*.

    Rebinds ``self.paths`` to a fresh empty dictionary (atomic) and
    clears this network's path-search memo (:meth:`path_cache`).
    **Other networks keep theirs** -- every network has its own memo.

    The rebind is atomic (``self.paths = {}``, not an in-place
    ``self.paths.clear()``): a mapping a caller saved with
    ``saved = dict(network.paths)`` before the call keeps its entries.
    :func:`groundinsight.analysis.inverse_rho_f.evaluate_max_epr_under_k`
    follows the same pattern.

    Call this whenever the user has flipped ``Bus.active`` /
    ``Branch.active`` flags or added / removed branches outside of
    a context manager that performs its own rollback.
    """
    # Atomic rebind so external snapshots survive.
    self.paths = {}
    self.path_cache().clear()

is_result_stale

is_result_stale(fault: str) -> bool

Whether the stored result of fault no longer matches the network.

See :meth:stale_results for what counts as a change.

Parameters:

Name Type Description Default
fault str

Name of a fault with a stored result.

required

Returns:

Type Description
bool

True if an input of the result has changed since it was computed; False if not, or if the result carries no digest.

Raises:

Type Description
ValueError

If no result is stored for fault.

Examples:

>>> net.is_result_stale("F")
False
Source code in src/groundinsight/models/core_models.py
def is_result_stale(self, fault: str) -> bool:
    """
    Whether the stored result of ``fault`` no longer matches the network.

    See :meth:`stale_results` for what counts as a change.

    Parameters
    ----------
    fault : str
        Name of a fault with a stored result.

    Returns
    -------
    bool
        ``True`` if an input of the result has changed since it was
        computed; ``False`` if not, or if the result carries no digest.

    Raises
    ------
    ValueError
        If no result is stored for ``fault``.

    Examples
    --------
    >>> net.is_result_stale("F")  # doctest: +SKIP
    False
    """
    if fault not in self.results:
        raise ValueError(f"No results available for fault '{fault}'.")
    return self._stale(fault, None)[0]

model_post_init

model_post_init(__context: Any) -> None

Attach every element to this network after construction.

Runs for every way a network is built -- the constructor, JSON and the database -- so that an element knows which network re-derives it (see :class:_NetworkLink).

Parameters:

Name Type Description Default
__context Any

Pydantic's validation context (unused).

required
Source code in src/groundinsight/models/core_models.py
def model_post_init(self, __context: Any) -> None:
    """
    Attach every element to this network after construction.

    Runs for every way a network is built -- the constructor, JSON and
    the database -- so that an element knows which network re-derives
    it (see :class:`_NetworkLink`).

    Parameters
    ----------
    __context : Any
        Pydantic's validation context (unused).
    """
    self._link_elements()

needs_path_rebuild

needs_path_rebuild() -> bool

Whether the stored paths have to be enumerated again.

Internal API: used by :func:groundinsight.run_fault and the electrical network; not exported from groundinsight and free to change in any release.

Returns:

Type Description
bool

True if there are no paths, or if the active topology changed since the paths were last built (see :meth:_active_topology_fingerprint).

Source code in src/groundinsight/models/core_models.py
def needs_path_rebuild(self) -> bool:
    """
    Whether the stored paths have to be enumerated again.

    Internal API: used by :func:`groundinsight.run_fault` and the
    electrical network; not exported from ``groundinsight`` and free to
    change in any release.

    Returns
    -------
    bool
        ``True`` if there are no paths, or if the active topology changed
        since the paths were last built (see
        :meth:`_active_topology_fingerprint`).
    """
    if not self.paths:
        return True
    return self._paths_fingerprint != self._active_topology_fingerprint()

path_cache

path_cache() -> PathfinderCache

The path-search memo of this network.

Internal API: used by :class:groundinsight.pathfinder.PathFinder, so that no other module needs this network's private attributes; not exported from groundinsight and free to change in any release.

The memo is created on first use. A shallow copy shares its original's private attributes, so the cache is checked to belong to this network and replaced by a fresh one otherwise.

Returns:

Type Description
PathfinderCache

The memo, owned by this network.

Source code in src/groundinsight/models/core_models.py
def path_cache(self) -> "PathfinderCache":
    """
    The path-search memo of this network.

    Internal API: used by :class:`groundinsight.pathfinder.PathFinder`, so
    that no other module needs this network's private attributes; not
    exported from ``groundinsight`` and free to change in any release.

    The memo is created on first use. A shallow copy shares its original's
    private attributes, so the cache is checked to belong to *this*
    network and replaced by a fresh one otherwise.

    Returns
    -------
    PathfinderCache
        The memo, owned by this network.
    """
    from groundinsight.pathfinder import PathfinderCache

    cache = self._pathfinder_cache
    if cache is None or not cache.belongs_to(self):
        cache = PathfinderCache(self)
        self._pathfinder_cache = cache
    return cache

remove_branch

remove_branch(name: str) -> Branch

Remove a branch.

Enumerated paths that run through the branch are dropped (see :meth:invalidate_paths); stored results become stale.

Parameters:

Name Type Description Default
name str

Name of the branch.

required

Returns:

Type Description
Branch

The removed branch; it no longer belongs to the network.

Raises:

Type Description
ValueError

If the branch does not exist.

Examples:

>>> net.remove_branch("cable_3")
Source code in src/groundinsight/models/core_models.py
def remove_branch(self, name: str) -> "Branch":
    """
    Remove a branch.

    Enumerated paths that run through the branch are dropped (see
    :meth:`invalidate_paths`); stored results become stale.

    Parameters
    ----------
    name : str
        Name of the branch.

    Returns
    -------
    Branch
        The removed branch; it no longer belongs to the network.

    Raises
    ------
    ValueError
        If the branch does not exist.

    Examples
    --------
    >>> net.remove_branch("cable_3")  # doctest: +SKIP
    """
    branch = self._lookup("branches", name)
    del self.branches[name]
    if any(seg.name == name for path in self.paths.values() for seg in path.segments):
        self.invalidate_paths()
    return branch

remove_bus

remove_bus(name: str) -> Bus

Remove a bus that nothing refers to any more.

Parameters:

Name Type Description Default
name str

Name of the bus.

required

Returns:

Type Description
Bus

The removed bus; it no longer belongs to the network.

Raises:

Type Description
ValueError

If the bus does not exist, or if a branch, source or fault still refers to it -- the message names every one of them.

Examples:

>>> net.remove_bus("spare")
Source code in src/groundinsight/models/core_models.py
def remove_bus(self, name: str) -> "Bus":
    """
    Remove a bus that nothing refers to any more.

    Parameters
    ----------
    name : str
        Name of the bus.

    Returns
    -------
    Bus
        The removed bus; it no longer belongs to the network.

    Raises
    ------
    ValueError
        If the bus does not exist, or if a branch, source or fault still
        refers to it -- the message names every one of them.

    Examples
    --------
    >>> net.remove_bus("spare")  # doctest: +SKIP
    """
    bus = self._lookup("buses", name)
    users = (
        [f"branch '{n}'" for n, b in self.branches.items() if name in (b.from_bus, b.to_bus)]
        + [f"source '{n}'" for n, src in self.sources.items() if src.bus == name]
        + [f"fault '{n}'" for n, flt in self.faults.items() if flt.bus == name]
    )
    if users:
        raise ValueError(
            f"Bus '{name}' cannot be removed: {', '.join(users)} still "
            f"refer{'s' if len(users) == 1 else ''} to it. Remove them first "
            "(remove_branch, remove_source, remove_fault) or reconnect them "
            "(update_branch(..., from_bus=..., to_bus=...))."
        )
    del self.buses[name]
    return bus

remove_fault

remove_fault(name: str) -> Fault

Remove a fault together with its stored result.

If it was the active fault, no fault is active afterwards. The results of the other faults are unaffected: they do not depend on this fault's definition.

Parameters:

Name Type Description Default
name str

Name of the fault.

required

Returns:

Type Description
Fault

The removed fault; it no longer belongs to the network.

Raises:

Type Description
ValueError

If the fault does not exist.

Examples:

>>> net.remove_fault("F_old")
Source code in src/groundinsight/models/core_models.py
def remove_fault(self, name: str) -> "Fault":
    """
    Remove a fault together with its stored result.

    If it was the active fault, no fault is active afterwards. The
    results of the other faults are unaffected: they do not depend on
    this fault's definition.

    Parameters
    ----------
    name : str
        Name of the fault.

    Returns
    -------
    Fault
        The removed fault; it no longer belongs to the network.

    Raises
    ------
    ValueError
        If the fault does not exist.

    Examples
    --------
    >>> net.remove_fault("F_old")  # doctest: +SKIP
    """
    fault = self._lookup("faults", name)
    del self.faults[name]
    self.results.pop(name, None)
    if self.active_fault == name:
        fault.mark_active(False)
        self.active_fault = None
    if any(path.fault == name for path in self.paths.values()):
        self.invalidate_paths()
    return fault

remove_source

remove_source(name: str) -> Source

Remove a source.

Parameters:

Name Type Description Default
name str

Name of the source.

required

Returns:

Type Description
Source

The removed source; it no longer belongs to the network.

Raises:

Type Description
ValueError

If the source does not exist.

Examples:

>>> net.remove_source("S2")
Source code in src/groundinsight/models/core_models.py
def remove_source(self, name: str) -> "Source":
    """
    Remove a source.

    Parameters
    ----------
    name : str
        Name of the source.

    Returns
    -------
    Source
        The removed source; it no longer belongs to the network.

    Raises
    ------
    ValueError
        If the source does not exist.

    Examples
    --------
    >>> net.remove_source("S2")  # doctest: +SKIP
    """
    source = self._lookup("sources", name)
    del self.sources[name]
    if any(path.source == name for path in self.paths.values()):
        self.invalidate_paths()
    return source

res_all_impedances

res_all_impedances() -> pl.DataFrame

Return the grounding impedance and the reduction factor of every fault.

One row per fault, bus and frequency, with the magnitude and angle of the grounding impedance and the reduction factor.

Returns:

Type Description
DataFrame

A DataFrame with the pinned schema :data:RES_ALL_IMPEDANCES_SCHEMA. There is no RMS row here -- a grounding impedance is defined per frequency. grounding_impedance_Ohm / _deg are Z_E, the driving-point impedance of the earthing network at the fault bus (ResultReductionFactor.z_earthing); reduction_factor is value and reduction_factor_current is value_current.

Notes
- Faults without results are skipped.
- Missing grounding impedance or reduction factor results are noted.
- The schema is pinned so an empty result is an empty frame with
  the documented columns rather than a 0x0 one, which would make
  every downstream ``filter``/``join`` fail with a missing-column
  error instead of returning nothing.
Source code in src/groundinsight/models/core_models.py
def res_all_impedances(self) -> pl.DataFrame:
    """
    Return the grounding impedance and the reduction factor of every fault.

    One row per fault, bus and frequency, with the magnitude and angle of
    the grounding impedance and the reduction factor.

    Returns
    -------
    pl.DataFrame
        A DataFrame with the pinned schema
        :data:`RES_ALL_IMPEDANCES_SCHEMA`. There is no RMS row here --
        a grounding impedance is defined per frequency.
        ``grounding_impedance_Ohm`` / ``_deg`` are ``Z_E``, the
        driving-point impedance of the earthing network at the fault bus
        (``ResultReductionFactor.z_earthing``); ``reduction_factor`` is
        ``value`` and ``reduction_factor_current`` is ``value_current``.

    Notes
    -----
        - Faults without results are skipped.
        - Missing grounding impedance or reduction factor results are noted.
        - The schema is pinned so an empty result is an empty frame with
          the documented columns rather than a 0x0 one, which would make
          every downstream ``filter``/``join`` fail with a missing-column
          error instead of returning nothing.
    """
    data = []
    for fault_name, fault in self.faults.items():
        if fault_name not in self.results:
            logger.warning(
                "No results available for fault '%s'. Skipping.",
                fault_name,
            )
            continue
        result = self.results[fault_name]
        fault_bus = fault.bus

        # Grounding Impedance
        grounding_impedance = result.grounding_impedance
        if not grounding_impedance:
            logger.warning(
                "No grounding impedance results for fault '%s'.",
                fault_name,
            )
            continue

        # Reduction Factor
        reduction_factor = result.reduction_factor
        if not reduction_factor:
            logger.warning(
                "No reduction factor results for fault '%s'.",
                fault_name,
            )
            continue

        for freq in self.frequencies:
            gi = grounding_impedance.value.get(freq)
            rf = reduction_factor.value.get(freq)
            rf_current = reduction_factor.value_current.get(freq)
            if gi:
                gi_magnitude = abs(complex(gi.real, gi.imag))
                gi_angle = np.degrees(np.angle(complex(gi.real, gi.imag)))
            else:
                gi_magnitude = None
                gi_angle = None

            data.append(
                {
                    "fault_name": fault_name,
                    "fault_bus": fault_bus,
                    "frequency_Hz": float(freq),
                    "grounding_impedance_Ohm": gi_magnitude,
                    "grounding_impedance_deg": gi_angle,
                    "reduction_factor": rf,
                    "reduction_factor_current": rf_current,
                }
            )
    return pl.DataFrame(data, schema=RES_ALL_IMPEDANCES_SCHEMA)

res_branches

res_branches(fault: Optional[str] = None) -> pl.DataFrame

Returns a Polars DataFrame with branch results for the specified fault.

If no fault is specified, returns results for the active fault.

Parameters:

Name Type Description Default
fault Optional[str]

The name of the fault. Defaults to None.

None

Returns:

Type Description
DataFrame

One row per (branch, frequency) plus one RMS row per branch, with the pinned schema :data:RES_BRANCHES_SCHEMA: branch_name, fault, frequency_Hz (Float64, null on the RMS row), is_rms (Boolean), I_branch_A, I_branch_degree.

Raises:

Type Description
ValueError

If no active fault is set or if results for the specified fault are unavailable.

Notes

See :meth:res_buses for why frequency_Hz is numeric and the RMS marker lives in is_rms.

Source code in src/groundinsight/models/core_models.py
def res_branches(self, fault: Optional[str] = None) -> pl.DataFrame:
    """
    Returns a Polars DataFrame with branch results for the specified fault.

    If no fault is specified, returns results for the active fault.

    Parameters
    ----------
    fault : Optional[str], optional
        The name of the fault. Defaults to None.

    Returns
    -------
    pl.DataFrame
        One row per (branch, frequency) plus one RMS row per branch, with
        the pinned schema :data:`RES_BRANCHES_SCHEMA`: ``branch_name``,
        ``fault``, ``frequency_Hz`` (``Float64``, ``null`` on the RMS
        row), ``is_rms`` (``Boolean``), ``I_branch_A``,
        ``I_branch_degree``.

    Raises
    ------
    ValueError
        If no active fault is set or if results for the specified fault are unavailable.

    Notes
    -----
    See :meth:`res_buses` for why ``frequency_Hz`` is numeric and the RMS
    marker lives in ``is_rms``.
    """
    if fault is None:
        fault = self.active_fault
        if fault is None:
            raise ValueError("No active fault set in the network.")

    if fault not in self.results:
        raise ValueError(f"No results available for fault '{fault}'.")

    # Column-wise (P11), as in res_buses. A falsy entry (``None``, or a
    # plain complex zero in a hand-built result) has never produced a row.
    result = self.results[fault]
    names: List[str] = []
    frequencies: List[float] = []
    rms_rows: List[int] = []
    shield = _PhasorColumn()
    for result_branch in result.branches:
        for freq, current in result_branch.i_s_freq.items():
            if current:
                names.append(result_branch.name)
                frequencies.append(float(freq))
                shield.phasor(current)
        rms_rows.append(len(names))
        names.append(result_branch.name)
        frequencies.append(0.0)
        shield.rms(result_branch.i_s)

    is_rms = np.zeros(len(names), dtype=bool)
    is_rms[rms_rows] = True
    columns = [
        pl.Series("branch_name", names, dtype=pl.Utf8),
        pl.Series("fault", [fault] * len(names), dtype=pl.Utf8),
        _frequency_series(frequencies, rms_rows),
        pl.Series("is_rms", is_rms, dtype=pl.Boolean),
        *shield.series("I_branch_A", "I_branch_degree"),
    ]
    return pl.DataFrame(columns, schema=RES_BRANCHES_SCHEMA)

res_buses

res_buses(fault: Optional[str] = None) -> pl.DataFrame

Returns a Polars DataFrame with bus results for the specified fault.

If no fault is specified, returns results for the active fault.

Parameters:

Name Type Description Default
fault Optional[str]

The name of the fault. Defaults to None.

None

Returns:

Type Description
DataFrame

One row per (bus, frequency) plus one RMS row per bus, with the pinned schema :data:RES_BUSES_SCHEMA:

bus_name, fault, frequency_Hz (Float64, null on the RMS row), is_rms (Boolean), EPR_V, EPR_degree, I_bus_A, I_bus_degree, I_inj_A, I_inj_degree.

Raises:

Type Description
ValueError

If no active fault is set or if results for the specified fault are unavailable.

Notes

frequency_Hz is numeric. The RMS row is marked in its own boolean column, is_rms, and carries null for the frequency, which is what it is: no single frequency. A literal "RMS" in the frequency column would type it Utf8 here while the sibling accessor :meth:res_all_impedances types it Float64, make filter(pl.col("frequency_Hz") == 50.0) silently match nothing, and make :func:groundinsight.summarize refuse the column outright.

I_inj_A / I_inj_degree report the earthing-conductor current i_inj -- the lumped injection at a source or fault bus, which the earthing conductor has to be sized for. It is a different current from I_bus_A (the share dissipated into the soil through the electrode); see :class:ResultBus.

Source code in src/groundinsight/models/core_models.py
def res_buses(self, fault: Optional[str] = None) -> pl.DataFrame:
    """
    Returns a Polars DataFrame with bus results for the specified fault.

    If no fault is specified, returns results for the active fault.

    Parameters
    ----------
    fault : Optional[str], optional
        The name of the fault. Defaults to None.

    Returns
    -------
    pl.DataFrame
        One row per (bus, frequency) plus one RMS row per bus, with the
        pinned schema :data:`RES_BUSES_SCHEMA`:

        ``bus_name``, ``fault``, ``frequency_Hz`` (``Float64``, ``null``
        on the RMS row), ``is_rms`` (``Boolean``), ``EPR_V``,
        ``EPR_degree``, ``I_bus_A``, ``I_bus_degree``, ``I_inj_A``,
        ``I_inj_degree``.

    Raises
    ------
    ValueError
        If no active fault is set or if results for the specified fault are unavailable.

    Notes
    -----
    ``frequency_Hz`` is numeric. The RMS row is marked in its own boolean
    column, ``is_rms``, and carries ``null`` for the frequency, which is
    what it is: no single frequency. A literal ``"RMS"`` in the frequency
    column would type it ``Utf8`` here while the sibling accessor
    :meth:`res_all_impedances` types it ``Float64``, make
    ``filter(pl.col("frequency_Hz") == 50.0)`` silently match nothing, and
    make :func:`groundinsight.summarize` refuse the column outright.

    ``I_inj_A`` / ``I_inj_degree`` report the *earthing-conductor* current
    ``i_inj`` -- the lumped injection at a source or fault bus, which the
    earthing conductor has to be sized for. It is a different current from
    ``I_bus_A`` (the share dissipated into the soil through the electrode);
    see :class:`ResultBus`.
    """
    if fault is None:
        fault = self.active_fault
        if fault is None:
            raise ValueError("No active fault set in the network.")

    if fault not in self.results:
        raise ValueError(f"No results available for fault '{fault}'.")

    # Column-wise (P11): one pass over the result objects collects the
    # phasors; magnitudes and angles are then computed on whole arrays
    # (see _PhasorColumn). Rows, order, schema and values are those of
    # the former row-by-row construction.
    result = self.results[fault]
    names: List[str] = []
    frequencies: List[float] = []
    rms_rows: List[int] = []
    epr, current, injection = _PhasorColumn(), _PhasorColumn(), _PhasorColumn()
    for result_bus in result.buses:
        ia_freq = result_bus.ia_freq
        inj_freq = result_bus.i_inj_freq
        for freq, voltage in result_bus.uepr_freq.items():
            names.append(result_bus.name)
            frequencies.append(float(freq))
            epr.phasor(voltage)
            current.phasor(ia_freq.get(freq))
            injection.phasor(inj_freq.get(freq))
        rms_rows.append(len(names))
        names.append(result_bus.name)
        frequencies.append(0.0)
        epr.rms(result_bus.uepr)
        current.rms(result_bus.ia)
        injection.rms(result_bus.i_inj)

    is_rms = np.zeros(len(names), dtype=bool)
    is_rms[rms_rows] = True
    columns = [
        pl.Series("bus_name", names, dtype=pl.Utf8),
        pl.Series("fault", [fault] * len(names), dtype=pl.Utf8),
        _frequency_series(frequencies, rms_rows),
        pl.Series("is_rms", is_rms, dtype=pl.Boolean),
        *epr.series("EPR_V", "EPR_degree"),
        *current.series("I_bus_A", "I_bus_degree"),
        *injection.series("I_inj_A", "I_inj_degree"),
    ]
    return pl.DataFrame(columns, schema=RES_BUSES_SCHEMA)

res_fault

res_fault(fault: str) -> pl.DataFrame

The key figures of one fault at the fault location, as one table.

Reads the stored result of fault -- nothing is solved -- and puts the numbers an assessment starts from side by side: the fault current, the earth potential rise at the fault bus and the largest one in the network, both reduction factors, the earth-return current and the earthing voltage and impedance of EN 50522. Without it they are spread over ResultBus, ResultReductionFactor, ResultGroundingImpedance and Network.faults.

Parameters:

Name Type Description Default
fault str

Name of a fault of this network with a stored result.

required

Returns:

Type Description
DataFrame

One row per network frequency and one RMS row (is_rms true, frequency_Hz null), with the pinned schema :data:RES_FAULT_SCHEMA:

fault, fault_bus The fault and the bus the result was computed for. I_F_A, I_F_degree The fault current I_F (ResultReductionFactor.i_fault). EPR_fault_V, EPR_fault_degree The EPR at the fault bus (ResultBus.uepr_freq). EPR_max_V, EPR_max_bus The largest EPR in the network and its bus (the first one in result order on a tie). r_epr, r_current The EPR-based reduction factor value and the current-based one value_current (|I_E| / |I_F|). I_E_A The earth-return current |I_E| (i_earth). U_E_V The earthing voltage |U_E| of EN 50522, the EPR at the fault bus (u_earthing). Z_E_Ohm, Z_E_degree The earthing impedance Z_E, the driving-point impedance of the earthing network at the fault bus (z_earthing, equal to ResultGroundingImpedance.value). n_diagnostics The number of records in Result.diagnostics, the same on every row: anything above zero qualifies how the row is read.

A value the result marks as undefined (None) is null. The RMS row holds the stored RMS EPR of the fault bus and the largest one of any bus, and the root sum of squares over the frequencies of I_F, I_E and U_E; ratios, impedances and angles have no RMS value and are null there.

Raises:

Type Description
ValueError

If fault is not a fault of this network.

RuntimeError

If the network holds no result for fault.

Notes

The table reports the stored result. If the network was edited after it was computed, :meth:stale_results lists the fault; the numbers are still those of the result, including the frequencies it was computed at (a network frequency the result does not cover gives a row of nulls). A result in the group format (see :class:ResultReductionFactor) carries no EN 50522 earthing quantities and no fault current; those columns stay null rather than being filled from its group values.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="demo", frequencies=[50.0, 250.0])
>>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
...                       impedance_formula="0.01*rho")
>>> cable = gi.BranchType(name="K", grounding_conductor=True,
...                       self_impedance_formula="(0.25+0.6*j*f/50)*l",
...                       mutual_impedance_formula="0.6*j*f/50*l")
>>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
>>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
>>> _ = gi.create_branch(name="k", type=cable, from_bus="b0", to_bus="b1",
...                      length=1.0, network=net)
>>> _ = gi.create_source(name="q", bus="b0", values={50.0: 100.0, 250.0: 10.0},
...                      network=net)
>>> _ = gi.create_fault(name="ef", bus="b1", network=net)
>>> _ = gi.run_fault(net, "ef")
>>> table = net.res_fault("ef")
>>> table.shape, table["is_rms"].to_list()
((3, 17), [False, False, True])
Source code in src/groundinsight/models/core_models.py
def res_fault(self, fault: str) -> pl.DataFrame:
    """
    The key figures of one fault at the fault location, as one table.

    Reads the stored result of ``fault`` -- nothing is solved -- and puts
    the numbers an assessment starts from side by side: the fault current,
    the earth potential rise at the fault bus and the largest one in the
    network, both reduction factors, the earth-return current and the
    earthing voltage and impedance of EN 50522. Without it they are spread
    over ``ResultBus``, ``ResultReductionFactor``,
    ``ResultGroundingImpedance`` and ``Network.faults``.

    Parameters
    ----------
    fault : str
        Name of a fault of this network with a stored result.

    Returns
    -------
    polars.DataFrame
        One row per network frequency and one RMS row (``is_rms`` true,
        ``frequency_Hz`` null), with the pinned schema
        :data:`RES_FAULT_SCHEMA`:

        ``fault``, ``fault_bus``
            The fault and the bus the result was computed for.
        ``I_F_A``, ``I_F_degree``
            The fault current ``I_F`` (``ResultReductionFactor.i_fault``).
        ``EPR_fault_V``, ``EPR_fault_degree``
            The EPR at the fault bus (``ResultBus.uepr_freq``).
        ``EPR_max_V``, ``EPR_max_bus``
            The largest EPR in the network and its bus (the first one in
            result order on a tie).
        ``r_epr``, ``r_current``
            The EPR-based reduction factor ``value`` and the
            current-based one ``value_current`` (``|I_E| / |I_F|``).
        ``I_E_A``
            The earth-return current ``|I_E|`` (``i_earth``).
        ``U_E_V``
            The earthing voltage ``|U_E|`` of EN 50522, the EPR at the
            fault bus (``u_earthing``).
        ``Z_E_Ohm``, ``Z_E_degree``
            The earthing impedance ``Z_E``, the driving-point impedance
            of the earthing network at the fault bus (``z_earthing``,
            equal to ``ResultGroundingImpedance.value``).
        ``n_diagnostics``
            The number of records in ``Result.diagnostics``, the same on
            every row: anything above zero qualifies how the row is read.

        A value the result marks as undefined (``None``) is null. The RMS
        row holds the stored RMS EPR of the fault bus and the largest one
        of any bus, and the root sum of squares over the frequencies of
        ``I_F``, ``I_E`` and ``U_E``; ratios, impedances and angles have
        no RMS value and are null there.

    Raises
    ------
    ValueError
        If ``fault`` is not a fault of this network.
    RuntimeError
        If the network holds no result for ``fault``.

    Notes
    -----
    The table reports the *stored* result. If the network was edited
    after it was computed, :meth:`stale_results` lists the fault; the
    numbers are still those of the result, including the frequencies it
    was computed at (a network frequency the result does not cover gives
    a row of nulls). A result in the group format (see
    :class:`ResultReductionFactor`) carries no EN 50522 earthing
    quantities and no fault current; those columns stay null rather than
    being filled from its group values.

    Examples
    --------
    >>> import groundinsight as gi
    >>> net = gi.create_network(name="demo", frequencies=[50.0, 250.0])
    >>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
    ...                       impedance_formula="0.01*rho")
    >>> cable = gi.BranchType(name="K", grounding_conductor=True,
    ...                       self_impedance_formula="(0.25+0.6*j*f/50)*l",
    ...                       mutual_impedance_formula="0.6*j*f/50*l")
    >>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
    >>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
    >>> _ = gi.create_branch(name="k", type=cable, from_bus="b0", to_bus="b1",
    ...                      length=1.0, network=net)
    >>> _ = gi.create_source(name="q", bus="b0", values={50.0: 100.0, 250.0: 10.0},
    ...                      network=net)
    >>> _ = gi.create_fault(name="ef", bus="b1", network=net)
    >>> _ = gi.run_fault(net, "ef")
    >>> table = net.res_fault("ef")
    >>> table.shape, table["is_rms"].to_list()
    ((3, 17), [False, False, True])
    """
    if fault not in self.faults:
        raise ValueError(
            f"Fault '{fault}' does not exist in network '{self.name}' "
            f"(faults: {sorted(self.faults)})."
        )
    result = self.results.get(fault)
    if result is None:
        raise RuntimeError(
            f"Network '{self.name}' holds no result for fault '{fault}'. "
            f"gi.run_fault(network, '{fault}') solves and stores one; "
            f"gi.solve(network, '{fault}') returns one without touching the "
            f"network -- keep it with network.results['{fault}'] = result."
        )
    return _fault_key_figures(self, fault, result)

set_active_fault

set_active_fault(fault: str, keep_results: bool = False)

Set the specified fault as active and deactivate all other faults.

Parameters:

Name Type Description Default
fault str

The name of the fault to activate. The former keyword fault_name is accepted as a deprecated alias.

required
keep_results bool

If False (the default), any cached :class:Result for fault is dropped so the next solve starts from a clean slate. If True, the cached result is preserved — useful when re-using the same network to plot a previous solve without recomputing it.

``False``

Raises:

Type Description
ValueError

If the specified fault does not exist in the network.

Source code in src/groundinsight/models/core_models.py
@renamed_parameters(fault_name="fault")
def set_active_fault(self, fault: str, keep_results: bool = False):
    """Set the specified fault as active and deactivate all other faults.

    Parameters
    ----------
    fault : str
        The name of the fault to activate. The former keyword
        ``fault_name`` is accepted as a deprecated alias.
    keep_results : bool, default ``False``
        If ``False`` (the default), any cached
        :class:`Result` for ``fault`` is dropped so the next
        solve starts from a clean slate. If ``True``, the cached
        result is preserved — useful when re-using the same
        network to plot a previous solve without recomputing it.

    Raises
    ------
    ValueError
        If the specified fault does not exist in the network.
    """
    if fault not in self.faults:
        raise ValueError(f"Fault '{fault}' does not exist in the network.")

    # Deactivate all faults
    for other in self.faults.values():
        other.mark_active(False)

    # Activate the specified fault
    self.faults[fault].mark_active(True)
    self.active_fault = fault

    # Clear previous results for the fault unless the caller
    # explicitly asks us to keep them.
    if not keep_results and fault in self.results:
        del self.results[fault]

sources_reaching

sources_reaching(fault: str) -> List[str]

Names of the sources that are connected to a fault over active elements.

The stationary solver in the default phase_current_mode="auto" needs to know which sources feed a fault, not how they get there. This method answers that with one breadth-first search per source over the active bus/branch sub-graph, in O(V + E), instead of enumerating every simple path -- a count that is exponential in the number of loops (1 262 816 paths and about a minute on a 6x6 grid, against milliseconds in the solver itself).

The result is identical to the set of sources that appear in self.paths for this fault after a full :meth:define_paths, because both traverse the same active sub-graph.

Parameters:

Name Type Description Default
fault str

Name of the fault to test reachability against. The former keyword fault_name is accepted as a deprecated alias.

required

Returns:

Type Description
List[str]

Source names in the insertion order of self.sources.

Raises:

Type Description
ValueError

If fault is not a fault of this network.

Examples:

>>> network.sources_reaching("Fault1")
['Source1']
Source code in src/groundinsight/models/core_models.py
@renamed_parameters(fault_name="fault")
def sources_reaching(self, fault: str) -> List[str]:
    """
    Names of the sources that are connected to a fault over active elements.

    The stationary solver in the default ``phase_current_mode="auto"``
    needs to know *which* sources feed a fault, not *how* they get there.
    This method answers that with one breadth-first search per source
    over the active bus/branch sub-graph, in ``O(V + E)``, instead of
    enumerating every simple path -- a count that is exponential in the
    number of loops (1 262 816 paths and about a minute on a 6x6 grid,
    against milliseconds in the solver itself).

    The result is identical to the set of sources that appear in
    ``self.paths`` for this fault after a full :meth:`define_paths`,
    because both traverse the same active sub-graph.

    Parameters
    ----------
    fault : str
        Name of the fault to test reachability against. The former
        keyword ``fault_name`` is accepted as a deprecated alias.

    Returns
    -------
    List[str]
        Source names in the insertion order of ``self.sources``.

    Raises
    ------
    ValueError
        If ``fault`` is not a fault of this network.

    Examples
    --------
    >>> network.sources_reaching("Fault1")  # doctest: +SKIP
    ['Source1']
    """
    from groundinsight.pathfinder import PathFinder  # local import

    if fault not in self.faults:
        raise ValueError(
            f"Fault '{fault}' does not exist in the network "
            f"'{self.name}'."
        )
    fault_bus = self.faults[fault].bus
    pathfinder = PathFinder(self)
    return [
        name
        for name, source in self.sources.items()
        if pathfinder.reaches(source.bus, fault_bus)
    ]

stale_results

stale_results() -> List[str]

Faults whose stored result no longer matches the network.

A result is stale when anything it was computed from has changed since: the frequencies, a bus, branch or source as the solver reads it (impedances, active, the wiring, the source data), or the definition of its own fault (bus, scalings). Metadata such as description, Fault.t_k_s or the IEC 60909 characteristics of a source do not count, and neither does another fault. The comparison is by content: an edit that is undone -- by hand, or by a study that restores the network -- leaves the result current.

Results without a digest -- stored in an earlier file format, or assembled by hand -- are never reported (their provenance is unknown). :func:groundinsight.run_fault makes the result of its fault current.

Returns:

Type Description
List[str]

Fault names, in the order of :attr:results.

Examples:

>>> gi.run_fault(net, "F")
>>> net.update_bus("b1", specific_earth_resistance=250.0)
>>> net.stale_results()
['F']
Source code in src/groundinsight/models/core_models.py
def stale_results(self) -> List[str]:
    """
    Faults whose stored result no longer matches the network.

    A result is stale when anything it was computed from has changed
    since: the frequencies, a bus, branch or source as the solver reads
    it (impedances, ``active``, the wiring, the source data), or the
    definition of its own fault (bus, scalings). Metadata such as
    ``description``, ``Fault.t_k_s`` or the IEC 60909 characteristics of a
    source do not count, and neither does another fault. The comparison
    is by content: an edit that is undone -- by hand, or by a study that
    restores the network -- leaves the result current.

    Results without a digest -- stored in an earlier file format, or
    assembled by hand -- are never reported (their provenance is unknown).
    :func:`groundinsight.run_fault` makes the result of its fault current.

    Returns
    -------
    List[str]
        Fault names, in the order of :attr:`results`.

    Examples
    --------
    >>> gi.run_fault(net, "F")  # doctest: +SKIP
    >>> net.update_bus("b1", specific_earth_resistance=250.0)  # doctest: +SKIP
    >>> net.stale_results()  # doctest: +SKIP
    ['F']
    """
    stale: List[str] = []
    common: Optional[bytes] = None
    for fault in self.results:
        is_stale, common = self._stale(fault, common)
        if is_stale:
            stale.append(fault)
    return stale

to_tables

to_tables() -> Dict[str, pl.DataFrame]

Export the network as the tables :func:groundinsight.network_from_tables reads.

Returns:

Type Description
dict of str to polars.DataFrame

One frame per table of :data:groundinsight.io.tables.TABLE_SCHEMAS, with that schema.

Raises:

Type Description
ValueError

If two different bus types, or branch types, share a name.

Notes

Thin wrapper around :func:groundinsight.io.tables.network_to_tables; see there for what the tables hold and what is recomputed.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="demo", frequencies=[50.0])
>>> list(net.to_tables())[:3]
['network', 'frequencies', 'bus_types']
Source code in src/groundinsight/models/core_models.py
def to_tables(self) -> Dict[str, pl.DataFrame]:
    """
    Export the network as the tables :func:`groundinsight.network_from_tables` reads.

    Returns
    -------
    dict of str to polars.DataFrame
        One frame per table of
        :data:`groundinsight.io.tables.TABLE_SCHEMAS`, with that schema.

    Raises
    ------
    ValueError
        If two different bus types, or branch types, share a name.

    Notes
    -----
    Thin wrapper around :func:`groundinsight.io.tables.network_to_tables`;
    see there for what the tables hold and what is recomputed.

    Examples
    --------
    >>> import groundinsight as gi
    >>> net = gi.create_network(name="demo", frequencies=[50.0])
    >>> list(net.to_tables())[:3]
    ['network', 'frequencies', 'bus_types']
    """
    from groundinsight.io.tables import network_to_tables  # avoids a cycle

    return network_to_tables(self)

update_branch

update_branch(name: str, /, **fields: Any) -> Branch

Change several fields of a branch at once, all or nothing.

Every value is validated first, from_bus/to_bus are checked against the network, then the impedances are derived from the new inputs; only when all of that succeeded are the fields written.

Parameters:

Name Type Description Default
name str

Name of the branch.

required
**fields Any

Fields to change: type, length, specific_earth_resistance, from_bus, to_bus, parallel_coefficient, active, description. The derived impedance and RLCM fields and name cannot be updated.

{}

Returns:

Type Description
Branch

The updated branch (the same object).

Raises:

Type Description
ValueError

If the branch does not exist, a field is unknown, derived or name, a value is invalid, a bus reference names no bus of the network, or the impedances cannot be derived. The branch is unchanged then.

Examples:

>>> net.update_branch("cable_1", length=2.5, to_bus="b3")
Source code in src/groundinsight/models/core_models.py
def update_branch(self, name: str, /, **fields: Any) -> "Branch":
    """
    Change several fields of a branch at once, all or nothing.

    Every value is validated first, ``from_bus``/``to_bus`` are checked
    against the network, then the impedances are derived from the new
    inputs; only when all of that succeeded are the fields written.

    Parameters
    ----------
    name : str
        Name of the branch.
    **fields : Any
        Fields to change: ``type``, ``length``,
        ``specific_earth_resistance``, ``from_bus``, ``to_bus``,
        ``parallel_coefficient``, ``active``, ``description``. The derived
        impedance and RLCM fields and ``name`` cannot be updated.

    Returns
    -------
    Branch
        The updated branch (the same object).

    Raises
    ------
    ValueError
        If the branch does not exist, a field is unknown, derived or
        ``name``, a value is invalid, a bus reference names no bus of
        the network, or the impedances cannot be derived. The branch is
        unchanged then.

    Examples
    --------
    >>> net.update_branch("cable_1", length=2.5, to_bus="b3")  # doctest: +SKIP
    """
    return self._update_element("branches", name, fields)

update_bus

update_bus(name: str, /, **fields: Any) -> Bus

Change several fields of a bus at once, all or nothing.

Every value is validated first, then the impedances are derived from the new inputs; only when all of that succeeded are the fields written. Assigning a single field (bus.specific_earth_resistance = 250) has the same effect for that field.

Parameters:

Name Type Description Default
name str

Name of the bus.

required
**fields Any

Fields to change: type, specific_earth_resistance, active, description. The derived fields (impedance, R, L, C) and name cannot be updated.

{}

Returns:

Type Description
Bus

The updated bus (the same object).

Raises:

Type Description
ValueError

If the bus does not exist, a field is unknown, derived or name, a value is invalid, or the impedances cannot be derived from the new inputs. The bus is unchanged then.

Examples:

>>> net.update_bus("b1", specific_earth_resistance=250.0)
Source code in src/groundinsight/models/core_models.py
def update_bus(self, name: str, /, **fields: Any) -> "Bus":
    """
    Change several fields of a bus at once, all or nothing.

    Every value is validated first, then the impedances are derived from
    the new inputs; only when all of that succeeded are the fields
    written. Assigning a single field (``bus.specific_earth_resistance =
    250``) has the same effect for that field.

    Parameters
    ----------
    name : str
        Name of the bus.
    **fields : Any
        Fields to change: ``type``, ``specific_earth_resistance``,
        ``active``, ``description``. The derived fields (``impedance``,
        ``R``, ``L``, ``C``) and ``name`` cannot be updated.

    Returns
    -------
    Bus
        The updated bus (the same object).

    Raises
    ------
    ValueError
        If the bus does not exist, a field is unknown, derived or
        ``name``, a value is invalid, or the impedances cannot be derived
        from the new inputs. The bus is unchanged then.

    Examples
    --------
    >>> net.update_bus("b1", specific_earth_resistance=250.0)  # doctest: +SKIP
    """
    return self._update_element("buses", name, fields)

Path

Bases: BaseModel

Ordered branch list connecting a source bus to a fault bus.

Attributes:

Name Type Description
name str

The name of the path.

description (str, optional)

A brief description of the path.

source str

The name of the source at the start of the path.

fault str

The name of the fault at the end of the path.

segments list of Branch

Ordered list of branches that make up the path, traversed from source to fault.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> gi.create_paths(net)
>>> path = next(iter(net.paths.values()))
>>> path.source, path.fault, [segment.name for segment in path.segments]
('src', 'fault', ['b12', 'b23'])

Result

Bases: BaseModel

Overall result of a single fault calculation.

Attributes:

Name Type Description
buses list of ResultBus

Per-bus results.

branches list of ResultBranch

Per-branch results.

reduction_factor (ResultReductionFactor, optional)

The reduction factor result, if available.

grounding_impedance (ResultGroundingImpedance, optional)

The grounding impedance result, if available.

fault str

The name of the fault that was active during the calculation.

diagnostics list of Diagnostic

Every package warning raised while this result was computed, with its code and the elements it concerns, in the order raised and without exact repetitions. Filled by :func:groundinsight.run_fault independently of the caller's warning filters, so a program (or a GUI) can read the conditions that qualify the result from the result itself. See :mod:groundinsight.diagnostics.

input_digest (str, optional)

Digest of the inputs this result was computed from -- the network frequencies, every bus, branch and source as the solver reads them, and the definition of this result's fault. Written by :func:groundinsight.run_fault; :meth:Network.stale_results compares it with the network's current inputs. None for results without a digest -- stored in an earlier file format, or assembled by hand -- which are never reported stale (their provenance is unknown).

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> result = gi.run_fault(build_minimal(), "fault")
>>> [bus.name for bus in result.buses], result.diagnostics
(['bus1', 'bus2', 'bus3'], [])
>>> round(result.reduction_factor.value_current[50.0], 4)
0.1803

ResultBus

Bases: BaseModel

Result data for a bus after running a fault calculation.

Three physically distinct currents meet at a grounding bus, and mixing them up is the classic sizing error EN 50522 / IEC 61936-1 guard against:

  • i_inj — the current injected into the grounding system at this bus by the sources (at a source bus) or drawn out of it by the fault (at the fault bus). It flows through a lumped connection, the earthing conductor (Erdungsleiter), which therefore has to be sized for the full earth-fault current. Zero at every other bus.
  • ia — the share of that current which is actually dissipated into the soil at this bus, u_EPR / Z_B. It flows through the earth electrode (Erder) and is generally much smaller.
  • the branch shield currents, reported per branch on :class:ResultBranch.

i_inj deliberately excludes the mutual Norton-equivalent injections of the inductively coupled branches: those model a distributed induced EMF along the line, not a current entering the node through a lumped conductor. The full nodal balance including them is ia = i_vector + sum_branches (u_other - u_self) * Y_self.

Attributes:

Name Type Description
name str

The name of the bus.

uepr float

RMS earth potential rise at the bus, in volts.

ia float

RMS bus current dissipated into the soil through the earth electrode, in amperes.

i_inj float

RMS source-side injection at the bus, in amperes — the current carried by the earthing conductor. Defaults to 0.0 so that results stored before this field existed still validate.

uepr_freq dict of float to ComplexNumber

Mapping of frequency to complex voltage values.

ia_freq dict of float to ComplexNumber

Mapping of frequency to complex electrode current values.

i_inj_freq dict of float to ComplexNumber

Mapping of frequency to complex injection values. Defaults to an empty mapping for backwards compatibility.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> bus = gi.run_fault(build_minimal(), "fault").buses[2]
>>> bus.name, round(bus.uepr, 2), round(abs(bus.uepr_freq[50.0]), 2)
('bus3', 18.03, 18.03)

ResultBranch

Bases: BaseModel

Result data for a branch after running a fault calculation.

Attributes:

Name Type Description
name str

The name of the branch.

i_s float

RMS shield (grounding-conductor) current in the branch, in amperes.

i_s_freq dict of float to ComplexNumber

Mapping of frequency to complex shield current values.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> branch = gi.run_fault(build_minimal(), "fault").branches[0]
>>> branch.name, round(branch.i_s, 2)
('b12', 84.11)

ResultReductionFactor

Bases: BaseModel

Reduction-factor result at the fault bus.

Attributes:

Name Type Description
name (str, optional)

The name of the reduction factor result.

fault_bus str

The bus where the fault occurred.

value dict of float to float, optional

Mapping from frequency to the EPR-based reduction factor r(f) = |u_fault with mutual| / |u_fault without mutual|. This is the quantity that reproduces the familiar closed form r = |1 - Z_mutual / Z_self| for a single shielded line. It is structurally independent of the impedance at the fault bus. None where the denominator is rounding noise -- below 1e-9 of the EPR the fault current alone would cause at the fault bus, |I_F| * |Z_FF| -- with a ModelAssumptionWarning REDUCTION_FACTOR_UNDEFINED (P9).

value_current dict of float to float, optional

Mapping from frequency to the current-based reduction factor r_I(f) = |I_E| / |I_F| -- the measured definition. I_E is the sum of the electrode currents of every bus that feeds the soil, not the electrode current at the faulted station: where the stations are bonded through continuous cable shields the current spreads along them and leaks into the soil at every one of them. Taking only the faulted station understates it by a factor of 1.8 to 4.7 on the verification feeder, depending on where the fault sits. Unlike value this factor responds to the fault-bus characteristic, which is what makes it usable as the ordinate of a rho-f sensitivity study. None per frequency where the frequency carries no fault current, and where no electrode carries more than 1e-9 of the fault current -- the current then returns through the shields and I_E is zero to within rounding; the latter comes with a ModelAssumptionWarning EARTH_GROUP_UNDEFINED (P9).

i_earth dict of float to complex, optional

The earth-return current I_E itself, per frequency, so a study can read the ampere value rather than only the ratio. Electrode currents at or below 1e-9 of the largest one are rounding noise and join neither group; None where value_current is None.

earth_buses dict of float to list of str, optional

The buses counted as feeding the soil at each frequency -- from the fault outwards, in every direction, up to where the potential profile turns. Reported because the split is a modelling statement and should be inspectable; see :mod:groundinsight.utils.earth_current.

i_fault dict of float to complex, optional

The fault current I_F = 3*I_0 the current-based factor divides by: sum(scaling * I_src) over the sources that reach the fault, a source on the fault bus included. For a Thevenin source this is its Norton current E / Z_src. None where no source has a value.

u_earthing dict of float to complex, optional

The earthing voltage U_E of EN 50522: the EPR at the fault bus, in the package's sign convention -- the same complex number as ResultBus.uepr_freq of the fault bus. This is the voltage the touch-voltage assessment starts from; in the norm's ideal case (a fault far from the infeed on a long bonded run) it equals r * |I_F| * |Z_E| with r = |1 - Z_m/Z_s| (value).

z_earthing dict of float to complex, optional

The earthing impedance Z_E of EN 50522: the driving-point impedance of the earthing network at the fault bus -- the voltage one ampere injected at the fault bus raises it to against remote earth, with every electrode and shield in place, without the inductive coupling and without the Thevenin loop closures of voltage sources (those belong to the fault loop, not to the earthing system). It is what an earthing-impedance measurement at the station would see, including the stations bonded to it through cable shields, and on a long homogeneous run it tends to the ladder limit -Z'/2 + sqrt(Z'^2/4 + Z_e*Z'). Equal to ResultGroundingImpedance.value. None only when the fault bus reaches remote earth through nothing but a Thevenin loop -- no bus connected to it through shields carries an electrode -- which is decided by that structure, not by the solver (EARTHING_IMPEDANCE_UNDEFINED).

u_earthing_group dict of float to complex, optional

Diagnostic: the current-weighted mean potential of the earth group earth_buses. On a long bonded run it lies 43 % below the fault-bus EPR, because the group reaches into the decaying tail of the potential profile.

z_earthing_group dict of float to complex, optional

Diagnostic: u_earthing_group / i_earth. The chain u_earthing_group = I_F * z_earthing_group * value_current closes on it by construction, which is why it is no check of anything.

Notes

Fault-bus quantities, not group means. u_earthing and z_earthing are taken at the fault bus. The group means come out 43 % / 45 % below the EPR and the driving-point impedance at the fault in the norm's ideal case -- unconservative if taken as U_E for a touch-voltage assessment -- and are kept as the *_group diagnostics only.

Stored results in the group format. A record without i_fault, u_earthing_group and z_earthing_group holds the group means in u_earthing / z_earthing. It still loads: its values are moved to the *_group fields and u_earthing / z_earthing stay empty until the fault is solved again, so no stored number claims a meaning it was not computed with.

ResultGroundingImpedance

Bases: BaseModel

Grounding impedance result at the fault bus.

Attributes:

Name Type Description
name (str, optional)

The name of the grounding impedance result.

fault_bus str

The bus where the fault occurred.

value dict of float to ComplexNumber, optional

Mapping from frequency to the grounding impedance Z_G(f) = Z_E(f) = Z_dp(F): the driving-point impedance of the earthing network at the fault bus, identical to ResultReductionFactor.z_earthing (see there).

ComplexNumber

Bases: BaseModel

Pydantic-compatible complex number with real and imaginary parts.

Wraps the native :class:complex type so that Pydantic models can serialise and deserialise complex numbers through JSON.

Attributes:

Name Type Description
real float

The real part of the complex number.

imag float

The imaginary part of the complex number.

Notes

Non-finite parts are serialised as the strings "inf", "-inf" and "nan" rather than as the bare JavaScript-style Infinity / NaN literals Python's json module emits. inf is a load-bearing value here -- it is the open-end sentinel produced by the "nan" impedance formula -- so it must survive a round-trip, and the file must stay RFC 8259 JSON: SQLite's json_valid() returns 0 for Infinity, and a browser's JSON.parse refuses it outright, which would make every stored network with an open end unreadable to anything but Python. The validator already accepts those strings, so the round-trip is symmetric.

Examples:

>>> from groundinsight import ComplexNumber
>>> z = ComplexNumber(real=3.0, imag=4.0)
>>> abs(z), complex(z)
(5.0, (3+4j))
>>> z * 2
ComplexNumber(real=6.0, imag=8.0)
>>> ComplexNumber.model_validate("1+2j")
ComplexNumber(real=1.0, imag=2.0)

__eq__

__eq__(other)

Compare against anything convertible; defer otherwise.

Returning NotImplemented instead of raising is what the data model asks for: Python then tries the reflected operation and finally falls back to identity, so z == None is False rather than a TypeError. Every Optional[ComplexNumber] field in this package is compared against None somewhere, and the raising version turned that ordinary check into a crash.

Source code in src/groundinsight/models/core_models.py
def __eq__(self, other):
    """Compare against anything convertible; defer otherwise.

    Returning ``NotImplemented`` instead of raising is what the data
    model asks for: Python then tries the reflected operation and finally
    falls back to identity, so ``z == None`` is ``False`` rather than a
    ``TypeError``. Every ``Optional[ComplexNumber]`` field in this package
    is compared against ``None`` somewhere, and the raising version turned
    that ordinary check into a crash.
    """
    try:
        other = self._convert_to_complex_number(other)
    except TypeError:
        return NotImplemented
    return self.real == other.real and self.imag == other.imag

__hash__

__hash__()

Hash as the equivalent :class:complex.

Defining __eq__ sets __hash__ to None, which made ComplexNumber unusable as a dict key or set member. Hashing the equivalent complex keeps the hash/eq contract across the types this class compares equal to: hash(ComplexNumber(real=1, imag=0)) equals hash(1.0).

Source code in src/groundinsight/models/core_models.py
def __hash__(self):
    """Hash as the equivalent :class:`complex`.

    Defining ``__eq__`` sets ``__hash__`` to ``None``, which made
    ``ComplexNumber`` unusable as a dict key or set member. Hashing the
    equivalent ``complex`` keeps the hash/eq contract across the types
    this class compares equal to: ``hash(ComplexNumber(real=1, imag=0))``
    equals ``hash(1.0)``.
    """
    return hash(complex(self.real, self.imag))

convert_to_float

convert_to_float(value: Any) -> float

Coerce real / imag inputs to float; None becomes NaN.

Parameters:

Name Type Description Default
value Any

Numeric input to coerce. None is interpreted as numpy.nan.

required

Returns:

Type Description
float

The coerced value.

Source code in src/groundinsight/models/core_models.py
@field_validator("real", "imag", mode="before")
def convert_to_float(cls, value: Any) -> float:
    """Coerce ``real`` / ``imag`` inputs to ``float``; ``None`` becomes ``NaN``.

    Parameters
    ----------
    value : Any
        Numeric input to coerce. ``None`` is interpreted
        as ``numpy.nan``.

    Returns
    -------
    float
        The coerced value.
    """
    if value is None:
        return np.nan
    return float(value)

validate_complex classmethod

validate_complex(value: Any) -> Union[ComplexNumber, dict]

Validates and converts the input value to a ComplexNumber instance.

Parameters:

Name Type Description Default
value Any

The value to validate and convert. Can be a ComplexNumber, complex, float, int, dict or str.

required

Returns:

Type Description
Union[ComplexNumber, dict]

Either the original

``ComplexNumber`` instance (passed through) or a dictionary
with ``real`` and ``imag`` keys ready for Pydantic to
instantiate ``ComplexNumber``.

Raises:

Type Description
ValueError

If the input string cannot be parsed as a complex number.

TypeError

If the input type is unsupported.

Source code in src/groundinsight/models/core_models.py
@model_validator(mode="before")
@classmethod
def validate_complex(cls, value: Any) -> Union["ComplexNumber", dict]:
    """
    Validates and converts the input value to a ComplexNumber instance.

    Parameters
    ----------
    value : Any
        The value to validate and convert. Can be a
        ``ComplexNumber``, ``complex``, ``float``, ``int``,
        ``dict`` or ``str``.

    Returns
    -------
    Union[ComplexNumber, dict]
        Either the original
    ``ComplexNumber`` instance (passed through) or a dictionary
    with ``real`` and ``imag`` keys ready for Pydantic to
    instantiate ``ComplexNumber``.

    Raises
    ------
    ValueError
        If the input string cannot be parsed as a complex number.
    TypeError
        If the input type is unsupported.
    """
    if isinstance(value, cls):
        return value
    elif isinstance(value, complex):
        return {"real": value.real, "imag": value.imag}
    elif isinstance(value, (float, int)):
        return {"real": float(value), "imag": 0.0}
    elif isinstance(value, dict):
        return value
    elif isinstance(value, str):
        try:
            c = complex(value.replace(" ", "").replace("i", "j"))
            return {"real": c.real, "imag": c.imag}
        except ValueError as error:
            raise ValueError(f"Invalid complex number string: {value}") from error
    elif isinstance(value, (np.generic, numbers.Complex)):
        # NumPy scalars reach the models straight from the solver arrays;
        # ``np.complex128`` happens to subclass ``complex`` but
        # ``np.complex64`` and the integer types do not, and a bare
        # TypeError for them would name neither the value nor the model.
        try:
            c = complex(value)
        except (TypeError, ValueError) as exc:
            raise TypeError(
                f"Cannot parse ComplexNumber from type {type(value)}"
            ) from exc
        return {"real": c.real, "imag": c.imag}
    else:
        raise TypeError(f"Cannot parse ComplexNumber from type {type(value)}")