Skip to content

Electrical network

Numerical core of groundinsight. ElectricalNetwork assembles the nodal admittance matrix \(Y(f)\) per frequency, fills the right-hand side with source and mutual-coupling Norton currents, solves the linear system via sparse LU and derives branch currents, reduction factors and grounding impedances.

Physical / modelling context

For each frequency \(f\) in the network's frequency list the model reduces to a sparse complex linear system

\[ Y(f)\,\underline{u}(f) \;=\; \underline{i}(f), \qquad \underline{u}(f) \;=\; Y(f)^{-1}\,\underline{i}(f), \]

with

  • \(Y(f)\) the nodal admittance matrix. The diagonal holds the admittances of the bus electrodes, \(1/Z_B(f, \rho)\) (the symbol \(Z_E\) is reserved for the earthing impedance of EN 50522, see the glossary); the branch self-admittances \(1/Z_b(f, l)\) of the branches with grounding_conductor=True join the buses they connect.
  • \(\underline{u}(f)\) the bus-EPR vector.
  • \(\underline{i}(f)\) the source currents (scaled by the fault scaling at \(f\)) plus the Norton equivalents of the mutual coupling between phase and grounding conductor along the source-to-fault path.

After the per-frequency solve the network derives:

  • Branch currents from \(\Delta u\) and the impressed mutual current.
  • Two reduction factors. value is the EPR ratio \(|\underline{u}_\text{with}|/|\underline{u}_\text{without}|\) at the fault bus, where the second solve omits the mutual Norton sources — a property of the line, not the reduction factor of EN 50522. value_current is \(|I_E|/|I_F|\), the earth-return current over the fault current: the reduction factor \(r\) of EN 50522. Both are stored in ResultReductionFactor (which one is which).
  • Earthing impedance \(Z_G = Z_E = Z_\text{dp}(F)\) per frequency (EN 50522): the driving-point impedance of the earthing network at the fault bus -- electrodes and shields, without the coupling and without Thevenin loop closures. The earthing voltage \(U_E\) is the EPR at the fault bus. The current-weighted mean of the earth group and its quotient by \(I_E\), reported as \(U_E\)/\(Z_E\) before audit pass 19, remain available as u_earthing_group / z_earthing_group.

The ElectricalNetwork is held as a PrivateAttr of Network, not exposed in the JSON / DB serialisation; it carries the raw NumPy / SciPy working arrays used by the LU solver.

Example

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

# Assume `net` was built via gi.create_* factories with a fault `f1`.
gi.run_fault(network=net, fault="f1")  # attaches net.electrical_network

# Inspect derived quantities through the public Network accessors:
df_bus = net.res_buses()           # EPR per bus
df_branch = net.res_branches()     # branch currents
df_zg = net.res_all_impedances()   # grounding impedance + reduction factor

Direct use of ElectricalNetwork is rarely needed; access is mostly via gi.run_fault and the Network.res_* DataFrame accessors.

API reference

electrical_network

The numerical kernel of the fault solve, built from the core models.

:class:ElectricalNetwork computes with the matrix form of the network:

Y * u = i u = Y^-1 * i

where:

Y - admittance matrix, branches and buses are used to build this matrix u - vector of bus voltages (earth potential rise per bus) i - vector of source injections plus the Norton-equivalent injections that represent the inductive coupling between phase conductors and shield (grounding) conductors along each branch.

Sign convention for the mutual coupling (see _add_mutual_currents): U_from - U_to = Z_self * I_s - Z_mutual * I_p where I_p is the phase current through the branch in from->to direction and I_s is the shield current in the same direction. The induced EMF enters the nodal form as a Norton current i_mut = (Z_mutual / Z_self) * I_p which is injected as +i_mut out of the from bus (nodal: i_vector[from] -= i_mut) and +i_mut into the to bus (nodal: i_vector[to] += i_mut).

Two strategies are available to determine the phase current I_p per branch: 1) Path-based (auto_phase_currents=False, the default of this class; run_fault(phase_current_mode="paths")). For every simple path from source to fault, the branch direction is derived from the actual path traversal (no index heuristic). The user may scale the contribution per branch via Branch.parallel_coefficient, the knob for splitting current between parallel paths in this mode. 2) Automatic distribution (auto_phase_currents=True; the default of :func:~groundinsight.run_fault, phase_current_mode="auto"). A reduced phase-only network is solved with +I at each source bus and the fault bus as reference. The resulting branch currents are used directly. In this mode parallel_coefficient is ignored. This mode is topology-agnostic and is the intended integration point for an external phase-current source (e.g. pandapower single-phase short-circuit results).

Sparse kernel

Both linear systems of a frequency are sparse -- a grounding network has a few entries per row -- and the kernel treats them that way end to end.

Model values as arrays. The impedance dictionaries of all buses, branches and voltage sources are read once per assembly into (elements, F) arrays (:class:_NetworkTables), with the 0 Hz stand-in applied to them as a whole. Every later stage indexes into those arrays instead of resolving one impedance per element and frequency in Python.

Index tables instead of dense matrices. Where a stamp lands -- a bus diagonal, the four entries of a grounding branch or of a Thevenin loop closure -- depends on the topology only. The positions are laid out once per network (:class:_StampPattern: CSC indices/indptr and the entry of every stamp); a frequency then costs one vector of admittances and one summation per entry, straight into the CSC matrix the LU factorises (:attr:ElectricalNetwork.Y_sparse). A dense n x n matrix kept per frequency would make the memory grow as n**2 * F; Y_matrices is therefore only a dense view that materialises a matrix when someone reads it.

One factorisation, many right-hand sides. The phase-conductor network is the same matrix for every source, so it is factorised once per frequency (:func:scipy.sparse.linalg.splu) and solved for all sources as the columns of one right-hand side. A dense n x n solve per source and frequency would be the dominant cost of a run, growing faster than n**2.

Result objects with the collector paused. A solve creates one :class:ComplexNumber per element, quantity and frequency. Those objects form no reference cycles, but their sheer number keeps triggering the cyclic garbage collector, which then walks the whole network model each time. The result rows are therefore built inside :func:_gc_paused, which restores the collector afterwards.

Program order, kept on purpose. Matrices are assembled from stamps whose contributions are summed entry by entry in the order an element-by-element dense assembly adds them (:func:_assemble_csc), so the sums are those of that reference. What differs from it is rounding: the admittances come from NumPy's complex division, which differs from Python's in the last bit for about a quarter of all values, and the factorisation is a sparse LU instead of LAPACK's dense one. On the badly conditioned phase network of a long radial feeder the sparse LU is the more accurate of the two.

ElectricalNetwork

ElectricalNetwork(
    network: Network,
    auto_phase_currents: bool = False,
    *,
    input_checks: bool = False,
)

Represents the electrical properties of a network, enabling calculations.

This class handles the construction of admittance matrices, voltage and current vectors, and performs network analysis to compute results such as bus voltages, branch currents, reduction factors, and grounding impedances.

Parameters:

Name Type Description Default
network Network

The Network instance containing buses, branches, sources, and faults.

required
auto_phase_currents bool

If True the phase current through each branch is computed by solving a reduced phase-only network (Variant B). If False (default) the phase current is derived from the enumerated source-to-fault paths using each branch's parallel_coefficient (Variant A). Defaults to False.

False
input_checks bool

Run the input checks of :func:~groundinsight.run_fault while the vectors are assembled: a source that reaches the fault with a value at none of the network frequencies raises ValueError (USE3/F8); partial source coverage, an incomplete Fault.scalings (F7) and a Thevenin source driving coupled branches (F5) are announced. :func:~groundinsight.build_electrical_network, the step run_fault uses, turns them on. Other users of the assembly leave them off -- the phase-split probe of the transient solver injects 1 A per source whatever its stationary values, and a source that only carries a transient waveform is legitimate there. Defaults to False.

False
Notes

An instance is copied and pickled together with the :class:Network it is attached to (copy.deepcopy(network), network.model_copy(deep=True), pickle.dumps(network)). Every attribute travels with it except the entries named in :attr:_UNCOPYABLE_CACHES: those hold SciPy SuperLU factorisations, which can be neither pickled nor deep-copied. They are pure caches -- a copy starts without them and the solver refactorises when it needs a factor again -- so dropping them loses no information. The back-reference :attr:network is copied through the copy memo and therefore points at the copied network, which is what :meth:matches_network_state needs.

Initialize the ElectricalNetwork with a given Network model.

Sets up necessary data structures and initializes the network calculations; the parameters are documented on the class.

