Skip to content

Analysis routines

Higher-level analysis workflows on top of a fully built network: the inverse rho problem at the bus-grounding side, the conductor thermal-limit check that assesses whether a grounding conductor survives the fault current it carries, and its node-side counterpart, the node thermal-limit check for earthing conductors and earth electrodes.

Physical / modelling context

A fully built Network solves a forward problem: given the bus grounding impedances \(Z_{\text{B},i}(\rho_E, f)\), find the EPR at the fault bus. The natural inverse question — "how poor can the soil get before the EPR at the fault bus exceeds a limit \(u_{\max}\)?" — is recurring in safety-engineering workflows: it sets the worst-case specific earth resistance the network can tolerate at the assumed fault current. \(u_{\max}\) limits the earth potential rise \(U_E\), not the touch voltage. \(U_E\) is an upper bound of the touch voltage, so with \(u_{\max}\) set to the permissible touch voltage \(U_{Tp}\) of EN 50522 the search returns the soil resistivity up to which the touch voltage is covered without being determined; beyond it the touch voltages have to be determined — see Compare results with EN 50522 limits.

find_max_rho_scaling solves that problem by log-bisection over a uniform scaling factor \(c\) of \(\rho_E\) on a user-supplied list of selected buses. At every trial \(c\), the bus-grounding impedance is re-evaluated through the bus's own BusType.impedance_formula and run_fault is invoked. The bracket converges on the largest \(c\) for which \(|U_\text{EPR}(f)|_{\text{RMS}} \le u_{\max}\) at the fault bus. The sister routine find_max_rho_f_scaling (and the diagnostic helper evaluate_max_epr_under_k) extend the same idea to a frequency- dependent rho-f characteristic: rho is scaled while a separate factor \(k\) tunes the imaginary, frequency-coupling part of the formula, so the inverse problem can be posed against a parametric rho-f curve rather than a single scalar.

The shape of the rho-f curve at each bus is controlled entirely by the existing BusType.impedance_formula; the analysis routines only vary the scalar factors, so any user-defined parametric form (linear, square root, frequency-dependent, …) is supported transparently. Original rho values are restored via a finally block, so the network is left untouched even if the bisection fails.

Example

# fragment: assumes a network `net` with the fault "fault1" and the buses named below
import groundinsight as gi

# Assume `net` is a built network with at least one fault and one
# source. Pick the buses whose specific_earth_resistance should be
# scaled jointly — typically all buses sharing a soil environment.
result = gi.find_max_rho_scaling(
    network=net,
    fault="fault1",
    bus_names=["bus_substation", "bus_fault"],
    u_limit=200.0,          # limit of the RMS EPR at the fault bus, in volts
    c_bounds=(0.1, 100.0),  # search bracket on the scaling factor
    tol_rel=1e-3,
    max_iter=40,
)

# `result` is a dict with keys: c_max, u_epr_rms_at_c_max,
# rho_max (per-bus dict), iterations, status, converged,
# c_bracket, bracket_rel_width.
#
# Read `converged` before `c_max`: c_max is always a scaling factor
# whose EPR was measured and found admissible, but only a converged
# search has also shown that nothing meaningfully larger is.
if not result["converged"]:
    print(f"not a maximum: {result['status']}, "
          f"bracket {result['c_bracket']}")

print(f"c_max = {result['c_max']:.3f}")
print(f"EPR at c_max = {result['u_epr_rms_at_c_max']:.1f} V")
for bus, rho_max in result["rho_max"].items():
    print(f"  {bus}: rho_max = {rho_max:.0f} Ω·m")

Reading the result

c_max carries a one-directional guarantee: the EPR at that scaling factor was computed and found to satisfy the limit. Whether it is also the largest such factor depends on how the search ended, and that is what status reports.

status converged what c_max means
"converged" True The bracket closed to within tol_rel. The true threshold lies inside c_bracket.
"bracket_within_tol_on_entry" True The supplied bracket was already narrower than tol_rel, so no step was needed. Same guarantee as above.
"bracket_fully_admissible" False Every factor in the bracket satisfied the limit, so c_max is the upper bound — a lower bound on the true maximum, since nothing above it was evaluated. c_bracket is (c_hi, inf), so math.isfinite(result["c_bracket"][1]) tests for this case. Widen c_bounds.
"max_iter_reached" False The step cap was hit before the bracket closed. c_max is admissible but can be far below the true threshold — on a saturating test network, a cap of 3 instead of 60 came out 81 % low. Raise max_iter, or narrow c_bounds.
"non_monotone" False find_max_rho_scaling only: the pre-scan over monotonicity_grid points found the EPR not rising monotonically with \(c\), so there is more than one threshold. c_max is the largest factor the scan measured as admissible, refined within its grid interval — a lower bound on the true maximum, as fine as the grid. Raise monotonicity_grid, or narrow c_bounds.

iterations on its own does not identify a case: two of the rows above can produce iterations == 0, and their c_max comes from opposite ends of the bracket. Branch on converged or status, never on the step count.

bracket_rel_width is (c_hi - c_lo) / c_lo for the reported bracket — directly comparable against tol_rel, and inf when the bracket is open upwards.

The arguments are validated strictly, because a limit search that returns a number nobody can tell apart from an answer is worse than one that raises. u_limit and tol_rel must be finite and strictly positive — NaN passes a plain <= 0 check and then makes every later comparison False — c_bounds must be finite, and max_iter must be an int of at least 1.

For the rho-f variant — useful when the bus impedance carries a frequency-coupling term whose magnitude should also be probed — see :func:find_max_rho_f_scaling. It reports the same four diagnostic keys with the same meaning.

Conductor thermal limits (IEC 60949 / IEC 60909-0)

The inverse-rho routines answer a person-safety question (does the EPR, an upper bound of the touch voltage, stay below a limit). check_conductor_limits answers the complementary equipment-integrity question: does the grounding conductor survive the fault thermally? It compares the thermally equivalent short-time current

\[ I_{th} = I_{s,\text{RMS}} \sqrt{m + n} \]

against the adiabatic limit of IEC 60949,

\[ I_{adm} = \frac{k \, S}{\sqrt{t_k}}, \qquad k = K \sqrt{\ln\!\frac{\theta_f + \beta}{\theta_i + \beta}} , \]

per grounding branch, and reports the utilisation and a pass/fail flag. A branch is checked only when its BranchType carries both conductor_material and cross_section_mm2.

What is superposed and what is not

This is the modelling rule the whole short-circuit side is built on. The frequency-domain solve superposes the linear AC-RMS currents as always. The IEC 60909 factors \(\kappa\) and \(m\) are non-linear in the fault-loop \(R/X\), so they are applied once, to the already aggregated branch current — \(i_p\) and \(I_{th}\) are never superposed directly.

With several infeeds the DC components add, so the largest possible peak of the total current is the sum of the individual peaks. Written as a single factor on the aggregate that is exactly the current-weighted mean

\[ \kappa_{\text{eff}} = \frac{\sum_i \kappa_i I_i}{\sum_i I_i} , \]

which resolve_fault_sc_characteristics uses by default (aggregation="weighted"); it reproduces the sum of the individual peaks identically. aggregation="max" is the strictly conservative variant. Reusing one source's \(\kappa\) for all of them is simply wrong and errs in either direction. Where the simultaneous-peak assumption is too crude — strongly mixed \(R/X\) infeeds — the transient solver remains the exact fallback, because it integrates the actual waveforms instead of applying a standard factor.

# fragment: assumes a solved network `net` with the source "src" and the fault "F"
import groundinsight as gi

# The characteristics can be set by hand ...
net.sources["src"].r_to_x = 0.1
net.faults["F"].t_k_s = 0.5

# ... or imported from a solved pandapower case, see the I/O page:
# gi.apply_shortcircuit_characteristics(net, net_pp, "F")

gi.run_fault(net, "F")
gi.check_conductor_limits(net, "F").select(
    "branch_name", "I_s_rms_A", "i_p_A", "I_th_A",
    "I_admissible_A", "utilization", "within_limit",
)

Explicit t_k_s, kappa / r_to_x and n_factor arguments override whatever is stored on the model, so sensitivity studies stay possible.

Node thermal limits — earthing conductor vs earth electrode

check_conductor_limits assesses the shield / earth wire between buses. check_node_limits assesses the two grounding elements at a bus, which EN 50522 / IEC 61936-1 keep strictly apart because they carry different currents. Confusing them is the classic sizing error, and in a meshed system it is an order-of-magnitude error in both directions.

element German current column
earthing conductor Erdungsleiter full injected earth-fault current ResultBus.i_inj
earth electrode Erder share dissipated into the soil, \(u_\text{EPR}/Z_B\) ResultBus.ia

Three physically distinct currents meet at a grounding bus: the lumped injection i_inj, the electrode current ia, and the branch shield currents reported per branch on ResultBranch. The nodal balance that ties them together is

\[ i_a = i_\text{vector} + \sum_\text{branches} (u_\text{other} - u_\text{self})\, Y_\text{self} . \]

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. It is non-zero only at source buses (the infeed) and at the fault bus (the total fault current).

Data model and current split

A bus is assessed per element, and only once its BusType carries both the material and the cross-section for that element. The two elements are independent — declaring one does not imply the other.

import groundinsight as gi

bt = gi.BusType(
    name="tower",
    system_type="Tower",
    voltage_level=110.0,
    impedance_formula="rho * 0.1",
    # Erdungsleiter — sized for the full earth-fault current
    earthing_conductor_material="Cu",
    earthing_conductor_cross_section_mm2=50.0,
    earthing_conductor_theta_final_C=gi.final_temperature("Cu", "bare"),
    # Erder — sized for what actually reaches the soil, four legs
    electrode_material="Steel",
    electrode_cross_section_mm2=95.0,
    electrode_current_split=0.25,
)

Each element carries a free factor current_split in \((0, 1]\), applied as \(I_\text{conductor} = I_\text{RMS}\cdot\texttt{current\_split}\). It expresses how the bus current divides between physically parallel paths that the nodal model lumps into one: 1.0 (default) for a single conductor, 1/N for \(N\) parallel legs, 0.5 for a ring fed at one point, or an IEEE Std 80 division factor. It is deliberately not derived automatically — the split depends on geometry the nodal model does not carry — and a value above 1 is rejected at the model level, because that would not be a split but an error.

# fragment: assumes a network `net` whose bus types carry the thermal data above, with the fault "F"
gi.run_fault(net, "F")
gi.check_node_limits(net, "F", t_k_s=0.5, r_to_x=0.1).select(
    "bus_name", "element", "I_rms_A", "current_split",
    "I_th_A", "I_admissible_A", "utilization", "within_limit",
)

The IEC 60909 excitation (t_k, kappa, m, n) is resolved by the same helper the branch check uses, so both views of one fault always agree. Buses whose type declares neither element still appear in the frame, with the currents filled in and within_limit = None — enough to size by hand without re-running anything.

Final temperatures

FINAL_TEMPERATURES and final_temperature(material, covering) provide \(\theta_f\) values with the source named inline per entry (National Grid ETS Table 5a for bare buried conductors, IEC 60364-5-54 Table 54.2 for PVC / XLPE). The catalog is deliberately incomplete rather than filled with plausible-looking numbers; final_temperature raises for anything missing and names EN 50522 Table 2 as the source to consult.

Steel default

The default final temperature theta_final_default_C of IEC60949_MATERIALS is 300 °C for every material, the value EN 50522 Table 2 gives for a bare or galvanised earthing conductor or earth electrode. Up to 0.4.0 Steel defaulted to 400 °C — more permissive, the unsafe direction for a limit check. A study that relied on the old default gets a smaller \(k\) and a smaller admissible current now; pass theta_final_C=400.0 explicitly to reproduce it.

The three catalogues, as the code holds them:

IEC60949_MATERIALS module-attribute

IEC60949_MATERIALS: Dict[str, Dict[str, float]] = {
    "Cu": {
        "K": 226.0,
        "beta": 234.5,
        "theta_final_default_C": 300.0,
    },
    "Al": {
        "K": 148.0,
        "beta": 228.0,
        "theta_final_default_C": 300.0,
    },
    "Steel": {
        "K": 78.0,
        "beta": 202.0,
        "theta_final_default_C": 300.0,
    },
}

FINAL_TEMPERATURES module-attribute

FINAL_TEMPERATURES: Dict[str, Dict[str, float]] = {
    "Cu": {
        "bare": 300.0,
        "tinned": 150.0,
        **CABLE_INSULATION_LIMITS,
    },
    "Al": {"bare": 300.0, **CABLE_INSULATION_LIMITS},
    "Steel": {
        "bare": 300.0,
        "galvanized": 300.0,
        **CABLE_INSULATION_LIMITS,
    },
}

CABLE_INSULATION_LIMITS module-attribute

CABLE_INSULATION_LIMITS: Dict[str, float] = {
    "PVC": 160.0,
    "XLPE": 250.0,
    "EPR": 250.0,
}

Results computed before this feature

ResultBus.i_inj defaults to 0.0 on results stored by an earlier version, so the earthing-conductor rows would read as unstressed. Re-run run_fault after upgrading.

Incomplete results are an error, not a pass

Both checks build their frame from the stored result of the fault, so a missing entry would produce no row — and a missing row is indistinguishable from a passing one. They therefore verify first that the stored result covers every branch and every active bus, and raise ValueError otherwise rather than reporting the missing elements as free of violations.

This matters because the gap is reachable through ordinary use. ElectricalNetwork.solve_network() replaces network.results[fault] with a result carrying bus rows only — compute_branch_currents() fills in the branches, which is why run_fault calls both — so solving a hand-built ElectricalNetwork to look at \(Y\), \(i\) or \(u\) discards the branch results. Adding a branch after run_fault leaves the same gap. To inspect the nodal system without disturbing anything, build the ElectricalNetwork (its constructor has no side effects) and read the voltages back from network.results[fault].buses instead of re-solving.

Both frames also carry an explicit schema, so a network genuinely without branches returns an empty frame that is still selectable and filterable, rather than a schema-less (0, 0) frame on which pl.col(...) raises.

API reference

analysis

Analysis subpackage.

Contains higher-level analysis routines on top of :mod:network_operations, such as inverse problems for the bus-grounding rho-f characteristic. These functions assume that the network is already fully built (buses, branches, faults, sources, paths) and orchestrate repeated :func:run_fault calls.

BusResponse

Bases: BaseModel

Closed-form response of the network to the electrode at one bus.

Built by :func:bus_response. Evaluating it costs no solve.

Attributes:

Name Type Description
fault str

Fault the response was built for.

bus str

Bus whose electrode is the free parameter.

fault_bus str

Bus the fault sits on. Used to anchor which group of buses is named as feeding the soil when the earth-return current is split.

frequencies list of float

Frequencies covered.

bus_names list of str

The active buses of the network, in the order of the nodal system; the keys of the voltage dictionaries.

z_network dict of float to complex

Driving-point impedance at bus with the local electrode removed -- the parallel impedance the rest of the network offers at that location. Independent of anything installed at bus.

u_open dict of float to dict of str to complex

Nodal voltages with the local electrode removed.

u_open_no_mutual dict of float to dict of str to complex

The same, for the injection vector without the mutual Norton equivalents -- the third right-hand side of the same factorisation. It is what makes the EPR-based reduction factor evaluable per electrode instead of assumed invariant. Empty when the solve carried no mutual-free vector, in which case :meth:evaluate falls back to :attr:r_epr.

other_impedance dict of float to dict of str to complex

Per frequency, the electrode impedance of every bus that carries one, the response bus included; what splits the earth-return current between the electrodes.

z_column dict of float to dict of str to complex

Voltage at every bus per ampere injected at bus, source-free.

r_epr dict of float to float or None

The EPR-based reduction factor of the solved fault, i.e. for the electrode that was installed at bus when :func:bus_response ran. It is constant along the curve only for bus == fault_bus; elsewhere use the r_epr column of :meth:evaluate, which is evaluated for the electrode in hand.

i_fault dict of float to complex

Fault current, the negated sum of source injections. Constant.

z_fault_open dict of float to complex

Driving-point impedance of the earthing network at the fault bus with the electrode at bus removed (Thevenin loop closures excluded) -- Z0_FF.

z_fault_transfer dict of float to complex

Transfer impedance between bus and the fault bus in that network -- Z0_Fb.

z_bus_open dict of float to complex

Driving-point impedance at bus in that network -- Z0_bb; equal to :attr:z_network when the network has no voltage source.

z_fault_ideal dict of float to complex

Where the electrode at bus is the only one of the fault side -- no other electrode is connected to the fault bus through shields -- the three open-network values above do not exist (that network floats). All of the fault current then leaves through the electrode at bus, and Z_E = Z_B + z_fault_ideal with z_fault_ideal the driving point at the fault bus for an ideal electrode at bus. Present only at such frequencies.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> response = gi.bus_response(net, fault="fault")
>>> response.bus, round(abs(response.z_network[50.0]), 4)
('bus3', 1.0965)
>>> frame = response.sweep([0.5, 1.0, 2.0])
>>> [round(v, 2) for v in frame["EPR_V"]]
[11.73, 18.03, 24.28]

admittance

admittance(z_bus: ElectrodeSpec) -> complex

Translate an electrode spelling into a shunt admittance.

None and an infinite impedance both mean no electrode (Y_B = 0); a zero impedance means an ideal one and is returned as inf, which :meth:voltages handles as a limit rather than a division.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode impedance in ohms; None for no electrode.

required

Returns:

Type Description
complex

The shunt admittance Y_B = 1 / z_bus in siemens: 0 without an electrode, inf for an ideal one.

Notes

The electrode is a value, not a frequency-dependent model: the frequency dependence lives in :attr:z_network and in whatever the caller passes per frequency. The method therefore takes no frequency: a parameter it never read would promise an influence it does not have.

Source code in src/groundinsight/analysis/response.py
def admittance(self, z_bus: ElectrodeSpec) -> complex:
    """
    Translate an electrode spelling into a shunt admittance.

    ``None`` and an infinite impedance both mean *no electrode*
    (``Y_B = 0``); a zero impedance means an *ideal* one and is returned as
    ``inf``, which :meth:`voltages` handles as a limit rather than a
    division.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode impedance in ohms; ``None`` for no electrode.

    Returns
    -------
    complex
        The shunt admittance ``Y_B = 1 / z_bus`` in siemens: ``0`` without
        an electrode, ``inf`` for an ideal one.

    Notes
    -----
    The electrode is a value, not a frequency-dependent model: the
    frequency dependence lives in :attr:`z_network` and in whatever the
    caller passes per frequency. The method therefore takes no frequency:
    a parameter it never read would promise an influence it does not
    have.
    """
    if z_bus is None:
        return 0.0 + 0.0j
    z = complex(z_bus)
    if np.isinf(z.real) or np.isinf(z.imag):
        return 0.0 + 0.0j
    if z == 0:
        return complex(np.inf, 0.0)
    return 1.0 / z

driving_point

driving_point(
    z_bus: ElectrodeSpec, frequency: float
) -> complex

Z_dp = 1 / (Y_B + 1/Z_net) -- the impedance seen at bus.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode at bus in Ohm: None or an infinite value for no electrode, 0 for an ideal one (see :meth:admittance).

required
frequency float

One of the frequencies of the response, in Hz. The former keyword freq is accepted as a deprecated alias.

required

Returns:

Type Description
complex

The driving-point impedance in Ohm.

Source code in src/groundinsight/analysis/response.py
@renamed_parameters(freq="frequency")
def driving_point(self, z_bus: ElectrodeSpec, frequency: float) -> complex:
    """
    ``Z_dp = 1 / (Y_B + 1/Z_net)`` -- the impedance seen at ``bus``.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode at ``bus`` in Ohm: ``None`` or an infinite value
        for no electrode, ``0`` for an ideal one (see :meth:`admittance`).
    frequency : float
        One of the frequencies of the response, in Hz. The former
        keyword ``freq`` is accepted as a deprecated alias.

    Returns
    -------
    complex
        The driving-point impedance in Ohm.
    """
    y = self.admittance(z_bus)
    if np.isinf(y.real):
        return 0.0 + 0.0j
    z_net = self.z_network[frequency]
    if z_net == 0:
        return 0.0 + 0.0j
    total = y + 1.0 / z_net
    if total == 0:
        return complex(np.inf, 0.0)
    return 1.0 / total

evaluate

evaluate(
    z_bus: ElectrodeSpec, *, label: Optional[str] = None
) -> pl.DataFrame

Everything the location does for one electrode, as one frame.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode. None or an infinite value means none installed, 0 means ideal. Both are evaluated as exact limits.

required
label str

Value of the case column. Defaults to a readable rendering of z_bus.

None

Returns:

Type Description
DataFrame

One row per frequency: case, bus, fault, frequency_Hz, Z_bus_Ohm, Z_network_Ohm, Z_driving_point_Ohm, EPR_V, EPR_deg, I_electrode_A, r_epr, r_current, Z_G_Ohm, plus EPR_<bus>_V for every other bus.

Notes

r_epr is evaluated for this electrode at the fault bus (see the module docstring); it is constant across electrodes only when bus is the fault bus. Z_G_Ohm is the EN 50522 earthing impedance |Z_E|: the driving-point impedance of the earthing network at the fault bus for this electrode (:meth:fault_driving_point), the same definition :func:~groundinsight.network_operations.run_fault reports. For bus == fault_bus it equals Z_driving_point_Ohm when the network has no voltage source.

Source code in src/groundinsight/analysis/response.py
def evaluate(
    self, z_bus: ElectrodeSpec, *, label: Optional[str] = None
) -> pl.DataFrame:
    """
    Everything the location does for one electrode, as one frame.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode. ``None`` or an infinite value means *none installed*,
        ``0`` means *ideal*. Both are evaluated as exact limits.
    label : str, optional
        Value of the ``case`` column. Defaults to a readable rendering of
        ``z_bus``.

    Returns
    -------
    pl.DataFrame
        One row per frequency: ``case``, ``bus``, ``fault``,
        ``frequency_Hz``, ``Z_bus_Ohm``, ``Z_network_Ohm``,
        ``Z_driving_point_Ohm``, ``EPR_V``, ``EPR_deg``, ``I_electrode_A``,
        ``r_epr``, ``r_current``, ``Z_G_Ohm``, plus ``EPR_<bus>_V`` for
        every other bus.

    Notes
    -----
    ``r_epr`` is evaluated **for this electrode** at the fault bus (see the
    module docstring); it is constant across electrodes only when ``bus`` is
    the fault bus. ``Z_G_Ohm`` is the EN 50522 earthing impedance
    ``|Z_E|``: the driving-point impedance of the earthing network at the
    **fault** bus for this electrode (:meth:`fault_driving_point`), the same
    definition :func:`~groundinsight.network_operations.run_fault` reports.
    For ``bus == fault_bus`` it equals
    ``Z_driving_point_Ohm`` when the network has no voltage source.
    """
    return _frame(self._rows(z_bus, label, self.frequencies))

extremes

extremes() -> pl.DataFrame

The bracket: no electrode, ideal electrode, and the passive worst case.

Three rows per frequency, labelled "open", "ideal" and "worst_passive". The first two are the endpoints of the curve; the third is the reactive electrode that maximises the driving-point magnitude (see :meth:worst_case_electrode).

Returns:

Type Description
DataFrame

The rows of :meth:evaluate for the three cases, stacked.

Source code in src/groundinsight/analysis/response.py
def extremes(self) -> pl.DataFrame:
    """
    The bracket: no electrode, ideal electrode, and the passive worst case.

    Three rows per frequency, labelled ``"open"``, ``"ideal"`` and
    ``"worst_passive"``. The first two are the endpoints of the curve; the
    third is the reactive electrode that maximises the driving-point
    magnitude (see :meth:`worst_case_electrode`).

    Returns
    -------
    pl.DataFrame
        The rows of :meth:`evaluate` for the three cases, stacked.
    """
    frames = [
        self.evaluate(None, label="open"),
        self.evaluate(0.0, label="ideal"),
    ]
    worst_rows: List[Dict[str, object]] = []
    for freq in self.frequencies:
        worst = self.worst_case_electrode(freq)
        worst_rows.extend(self._rows(worst["z_bus"], "worst_passive", [freq]))
    frames.append(_frame(worst_rows))
    return pl.concat(frames, how="diagonal")

fault_driving_point

fault_driving_point(
    z_bus: ElectrodeSpec, frequency: float
) -> Optional[complex]

Z_E, the driving-point impedance at the fault bus, for one electrode.

The electrode sits at bus; the impedance is the one seen at the fault bus.

The shunt Y_B at bus is a rank-one change of the earthing network, so the fault-bus driving point is Möbius in it as well:

Z_FF(Y_B) = Z0_FF - Y_B * Z0_Fb**2 / (1 + Y_B * Z0_bb)

with both endpoints as exact limits. It is the quantity run_fault reports as ResultReductionFactor.z_earthing and as the grounding impedance; for bus == fault_bus it reduces to :meth:driving_point of a network without voltage source.

Where the electrode at bus is the only one of the fault side (:attr:z_fault_ideal), every ampere leaves through it and Z_FF = Z_B + z_fault_ideal: finite for every electrode, undefined without one.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode at bus, as for :meth:evaluate.

required
frequency float

Frequency in Hz.

required

Returns:

Type Description
complex or None

None where Z_E does not exist: the fault side reaches remote earth only through the loop closure of a voltage source -- whatever the electrode at bus, or because z_bus is None and the electrode at bus was its only path.

