Skip to content

Transient simulations

The groundinsight.simulation.transient module extends the package beyond the steady-state phasor solve into the time domain. A TransientStudy binds a network, an active fault and one or more user-defined source waveforms together and produces a ResultTransient with EPR and shield-current time series at the declared observation points.

Physical / modelling context

The frequency-domain solver answers "given a sinusoidal injection at frequency \(f\), what is the EPR?". Real fault currents are non-sinusoidal: they switch on at fault inception, may carry an exponentially decaying DC offset, and switch off again at clearing. Two complementary solver paths are implemented to capture that behaviour:

  • FFT solver (solver="fft") — samples the user waveform on a regular time grid, transforms to the frequency domain via NumPy's real-valued FFT, evaluates the existing nodal-admittance solve at every FFT bin, and transforms the bus voltages back via IFFT. It reuses BusType.impedance_formula and BranchType.self_impedance_formula and is therefore consistent with the stationary results bin-by-bin. Only current sources are accepted, and only those with a galvanic connection to the fault bus inject — the same rule the stationary solver applies through its source-to-fault paths. Mutual coupling is not evaluated by this path; a network that carries it raises a TransientModelWarning, and the state-space solver is the one that models it. The DFT's periodicity is checked at the end of the window and solve(..., zero_pad=True) solves on a doubled window when the response has not decayed.
  • State-space solver (solver="state_space") — assembles a modified-nodal-analysis ODE system \(\dot x = A x + B u\), \(y = C x + D u\) from the lumped RLC fields on BusType and BranchType (R_formula, L_formula, C_formula, R_self_formula, L_self_formula, C_self_formula, R_mutual_formula, M_mutual_formula) and integrates with scipy.signal.lsim. Voltage sources, Carson-style mutual coupling and pi-section branch capacitance are supported.

Source waveforms are produced by the small library in groundinsight.simulation.waveforms: step, sinusoidal_with_dc_offset (the textbook single-line-to-ground fault current with DC asymmetry) and damped_oscillation. Custom waveforms are any vectorised callable f(t) -> values. A waveform gives instantaneous values, so its amplitude is a peak value, while Source.values holds RMS phasors: a fault current of 1000 A RMS has the amplitude \(\sqrt 2 \cdot 1000\) A.

Example

# fragment: assumes a network `net` with the current source "infeed", the fault "fault1", the bus "bus_fault" and the branch "cable_1"
import math

import groundinsight as gi
from groundinsight import waveforms

# Assume `net` is a built network with one current source 'infeed'
# and a fault 'fault1'.

study = gi.TransientStudy(network=net, fault="fault1")
study.set_source_waveform(
    "infeed",
    waveforms.sinusoidal_with_dc_offset(
        amplitude=math.sqrt(2) * 1e3,   # peak value: a fault current of 1000 A RMS
        frequency_hz=50.0,
        t_on=0.02, t_off=0.12,
        dc_amplitude=500.0,             # initial value of the DC offset, in A
        dc_decay_tau=0.05,
    ),
)
study.set_observation(buses=["bus_fault"], branches=["cable_1"])

result = study.solve(t_end=0.2, dt=1e-4, solver="fft")

# Plot the time series
gi.plot_epr_transient(result=result, title="EPR transient")
gi.plot_branch_current_transient(result=result, title="Shield current")

# Long-format DataFrame for further post-processing
df = result.to_polars()

Switching to the state-space solver only requires changing the solver argument and ensuring the network's bus and branch types carry the lumped RLC formulas required by the ODE form. That path reads those values at one frequency — the smallest strictly positive entry of network.frequencies unless solve(..., f_eval=...) names another one — and rejects a negative R, L or C instead of dropping the element.

Both solvers ignore Fault.scalings (the source waveform is the literal injection) and both warn when the active fault carries any. See Transient simulation for the derivations, the limitations of each path and the measured cross-checks.

Memory of the FFT solver

The FFT solver assembles the dense \(n \times n\) admittance matrices of up to 512 frequency bins at a time and hands them to LAPACK as one stacked array — \(16\,n^2\) bytes per bin for \(n\) active buses. Since audit pass 19 the batch also stays within a byte budget, solve(..., fft_block_bytes=...), 256 MiB by default, which binds from 182 buses on. The fixed 512-bin batch needed 1.3 GB at 400 buses and 8.2 GB at 1000, and the previous batch was still alive while the next one was assembled; with the default budget a 400-bus solve over 1001 bins peaks at about 0.3 GB. The budget changes the memory, not the result: every bin is an independent solve, and the spectra are bit-identical to the old batching. A very small budget does cost time on mid-size networks, because each batch is one assembly pass over all elements — 150 buses and 1001 bins take 0.7 s at the default and 4.5 s at 1 MiB (two bins per batch). A single matrix larger than the budget is solved one bin at a time, with a log message.