Source code in src/groundinsight/electrical_network.py
def __init__(
    self,
    network: Network,
    auto_phase_currents: bool = False,
    *,
    input_checks: bool = False,
):
    """
    Initialize the ElectricalNetwork with a given Network model.

    Sets up necessary data structures and initializes the network
    calculations; the parameters are documented on the class.
    """
    self.network = network
    self.auto_phase_currents = auto_phase_currents
    self._input_checks = input_checks
    self.bus_indices = {}
    # Nodal admittance matrix per frequency, CSC (the solver's matrices).
    self.Y_sparse: Dict[float, csc_matrix] = {}
    # Dense view of the same matrices, materialised on access only; see
    # :class:`_DenseYView`. Kept for code that reads ``Y_matrices``.
    self.Y_matrices = {}
    self.u_vectors = {}  # Voltage vectors for each frequency
    self.u_vectors_no_mutual = {}  # Voltage vectors without mutual currents
    self.i_vectors_no_mutual = {}  # Current vectors without mutual currents
    self.i_vectors = {}  # Current vectors for each frequency
    # Sparse LU factorisation of Y(f), kept per frequency by
    # ``solve_network`` so that ``compute_reduction_factors`` can reuse it
    # for the second right-hand side instead of factorising the same
    # matrix a second time with a dense solver. Cleared whenever the
    # matrices are rebuilt.
    self._lu_factors = {}
    self.results: Result = Result()  # Stores the calculation results
    self.i_mutuals = {}  # Store mutual currents per frequency per branch
    self.total_source_currents = {}  # Store total source currents per frequency
    # Source-only nodal injection per frequency, i.e. the ``i`` vector *before*
    # the mutual Norton equivalents are added on top. This is the current that
    # physically enters the grounding system through a lumped connection at the
    # bus -- the earthing conductor (EN 50522 "Erdungsleiter") -- as opposed to
    # ``ResultBus.ia``, which is the share dissipated into the soil through the
    # earth electrode ("Erder"). The mutual terms are a distributed modelling
    # artefact of the line/shield coupling and are deliberately excluded here:
    # no lumped conductor carries them into the node.
    self.source_injections = {}
    self.phase_currents = {}  # Signed phase current per branch per frequency
    # One-shot latch so the phase-impedance proxy warning is emitted once
    # per network, not once per frequency of the sweep.
    self._phase_proxy_warned = False
    # Sources that reach the fault through the earthing network but not
    # through the phase network, with the frequencies concerned; reported
    # once per source after the frequency loop (PH9).
    self._sources_without_phase_path: Dict[str, List[float]] = {}
    # Substitute impedance per frequency for elements that are a short
    # circuit there. Only 0 Hz can have an entry, and only when the network
    # actually contains such an element. See _dc_substitute_at.
    self._dc_substitutes: Dict[float, float] = {}
    # Digest of the model values the matrices below were assembled from.
    # Filled once the assembly is done; see :meth:`state_fingerprint`.
    self._build_fingerprint: Optional[tuple] = None
    # The model values of this assembly as arrays, gathered once (P6);
    # see :class:`_NetworkTables` and :meth:`_network_tables`.
    self._tables: Optional[_NetworkTables] = None
    # The grounding admittance stamped on the diagonal per active bus and
    # frequency, ``(n, F)``; see :meth:`grounding_shunts`.
    self._bus_admittance: Optional[np.ndarray] = None
    # Where every stamp of Y lands, and the admittances of the stamps
    # that are not bus electrodes (grounding branches, Thevenin loop
    # closures), ``(stamps, F)`` each. Kept so that Y can be re-assembled
    # for other bus admittances without touching the model (P4); see
    # :meth:`_assemble_nodal`.
    self._stamp_pattern: Optional[_StampPattern] = None
    self._grid_admittance: Optional[np.ndarray] = None
    self._loop_admittance: Optional[np.ndarray] = None
    # The electrode currents ``u / Z`` per active bus and frequency as
    # ``solve_network`` reports them in ``ResultBus.ia``, and where a bus
    # has an electrode at all; the earth-return split reads these (P6).
    self._electrode_currents: Optional[np.ndarray] = None
    self._electrode_usable: Optional[np.ndarray] = None

    self._initialize()
    # The tables were gathered from this very state a moment ago; digest
    # them instead of reading the model a second time.
    self._build_fingerprint = self._network_tables().fingerprint(
        self.network.active_fault
    )

__getstate__

__getstate__() -> Dict[str, object]

State for pickle and copy.deepcopy, without the factor caches.

copy.deepcopy and pickle both go through this method, so one override covers both. The caches are replaced by empty dictionaries, not removed, so that every method can keep reading them as before.

Returns:

Type Description
Dict[str, object]

A shallow copy of the instance dictionary with every entry of :attr:_UNCOPYABLE_CACHES replaced by an empty dict.

Source code in src/groundinsight/electrical_network.py
def __getstate__(self) -> Dict[str, object]:
    """
    State for ``pickle`` and ``copy.deepcopy``, without the factor caches.

    ``copy.deepcopy`` and ``pickle`` both go through this method, so one
    override covers both. The caches are replaced by empty dictionaries,
    not removed, so that every method can keep reading them as before.

    Returns
    -------
    Dict[str, object]
        A shallow copy of the instance dictionary with every entry of
        :attr:`_UNCOPYABLE_CACHES` replaced by an empty dict.
    """
    state = self.__dict__.copy()
    for name in self._UNCOPYABLE_CACHES:
        if name in state:
            state[name] = {}
    return state

compute_branch_currents

compute_branch_currents()

Compute branch currents for each frequency and store them in the Result object.

This method calculates the current flowing through each branch based on the bus voltages and branch impedances. The results are stored as ResultBranch instances within the network's results object.

Source code in src/groundinsight/electrical_network.py
def compute_branch_currents(self):
    """
    Compute branch currents for each frequency and store them in the Result object.

    This method calculates the current flowing through each branch based on the bus voltages
    and branch impedances. The results are stored as `ResultBranch` instances within the
    network's results object.
    """
    fault_name = self.network.active_fault
    if fault_name is None:
        raise ValueError("No active fault set in the network.")

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

    result = self.network.results[fault_name]
    tables = self._network_tables()
    frequencies = self.network.frequencies

    # Inactive branches and branches with at least one inactive endpoint
    # are open-circuited: their shield current is zero by construction, as
    # is that of a branch without grounding conductor and of a frequency
    # whose self impedance is missing or open. Everything else carries
    # (u_to - u_from) * Y_self plus the stored mutual term, whose sign
    # already combines with that difference (see _add_mutual_currents).
    conducting = (
        (tables.branch_in_net & tables.branch_grounding)[:, None]
        & tables.self_present
        & ~_open_mask(tables.self_z)
    )
    admittance = _reciprocal(tables.self_z, conducting)
    potentials = self._stacked(self.u_vectors)
    from_idx = np.where(tables.branch_from >= 0, tables.branch_from, 0)
    to_idx = np.where(tables.branch_to >= 0, tables.branch_to, 0)
    names = tables.branch_names
    mutual = np.zeros(admittance.shape, dtype=complex)
    for j, freq in enumerate(frequencies):
        stored = self.i_mutuals.get(freq, {})
        if stored:
            mutual[:, j] = np.fromiter(
                (stored.get(name, 0) for name in names), dtype=complex,
                count=len(names),
            )
    current = np.zeros(admittance.shape, dtype=complex)
    with np.errstate(over="ignore", invalid="ignore"):
        delta = potentials[to_idx] - potentials[from_idx]
        current[conducting] = (delta * admittance + mutual)[conducting]
    result.branches.extend(
        self._result_rows(ResultBranch, names, frequencies, {"i_s": current})
    )

    # Update the result in the network's results dictionary
    self.network.results[fault_name] = result
    self.results = result  # Update self.results

compute_grounding_impedance

compute_grounding_impedance()

Compute the grounding impedance for the fault bus.

The grounding impedance is the earthing impedance of EN 50522 at the fault bus::

Z_G = Z_E = Z_dp(F)

the driving-point impedance of the earthing network at the fault bus: the voltage one ampere injected there raises the bus to against remote earth, with every electrode and shield in place, without the inductive coupling and without the Thevenin loop closures of voltage sources. It is a property of the earthing system -- what an earthing-impedance measurement at the station sees, the stations bonded to it through cable shields included -- and it is computed alongside the reduction factors as ResultReductionFactor.z_earthing, which this method copies. With U_E the EPR at the fault bus and r = |1 - Z_m/Z_s| the norm's chain U_E = r * 3*I_0 * Z_E then holds where the norm's assumptions hold (a fault far from the infeed on a long bonded run), as a physical statement rather than by construction.

The quotient U_E / I_E over the earth group is not used for Z_E (it is kept as z_earthing_group): on a long homogeneous chain it comes out 44.5 % below the driving-point impedance. docs/explanation/reduction-factors.md and docs/api/electrical_network.md state the same definition.