Source code in src/groundinsight/analysis/response.py
def fault_driving_point(
    self, z_bus: ElectrodeSpec, frequency: float
) -> Optional[complex]:
    """
    ``Z_E``, the driving-point impedance at the fault bus, for one electrode.

    The electrode sits at ``bus``; the impedance is the one seen at the
    **fault** bus.

    The shunt ``Y_B`` at ``bus`` is a rank-one change of the earthing
    network, so the fault-bus driving point is Möbius in it as well:

    ``Z_FF(Y_B) = Z0_FF - Y_B * Z0_Fb**2 / (1 + Y_B * Z0_bb)``

    with both endpoints as exact limits. It is the quantity
    ``run_fault`` reports as ``ResultReductionFactor.z_earthing`` and as
    the grounding impedance; for ``bus == fault_bus`` it
    reduces to :meth:`driving_point` of a network without voltage source.

    Where the electrode at ``bus`` is the only one of the fault side
    (:attr:`z_fault_ideal`), every ampere leaves through it and
    ``Z_FF = Z_B + z_fault_ideal``: finite for every electrode, undefined
    without one.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode at ``bus``, as for :meth:`evaluate`.
    frequency : float
        Frequency in Hz.

    Returns
    -------
    complex or None
        ``None`` where ``Z_E`` does not exist: the fault side reaches
        remote earth only through the loop closure of a voltage source --
        whatever the electrode at ``bus``, or because ``z_bus`` is ``None``
        and the electrode at ``bus`` was its only path.
    """
    z_ff = self.z_fault_open.get(frequency)
    z_fb = self.z_fault_transfer.get(frequency)
    z_bb = self.z_bus_open.get(frequency)
    if z_ff is None or z_fb is None or z_bb is None:
        ideal = self.z_fault_ideal.get(frequency)
        if ideal is None:
            return None
        y = self.admittance(z_bus)
        if y == 0:
            return None
        if np.isinf(y.real):
            return ideal
        return ideal + 1.0 / y
    y = self.admittance(z_bus)
    if np.isinf(y.real):
        if z_bb == 0:
            return z_ff
        return z_ff - z_fb * z_fb / z_bb
    if y == 0:
        return z_ff
    denominator = 1.0 + y * z_bb
    if denominator == 0:
        return None
    return z_ff - y * z_fb * z_fb / denominator

sweep

sweep(
    z_values: Sequence[ElectrodeSpec],
    *,
    labels: Optional[Sequence[str]] = None,
) -> pl.DataFrame

Evaluate many electrodes at once. No solve, whatever the length.

Parameters:

Name Type Description Default
z_values sequence

Electrodes, in the spellings :meth:evaluate accepts.

required
labels sequence of str

One label per value. Defaults to a rendering of each value.

None

Returns:

Type Description
DataFrame

The rows of :meth:evaluate for every electrode, stacked in the order of z_values.

Raises:

Type Description
ValueError

If z_values is empty, or if labels has a different length. An empty sweep would otherwise reach pl.concat([]) and come back as a polars error about an empty iterable, which names neither the argument nor the caller's mistake.

Source code in src/groundinsight/analysis/response.py
def sweep(
    self,
    z_values: Sequence[ElectrodeSpec],
    *,
    labels: Optional[Sequence[str]] = None,
) -> pl.DataFrame:
    """
    Evaluate many electrodes at once. No solve, whatever the length.

    Parameters
    ----------
    z_values : sequence
        Electrodes, in the spellings :meth:`evaluate` accepts.
    labels : sequence of str, optional
        One label per value. Defaults to a rendering of each value.

    Returns
    -------
    pl.DataFrame
        The rows of :meth:`evaluate` for every electrode, stacked in the
        order of ``z_values``.

    Raises
    ------
    ValueError
        If ``z_values`` is empty, or if ``labels`` has a different length.
        An empty sweep would otherwise reach ``pl.concat([])`` and come
        back as a polars error about an empty iterable, which names
        neither the argument nor the caller's mistake.
    """
    if not len(z_values):
        raise ValueError(
            "sweep() needs at least one electrode; an empty z_values has "
            "no frame to build. Pass the electrodes to evaluate, e.g. "
            "sweep([1.0, 10.0, None])."
        )
    if labels is not None and len(labels) != len(z_values):
        raise ValueError(
            f"{len(z_values)} electrode(s) were given but {len(labels)} "
            f"label(s); they have to correspond one to one."
        )
    frames = [
        self.evaluate(z, label=None if labels is None else labels[i])
        for i, z in enumerate(z_values)
    ]
    return pl.concat(frames, how="diagonal")

voltages

voltages(
    z_bus: ElectrodeSpec, frequency: float
) -> Dict[str, complex]

Nodal voltages for one electrode at one frequency.

Both endpoints are evaluated as limits, so an ideal electrode gives exactly zero at bus instead of a very small number.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode at bus in Ohm: None or an infinite value for no electrode, 0 for an ideal one (see :meth:admittance).

required
frequency float

One of the frequencies of the response, in Hz. The former keyword freq is accepted as a deprecated alias.

required

Returns:

Type Description
dict of str to complex

The EPR phasor per bus.

Source code in src/groundinsight/analysis/response.py
@renamed_parameters(freq="frequency")
def voltages(
    self, z_bus: ElectrodeSpec, frequency: float
) -> Dict[str, complex]:
    """
    Nodal voltages for one electrode at one frequency.

    Both endpoints are evaluated as limits, so an ideal electrode gives
    exactly zero at ``bus`` instead of a very small number.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode at ``bus`` in Ohm: ``None`` or an infinite value
        for no electrode, ``0`` for an ideal one (see :meth:`admittance`).
    frequency : float
        One of the frequencies of the response, in Hz. The former
        keyword ``freq`` is accepted as a deprecated alias.

    Returns
    -------
    dict of str to complex
        The EPR phasor per bus.
    """
    return self._with_electrode(self.u_open[frequency], z_bus, frequency)

voltages_no_mutual

voltages_no_mutual(
    z_bus: ElectrodeSpec, frequency: float
) -> Optional[Dict[str, complex]]

The same, for the injection vector without the mutual Norton sources.

This is the denominator of the EPR-based reduction factor. None when the response was built without that right-hand side.

Parameters:

Name Type Description Default
z_bus (complex, float or None)

The electrode at bus in Ohm: None or an infinite value for no electrode, 0 for an ideal one (see :meth:admittance).

required
frequency float

One of the frequencies of the response, in Hz. The former keyword freq is accepted as a deprecated alias.

required

Returns:

Type Description
dict of str to complex or None

The EPR phasor per bus without mutual coupling.

Source code in src/groundinsight/analysis/response.py
@renamed_parameters(freq="frequency")
def voltages_no_mutual(
    self, z_bus: ElectrodeSpec, frequency: float
) -> Optional[Dict[str, complex]]:
    """
    The same, for the injection vector without the mutual Norton sources.

    This is the denominator of the EPR-based reduction factor. ``None`` when
    the response was built without that right-hand side.

    Parameters
    ----------
    z_bus : complex, float or None
        The electrode at ``bus`` in Ohm: ``None`` or an infinite value
        for no electrode, ``0`` for an ideal one (see :meth:`admittance`).
    frequency : float
        One of the frequencies of the response, in Hz. The former
        keyword ``freq`` is accepted as a deprecated alias.

    Returns
    -------
    dict of str to complex or None
        The EPR phasor per bus without mutual coupling.
    """
    u0 = self.u_open_no_mutual.get(frequency)
    if u0 is None:
        return None
    return self._with_electrode(u0, z_bus, frequency)

worst_case_electrode

worst_case_electrode(
    frequency: float,
) -> Dict[str, complex]

The passive electrode that maximises |Z_dp|, and the value it gives.

Over the closed right half-plane of Y_B the magnitude of 1/(Y_B + Y_net) is largest where the imaginary parts cancel and the real part is as small as it can be, i.e. at Y_B = -j*Im(Y_net). The result exceeds |Z_net| only slightly in a cable network, but it is the true bound rather than an assumed one.

Parameters:

Name Type Description Default
frequency float

One of the frequencies of the response, in Hz. The former keyword freq is accepted as a deprecated alias.

required

Returns:

Type Description
dict

z_bus (the electrode, purely reactive) and z_driving_point.

Raises:

Type Description
ValueError

If Re(1/Z_net) <= 0. The bound 1/Re(Y_net) is only the maximum while the network's conductance is positive; a non-positive one turns the same expression into a negative or infinite "worst case" that reads like an answer.

Source code in src/groundinsight/analysis/response.py
@renamed_parameters(freq="frequency")
def worst_case_electrode(self, frequency: float) -> Dict[str, complex]:
    """
    The passive electrode that maximises ``|Z_dp|``, and the value it gives.

    Over the closed right half-plane of ``Y_B`` the magnitude of
    ``1/(Y_B + Y_net)`` is largest where the imaginary parts cancel and the
    real part is as small as it can be, i.e. at ``Y_B = -j*Im(Y_net)``. The
    result exceeds ``|Z_net|`` only slightly in a cable network, but it is
    the true bound rather than an assumed one.

    Parameters
    ----------
    frequency : float
        One of the frequencies of the response, in Hz. The former
        keyword ``freq`` is accepted as a deprecated alias.

    Returns
    -------
    dict
        ``z_bus`` (the electrode, purely reactive) and ``z_driving_point``.

    Raises
    ------
    ValueError
        If ``Re(1/Z_net) <= 0``. The bound ``1/Re(Y_net)`` is only the
        maximum while the network's conductance is positive; a
        non-positive one turns the same expression into a negative or
        infinite "worst case" that reads like an answer.
    """
    z_net = self.z_network[frequency]
    if z_net == 0 or not np.isfinite(z_net):
        return {"z_bus": complex(np.inf, 0.0), "z_driving_point": z_net}
    y_net = 1.0 / z_net
    if y_net.real <= 0:
        raise ValueError(
            f"The network at bus '{self.bus}' has a non-positive "
            f"conductance at {frequency} Hz (Re(1/Z_net) = {y_net.real:g}), so "
            f"the passive worst case 1/Re(Y_net) is not a maximum -- it "
            f"would come back negative or infinite. A passive network "
            f"cannot do this: check the grounding impedances of network "
            f"'{self.fault}' behind this bus, and whether the assembled "
            f"system still matches them (see run_fault)."
        )
    y_b = complex(0.0, -y_net.imag)
    if y_b == 0:
        return {"z_bus": complex(np.inf, 0.0), "z_driving_point": z_net}
    return {"z_bus": 1.0 / y_b, "z_driving_point": 1.0 / y_net.real}

Cut

Bases: BaseModel

A named set of branches separating one side of the network from the fault.

Attributes:

Name Type Description
name str

Label used in the result frame. Must not collide with the reserved name "rest", which is used for the implicit remainder side.

branches list of str

Names of the branches forming the cut. All of them must exist, be active, carry a grounding conductor and be incident to the fault bus.

description (str, optional)

Free text carried through to the result frame.

Examples:

>>> import groundinsight as gi
>>> cut = gi.Cut(name="towards_source", branches=["b23"])
>>> cut.name, cut.branches
('towards_source', ['b23'])

CutAnalysis

Bases: BaseModel

Result of :func:analyze_cuts for one fault.

Attributes:

Name Type Description
fault str

Name of the analysed fault.

fault_bus str

Bus the fault sits on -- the reference point of the decomposition.

frequencies list of float

Frequencies the analysis was run at.

sides dict of str to list of str

Buses visible from the fault bus when looking out through that cut, with the other cuts' branches removed. In a ring the entries overlap.

sides_are_disjoint bool

True when no two directions reach the same bus. The far-side current quantities are only defined in that case.

branches dict of str to list of str

The branches of each cut, including the implicit "rest" side.

z_local dict of float to complex

Impedance of the fault bus's own electrode per frequency.

z_side dict of str to dict of float to complex

Impedance of each direction, from source-free current division.

z_parallel dict of float to complex

z_local in parallel with every z_side.

z_driving_point dict of float to complex

Driving-point impedance of the complete network at the fault bus, read off the solver's assembled nodal system (its 0 Hz substitutes and its Thevenin loop closures included). Equal to z_parallel up to identity_residual.

identity_residual dict of float to float

|z_parallel - z_driving_point| / |z_driving_point| per frequency. What it can and cannot show: z_parallel is the decomposition and z_driving_point is the system that was actually solved, so the residual grows as soon as the decomposition misses a current path out of the fault bus -- a Thevenin loop closure, say, which is worth 2.5 to 23 % of the fault current on the review's cases. It cannot show that the model is right; that is what the reference cases are for. The two sides do not come from one locally assembled matrix: the residual would then be zero by construction -- it would follow from the KCL of the unit-injection solve and could not disagree with anything.

i_shield dict of str to dict of float to complex

Shield current leaving the fault bus in each direction. Empty when no solved result was available.

i_fault, i_local dict of float to complex

Injection at the fault bus and the part of it taken by the fault bus's own electrode.

current_share dict of str to dict of float to float or None

|i_shield| / |i_fault| -- the share of the fault current leaving metallically in that direction. Always defined.

i_earth, i_total dict of str to dict of float to complex or None

Soil and total current crossing the cut, summed over the far side. None per entry when the directions overlap.

r_side dict of str to dict of float to float or None

|i_earth| / |i_total| per direction -- the earth-return share of what crosses that cut. None when the far side carries no injection or when the directions overlap.

kcl_residual dict of float to float

|i_fault - i_local - sum(i_shield)| / |i_fault|. Zero to machine precision confirms the split accounts for the whole fault current.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> analysis = gi.analyze_cuts(net, fault="fault",
...                            cuts=[gi.Cut(name="line", branches=["b23"])])
>>> analysis.has_currents, round(analysis.current_share["line"][50.0], 4)
(True, 0.8411)

has_currents property

has_currents: bool

True when a solved fault result was available.

Returns:

Type Description
bool

Whether the current columns of :meth:to_polars are filled.

to_polars

to_polars() -> pl.DataFrame

Return the analysis as one long-format frame.

One row per direction and frequency.

Returns:

Type Description
DataFrame

One row per (cut, frequency), with a pinned schema and the columns fault, fault_bus, cut, side_buses, n_side_buses, branches, sides_are_disjoint, frequency_Hz, Z_side_Ohm, Z_side_deg, Z_local_Ohm, Z_parallel_Ohm, Z_driving_point_Ohm, identity_residual, I_fault_A, I_local_A, I_shield_A, I_shield_deg, current_share, I_earth_A, I_total_A, r_side, kcl_residual.

Notes

The dtypes are pinned rather than inferred. Without a solved result the nine current columns are all-null, and polars infers Null for them -- a frame that then refuses to concat with one from a solved analysis, which is exactly the comparison a study makes.

Source code in src/groundinsight/analysis/decomposition.py
def to_polars(self) -> pl.DataFrame:
    """
    Return the analysis as one long-format frame.

    One row per direction and frequency.

    Returns
    -------
    pl.DataFrame
        One row per (cut, frequency), with a pinned schema and the
        columns fault, fault_bus, cut, side_buses, n_side_buses,
        branches, sides_are_disjoint, frequency_Hz, Z_side_Ohm,
        Z_side_deg, Z_local_Ohm, Z_parallel_Ohm, Z_driving_point_Ohm,
        identity_residual, I_fault_A, I_local_A, I_shield_A,
        I_shield_deg, current_share, I_earth_A, I_total_A, r_side,
        kcl_residual.

    Notes
    -----
    The dtypes are pinned rather than inferred. Without a solved result the
    nine current columns are all-null, and polars infers ``Null`` for them
    -- a frame that then refuses to ``concat`` with one from a solved
    analysis, which is exactly the comparison a study makes.
    """

    def _mag(value):
        return None if value is None else float(abs(value))

    rows = []
    for cut_name in self.z_side:
        for freq in self.frequencies:
            z = self.z_side[cut_name][freq]
            row = {
                "fault": self.fault,
                "fault_bus": self.fault_bus,
                "cut": cut_name,
                "side_buses": ", ".join(self.sides[cut_name]),
                "n_side_buses": len(self.sides[cut_name]),
                "branches": ", ".join(self.branches[cut_name]),
                "sides_are_disjoint": self.sides_are_disjoint,
                "frequency_Hz": float(freq),
                "Z_side_Ohm": float(abs(z)),
                "Z_side_deg": float(np.degrees(np.angle(z))),
                "Z_local_Ohm": float(abs(self.z_local[freq])),
                "Z_parallel_Ohm": float(abs(self.z_parallel[freq])),
                "Z_driving_point_Ohm": float(abs(self.z_driving_point[freq])),
                "identity_residual": float(self.identity_residual[freq]),
            }
            if self.has_currents:
                i_sh = self.i_shield[cut_name][freq]
                row.update(
                    {
                        "I_fault_A": _mag(self.i_fault[freq]),
                        "I_local_A": _mag(self.i_local[freq]),
                        "I_shield_A": float(abs(i_sh)),
                        "I_shield_deg": float(np.degrees(np.angle(i_sh))),
                        "current_share": self.current_share[cut_name][freq],
                        "I_earth_A": _mag(self.i_earth[cut_name][freq]),
                        "I_total_A": _mag(self.i_total[cut_name][freq]),
                        "r_side": self.r_side[cut_name][freq],
                        "kcl_residual": float(self.kcl_residual[freq]),
                    }
                )
            else:
                row.update(
                    {
                        "I_fault_A": None,
                        "I_local_A": None,
                        "I_shield_A": None,
                        "I_shield_deg": None,
                        "current_share": None,
                        "I_earth_A": None,
                        "I_total_A": None,
                        "r_side": None,
                        "kcl_residual": None,
                    }
                )
            rows.append(row)
    return pl.DataFrame(rows, schema=CUT_FRAME_SCHEMA)

FaultShortCircuitData

Bases: BaseModel

Resolved IEC 60909 characteristics of one fault.

The result of aggregating the per-source data (:attr:Source.i_k_a <groundinsight.models.core_models.Source.i_k_a>, r_to_x, kappa) with the fault-level data (:attr:Fault.t_k_s <groundinsight.models.core_models.Fault.t_k_s>, n_factor) into the single set of numbers the non-linear 60909 factors are evaluated with.

Attributes:

Name Type Description
fault_name str

Name of the fault these characteristics belong to.

frequency float

Frequency in Hz at which the source currents were weighted.

kappa (float, optional)

Effective peak factor, or None when no participating source carries kappa / r_to_x.

r_to_x (float, optional)

Effective R/X, reported only when it is unambiguous (all contributing sources share one value).

t_k_s (float, optional)

Fault duration T_k in seconds, taken from the fault.

n_factor float

AC-decay heat factor n taken from the fault.

m (float, optional)

DC heat-effect factor at kappa, frequency and t_k_s. None when either kappa or t_k_s is unknown.

i_k_a float

Arithmetic sum of the participating source injection magnitudes at frequency (in amperes), i.e. the weight base of the aggregation. This is not the branch current -- that comes from the solve.

i_p_a (float, optional)

kappa * sqrt(2) * i_k_a, reported for reference.

aggregation str

"weighted" or "max".

homogeneous bool

True when every contributing source shares the same kappa (within 1e-9), so the aggregation is exact rather than an interpolation.

sources list of str

Names of the sources that contributed a kappa.

sources_without_kappa list of str

Names of sources that inject current at frequency but carry no 60909 data; they are part of the linear solve but excluded from the kappa aggregation.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="demo", frequencies=[50.0])
>>> bt = gi.BusType(name="b", system_type="s", voltage_level=20.0,
...                 impedance_formula="rho*0 + 1.0")
>>> _ = gi.create_bus(name="B1", type=bt, network=net)
>>> _ = gi.create_source(name="S1", bus="B1", values={50.0: 1000.0},
...                      network=net, r_to_x=0.1)
>>> _ = gi.create_fault(name="F1", bus="B1", scalings={50.0: 1.0},
...                     network=net, t_k_s=0.5)
>>> data = gi.resolve_fault_sc_characteristics(net, "F1")
>>> data.fault_name, data.i_k_a, round(data.kappa, 4), data.homogeneous
('F1', 1000.0, 1.746, True)

ReferenceCase

ReferenceCase(
    name: str,
    quantity: str,
    conditions: str,
    tolerance: float,
    run: Callable[[], Tuple[float, float]],
)

One closed-form case and the model run that has to match it.

Parameters:

Name Type Description Default
name str

Short identifier, used as the row key.

required
quantity str

What is being compared, with its unit.

required
conditions str

The boundary conditions under which the closed form holds. A deviation outside tolerance means either the model is wrong or a condition here was not met -- the second is the more common finding.

required
tolerance float

Relative deviation still counted as agreement.

required
run callable

run() -> (closed_form, model): builds the case's network, solves it and returns both numbers.

required

Attributes:

Name Type Description
name, quantity, conditions, tolerance

The constructor arguments of the same name.

Examples:

>>> import groundinsight as gi
>>> case = gi.REFERENCE_CASES[0]
>>> isinstance(case, gi.ReferenceCase)
True
>>> row = case.evaluate()
>>> row["case"] == case.name, row["agrees"]
(True, True)
Source code in src/groundinsight/analysis/reference.py
def __init__(
    self,
    name: str,
    quantity: str,
    conditions: str,
    tolerance: float,
    run: Callable[[], Tuple[float, float]],
):
    self.name = name
    self.quantity = quantity
    self.conditions = conditions
    self.tolerance = tolerance
    self._run = run

evaluate

evaluate() -> Dict[str, object]

Run the case and return its row.

Returns:

Type Description
dict

The row of :func:run_reference_cases: case, quantity, conditions, closed_form, model, rel_deviation, tolerance and agrees.

Source code in src/groundinsight/analysis/reference.py
def evaluate(self) -> Dict[str, object]:
    """
    Run the case and return its row.

    Returns
    -------
    dict
        The row of :func:`run_reference_cases`: ``case``, ``quantity``,
        ``conditions``, ``closed_form``, ``model``, ``rel_deviation``,
        ``tolerance`` and ``agrees``.
    """
    closed_form, model = self._run()
    reference = abs(closed_form)
    deviation = (
        abs(model - closed_form) / reference if reference > 0 else float("nan")
    )
    return {
        "case": self.name,
        "quantity": self.quantity,
        "conditions": self.conditions,
        "closed_form": float(closed_form),
        "model": float(model),
        "rel_deviation": float(deviation),
        "tolerance": float(self.tolerance),
        "agrees": bool(deviation <= self.tolerance),
    }

admissible_short_circuit_current

admissible_short_circuit_current(
    k: float, cross_section_mm2: float, t_k_s: float
) -> float

Adiabatic admissible short-circuit current I_adm = k*S/sqrt(t_k_s).

Parameters:

Name Type Description Default
k float

Material constant from :func:iec60949_k, in A·s^0.5/mm².

required
cross_section_mm2 float

Conductor cross-section S in mm². Must be strictly positive.

required
t_k_s float

Fault duration T_k in seconds. Must be strictly positive. The former keyword t_k is accepted as a deprecated alias.

required

Returns:

Type Description
float

The admissible short-circuit current in amperes.

Raises:

Type Description
ValueError

If cross_section_mm2 or t_k_s is not strictly positive.

Examples:

>>> import groundinsight as gi
>>> k = gi.iec60949_k("Cu", theta_initial_C=20.0, theta_final_C=200.0)
>>> round(gi.admissible_short_circuit_current(k, 35.0, 1.0))
5785
Source code in src/groundinsight/analysis/thermal.py
@renamed_parameters(t_k="t_k_s")
def admissible_short_circuit_current(
    k: float, cross_section_mm2: float, t_k_s: float
) -> float:
    """
    Adiabatic admissible short-circuit current ``I_adm = k*S/sqrt(t_k_s)``.

    Parameters
    ----------
    k : float
        Material constant from :func:`iec60949_k`, in A·s^0.5/mm².
    cross_section_mm2 : float
        Conductor cross-section ``S`` in mm². Must be strictly positive.
    t_k_s : float
        Fault duration ``T_k`` in seconds. Must be strictly positive. The
        former keyword ``t_k`` is accepted as a deprecated alias.

    Returns
    -------
    float
        The admissible short-circuit current in amperes.

    Raises
    ------
    ValueError
        If ``cross_section_mm2`` or ``t_k_s`` is not strictly positive.

    Examples
    --------
    >>> import groundinsight as gi
    >>> k = gi.iec60949_k("Cu", theta_initial_C=20.0, theta_final_C=200.0)
    >>> round(gi.admissible_short_circuit_current(k, 35.0, 1.0))
    5785
    """
    if cross_section_mm2 <= 0:
        raise ValueError(
            f"cross_section_mm2 must be strictly positive, got {cross_section_mm2!r}."
        )
    if t_k_s <= 0:
        raise ValueError(f"t_k_s must be strictly positive, got {t_k_s!r}.")
    return k * cross_section_mm2 / math.sqrt(t_k_s)

analyze_cuts

analyze_cuts(
    network: Network,
    *,
    fault: str,
    cuts: Sequence[Cut],
    include_currents: bool = True,
) -> CutAnalysis

Split the network at the fault bus and quantify each direction.

Parameters:

Name Type Description Default
network Network

The network. Bus and branch impedances must have been evaluated at network.frequencies (they are, after add_bus / add_branch).

required
fault str

Name of the fault whose bus is the reference of the decomposition.

required
cuts sequence of Cut

Named sets of branches, each incident to the fault bus and disjoint from the others. Incident branches that no cut claims form the implicit side "rest".

required
include_currents bool

If True (default) the current split is read from network.results[fault]. When no such result exists the impedances are still returned and the current fields stay empty -- the impedance half of the analysis needs no solve.

True

Returns:

Type Description
CutAnalysis

Impedances, currents and the residual of the parallel identity.

Raises:

Type Description
ValueError