# fragment: continues the study above
result = study.solve(t_end=0.2, dt=1e-4, solver="fft",
                     fft_block_bytes=64 * 2**20)   # 64 MiB per batch

API reference

Transient study and result

transient

Transient Simulation Layer.

This module hosts the high-level :class:TransientStudy workflow and the matching :class:ResultTransient Pydantic model. One study object and one observation contract serve two solvers:

  • solver="fft" samples a user-defined source waveform on a regular time grid, transforms it to a frequency spectrum via NumPy's real-valued FFT, feeds it into the per-frequency network solve and transforms the result back via IFFT.
  • solver="state_space" integrates one linear ODE built from the lumped R / L / C fields of the bus and branch types.

Design choices:

  • The FFT solver takes current sources only (Source.source_type='current'). A current source's frequency-dependent values are replaced by the FFT spectrum of the user-supplied waveform; the rest of the network remains untouched. A Thevenin (voltage) source needs the state-space solver, where the loop closure is naturally part of the ODE system.
  • Observation points (buses for EPR, branches for shield current) are passed explicitly to set_observation -- there is no "all" default, to keep memory and post-processing tractable on large networks.
  • The FFT solver does not evaluate mutual coupling: the phase current along each path would itself be time-dependent and is more natural to handle in the state-space formulation. It ignores mutual impedance and says so: meeting a coupled branch it raises a :class:~groundinsight.models.core_models.TransientModelWarning, because the same network solved stationarily or with the state-space solver returns a lower EPR at the fault (49.2 V against 77.6 V on a coupled two-bus cable link) and a silent difference of that size is indistinguishable from a modelling result. The FFT answer is the conservative one at the fault bus.
  • Only sources that can actually reach the fault inject. The stationary solver filters its sources through the source-to-fault paths; the FFT solver reproduces that with a breadth-first reachability search over the active branches, so a galvanically isolated source contributes 0 V in both solvers instead of its full spectrum in one of them.

ResultTransient

Bases: BaseModel

Container for the time-domain results of a transient simulation.

Attributes:

Name Type Description
time_s list of float

Time samples in seconds, equally spaced.

epr_t dict of str to list of float

Mapping of observed bus name to its EPR time series in volts.

i_branch_t dict of str to list of float

Mapping of observed branch name to its branch current time series in amperes.

source_t dict of str to list of float

The sampled source waveforms keyed by source name, in the natural unit of the source (amperes for current sources, volts for voltage sources).

fault str

Name of the fault that was active during the simulation.

solver str

Identifier of the solver that produced this result ("fft" or "state_space").

Notes

The list-typed fields use plain Python lists for JSON serialisability. Convert to numpy.ndarray at the call site if you need vectorised post-processing.

Examples:

>>> 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)
>>> from groundinsight.simulation import waveforms
>>> study = gi.TransientStudy(net, fault="F1")
>>> study.set_source_waveform("S1", waveforms.step(100.0, t_on=0.01, t_off=0.03))
>>> result = study.solve(t_end=0.05, dt=1e-3)
>>> result.solver, result.fault, len(result.time_s)
('fft', 'F1', 50)
>>> sorted(result.epr_t)
[]

to_polars

to_polars() -> pl.DataFrame

Convert the result to a Polars DataFrame in long form.

Returns:

Type Description
DataFrame

A DataFrame with columns time_s, signal_kind ("epr" / "i_branch" / "source"), name and value. Rows are grouped by signal kind and then by name, in the insertion order of the result dictionaries, with the time axis running inside each group.

Notes

Assembled one series at a time -- the time axis and the values as NumPy columns, the two label columns as Polars literals -- and stacked with pl.concat. A transient of 20 000 samples over 25 buses and 24 branches is a million rows, and materialising a million single-row Python dictionaries to hand them to Polars took 1.0 s and several hundred MB of temporary objects. Expanding the labels inside Polars instead keeps the whole conversion in Arrow: the same million-row frame is built in ~0.02 s.