The results are stored in the network's results object.

Source code in src/groundinsight/electrical_network.py
def compute_grounding_impedance(self):
    """
    Compute the grounding impedance for the fault bus.

    The grounding impedance is the earthing impedance of EN 50522 at the
    fault bus::

        Z_G = Z_E = Z_dp(F)

    the driving-point impedance of the earthing network at the fault bus:
    the voltage one ampere injected there raises the bus to against remote
    earth, with every electrode and shield in place, without the inductive
    coupling and without the Thevenin loop closures of voltage sources. It
    is a property of the earthing system -- what an earthing-impedance
    measurement at the station sees, the stations bonded to it through
    cable shields included -- and it is computed alongside the reduction
    factors as ``ResultReductionFactor.z_earthing``, which this method
    copies. With ``U_E`` the EPR at the fault bus and
    ``r = |1 - Z_m/Z_s|`` the norm's chain ``U_E = r * 3*I_0 * Z_E`` then
    holds where the norm's assumptions hold (a fault far from the infeed
    on a long bonded run), as a physical statement rather than by
    construction.

    The quotient ``U_E / I_E`` over the earth group is not used for
    ``Z_E`` (it is kept as ``z_earthing_group``): on a long homogeneous
    chain it comes out 44.5 % below the driving-point impedance.
    ``docs/explanation/reduction-factors.md`` and
    ``docs/api/electrical_network.md`` state the same definition.

    The results are stored in the network's results object.
    """
    fault_name = self.network.active_fault
    if fault_name is None:
        raise ValueError("No active fault set in the network.")

    fault_bus = self.network.faults[fault_name].bus

    grounding_impedances = (
        {}
    )  # Dictionary to store grounding impedance per frequency

    frequencies = self.network.frequencies

    result = self.network.results[fault_name]

    # Ensure that reduction factors are computed
    if not result.reduction_factor:
        raise ValueError(
            "Reduction factors not computed. Please compute reduction factors before grounding impedance."
        )

    for freq in frequencies:
        # Z_E = Z_dp(F), computed alongside the reduction factors (F4).
        z_earthing = result.reduction_factor.z_earthing.get(freq)
        if z_earthing is not None:
            grounding_impedances[freq] = ComplexNumber(
                real=complex(z_earthing).real, imag=complex(z_earthing).imag
            )
            continue

        # The fault bus reaches remote earth only through a Thevenin loop
        # (no bus connected to it through shields carries an electrode):
        # the earthing network alone presents no finite impedance there.
        grounding_impedances[freq] = None

    # Store the grounding impedance in the result
    result_grounding_impedance = ResultGroundingImpedance(
        fault_bus=fault_bus, value=grounding_impedances
    )
    result.grounding_impedance = result_grounding_impedance

    # Update the result in the network's results dictionary
    self.network.results[fault_name] = result
    self.results = result  # Update self.results

compute_phase_currents

compute_phase_currents(
    freq: float, sources_with_path
) -> Dict[str, complex]

Compute the signed phase current per branch at a given frequency.

Internal API: also used by :mod:groundinsight.simulation.transient; not exported from groundinsight and free to change in any release.

In the path-based mode (auto_phase_currents=False) the contributions are accumulated from each source's paths to the active fault. Direction comes from the actual path traversal (from-bus vs to-bus ordering) and the magnitude is scaled by Branch.parallel_coefficient. A branch that lies on any path receives exactly one contribution per source (not one per path): the paths of a source are taken as one set of branches.

In the automatic mode (auto_phase_currents=True) a reduced phase-only network is solved per source using the branch self-impedance as the phase impedance proxy and the fault bus as the reference node. The resulting branch current is used directly and parallel_coefficient is ignored.

Parameters:

Name Type Description Default
freq float

The frequency at which to compute the phase currents.

required
sources_with_path Iterable[str]

Names of sources that have a path to the active fault.

required

Returns:

Type Description
Dict[str, complex]

Mapping from branch name to signed phase current (positive when the current flows from from_bus to to_bus).

Source code in src/groundinsight/electrical_network.py
def compute_phase_currents(
    self, freq: float, sources_with_path
) -> Dict[str, complex]:
    """
    Compute the signed phase current per branch at a given frequency.

    Internal API: also used by :mod:`groundinsight.simulation.transient`;
    not exported from ``groundinsight`` and free to change in any release.

    In the path-based mode (``auto_phase_currents=False``) the contributions are
    accumulated from each source's paths to the active fault. Direction comes from
    the actual path traversal (from-bus vs to-bus ordering) and the magnitude is
    scaled by ``Branch.parallel_coefficient``. A branch that lies on any path
    receives exactly one contribution per source (not one per path): the paths
    of a source are taken as one set of branches.

    In the automatic mode (``auto_phase_currents=True``) a reduced phase-only
    network is solved per source using the branch self-impedance as the phase
    impedance proxy and the fault bus as the reference node. The resulting branch
    current is used directly and ``parallel_coefficient`` is ignored.

    Parameters
    ----------
    freq : float
        The frequency at which to compute the phase currents.
    sources_with_path : Iterable[str]
        Names of sources that have a path to the
        active fault.

    Returns
    -------
    Dict[str, complex]
        Mapping from branch name to signed phase current (positive when
        the current flows from ``from_bus`` to ``to_bus``).
    """
    if self.auto_phase_currents:
        return self._compute_phase_currents_auto(freq, sources_with_path)
    return self._compute_phase_currents_from_paths(freq, sources_with_path)

compute_reduction_factors

compute_reduction_factors()

Compute the reduction factors by solving the network with and without mutual currents.

This method calculates how much the presence of mutual currents affects the Earth Potential Rise (EPR). The reduction factors are stored in the network's results object.

Warns:

Type Description
ModelAssumptionWarning

REDUCTION_FACTOR_UNDEFINED (elements: the fault and its bus) for a frequency at which the EPR-based reduction factor is undefined -- the no-mutual EPR of the fault bus is rounding noise, or the solve without mutual coupling failed there.

Notes

The no-mutual system uses the same Y(f) that :meth:solve_network has already factorised, only with a different right-hand side. The sparse LU factors kept in self._lu_factors are therefore reused and the second solve costs one triangular back-substitution. The earlier numpy.linalg.solve refactorised the matrix densely -- 2.5 s of a 6.9 s profile on a 200-bus chain over 50 frequencies -- and did so with a different singularity treatment than the first solve, so the two paths could disagree about whether the same matrix was solvable. Frequencies without a stored factor (compute_reduction_factors called on its own) factorise :attr:Y_sparse afresh with the same sparse LU.

