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 ingroundinsight.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) andFault(which bus, which scaling per frequency). - Results —
Result,ResultBus,ResultBranch,ResultReductionFactor,ResultGroundingImpedance— the outcome ofrun_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.pathsitself.- The network's path-search memo (
network.path_cache(), seegroundinsight.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 clearValueError. DC (f = 0) is permitted because the FFT transient solver ingroundinsight.simulation.transientuses the zero-frequency bin to carry the steady-state offset. - Duplicate frequencies are rejected — the same
ftwice in the list silently doubled the work insolve_networkand 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 in0.5.0). The FFT transient solver maps spectral bins by position inNetwork.frequencies, so a shuffled or descending list is almost always a user error. Mirrorsgroundfield.solver.engine.EngineFrequencyOrderWarningso 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.lengthandBranch.specific_earth_resistanceon an element that belongs to a network re-derive it through the same code path asNetwork.add_*; assigningNetwork.frequenciesre-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_branchchange 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_busrefuses while a branch, source or fault refers to the bus and names all of them;remove_branch,remove_sourceandremove_fault(which also drops that fault's stored result) complete the set. Unknown names raiseValueError, 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:
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 ¶
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: |
required |
allowed
|
Iterable[str]
|
The parameters the evaluator binds for this formula; |
required |
context
|
str
|
How to name the formula in the message, e.g.
|
'formula'
|
Returns:
| Type | Description |
|---|---|
str
|
|
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
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 | |
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 asNetwork.add_*; assigningNetwork.frequenciesre-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_resultscompares 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_branchand theremove_*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 |
R |
dict of float to float, optional
|
Evaluated lumped resistance per frequency in Ohm. Populated only
if |
L |
dict of float to float, optional
|
Evaluated lumped inductance per frequency in Henry. Populated
only if |
C |
dict of float to float, optional
|
Evaluated lumped capacitance to remote earth per frequency in
Farad. Populated only if |
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 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
validate_impedance ¶
Coerce the keys to float and every value to a ComplexNumber.
Source code in src/groundinsight/models/core_models.py
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. |
voltage_level |
float
|
The voltage level of the bus, in kV. |
impedance_formula |
str
|
SymPy formula for the frequency-domain grounding impedance
|
R_formula |
(str, optional)
|
SymPy formula for the lumped resistance |
L_formula |
(str, optional)
|
SymPy formula for the lumped inductance |
C_formula |
(str, optional)
|
SymPy formula for the lumped capacitance to remote earth
|
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: |
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
|
earthing_conductor_theta_final_C |
(float, optional)
|
Maximum permissible earthing-conductor temperature in °C.
Defaults to the material value in
:data: |
earthing_conductor_current_split |
float
|
Share of the bus injection this conductor carries, in |
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 |
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
|
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 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
validate_rlc_formula ¶
Validate the optional lumped RLC formula strings; None is allowed.
Source code in src/groundinsight/models/core_models.py
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
|
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 |
phase_impedance |
dict of float to ComplexNumber, optional
|
Phase-conductor impedance per frequency, evaluated from
|
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 |
R_mutual, M_mutual |
dict of float to float, optional
|
Mutual resistance (Ohm) and mutual inductance (H) per frequency, from
the matching |
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 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
validate_mutual_impedance ¶
Coerce the keys to float and every value to a ComplexNumber.
Source code in src/groundinsight/models/core_models.py
validate_phase_impedance ¶
Accept None or the same shapes as the other impedance dicts.
Source code in src/groundinsight/models/core_models.py
validate_self_impedance ¶
Coerce the keys to float and every value to a ComplexNumber.
Source code in src/groundinsight/models/core_models.py
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 |
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: |
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 |
theta_final_C |
(float, optional)
|
Maximum permissible conductor temperature in °C. Defaults to the
material value in
:data: |
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 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
validate_rlc_formula ¶
Validate the optional phase / lumped RLCM formula strings; None is allowed.
Source code in src/groundinsight/models/core_models.py
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}
|
|
values |
dict of float to ComplexNumber, optional
|
Frequency-dependent current injection, one phasor per frequency.
Required when |
voltage |
dict of float to ComplexNumber, optional
|
Frequency-dependent Thevenin EMF, one phasor per frequency, again
as RMS amplitudes. Required when |
source_impedance |
dict of float to ComplexNumber, optional
|
Frequency-dependent internal impedance of the Thevenin source.
Required when |
i_k_a |
(float, optional)
|
Initial symmetrical short-circuit current |
r_to_x |
(float, optional)
|
Ratio |
kappa |
(float, optional)
|
IEC 60909-0 peak factor |
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 ( |
t_k_s |
(float, optional)
|
Short-circuit duration (clearing time) |
n_factor |
float, default 1.0
|
AC heat factor |
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
¶
Whether this fault is currently the active one in the network.
Returns:
| Type | Description |
|---|---|
bool
|
|
mark_active ¶
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
scaling_at ¶
The factor this fault applies to the source currents at a frequency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequency
|
float
|
Frequency in Hz (an |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
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
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
¶
The solver workspace of the last build, or None.
Returns:
| Type | Description |
|---|---|
ElectricalNetwork or None
|
The :class: |
pathfinder_settings
property
writable
¶
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 |
Examples:
__setstate__ ¶
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 |
required |
Source code in src/groundinsight/models/core_models.py
add_branch ¶
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 |
Source code in src/groundinsight/models/core_models.py
add_bus ¶
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 |
Source code in src/groundinsight/models/core_models.py
add_fault ¶
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
add_path ¶
Adds a path to the network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
The path instance to add. |
required |
add_source ¶
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 code in src/groundinsight/models/core_models.py
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
input_digest ¶
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: |
None
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
|
Source code in src/groundinsight/models/core_models.py
invalidate_paths ¶
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
is_result_stale ¶
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no result is stored for |
Examples:
Source code in src/groundinsight/models/core_models.py
model_post_init ¶
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
needs_path_rebuild ¶
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
|
|
Source code in src/groundinsight/models/core_models.py
path_cache ¶
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
remove_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:
Source code in src/groundinsight/models/core_models.py
remove_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:
Source code in src/groundinsight/models/core_models.py
remove_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:
Source code in src/groundinsight/models/core_models.py
remove_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:
Source code in src/groundinsight/models/core_models.py
res_all_impedances ¶
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: |
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
4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 | |
res_branches ¶
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: |
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
4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 | |
res_buses ¶
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:
|
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
4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 | |
res_fault ¶
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 (
A value the result marks as undefined ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If the network holds no result for |
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
4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 | |
set_active_fault ¶
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
|
required |
keep_results
|
bool
|
If |
``False``
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specified fault does not exist in the network. |
Source code in src/groundinsight/models/core_models.py
sources_reaching ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
Source names in the insertion order of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/groundinsight/models/core_models.py
stale_results ¶
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: |
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
to_tables ¶
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: |
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
update_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: |
{}
|
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
|
Examples:
Source code in src/groundinsight/models/core_models.py
update_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: |
{}
|
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
|
Examples:
Source code in src/groundinsight/models/core_models.py
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
|
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: |
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: |
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 |
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
|
value_current |
dict of float to float, optional
|
Mapping from frequency to the current-based reduction factor
|
i_earth |
dict of float to complex, optional
|
The earth-return current |
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: |
i_fault |
dict of float to complex, optional
|
The fault current |
u_earthing |
dict of float to complex, optional
|
The earthing voltage |
z_earthing |
dict of float to complex, optional
|
The earthing impedance |
u_earthing_group |
dict of float to complex, optional
|
Diagnostic: the current-weighted mean potential of the earth group
|
z_earthing_group |
dict of float to complex, optional
|
Diagnostic: |
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
|
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__ ¶
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
__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
convert_to_float ¶
Coerce real / imag inputs to float; None becomes NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Numeric input to coerce. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The coerced value. |
Source code in src/groundinsight/models/core_models.py
validate_complex
classmethod
¶
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
|
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. |