Source code in src/groundinsight/simulation/transient.py
def to_polars(self) -> "pl.DataFrame":  # noqa: F821 -- forward ref
    """
    Convert the result to a Polars DataFrame in long form.

    Returns
    -------
    polars.DataFrame
        A DataFrame with columns ``time_s``, ``signal_kind``
        (``"epr"`` / ``"i_branch"`` / ``"source"``), ``name`` and
        ``value``. Rows are grouped by signal kind and then by name,
        in the insertion order of the result dictionaries, with the
        time axis running inside each group.

    Notes
    -----
    Assembled one *series* at a time -- the time axis and the values as
    NumPy columns, the two label columns as Polars literals -- and
    stacked with ``pl.concat``. A transient of 20 000 samples over
    25 buses and 24 branches is a million rows, and materialising a
    million single-row Python dictionaries to hand them to Polars took
    1.0 s and several hundred MB of temporary objects. Expanding the
    labels inside Polars instead keeps the whole conversion in Arrow:
    the same million-row frame is built in ~0.02 s.
    """
    import polars as pl

    schema = {
        "time_s": pl.Float64,
        "signal_kind": pl.Utf8,
        "name": pl.Utf8,
        "value": pl.Float64,
    }
    time = np.asarray(self.time_s, dtype=float)

    frames: List[pl.DataFrame] = []
    for kind, table in (
        ("epr", self.epr_t),
        ("i_branch", self.i_branch_t),
        ("source", self.source_t),
    ):
        for name, series in table.items():
            frames.append(
                pl.DataFrame(
                    {
                        "time_s": time,
                        "value": np.asarray(series, dtype=float),
                    }
                )
                .with_columns(
                    pl.lit(kind, dtype=pl.Utf8).alias("signal_kind"),
                    pl.lit(name, dtype=pl.Utf8).alias("name"),
                )
                .select(list(schema))
            )

    if not frames:
        return pl.DataFrame(schema=schema)
    return pl.concat(frames)

TransientStudy

TransientStudy(network: Network, fault: str)

High-level entry point for transient simulations.

A study binds together a :class:Network, the active fault to study, a set of source waveforms (one per source contributing to the fault), and the list of observation points (buses and branches) that should be returned as time series. Calling :meth:solve produces a :class:ResultTransient.

Parameters:

Name Type Description Default
network Network

The network model. Buses, branches, sources and faults are taken from this object. Nothing is written back -- no impedance, no active flag, no stored result, no network.paths and not network.active_fault. The state-space solver takes the phase split for its mutual coupling from the stationary phase-network solve, which needs no path set.

required
fault str

Name of the fault this study simulates. It does not have to be the network's active fault. It is kept as the attribute fault_name. The former keyword fault_name is accepted as a deprecated alias.

required

Examples:

A 100 A pulse into a resistive two-station network:

>>> 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)
>>> from groundinsight.simulation import waveforms
>>> study = gi.TransientStudy(net, fault="F1")
>>> study.set_source_waveform("S1", waveforms.step(100.0, t_on=0.01, t_off=0.03))
>>> study.set_observation(buses=["B2"], branches=["L1"])
>>> result = study.solve(t_end=0.05, dt=1e-3)
>>> round(max(abs(v) for v in result.epr_t["B2"]), 2)
11.11
Source code in src/groundinsight/simulation/transient.py
@renamed_parameters(fault_name="fault")
def __init__(self, network: Network, fault: str):
    if fault not in network.faults:
        raise ValueError(
            f"Fault '{fault}' does not exist in the network."
        )
    self.network = network
    self.fault_name = fault
    self._source_waveforms: Dict[str, WaveformFunc] = {}
    self._obs_buses: List[str] = []
    self._obs_branches: List[str] = []
    # Stand-in impedance for elements that are an ideal short circuit at
    # the 0 Hz bin, and the index of that bin. Both stay ``None`` unless
    # the FFT solver actually meets such an element. See
    # :meth:`_dc_substitute_for` and :meth:`_resolved_z_stack`.
    self._dc_substitute: Optional[float] = None
    self._dc_bin: Optional[int] = None
    # Progress and cancellation of the solve() call in flight; a silent
    # instance outside of one. See :mod:`groundinsight.progress`.
    self._hooks = StudyHooks("TransientStudy.solve", 0)

set_observation

set_observation(
    *,
    buses: Optional[List[str]] = None,
    branches: Optional[List[str]] = None,
)

Declare which buses and branches should be returned as time series.

Parameters:

Name Type Description Default
buses list of str

Names of buses whose EPR u(t) should be returned. Defaults to no buses.

None
branches list of str

Names of branches whose shield current i(t) should be returned. Defaults to no branches.

None

Raises:

Type Description
ValueError

If a name is not present in the network.

Source code in src/groundinsight/simulation/transient.py
def set_observation(
    self,
    *,
    buses: Optional[List[str]] = None,
    branches: Optional[List[str]] = None,
):
    """
    Declare which buses and branches should be returned as time series.

    Parameters
    ----------
    buses : list of str, optional
        Names of buses whose EPR ``u(t)`` should be returned. Defaults
        to no buses.
    branches : list of str, optional
        Names of branches whose shield current ``i(t)`` should be
        returned. Defaults to no branches.

    Raises
    ------
    ValueError
        If a name is not present in the network.
    """
    for name in buses or []:
        if name not in self.network.buses:
            raise ValueError(f"Bus '{name}' not in network.")
    for name in branches or []:
        if name not in self.network.branches:
            raise ValueError(f"Branch '{name}' not in network.")
    self._obs_buses = list(buses or [])
    self._obs_branches = list(branches or [])