Source code in src/groundinsight/electrical_network.py
def compute_reduction_factors(self):
    """
    Compute the reduction factors by solving the network with and without mutual currents.

    This method calculates how much the presence of mutual currents affects the Earth Potential Rise (EPR).
    The reduction factors are stored in the network's results object.

    Warns
    -----
    ModelAssumptionWarning
        ``REDUCTION_FACTOR_UNDEFINED`` (elements: the fault and its bus)
        for a frequency at which the EPR-based reduction factor is
        undefined -- the no-mutual EPR of the fault bus is rounding noise,
        or the solve without mutual coupling failed there.

    Notes
    -----
    The no-mutual system uses the *same* ``Y(f)`` that
    :meth:`solve_network` has already factorised, only with a different
    right-hand side. The sparse LU factors kept in ``self._lu_factors``
    are therefore reused and the second solve costs one triangular
    back-substitution. The earlier ``numpy.linalg.solve`` refactorised
    the matrix densely -- 2.5 s of a 6.9 s profile on a 200-bus chain
    over 50 frequencies -- and did so with a *different* singularity
    treatment than the first solve, so the two paths could disagree
    about whether the same matrix was solvable. Frequencies without a
    stored factor (``compute_reduction_factors`` called on its own)
    factorise :attr:`Y_sparse` afresh with the same sparse LU.
    """
    fault_name = self.network.active_fault
    if fault_name is None:
        raise ValueError("No active fault set in the network.")

    fault_bus = self.network.faults[fault_name].bus
    fault_bus_idx = self.bus_indices[fault_bus]

    reduction_factors = {}
    uepr_with_mutual = {}
    uepr_without_mutual = {}

    frequencies = self.network.frequencies

    # Step 1: Solve network with mutual currents (already done)
    # Voltages are stored in self.u_vectors

    # Store uepr with mutual currents
    for freq in frequencies:
        voltage = self.u_vectors[freq][fault_bus_idx]
        uepr_with_mutual[freq] = voltage
    # Step 2: Create i_vectors without mutual currents
    self._construct_vectors_no_mutual()
    # Step 3: Solve network without mutual currents
    self.u_vectors_no_mutual = {}
    for freq in frequencies:
        i_vector = self.i_vectors_no_mutual[freq]
        lu = self._lu_factors.get(freq)
        try:
            # Solve for u_vector without mutual currents. The LU factors
            # of Y(f) come from ``solve_network``; only a caller that
            # skipped it has to pay for a fresh factorisation.
            if lu is None:
                lu = splu(self.Y_sparse[freq])
            u_vector = lu.solve(i_vector)
            self.u_vectors_no_mutual[freq] = u_vector

        except (np.linalg.LinAlgError, RuntimeError) as e:
            # Result-relevant: the EPR-based reduction factor of this
            # frequency is reported as None, and the reader has to know
            # why (GUI4). The traceback stays available at DEBUG level.
            logger.debug(
                "Solve without mutual currents failed at %s Hz.",
                freq,
                exc_info=True,
            )
            emit(
                ModelAssumptionWarning,
                f"Fault '{fault_name}': the solve without mutual coupling "
                f"failed at {freq:g} Hz ({type(e).__name__}: {e}), so the "
                f"EPR-based reduction factor (ResultReductionFactor.value) "
                f"is undefined there and reported as None. The solution "
                f"with coupling -- the EPR and every current -- is not "
                f"affected.",
                code="REDUCTION_FACTOR_UNDEFINED",
                elements=[("fault", fault_name), ("bus", fault_bus)],
                stacklevel=3,
            )
            continue

    # Store uepr without mutual currents. A frequency whose no-mutual solve
    # failed above is absent from ``u_vectors_no_mutual``; it is skipped here
    # and reported as ``None`` rather than raising a bare KeyError out of the
    # solver core.
    for freq in frequencies:
        if freq not in self.u_vectors_no_mutual:
            continue
        voltage = self.u_vectors_no_mutual[freq][fault_bus_idx]
        uepr_without_mutual[freq] = voltage

    # Z_E of EN 50522 (F4): the driving-point impedance of the earthing
    # network at the fault bus. Computed first, because it is also the
    # yardstick of the noise rule for the EPR-based factor below.
    z_driving_point, z_undefined = self._earthing_driving_points(fault_bus_idx)

    # Step 4: Compute reduction factors
    epr_undefined: List[Tuple[float, float, float]] = []
    for freq in frequencies:
        if freq not in uepr_without_mutual:
            reduction_factors[freq] = None
            continue
        v_with = uepr_with_mutual[freq]
        v_without = uepr_without_mutual[freq]
        # Compute magnitudes
        mag_with = abs(v_with)
        mag_without = abs(v_without)

        # The quotient means something only while its denominator stands
        # above rounding noise (P9). A fault bus that is at zero potential
        # in exact arithmetic -- every source on the fault bus, or a source
        # behind a dead end that returns all its current through one
        # shield -- comes out at ~1e-14 V, and the ratio of two such
        # numbers would be reported as a reduction factor (0.449 =
        # 5.1e-14 V / 1.1e-13 V for a source behind a dead end, next to
        # 320 V at the source tower). The yardstick is the EPR the fault
        # current would raise the fault bus to on its own,
        # |I_F| * |Z_FF|: an exact zero sits at ~1e-16 of it, while a
        # near-ideal fault-bus electrode -- a small but accurate EPR --
        # stays at the order of |1 - k| of it.
        # (The largest EPR of the solution is no yardstick: it calls the
        # near-ideal electrode noise.)
        i_fault = complex(self.total_source_currents.get(freq) or 0)
        reference = 0.0
        if i_fault != 0:
            z_ff = z_driving_point.get(freq)
            if z_ff is None:
                z_ff = self._solved_driving_point(freq, fault_bus_idx)
            reference = abs(i_fault) * (abs(z_ff) if z_ff is not None else 0.0)
        if mag_without > NOISE_REL * reference:
            reduction_factor = mag_with / mag_without
        else:
            reduction_factor = None
            # Said out loud only where the earthing network is excited at
            # all. Every source on the fault bus injects nothing anywhere:
            # that null case has no earth current and no factor by
            # definition, as it always had, and a study that scans every
            # bus as a fault location would otherwise repeat it per bus.
            if i_fault != 0 and self._is_excited(freq):
                epr_undefined.append((freq, mag_without, reference))
        reduction_factors[freq] = reduction_factor

    # Step 5: the current-based reduction factor -- see the method docstring.
    (
        reduction_factors_current,
        earth_currents,
        earth_buses,
        earthing_voltages,
        earthing_impedances,
        group_undefined,
    ) = self._compute_current_reduction_factors()

    self._report_undefined_reduction_quantities(
        fault_name, fault_bus, epr_undefined, group_undefined, z_undefined
    )

    # The two definitions answer different questions and only coincide in
    # the limit of ideally bonded stations. Saying so where they part
    # company beats leaving a factor of forty to be discovered later.
    self._warn_on_reduction_factor_divergence(
        reduction_factors, reduction_factors_current
    )

    # The EN 50522 quantities (F4): U_E is the EPR at the fault bus -- the
    # very number ResultBus reports there -- and Z_E the driving-point
    # impedance of the earthing network at the fault bus. The group mean
    # and its quotient by I_E, which carried these names before, stay
    # available as diagnostics.
    fault_currents = {
        freq: (
            None
            if self.total_source_currents.get(freq) is None
            else complex(self.total_source_currents[freq])
        )
        for freq in frequencies
    }
    fault_potentials = {
        freq: complex(self.u_vectors[freq][fault_bus_idx]) for freq in frequencies
    }

    # Store the reduction factors in the result
    result = self.network.results[fault_name]
    result_reduction_factor = ResultReductionFactor(
        fault_bus=fault_bus,
        value=reduction_factors,
        value_current=reduction_factors_current,
        i_fault=fault_currents,
        i_earth=earth_currents,
        earth_buses=earth_buses,
        u_earthing=fault_potentials,
        z_earthing=z_driving_point,
        u_earthing_group=earthing_voltages,
        z_earthing_group=earthing_impedances,
    )
    result.reduction_factor = result_reduction_factor

    # Update the result in the network's results dictionary
    self.network.results[fault_name] = result
    self.results = result  # Update self.results

earthed_buses

earthed_buses(freq: float) -> np.ndarray

Buses with a path to remote earth of their own at freq.

Internal API: also used by :mod:groundinsight.analysis.response; not exported from groundinsight and free to change in any release.

The admittance is the one the assembly stamped (0 Hz stand-in applied), so a missing, open ("nan") or non-finite electrode does not count.

Parameters:

Name Type Description Default
freq float

A frequency of the network.

required

Returns:

Type Description
ndarray

Boolean mask in :attr:bus_indices order.

Source code in src/groundinsight/electrical_network.py
def earthed_buses(self, freq: float) -> np.ndarray:
    """
    Buses with a path to remote earth of their own at ``freq``.

    Internal API: also used by :mod:`groundinsight.analysis.response`; not
    exported from ``groundinsight`` and free to change in any release.

    The admittance is the one the assembly stamped (0 Hz stand-in
    applied), so a missing, open (``"nan"``) or non-finite electrode does
    not count.

    Parameters
    ----------
    freq : float
        A frequency of the network.

    Returns
    -------
    numpy.ndarray
        Boolean mask in :attr:`bus_indices` order.
    """
    _, admittance = self.grounding_shunts(freq)
    return np.isfinite(admittance) & (admittance != 0)

earthing_admittance_matrix

earthing_admittance_matrix(freq: float) -> np.ndarray

Y(freq) of the earthing network alone, Thevenin loops removed.

The nodal matrix that is solved also carries the loop closures of the voltage sources (:meth:thevenin_loop_admittances). They belong to the fault loop, not to the earthing system, so a property of the earthing system -- its driving-point impedance at the fault bus, Z_E of EN 50522 -- is taken from this matrix instead. Without a voltage source it is a copy of the solved one.

Parameters:

Name Type Description Default
freq float

Frequency in Hz; Y_sparse[freq] must exist.

required

Returns:

Type Description
ndarray

A new dense array; the assembled matrix is not modified.

Notes

Like :attr:Y_matrices this is a dense view, materialised on request: Z_E itself is computed from the sparse form (:meth:_earthing_admittance_sparse), so run_fault never builds an n x n array for it.