If the fault is unknown, if a cut names a branch that is not an active grounding branch at the fault bus, or if two cuts claim the same branch.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> analysis = gi.analyze_cuts(net, fault="fault",
...                            cuts=[gi.Cut(name="line", branches=["b23"])])
>>> frame = analysis.to_polars()
>>> [(cut, f, round(z, 9)) for cut, f, z in
...  frame.select("cut", "frequency_Hz", "Z_side_Ohm").rows()]
[('line', 50.0, 1.096518338)]
Source code in src/groundinsight/analysis/decomposition.py
def analyze_cuts(
    network: Network,
    *,
    fault: str,
    cuts: Sequence[Cut],
    include_currents: bool = True,
) -> CutAnalysis:
    """
    Split the network at the fault bus and quantify each direction.

    Parameters
    ----------
    network : Network
        The network. Bus and branch impedances must have been evaluated at
        ``network.frequencies`` (they are, after ``add_bus`` / ``add_branch``).
    fault : str
        Name of the fault whose bus is the reference of the decomposition.
    cuts : sequence of Cut
        Named sets of branches, each incident to the fault bus and disjoint from
        the others. Incident branches that no cut claims form the implicit side
        ``"rest"``.
    include_currents : bool, optional
        If ``True`` (default) the current split is read from
        ``network.results[fault]``. When no such result exists the impedances
        are still returned and the current fields stay empty -- the impedance
        half of the analysis needs no solve.

    Returns
    -------
    CutAnalysis
        Impedances, currents and the residual of the parallel identity.

    Raises
    ------
    ValueError
        If the fault is unknown, if a cut names a branch that is not an active
        grounding branch at the fault bus, or if two cuts claim the same branch.

    Examples
    --------
    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> net = build_minimal()
    >>> _ = gi.run_fault(net, "fault")
    >>> analysis = gi.analyze_cuts(net, fault="fault",
    ...                            cuts=[gi.Cut(name="line", branches=["b23"])])
    >>> frame = analysis.to_polars()
    >>> [(cut, f, round(z, 9)) for cut, f, z in
    ...  frame.select("cut", "frequency_Hz", "Z_side_Ohm").rows()]
    [('line', 50.0, 1.096518338)]
    """
    if fault not in network.faults:
        raise ValueError(
            f"Fault '{fault}' does not exist in network '{network.name}'. "
            f"Available: {sorted(network.faults)}."
        )
    fault_bus = network.faults[fault].bus
    resolved, incident = _validate_cuts(network, cuts, fault_bus)
    frequencies = [float(f) for f in network.frequencies]

    # The solver's own matrices, when there are any and they still describe
    # this network. Everything below reads impedances through them, so the
    # decomposition is of the system that was solved rather than of a second
    # one assembled from the same fields under slightly different rules.
    electrical = _assembled_system(network)

    directions = {
        name: _direction_buses(network, set(branches), incident, fault_bus)
        for name, branches in resolved.items()
    }
    # Disjointness is a statement about the *galvanic* sides, so it is decided
    # before the loop closure is added below -- that one shares its buses with
    # whichever side reaches the source and would report every Thevenin network
    # as overlapping.
    cut_names = list(resolved)
    disjoint = all(
        not (set(directions[a]) & set(directions[b]))
        for i, a in enumerate(cut_names)
        for b in cut_names[i + 1 :]
    )

    # The Thevenin loop closures, if any, are a direction of their own: they
    # carry current out of the fault bus without being a branch of the
    # grounding grid. The buses they reach are the source buses.
    loop_sources = {
        freq: _source_loop_closures(network, fault_bus, freq, electrical)
        for freq in frequencies
    }
    loop_source_names = sorted(
        {name for freq in frequencies for name in loop_sources[freq]}
    )
    if loop_source_names:
        resolved[SOURCE_LOOP_SIDE] = loop_source_names
        directions[SOURCE_LOOP_SIDE] = sorted(
            {network.sources[n].bus for n in loop_source_names}
        )
        logger.info(
            "Fault bus '%s' carries a Thevenin loop closure from source(s) %s. "
            "It is reported as the direction '%s': not a side of the grounding "
            "grid, but a current path out of the fault location that the "
            "parallel identity and the current balance both have to include.",
            fault_bus, ", ".join(loop_source_names), SOURCE_LOOP_SIDE,
        )
    names = list(resolved)

    z_local: Dict[float, complex] = {}
    z_side: Dict[str, Dict[float, complex]] = {name: {} for name in resolved}
    z_parallel: Dict[float, complex] = {}
    z_driving_point: Dict[float, complex] = {}
    identity_residual: Dict[float, float] = {}

    infinite = complex(np.inf, 0.0)
    for freq in frequencies:
        local = _resolve(
            electrical, network.buses[fault_bus].impedance.get(freq), freq
        )
        z_local[freq] = local if local is not None else infinite

        u = _unit_injection(network, fault_bus, freq, electrical)
        if u is None:
            z_driving_point[freq] = infinite
            for name in resolved:
                z_side[name][freq] = infinite
            z_parallel[freq] = infinite
            identity_residual[freq] = float("nan")
            continue

        u_fault = u[fault_bus]
        z_driving_point[freq] = u_fault

        admittance = 0.0 + 0.0j if local is None else 1.0 / local
        for name, branches in resolved.items():
            if name == SOURCE_LOOP_SIDE:
                i_cut = sum(
                    (
                        (u_fault - u[network.sources[s].bus]) * y
                        for s, y in loop_sources[freq].items()
                    ),
                    0.0 + 0.0j,
                )
            else:
                i_cut = sum(
                    (
                        _branch_current_out(
                            network, b, fault_bus, u, freq, electrical
                        )
                        for b in branches
                    ),
                    0.0 + 0.0j,
                )
            if i_cut == 0 or u_fault == 0:
                z_side[name][freq] = infinite
            else:
                z = u_fault / i_cut
                z_side[name][freq] = z
                admittance += 1.0 / z

        z_parallel[freq] = 1.0 / admittance if admittance != 0 else infinite
        reference = abs(z_driving_point[freq])
        identity_residual[freq] = (
            abs(z_parallel[freq] - z_driving_point[freq]) / reference
            if reference > 0 and np.isfinite(reference)
            else float("nan")
        )

    analysis_kwargs = dict(
        fault=fault,
        fault_bus=fault_bus,
        frequencies=frequencies,
        sides=directions,
        sides_are_disjoint=disjoint,
        branches=resolved,
        z_local=z_local,
        z_side=z_side,
        z_parallel=z_parallel,
        z_driving_point=z_driving_point,
        identity_residual=identity_residual,
    )

    if include_currents and fault in network.results:
        result = network.results[fault]
        branch_results = {b.name: b for b in result.branches}
        bus_results = {b.name: b for b in result.buses}

        # A result that does not cover the whole network would otherwise
        # surface as a bare ``KeyError: 'K9'`` out of the loops below. The
        # guard is the one the thermal checks use, so both name the cause and
        # the remedy the same way.
        needed_buses = sorted(
            {fault_bus}
            | {b for side in directions.values() for b in side}
        )
        require_complete_results(
            fault, needed_buses, list(bus_results), "bus"
        )
        require_complete_results(
            fault,
            sorted({b for name in resolved if name != SOURCE_LOOP_SIDE
                    for b in resolved[name]}),
            list(branch_results),
            "branch",
        )

        i_shield: Dict[str, Dict[float, complex]] = {n: {} for n in resolved}
        i_earth: Dict[str, Dict[float, complex]] = {n: {} for n in resolved}
        i_total: Dict[str, Dict[float, complex]] = {n: {} for n in resolved}
        r_side: Dict[str, Dict[float, Optional[float]]] = {n: {} for n in resolved}
        current_share: Dict[str, Dict[float, Optional[float]]] = {
            n: {} for n in resolved
        }
        i_fault: Dict[float, complex] = {}
        i_local: Dict[float, complex] = {}
        kcl_residual: Dict[float, float] = {}

        for freq in frequencies:
            injection = complex(bus_results[fault_bus].i_inj_freq[freq])
            local_current = complex(bus_results[fault_bus].ia_freq[freq])
            i_fault[freq] = injection
            i_local[freq] = local_current
            leaving = 0.0 + 0.0j

            for name, branches in resolved.items():
                total_out = 0.0 + 0.0j
                if name == SOURCE_LOOP_SIDE:
                    # The loop closure carries no shield current of its own; it
                    # is an admittance between two nodes, so its current is read
                    # off the solved potentials.
                    u_f = complex(bus_results[fault_bus].uepr_freq[freq])
                    for source_name, y in loop_sources[freq].items():
                        source_bus = network.sources[source_name].bus
                        if source_bus not in bus_results:
                            continue
                        u_s = complex(bus_results[source_bus].uepr_freq[freq])
                        total_out += (u_f - u_s) * y
                else:
                    for branch_name in branches:
                        branch = network.branches[branch_name]
                        stored = complex(branch_results[branch_name].i_s_freq[freq])
                        # ``i_s`` is oriented to_bus -> from_bus, so it already is
                        # the current leaving the fault bus when the fault bus is
                        # the to_bus, and the negative of it otherwise.
                        sign = 1.0 if branch.to_bus == fault_bus else -1.0
                        total_out += sign * stored
                i_shield[name][freq] = total_out
                leaving += total_out
                current_share[name][freq] = (
                    abs(total_out) / abs(injection) if injection != 0 else None
                )

                if disjoint and name != SOURCE_LOOP_SIDE:
                    far = directions[name]
                    earth = sum(
                        (complex(bus_results[b].ia_freq[freq]) for b in far),
                        0.0 + 0.0j,
                    )
                    total = sum(
                        (complex(bus_results[b].i_inj_freq[freq]) for b in far),
                        0.0 + 0.0j,
                    )
                    i_earth[name][freq] = earth
                    i_total[name][freq] = total
                    r_side[name][freq] = (
                        abs(earth) / abs(total) if abs(total) > 0 else None
                    )
                else:
                    i_earth[name][freq] = None
                    i_total[name][freq] = None
                    r_side[name][freq] = None

            reference = abs(injection)
            kcl_residual[freq] = (
                abs(injection - local_current - leaving) / reference
                if reference > 0
                else 0.0
            )

        if not disjoint:
            logger.info(
                "The directions out of fault bus '%s' overlap -- %s reach each "
                "other around a ring -- so there is no far side belonging to "
                "one cut alone. The impedances are unaffected (they come from "
                "current division), but I_earth, I_total and r_side are left "
                "empty; use current_share instead.",
                fault_bus,
                " and ".join(f"'{n}'" for n in names),
            )

        analysis_kwargs.update(
            i_shield=i_shield,
            i_earth=i_earth,
            i_total=i_total,
            r_side=r_side,
            current_share=current_share,
            i_fault=i_fault,
            i_local=i_local,
            kcl_residual=kcl_residual,
        )
    elif include_currents:
        logger.info(
            "No solved result for fault '%s' on network '%s', so only the "
            "source-free impedances are reported. Call run_fault first if you "
            "also want the current split.",
            fault,
            network.name,
        )

    return CutAnalysis(**analysis_kwargs)

bus_response

bus_response(
    network: Network,
    *,
    fault: str,
    bus: Optional[str] = None,
) -> BusResponse

Build the closed-form response of the network to the electrode at one bus.

Requires a solved fault: the assembled nodal system is reused, the bus's own shunt is taken back out of it, and three right-hand sides are solved against the one factorisation -- the fault with the electrode removed, a unit injection at the bus, and the same fault without the mutual Norton equivalents. None of them depends on the electrode, which is why the result covers every electrode.

Parameters:

Name Type Description Default
network Network

A network with network.results[fault] present, i.e. after :func:~groundinsight.network_operations.run_fault.

required
fault str

The solved fault.

required
bus str

Bus whose electrode is the free parameter. Defaults to the fault bus.

None

Returns:

Type Description
BusResponse

The response of the network to the electrode at bus; evaluating it for any electrode costs no further solve.

Raises:

Type Description
ValueError

If the fault has not been solved, if the bus is unknown or inactive, or if the network without that electrode has no path to reference earth -- in which case there is nothing to characterise, because the location's behaviour is its own electrode.

Examples:

The fault bus of the minimal network, with its own electrode as the free parameter -- every electrode is evaluated without another solve:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> response = gi.bus_response(net, fault="fault", bus="bus3")
>>> row = response.evaluate(1.0)
>>> round(row["EPR_V"].item(), 2)
18.03
Source code in src/groundinsight/analysis/response.py
def bus_response(
    network: Network,
    *,
    fault: str,
    bus: Optional[str] = None,
) -> BusResponse:
    """
    Build the closed-form response of the network to the electrode at one bus.

    Requires a solved fault: the assembled nodal system is reused, the bus's own
    shunt is taken back out of it, and three right-hand sides are solved against
    the one factorisation -- the fault with the electrode removed, a unit
    injection at the bus, and the same fault without the mutual Norton
    equivalents. None of them depends on the electrode, which is why the result
    covers every electrode.

    Parameters
    ----------
    network : Network
        A network with ``network.results[fault]`` present, i.e. after
        :func:`~groundinsight.network_operations.run_fault`.
    fault : str
        The solved fault.
    bus : str, optional
        Bus whose electrode is the free parameter. Defaults to the fault bus.

    Returns
    -------
    BusResponse
        The response of the network to the electrode at ``bus``; evaluating
        it for any electrode costs no further solve.

    Raises
    ------
    ValueError
        If the fault has not been solved, if the bus is unknown or inactive, or
        if the network without that electrode has no path to reference earth --
        in which case there is nothing to characterise, because the location's
        behaviour *is* its own electrode.

    Examples
    --------
    The fault bus of the minimal network, with its own electrode as the free
    parameter -- every electrode is evaluated without another solve:

    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> net = build_minimal()
    >>> _ = gi.run_fault(net, "fault")
    >>> response = gi.bus_response(net, fault="fault", bus="bus3")
    >>> row = response.evaluate(1.0)
    >>> round(row["EPR_V"].item(), 2)
    18.03
    """
    if fault not in network.results:
        raise ValueError(
            f"Fault '{fault}' has no result on network '{network.name}'. The "
            f"response is read off the assembled nodal system, so call "
            f"run_fault first."
        )
    electrical = network.electrical_network
    if electrical is None or not getattr(electrical, "Y_sparse", None):
        raise ValueError(
            f"Network '{network.name}' carries no assembled electrical network. "
            f"Call run_fault before asking for a bus response."
        )
    # The response is read off the assembled matrices, and those are a
    # snapshot: an impedance changed after ``run_fault`` -- by hand, or by a
    # study that scaled rho and put it back -- does not reach them. Reading a
    # stale Y next to the current impedances does not fail loudly; it produced
    # a *negative* driving-point impedance in the review case, because the
    # shunt taken out below was never the shunt that went in. So refuse rather
    # than answer.
    if not electrical.matches_network_state():
        raise ValueError(
            f"The assembled nodal system of network '{network.name}' was built "
            f"from different model values than the ones the network carries "
            f"now (impedances, active flags or the active fault changed since "
            f"the last run_fault). A bus response read off it would mix the two "
            f"states and can come out non-physical -- a negative driving-point "
            f"impedance, for instance. Call run_fault again for fault "
            f"'{fault}' before asking for the response."
        )

    target = bus if bus is not None else network.faults[fault].bus
    if target not in electrical.bus_indices:
        known = sorted(electrical.bus_indices)
        raise ValueError(
            f"Bus '{target}' is not part of the solved system of network "
            f"'{network.name}'. Active buses: {known}."
        )

    index = electrical.bus_indices
    order = sorted(index, key=lambda name: index[name])
    k = index[target]
    frequencies = [float(f) for f in network.frequencies]

    result = network.results[fault]
    reduction = result.reduction_factor
    r_epr = dict(reduction.value) if reduction is not None else {}

    z_network: Dict[float, complex] = {}
    u_open: Dict[float, Dict[str, complex]] = {}
    u_open_no_mutual: Dict[float, Dict[str, complex]] = {}
    z_column: Dict[float, Dict[str, complex]] = {}
    other_impedance: Dict[float, Dict[str, complex]] = {}
    i_fault: Dict[float, complex] = {}
    z_fault_open: Dict[float, complex] = {}
    z_fault_transfer: Dict[float, complex] = {}
    z_bus_open: Dict[float, complex] = {}
    z_fault_ideal: Dict[float, complex] = {}
    fault_bus = network.faults[fault].bus

    for freq in frequencies:
        Y = electrical.Y_sparse.get(freq)
        i_vector = electrical.i_vectors.get(freq)
        if Y is None or i_vector is None:
            continue

        # The resolved grounding impedance of every bus, and the admittance the
        # assembly stamped for it, in one call. The same values answer three
        # questions below -- the shunt to remove, whether any other bus
        # reaches earth, and the electrode currents.
        impedances, admittances = electrical.grounding_shunts(freq)
        electrode = np.isfinite(impedances) & (impedances != 0)

        # Take the bus's own shunt back out of a copy of the sparse matrix.
        # The same rules as the assembly: a missing or infinite impedance
        # never contributed one in the first place. The value subtracted is
        # the one that was added, so an electrode that was the bus's only
        # connection leaves an exact zero behind.
        Y0 = Y.copy()
        if electrode[k]:
            Y0 = _subtract_from_diagonal(Y0, k, admittances[k])

        # The check is structural, not a tolerance: at least one *other* bus of
        # the target's group -- the buses the solved matrix couples it to,
        # through shields or a voltage source's loop closure -- has to carry a
        # finite, non-zero grounding impedance once the target's shunt is
        # gone. Leaving it to the linear solver is not enough -- measured on
        # the exactly singular case, numpy returns a finite but meaningless
        # -2.25e15 instead of raising, the same inconsistency the DC work
        # found in scipy's splu -- and an earthed bus elsewhere in the
        # network does not help a group that is not connected to it.
        others = electrode.copy()
        others[k] = False
        labels = component_labels(Y0)
        if not np.any(others & (labels == labels[k])):
            raise ValueError(
                f"With the electrode at bus '{target}' removed, no other bus of "
                f"network '{network.name}' connected to it has a finite "
                f"grounding impedance at {freq} Hz, so there is no path to "
                f"reference earth. There is nothing to characterise "
                f"independently of that electrode: at this location the "
                f"network's behaviour *is* the electrode. Pick a bus that has "
                f"at least one other earthed bus behind it."
            )

        unit = np.zeros(len(order), dtype=complex)
        unit[k] = 1.0
        # Three right-hand sides, one factorisation: the fault injection, the
        # unit injection at the bus, and -- when the solve carried it -- the
        # same fault injection without the mutual Norton equivalents. The third
        # is what makes ``r_epr`` evaluable per electrode (it is the denominator
        # of the reduction factor). The factorisation is a sparse LU of the
        # assembled matrix: a dense solve on a copy of a dense ``Y`` is cubic in
        # the number of buses -- 5.6 s on a 2000-bus ring at seven frequencies,
        # the dense earthing columns included.
        i_no_mutual = electrical.i_vectors_no_mutual.get(freq)
        rhs = [np.asarray(i_vector, dtype=complex), unit]
        if i_no_mutual is not None:
            rhs.append(np.asarray(i_no_mutual, dtype=complex))
        try:
            factor = splu(Y0)
            solved = factor.solve(np.column_stack(rhs))
            u0 = solved[:, 0]
            z_col = solved[:, 1]
            u0_nm = solved[:, 2] if i_no_mutual is not None else None
        except (np.linalg.LinAlgError, RuntimeError) as exc:
            raise ValueError(
                f"The nodal system of network '{network.name}' is singular at "
                f"{freq} Hz once the electrode at bus '{target}' is removed, "
                f"even though other buses are earthed. Check for a subnetwork "
                f"that reaches earth only through '{target}'."
            ) from exc
        if not (np.all(np.isfinite(u0)) and np.all(np.isfinite(z_col))):
            raise ValueError(
                f"The response of bus '{target}' at {freq} Hz came out "
                f"non-finite. That points at an infinite or NaN impedance "
                f"somewhere in network '{network.name}' rather than at the bus "
                f"itself."
            )

        z_network[freq] = complex(z_col[k])
        u_open[freq] = dict(zip(order, u0.tolist(), strict=True))
        z_column[freq] = dict(zip(order, z_col.tolist(), strict=True))
        if u0_nm is not None:
            u_open_no_mutual[freq] = dict(zip(order, u0_nm.tolist(), strict=True))

        other_impedance[freq] = {
            order[i]: complex(impedances[i]) for i in np.flatnonzero(electrode)
        }

        # The earthing network without the electrode at ``target`` and without
        # the Thevenin loop closures: three numbers make the fault-bus driving
        # point Z_E available for every electrode (fault_driving_point, F4).
        earth_columns = _earthing_columns(
            electrical, Y0, factor, k, index[fault_bus], freq
        )
        if earth_columns is not None:
            kind, values = earth_columns
            if kind == "open":
                z_fault_open[freq], z_fault_transfer[freq], z_bus_open[freq] = values
            else:
                z_fault_ideal[freq] = values

        total_source = electrical.total_source_currents.get(freq)
        if total_source is not None:
            i_fault[freq] = -complex(total_source)

    if not z_network:
        raise ValueError(
            f"No frequency of fault '{fault}' carried an assembled system, so "
            f"there is no response to build."
        )

    return BusResponse(
        fault=fault,
        bus=target,
        fault_bus=network.faults[fault].bus,
        frequencies=[f for f in frequencies if f in z_network],
        bus_names=order,
        z_network=z_network,
        u_open=u_open,
        u_open_no_mutual=u_open_no_mutual,
        z_column=z_column,
        other_impedance=other_impedance,
        r_epr=r_epr,
        i_fault=i_fault,
        z_fault_open=z_fault_open,
        z_fault_transfer=z_fault_transfer,
        z_bus_open=z_bus_open,
        z_fault_ideal=z_fault_ideal,
    )

check_conductor_limits

check_conductor_limits(
    network: Network,
    fault: str,
    t_k_s: Optional[float] = None,
    *,
    kappa: Optional[float] = None,
    r_to_x: Optional[float] = None,
    n_factor: Optional[float] = None,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
) -> pl.DataFrame

Check every grounding branch against its adiabatic thermal limit.

For the given fault the RMS shield current of every branch (from the most recent :func:groundinsight.run_fault) is converted into the thermally equivalent short-time current I_th = I_ac_rms * sqrt(m + n) (IEC 60909-0) and compared against the admissible adiabatic current I_adm = k * S / sqrt(t_k) (IEC 60949) of the branch conductor. A branch is checked only if its :class:BranchType carries both conductor_material and cross_section_mm2; the others are reported with within_limit = None.

.. note:: The thermal data is opt-in. A network that declares none of it still solves and is still reported here — every branch appears with its currents (I_s_rms_A, i_p_A, I_th_A) and only the judgement columns are None. Declaring half of it (a material without a cross-section or the reverse) is the one case that is announced, with an InputWarning (THERMAL_DATA_INCOMPLETE), because such a row is indistinguishable from a passing one at a glance.

.. note:: The 0 Hz bin is taken out of I_th. ResultBranch.i_s is sqrt(sum_f |I(f)|^2) over every frequency of the study, and sqrt(m + n) already accounts for the DC content of the fault current through m. A network solved with a 0 Hz bin would therefore carry its direct current into I_th twice — measured on the audit case, [50 Hz] gave 1028 A and [0, 50 Hz] with 700 A of direct current gave 1255 A, none of which is physics. The direct current is reported in its own column I_dc_A instead (None when the study has no 0 Hz bin, which reads differently from a measured zero), and I_ac_rms_A carries the RMS the check is built on. A standing direct current is a real thermal load, but a continuous one: it belongs in the conductor's continuous rating, not in an adiabatic short-time check. Where a direct current is present the check says so with a ModelAssumptionWarning THERMAL_DC_EXCLUDED: if it flows during T_k it adds about I_dc**2 to I_th**2 and the reported check is unconservative (PH10).

All three IEC 60909 inputs — t_k_s, kappa and n_factor — can either be passed explicitly or be left to the network data:

  • t_k_s falls back to Fault.t_k_s,
  • n_factor falls back to Fault.n_factor (default 1.0),
  • kappa falls back to the current-weighted aggregation over the feeding sources' kappa / r_to_x, see :func:~groundinsight.analysis.shortcircuit.resolve_fault_sc_characteristics.

An explicit argument always wins over the stored value, so a study can override a single scenario without editing the network.

Parameters:

Name Type Description Default
network Network

A network that already has results for fault (call :func:run_fault first).

required
fault str

Name of the solved fault whose branch currents are checked.

required
t_k_s float

Fault duration T_k in seconds. Must be strictly positive. Defaults to Fault.t_k_s of the named fault.

None
kappa float

Peak factor kappa in (1, 2]. Mutually exclusive with r_to_x. If neither is given, kappa is resolved from the sources' IEC 60909 data.

None
r_to_x float

R/X ratio at the fault, converted to kappa internally. Mutually exclusive with kappa.

None
n_factor float

AC-decay heat factor n (IEC 60909-0). Defaults to Fault.n_factor, i.e. 1.0 (far-from-generator; I_k'' = I_k).

None
frequency float

System frequency in Hz used in the m factor. Defaults to the lowest positive frequency of network (usually 50), or 50.0. The former keywords fault_name, t_k, n and f are accepted as deprecated aliases of fault, t_k_s, n_factor and frequency.

None
aggregation (weighted, max)

Only relevant when kappa is resolved from the sources. "weighted" reproduces the sum of the individual source peaks exactly; "max" takes the largest source kappa and is conservative. Ignored when kappa or r_to_x is given.

'weighted'

Returns:

Type Description
DataFrame

One row per branch with the columns branch_name, I_s_rms_A, i_p_A, kappa, m, n, t_k_s, I_th_factor, I_th_A, material, cross_section_mm2, k, I_admissible_A, utilization (I_th / I_adm) and within_limit (bool or None when the branch has no thermal parameters), plus I_dc_A and I_ac_rms_A (see the note on the DC bin below). i_p_A = kappa * sqrt(2) * I_ac_rms is the peak current of that branch and is the input for a later electrodynamic-force check.

Raises:

Type Description
ValueError

If t_k_s is neither given nor stored and positive, if both kappa and r_to_x are given, if kappa can be resolved from neither the arguments nor the sources, or if network has no results for fault. Also if the stored result does not cover every branch of the network -- an incomplete result would silently report the missing branches as free of violations. Re-run :func:groundinsight.run_fault in that case.

Warns:

Type Description
InputWarning

THERMAL_DATA_INCOMPLETE for branches whose type declares only one of material and cross-section (their rows stay unassessed), and SC_DATA_INCOMPLETE from :func:resolve_fault_sc_characteristics.

ModelAssumptionWarning

THERMAL_DC_EXCLUDED (see below), and SC_KAPPA_MIXED from :func:resolve_fault_sc_characteristics.

Examples:

Without thermal data on the branch types every branch is reported with its currents, and the judgement is None:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> frame = gi.check_conductor_limits(net, "fault", t_k_s=0.5, kappa=1.8)
>>> [(row["branch_name"], round(row["I_s_rms_A"], 2), row["within_limit"])
...  for row in frame.iter_rows(named=True)]
[('b12', 84.11, None), ('b23', 84.11, None)]
Source code in src/groundinsight/analysis/thermal.py
@renamed_parameters(fault_name="fault", t_k="t_k_s", n="n_factor", f="frequency")
def check_conductor_limits(
    network: Network,
    fault: str,
    t_k_s: Optional[float] = None,
    *,
    kappa: Optional[float] = None,
    r_to_x: Optional[float] = None,
    n_factor: Optional[float] = None,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
) -> pl.DataFrame:
    """
    Check every grounding branch against its adiabatic thermal limit.

    For the given fault the RMS shield current of every branch (from the
    most recent :func:`groundinsight.run_fault`) is converted into the
    thermally equivalent short-time current ``I_th = I_ac_rms * sqrt(m + n)``
    (IEC 60909-0) and compared against the admissible adiabatic current
    ``I_adm = k * S / sqrt(t_k)`` (IEC 60949) of the branch conductor. A
    branch is checked only if its :class:`BranchType` carries both
    ``conductor_material`` and ``cross_section_mm2``; the others are
    reported with ``within_limit = None``.

    .. note::
       The thermal data is **opt-in**. A network that declares none of it
       still solves and is still reported here — every branch appears with
       its currents (``I_s_rms_A``, ``i_p_A``, ``I_th_A``) and only the
       judgement columns are ``None``. Declaring *half* of it
       (a material without a cross-section or the reverse) is the one case
       that is announced, with an ``InputWarning``
       (``THERMAL_DATA_INCOMPLETE``), because such a row is
       indistinguishable from a passing one at a glance.

    .. note::
       **The 0 Hz bin is taken out of** ``I_th``. ``ResultBranch.i_s`` is
       ``sqrt(sum_f |I(f)|^2)`` over every frequency of the study, and
       ``sqrt(m + n)`` already accounts for the DC content of the fault
       current through ``m``. A network solved with a 0 Hz bin would
       therefore carry its direct current into ``I_th`` twice — measured on
       the audit case, ``[50 Hz]`` gave 1028 A and ``[0, 50 Hz]`` with 700 A
       of direct current gave 1255 A, none of which is physics. The direct
       current is reported in its own column ``I_dc_A`` instead
       (``None`` when the study has no 0 Hz bin, which reads differently
       from a measured zero), and ``I_ac_rms_A`` carries the RMS the check
       is built on. A standing direct current is a real thermal load, but a
       continuous one: it belongs in the conductor's continuous rating, not
       in an adiabatic short-time check. Where a direct current is present
       the check says so with a ``ModelAssumptionWarning``
       ``THERMAL_DC_EXCLUDED``: if it flows *during* ``T_k`` it adds about
       ``I_dc**2`` to ``I_th**2`` and the reported check is unconservative
       (PH10).

    All three IEC 60909 inputs — ``t_k_s``, ``kappa`` and ``n_factor`` — can
    either be passed explicitly or be left to the network data:

    * ``t_k_s`` falls back to ``Fault.t_k_s``,
    * ``n_factor`` falls back to ``Fault.n_factor`` (default ``1.0``),
    * ``kappa`` falls back to the current-weighted aggregation over the
      feeding sources' ``kappa`` / ``r_to_x``, see
      :func:`~groundinsight.analysis.shortcircuit.resolve_fault_sc_characteristics`.

    An explicit argument always wins over the stored value, so a study can
    override a single scenario without editing the network.

    Parameters
    ----------
    network : Network
        A network that already has results for ``fault`` (call
        :func:`run_fault` first).
    fault : str
        Name of the solved fault whose branch currents are checked.
    t_k_s : float, optional
        Fault duration ``T_k`` in seconds. Must be strictly positive.
        Defaults to ``Fault.t_k_s`` of the named fault.
    kappa : float, optional
        Peak factor ``kappa`` in ``(1, 2]``. Mutually exclusive with
        ``r_to_x``. If neither is given, ``kappa`` is resolved from the
        sources' IEC 60909 data.
    r_to_x : float, optional
        ``R/X`` ratio at the fault, converted to ``kappa`` internally.
        Mutually exclusive with ``kappa``.
    n_factor : float, optional
        AC-decay heat factor ``n`` (IEC 60909-0). Defaults to
        ``Fault.n_factor``, i.e. ``1.0`` (far-from-generator;
        ``I_k'' = I_k``).
    frequency : float, optional
        System frequency in Hz used in the ``m`` factor. Defaults to the
        lowest positive frequency of ``network`` (usually 50), or ``50.0``.
        The former keywords ``fault_name``, ``t_k``, ``n`` and ``f`` are
        accepted as deprecated aliases of ``fault``, ``t_k_s``,
        ``n_factor`` and ``frequency``.
    aggregation : {'weighted', 'max'}, default 'weighted'
        Only relevant when ``kappa`` is resolved from the sources.
        ``"weighted"`` reproduces the sum of the individual source peaks
        exactly; ``"max"`` takes the largest source ``kappa`` and is
        conservative. Ignored when ``kappa`` or ``r_to_x`` is given.

    Returns
    -------
    polars.DataFrame
        One row per branch with the columns ``branch_name``,
        ``I_s_rms_A``, ``i_p_A``, ``kappa``, ``m``, ``n``, ``t_k_s``,
        ``I_th_factor``, ``I_th_A``, ``material``, ``cross_section_mm2``,
        ``k``, ``I_admissible_A``, ``utilization`` (``I_th / I_adm``) and
        ``within_limit`` (``bool`` or ``None`` when the branch has no
        thermal parameters), plus ``I_dc_A`` and ``I_ac_rms_A`` (see the
        note on the DC bin below). ``i_p_A = kappa * sqrt(2) * I_ac_rms`` is
        the peak current of that branch and is the input for a later
        electrodynamic-force check.

    Raises
    ------
    ValueError
        If ``t_k_s`` is neither given nor stored and positive, if both
        ``kappa`` and ``r_to_x`` are given, if ``kappa`` can be resolved
        from neither the arguments nor the sources, or if ``network`` has
        no results for ``fault``. Also if the stored result does not
        cover every branch of the network -- an incomplete result would
        silently report the missing branches as free of violations. Re-run
        :func:`groundinsight.run_fault` in that case.

    Warns
    -----
    InputWarning
        ``THERMAL_DATA_INCOMPLETE`` for branches whose type declares only one
        of material and cross-section (their rows stay unassessed), and
        ``SC_DATA_INCOMPLETE`` from :func:`resolve_fault_sc_characteristics`.
    ModelAssumptionWarning
        ``THERMAL_DC_EXCLUDED`` (see below), and ``SC_KAPPA_MIXED`` from
        :func:`resolve_fault_sc_characteristics`.

    Examples
    --------
    Without thermal data on the branch types every branch is reported with its
    currents, and the judgement is ``None``:

    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> net = build_minimal()
    >>> _ = gi.run_fault(net, "fault")
    >>> frame = gi.check_conductor_limits(net, "fault", t_k_s=0.5, kappa=1.8)
    >>> [(row["branch_name"], round(row["I_s_rms_A"], 2), row["within_limit"])
    ...  for row in frame.iter_rows(named=True)]
    [('b12', 84.11, None), ('b23', 84.11, None)]
    """
    sc = _resolve_sc_inputs(
        network, fault, t_k_s, kappa, r_to_x, n_factor, frequency, aggregation
    )
    t_k, kappa, m, n, i_th_factor = (
        sc.t_k, sc.kappa, sc.m, sc.n, sc.i_th_factor
    )

    result = network.results[fault]
    # ``compute_branch_currents`` emits a row for *every* branch, including
    # inactive and open ones, so any missing name means the stored result is
    # stale or half-built. See _require_complete_results.
    _require_complete_results(
        fault,
        list(network.branches),
        [rb.name for rb in result.branches],
        "branch",
    )
    has_dc_bin = any(float(x) == 0.0 for x in network.frequencies)
    rows: List[Dict[str, Any]] = []
    incomplete: List[Tuple[str, str]] = []
    for result_branch in result.branches:
        name = result_branch.name
        i_s_rms = float(result_branch.i_s)
        i_dc, i_ac_rms = _split_dc(
            i_s_rms, getattr(result_branch, "i_s_freq", None), has_dc_bin
        )
        i_th = thermal_equivalent_current(i_ac_rms, m, n)

        branch = network.branches.get(name)
        material = None
        cross_section = None
        k_val = None
        i_adm = None
        utilization = None
        within = None
        if branch is not None:
            btype = branch.type
            material = getattr(btype, "conductor_material", None)
            cross_section = getattr(btype, "cross_section_mm2", None)
            if material is not None and cross_section is not None:
                k_val = iec60949_k(
                    material,
                    theta_initial_C=getattr(btype, "theta_initial_C", 20.0),
                    theta_final_C=getattr(btype, "theta_final_C", None),
                )
                i_adm = admissible_short_circuit_current(k_val, cross_section, t_k)
                utilization = i_th / i_adm if i_adm > 0 else None
                within = bool(i_th <= i_adm)
            elif material is not None:
                incomplete.append((name, "cross_section_mm2"))
            elif cross_section is not None:
                incomplete.append((name, "conductor_material"))

        rows.append(
            {
                "branch_name": name,
                "I_s_rms_A": i_s_rms,
                "I_dc_A": i_dc,
                "I_ac_rms_A": float(i_ac_rms),
                "i_p_A": peak_short_circuit_current(i_ac_rms, kappa),
                "kappa": float(kappa),
                "m": float(m),
                "n": float(n),
                "t_k_s": float(t_k),
                "I_th_factor": float(i_th_factor),
                "I_th_A": float(i_th),
                "material": material,
                "cross_section_mm2": cross_section,
                "k": k_val,
                "I_admissible_A": i_adm,
                "utilization": utilization,
                "within_limit": within,
            }
        )

    _warn_half_declared(incomplete, fault, "branch(es)", "branch")
    _warn_dc_excluded(rows, fault, "branch_name", "branch")

    violations = [r["branch_name"] for r in rows if r["within_limit"] is False]
    if violations:
        logger.warning(
            "Thermal limit exceeded on %d branch(es) for fault '%s' "
            "(t_k=%.3g s, kappa=%.3f): %s",
            len(violations), fault, t_k, kappa, violations,
        )

    return pl.DataFrame(rows, schema=_BRANCH_SCHEMA)

check_node_limits

check_node_limits(
    network: Network,
    fault: str,
    t_k_s: Optional[float] = None,
    *,
    kappa: Optional[float] = None,
    r_to_x: Optional[float] = None,
    n_factor: Optional[float] = None,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
    elements: Sequence[str] = (
        "earthing_conductor",
        "electrode",
    ),
) -> pl.DataFrame

Check every bus against the adiabatic thermal limits of its grounding.

The node-side counterpart of :func:check_conductor_limits. Where the branch check assesses the shield / earth wire between buses, this one assesses the two elements at a bus, which EN 50522 / IEC 61936-1 keep strictly apart because they carry different currents:

earthing_conductor The earthing conductor (Erdungsleiter): the lumped connection that brings the earth-fault current from the installation into the grounding system. It carries the full injected current ResultBus.i_inj — at a source bus the source infeed, at the fault bus the total fault current — and is therefore the more heavily stressed of the two.

electrode The earth electrode (Erder): the buried part, which only carries the share actually dissipated into the soil at this bus, ResultBus.ia = u_EPR / Z_B. In a well-meshed system that is a small fraction of the injection, so sizing the electrode for the full fault current is wasteful — and sizing the earthing conductor for the electrode current is dangerous.

Both are reported separately, one row each, in a long-format frame.

An element is assessed only if its :class:BusType carries both the *_material and the *_cross_section_mm2 field of that prefix; otherwise the row is reported with within_limit = None.

.. note:: The thermal data is opt-in. A network that declares none of it still solves and is still reported here — every active bus appears with its currents and only the judgement columns are None. Declaring half of it (a material without a cross-section or the reverse) is the one case that is announced, with an InputWarning (THERMAL_DATA_INCOMPLETE), because such a row is indistinguishable from a passing one at a glance.

.. note:: The 0 Hz bin is taken out of I_th, exactly as in :func:check_conductor_limits: ResultBus.i_inj and ResultBus.ia are RMS values over every frequency of the study, and sqrt(m + n) already carries the DC content through m, so a study with a 0 Hz bin counted its direct current twice. It is reported in I_dc_A instead (None without a 0 Hz bin), and I_ac_rms_A is what I_th and i_p are built on. Where a direct current is present the same ModelAssumptionWarning THERMAL_DC_EXCLUDED is raised as in :func:check_conductor_limits (PH10).

Parameters:

Name Type Description Default
network Network

A network that already has results for fault (call :func:run_fault first).

required
fault str

Name of the solved fault whose bus currents are checked.

required
t_k_s float

Fault duration T_k in seconds. Defaults to Fault.t_k_s.

None
kappa float

Peak factor kappa in (1, 2]. Mutually exclusive with r_to_x. Resolved from the sources when neither is given.

None
r_to_x float

R/X ratio at the fault, converted to kappa internally. Mutually exclusive with kappa.

None
n_factor float

AC-decay heat factor n (IEC 60909-0). Defaults to Fault.n_factor, i.e. 1.0.

None
frequency float

System frequency in Hz used in the m factor. Defaults to the lowest positive frequency of network, or 50.0. The former keywords fault_name, t_k, n and f are accepted as deprecated aliases of fault, t_k_s, n_factor and frequency.

None
aggregation (weighted, max)

Only relevant when kappa is resolved from the sources; see :func:check_conductor_limits.

'weighted'
elements sequence of str

Which of the two elements to report. Pass a single-element sequence to restrict the frame.

``('earthing_conductor', 'electrode')``

Returns:

Type Description
DataFrame

Long format, one row per bus and requested element, with the columns bus_name, element, I_rms_A (the bus current before the split), current_split, I_conductor_A, i_p_A, kappa, m, n, t_k_s, I_th_factor, I_th_A, I_dc_A, I_ac_rms_A, material, cross_section_mm2, k, I_admissible_A, utilization and within_limit. within_limit is None where the BusType declares no material / cross-section for that element — the current columns are still filled, so an undimensioned bus shows what it would have to carry.

Raises:

Type Description
ValueError

For an unknown entry in elements, and for the same conditions as :func:check_conductor_limits (no results, missing t_k_s, unresolvable kappa, both kappa and r_to_x given, or a stored result that does not cover every active bus).

Warns:

Type Description
InputWarning

THERMAL_DATA_INCOMPLETE for buses whose type declares only one of material and cross-section for an element (those rows stay unassessed), and SC_DATA_INCOMPLETE from :func:resolve_fault_sc_characteristics.

ModelAssumptionWarning

THERMAL_DC_EXCLUDED and SC_KAPPA_MIXED, as for :func:check_conductor_limits.

Notes

Current split. Each element carries a free factor current_split in (0, 1] (BusType.earthing_conductor_current_split / BusType.electrode_current_split), applied as I_conductor = I_rms * current_split. It expresses how the bus current divides between physically parallel paths that the nodal model lumps into one:

  • 1.0 (default) — one conductor / one electrode carries everything.
  • 1/N — N equal parallel paths, e.g. 0.25 for four down-conductors from a substation steelwork to the grid.
  • 0.5 — a ring electrode fed at a single point: the current splits into the two halves of the ring.
  • any IEEE Std 80 style split / division factor, entered directly.

The factor is deliberately not derived automatically: the split depends on the physical arrangement inside the substation, which the nodal grounding model does not resolve. Values above 1 are rejected at the model level — more current than the bus carries is an error, not a split.

Superposition. Identical to the branch check: the frequency-domain solve superposes the linear AC RMS currents, and the non-linear IEC 60909 factors kappa / m are applied once to the aggregate. i_p and I_th are never superposed directly.

A bus that is both the fault bus and the only source bus gets i_inj = 0: the current never enters the grounding system, it circulates in the phase conductor. That is physically correct and not a missing value.

Results computed before ResultBus.i_inj existed default to 0 for the injection. Re-run :func:run_fault if an earthing-conductor row reads I_rms_A = 0 at a bus that should be carrying current.

Examples:

The electrode currents of the minimal network; without thermal data on the bus type the judgement is None:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> _ = gi.run_fault(net, "fault")
>>> frame = gi.check_node_limits(net, "fault", t_k_s=0.5, kappa=1.8,
...                              elements=["electrode"])
>>> [(row["bus_name"], round(row["I_rms_A"], 2), row["within_limit"])
...  for row in frame.iter_rows(named=True)]
[('bus1', 18.03, None), ('bus2', 0.0, None), ('bus3', 18.03, None)]
Source code in src/groundinsight/analysis/thermal.py
@renamed_parameters(fault_name="fault", t_k="t_k_s", n="n_factor", f="frequency")
def check_node_limits(
    network: Network,
    fault: str,
    t_k_s: Optional[float] = None,
    *,
    kappa: Optional[float] = None,
    r_to_x: Optional[float] = None,
    n_factor: Optional[float] = None,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
    elements: Sequence[str] = ("earthing_conductor", "electrode"),
) -> pl.DataFrame:
    """
    Check every bus against the adiabatic thermal limits of its grounding.

    The node-side counterpart of :func:`check_conductor_limits`. Where the
    branch check assesses the shield / earth wire *between* buses, this one
    assesses the two elements *at* a bus, which EN 50522 / IEC 61936-1 keep
    strictly apart because they carry different currents:

    ``earthing_conductor``
        The **earthing conductor** (*Erdungsleiter*): the lumped connection
        that brings the earth-fault current from the installation into the
        grounding system. It carries the full injected current
        ``ResultBus.i_inj`` — at a source bus the source infeed, at the
        fault bus the total fault current — and is therefore the more
        heavily stressed of the two.

    ``electrode``
        The **earth electrode** (*Erder*): the buried part, which only
        carries the share actually dissipated into the soil at this bus,
        ``ResultBus.ia = u_EPR / Z_B``. In a well-meshed system that is a
        small fraction of the injection, so sizing the electrode for the
        full fault current is wasteful — and sizing the earthing conductor
        for the electrode current is dangerous.

    Both are reported separately, one row each, in a long-format frame.

    An element is assessed only if its :class:`BusType` carries both the
    ``*_material`` and the ``*_cross_section_mm2`` field of that prefix;
    otherwise the row is reported with ``within_limit = None``.

    .. note::
       The thermal data is **opt-in**. A network that declares none of it
       still solves and is still reported here — every active bus appears
       with its currents and only the judgement columns are ``None``.
       Declaring *half* of it (a material without a cross-section or the
       reverse) is the one case that is announced, with an ``InputWarning``
       (``THERMAL_DATA_INCOMPLETE``), because such a row is
       indistinguishable from a passing one at a glance.

    .. note::
       **The 0 Hz bin is taken out of** ``I_th``, exactly as in
       :func:`check_conductor_limits`: ``ResultBus.i_inj`` and
       ``ResultBus.ia`` are RMS values over every frequency of the study,
       and ``sqrt(m + n)`` already carries the DC content through ``m``, so
       a study with a 0 Hz bin counted its direct current twice. It is
       reported in ``I_dc_A`` instead (``None`` without a 0 Hz bin), and
       ``I_ac_rms_A`` is what ``I_th`` and ``i_p`` are built on. Where a
       direct current is present the same ``ModelAssumptionWarning``
       ``THERMAL_DC_EXCLUDED`` is raised as in
       :func:`check_conductor_limits` (PH10).

    Parameters
    ----------
    network : Network
        A network that already has results for ``fault`` (call
        :func:`run_fault` first).
    fault : str
        Name of the solved fault whose bus currents are checked.
    t_k_s : float, optional
        Fault duration ``T_k`` in seconds. Defaults to ``Fault.t_k_s``.
    kappa : float, optional
        Peak factor ``kappa`` in ``(1, 2]``. Mutually exclusive with
        ``r_to_x``. Resolved from the sources when neither is given.
    r_to_x : float, optional
        ``R/X`` ratio at the fault, converted to ``kappa`` internally.
        Mutually exclusive with ``kappa``.
    n_factor : float, optional
        AC-decay heat factor ``n`` (IEC 60909-0). Defaults to
        ``Fault.n_factor``, i.e. ``1.0``.
    frequency : float, optional
        System frequency in Hz used in the ``m`` factor. Defaults to the
        lowest positive frequency of ``network``, or ``50.0``. The former
        keywords ``fault_name``, ``t_k``, ``n`` and ``f`` are accepted as
        deprecated aliases of ``fault``, ``t_k_s``, ``n_factor`` and
        ``frequency``.
    aggregation : {'weighted', 'max'}, default 'weighted'
        Only relevant when ``kappa`` is resolved from the sources; see
        :func:`check_conductor_limits`.
    elements : sequence of str, default ``('earthing_conductor', 'electrode')``
        Which of the two elements to report. Pass a single-element
        sequence to restrict the frame.

    Returns
    -------
    polars.DataFrame
        Long format, one row per bus and requested element, with the
        columns ``bus_name``, ``element``, ``I_rms_A`` (the bus current
        before the split), ``current_split``, ``I_conductor_A``,
        ``i_p_A``, ``kappa``, ``m``, ``n``, ``t_k_s``, ``I_th_factor``,
        ``I_th_A``, ``I_dc_A``, ``I_ac_rms_A``, ``material``,
        ``cross_section_mm2``, ``k``,
        ``I_admissible_A``, ``utilization`` and ``within_limit``.
        ``within_limit`` is ``None`` where the ``BusType`` declares no
        material / cross-section for that element — the current columns
        are still filled, so an undimensioned bus shows what it would have
        to carry.

    Raises
    ------
    ValueError
        For an unknown entry in ``elements``, and for the same conditions
        as :func:`check_conductor_limits` (no results, missing ``t_k_s``,
        unresolvable ``kappa``, both ``kappa`` and ``r_to_x`` given, or a
        stored result that does not cover every *active* bus).

    Warns
    -----
    InputWarning
        ``THERMAL_DATA_INCOMPLETE`` for buses whose type declares only one of
        material and cross-section for an element (those rows stay
        unassessed), and ``SC_DATA_INCOMPLETE`` from
        :func:`resolve_fault_sc_characteristics`.
    ModelAssumptionWarning
        ``THERMAL_DC_EXCLUDED`` and ``SC_KAPPA_MIXED``, as for
        :func:`check_conductor_limits`.

    Notes
    -----
    **Current split.** Each element carries a free factor ``current_split``
    in ``(0, 1]`` (``BusType.earthing_conductor_current_split`` /
    ``BusType.electrode_current_split``), applied as
    ``I_conductor = I_rms * current_split``. It expresses how the bus
    current divides between physically parallel paths that the nodal model
    lumps into one:

    * ``1.0`` (default) — one conductor / one electrode carries everything.
    * ``1/N`` — ``N`` equal parallel paths, e.g. ``0.25`` for four
      down-conductors from a substation steelwork to the grid.
    * ``0.5`` — a ring electrode fed at a single point: the current splits
      into the two halves of the ring.
    * any IEEE Std 80 style split / division factor, entered directly.

    The factor is deliberately *not* derived automatically: the split
    depends on the physical arrangement inside the substation, which the
    nodal grounding model does not resolve. Values above ``1`` are rejected
    at the model level — more current than the bus carries is an error, not
    a split.

    **Superposition.** Identical to the branch check: the frequency-domain
    solve superposes the *linear* AC RMS currents, and the *non-linear*
    IEC 60909 factors ``kappa`` / ``m`` are applied once to the aggregate.
    ``i_p`` and ``I_th`` are never superposed directly.

    A bus that is *both* the fault bus and the only source bus gets
    ``i_inj = 0``: the current never enters the grounding system, it
    circulates in the phase conductor. That is physically correct and not
    a missing value.

    Results computed before ``ResultBus.i_inj`` existed default to ``0``
    for the injection. Re-run :func:`run_fault` if an earthing-conductor
    row reads ``I_rms_A = 0`` at a bus that should be carrying current.

    Examples
    --------
    The electrode currents of the minimal network; without thermal data on the
    bus type the judgement is ``None``:

    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> net = build_minimal()
    >>> _ = gi.run_fault(net, "fault")
    >>> frame = gi.check_node_limits(net, "fault", t_k_s=0.5, kappa=1.8,
    ...                              elements=["electrode"])
    >>> [(row["bus_name"], round(row["I_rms_A"], 2), row["within_limit"])
    ...  for row in frame.iter_rows(named=True)]
    [('bus1', 18.03, None), ('bus2', 0.0, None), ('bus3', 18.03, None)]
    """
    unknown = [e for e in elements if e not in _NODE_ELEMENTS]
    if unknown:
        raise ValueError(
            f"Unknown node element(s) {unknown}. Known elements: "
            f"{sorted(_NODE_ELEMENTS)}."
        )

    sc = _resolve_sc_inputs(
        network, fault, t_k_s, kappa, r_to_x, n_factor, frequency, aggregation
    )

    result = network.results[fault]
    # ``solve_network`` emits a row for every *active* bus (inactive ones are
    # removed from the nodal system and carry no EPR), so the expectation is
    # the set of active buses. See _require_complete_results.
    _require_complete_results(
        fault,
        [name for name, bus in network.buses.items() if bus.active],
        [rb.name for rb in result.buses],
        "bus",
    )
    has_dc_bin = any(float(x) == 0.0 for x in network.frequencies)
    rows: List[Dict[str, Any]] = []
    incomplete: List[Tuple[str, str]] = []
    for result_bus in result.buses:
        name = result_bus.name
        bus = network.buses.get(name)
        btype = getattr(bus, "type", None)

        for element in elements:
            spec = _NODE_ELEMENTS[element]
            prefix = spec["prefix"]

            i_rms = float(getattr(result_bus, spec["current_attr"], 0.0) or 0.0)

            split = 1.0
            material = None
            cross_section = None
            k_val = None
            i_adm = None
            utilization = None
            within = None
            if btype is not None:
                split = float(
                    getattr(btype, f"{prefix}current_split", 1.0) or 1.0
                )
                material = getattr(btype, f"{prefix}material", None)
                cross_section = getattr(btype, f"{prefix}cross_section_mm2", None)

            i_conductor = i_rms * split
            i_dc, i_ac_conductor = _split_dc(
                i_conductor,
                {
                    freq: value * split
                    for freq, value in (
                        getattr(result_bus, spec["current_attr"] + "_freq", None)
                        or {}
                    ).items()
                },
                has_dc_bin,
            )
            i_th = thermal_equivalent_current(i_ac_conductor, sc.m, sc.n)

            if material is not None and cross_section is not None:
                k_val = iec60949_k(
                    material,
                    theta_initial_C=getattr(btype, f"{prefix}theta_initial_C", 20.0),
                    theta_final_C=getattr(btype, f"{prefix}theta_final_C", None),
                )
                i_adm = admissible_short_circuit_current(
                    k_val, cross_section, sc.t_k
                )
                utilization = i_th / i_adm if i_adm > 0 else None
                within = bool(i_th <= i_adm)
            elif material is not None:
                incomplete.append((f"{name}/{element}", f"{prefix}cross_section_mm2"))
            elif cross_section is not None:
                incomplete.append((f"{name}/{element}", f"{prefix}material"))

            rows.append(
                {
                    "bus_name": name,
                    "element": element,
                    "I_rms_A": i_rms,
                    "current_split": split,
                    "I_conductor_A": i_conductor,
                    "I_dc_A": i_dc,
                    "I_ac_rms_A": float(i_ac_conductor),
                    "i_p_A": peak_short_circuit_current(i_ac_conductor, sc.kappa),
                    "kappa": sc.kappa,
                    "m": sc.m,
                    "n": sc.n,
                    "t_k_s": sc.t_k,
                    "I_th_factor": sc.i_th_factor,
                    "I_th_A": float(i_th),
                    "material": material,
                    "cross_section_mm2": cross_section,
                    "k": k_val,
                    "I_admissible_A": i_adm,
                    "utilization": utilization,
                    "within_limit": within,
                }
            )

    _warn_half_declared(incomplete, fault, "node element(s)", "bus")
    _warn_dc_excluded(rows, fault, "bus_name", "bus")

    violations = [
        f"{r['bus_name']}/{r['element']}" for r in rows if r["within_limit"] is False
    ]
    if violations:
        logger.warning(
            "Thermal limit exceeded on %d node element(s) for fault '%s' "
            "(t_k=%.3g s, kappa=%.3f): %s",
            len(violations), fault, sc.t_k, sc.kappa, violations,
        )

    return pl.DataFrame(rows, schema=_NODE_SCHEMA)