set_source_waveform

set_source_waveform(
    source_name: str, waveform: WaveformFunc
)

Bind a time-domain waveform to a network source.

For source_type='current' the waveform is the injected current in amperes. For source_type='voltage' the waveform is the Thevenin EMF in volts (the source_impedance is taken from the :class:Source definition). Voltage sources are accepted by the state-space solver but rejected by the FFT solver, which still only supports current sources — the relevant solver checks the type at solve() time.

Parameters:

Name Type Description Default
source_name str

Name of a source defined on the network.

required
waveform callable

Vectorised function f(t) -> values mapping a 1-D time array to source values of the same shape.

required

Raises:

Type Description
ValueError

If the source does not exist on the network.

Source code in src/groundinsight/simulation/transient.py
def set_source_waveform(self, source_name: str, waveform: WaveformFunc):
    """
    Bind a time-domain waveform to a network source.

    For ``source_type='current'`` the waveform is the injected current
    in amperes. For ``source_type='voltage'`` the waveform is the
    Thevenin EMF in volts (the ``source_impedance`` is taken from the
    :class:`Source` definition). Voltage sources are accepted by the
    state-space solver but rejected by the FFT solver, which still
    only supports current sources — the relevant solver checks the
    type at ``solve()`` time.

    Parameters
    ----------
    source_name : str
        Name of a source defined on the network.
    waveform : callable
        Vectorised function ``f(t) -> values`` mapping a 1-D time
        array to source values of the same shape.

    Raises
    ------
    ValueError
        If the source does not exist on the network.
    """
    src = self.network.sources.get(source_name)
    if src is None:
        raise ValueError(
            f"Source '{source_name}' does not exist in the network."
        )
    if src.source_type not in ("current", "voltage"):
        raise ValueError(
            f"Source '{source_name}' has unknown source_type "
            f"'{src.source_type}'."
        )
    self._source_waveforms[source_name] = waveform

solve