Source code in src/groundinsight/electrical_network.py
def earthing_admittance_matrix(self, freq: float) -> np.ndarray:
    """
    ``Y(freq)`` of the earthing network alone, Thevenin loops removed.

    The nodal matrix that is solved also carries the loop closures of the
    voltage sources (:meth:`thevenin_loop_admittances`). They belong to
    the fault loop, not to the earthing system, so a property *of the
    earthing system* -- its driving-point impedance at the fault bus,
    ``Z_E`` of EN 50522 -- is taken from this matrix instead. Without a
    voltage source it is a copy of the solved one.

    Parameters
    ----------
    freq : float
        Frequency in Hz; ``Y_sparse[freq]`` must exist.

    Returns
    -------
    numpy.ndarray
        A new dense array; the assembled matrix is not modified.

    Notes
    -----
    Like :attr:`Y_matrices` this is a dense view, materialised on
    request: ``Z_E`` itself is computed from the sparse form
    (:meth:`_earthing_admittance_sparse`), so ``run_fault`` never builds
    an ``n x n`` array for it.
    """
    return self._earthing_admittance_sparse(freq).toarray()

grounding_shunts

grounding_shunts(
    freq: float,
) -> Tuple[np.ndarray, np.ndarray]

Grounding impedance of every active bus, and the admittance stamped.

Internal API: also used by :mod:groundinsight.analysis.response; not exported from groundinsight and free to change in any release.

The interface :func:~groundinsight.analysis.response.bus_response uses to take one bus's electrode back out of the assembled matrix. Subtracting exactly the value that was added -- rather than a reciprocal recomputed with a different rounding -- leaves an exact zero where the electrode was a bus's only connection, so such a system is still recognised as singular.

Parameters:

Name Type Description Default
freq float

A frequency of the network.

required

Returns:

Name Type Description
impedance ndarray

Resolved grounding impedance per bus in :attr:bus_indices order (0 Hz stand-in applied; nan where none is stored).

admittance ndarray

The admittance on the diagonal of :attr:Y_sparse for that impedance; zero for a missing or open electrode.

Source code in src/groundinsight/electrical_network.py
def grounding_shunts(self, freq: float) -> Tuple[np.ndarray, np.ndarray]:
    """Grounding impedance of every active bus, and the admittance stamped.

    Internal API: also used by :mod:`groundinsight.analysis.response`; not
    exported from ``groundinsight`` and free to change in any release.

    The interface :func:`~groundinsight.analysis.response.bus_response`
    uses to take one bus's electrode back out of the assembled matrix.
    Subtracting exactly the value that was added -- rather than a
    reciprocal recomputed with a different rounding -- leaves an exact
    zero where the electrode was a bus's only connection, so such a
    system is still recognised as singular.

    Parameters
    ----------
    freq : float
        A frequency of the network.

    Returns
    -------
    impedance : numpy.ndarray
        Resolved grounding impedance per bus in :attr:`bus_indices` order
        (0 Hz stand-in applied; ``nan`` where none is stored).
    admittance : numpy.ndarray
        The admittance on the diagonal of :attr:`Y_sparse` for that
        impedance; zero for a missing or open electrode.
    """
    tables = self._network_tables()
    column = tables.column[float(freq)]
    if self._bus_admittance is None:  # pragma: no cover -- set by the assembly
        usable = tables.bus_present & ~_open_mask(tables.bus_z)
        self._bus_admittance = _reciprocal(tables.bus_z, usable)
    return tables.bus_z[:, column], self._bus_admittance[:, column]

matches_network_state

matches_network_state() -> bool

True while the assembled matrices still describe self.network.

See :meth:state_fingerprint for what "still describe" covers.

Returns:

Type Description
bool

Whether the network's state fingerprint equals the one recorded when the matrices were built.

Source code in src/groundinsight/electrical_network.py
def matches_network_state(self) -> bool:
    """
    ``True`` while the assembled matrices still describe ``self.network``.

    See :meth:`state_fingerprint` for what "still describe" covers.

    Returns
    -------
    bool
        Whether the network's state fingerprint equals the one recorded
        when the matrices were built.
    """
    if self._build_fingerprint is None:  # pragma: no cover -- mid-assembly
        return True
    return self.state_fingerprint() == self._build_fingerprint

nodal_parts

nodal_parts() -> Optional[NodalParts]

The parts of the assembled system a re-assembly of Y reads.

Internal API: used by the study sessions of :mod:groundinsight.analysis._session (P4); not exported from groundinsight and free to change in any release.

Returns:

Type Description
NodalParts or None

None until the matrices are assembled. The arrays are those of this assembly, not copies; a reader must not write to them.

Source code in src/groundinsight/electrical_network.py
def nodal_parts(self) -> Optional[NodalParts]:
    """
    The parts of the assembled system a re-assembly of ``Y`` reads.

    Internal API: used by the study sessions of
    :mod:`groundinsight.analysis._session` (P4); not exported from
    ``groundinsight`` and free to change in any release.

    Returns
    -------
    NodalParts or None
        ``None`` until the matrices are assembled. The arrays are those
        of this assembly, not copies; a reader must not write to them.
    """
    if self._stamp_pattern is None:
        return None
    tables = self._network_tables()
    return NodalParts(
        pattern=self._stamp_pattern,
        bus_z=tables.bus_z,
        bus_present=tables.bus_present,
        grid_admittance=self._grid_admittance,
        loop_admittance=self._loop_admittance,
        i_vectors=[self.i_vectors[freq] for freq in self.network.frequencies],
        dc_substitute=bool(self._dc_substitutes),
    )

remove_loop_closures

remove_loop_closures(
    matrix: csc_matrix, freq: float
) -> csc_matrix

matrix with the Thevenin loop-closure stamps of freq taken out.

Internal API: also used by :mod:groundinsight.analysis.response; not exported from groundinsight and free to change in any release.

The stamps of :meth:thevenin_loop_admittances are subtracted source by source, exactly as the dense definition of the earthing matrix does it -- every entry is bit for bit the one the dense Y - loops gives for the same Y -- and entries that cancel to zero leave the sparsity pattern. Used for the earthing matrix of the solved system and, in :func:~groundinsight.analysis.response.bus_response, for the solved system with one electrode removed.

Parameters:

Name Type Description Default
matrix csc_matrix

A nodal matrix of this network at freq that carries the loop closures.

required
freq float

Frequency in Hz.

required

Returns:

Type Description
csc_matrix

A new matrix (a copy when there is no loop closure); matrix is not modified.

Source code in src/groundinsight/electrical_network.py
def remove_loop_closures(self, matrix: csc_matrix, freq: float) -> csc_matrix:
    """
    ``matrix`` with the Thevenin loop-closure stamps of ``freq`` taken out.

    Internal API: also used by :mod:`groundinsight.analysis.response`; not
    exported from ``groundinsight`` and free to change in any release.

    The stamps of :meth:`thevenin_loop_admittances` are subtracted source
    by source, exactly as the dense definition of the earthing matrix
    does it -- every entry is bit for bit the one the dense
    ``Y - loops`` gives for the same ``Y`` -- and entries that cancel to
    zero leave the sparsity pattern. Used for the earthing matrix of the
    solved system and, in :func:`~groundinsight.analysis.response.bus_response`,
    for the solved system with one electrode removed.

    Parameters
    ----------
    matrix : scipy.sparse.csc_matrix
        A nodal matrix of this network at ``freq`` that carries the loop
        closures.
    freq : float
        Frequency in Hz.

    Returns
    -------
    scipy.sparse.csc_matrix
        A new matrix (a copy when there is no loop closure); ``matrix``
        is not modified.
    """
    size = matrix.shape[0]
    earthing = matrix.copy()
    for src_idx, loop_idx, y_src in self.thevenin_loop_admittances(freq):
        loop = _assemble_csc(
            np.array([src_idx, loop_idx, src_idx, loop_idx], dtype=np.int64),
            np.array([src_idx, loop_idx, loop_idx, src_idx], dtype=np.int64),
            np.array([y_src, y_src, -y_src, -y_src], dtype=complex),
            size,
        )
        earthing = csc_matrix(earthing - loop)
    return earthing

resolved_impedance

resolved_impedance(
    impedance, freq: float
) -> Optional[complex]

Complex value of a stored impedance, with a 0 Hz short substituted.

Internal API: also used by :mod:groundinsight.analysis.decomposition; not exported from groundinsight and free to change in any release.

Every place that inverts an impedance has to see the same value, otherwise the admittance matrix and the currents derived from it would describe two different networks. This is that single place. Away from 0 Hz, and for every value that is not a short circuit, it is a plain conversion to :class:complex.

Parameters:

Name Type Description Default
impedance ComplexNumber or None

The stored value, or None when the frequency is absent.

required
freq float

The frequency the value belongs to, in Hz.

required

Returns:

Type Description
complex or None

The value to invert, or None if impedance was None.