classify

classify(
    frame: DataFrame,
    value: str,
    edges: Sequence[float],
    *,
    labels: Optional[Sequence[str]] = None,
    name: str = "class",
) -> pl.DataFrame

Add a class column by binning a numeric column at the given edges.

edges are the interior boundaries: n edges make n + 1 classes. Bins are closed on the right, so a value exactly on an edge falls into the lower class -- the conservative reading when the edge is a limit.

Parameters:

Name Type Description Default
frame DataFrame

Frame to extend.

required
value str

Numeric column to classify.

required
edges sequence of float

Strictly increasing interior boundaries, e.g. [80, 150] for the three bands "below 80", "80 to 150" and "above 150".

required
labels sequence of str

Names for the classes, len(edges) + 1 of them. Defaults to readable interval labels built from the edges.

None
name str

Name of the added column. Defaults to "class".

'class'

Returns:

Type Description
DataFrame

The input with one column added. Rows whose value is null or NaN get a null class rather than being forced into a band. Banded, a NaN would land in the highest class, because every NaN <= edge is false and the chain would fall through to the otherwise branch -- a failed sweep point would be reported as the worst case rather than as unassessed, and a study reading the top band as its violations would count it.

Raises:

Type Description
ValueError

If the column is missing or not numeric, if edges is empty or not strictly increasing, or if labels has the wrong length.

Examples:

>>> import polars as pl
>>> from groundinsight.analysis import classify
>>> frame = pl.DataFrame({"EPR_V": [12.0, 80.0, 450.0]})
>>> classify(frame, "EPR_V", [75.0, 300.0])["class"].to_list()
['<= 75', '75 - 300', '> 300']
Source code in src/groundinsight/analysis/statistics.py
def classify(
    frame: pl.DataFrame,
    value: str,
    edges: Sequence[float],
    *,
    labels: Optional[Sequence[str]] = None,
    name: str = "class",
) -> pl.DataFrame:
    """
    Add a class column by binning a numeric column at the given edges.

    ``edges`` are the interior boundaries: ``n`` edges make ``n + 1`` classes.
    Bins are closed on the right, so a value exactly on an edge falls into the
    lower class -- the conservative reading when the edge is a limit.

    Parameters
    ----------
    frame : pl.DataFrame
        Frame to extend.
    value : str
        Numeric column to classify.
    edges : sequence of float
        Strictly increasing interior boundaries, e.g. ``[80, 150]`` for the
        three bands "below 80", "80 to 150" and "above 150".
    labels : sequence of str, optional
        Names for the classes, ``len(edges) + 1`` of them. Defaults to readable
        interval labels built from the edges.
    name : str, optional
        Name of the added column. Defaults to ``"class"``.

    Returns
    -------
    pl.DataFrame
        The input with one column added. Rows whose value is null **or NaN**
        get a null class rather than being forced into a band. Banded, a NaN
        would land in the *highest* class, because every ``NaN <= edge`` is
        false and the chain would fall through to the ``otherwise`` branch --
        a failed sweep point would be reported as the worst case rather than
        as unassessed, and a study reading the top band as its violations
        would count it.

    Raises
    ------
    ValueError
        If the column is missing or not numeric, if ``edges`` is empty or not
        strictly increasing, or if ``labels`` has the wrong length.

    Examples
    --------
    >>> import polars as pl
    >>> from groundinsight.analysis import classify
    >>> frame = pl.DataFrame({"EPR_V": [12.0, 80.0, 450.0]})
    >>> classify(frame, "EPR_V", [75.0, 300.0])["class"].to_list()
    ['<= 75', '75 - 300', '> 300']
    """
    if value not in frame.columns:
        raise ValueError(
            f"Column '{value}' is not in the frame. Available: {frame.columns}."
        )
    if not frame.schema[value].is_numeric():
        raise ValueError(
            f"Column '{value}' has dtype {frame.schema[value]} and cannot be "
            f"binned numerically."
        )
    edges = [float(e) for e in edges]
    if not edges:
        raise ValueError(
            "classify needs at least one edge; with none there is only one "
            "class and nothing to decide."
        )
    if any(b <= a for a, b in pairwise(edges)):
        raise ValueError(
            f"Edges must be strictly increasing, got {edges}. Overlapping or "
            f"repeated edges would make the class assignment ambiguous."
        )

    if labels is None:
        labels = [f"<= {edges[0]:g}"]
        labels += [f"{a:g} - {b:g}" for a, b in pairwise(edges)]
        labels.append(f"> {edges[-1]:g}")
    labels = list(labels)
    if len(labels) != len(edges) + 1:
        raise ValueError(
            f"{len(edges)} edge(s) define {len(edges) + 1} classes, but "
            f"{len(labels)} label(s) were given."
        )

    unassessable = pl.col(value).is_null()
    if frame.schema[value].is_float():
        unassessable = unassessable | pl.col(value).is_nan()
    expression = pl.when(unassessable).then(None)
    # One label per edge; the last label is the class above every edge.
    for edge, label in zip(edges, labels[:-1], strict=True):
        expression = expression.when(pl.col(value) <= edge).then(pl.lit(label))
    expression = expression.otherwise(pl.lit(labels[-1]))
    return frame.with_columns(expression.alias(name))

evaluate_max_epr_under_k

evaluate_max_epr_under_k(
    network: Network,
    bus_names: List[str],
    k: KVector,
    *,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
) -> Dict[str, float]

Evaluate the RMS EPR at each selected bus for a given k vector.

For every name in bus_names the bus grounding impedance is overwritten with the rho-f linear form Z(rho, f) = k1*rho + (k2+jk3)*f + (k4+jk5)*rho*f — using the bus' own :attr:Bus.specific_earth_resistance for rho — and the bus is swept as the active fault. An existing fault at that bus is reused; otherwise a temporary one is created with fault_scalings (or 1.0 at every simulation frequency by default) and removed at the end. The original bus impedances, the temporary faults and the previous active_fault are restored in a finally block, so the network is left exactly as it was on entry.

Parameters:

Name Type Description Default
network Network

The simulation network. Sources, branches and the buses to be swept must already be configured; paths are not needed (see :func:~groundinsight.analysis.inverse_rho.find_max_rho_scaling).

required
bus_names list of str

Buses whose impedance is rewritten and which are swept as fault locations one by one. Must be non-empty and refer to buses in network.

required
k tuple of (float, float, float, float, float)

Real model parameters (k1, k2, k3, k4, k5).

required
fault_scalings dict of float to float

Frequency-resolved scalings used for any fault that has to be created on the fly (no pre-existing fault at the swept bus). Defaults to {f: 1.0} for every simulation frequency. Existing faults are reused unmodified.

None
run_fault_kwargs dict

Extra keyword arguments forwarded to :func:run_fault at every step.

None

Returns:

Type Description
dict of str to float

Mapping of each bus_name to its RMS EPR in volts at that bus when it is the active fault.

Raises:

Type Description
ValueError

If bus_names is empty, k does not have length 5, or any name is not in the network.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> eprs = gi.evaluate_max_epr_under_k(build_minimal(), ["bus3"],
...                                    (0.01, 0.0, 0.0, 0.0, 0.0))
>>> {bus: round(epr, 2) for bus, epr in eprs.items()}
{'bus3': 18.03}
Source code in src/groundinsight/analysis/inverse_rho_f.py
def evaluate_max_epr_under_k(
    network: Network,
    bus_names: List[str],
    k: KVector,
    *,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
) -> Dict[str, float]:
    """Evaluate the RMS EPR at each selected bus for a given ``k`` vector.

    For every name in ``bus_names`` the bus grounding impedance is
    overwritten with the rho-f linear form
    ``Z(rho, f) = k1*rho + (k2+jk3)*f + (k4+jk5)*rho*f`` — using the
    bus' own :attr:`Bus.specific_earth_resistance` for ``rho`` — and
    the bus is swept as the active fault. An existing fault at that bus
    is reused; otherwise a temporary one is created with
    ``fault_scalings`` (or ``1.0`` at every simulation frequency by
    default) and removed at the end. The original bus impedances, the
    temporary faults and the previous ``active_fault`` are restored in a
    ``finally`` block, so the network is left exactly as it was on entry.

    Parameters
    ----------
    network : Network
        The simulation network. Sources, branches and the buses to be swept
        must already be configured; paths are not needed (see
        :func:`~groundinsight.analysis.inverse_rho.find_max_rho_scaling`).
    bus_names : list of str
        Buses whose impedance is rewritten and which are swept as fault
        locations one by one. Must be non-empty and refer to buses in
        ``network``.
    k : tuple of (float, float, float, float, float)
        Real model parameters ``(k1, k2, k3, k4, k5)``.
    fault_scalings : dict of float to float, optional
        Frequency-resolved scalings used for any fault that has to be
        created on the fly (no pre-existing fault at the swept bus).
        Defaults to ``{f: 1.0}`` for every simulation frequency. Existing
        faults are reused unmodified.
    run_fault_kwargs : dict, optional
        Extra keyword arguments forwarded to :func:`run_fault` at every
        step.

    Returns
    -------
    dict of str to float
        Mapping of each ``bus_name`` to its RMS EPR in volts at that bus
        when it is the active fault.

    Raises
    ------
    ValueError
        If ``bus_names`` is empty, ``k`` does not have length 5, or any
        name is not in the network.

    Examples
    --------
    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> eprs = gi.evaluate_max_epr_under_k(build_minimal(), ["bus3"],
    ...                                    (0.01, 0.0, 0.0, 0.0, 0.0))
    >>> {bus: round(epr, 2) for bus, epr in eprs.items()}
    {'bus3': 18.03}
    """
    return _evaluate_max_epr_under_k(
        network,
        bus_names,
        k,
        fault_scalings=fault_scalings,
        run_fault_kwargs=run_fault_kwargs,
    )

final_temperature

final_temperature(material: str, covering: str) -> float

Look up a tabulated maximum final temperature theta_f.

Convenience accessor for :data:FINAL_TEMPERATURES, meant to be used when building a BranchType or BusType so that the source of the number stays visible in the model::

gi.BusType(..., electrode_theta_final_C=gi.final_temperature("Steel", "bare"))

Which standard the answer comes from depends on the covering: EN 50522 Table 2 for an uninsulated conductor, IEC 60364-5-54 Table 54.2 for an insulated one. The insulated caps are much lower, so the two must not be confused — hence one accessor over one catalogue rather than a per-source lookup the caller has to choose between.

Parameters:

Name Type Description Default
material str

One of the keys of :data:IEC60949_MATERIALS ("Cu", "Al", "Steel").

required
covering str

Covering / surface treatment key. Uninsulated: "bare", "tinned" (copper only) or "galvanized" (steel only). Insulated: "PVC", "XLPE" or "EPR". Only combinations that occur in practice are tabulated — there is no tinned aluminium and no galvanised copper — and "PE" is not tabulated at all.

required

Returns:

Type Description
float

Maximum permissible final temperature in °C.

Raises:

Type Description
ValueError

If the material or the material / covering combination is not tabulated. The message lists what is available — the table is intentionally incomplete rather than populated with unsourced values, since an over-estimated theta_f permits too much current.

See Also

CABLE_INSULATION_LIMITS : the insulated subset, on its own, when the conductor material is not known or not relevant.

Examples:

>>> final_temperature("Cu", "bare")
300.0
>>> final_temperature("Cu", "tinned")
150.0
>>> final_temperature("Cu", "PVC")
160.0
Source code in src/groundinsight/analysis/thermal.py
def final_temperature(material: str, covering: str) -> float:
    """
    Look up a tabulated maximum final temperature ``theta_f``.

    Convenience accessor for :data:`FINAL_TEMPERATURES`, meant to be used when
    *building* a ``BranchType`` or ``BusType`` so that the source of the
    number stays visible in the model::

        gi.BusType(..., electrode_theta_final_C=gi.final_temperature("Steel", "bare"))

    Which standard the answer comes from depends on the covering: EN 50522
    Table 2 for an uninsulated conductor, IEC 60364-5-54 Table 54.2 for an
    insulated one. The insulated caps are much lower, so the two must not be
    confused — hence one accessor over one catalogue rather than a per-source
    lookup the caller has to choose between.

    Parameters
    ----------
    material : str
        One of the keys of :data:`IEC60949_MATERIALS` (``"Cu"``, ``"Al"``,
        ``"Steel"``).
    covering : str
        Covering / surface treatment key. Uninsulated: ``"bare"``,
        ``"tinned"`` (copper only) or ``"galvanized"`` (steel only).
        Insulated: ``"PVC"``, ``"XLPE"`` or ``"EPR"``. Only combinations that
        occur in practice are tabulated — there is no tinned aluminium and no
        galvanised copper — and ``"PE"`` is not tabulated at all.

    Returns
    -------
    float
        Maximum permissible final temperature in °C.

    Raises
    ------
    ValueError
        If the material or the material / covering combination is not
        tabulated. The message lists what *is* available — the table is
        intentionally incomplete rather than populated with unsourced
        values, since an over-estimated ``theta_f`` permits too much
        current.

    See Also
    --------
    CABLE_INSULATION_LIMITS : the insulated subset, on its own, when the
        conductor material is not known or not relevant.

    Examples
    --------
    >>> final_temperature("Cu", "bare")
    300.0
    >>> final_temperature("Cu", "tinned")
    150.0
    >>> final_temperature("Cu", "PVC")
    160.0
    """
    if material not in FINAL_TEMPERATURES:
        raise ValueError(
            f"No tabulated final temperatures for material {material!r}. "
            f"Known materials: {sorted(FINAL_TEMPERATURES)}."
        )
    coverings = FINAL_TEMPERATURES[material]
    if covering not in coverings:
        raise ValueError(
            f"No tabulated final temperature for covering {covering!r} on "
            f"{material!r}. Tabulated coverings: {sorted(coverings)}. Add the "
            "value from EN 50522 Table 2 (uninsulated) or IEC 60364-5-54 "
            "Table 54.2 (insulated) to "
            "groundinsight.analysis.thermal.FINAL_TEMPERATURES, or pass "
            "theta_final_C explicitly."
        )
    return float(coverings[covering])

find_max_rho_f_scaling

find_max_rho_f_scaling(
    network: Network,
    bus_names: List[str],
    u_limit: float,
    k_ref: KVector,
    *,
    c_bounds: Tuple[float, float] = (0.001, 1000.0),
    tol_rel: float = 0.001,
    max_iter: int = 60,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    progress: Optional[
        Callable[[int, int, str], None]
    ] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]

Find the largest scaling factor c of a reference k-vector.

Performs a log-scale bisection on c so that k = c * k_ref yields a maximum RMS EPR (across all buses swept as faults) that is at or below u_limit. k_ref is typically obtained by fitting the rho-f model above to measured impedance points; this function answers how much head-room the network has around that characteristic.

Parameters:

Name Type Description Default
network Network

The simulation network. Buses, branches, sources and paths must already be configured.

required
bus_names list of str

Buses whose impedance is parameterised by k and which are swept as fault locations.

required
u_limit float

Upper bound on the RMS EPR (in volts) at any swept bus. Must be finite and strictly positive.

required
k_ref tuple of (float, float, float, float, float)

Reference 5-tuple (k1_ref, ..., k5_ref). Must have length 5 and not be the zero vector.

required
c_bounds tuple of (float, float)

Search interval for c. Finite, strictly positive, c_bounds[0] < c_bounds[1]. Defaults to (1e-3, 1e3).

(0.001, 1000.0)
tol_rel float

Bisection tolerance on the relative bracket width (c_hi - c_lo) / c_lo. Must be finite and strictly positive. Defaults to 1e-3.

0.001
max_iter int

Hard cap on bisection steps. Must be an int of at least 1. Defaults to 60.

60
fault_scalings dict of float to float

See :func:evaluate_max_epr_under_k.

None
run_fault_kwargs dict

Forwarded to :func:run_fault.

None
progress callable

progress(done, total, label), called after every bus solve of every trial factor (label "c = <factor>, bus <name>"). total is len(bus_names) times the trial factors the bracket and tolerance require; see :mod:groundinsight.progress.

None
should_cancel callable

Asked before every bus solve; a true answer raises :class:~groundinsight.progress.StudyCancelled, also in the middle of a bus sweep.

None

Returns:

Type Description
dict

Mapping with keys

  • "c_max" (float): a scaling factor whose swept maximum EPR was evaluated and found compatible with u_limit. It is the largest such factor only when "converged" is True.
  • "k_max" (tuple of float): c_max * k_ref.
  • "max_epr_rms_at_c_max" (float): maximum RMS EPR across all swept buses at c_max, in volts.
  • "epr_rms_per_bus_at_c_max" (dict of str to float): RMS EPR per swept bus at c_max.
  • "iterations" (int): number of bisection steps taken.
  • "converged" (bool): True iff the bracket was closed to within tol_rel. Check this before using c_max or k_max as a design value.
  • "status" (str): "converged", "bracket_within_tol_on_entry", "max_iter_reached" or "bracket_fully_admissible".
  • "c_bracket" (tuple of float): the interval provably containing the true maximum; (c_hi, inf) when the whole bracket was admissible.
  • "bracket_rel_width" (float): (c_hi - c_lo) / c_lo of that interval, comparable against tol_rel.

As in :func:~groundinsight.analysis.find_max_rho_scaling, iterations == 0 does not identify a case on its own; read "status".

Raises:

Type Description
ValueError

For invalid input -- u_limit, tol_rel, max_iter and c_bounds are checked for finiteness as well as range -- or if c = c_bounds[0] already violates the EPR limit, or if the model returns a non-finite EPR at some trial factor.

TypeError

If progress or should_cancel is not callable.

StudyCancelled

If should_cancel() returned true; the network is as found.

Notes