solve(
    *,
    t_end: float,
    dt: float,
    solver: str = "fft",
    f_eval: Optional[float] = None,
    zero_pad: bool = False,
    fft_block_bytes: Optional[int] = None,
    progress: Optional[
        Callable[[int, int, str], None]
    ] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> ResultTransient

Run the transient solve and return the resulting time series.

Parameters:

Name Type Description Default
t_end float

End time of the simulation in seconds. t=0 is always the start. Both solvers use the same grid (see :func:_time_grid), which may extend by one sample so the sample count is even.

required
dt float

Time-step in seconds. For the FFT solver this determines the Nyquist frequency f_max = 1/(2*dt) and therefore the highest harmonic resolved. For the state-space solver dt is the integration time-step (first-order hold on the source signal between samples).

required
solver (fft, state_space)

Solver to use. "fft" uses BusType.impedance_formula and BranchType.self_impedance_formula (frequency-domain impedances); "state_space" uses the lumped RLC fields on BusType / BranchType and integrates with :func:scipy.signal.lsim. Defaults to "fft".

'fft'
f_eval float

State-space solver only. The frequency in Hz at which the lumped R / L / C values and the Thevenin source impedance are read. The state-space model treats them as frequency-independent, so this picks the operating point. Must be one of network.frequencies. Defaults to the smallest strictly positive entry of network.frequencies rather than to its first element: with [0, 50] the first element is 0 Hz, where L_src = Im(Z_src)/omega is not defined -- reading it there as zero changes the EPR of the reference case by a factor of 680, decided by nothing but the order of the frequency list.

None
zero_pad bool

FFT solver only. Solve on a window twice as long and return only its first half. The DFT is periodic, so a response that has not decayed by t_end wraps around into the start of the trace; doubling the window pushes the wrap out of the reported interval. Costs twice the solve time. Defaults to False.

False
fft_block_bytes int

FFT solver only. Upper bound in bytes for one batch of dense complex admittance matrices (16 * n**2 bytes per frequency bin for n active buses). The solver assembles and solves at most 512 bins per batch; above about 181 buses this budget decides instead, so memory stays bounded for any network size -- a fixed 512-bin batch would take 1.3 GB at 400 buses and 8.2 GB at 1000. The result does not depend on it (every bin is solved on its own). A very small budget costs time on mid-size networks, because every batch is one pass of the element-wise assembly: 150 buses and 1001 bins took 4.5 s at 1 MiB (two bins per batch) against 0.7 s at the default. A single matrix larger than the budget is solved one bin at a time and logged. Defaults to 256 MiB.

None
progress callable

progress(done, total, label). The FFT solver reports one unit per batch of frequency bins solved together (see fft_block_bytes), the state-space solver the two stages "assembled" and "integrated". See :mod:groundinsight.progress.

None
should_cancel callable

Asked before the solve and before every unit; a true answer raises :class:~groundinsight.progress.StudyCancelled. The integration of the state-space solver is a single library call and cannot be interrupted once it runs.

None

Returns:

Type Description
ResultTransient

Time-domain results at the observation points.

Raises:

Type Description
ValueError

If no source waveform is set, if the time parameters are invalid, if f_eval is not one of network.frequencies, if fft_block_bytes is not positive, or if the network is missing the lumped RLC fields required by the state-space solver.

TypeError

If fft_block_bytes is not an integer, or if progress or should_cancel is not callable.

NotImplementedError

If solver is not one of the supported identifiers.

StudyCancelled

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

Warns:

Type Description
TransientModelWarning

If the network carries mutual coupling the FFT solver cannot evaluate, if the active fault carries per-frequency scalings other than 1 (both solvers apply the source waveform as given and ignore them), or if the FFT window ends while the response is still ringing.

ModelAssumptionWarning

Code TRANSIENT_PHASE_SPLIT, state-space solver only: the phase current of a meshed network divides between routes of different R/L ratio, so the split the coupling uses -- exact at f_eval -- differs at the other frequencies in the waveform.

Source code in src/groundinsight/simulation/transient.py
def solve(
    self,
    *,
    t_end: float,
    dt: float,
    solver: str = "fft",
    f_eval: Optional[float] = None,
    zero_pad: bool = False,
    fft_block_bytes: Optional[int] = None,
    progress: Optional[Callable[[int, int, str], None]] = None,
    should_cancel: Optional[Callable[[], bool]] = None,
) -> ResultTransient:
    """
    Run the transient solve and return the resulting time series.

    Parameters
    ----------
    t_end : float
        End time of the simulation in seconds. ``t=0`` is always the
        start. Both solvers use the same grid (see
        :func:`_time_grid`), which may extend by one sample so the
        sample count is even.
    dt : float
        Time-step in seconds. For the FFT solver this determines the
        Nyquist frequency ``f_max = 1/(2*dt)`` and therefore the
        highest harmonic resolved. For the state-space solver ``dt``
        is the integration time-step (first-order hold on the source
        signal between samples).
    solver : {'fft', 'state_space'}, optional
        Solver to use. ``"fft"`` uses ``BusType.impedance_formula``
        and ``BranchType.self_impedance_formula`` (frequency-domain
        impedances); ``"state_space"`` uses the lumped RLC fields on
        ``BusType`` / ``BranchType`` and integrates with
        :func:`scipy.signal.lsim`. Defaults to ``"fft"``.
    f_eval : float, optional
        *State-space solver only.* The frequency in Hz at which the
        lumped ``R`` / ``L`` / ``C`` values and the Thevenin source
        impedance are read. The state-space model treats them as
        frequency-independent, so this picks the operating point.
        Must be one of ``network.frequencies``. Defaults to the
        **smallest strictly positive** entry of ``network.frequencies``
        rather than to its first element: with ``[0, 50]`` the first
        element is 0 Hz, where ``L_src = Im(Z_src)/omega`` is not
        defined -- reading it there as zero changes the EPR of the
        reference case by a factor of 680, decided by nothing but the
        order of the frequency list.
    zero_pad : bool, optional
        *FFT solver only.* Solve on a window twice as long and return
        only its first half. The DFT is periodic, so a response that
        has not decayed by ``t_end`` wraps around into the start of
        the trace; doubling the window pushes the wrap out of the
        reported interval. Costs twice the solve time. Defaults to
        ``False``.
    fft_block_bytes : int, optional
        *FFT solver only.* Upper bound in bytes for one batch of dense
        complex admittance matrices (``16 * n**2`` bytes per frequency
        bin for ``n`` active buses). The solver assembles and solves at
        most 512 bins per batch; above about 181 buses this budget
        decides instead, so memory stays bounded for any network size --
        a fixed 512-bin batch would take 1.3 GB at 400 buses and 8.2 GB
        at 1000. The result does not depend on it (every bin is solved on
        its own). A very small budget costs time on mid-size networks,
        because every batch is one pass of the element-wise assembly:
        150 buses and 1001 bins took 4.5 s at 1 MiB (two bins per batch)
        against 0.7 s at the default. A single matrix larger than the
        budget is solved one bin at a time and logged. Defaults to
        256 MiB.
    progress : callable, optional
        ``progress(done, total, label)``. The FFT solver reports one unit
        per batch of frequency bins solved together (see
        ``fft_block_bytes``), the state-space solver the two stages
        ``"assembled"`` and ``"integrated"``. See
        :mod:`groundinsight.progress`.
    should_cancel : callable, optional
        Asked before the solve and before every unit; a true answer
        raises :class:`~groundinsight.progress.StudyCancelled`. The
        integration of the state-space solver is a single library call
        and cannot be interrupted once it runs.

    Returns
    -------
    ResultTransient
        Time-domain results at the observation points.

    Raises
    ------
    ValueError
        If no source waveform is set, if the time parameters are
        invalid, if ``f_eval`` is not one of ``network.frequencies``,
        if ``fft_block_bytes`` is not positive, or if the network is
        missing the lumped RLC fields required by the state-space
        solver.
    TypeError
        If ``fft_block_bytes`` is not an integer, or if ``progress`` or
        ``should_cancel`` is not callable.
    NotImplementedError
        If ``solver`` is not one of the supported identifiers.
    StudyCancelled
        If ``should_cancel()`` returned true; the network is as found.

    Warns
    -----
    TransientModelWarning
        If the network carries mutual coupling the FFT solver cannot
        evaluate, if the active fault carries per-frequency
        ``scalings`` other than 1 (both solvers apply the source
        waveform as given and ignore them), or if the FFT window ends
        while the response is still ringing.
    ModelAssumptionWarning
        Code ``TRANSIENT_PHASE_SPLIT``, state-space solver only: the
        phase current of a meshed network divides between routes of
        different R/L ratio, so the split the coupling uses -- exact at
        ``f_eval`` -- differs at the other frequencies in the waveform.
    """
    block_bytes = _validated_block_bytes(fft_block_bytes)
    if solver not in ("fft", "state_space"):
        raise NotImplementedError(
            f"Unknown transient solver: '{solver}'. "
            "Supported: 'fft', 'state_space'."
        )
    self._hooks = StudyHooks(
        "TransientStudy.solve", 0, progress, should_cancel
    )
    try:
        with restore_on_cancel(self.network):
            self._hooks.checkpoint()
            if solver == "fft":
                return self._solve_fft(
                    t_end=t_end, dt=dt, zero_pad=zero_pad, block_bytes=block_bytes
                )
            return self._solve_state_space(t_end=t_end, dt=dt, f_eval=f_eval)
    finally:
        self._hooks = StudyHooks("TransientStudy.solve", 0)

Waveforms

waveforms

Waveform Library for Transient Simulations.

This module provides a small library of factory functions that return Callable[[np.ndarray], np.ndarray] waveforms suitable for the :class:groundinsight.simulation.transient.TransientStudy solver. Each factory captures its own parameters and returns a vectorised function f(t) -> values that can be called with an array of time samples.

The included waveforms cover the typical fault-current scenarios for low- and medium-voltage grounding studies:

  • :func:step -- a Heaviside-style on/off pulse, the simplest fault model (the source comes on at t_on and off again at t_off).
  • :func:sinusoidal_with_dc_offset -- a power-frequency current with an exponentially decaying DC component, the textbook representation of a single-line-to-ground fault current including the asymmetry caused by the inductive loop.
  • :func:damped_oscillation -- a damped sinusoid useful for switching transients and ringing studies.

Custom waveforms can be defined as any user function that accepts a 1-D np.ndarray of time samples and returns an array of the same shape.

Examples:

>>> import numpy as np
>>> from groundinsight.simulation import waveforms
>>> pulse = waveforms.step(100.0, t_on=0.01, t_off=0.03)
>>> pulse(np.array([0.0, 0.02, 0.04])).tolist()
[0.0, 100.0, 0.0]

damped_oscillation

damped_oscillation(
    amplitude: float,
    frequency_hz: float,
    decay_tau: float,
    *,
    phase_rad: float = 0.0,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]

Construct a damped sinusoid, useful for switching-transient studies.

The waveform is::

x(t) = A * exp(-(t - t_on)/tau) * sin(omega*(t - t_on) + phi)

inside the on-window [t_on, t_off), and zero outside.

Parameters:

Name Type Description Default
amplitude float

Initial peak amplitude.

required
frequency_hz float

Oscillation frequency in Hz.

required
decay_tau float

Decay time constant in seconds.

required
phase_rad float

Phase offset of the sinusoid, in radians. Defaults to 0.0.

0.0
t_on float

Onset time, in seconds. Defaults to 0.0.

0.0
t_off float

Cut-off time, in seconds. None lets the oscillation decay naturally to the end of the time grid.

None

Returns:

Type Description
callable

A vectorised waveform.

Examples:

>>> w = damped_oscillation(
...     amplitude=1e3, frequency_hz=500.0, decay_tau=2e-3,
...     t_on=0.01,
... )
Source code in src/groundinsight/simulation/waveforms.py
def damped_oscillation(
    amplitude: float,
    frequency_hz: float,
    decay_tau: float,
    *,
    phase_rad: float = 0.0,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]:
    """
    Construct a damped sinusoid, useful for switching-transient studies.

    The waveform is::

        x(t) = A * exp(-(t - t_on)/tau) * sin(omega*(t - t_on) + phi)

    inside the on-window ``[t_on, t_off)``, and zero outside.

    Parameters
    ----------
    amplitude : float
        Initial peak amplitude.
    frequency_hz : float
        Oscillation frequency in Hz.
    decay_tau : float
        Decay time constant in seconds.
    phase_rad : float, optional
        Phase offset of the sinusoid, in radians. Defaults to ``0.0``.
    t_on : float, optional
        Onset time, in seconds. Defaults to ``0.0``.
    t_off : float, optional
        Cut-off time, in seconds. ``None`` lets the oscillation decay
        naturally to the end of the time grid.

    Returns
    -------
    callable
        A vectorised waveform.

    Examples
    --------
    >>> w = damped_oscillation(
    ...     amplitude=1e3, frequency_hz=500.0, decay_tau=2e-3,
    ...     t_on=0.01,
    ... )
    """
    if not np.isfinite(frequency_hz) or frequency_hz <= 0:
        raise ValueError(
            "damped_oscillation: frequency_hz must be a finite positive "
            f"number (got {frequency_hz!r})."
        )
    if not np.isfinite(decay_tau) or decay_tau <= 0:
        raise ValueError(
            "damped_oscillation: decay_tau must be a finite positive "
            f"number (got {decay_tau!r}). decay_tau == 0 divides by zero "
            "and decay_tau < 0 produces an exponentially growing "
            "waveform — almost certainly not what was intended."
        )
    _validate_window(t_on, t_off, "damped_oscillation")
    omega = 2.0 * np.pi * frequency_hz

    def _wave(t: np.ndarray) -> np.ndarray:
        t = np.asarray(t, dtype=float)
        on = t >= t_on
        if t_off is not None:
            on = on & (t < t_off)
        tau_local = np.maximum(t - t_on, 0.0)
        envelope = amplitude * np.exp(-tau_local / decay_tau)
        signal = envelope * np.sin(omega * tau_local + phase_rad)
        return np.where(on, signal, 0.0)

    return _wave

sinusoidal_with_dc_offset

sinusoidal_with_dc_offset(
    amplitude: float,
    frequency_hz: float,
    *,
    phase_rad: float = 0.0,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
    dc_amplitude: float = 0.0,
    dc_decay_tau: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]

Construct a windowed sinusoid with optional exponentially decaying DC.

Models the typical single-line-to-ground fault current::

i(t) = A * sin(omega*(t - t_on) + phi) + I_dc * exp(-(t - t_on)/tau)

multiplied by a rectangular window between t_on and t_off. The DC component captures the asymmetric peak that arises when the fault occurs at a non-zero-crossing instant of the source voltage and the loop has finite inductance.

Parameters:

Name Type Description Default
amplitude float

Peak value of the AC component.

required
frequency_hz float

Power frequency in Hz (e.g. 50 or 60).

required
phase_rad float

Initial phase of the AC component, in radians. Defaults to 0.0.

0.0
t_on float

Fault initiation time, in seconds. Defaults to 0.0.

0.0
t_off float

Fault clearing time, in seconds. None keeps the fault on until the end of the time grid.

None
dc_amplitude float

Initial value of the DC component. Defaults to 0.0 (no DC offset).

0.0
dc_decay_tau float

Time constant L/R of the loop governing the DC decay, in seconds. None disables the decay (DC stays constant during the on-window). Required when dc_amplitude != 0 and a finite decay is desired.

None

Returns:

Type Description
callable

A vectorised waveform f(t) -> values.

Examples:

>>> w = sinusoidal_with_dc_offset(
...     amplitude=20e3, frequency_hz=50.0,
...     t_on=0.02, t_off=0.12,
...     dc_amplitude=10e3, dc_decay_tau=0.05,
... )
Source code in src/groundinsight/simulation/waveforms.py
def sinusoidal_with_dc_offset(
    amplitude: float,
    frequency_hz: float,
    *,
    phase_rad: float = 0.0,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
    dc_amplitude: float = 0.0,
    dc_decay_tau: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]:
    """
    Construct a windowed sinusoid with optional exponentially decaying DC.

    Models the typical single-line-to-ground fault current::

        i(t) = A * sin(omega*(t - t_on) + phi) + I_dc * exp(-(t - t_on)/tau)

    multiplied by a rectangular window between ``t_on`` and ``t_off``.
    The DC component captures the asymmetric peak that arises when the
    fault occurs at a non-zero-crossing instant of the source voltage
    and the loop has finite inductance.

    Parameters
    ----------
    amplitude : float
        Peak value of the AC component.
    frequency_hz : float
        Power frequency in Hz (e.g. 50 or 60).
    phase_rad : float, optional
        Initial phase of the AC component, in radians. Defaults to ``0.0``.
    t_on : float, optional
        Fault initiation time, in seconds. Defaults to ``0.0``.
    t_off : float, optional
        Fault clearing time, in seconds. ``None`` keeps the fault on
        until the end of the time grid.
    dc_amplitude : float, optional
        Initial value of the DC component. Defaults to ``0.0`` (no DC
        offset).
    dc_decay_tau : float, optional
        Time constant ``L/R`` of the loop governing the DC decay, in
        seconds. ``None`` disables the decay (DC stays constant during
        the on-window). Required when ``dc_amplitude != 0`` and a finite
        decay is desired.

    Returns
    -------
    callable
        A vectorised waveform ``f(t) -> values``.

    Examples
    --------
    >>> w = sinusoidal_with_dc_offset(
    ...     amplitude=20e3, frequency_hz=50.0,
    ...     t_on=0.02, t_off=0.12,
    ...     dc_amplitude=10e3, dc_decay_tau=0.05,
    ... )
    """
    if not np.isfinite(frequency_hz) or frequency_hz <= 0:
        raise ValueError(
            "sinusoidal_with_dc_offset: frequency_hz must be a finite "
            f"positive number (got {frequency_hz!r}). Negative frequency "
            "is silently equivalent to flipping the phase and "
            "frequency_hz == 0 collapses to a constant offset that "
            "masks user confusion with the dc_amplitude term."
        )
    if dc_decay_tau is not None and (
        not np.isfinite(dc_decay_tau) or dc_decay_tau <= 0
    ):
        raise ValueError(
            "sinusoidal_with_dc_offset: dc_decay_tau must be a finite "
            f"positive number when set (got {dc_decay_tau!r}). Pass "
            "dc_decay_tau=None to disable the decay altogether."
        )
    _validate_window(t_on, t_off, "sinusoidal_with_dc_offset")
    omega = 2.0 * np.pi * frequency_hz

    def _wave(t: np.ndarray) -> np.ndarray:
        t = np.asarray(t, dtype=float)
        on = t >= t_on
        if t_off is not None:
            on = on & (t < t_off)

        tau_local = t - t_on
        ac = amplitude * np.sin(omega * tau_local + phase_rad)
        if dc_amplitude == 0.0:
            dc = np.zeros_like(t)
        elif dc_decay_tau is None:
            dc = np.full_like(t, dc_amplitude)
        else:
            # Exponential decay starting at t_on, only meaningful in the
            # on-window. Outside the window the rectangular factor below
            # forces it to zero anyway.
            dc = dc_amplitude * np.exp(
                -np.maximum(tau_local, 0.0) / dc_decay_tau
            )

        return np.where(on, ac + dc, 0.0)

    return _wave

step

step(
    amplitude: float,
    *,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]

Construct a rectangular pulse waveform.

The output is zero before t_on, equals amplitude between t_on and t_off and is zero again after t_off. With t_off=None the pulse extends to the end of the time grid (a classic Heaviside step).

Parameters:

Name Type Description Default
amplitude float

Plateau value of the pulse.

required
t_on float

Time at which the pulse switches on, in seconds. Defaults to 0.0.

0.0
t_off float

Time at which the pulse switches off, in seconds. None means "stays on indefinitely". Defaults to None.

None

Returns:

Type Description
callable

A vectorised waveform function f(t) -> values.

Examples:

>>> import numpy as np
>>> w = step(amplitude=100.0, t_on=0.02, t_off=0.12)
>>> y = w(np.linspace(0.0, 0.2, 5))
Source code in src/groundinsight/simulation/waveforms.py
def step(
    amplitude: float,
    *,
    t_on: float = 0.0,
    t_off: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]:
    """
    Construct a rectangular pulse waveform.

    The output is zero before ``t_on``, equals ``amplitude`` between
    ``t_on`` and ``t_off`` and is zero again after ``t_off``. With
    ``t_off=None`` the pulse extends to the end of the time grid
    (a classic Heaviside step).

    Parameters
    ----------
    amplitude : float
        Plateau value of the pulse.
    t_on : float, optional
        Time at which the pulse switches on, in seconds. Defaults to
        ``0.0``.
    t_off : float, optional
        Time at which the pulse switches off, in seconds. ``None`` means
        "stays on indefinitely". Defaults to ``None``.

    Returns
    -------
    callable
        A vectorised waveform function ``f(t) -> values``.

    Examples
    --------
    >>> import numpy as np
    >>> w = step(amplitude=100.0, t_on=0.02, t_off=0.12)
    >>> y = w(np.linspace(0.0, 0.2, 5))
    """
    _validate_window(t_on, t_off, "step")

    def _wave(t: np.ndarray) -> np.ndarray:
        t = np.asarray(t, dtype=float)
        on = t >= t_on
        if t_off is not None:
            on = on & (t < t_off)
        return np.where(on, amplitude, 0.0)

    return _wave

The matching matplotlib helpers plot_epr_transient and plot_branch_current_transient are documented on the Plotting page.