Source code in src/groundinsight/electrical_network.py
def resolved_impedance(self, impedance, freq: float) -> Optional[complex]:
    """Complex value of a stored impedance, with a 0 Hz short substituted.

    Internal API: also used by :mod:`groundinsight.analysis.decomposition`;
    not exported from ``groundinsight`` and free to change in any release.

    Every place that inverts an impedance has to see the *same* value,
    otherwise the admittance matrix and the currents derived from it would
    describe two different networks. This is that single place. Away from
    0 Hz, and for every value that is not a short circuit, it is a plain
    conversion to :class:`complex`.

    Parameters
    ----------
    impedance : ComplexNumber or None
        The stored value, or ``None`` when the frequency is absent.
    freq : float
        The frequency the value belongs to, in Hz.

    Returns
    -------
    complex or None
        The value to invert, or ``None`` if ``impedance`` was ``None``.
    """
    if impedance is None:
        return None
    value = complex(impedance.real, impedance.imag)
    substitute = self._dc_substitutes.get(freq)
    if substitute is not None and is_short_circuit(value):
        return complex(substitute, 0.0)
    return value

solve_network

solve_network()

Solve the network equations Y * u = i for each frequency.

This method computes the bus voltages by solving the admittance matrix equations for each frequency. The results are stored in the network's results object. It uses the csc_matrix and splu functions from scipy, assuming the Y-Matrix is a sparse matrix.

.. warning::

This **replaces** ``network.results[fault]`` with a fresh
:class:`Result` that carries bus rows only. The branch rows are
filled in by :meth:`compute_branch_currents`, which must be
called afterwards -- :func:`groundinsight.run_fault` does exactly
that. Calling ``solve_network`` on its own, e.g. on a hand-built
:class:`ElectricalNetwork` used to inspect ``Y``, ``i`` or ``u``,
therefore discards the branch results of a previous ``run_fault``.
Clearing them is deliberate -- stale branch currents next to fresh
bus voltages would be silently inconsistent -- and the thermal
checks raise on the resulting gap rather than reporting an
incomplete result as free of violations.

To inspect the nodal system without touching the stored results,
build the :class:`ElectricalNetwork` (its constructor has no side
effects on ``network.results``) and read ``u`` back from
``network.results[fault].buses`` instead of re-solving.
Source code in src/groundinsight/electrical_network.py
def solve_network(self):
    """
    Solve the network equations Y * u = i for each frequency.

    This method computes the bus voltages by solving the admittance matrix equations for each frequency.
    The results are stored in the network's results object.
    It uses the csc_matrix and splu functions from scipy, assuming the Y-Matrix is a sparse matrix.

    .. warning::

        This **replaces** ``network.results[fault]`` with a fresh
        :class:`Result` that carries bus rows only. The branch rows are
        filled in by :meth:`compute_branch_currents`, which must be
        called afterwards -- :func:`groundinsight.run_fault` does exactly
        that. Calling ``solve_network`` on its own, e.g. on a hand-built
        :class:`ElectricalNetwork` used to inspect ``Y``, ``i`` or ``u``,
        therefore discards the branch results of a previous ``run_fault``.
        Clearing them is deliberate -- stale branch currents next to fresh
        bus voltages would be silently inconsistent -- and the thermal
        checks raise on the resulting gap rather than reporting an
        incomplete result as free of violations.

        To inspect the nodal system without touching the stored results,
        build the :class:`ElectricalNetwork` (its constructor has no side
        effects on ``network.results``) and read ``u`` back from
        ``network.results[fault].buses`` instead of re-solving.
    """
    fault_name = self.network.active_fault
    if fault_name is None:
        raise ValueError("No active fault set in the network.")

    result = Result(buses=[], branches=[], fault=fault_name)
    # Drop factorisations of a previous solve: the Y matrices may have
    # been rebuilt since (a changed rho, a flipped active flag), and a
    # stale factor would silently answer with the old topology.
    self._lu_factors = {}
    tables = self._network_tables()
    for freq in self.network.frequencies:
        Y_matrix = self.Y_sparse[freq]
        i_vector = self.i_vectors[freq]
        singular_msg = (
            f"Singular admittance matrix at f={freq} Hz: the network has no "
            "path to reference earth. Ensure at least one bus has a finite "
            "grounding impedance and that the fault bus is connected to it."
        )
        # A NaN anywhere in the nodal system poisons the factorisation, and
        # scipy reports that as a singular matrix -- which reads like a
        # topology error and sends the engineer looking for a missing
        # earth connection that is not missing. Catch it first and name
        # what is actually NaN.
        self._assert_finite_system(freq, Y_matrix, i_vector)

        # Exact, solver-independent floating-network guard. If no active bus
        # is referenced to earth at this frequency (every grounding impedance
        # is zero, infinite or missing) the admittance matrix is singular.
        # scipy's sparse ``splu`` handles a singular Y inconsistently across
        # versions -- it may raise ``RuntimeError``, return a non-finite
        # solution, or return an arbitrary finite one (a floating network has
        # no unique EPR) -- so the common floating case is caught structurally
        # here, before the solve, with no numerical tolerance. The test runs
        # on the stored values as a whole; the per-bus classification is
        # only needed for the message.
        stored = tables.bus_z_raw[:, tables.column[float(freq)]]
        present = tables.bus_present[:, tables.column[float(freq)]]
        if not np.any(present & np.isfinite(stored) & (stored != 0)):
            grouped = self._classify_bus_grounding(freq)
            raise ValueError(self._no_ground_reference_message(freq, grouped))
        # The same question for every group of buses the matrix couples:
        # one group without an electrode is enough to make Y singular, and
        # once it holds two or more buses only up to rounding -- splu then
        # returns 1e18 V for it instead of raising (see component_labels).
        floating = self._floating_buses(freq, Y_matrix)
        if floating:
            raise ValueError(self._floating_group_message(freq, floating))
        try:
            # Backstops for any remaining singular case (e.g. a disconnected
            # ungrounded island): scipy may raise, or return a non-finite
            # solution. The matrix is assembled as CSC, so it is factorised
            # as it is -- no dense-to-sparse scan.
            lu = splu(Y_matrix)
            u_vector = lu.solve(i_vector)
        except (np.linalg.LinAlgError, RuntimeError) as e:
            raise ValueError(f"{singular_msg} Original solver error: {e}") from e
        if not np.all(np.isfinite(u_vector)):
            raise ValueError(singular_msg)
        self.u_vectors[freq] = u_vector
        # Keep the factorisation: ``compute_reduction_factors`` solves the
        # *same* Y with a second right-hand side (the injection without the
        # mutual Norton terms). Re-using the factor turns that second solve
        # into a triangular back-substitution.
        self._lu_factors[freq] = lu

    # Create ResultBus instances. Inactive buses are not in ``bus_indices``
    # and therefore do not appear in the result -- they are physically
    # disconnected from the nodal system. The electrode current is
    # ``u / Z`` with the 0 Hz stand-in applied, zero for a missing or open
    # electrode; the injection is the source-only vector.
    frequencies = self.network.frequencies
    potentials = self._stacked(self.u_vectors)
    self._electrode_currents = None
    electrode, usable = self._electrode_arrays(potentials)
    injection = self._stacked(self.source_injections)
    result.buses.extend(
        self._result_rows(
            ResultBus,
            list(self.bus_indices),
            frequencies,
            {"uepr": potentials, "ia": electrode, "i_inj": injection},
        )
    )

    # Store the result in the network's results dictionary
    self.network.results[fault_name] = result
    self.results = result  # Also keep a reference in self.results

state_fingerprint

state_fingerprint() -> tuple

Digest of every model value the assembled matrices depend on.

The assembled system is a snapshot: once Y is built, later changes to a bus impedance, to an active flag or to the active fault do not reach it. Anything that reads Y_sparse back out afterwards -- :func:~groundinsight.analysis.response.bus_response above all -- therefore has to be able to tell whether the snapshot still describes the network in hand. This fingerprint is that test: it covers exactly the inputs :meth:_construct_Y_matrices reads, in their stored form, so an equal fingerprint means an equal matrix.

Returns:

Type Description
tuple

Hashable digest. Compare it against :attr:_build_fingerprint (or use :meth:matches_network_state); the value itself carries no meaning beyond equality.

Notes

The model is read afresh into arrays (:class:_NetworkTables) and digested with BLAKE2 (:meth:_NetworkTables.fingerprint); the digest covers every stored value, including values at frequencies the network is not solved at. A call here reads the model afresh (about 25 ms on a 4000-bus ring at seven frequencies); the fingerprint of a build reuses the tables of the assembly and costs about 5 ms.