The monotonicity assumption. The bisection finds the crossing of max EPR(c) with u_limit and therefore presumes there is only one. Unlike :func:~groundinsight.analysis.find_max_rho_scaling, this search scales all five k and with them every term of the impedance, so at a single bus the whole impedance scales with c and monotonicity follows. In a coupled multi-bus network it does not follow: the swept maximum is a maximum over buses, each of which sees the others through the shields, and a chain resonance can in principle make it turn. That case has not been constructed, so treat it as unproven rather than as excluded -- if c_max looks implausible, sweep c explicitly with :func:evaluate_max_epr_under_k and look at the curve. The rho-only search has a pre-scan for exactly this (monotonicity_grid); here the same scan would cost a full bus sweep per point and is left to the caller.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> report = gi.find_max_rho_f_scaling(build_minimal(), ["bus3"], u_limit=10.0,
...                                    k_ref=(0.01, 0.0, 0.0, 0.0, 0.0))
>>> report["status"], report["max_epr_rms_at_c_max"] <= 10.0
('converged', True)
Source code in src/groundinsight/analysis/inverse_rho_f.py
def find_max_rho_f_scaling(
    network: Network,
    bus_names: List[str],
    u_limit: float,
    k_ref: KVector,
    *,
    c_bounds: Tuple[float, float] = (1e-3, 1e3),
    tol_rel: float = 1e-3,
    max_iter: int = 60,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    progress: Optional[Callable[[int, int, str], None]] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
    """Find the largest scaling factor ``c`` of a reference k-vector.

    Performs a log-scale bisection on ``c`` so that ``k = c * k_ref``
    yields a maximum RMS EPR (across all buses swept as faults) that is
    at or below ``u_limit``. ``k_ref`` is typically obtained by fitting
    the rho-f model above to measured impedance points; this function
    answers *how much head-room the network has around that
    characteristic*.

    Parameters
    ----------
    network : Network
        The simulation network. Buses, branches, sources and paths must
        already be configured.
    bus_names : list of str
        Buses whose impedance is parameterised by ``k`` *and* which are
        swept as fault locations.
    u_limit : float
        Upper bound on the RMS EPR (in volts) at any swept bus. Must be
        finite and strictly positive.
    k_ref : tuple of (float, float, float, float, float)
        Reference 5-tuple ``(k1_ref, ..., k5_ref)``. Must have length 5
        and not be the zero vector.
    c_bounds : tuple of (float, float), optional
        Search interval for ``c``. Finite, strictly positive,
        ``c_bounds[0] < c_bounds[1]``. Defaults to ``(1e-3, 1e3)``.
    tol_rel : float, optional
        Bisection tolerance on the relative bracket width
        ``(c_hi - c_lo) / c_lo``. Must be finite and strictly positive.
        Defaults to ``1e-3``.
    max_iter : int, optional
        Hard cap on bisection steps. Must be an ``int`` of at least 1.
        Defaults to ``60``.
    fault_scalings : dict of float to float, optional
        See :func:`evaluate_max_epr_under_k`.
    run_fault_kwargs : dict, optional
        Forwarded to :func:`run_fault`.
    progress : callable, optional
        ``progress(done, total, label)``, called after every bus solve of
        every trial factor (label ``"c = <factor>, bus <name>"``). ``total``
        is ``len(bus_names)`` times the trial factors the bracket and
        tolerance require; see :mod:`groundinsight.progress`.
    should_cancel : callable, optional
        Asked before every bus solve; a true answer raises
        :class:`~groundinsight.progress.StudyCancelled`, also in the middle
        of a bus sweep.

    Returns
    -------
    dict
        Mapping with keys

        - ``"c_max"`` (float): a scaling factor whose swept maximum EPR
          was evaluated and found compatible with ``u_limit``. It is the
          *largest* such factor only when ``"converged"`` is ``True``.
        - ``"k_max"`` (tuple of float): ``c_max * k_ref``.
        - ``"max_epr_rms_at_c_max"`` (float): maximum RMS EPR across all
          swept buses at ``c_max``, in volts.
        - ``"epr_rms_per_bus_at_c_max"`` (dict of str to float): RMS EPR
          per swept bus at ``c_max``.
        - ``"iterations"`` (int): number of bisection steps taken.
        - ``"converged"`` (bool): ``True`` iff the bracket was closed to
          within ``tol_rel``. Check this before using ``c_max`` or
          ``k_max`` as a design value.
        - ``"status"`` (str): ``"converged"``,
          ``"bracket_within_tol_on_entry"``, ``"max_iter_reached"`` or
          ``"bracket_fully_admissible"``.
        - ``"c_bracket"`` (tuple of float): the interval provably
          containing the true maximum; ``(c_hi, inf)`` when the whole
          bracket was admissible.
        - ``"bracket_rel_width"`` (float): ``(c_hi - c_lo) / c_lo`` of
          that interval, comparable against ``tol_rel``.

        As in :func:`~groundinsight.analysis.find_max_rho_scaling`,
        ``iterations == 0`` does not identify a case on its own; read
        ``"status"``.

    Raises
    ------
    ValueError
        For invalid input -- ``u_limit``, ``tol_rel``, ``max_iter`` and
        ``c_bounds`` are checked for finiteness as well as range -- or if
        ``c = c_bounds[0]`` already violates the EPR limit, or if the
        model returns a non-finite EPR at some trial factor.
    TypeError
        If ``progress`` or ``should_cancel`` is not callable.
    StudyCancelled
        If ``should_cancel()`` returned true; the network is as found.

    Notes
    -----
    **The monotonicity assumption.** The bisection finds *the* crossing of
    ``max EPR(c)`` with ``u_limit`` and therefore presumes there is only one.
    Unlike :func:`~groundinsight.analysis.find_max_rho_scaling`, this search
    scales all five ``k`` and with them every term of the impedance, so at a
    single bus the whole impedance scales with ``c`` and monotonicity follows.
    In a coupled multi-bus network it does **not** follow: the swept maximum
    is a maximum over buses, each of which sees the others through the
    shields, and a chain resonance can in principle make it turn. That case
    has not been constructed, so treat it as unproven rather than as excluded
    -- if ``c_max`` looks implausible, sweep ``c`` explicitly with
    :func:`evaluate_max_epr_under_k` and look at the curve. The rho-only
    search has a pre-scan for exactly this (``monotonicity_grid``); here the
    same scan would cost a full bus sweep per point and is left to the caller.

    Examples
    --------
    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> report = gi.find_max_rho_f_scaling(build_minimal(), ["bus3"], u_limit=10.0,
    ...                                    k_ref=(0.01, 0.0, 0.0, 0.0, 0.0))
    >>> report["status"], report["max_epr_rms_at_c_max"] <= 10.0
    ('converged', True)
    """
    validate_limit(u_limit, "u_limit")
    validate_tol_rel(tol_rel)
    validate_max_iter(max_iter)
    if not bus_names:
        raise ValueError("bus_names must not be empty.")
    if len(k_ref) != 5:
        raise ValueError(f"k_ref must be a 5-tuple, got length {len(k_ref)}.")
    if all(x == 0 for x in k_ref):
        raise ValueError("k_ref must not be the zero vector.")
    c_lo_init, c_hi_init = validate_c_bounds(c_bounds)
    # Both bracket ends, then the halvings that close the bracket: a fixed
    # count (see planned_steps), times one solve per swept bus.
    hooks = StudyHooks(
        "find_max_rho_f_scaling",
        len(bus_names) * (2 + planned_steps(c_lo_init, c_hi_init, tol_rel, max_iter)),
        progress,
        should_cancel,
    )

    last_epr_per_bus: Dict[str, Dict[str, float]] = {"value": {}}
    # A trial factor changes the grounding impedances of the swept buses and
    # nothing else; every fault location keeps its injection vectors and its
    # stamp pattern from the first full sweep. Later trials are re-solved on
    # those (P4, see analysis._session) -- bit for bit the EPRs a full sweep
    # computes. A bus whose session cannot answer a trial is solved in full.
    sessions: Dict[str, Optional[BusImpedanceSession]] = {}
    # Per swept bus: does its session share the nodal matrix of the first
    # one? Decided once per set of sessions.
    sharing: Dict[str, bool] = {}

    def _session_eprs(k: KVector, label: str) -> Optional[Dict[str, float]]:
        """The EPR per swept bus from the sessions, or ``None`` for a full sweep."""
        if not sessions or any(sessions.get(b) is None for b in bus_names):
            return None
        frequencies = [float(f) for f in network.frequencies]
        impedances: Dict[str, np.ndarray] = {}
        for b in bus_names:
            rho = float(network.buses[b].specific_earth_resistance)
            impedances[b] = np.array(
                [complex(z.real, z.imag)
                 for z in (_z_rho_f(k, rho, f) for f in frequencies)],
                dtype=complex,
            )
        # Fault locations without a voltage-source loop share their nodal
        # matrix, so one factorisation per trial serves all of them.
        anchor = sessions[bus_names[0]]
        if not sharing:
            sharing.update(
                {b: sessions[b].same_matrix_as(anchor) for b in bus_names}
            )
        shared: Dict[int, Optional[list]] = {}

        def factors_for(b: str) -> Optional[list]:
            if not sharing[b]:
                return None
            if 0 not in shared:
                shared[0] = anchor.factorise(impedances)
            return shared[0]

        eprs: Dict[str, float] = {}
        for b in bus_names:
            hooks.checkpoint()
            epr = sessions[b].epr_rms(impedances, factors_for(b))
            if epr is None:
                epr = _evaluate_max_epr_under_k(
                    network, bus_names, k=k,
                    fault_scalings=fault_scalings,
                    run_fault_kwargs=run_fault_kwargs,
                    solve_buses=[b],
                )[b]
            eprs[b] = epr
            hooks.advance(f"{label}bus {b}")
        return eprs

    def _max_epr_at(c: float) -> float:
        k = tuple(c * x for x in k_ref)
        label = f"c = {c:.6g}, "
        eprs = _session_eprs(k, label)
        if eprs is None:
            sessions.clear()
            sharing.clear()
            eprs = _evaluate_max_epr_under_k(
                network, bus_names,
                k=k,
                fault_scalings=fault_scalings,
                run_fault_kwargs=run_fault_kwargs,
                hooks=hooks,
                label=label,
                sessions=sessions,
            )
        last_epr_per_bus["value"] = eprs
        epr = max(eprs.values()) if eprs else 0.0
        if not math.isfinite(epr):
            # Same reasoning as in ``inverse_rho``: a non-finite EPR makes
            # every comparison against u_limit False, so the bisection would
            # take the same turn at every step and reach the lower bracket
            # bound without ever raising.
            raise ValueError(
                f"The swept maximum EPR evaluated to {epr!r} for the scaling "
                f"factor c={c:g} (k = {tuple(c * x for x in k_ref)!r}). A "
                "non-finite EPR cannot be compared against u_limit -- every "
                "comparison would be False and the bisection would walk to "
                "the lower bracket bound without raising. Check the k-vector "
                "at that scale against the buses' specific_earth_resistance."
            )
        return epr

    epr_lo = _max_epr_at(c_lo_init)
    eprs_lo_snapshot: Dict[str, float] = dict(last_epr_per_bus["value"])
    if epr_lo > u_limit:
        raise ValueError(
            f"u_limit={u_limit:g} V is below the maximum EPR at "
            f"c={c_lo_init:g}: max EPR_RMS={epr_lo:g} V — no scaling "
            f"factor in the bracket {c_bounds!r} satisfies the constraint."
        )

    epr_hi = _max_epr_at(c_hi_init)
    iterations = 0
    if epr_hi <= u_limit:
        logger.info(
            "Bracket fully admissible: max EPR_RMS at c=%g is %g V <= "
            "u_limit=%g V. Consider widening c_bounds.",
            c_hi_init, epr_hi, u_limit,
        )
        c_max, epr_at = c_hi_init, epr_hi
        epr_per_bus_at = dict(last_epr_per_bus["value"])
        status = STATUS_BRACKET_FULLY_ADMISSIBLE
        c_lo, c_hi = c_lo_init, c_hi_init
    else:
        c_lo, c_hi = c_lo_init, c_hi_init
        while iterations < max_iter and (c_hi - c_lo) / c_lo > tol_rel:
            c_mid = math.sqrt(c_lo * c_hi)  # geometric mean -> log bisection
            epr_mid = _max_epr_at(c_mid)
            if epr_mid <= u_limit:
                c_lo, epr_lo = c_mid, epr_mid
                eprs_lo_snapshot = dict(last_epr_per_bus["value"])
            else:
                c_hi = c_mid
            iterations += 1
        c_max, epr_at = c_lo, epr_lo
        epr_per_bus_at = eprs_lo_snapshot
        status = classify(iterations, c_lo, c_hi, tol_rel)
        if status == STATUS_MAX_ITER_REACHED:
            logger.warning(
                "Bisection stopped at the step cap max_iter=%d without "
                "closing the bracket: c in [%g, %g], relative width %g > "
                "tol_rel=%g. c_max=%g is admissible but may be well below "
                "the true maximum.",
                max_iter, c_lo, c_hi, (c_hi - c_lo) / c_lo, tol_rel, c_lo,
            )

    # The invariant: the maximum of the per-bus EPRs at c_max is the reported
    # ``max_epr_rms_at_c_max``. It holds without evaluating ``c_max`` once
    # more -- a full bus sweep, ``N`` run_fault calls -- because
    # ``eprs_lo_snapshot`` is the per-bus dict of exactly the evaluation that
    # set ``epr_lo``, at exactly this ``c``. Taking the headline figure *from*
    # the snapshot rather than beside it makes the two agree by construction
    # instead of by repetition, at (iter + 2)*N run_fault calls instead of
    # (iter + 3)*N.
    epr_at = max(epr_per_bus_at.values()) if epr_per_bus_at else epr_at

    return {
        "c_max": c_max,
        "k_max": tuple(c_max * x for x in k_ref),
        "max_epr_rms_at_c_max": epr_at,
        "epr_rms_per_bus_at_c_max": epr_per_bus_at,
        "iterations": iterations,
        **report(status, c_lo, c_hi),
    }

find_max_rho_scaling

find_max_rho_scaling(
    network: Network,
    fault: str,
    bus_names: List[str],
    u_limit: float,
    *,
    c_bounds: Tuple[float, float] = (0.001, 1000.0),
    tol_rel: float = 0.001,
    max_iter: int = 60,
    monotonicity_grid: int = 9,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    progress: Optional[
        Callable[[int, int, str], None]
    ] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]

Find the largest uniform rho-scaling factor compatible with an EPR limit.

Bisects the scalar c such that scaling every selected bus' specific earth resistance to c * rho_0 yields an RMS earth potential rise at the fault bus that just satisfies |u_EPR|_rms <= u_limit. The bus impedance formula is re-evaluated through the existing :meth:Bus.calculate_impedance machinery, so any user-defined rho-f characteristic is honoured.

Parameters:

Name Type Description Default
network Network

The simulation network. Must already contain the named fault, the sources and the buses listed in bus_names. Paths are not needed: the default phase_current_mode="auto" of :func:run_fault solves the phase-conductor network, and the legacy "paths" mode (through run_fault_kwargs) enumerates the paths it needs itself.

required
fault str

Name of the fault to evaluate. Used as active_fault during every bisection step. The former keyword fault_name is accepted as a deprecated alias.

required
bus_names list of str

Names of the buses whose specific earth resistance is uniformly scaled by the same factor c. Must be non-empty and refer to buses in network.

required
u_limit float

Upper bound on the RMS earth potential rise at the fault bus, in volts. Must be finite and strictly positive. The RMS is taken over all simulation frequencies, matching :attr:ResultBus.uepr. The former keyword u_max is accepted as a deprecated alias.

required
c_bounds tuple of (float, float)

Search interval for the scaling factor c. Both bounds must be finite and strictly positive and c_bounds[0] < c_bounds[1]. Defaults to (1e-3, 1e3), i.e. six decades.

(0.001, 1000.0)
tol_rel float

Relative tolerance on the bracket width (c_hi - c_lo) / c_lo at which the bisection terminates. Must be finite and strictly positive. Defaults to 1e-3.

0.001
max_iter int

Hard cap on the number of bisection steps. Must be an int of at least 1. Defaults to 60, which is roughly four times what the default bracket and tolerance need.

60
monotonicity_grid int

Number of factors evaluated on a logarithmic grid across c_bounds before the bisection, to test the monotonicity the bisection assumes. Must be 0 (no scan) or at least 3; defaults to 9. The scan is not free -- it costs one solve per point -- but it pays part of itself back: on a monotone curve the bisection starts from the one grid interval the threshold falls in rather than from the whole bracket, which is worth log2(monotonicity_grid - 1) steps. Set it to 0 only where monotonicity is known from the model (e.g. an impedance formula in which every term scales with rho).

9
run_fault_kwargs dict

Extra keyword arguments forwarded to :func:run_fault (e.g. {"phase_current_mode": "paths"}). Defaults to None.

None
progress callable

progress(done, total, label), called after every solve (scan points and bisection steps alike) with the trial factor as label. total is the evaluation count the bracket and tolerance require; see :mod:groundinsight.progress.

None
should_cancel callable

Asked before every solve; a true answer raises :class:~groundinsight.progress.StudyCancelled.

None

Returns:

Type Description
dict

Mapping with keys

  • "c_max" (float): a scaling factor whose EPR was evaluated and found to satisfy the constraint. This is a guarantee in one direction only: c_max is always admissible, but it is the largest admissible factor only when "converged" is True.
  • "u_epr_rms_at_c_max" (float): the RMS EPR at the fault bus evaluated at c_max, in volts.
  • "rho_max" (dict of str to float): c_max * rho_0[bus] for every selected bus.
  • "iterations" (int): number of bisection steps taken.
  • "converged" (bool): True iff the search closed the bracket to within tol_rel around the threshold. Check this before using c_max as a design value.
  • "status" (str): which stopping condition applied -- "converged", "bracket_within_tol_on_entry", "max_iter_reached", "bracket_fully_admissible" or "non_monotone". See :mod:groundinsight.analysis._bisection.
  • "c_bracket" (tuple of float): the interval that provably contains the true maximum admissible factor. For "bracket_fully_admissible" this is (c_hi, inf): nothing above the bracket was ever evaluated, so widen c_bounds.
  • "bracket_rel_width" (float): (c_hi - c_lo) / c_lo of that interval, directly comparable against tol_rel, and inf for "bracket_fully_admissible".

iterations == 0 on its own does not identify a case: it is produced by a fully admissible bracket, by a bracket that was already narrower than tol_rel, and (before the guards below existed) by a cap of zero steps -- outcomes whose c_max came from opposite ends of the bracket. Use "status".

Raises:

Type Description
ValueError

If u_limit, tol_rel, max_iter, monotonicity_grid or c_bounds is invalid (see the parameter descriptions -- non-finite values are rejected, not just out-of-range ones), bus_names is empty, any name is not in the network, the EPR at the lower bound c_bounds[0] already exceeds u_limit, or the model returns a non-finite EPR at some trial factor.

TypeError

If progress or should_cancel is not callable.

StudyCancelled

If should_cancel() returned true.

Notes

The assumption, and what happens when it does not hold. A bisection finds the crossing of EPR(c) with u_limit, which presumes there is only one -- i.e. that EPR rises monotonically with c. That is the usual case but not a theorem: this function scales the scalar rho, and an impedance formula in which only part of the expression carries rho ("0.02*rho + 0.1*f*j", say) leaves the reactance fixed. The network admittance |Y_net| = |G + 1/(R + jX)| then has a maximum at R = (-1 + sqrt(1 + 4 G^2 X^2)) / (2 G), so the EPR has a minimum there and falls before it rises. Around that dip a bisection can discard the half of the bracket that holds the answer, and it did: the review's case reported "no scaling factor satisfies the constraint" while c = 1 satisfied it.

monotonicity_grid scans for exactly that before the bisection starts. Where the curve turns, the result comes back with status = "non_monotone" and converged = False: c_max is then the largest measured admissible factor, refined inside its grid interval, and a lower bound on the true maximum rather than the maximum. Its resolution is the grid's.

Cost. Only the first trial is a full :func:run_fault. A trial changes nothing but the grounding impedances of the selected buses, which enter the nodal matrix on its diagonal only, so every later trial is re-solved on what the first one assembled -- injection vectors, phase currents, stamp pattern -- by re-assembling the matrix values and factorising them (P4, :mod:groundinsight.analysis._session). The EPR of a trial is bit for bit the one a full run_fault reports, so the search takes the same steps; it is about seven times faster on a 1000-bus ring with every bus scaled. A trial the re-solve cannot answer (a 0 Hz stand-in, a bus that gains or loses its electrode, a value the model rejects) is a full run_fault again, with its errors.

Examples:

Two stations whose electrodes follow the soil (rho * 0.01): by which factor c may the resistivity around both change before the EPR at the fault exceeds 5 V?

>>> import groundinsight as gi
>>> net = gi.create_network(name="station", frequencies=[50.0])
>>> grid = gi.BusType(name="grid", system_type="Substation", voltage_level=20.0,
...                   impedance_formula="rho * 0.01")
>>> line = gi.BranchType(name="line", grounding_conductor=True,
...                      self_impedance_formula="0.25 * l",
...                      mutual_impedance_formula="0 * l")
>>> for name in ("B1", "B2"):
...     _ = gi.create_bus(name=name, type=grid, network=net)
>>> _ = gi.create_branch(name="L1", type=line, from_bus="B1", to_bus="B2",
...                      length=1.0, network=net)
>>> _ = gi.create_source(name="S1", bus="B1", values={50.0: 100.0}, network=net)
>>> _ = gi.create_fault(name="F1", bus="B2", network=net)
>>> report = gi.find_max_rho_scaling(net, "F1", ["B1", "B2"], u_limit=5.0)
>>> report["status"], round(report["c_max"], 3), report["u_epr_rms_at_c_max"] <= 5.0
('converged', 0.083, True)
Source code in src/groundinsight/analysis/inverse_rho.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
@renamed_parameters(fault_name="fault", u_max="u_limit")
def find_max_rho_scaling(
    network: Network,
    fault: str,
    bus_names: List[str],
    u_limit: float,
    *,
    c_bounds: Tuple[float, float] = (1e-3, 1e3),
    tol_rel: float = 1e-3,
    max_iter: int = 60,
    monotonicity_grid: int = 9,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    progress: Optional[Callable[[int, int, str], None]] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
    """
    Find the largest uniform rho-scaling factor compatible with an EPR limit.

    Bisects the scalar ``c`` such that scaling every selected bus'
    specific earth resistance to ``c * rho_0`` yields an RMS earth
    potential rise at the fault bus that just satisfies
    ``|u_EPR|_rms <= u_limit``. The bus impedance formula is re-evaluated
    through the existing :meth:`Bus.calculate_impedance` machinery, so
    any user-defined rho-f characteristic is honoured.

    Parameters
    ----------
    network : Network
        The simulation network. Must already contain the named fault, the
        sources and the buses listed in ``bus_names``. Paths are not
        needed: the default ``phase_current_mode="auto"`` of
        :func:`run_fault` solves the phase-conductor network, and the legacy
        ``"paths"`` mode (through ``run_fault_kwargs``) enumerates the paths
        it needs itself.
    fault : str
        Name of the fault to evaluate. Used as ``active_fault`` during
        every bisection step. The former keyword ``fault_name`` is accepted
        as a deprecated alias.
    bus_names : list of str
        Names of the buses whose specific earth resistance is uniformly
        scaled by the same factor ``c``. Must be non-empty and refer to
        buses in ``network``.
    u_limit : float
        Upper bound on the RMS earth potential rise at the fault bus, in
        volts. Must be finite and strictly positive. The RMS is taken
        over all simulation frequencies, matching :attr:`ResultBus.uepr`.
        The former keyword ``u_max`` is accepted as a deprecated alias.
    c_bounds : tuple of (float, float), optional
        Search interval for the scaling factor ``c``. Both bounds must be
        finite and strictly positive and ``c_bounds[0] < c_bounds[1]``.
        Defaults to ``(1e-3, 1e3)``, i.e. six decades.
    tol_rel : float, optional
        Relative tolerance on the bracket width
        ``(c_hi - c_lo) / c_lo`` at which the bisection terminates. Must
        be finite and strictly positive. Defaults to ``1e-3``.
    max_iter : int, optional
        Hard cap on the number of bisection steps. Must be an ``int``
        of at least 1. Defaults to ``60``, which is roughly four times
        what the default bracket and tolerance need.
    monotonicity_grid : int, optional
        Number of factors evaluated on a logarithmic grid across
        ``c_bounds`` *before* the bisection, to test the monotonicity
        the bisection assumes. Must be ``0`` (no scan) or at least 3;
        defaults to ``9``. The scan is not free -- it costs one solve
        per point -- but it pays part of itself back: on
        a monotone curve the bisection starts from the one grid
        interval the threshold falls in rather than from the whole
        bracket, which is worth ``log2(monotonicity_grid - 1)`` steps.
        Set it to ``0`` only where monotonicity is known from the
        model (e.g. an impedance formula in which *every* term scales
        with ``rho``).
    run_fault_kwargs : dict, optional
        Extra keyword arguments forwarded to :func:`run_fault` (e.g.
        ``{"phase_current_mode": "paths"}``). Defaults to ``None``.
    progress : callable, optional
        ``progress(done, total, label)``, called after every solve (scan
        points and bisection steps alike) with the trial factor as label.
        ``total`` is the evaluation count the bracket and tolerance require;
        see :mod:`groundinsight.progress`.
    should_cancel : callable, optional
        Asked before every solve; a true answer raises
        :class:`~groundinsight.progress.StudyCancelled`.

    Returns
    -------
    dict
        Mapping with keys

        - ``"c_max"`` (float): a scaling factor whose EPR was evaluated
          and found to satisfy the constraint. **This is a guarantee in
          one direction only**: ``c_max`` is always admissible, but it is
          the *largest* admissible factor only when ``"converged"`` is
          ``True``.
        - ``"u_epr_rms_at_c_max"`` (float): the RMS EPR at the fault bus
          evaluated at ``c_max``, in volts.
        - ``"rho_max"`` (dict of str to float): ``c_max * rho_0[bus]`` for
          every selected bus.
        - ``"iterations"`` (int): number of bisection steps taken.
        - ``"converged"`` (bool): ``True`` iff the search closed the
          bracket to within ``tol_rel`` around the threshold. Check this
          before using ``c_max`` as a design value.
        - ``"status"`` (str): which stopping condition applied --
          ``"converged"``, ``"bracket_within_tol_on_entry"``,
          ``"max_iter_reached"``, ``"bracket_fully_admissible"`` or
          ``"non_monotone"``. See
          :mod:`groundinsight.analysis._bisection`.
        - ``"c_bracket"`` (tuple of float): the interval that provably
          contains the true maximum admissible factor. For
          ``"bracket_fully_admissible"`` this is ``(c_hi, inf)``: nothing
          above the bracket was ever evaluated, so widen ``c_bounds``.
        - ``"bracket_rel_width"`` (float): ``(c_hi - c_lo) / c_lo`` of
          that interval, directly comparable against ``tol_rel``, and
          ``inf`` for ``"bracket_fully_admissible"``.

        ``iterations == 0`` on its own does **not** identify a case: it is
        produced by a fully admissible bracket, by a bracket that was
        already narrower than ``tol_rel``, and (before the guards below
        existed) by a cap of zero steps -- outcomes whose ``c_max`` came
        from opposite ends of the bracket. Use ``"status"``.

    Raises
    ------
    ValueError
        If ``u_limit``, ``tol_rel``, ``max_iter``, ``monotonicity_grid`` or
        ``c_bounds`` is invalid (see the parameter descriptions --
        non-finite values are rejected, not just out-of-range ones),
        ``bus_names`` is empty, any name is not in the network, the EPR at
        the lower bound ``c_bounds[0]`` already exceeds ``u_limit``, or the
        model returns a non-finite EPR at some trial factor.
    TypeError
        If ``progress`` or ``should_cancel`` is not callable.
    StudyCancelled
        If ``should_cancel()`` returned true.

    Notes
    -----
    **The assumption, and what happens when it does not hold.** A bisection
    finds *the* crossing of ``EPR(c)`` with ``u_limit``, which presumes there
    is only one -- i.e. that ``EPR`` rises monotonically with ``c``. That is
    the usual case but not a theorem: this function scales the scalar ``rho``,
    and an impedance formula in which only part of the expression carries
    ``rho`` (``"0.02*rho + 0.1*f*j"``, say) leaves the reactance fixed. The
    network admittance ``|Y_net| = |G + 1/(R + jX)|`` then has a *maximum* at
    ``R = (-1 + sqrt(1 + 4 G^2 X^2)) / (2 G)``, so the EPR has a minimum
    there and falls before it rises. Around that dip a bisection can discard
    the half of the bracket that holds the answer, and it did: the review's
    case reported "no scaling factor satisfies the constraint" while ``c = 1``
    satisfied it.

    ``monotonicity_grid`` scans for exactly that before the bisection starts.
    Where the curve turns, the result comes back with
    ``status = "non_monotone"`` and ``converged = False``: ``c_max`` is then
    the largest *measured* admissible factor, refined inside its grid
    interval, and a lower bound on the true maximum rather than the maximum.
    Its resolution is the grid's.

    **Cost.** Only the first trial is a full :func:`run_fault`. A trial
    changes nothing but the grounding impedances of the selected buses, which
    enter the nodal matrix on its diagonal only, so every later trial is
    re-solved on what the first one assembled -- injection vectors, phase
    currents, stamp pattern -- by re-assembling the matrix values and
    factorising them (P4, :mod:`groundinsight.analysis._session`). The EPR of
    a trial is bit for bit the one a full ``run_fault`` reports, so the
    search takes the same steps; it is about seven times faster on a
    1000-bus ring with every bus scaled. A trial the re-solve cannot answer
    (a 0 Hz stand-in, a bus that gains or loses its electrode, a value the
    model rejects) is a full ``run_fault`` again, with its errors.

    Examples
    --------
    Two stations whose electrodes follow the soil (``rho * 0.01``): by which
    factor ``c`` may the resistivity around both change before the EPR at the
    fault exceeds 5 V?

    >>> import groundinsight as gi
    >>> net = gi.create_network(name="station", frequencies=[50.0])
    >>> grid = gi.BusType(name="grid", system_type="Substation", voltage_level=20.0,
    ...                   impedance_formula="rho * 0.01")
    >>> line = gi.BranchType(name="line", grounding_conductor=True,
    ...                      self_impedance_formula="0.25 * l",
    ...                      mutual_impedance_formula="0 * l")
    >>> for name in ("B1", "B2"):
    ...     _ = gi.create_bus(name=name, type=grid, network=net)
    >>> _ = gi.create_branch(name="L1", type=line, from_bus="B1", to_bus="B2",
    ...                      length=1.0, network=net)
    >>> _ = gi.create_source(name="S1", bus="B1", values={50.0: 100.0}, network=net)
    >>> _ = gi.create_fault(name="F1", bus="B2", network=net)
    >>> report = gi.find_max_rho_scaling(net, "F1", ["B1", "B2"], u_limit=5.0)
    >>> report["status"], round(report["c_max"], 3), report["u_epr_rms_at_c_max"] <= 5.0
    ('converged', 0.083, True)
    """
    validate_limit(u_limit, "u_limit")
    validate_tol_rel(tol_rel)
    validate_max_iter(max_iter)
    validate_grid_points(monotonicity_grid)
    if not bus_names:
        raise ValueError("bus_names must not be empty.")
    c_lo_init, c_hi_init = validate_c_bounds(c_bounds)
    missing = [b for b in bus_names if b not in network.buses]
    if missing:
        raise ValueError(f"Unknown bus(es) in network: {missing!r}.")
    if fault not in network.faults:
        raise ValueError(f"Unknown fault {fault!r} in network.")

    rfk: Dict[str, Any] = dict(run_fault_kwargs) if run_fault_kwargs else {}

    # The evaluation count is known before the first solve: the scan, plus the
    # halvings that close one scan interval (the whole bracket without a scan)
    # to tol_rel -- a log-bisection needs the same number wherever the
    # threshold lies.
    n_scan = len(log_grid(c_lo_init, c_hi_init, monotonicity_grid))
    interval = (c_hi_init / c_lo_init) ** (1.0 / max(n_scan - 1, 1))
    hooks = StudyHooks(
        "find_max_rho_scaling",
        n_scan + planned_steps(1.0, interval, tol_rel, max_iter),
        progress,
        should_cancel,
    )

    fault_bus_name = network.faults[fault].bus

    # Snapshot original rhos so the network can be restored at the end.
    rho_0: Dict[str, float] = {
        b: float(network.buses[b].specific_earth_resistance) for b in bus_names
    }
    # Snapshot the state run_fault will mutate so the search leaves the network
    # exactly as it found it (the returned figures are already final).
    active_fault_backup = network.active_fault
    result_backup = network.results.get(fault)
    had_result = fault in network.results
    # The assembled nodal system is *not* recomputed by anything the caller
    # does afterwards -- ``bus_response`` and ``analyze_cuts`` read it back as
    # it stands. Every ``run_fault`` below replaces it with the matrices of a
    # trial rho, so without this backup the network would be left carrying the
    # Y of the last bisection step next to the restored rho. That combination
    # is not merely stale, it is inconsistent: it gives a *negative*
    # driving-point impedance in the review case. The pre-search object was
    # built from exactly the state restored below, so putting it back is
    # correct rather than merely conservative.
    electrical_backup = network.electrical_network

    # A trial changes nothing but the grounding impedances of the selected
    # buses, i.e. the diagonal of Y. The first trial is a full run_fault; the
    # others are re-solved on what it assembled (P4, see analysis._session):
    # the same matrix values, factorisation and RMS, so the same EPR bit for
    # bit. A trial the session cannot answer is solved in full again, and the
    # session then continues from that solve.
    session_box: Dict[str, Optional[BusImpedanceSession]] = {"session": None}

    def _session_epr(c: float) -> Optional[float]:
        """The EPR of a trial from the session, or ``None`` for a full solve."""
        session = session_box["session"]
        if session is None:
            return None
        try:
            impedances = {
                b: bus_impedance_at(
                    network.buses[b], c * rho_0[b], network.frequencies
                )
                for b in bus_names
            }
        except Exception:  # noqa: BLE001 -- the full solve raises it in its own words
            return None
        return session.epr_rms(impedances)

    def _epr_rms_at(c: float) -> float:
        """Evaluate the RMS EPR at the fault bus for a given scaling factor."""
        hooks.checkpoint()
        epr = _session_epr(c)
        if epr is None:
            for b in bus_names:
                bus = network.buses[b]
                bus.specific_earth_resistance = c * rho_0[b]
                bus.calculate_impedance(network.frequencies)
            run_fault(network, fault=fault, **rfk)
            result_bus = next(
                rb
                for rb in network.results[fault].buses
                if rb.name == fault_bus_name
            )
            epr = float(result_bus.uepr)
            session_box["session"] = BusImpedanceSession.attach(network, fault)
        if not math.isfinite(epr):
            # A non-finite EPR cannot be compared against u_limit: every
            # comparison is False, so the bisection would take the same turn
            # at every step and walk silently to the lower bracket bound.
            # The impedance pipeline raises on NaN before a formula can get
            # this far today, so this is a second lock on the same door --
            # it defends the search below it, not the model above it.
            raise ValueError(
                f"The EPR at bus {fault_bus_name!r} evaluated to {epr!r} for "
                f"the scaling factor c={c:g}. A non-finite EPR cannot be "
                "compared against u_limit -- every comparison would be False "
                "and the bisection would walk to the lower bracket bound "
                "without ever raising. This is a model problem, not a search "
                "problem: check the bus impedance formula at the scaled rho."
            )
        hooks.advance(f"c = {c:.6g}")
        return epr

    # Everything above restores the network field by field; this records the
    # network-level state as a whole, so the restore in ``finally`` is exact
    # -- result order, path set and private state included (GUI5).
    state = NetworkState(network)
    iterations = 0
    try:
        c_lo, c_hi = c_lo_init, c_hi_init
        # Pre-scan. The bisection needs EPR(c) to rise with c, and the rho
        # sweep does not always: only the resistive part of the bus impedance
        # scales, so |Y_net| = |G + 1/(R + jX)| passes through a maximum at
        # R = (-1 + sqrt(1 + 4 G^2 X^2)) / (2G) and the EPR through a minimum
        # there. The scan measures whether that happens inside this bracket
        # instead of assuming it does not.
        grid = log_grid(c_lo, c_hi, monotonicity_grid)
        grid_eprs = tuple(_epr_rms_at(c) for c in grid)
        monotone = monotonicity_grid < 3 or is_monotone(grid_eprs)
        epr_lo, epr_hi = grid_eprs[0], grid_eprs[-1]

        if not monotone:
            return _non_monotone_result(
                grid, grid_eprs, u_limit, tol_rel, max_iter, _epr_rms_at,
                rho_0, bus_names, c_bounds,
            )

        # Monotone: the scan also narrows the bracket to the one grid interval
        # the threshold falls in, which pays back part of its own cost --
        # every interval skipped is a bisection step not taken.
        for value, epr in zip(grid, grid_eprs, strict=True):
            if epr <= u_limit:
                c_lo, epr_lo = value, epr
            else:
                c_hi, epr_hi = value, epr
                break

        if epr_lo > u_limit:
            raise ValueError(
                f"u_limit={u_limit:g} V is below the EPR at c_min={c_lo:g}: "
                f"|u_EPR|_rms(c_min)={epr_lo:g} V — no scaling factor in "
                f"the bracket {c_bounds!r} satisfies the constraint."
            )
        if epr_hi <= u_limit:
            # Whole bracket is admissible. c_hi is a real, measured answer,
            # but it is a lower bound on the true maximum, not the maximum:
            # nothing above c_hi was evaluated. The status says so, and
            # ``c_bracket`` comes back as (c_hi, inf) to make that
            # machine-readable.
            logger.info(
                "Bracket fully admissible: |u_EPR|_rms(c_hi=%g)=%g V <= "
                "u_limit=%g V. Consider widening c_bounds.",
                c_hi, epr_hi, u_limit,
            )
            c_max, epr_at = c_hi, epr_hi
            status = STATUS_BRACKET_FULLY_ADMISSIBLE
        else:
            # From here on epr(c_lo) <= u_limit < epr(c_hi) holds and is
            # preserved by every step, so c_lo is always a *verified*
            # admissible factor and the threshold stays bracketed.
            while iterations < max_iter and (c_hi - c_lo) / c_lo > tol_rel:
                c_mid = math.sqrt(c_lo * c_hi)  # geometric mean -> log bisection
                epr_mid = _epr_rms_at(c_mid)
                if epr_mid <= u_limit:
                    c_lo, epr_lo = c_mid, epr_mid
                else:
                    c_hi, epr_hi = c_mid, epr_mid
                iterations += 1
            c_max, epr_at = c_lo, epr_lo
            status = classify(iterations, c_lo, c_hi, tol_rel)
            # Ask the classifier rather than re-deriving the same condition:
            # two copies of "did it close?" is exactly how a status and its
            # log message drift apart.
            if status == STATUS_MAX_ITER_REACHED:
                logger.warning(
                    "Bisection stopped at the step cap max_iter=%d without "
                    "closing the bracket: c in [%g, %g], relative width %g > "
                    "tol_rel=%g. c_max=%g is admissible but may be well below "
                    "the true maximum.",
                    max_iter, c_lo, c_hi, (c_hi - c_lo) / c_lo, tol_rel, c_lo,
                )
    finally:
        # Restore original rhos and recompute their impedances no matter what.
        for b in bus_names:
            bus = network.buses[b]
            bus.specific_earth_resistance = rho_0[b]
            bus.calculate_impedance(network.frequencies)
        # Restore the result cache and active fault so no trace of the search
        # remains on the network.
        if had_result:
            network.results[fault] = result_backup
        else:
            network.results.pop(fault, None)
        if active_fault_backup is None:
            network.active_fault = None
            for _flt in network.faults.values():
                _flt.mark_active(False)
        elif active_fault_backup in network.faults:
            network.set_active_fault(active_fault_backup, keep_results=True)
        # Restore the assembled system last: it has to agree with the rho,
        # results and active fault put back above. If the network carried none
        # on entry it gets none back -- a stale matrix is worse than no matrix,
        # because the readers above it raise on the second and not on the first.
        network.electrical_network = electrical_backup
        # And the network-level state exactly as recorded before the search.
        state.restore()

    return {
        "c_max": c_max,
        "u_epr_rms_at_c_max": epr_at,
        "rho_max": {b: c_max * rho_0[b] for b in bus_names},
        "iterations": iterations,
        **report(status, c_lo, c_hi),
    }

iec60909_m

iec60909_m(
    kappa: float, frequency: float, t_k_s: float
) -> float

Heat-effect factor m of the aperiodic (DC) short-circuit component.

m = (exp(4*f*Tk*ln(kappa-1)) - 1) / (2*f*Tk*ln(kappa-1)) per IEC 60909-0. The limits are handled explicitly: kappa -> 1 (no DC offset) gives m -> 0; kappa -> 2 (non-decaying DC, X/R -> inf) gives m -> 2.

Parameters:

Name Type Description Default
kappa float

Peak factor kappa in (1, 2] (see :func:kappa_from_r_to_x).

required
frequency float

System frequency f in Hz (50 or 60). The former keyword f is accepted as a deprecated alias.

required
t_k_s float

Fault duration T_k in seconds. Must be strictly positive. The former keyword t_k is accepted as a deprecated alias.

required

Returns:

Type Description
float

The dimensionless factor m (>= 0).

Raises:

Type Description
ValueError

If t_k_s or frequency is not strictly positive.

Notes

The kappa -> 2 limit is worth spelling out because it is easy to get backwards. Substituting a = ln(kappa - 1) -> 0 and expanding, (exp(4 f Tk a) - 1) / (2 f Tk a) -> 4 f Tk a / (2 f Tk a) = 2. A vanishing-resistance fault therefore carries the maximum DC heat, not none. pandapower's _calc_ith sets m = 0 for kappa > 1.99, which is why :func:groundinsight.io.pandapower_sc.read_shortcircuit_results recomputes I_th with this function instead of copying pandapower's ith_ka.

Examples:

>>> iec60909_m(1.0, 50.0, 0.5)
0.0
>>> iec60909_m(2.0, 50.0, 0.5)
2.0
Source code in src/groundinsight/analysis/shortcircuit.py
@renamed_parameters(f="frequency", t_k="t_k_s")
def iec60909_m(kappa: float, frequency: float, t_k_s: float) -> float:
    """
    Heat-effect factor ``m`` of the aperiodic (DC) short-circuit component.

    ``m = (exp(4*f*Tk*ln(kappa-1)) - 1) / (2*f*Tk*ln(kappa-1))`` per
    IEC 60909-0. The limits are handled explicitly: ``kappa -> 1`` (no DC
    offset) gives ``m -> 0``; ``kappa -> 2`` (non-decaying DC, ``X/R -> inf``)
    gives ``m -> 2``.

    Parameters
    ----------
    kappa : float
        Peak factor ``kappa`` in ``(1, 2]`` (see :func:`kappa_from_r_to_x`).
    frequency : float
        System frequency ``f`` in Hz (50 or 60). The former keyword ``f`` is
        accepted as a deprecated alias.
    t_k_s : float
        Fault duration ``T_k`` in seconds. Must be strictly positive. The
        former keyword ``t_k`` is accepted as a deprecated alias.

    Returns
    -------
    float
        The dimensionless factor ``m`` (``>= 0``).

    Raises
    ------
    ValueError
        If ``t_k_s`` or ``frequency`` is not strictly positive.

    Notes
    -----
    The ``kappa -> 2`` limit is worth spelling out because it is easy to get
    backwards. Substituting ``a = ln(kappa - 1) -> 0`` and expanding,
    ``(exp(4 f Tk a) - 1) / (2 f Tk a) -> 4 f Tk a / (2 f Tk a) = 2``. A
    vanishing-resistance fault therefore carries the *maximum* DC heat, not
    none. pandapower's ``_calc_ith`` sets ``m = 0`` for ``kappa > 1.99``,
    which is why :func:`groundinsight.io.pandapower_sc.read_shortcircuit_results`
    recomputes ``I_th`` with this function instead of copying pandapower's
    ``ith_ka``.

    Examples
    --------
    >>> iec60909_m(1.0, 50.0, 0.5)
    0.0
    >>> iec60909_m(2.0, 50.0, 0.5)
    2.0
    """
    if t_k_s <= 0:
        raise ValueError(f"t_k_s must be strictly positive, got {t_k_s!r}.")
    if frequency <= 0:
        raise ValueError(f"frequency must be strictly positive, got {frequency!r}.")
    if kappa <= 1.0:
        return 0.0
    if kappa >= 2.0:
        return 2.0
    a = math.log(kappa - 1.0)  # negative for 1 < kappa < 2
    denom = 2.0 * frequency * t_k_s * a
    if abs(denom) < 1e-12:  # kappa extremely close to 2 -> non-decaying DC
        return 2.0
    return (math.exp(4.0 * frequency * t_k_s * a) - 1.0) / denom

iec60949_k

iec60949_k(
    material: str,
    theta_initial_C: float = 20.0,
    theta_final_C: Optional[float] = None,
) -> float

Material constant k of the adiabatic short-circuit equation.

k = K * sqrt(ln((theta_f + beta) / (theta_i + beta))) per IEC 60949 / IEC 60364-5-54, with the base constant K and beta taken from :data:IEC60949_MATERIALS.

Parameters:

Name Type Description Default
material str

One of the keys of :data:IEC60949_MATERIALS ("Cu", "Al", "Steel").

required
theta_initial_C float

Initial conductor temperature theta_i in °C. Defaults to 20.0 (ambient). For a conductor that also carries load current use its maximum continuous operating temperature.

20.0
theta_final_C float

Final (maximum permissible) conductor temperature theta_f in °C. Defaults to the material's bare-earthing-conductor value from :data:IEC60949_MATERIALS.

None

Returns:

Type Description
float

The material constant k in A·s^0.5/mm².

Raises:

Type Description
ValueError

If material is unknown or theta_final_C <= theta_initial_C.

Examples:

>>> round(iec60949_k("Cu", theta_initial_C=90.0, theta_final_C=250.0))
143
Source code in src/groundinsight/analysis/thermal.py
def iec60949_k(
    material: str,
    theta_initial_C: float = 20.0,
    theta_final_C: Optional[float] = None,
) -> float:
    """
    Material constant ``k`` of the adiabatic short-circuit equation.

    ``k = K * sqrt(ln((theta_f + beta) / (theta_i + beta)))`` per IEC 60949 /
    IEC 60364-5-54, with the base constant ``K`` and ``beta`` taken from
    :data:`IEC60949_MATERIALS`.

    Parameters
    ----------
    material : str
        One of the keys of :data:`IEC60949_MATERIALS` (``"Cu"``, ``"Al"``,
        ``"Steel"``).
    theta_initial_C : float
        Initial conductor temperature ``theta_i`` in °C. Defaults to
        ``20.0`` (ambient). For a conductor that also carries load current
        use its maximum continuous operating temperature.
    theta_final_C : float, optional
        Final (maximum permissible) conductor temperature ``theta_f`` in °C.
        Defaults to the material's bare-earthing-conductor value from
        :data:`IEC60949_MATERIALS`.

    Returns
    -------
    float
        The material constant ``k`` in A·s^0.5/mm².

    Raises
    ------
    ValueError
        If ``material`` is unknown or ``theta_final_C <= theta_initial_C``.

    Examples
    --------
    >>> round(iec60949_k("Cu", theta_initial_C=90.0, theta_final_C=250.0))
    143
    """
    if material not in IEC60949_MATERIALS:
        raise ValueError(
            f"Unknown conductor material {material!r}. Known materials: "
            f"{sorted(IEC60949_MATERIALS)}."
        )
    data = IEC60949_MATERIALS[material]
    theta_f = (
        data["theta_final_default_C"] if theta_final_C is None else float(theta_final_C)
    )
    beta = data["beta"]
    if theta_f <= theta_initial_C:
        raise ValueError(
            f"theta_final_C ({theta_f}) must exceed theta_initial_C "
            f"({theta_initial_C}) for material {material!r}."
        )
    return data["K"] * math.sqrt(
        math.log((theta_f + beta) / (theta_initial_C + beta))
    )

kappa_from_r_to_x

kappa_from_r_to_x(r_to_x: float) -> float

Peak factor kappa from the R/X ratio (IEC 60909-0).

kappa = 1.02 + 0.98 * exp(-3 * R/X).

The range of the expression is [1.02, 2], not the (1, 2] the IEC formula is often quoted with: the constant term is 1.02, so the exponential approaches 1.02 from above as R/X grows and never reaches 1. Consumers that range-check kappa against (1, 2] therefore accept everything this function can return, which is the point of saying so here.

The R/X to insert is the ratio of the fault loop, not of the positive-sequence system alone. For a three-phase fault the two coincide; for the line-to-earth fault that dominates grounding studies the loop impedance is 2*Z1 + Z0, hence R/X = (2*R1 + R0) / (2*X1 + X0) (see :func:groundinsight.io.pandapower_sc.read_shortcircuit_results).

Parameters:

Name Type Description Default
r_to_x float

The R/X ratio of the fault loop. Must be non-negative.

required

Returns:

Type Description
float

The peak factor kappa.

Raises:

Type Description
ValueError

If r_to_x is negative.

Examples:

>>> round(kappa_from_r_to_x(0.0), 3)
2.0
>>> round(kappa_from_r_to_x(0.1), 4)
1.746
Source code in src/groundinsight/analysis/shortcircuit.py
def kappa_from_r_to_x(r_to_x: float) -> float:
    """
    Peak factor ``kappa`` from the ``R/X`` ratio (IEC 60909-0).

    ``kappa = 1.02 + 0.98 * exp(-3 * R/X)``.

    The range of the expression is ``[1.02, 2]``, not the ``(1, 2]`` the IEC
    formula is often quoted with: the constant term is 1.02, so the exponential
    approaches 1.02 from above as ``R/X`` grows and never reaches 1. Consumers
    that range-check ``kappa`` against ``(1, 2]`` therefore accept everything
    this function can return, which is the point of saying so here.

    The ``R/X`` to insert is the ratio of the **fault loop**, not of the
    positive-sequence system alone. For a three-phase fault the two
    coincide; for the line-to-earth fault that dominates grounding studies
    the loop impedance is ``2*Z1 + Z0``, hence
    ``R/X = (2*R1 + R0) / (2*X1 + X0)``
    (see :func:`groundinsight.io.pandapower_sc.read_shortcircuit_results`).

    Parameters
    ----------
    r_to_x : float
        The ``R/X`` ratio of the fault loop. Must be non-negative.

    Returns
    -------
    float
        The peak factor ``kappa``.

    Raises
    ------
    ValueError
        If ``r_to_x`` is negative.

    Examples
    --------
    >>> round(kappa_from_r_to_x(0.0), 3)
    2.0
    >>> round(kappa_from_r_to_x(0.1), 4)
    1.746
    """
    if r_to_x < 0:
        raise ValueError(f"r_to_x must be non-negative, got {r_to_x!r}.")
    return 1.02 + 0.98 * math.exp(-3.0 * r_to_x)

peak_short_circuit_current

peak_short_circuit_current(
    i_k: float, kappa: float
) -> float

Peak short-circuit current i_p = kappa * sqrt(2) * I_k'' (IEC 60909-0).

i_p drives the electrodynamic (mechanical) stress on conductors and supports; the thermal counterpart is :func:thermal_equivalent_current.

Parameters:

Name Type Description Default
i_k float

RMS short-circuit current I_k'' in amperes. Must be non-negative.

required
kappa float

Peak factor from :func:kappa_from_r_to_x.

required

Returns:

Type Description
float

The peak current in amperes.

Raises:

Type Description
ValueError

If i_k is negative.

Examples:

>>> round(peak_short_circuit_current(1000.0, 1.8), 2)
2545.58
Source code in src/groundinsight/analysis/shortcircuit.py
def peak_short_circuit_current(i_k: float, kappa: float) -> float:
    """
    Peak short-circuit current ``i_p = kappa * sqrt(2) * I_k''`` (IEC 60909-0).

    ``i_p`` drives the *electrodynamic* (mechanical) stress on conductors and
    supports; the thermal counterpart is
    :func:`thermal_equivalent_current`.

    Parameters
    ----------
    i_k : float
        RMS short-circuit current ``I_k''`` in amperes. Must be
        non-negative.
    kappa : float
        Peak factor from :func:`kappa_from_r_to_x`.

    Returns
    -------
    float
        The peak current in amperes.

    Raises
    ------
    ValueError
        If ``i_k`` is negative.

    Examples
    --------
    >>> round(peak_short_circuit_current(1000.0, 1.8), 2)
    2545.58
    """
    if i_k < 0:
        raise ValueError(f"i_k must be non-negative, got {i_k!r}.")
    return kappa * math.sqrt(2.0) * i_k

resolve_fault_sc_characteristics

resolve_fault_sc_characteristics(
    network: Network,
    fault: str,
    *,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
) -> FaultShortCircuitData

Aggregate the IEC 60909 data of a fault and its sources.

The result is one set of characteristics for the fault.

This is the executable form of the project's superposition rule (see the module docstring): the linear RMS currents stay superposed by the solve, and one effective kappa is resolved here so that the non-linear 60909 factors are applied exactly once, to the aggregate.

Parameters:

Name Type Description Default
network Network

The network holding the fault and its sources.

required
fault str

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

required
frequency float

Frequency in Hz at which the source injections are weighted. Defaults to the lowest positive frequency of network (the power frequency in a harmonic study), or 50.0.

None
aggregation (weighted, max)

"weighted" (default) takes the current-weighted mean of the source kappa values, which reproduces the sum of the individual peak currents exactly. "max" takes the largest kappa, a strictly conservative bound.

'weighted'

Returns:

Type Description
FaultShortCircuitData

The resolved characteristics. kappa is None when no contributing source carries 60909 data -- callers must then fall back to an explicit argument.

Raises:

Type Description
ValueError

If fault is unknown or aggregation is not one of the supported modes.

Warns:

Type Description
ModelAssumptionWarning

Code SC_KAPPA_MIXED (elements: the sources with a kappa and the fault) when the feeding sources have different R/X: the non-linear IEC 60909 factors are applied once, with the aggregated kappa.

InputWarning

Code SC_DATA_INCOMPLETE (elements: the sources without IEC 60909 data and the fault) when part of the current comes from sources that carry no r_to_x or kappa: kappa_eff then describes only the remaining share and i_p applies it to the whole current.

Notes

What the aggregation actually does, stated exactly. The two returned quantities are not taken over the same set of sources, and it matters:

  • kappa is the weighted mean over the sources that carry 60909 data (kappa or r_to_x). Sources without it cannot contribute a value and are left out; they are listed in sources_without_kappa.
  • i_k_a is the sum over all feeding sources, those included.

A consumer that then forms i_p = kappa * sqrt(2) * i_k_a -- which is what :func:~groundinsight.check_conductor_limits and :func:~groundinsight.check_node_limits do -- therefore applies the peak factor of one subset to the current of the whole. Where every source carries data the subsets coincide and the result is exact; where they do not, the answer is an approximation whose quality is the share of the current the data covers. That share is reported in the InputWarning (SC_DATA_INCOMPLETE) this function emits, and above half of the current the message says outright that i_p rests mostly on an assumption. The alternative -- dropping the undocumented sources from i_k_a as well -- would understate the current, which is the unsafe direction.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="demo", frequencies=[50.0])
>>> bt = gi.BusType(name="b", system_type="s", voltage_level=20.0,
...                 impedance_formula="rho*0 + 1.0")
>>> _ = gi.create_bus(name="B1", type=bt, network=net)
>>> _ = gi.create_source(name="S1", bus="B1", values={50.0: 1000.0},
...                      network=net, r_to_x=0.1)
>>> _ = gi.create_fault(name="F1", bus="B1", scalings={50.0: 1.0},
...                     network=net, t_k_s=0.5)
>>> data = gi.resolve_fault_sc_characteristics(net, "F1")
>>> round(data.kappa, 4)
1.746
Source code in src/groundinsight/analysis/shortcircuit.py
@renamed_parameters(fault_name="fault")
def resolve_fault_sc_characteristics(
    network: Network,
    fault: str,
    *,
    frequency: Optional[float] = None,
    aggregation: str = "weighted",
) -> FaultShortCircuitData:
    """
    Aggregate the IEC 60909 data of a fault and its sources.

    The result is one set of characteristics for the fault.

    This is the executable form of the project's superposition rule (see the
    module docstring): the *linear* RMS currents stay superposed by the
    solve, and one effective ``kappa`` is resolved here so that the
    *non-linear* 60909 factors are applied exactly once, to the aggregate.

    Parameters
    ----------
    network : Network
        The network holding the fault and its sources.
    fault : str
        Name of the fault to resolve. The former keyword ``fault_name`` is
        accepted as a deprecated alias.
    frequency : float, optional
        Frequency in Hz at which the source injections are weighted.
        Defaults to the lowest positive frequency of ``network`` (the power
        frequency in a harmonic study), or ``50.0``.
    aggregation : {'weighted', 'max'}
        ``"weighted"`` (default) takes the current-weighted mean of the
        source ``kappa`` values, which reproduces the sum of the individual
        peak currents exactly. ``"max"`` takes the largest ``kappa``, a
        strictly conservative bound.

    Returns
    -------
    FaultShortCircuitData
        The resolved characteristics. ``kappa`` is ``None`` when no
        contributing source carries 60909 data -- callers must then fall
        back to an explicit argument.

    Raises
    ------
    ValueError
        If ``fault`` is unknown or ``aggregation`` is not one of the
        supported modes.

    Warns
    -----
    ModelAssumptionWarning
        Code ``SC_KAPPA_MIXED`` (elements: the sources with a ``kappa`` and the
        fault) when the feeding sources have different R/X: the non-linear
        IEC 60909 factors are applied once, with the aggregated ``kappa``.
    InputWarning
        Code ``SC_DATA_INCOMPLETE`` (elements: the sources without IEC 60909
        data and the fault) when part of the current comes from sources that
        carry no ``r_to_x`` or ``kappa``: ``kappa_eff`` then describes only
        the remaining share and ``i_p`` applies it to the whole current.

    Notes
    -----
    **What the aggregation actually does, stated exactly.** The two returned
    quantities are not taken over the same set of sources, and it matters:

    * ``kappa`` is the weighted mean over the sources that **carry** 60909
      data (``kappa`` or ``r_to_x``). Sources without it cannot contribute a
      value and are left out; they are listed in ``sources_without_kappa``.
    * ``i_k_a`` is the sum over **all** feeding sources, those included.

    A consumer that then forms ``i_p = kappa * sqrt(2) * i_k_a`` -- which is
    what :func:`~groundinsight.check_conductor_limits` and
    :func:`~groundinsight.check_node_limits` do -- therefore applies the peak
    factor of one subset to the current of the whole. Where every source
    carries data the subsets coincide and the result is exact; where they do
    not, the answer is an approximation whose quality is the share of the
    current the data covers. That share is reported in the ``InputWarning``
    (``SC_DATA_INCOMPLETE``) this function emits, and above half of the
    current the message says outright that ``i_p`` rests mostly on an
    assumption. The alternative -- dropping the undocumented sources from
    ``i_k_a`` as well -- would understate the current, which is the unsafe
    direction.

    Examples
    --------
    >>> import groundinsight as gi
    >>> net = gi.create_network(name="demo", frequencies=[50.0])
    >>> bt = gi.BusType(name="b", system_type="s", voltage_level=20.0,
    ...                 impedance_formula="rho*0 + 1.0")
    >>> _ = gi.create_bus(name="B1", type=bt, network=net)
    >>> _ = gi.create_source(name="S1", bus="B1", values={50.0: 1000.0},
    ...                      network=net, r_to_x=0.1)
    >>> _ = gi.create_fault(name="F1", bus="B1", scalings={50.0: 1.0},
    ...                     network=net, t_k_s=0.5)
    >>> data = gi.resolve_fault_sc_characteristics(net, "F1")
    >>> round(data.kappa, 4)
    1.746
    """
    if aggregation not in ("weighted", "max"):
        raise ValueError(
            f"aggregation must be 'weighted' or 'max', got {aggregation!r}."
        )
    fault_obj = network.faults.get(fault)
    if fault_obj is None:
        raise ValueError(
            f"Unknown fault {fault!r}. Known faults: "
            f"{sorted(network.faults)}."
        )

    if frequency is None:
        frequency = next((float(x) for x in network.frequencies if x > 0), 50.0)
    frequency = float(frequency)
    scaling = fault_obj.scaling_at(frequency)

    weights: Dict[str, float] = {}
    kappas: Dict[str, float] = {}
    r_values: List[float] = []
    without_kappa: List[str] = []
    i_k_total = 0.0
    weight_without_kappa = 0.0

    for source_name in sources_feeding(network, fault):
        source = network.sources[source_name]
        weight = _source_injection_magnitude(source, frequency, scaling)
        kappa_i = _source_kappa(source)
        if kappa_i is None:
            if weight > 0:
                without_kappa.append(source_name)
                weight_without_kappa += weight
            i_k_total += weight
            continue
        # A source that carries 60909 data but injects nothing at this
        # frequency would silently vanish from a purely current-weighted
        # mean; give it a nominal weight so its kappa still counts.
        if weight <= 0:
            weight = float(getattr(source, "i_k_a", None) or 0.0)
        weights[source_name] = weight
        kappas[source_name] = kappa_i
        r_to_x_i = getattr(source, "r_to_x", None)
        if r_to_x_i is not None:
            r_values.append(float(r_to_x_i))
        i_k_total += weight

    n_factor = float(getattr(fault_obj, "n_factor", 1.0) or 1.0)
    t_k_s = getattr(fault_obj, "t_k_s", None)
    t_k_s = None if t_k_s is None else float(t_k_s)

    if not kappas:
        if without_kappa:
            logger.debug(
                "Fault %r: none of the feeding sources (%s) carries IEC 60909 "
                "data; kappa stays unresolved.",
                fault,
                ", ".join(without_kappa),
            )
        return FaultShortCircuitData(
            fault_name=fault,
            frequency=frequency,
            t_k_s=t_k_s,
            n_factor=n_factor,
            i_k_a=i_k_total,
            aggregation=aggregation,
            sources_without_kappa=without_kappa,
        )

    kappa_list = list(kappas.values())
    homogeneous = (max(kappa_list) - min(kappa_list)) <= 1e-9

    if aggregation == "max" or homogeneous:
        kappa_eff = max(kappa_list)
    else:
        weight_sum = sum(weights.values())
        if weight_sum > 0:
            kappa_eff = (
                sum(kappas[name] * weights[name] for name in kappas) / weight_sum
            )
        else:  # no current information at all -> plain mean
            kappa_eff = sum(kappa_list) / len(kappa_list)

    if not homogeneous:
        emit(
            ModelAssumptionWarning,
            f"Fault {fault!r} is fed by sources with different R/X (kappa "
            f"between {min(kappa_list):.4f} and {max(kappa_list):.4f}). The "
            f"non-linear IEC 60909 factors are applied once, with the "
            f"{aggregation} kappa = {kappa_eff:.4f}. Use the transient solver "
            f"for an exact mixed-R/X result.",
            code="SC_KAPPA_MIXED",
            elements=[("source", name) for name in kappas] + [("fault", fault)],
            stacklevel=2,
        )
    if without_kappa:
        share = weight_without_kappa / i_k_total if i_k_total > 0 else 0.0
        majority = (
            " That is the majority of the current, so i_p and I_th rest "
            "mostly on an assumption: give those sources an r_to_x or a "
            "kappa, or pass kappa explicitly."
            if share > 0.5
            else ""
        )
        emit(
            InputWarning,
            f"Fault {fault!r}: source(s) {', '.join(without_kappa)} inject "
            f"{100.0 * share:.0f} % of the current at {frequency:.1f} Hz but "
            f"carry no IEC 60909 data. They are excluded from the kappa "
            f"aggregation and included in i_k_a, so kappa_eff = {kappa_eff:.4f} "
            f"is the figure of the remaining {100.0 * (1.0 - share):.0f} % and "
            f"i_p applies it to the whole current.{majority}",
            code="SC_DATA_INCOMPLETE",
            elements=[("source", name) for name in without_kappa] + [("fault", fault)],
            stacklevel=2,
        )

    r_to_x_eff = None
    if r_values and (max(r_values) - min(r_values)) <= 1e-12:
        r_to_x_eff = r_values[0]

    m = None
    if t_k_s is not None and t_k_s > 0:
        m = iec60909_m(kappa_eff, frequency, t_k_s)

    return FaultShortCircuitData(
        fault_name=fault,
        frequency=frequency,
        kappa=kappa_eff,
        r_to_x=r_to_x_eff,
        t_k_s=t_k_s,
        n_factor=n_factor,
        m=m,
        i_k_a=i_k_total,
        i_p_a=peak_short_circuit_current(i_k_total, kappa_eff),
        aggregation=aggregation,
        homogeneous=homogeneous,
        sources=sorted(kappas),
        sources_without_kappa=without_kappa,
    )

run_reference_cases

run_reference_cases(
    cases: Optional[List[ReferenceCase]] = None,
) -> pl.DataFrame

Run the closed-form reference cases and report the comparison.

Parameters:

Name Type Description Default
cases list of ReferenceCase

Defaults to :data:REFERENCE_CASES.

None

Returns:

Type Description
DataFrame

One row per case: case, quantity, conditions, closed_form, model, rel_deviation, tolerance, agrees.

Examples:

>>> import groundinsight as gi
>>> table = gi.run_reference_cases()
>>> table.height == len(gi.REFERENCE_CASES), table["agrees"].all()
(True, True)
Source code in src/groundinsight/analysis/reference.py
def run_reference_cases(
    cases: Optional[List[ReferenceCase]] = None,
) -> pl.DataFrame:
    """
    Run the closed-form reference cases and report the comparison.

    Parameters
    ----------
    cases : list of ReferenceCase, optional
        Defaults to :data:`REFERENCE_CASES`.

    Returns
    -------
    pl.DataFrame
        One row per case: ``case``, ``quantity``, ``conditions``,
        ``closed_form``, ``model``, ``rel_deviation``, ``tolerance``,
        ``agrees``.

    Examples
    --------
    >>> import groundinsight as gi
    >>> table = gi.run_reference_cases()
    >>> table.height == len(gi.REFERENCE_CASES), table["agrees"].all()
    (True, True)
    """
    rows = [case.evaluate() for case in (cases or REFERENCE_CASES)]
    frame = pl.DataFrame(rows)
    failed = frame.filter(~pl.col("agrees"))
    if failed.height:
        logger.warning(
            "%d reference case(s) missed their closed form: %s. Either the model "
            "is wrong or a stated boundary condition was not met -- the second "
            "is the more common finding, so read the 'conditions' column first.",
            failed.height,
            ", ".join(failed["case"].to_list()),
        )
    return frame

select_rho_f_from_catalog

select_rho_f_from_catalog(
    network: Network,
    bus_names: List[str],
    u_limit: float,
    candidates: Dict[str, KVector],
    *,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    sort_by: Literal[
        "max_epr_asc", "max_epr_desc", "name"
    ] = "max_epr_asc",
) -> pl.DataFrame

Pick admissible rho-f characteristics from a user-provided catalog.

Evaluates every candidate k in the catalog with :func:evaluate_max_epr_under_k and reports, per candidate, the maximum RMS EPR observed across the bus sweep, the per-bus EPRs and whether the candidate satisfies the limit u_limit. The catalog is typically a hand-curated list of soil scenarios (e.g. dry sand, wet clay, permafrost) or rho-f fits from previous measurements.

Parameters:

Name Type Description Default
network Network

The simulation network. Sources, branches and the buses to be swept must already be configured.

required
bus_names list of str

Buses whose impedance is parameterised by every candidate k and which are swept as fault locations.

required
u_limit float

Upper bound on the RMS EPR (in volts) at any swept bus. Must be strictly positive.

required
candidates dict of str to tuple of float

Mapping {name: (k1, k2, k3, k4, k5)} of the candidate rho-f characteristics. Names must be unique (Python dict guarantees that), tuples must each have length 5. May be empty -- the result is then an empty DataFrame with the documented schema.

required
fault_scalings dict of float to float

Frequency-resolved scalings for any fault that has to be created on the fly. See :func:evaluate_max_epr_under_k.

None
run_fault_kwargs dict

Forwarded to :func:run_fault.

None
sort_by (max_epr_asc, max_epr_desc, name)

How to sort the result rows.

  • "max_epr_asc" (default): admissible candidates first, tightest-EPR-margin candidates at the top.
  • "max_epr_desc": largest EPR first; useful to inspect the worst-case candidates.
  • "name": lexicographic by candidate name.
"max_epr_asc"

Returns:

Type Description
DataFrame

One row per candidate, with the columns

  • "name" (str);
  • "k1" ... "k5" (float);
  • "max_epr_rms_V" (float): the maximum RMS EPR across the bus sweep, in volts;
  • "admissible" (bool): True iff max_epr_rms_V <= u_limit;
  • one "epr_<bus>_V" column per swept bus: the RMS EPR at that bus when it is the active fault, in volts.

Raises:

Type Description
ValueError

If u_limit is not finite and strictly positive, bus_names is empty, or any candidate has a wrong-length k or refers to an unknown bus (the underlying helper validates this). A NaN u_limit is rejected explicitly: it would otherwise pass a plain positivity check and mark the whole catalog inadmissible.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.models.core_models import BusType, BranchType
>>> from groundinsight.analysis import select_rho_f_from_catalog
>>> bt = BusType(name="BT", system_type="Grounded",
...              voltage_level=20.0,
...              impedance_formula="rho * 0.01 + 0*f")
>>> brt = BranchType(name="BRT", grounding_conductor=True,
...                  self_impedance_formula="(0.25 + I*0.6)*l",
...                  mutual_impedance_formula="(0.0 + I*0.6)*l")
>>> net = gi.create_network(name="N", frequencies=[50])
>>> _ = gi.create_bus(name="b0", type=bt, network=net)
>>> _ = gi.create_bus(name="b1", type=bt, network=net)
>>> _ = gi.create_branch(name="br", type=brt, from_bus="b0",
...                      to_bus="b1", length=1.0, network=net)
>>> _ = gi.create_source(name="src", bus="b0",
...                      values={50: 100.0}, network=net)
>>> catalog = {
...     "low":   (0.005, 0.0, 0.0, 0.0, 0.0),
...     "med":   (0.01,  0.0, 0.0, 0.0, 0.0),
...     "high":  (0.05,  0.0, 0.0, 0.0, 0.0),
... }
>>> df = select_rho_f_from_catalog(
...     net, ["b0", "b1"], u_limit=20.0, candidates=catalog,
... )
>>> set(df.columns) >= {"name", "k1", "max_epr_rms_V", "admissible"}
True
Source code in src/groundinsight/analysis/inverse_rho_f.py
def select_rho_f_from_catalog(
    network: Network,
    bus_names: List[str],
    u_limit: float,
    candidates: Dict[str, KVector],
    *,
    fault_scalings: Optional[Dict[float, float]] = None,
    run_fault_kwargs: Optional[Dict[str, Any]] = None,
    sort_by: Literal["max_epr_asc", "max_epr_desc", "name"] = "max_epr_asc",
) -> pl.DataFrame:
    """Pick admissible rho-f characteristics from a user-provided catalog.

    Evaluates every candidate ``k`` in the catalog with
    :func:`evaluate_max_epr_under_k` and reports, per candidate, the
    maximum RMS EPR observed across the bus sweep, the per-bus EPRs and
    whether the candidate satisfies the limit ``u_limit``. The catalog is
    typically a hand-curated list of soil scenarios (e.g. dry sand, wet
    clay, permafrost) or rho-f fits from previous measurements.

    Parameters
    ----------
    network : Network
        The simulation network. Sources, branches and the buses
        to be swept must already be configured.
    bus_names : list of str
        Buses whose impedance is parameterised by every
        candidate ``k`` and which are swept as fault locations.
    u_limit : float
        Upper bound on the RMS EPR (in volts) at any swept bus.
        Must be strictly positive.
    candidates : dict of str to tuple of float
        Mapping ``{name: (k1, k2, k3, k4, k5)}`` of the
        candidate rho-f characteristics. Names must be unique
        (Python dict guarantees that), tuples must each have length
        5. May be empty -- the result is then an empty DataFrame
        with the documented schema.
    fault_scalings : dict of float to float, optional
        Frequency-resolved scalings for any fault that
        has to be created on the fly. See
        :func:`evaluate_max_epr_under_k`.
    run_fault_kwargs : dict, optional
        Forwarded to :func:`run_fault`.
    sort_by : {"max_epr_asc", "max_epr_desc", "name"}, optional
        How to sort the result rows.

        - ``"max_epr_asc"`` (default): admissible candidates first,
          tightest-EPR-margin candidates at the top.
        - ``"max_epr_desc"``: largest EPR first; useful to inspect
          the worst-case candidates.
        - ``"name"``: lexicographic by candidate name.

    Returns
    -------
    pl.DataFrame
        One row per candidate, with the columns

        - ``"name"`` (str);
        - ``"k1"`` ... ``"k5"`` (float);
        - ``"max_epr_rms_V"`` (float): the maximum RMS EPR across the bus
          sweep, in volts;
        - ``"admissible"`` (bool): ``True`` iff ``max_epr_rms_V <= u_limit``;
        - one ``"epr_<bus>_V"`` column per swept bus: the RMS EPR at that
          bus when it is the active fault, in volts.

    Raises
    ------
    ValueError
        If ``u_limit`` is not finite and strictly positive,
        ``bus_names`` is empty, or any candidate has a wrong-length
        ``k`` or refers to an unknown bus (the underlying helper
        validates this). A NaN ``u_limit`` is rejected explicitly:
        it would otherwise pass a plain positivity check and mark
        the whole catalog inadmissible.

    Examples
    --------
        >>> import groundinsight as gi
        >>> from groundinsight.models.core_models import BusType, BranchType
        >>> from groundinsight.analysis import select_rho_f_from_catalog
        >>> bt = BusType(name="BT", system_type="Grounded",
        ...              voltage_level=20.0,
        ...              impedance_formula="rho * 0.01 + 0*f")
        >>> brt = BranchType(name="BRT", grounding_conductor=True,
        ...                  self_impedance_formula="(0.25 + I*0.6)*l",
        ...                  mutual_impedance_formula="(0.0 + I*0.6)*l")
        >>> net = gi.create_network(name="N", frequencies=[50])
        >>> _ = gi.create_bus(name="b0", type=bt, network=net)
        >>> _ = gi.create_bus(name="b1", type=bt, network=net)
        >>> _ = gi.create_branch(name="br", type=brt, from_bus="b0",
        ...                      to_bus="b1", length=1.0, network=net)
        >>> _ = gi.create_source(name="src", bus="b0",
        ...                      values={50: 100.0}, network=net)
        >>> catalog = {
        ...     "low":   (0.005, 0.0, 0.0, 0.0, 0.0),
        ...     "med":   (0.01,  0.0, 0.0, 0.0, 0.0),
        ...     "high":  (0.05,  0.0, 0.0, 0.0, 0.0),
        ... }
        >>> df = select_rho_f_from_catalog(
        ...     net, ["b0", "b1"], u_limit=20.0, candidates=catalog,
        ... )
        >>> set(df.columns) >= {"name", "k1", "max_epr_rms_V", "admissible"}
        True
    """
    # Same check as in the two searches, and for the same reason -- but the
    # consequence here is worse. This function does not return a scalar a
    # reader might sanity-check, it returns a table with an ``admissible``
    # column, and every entry in it is ``max_epr <= u_limit``. Against NaN
    # every one of those comparisons is False, so the table would report
    # that *no* soil model in the catalog is usable, next to an EPR column
    # that is correct and finite. Nothing in the output would point at the
    # limit as the broken part.
    validate_limit(u_limit, "u_limit")
    if not bus_names:
        raise ValueError("bus_names must not be empty.")

    # Empty catalog -> return an empty DataFrame with the documented schema.
    if not candidates:
        schema = {
            "name": pl.Utf8,
            "k1": pl.Float64, "k2": pl.Float64, "k3": pl.Float64,
            "k4": pl.Float64, "k5": pl.Float64,
            "max_epr_rms_V": pl.Float64,
            "admissible": pl.Boolean,
        }
        for b in bus_names:
            schema[f"epr_{b}_V"] = pl.Float64
        return pl.DataFrame(schema=schema)

    rows: List[Dict[str, Any]] = []
    for name, k in candidates.items():
        if len(k) != 5:
            raise ValueError(
                f"Candidate {name!r}: k must be a 5-tuple, got length {len(k)}."
            )
        eprs = evaluate_max_epr_under_k(
            network, bus_names, k=tuple(k),
            fault_scalings=fault_scalings,
            run_fault_kwargs=run_fault_kwargs,
        )
        max_epr = max(eprs.values()) if eprs else 0.0
        row: Dict[str, Any] = {
            "name": name,
            "k1": float(k[0]),
            "k2": float(k[1]),
            "k3": float(k[2]),
            "k4": float(k[3]),
            "k5": float(k[4]),
            "max_epr_rms_V": float(max_epr),
            "admissible": bool(max_epr <= u_limit),
        }
        for b in bus_names:
            row[f"epr_{b}_V"] = float(eprs[b])
        rows.append(row)

    df = pl.DataFrame(rows)

    if sort_by == "max_epr_asc":
        # Admissible first (True -> 1 sorts after False -> 0 by default,
        # so descending on ``admissible`` puts True on top), then
        # ascending EPR within each block.
        df = df.sort(
            by=["admissible", "max_epr_rms_V"], descending=[True, False]
        )
    elif sort_by == "max_epr_desc":
        df = df.sort(by="max_epr_rms_V", descending=True)
    elif sort_by == "name":
        df = df.sort(by="name")
    else:  # pragma: no cover -- guarded by Literal type, defensive
        raise ValueError(
            f"sort_by must be one of "
            f"'max_epr_asc' | 'max_epr_desc' | 'name', got {sort_by!r}."
        )

    return df

summarize

summarize(
    frame: DataFrame,
    value: str,
    *,
    by: Optional[Sequence[str]] = None,
    quantiles: Sequence[float] = DEFAULT_QUANTILES,
) -> pl.DataFrame

Reduce one column to count, spread, quantiles and extremes.

Parameters:

Name Type Description Default
frame DataFrame

Long-format results, e.g. from :meth:~groundinsight.simulation.sweep.SweepResult.buses.

required
value str

Numeric column to summarise.

required
by sequence of str

Grouping columns. Without them the whole frame is one group.

None
quantiles sequence of float

Quantiles in [0, 1]. Each becomes a column p05, p50, ...

DEFAULT_QUANTILES

Returns:

Type Description
DataFrame

One row per group: the grouping columns, then n, n_null, n_nan, mean, std, min, the quantiles, and max. Sorted by the grouping columns so repeated runs produce identical output.

Raises:

Type Description
ValueError

If a named column is missing, if the value column is not numeric, or if a quantile lies outside [0, 1].

Notes

Read n_nan before the statistics. Polars counts a NaN as a value, not as a null: it lands in n, not in n_null, it propagates through mean, std and every quantile, and min / max skip it -- so a single NaN leaves a summary in which the extremes look sound and the mean is NaN, with nothing in the row saying why. That is a realistic input here rather than a hypothetical: a sweep point that failed under on_error="record" writes NaN into the value column. n_nan is the column that says how many, and it is 0 for an integer column, which cannot carry one.

Examples:

>>> import polars as pl
>>> from groundinsight.analysis import summarize
>>> frame = pl.DataFrame({"bus_name": ["A", "A", "B"], "EPR_V": [10.0, 30.0, 5.0]})
>>> summary = summarize(frame, "EPR_V", by=["bus_name"])
>>> summary.select("bus_name", "n", "mean", "max").rows()
[('A', 2, 20.0, 30.0), ('B', 1, 5.0, 5.0)]
Source code in src/groundinsight/analysis/statistics.py
def summarize(
    frame: pl.DataFrame,
    value: str,
    *,
    by: Optional[Sequence[str]] = None,
    quantiles: Sequence[float] = DEFAULT_QUANTILES,
) -> pl.DataFrame:
    """
    Reduce one column to count, spread, quantiles and extremes.

    Parameters
    ----------
    frame : pl.DataFrame
        Long-format results, e.g. from
        :meth:`~groundinsight.simulation.sweep.SweepResult.buses`.
    value : str
        Numeric column to summarise.
    by : sequence of str, optional
        Grouping columns. Without them the whole frame is one group.
    quantiles : sequence of float, optional
        Quantiles in ``[0, 1]``. Each becomes a column ``p05``, ``p50``, ...

    Returns
    -------
    pl.DataFrame
        One row per group: the grouping columns, then ``n``, ``n_null``,
        ``n_nan``, ``mean``, ``std``, ``min``, the quantiles, and ``max``.
        Sorted by the grouping columns so repeated runs produce identical
        output.

    Raises
    ------
    ValueError
        If a named column is missing, if the value column is not numeric, or if
        a quantile lies outside ``[0, 1]``.

    Notes
    -----
    **Read ``n_nan`` before the statistics.** Polars counts a NaN as a
    *value*, not as a null: it lands in ``n``, not in ``n_null``, it
    propagates through ``mean``, ``std`` and every quantile, and ``min`` /
    ``max`` skip it -- so a single NaN leaves a summary in which the extremes
    look sound and the mean is NaN, with nothing in the row saying why. That
    is a realistic input here rather than a hypothetical: a sweep point that
    failed under ``on_error="record"`` writes NaN into the value column.
    ``n_nan`` is the column that says how many, and it is ``0`` for an integer
    column, which cannot carry one.

    Examples
    --------
    >>> import polars as pl
    >>> from groundinsight.analysis import summarize
    >>> frame = pl.DataFrame({"bus_name": ["A", "A", "B"], "EPR_V": [10.0, 30.0, 5.0]})
    >>> summary = summarize(frame, "EPR_V", by=["bus_name"])
    >>> summary.select("bus_name", "n", "mean", "max").rows()
    [('A', 2, 20.0, 30.0), ('B', 1, 5.0, 5.0)]
    """
    missing = [c for c in [value, *(by or [])] if c not in frame.columns]
    if missing:
        raise ValueError(
            f"Column(s) {missing} are not in the frame. Available: "
            f"{frame.columns}."
        )
    if not frame.schema[value].is_numeric():
        raise ValueError(
            f"Column '{value}' has dtype {frame.schema[value]}, which cannot be "
            f"summarised numerically. Cast it, or group on it with `by=` "
            f"instead of summarising it."
        )
    bad = [q for q in quantiles if not 0.0 <= q <= 1.0]
    if bad:
        raise ValueError(f"Quantile(s) {bad} lie outside [0, 1].")

    # ``is_nan`` is only defined on the float dtypes; an integer column cannot
    # carry a NaN, so the count is a constant zero there rather than an error.
    n_nan = (
        pl.col(value).is_nan().sum().alias("n_nan")
        if frame.schema[value].is_float()
        else pl.lit(0, dtype=pl.UInt32).alias("n_nan")
    )
    aggregations = [
        pl.col(value).count().alias("n"),
        pl.col(value).null_count().alias("n_null"),
        n_nan,
        pl.col(value).mean().alias("mean"),
        pl.col(value).std().alias("std"),
        pl.col(value).min().alias("min"),
    ]
    aggregations += [
        pl.col(value).quantile(q, interpolation="linear").alias(_quantile_name(q))
        for q in quantiles
    ]
    aggregations.append(pl.col(value).max().alias("max"))

    if by:
        return frame.group_by(list(by)).agg(aggregations).sort(list(by))
    return frame.select(aggregations)

thermal_equivalent_current

thermal_equivalent_current(
    i_k: float, m: float, n_factor: float = 1.0
) -> float

Thermally equivalent short-time current I_th = I_k'' * sqrt(m + n).

Parameters:

Name Type Description Default
i_k float

RMS short-circuit current I_k'' in amperes. Must be non-negative.

required
m float

DC heat-effect factor from :func:iec60909_m. Must be non-negative.

required
n_factor float

AC-decay heat factor n in (0, 1]. 1.0 for the far-from-generator faults typical of distribution grounding studies. The former keyword n is accepted as a deprecated alias.

1.0

Returns:

Type Description
float

The thermally equivalent current in amperes.

Raises:

Type Description
ValueError

If i_k or m is negative, or n_factor is not in (0, 1].

Notes

The bounds are enforced rather than clipped because violating them fails silently downwards: a negative m, or an n above one supplied in place of a correct smaller value, changes sqrt(m + n) without any visible symptom, and a too-small result under-estimates the thermal stress -- the unsafe direction for a limit check. A caller that hands in such a value has a bug upstream and should hear about it.

Examples:

>>> round(thermal_equivalent_current(1000.0, 0.0, 1.0), 6)
1000.0
Source code in src/groundinsight/analysis/shortcircuit.py
@renamed_parameters(n="n_factor")
def thermal_equivalent_current(
    i_k: float, m: float, n_factor: float = 1.0
) -> float:
    """
    Thermally equivalent short-time current ``I_th = I_k'' * sqrt(m + n)``.

    Parameters
    ----------
    i_k : float
        RMS short-circuit current ``I_k''`` in amperes. Must be
        non-negative.
    m : float
        DC heat-effect factor from :func:`iec60909_m`. Must be
        non-negative.
    n_factor : float
        AC-decay heat factor ``n`` in ``(0, 1]``. ``1.0`` for the
        far-from-generator faults typical of distribution grounding
        studies. The former keyword ``n`` is accepted as a deprecated
        alias.

    Returns
    -------
    float
        The thermally equivalent current in amperes.

    Raises
    ------
    ValueError
        If ``i_k`` or ``m`` is negative, or ``n_factor`` is not in ``(0, 1]``.

    Notes
    -----
    The bounds are enforced rather than clipped because violating them
    fails *silently downwards*: a negative ``m``, or an ``n`` above one
    supplied in place of a correct smaller value, changes ``sqrt(m + n)``
    without any visible symptom, and a too-small result under-estimates the
    thermal stress -- the unsafe direction for a limit check. A caller that
    hands in such a value has a bug upstream and should hear about it.

    Examples
    --------
    >>> round(thermal_equivalent_current(1000.0, 0.0, 1.0), 6)
    1000.0
    """
    if i_k < 0:
        raise ValueError(f"i_k must be non-negative, got {i_k!r}.")
    if m < 0:
        raise ValueError(f"m must be non-negative, got {m!r}.")
    if not 0.0 < n_factor <= 1.0:
        raise ValueError(f"n_factor must lie in (0, 1], got {n_factor!r}.")
    return i_k * math.sqrt(m + n_factor)