Source code in src/groundinsight/electrical_network.py
def state_fingerprint(self) -> tuple:
    """
    Digest of every model value the assembled matrices depend on.

    The assembled system is a *snapshot*: once ``Y`` is built, later
    changes to a bus impedance, to an ``active`` flag or to the active
    fault do not reach it. Anything that reads ``Y_sparse`` back out
    afterwards -- :func:`~groundinsight.analysis.response.bus_response`
    above all -- therefore has to be able to tell whether the snapshot
    still describes the network in hand. This fingerprint is that test:
    it covers exactly the inputs :meth:`_construct_Y_matrices` reads, in
    their stored form, so an equal fingerprint means an equal matrix.

    Returns
    -------
    tuple
        Hashable digest. Compare it against :attr:`_build_fingerprint`
        (or use :meth:`matches_network_state`); the value itself carries
        no meaning beyond equality.

    Notes
    -----
    The model is read afresh into arrays (:class:`_NetworkTables`) and
    digested with BLAKE2 (:meth:`_NetworkTables.fingerprint`); the
    digest covers every stored value, including values at frequencies the
    network is not solved at. A call here reads the model afresh (about
    25 ms on a 4000-bus ring at seven frequencies); the fingerprint of a
    build reuses the tables of the assembly and costs about 5 ms.
    """
    return _NetworkTables(self, fingerprint_only=True).fingerprint(
        self.network.active_fault
    )

thevenin_loop_admittances

thevenin_loop_admittances(
    freq: float,
) -> List[Tuple[int, int, complex]]

The loop-closure stamps the Thevenin sources put into Y(freq).

A voltage source closes its loop with Y_src = 1/Z_src between its own bus and the active fault bus: the non-grounding part of the fault loop (transformer, phase conductor) that the earthing network does not model. :meth:_construct_Y_matrices stamps them and :meth:earthing_admittance_matrix takes them back out, both from :meth:_NetworkTables.thevenin_loops -- one rule in one place, so the two cannot drift apart, and the values here are bit for bit the ones in :attr:Y_sparse.

Parameters:

Name Type Description Default
freq float

Frequency in Hz, one of the network frequencies.

required

Returns:

Type Description
list of tuple of (int, int, complex)

(source bus row, fault bus row, Y_src) per voltage source on an active bus other than the fault bus, with a finite source impedance at freq. Empty without an active fault, and for a frequency the network is not solved at (Y(freq) does not exist there).

Source code in src/groundinsight/electrical_network.py
def thevenin_loop_admittances(self, freq: float) -> List[Tuple[int, int, complex]]:
    """
    The loop-closure stamps the Thevenin sources put into ``Y(freq)``.

    A voltage source closes its loop with ``Y_src = 1/Z_src`` between its
    own bus and the active fault bus: the non-grounding part of the fault
    loop (transformer, phase conductor) that the earthing network does not
    model. :meth:`_construct_Y_matrices` stamps them and
    :meth:`earthing_admittance_matrix` takes them back out, both from
    :meth:`_NetworkTables.thevenin_loops` -- one rule in one place, so
    the two cannot drift apart, and the values here are bit for bit the
    ones in :attr:`Y_sparse`.

    Parameters
    ----------
    freq : float
        Frequency in Hz, one of the network frequencies.

    Returns
    -------
    list of tuple of (int, int, complex)
        ``(source bus row, fault bus row, Y_src)`` per voltage source on
        an active bus other than the fault bus, with a finite source
        impedance at ``freq``. Empty without an active fault, and for a
        frequency the network is not solved at (``Y(freq)`` does not
        exist there).
    """
    active_fault = self.network.active_fault
    if active_fault is None:
        return []
    fault_bus_idx = self.bus_indices.get(self.network.faults[active_fault].bus)
    if fault_bus_idx is None:
        return []
    tables = self._network_tables()
    column = tables.column.get(float(freq))
    if column is None:
        return []
    loops, admittance, usable = tables.thevenin_loops(fault_bus_idx)
    stamped = usable[:, column]
    return [
        (src_idx, fault_bus_idx, y_src)
        for src_idx, y_src in zip(
            tables.vs_bus[loops][stamped].tolist(),
            admittance[stamped, column].tolist(),
            strict=True,
        )
    ]

NodalParts

Bases: NamedTuple

What a re-assembly of Y for other bus impedances needs from a solve.

Internal API: handed to :mod:groundinsight.analysis._session by :meth:ElectricalNetwork.nodal_parts; not exported from groundinsight and free to change in any release.

Attributes:

Name Type Description
pattern _StampPattern

Where every stamp of Y lands.

bus_z ndarray

Resolved grounding impedance per active bus and frequency, (n, F).

bus_present ndarray

Where a bus impedance is stored, same shape.

grid_admittance ndarray

Admittance per grounding branch and frequency.

loop_admittance ndarray

Admittance per Thevenin loop closure and frequency.

i_vectors list of numpy.ndarray

The injection vector per network frequency, in frequency order.

dc_substitute bool

Whether a 0 Hz stand-in is in use (its size may follow a bus impedance, so the parts do not describe Y for other ones).

assemble_nodal_matrices

assemble_nodal_matrices(
    pattern: _StampPattern,
    y_bus: ndarray,
    y_grid: ndarray,
    y_loop: ndarray,
    frequencies: List[float],
) -> Dict[float, csc_matrix]

The nodal matrices from the stamp pattern and the stamp admittances.

Internal API: also used by :mod:groundinsight.analysis._session; not exported from groundinsight and free to change in any release.

The bus admittances are the first n stamps of the pattern; the four stamps of every grounding branch and of every Thevenin loop closure follow, in the order an element-by-element dense assembly adds them, and every entry is summed in that order (:meth:_StampPattern.matrix). The assembly and the study sessions that re-assemble Y for changed bus impedances both go through here, so the same admittances give bit for bit the same matrices.

Parameters:

Name Type Description Default
pattern _StampPattern

Where every stamp lands.

required
y_bus ndarray

Grounding admittance per active bus and frequency, (n, F).

required
y_grid ndarray

Admittance per grounding branch and frequency.

required
y_loop ndarray

Admittance per Thevenin loop closure and frequency.

required
frequencies list of float

The network frequencies, one per column.

required

Returns:

Type Description
dict of float to scipy.sparse.csc_matrix

One matrix per frequency.

Source code in src/groundinsight/electrical_network.py
def assemble_nodal_matrices(
    pattern: "_StampPattern",
    y_bus: np.ndarray,
    y_grid: np.ndarray,
    y_loop: np.ndarray,
    frequencies: List[float],
) -> Dict[float, csc_matrix]:
    """The nodal matrices from the stamp pattern and the stamp admittances.

    Internal API: also used by :mod:`groundinsight.analysis._session`; not
    exported from ``groundinsight`` and free to change in any release.

    The bus admittances are the first ``n`` stamps of the pattern; the four
    stamps of every grounding branch and of every Thevenin loop closure
    follow, in the order an element-by-element dense assembly adds them, and
    every entry is summed in that order (:meth:`_StampPattern.matrix`). The
    assembly and the study sessions that re-assemble ``Y`` for changed bus
    impedances both go through here, so the same admittances give bit for
    bit the same matrices.

    Parameters
    ----------
    pattern : _StampPattern
        Where every stamp lands.
    y_bus : numpy.ndarray
        Grounding admittance per active bus and frequency, ``(n, F)``.
    y_grid : numpy.ndarray
        Admittance per grounding branch and frequency.
    y_loop : numpy.ndarray
        Admittance per Thevenin loop closure and frequency.
    frequencies : list of float
        The network frequencies, one per column.

    Returns
    -------
    dict of float to scipy.sparse.csc_matrix
        One matrix per frequency.
    """
    matrices: Dict[float, csc_matrix] = {}
    for j, freq in enumerate(frequencies):
        y_g, y_l = y_grid[:, j], y_loop[:, j]
        values = np.concatenate([
            y_bus[:, j],
            np.stack([-y_g, -y_g, y_g, y_g], axis=1).ravel(),
            np.stack([y_l, y_l, -y_l, -y_l], axis=1).ravel(),
        ])
        matrices[freq] = pattern.matrix(values)
    return matrices

bus_admittances

bus_admittances(
    bus_z: ndarray, present: ndarray
) -> np.ndarray

The grounding admittance each bus stamps on the diagonal of Y.

Internal API: also used by :mod:groundinsight.analysis._session; not exported from groundinsight and free to change in any release.

The one rule for it, shared by the assembly and by the study sessions that re-assemble Y for changed bus impedances (P4): 1/Z where a value is stored and not open, zero elsewhere.

Parameters:

Name Type Description Default
bus_z ndarray

Resolved grounding impedances, (buses, F).

required
present ndarray

Where a value is stored, same shape.

required

Returns:

Type Description
ndarray

Complex admittances, same shape.

Source code in src/groundinsight/electrical_network.py
def bus_admittances(
    bus_z: np.ndarray, present: np.ndarray
) -> np.ndarray:
    """The grounding admittance each bus stamps on the diagonal of ``Y``.

    Internal API: also used by :mod:`groundinsight.analysis._session`; not
    exported from ``groundinsight`` and free to change in any release.

    The one rule for it, shared by the assembly and by the study sessions
    that re-assemble ``Y`` for changed bus impedances (P4): ``1/Z`` where a
    value is stored and not open, zero elsewhere.

    Parameters
    ----------
    bus_z : numpy.ndarray
        Resolved grounding impedances, ``(buses, F)``.
    present : numpy.ndarray
        Where a value is stored, same shape.

    Returns
    -------
    numpy.ndarray
        Complex admittances, same shape.
    """
    return _reciprocal(bus_z, present & ~_open_mask(bus_z))

component_labels

component_labels(matrix) -> np.ndarray

Connected groups of buses of a nodal matrix, from its off-diagonal entries.

Internal API: also used by :mod:groundinsight.analysis.response; not exported from groundinsight and free to change in any release.

Two buses belong together when the matrix couples them: a shield with a non-zero admittance at that frequency, or -- in the solved matrix -- the loop closure of a voltage source. An electrode sits on the diagonal and couples nothing. Whether a group reaches remote earth is then a question of structure, answered without a tolerance: it does if and only if one of its buses has a finite, non-zero electrode admittance. The linear solver cannot be asked instead. The matrix of a floating group of two or more buses is singular only up to rounding -- every row of a shield stamp sums to zero in exact arithmetic, not in floating point -- and splu then returns potentials of 1e15 Ohm per ampere and more instead of raising.

Parameters:

Name Type Description Default
matrix spmatrix

A square nodal matrix.

required

Returns:

Type Description
ndarray

Integer group label per row.

Source code in src/groundinsight/electrical_network.py
def component_labels(matrix) -> np.ndarray:
    """
    Connected groups of buses of a nodal matrix, from its off-diagonal entries.

    Internal API: also used by :mod:`groundinsight.analysis.response`; not
    exported from ``groundinsight`` and free to change in any release.

    Two buses belong together when the matrix couples them: a shield with a
    non-zero admittance at that frequency, or -- in the solved matrix -- the
    loop closure of a voltage source. An electrode sits on the diagonal and
    couples nothing. Whether a group reaches remote earth is then a question
    of structure, answered without a tolerance: it does if and only if one of
    its buses has a finite, non-zero electrode admittance. The linear solver
    cannot be asked instead. The matrix of a floating group of two or more
    buses is singular only up to rounding -- every row of a shield stamp sums
    to zero in exact arithmetic, not in floating point -- and ``splu`` then
    returns potentials of 1e15 Ohm per ampere and more instead of raising.

    Parameters
    ----------
    matrix : scipy.sparse.spmatrix
        A square nodal matrix.

    Returns
    -------
    numpy.ndarray
        Integer group label per row.
    """
    coo = matrix.tocoo()
    link = (coo.row != coo.col) & (coo.data != 0)
    graph = csr_matrix(
        (np.ones(int(link.sum())), (coo.row[link], coo.col[link])),
        shape=matrix.shape,
    )
    _, labels = connected_components(graph, directed=False)
    return labels

restricted_columns

restricted_columns(
    matrix, rows: ndarray, units: List[int]
) -> Optional[np.ndarray]

Unit-injection columns of matrix, solved on one group of buses only.

Internal API: also used by :mod:groundinsight.analysis.response; not exported from groundinsight and free to change in any release.

The buses outside rows are decoupled from it by construction (see :func:component_labels), so the columns inside the group do not depend on them -- and a floating group elsewhere in the matrix cannot make this solve singular.

Parameters:

Name Type Description Default
matrix spmatrix

Square nodal matrix.

required
rows ndarray

Boolean mask of the group.

required
units list of int

Rows (inside the group) at which one ampere is injected, one column each.

required

Returns:

Type Description
ndarray or None

(n, len(units)) voltages, zero outside the group; None if the group's matrix is numerically singular or the solve is not finite.

Source code in src/groundinsight/electrical_network.py
def restricted_columns(
    matrix, rows: np.ndarray, units: List[int]
) -> Optional[np.ndarray]:
    """
    Unit-injection columns of ``matrix``, solved on one group of buses only.

    Internal API: also used by :mod:`groundinsight.analysis.response`; not
    exported from ``groundinsight`` and free to change in any release.

    The buses outside ``rows`` are decoupled from it by construction (see
    :func:`component_labels`), so the columns inside the group do not
    depend on them -- and a floating group elsewhere in the matrix cannot
    make this solve singular.

    Parameters
    ----------
    matrix : scipy.sparse.spmatrix
        Square nodal matrix.
    rows : numpy.ndarray
        Boolean mask of the group.
    units : list of int
        Rows (inside the group) at which one ampere is injected, one column
        each.

    Returns
    -------
    numpy.ndarray or None
        ``(n, len(units))`` voltages, zero outside the group; ``None`` if the
        group's matrix is numerically singular or the solve is not finite.
    """
    index = np.flatnonzero(rows)
    sub = csc_matrix(matrix.tocsr()[index][:, index])
    rhs = np.zeros((index.size, len(units)), dtype=complex)
    rhs[np.searchsorted(index, units), np.arange(len(units))] = 1.0
    try:
        solved = splu(sub).solve(rhs)
    except (np.linalg.LinAlgError, RuntimeError):
        return None
    if not np.all(np.isfinite(solved)):
        return None
    columns = np.zeros((matrix.shape[0], len(units)), dtype=complex)
    columns[index] = solved
    return columns

rms_columns

rms_columns(values: ndarray) -> np.ndarray

RMS over the frequency columns, the convention of the result rows.

Internal API: also used by :mod:groundinsight.analysis._session; not exported from groundinsight and free to change in any release.

sqrt(sum |x|**2), accumulated frequency by frequency (see :meth:ElectricalNetwork._calculate_rms). The result rows and the study sessions (P4) both take their RMS from here, so that a re-solved trial reports bit for bit the value a full run_fault stores.

Parameters:

Name Type Description Default
values ndarray

Complex array (elements, F).

required

Returns:

Type Description
ndarray

Float array (elements,).

Source code in src/groundinsight/electrical_network.py
def rms_columns(values: np.ndarray) -> np.ndarray:
    """RMS over the frequency columns, the convention of the result rows.

    Internal API: also used by :mod:`groundinsight.analysis._session`; not
    exported from ``groundinsight`` and free to change in any release.

    ``sqrt(sum |x|**2)``, accumulated frequency by frequency (see
    :meth:`ElectricalNetwork._calculate_rms`). The result rows and the study
    sessions (P4) both take their RMS from here, so that a re-solved trial
    reports bit for bit the value a full ``run_fault`` stores.

    Parameters
    ----------
    values : numpy.ndarray
        Complex array ``(elements, F)``.

    Returns
    -------
    numpy.ndarray
        Float array ``(elements,)``.
    """
    square = np.zeros(values.shape[0])
    for j in range(values.shape[1]):
        magnitude = np.abs(values[:, j])
        square += magnitude * magnitude
    return np.sqrt(square)

stack_columns

stack_columns(
    vectors: List[Optional[ndarray]], rows: int
) -> np.ndarray

Per-frequency vectors as the columns of one (rows, F) array.

Internal API: also used by :mod:groundinsight.analysis._session; not exported from groundinsight and free to change in any release.

Parameters:

Name Type Description Default
vectors list of numpy.ndarray or None

One vector per frequency, in frequency order; None leaves the column at zero.

required
rows int

Length of every vector.

required

Returns:

Type Description
ndarray

Complex array; column j is vectors[j].

Source code in src/groundinsight/electrical_network.py
def stack_columns(vectors: List[Optional[np.ndarray]], rows: int) -> np.ndarray:
    """Per-frequency vectors as the columns of one ``(rows, F)`` array.

    Internal API: also used by :mod:`groundinsight.analysis._session`; not
    exported from ``groundinsight`` and free to change in any release.

    Parameters
    ----------
    vectors : list of numpy.ndarray or None
        One vector per frequency, in frequency order; ``None`` leaves the
        column at zero.
    rows : int
        Length of every vector.

    Returns
    -------
    numpy.ndarray
        Complex array; column ``j`` is ``vectors[j]``.
    """
    out = np.zeros((rows, len(vectors)), dtype=complex)
    for j, vector in enumerate(vectors):
        if vector is not None:
            out[:, j] = vector
    return out