Skip to content

Top-level package

import groundinsight as gi is all everyday work needs: the package re-exports every public function, class and constant at the top level. This page lists each of them — the names of groundinsight.__all__ and those of the service layer groundinsight.api — with the API page that documents it, and renders the few that have no page of their own below.

import groundinsight as gi

net = gi.create_network(name="example", frequencies=[50.0])
print(len(gi.__all__) > 100, gi.__version__ == gi.show_versions()["groundinsight"])  # True True

from groundinsight import * imports exactly these names. Everything else — module internals, the ORM classes of the database, the helpers named in the internal API — can change in any release; the names below follow the deprecation policy (a renamed or removed name keeps working with a DeprecationWarning for at least two releases and six months).

groundinsight

Topic Names Page
Build and solve create_network, create_bus, create_branch, create_source, create_voltage_source, create_fault, create_network_assistant, set_active_fault, run_fault, build_electrical_network, create_paths Network operations
Solve without side effects, check, diagnostics solve, check_network, Diagnostic, GroundinsightWarning, ModelAssumptionWarning, InputWarning, StudyCancelled Service functions
Model classes Network, Bus, BusType, Branch, BranchType, Source, Fault, Path, Result, ResultBus, ResultBranch, ComplexNumber, RES_FAULT_SCHEMA Core models
Rho searches, short-circuit and thermal checks find_max_rho_scaling, find_max_rho_f_scaling, evaluate_max_epr_under_k, select_rho_f_from_catalog, check_conductor_limits, check_node_limits, resolve_fault_sc_characteristics, FaultShortCircuitData, admissible_short_circuit_current, final_temperature, iec60909_m, iec60949_k, kappa_from_r_to_x, peak_short_circuit_current, thermal_equivalent_current, FINAL_TEMPERATURES, CABLE_INSULATION_LIMITS, IEC60949_MATERIALS Analysis
Decomposition at the fault Cut, CutAnalysis, analyze_cuts Decomposition
Location response BusResponse, bus_response Location response
Reference cases ReferenceCase, REFERENCE_CASES, run_reference_cases Reference cases
Parameter sweeps SweepPoint, SweepResult, rho_f_points, run_sweep Parameter sweeps
Statistics summarize, classify Statistics
Outage studies Outage, OutageStudyResult, outage_context, run_outage_study Outage studies
Transient studies TransientStudy, ResultTransient, waveforms Transient simulations
Plots plot_bus_voltages, plot_branch_currents, plot_bus_currents, plot_epr_transient, plot_branch_current_transient Plotting
Importers, tables, project files ImportDefaults, from_pandapower, preview_pandapower_import, read_shortcircuit_results, apply_shortcircuit_characteristics, network_from_tables, save_network_to_json, load_network_from_json I/O
Database Database, start_dbsession, close_dbsession, save_bustype_to_db, load_bustypes_from_db, save_branchtype_to_db, load_branchtypes_from_db, save_network_to_db, load_network_from_db, needs_migration, migrate_database, MigrationReport Database
Path search PathfinderSettings, clear_pathfinder_cache, get_pathfinder_cache_size, set_pathfinder_cache_size Pathfinder
Logging, versions, warning classes set_log_level, show_versions, NetworkFrequencyOrderWarning, TransientModelWarning, DCLimitWarning below

groundinsight.api

The service layer for front ends is a namespace of its own and is not re-exported at the top level: from groundinsight.api import ProjectSession. How to use it: Service layer and command line.

Topic Names Page
Sessions and stores ProjectSession, ProjectError, ProjectStore, MemoryStore, DatabaseStore, EXAMPLES Service functions
Commands Command, CommandError, COMMAND_OPS, parse_command, AddBus, UpdateBus, RemoveBus, AddBranch, UpdateBranch, RemoveBranch, AddSource, UpdateSource, RemoveSource, AddFault, UpdateFault, RemoveFault, AddBusType, UpdateBusType, RemoveBusType, AddBranchType, UpdateBranchType, RemoveBranchType, SetFrequencies Service functions
Jobs JobRunner, JobHandle, JobCancelled, JobTimeout, JobFailed, snapshot_network, parse_job_request Service functions
DTOs and schemas DTO_SCHEMA_VERSION, json_schemas, finite_or_none, ElementRefDTO, DiagnosticDTO, CheckReportDTO, ColumnDTO, TableDTO, NetworkTablesDTO, SessionLimitsDTO, NetworkSummaryDTO, CommandResultDTO, KeyFigureRowDTO, KeyFiguresDTO, FaultResultDTO, FaultResultsDTO, StudyResultDTO, ProgressDTO, JobErrorDTO, JobStatusDTO, ComplexDTO, SolveRequestDTO, SolveAllRequestDTO, SweepPointDTO, SweepRequestDTO, OutageScenarioDTO, OutageStudyRequestDTO, MaxRhoRequestDTO Service functions

Rendered here

groundinsight package initialisation.

Re-exports the public API surface of groundinsight: the SQLite store (Database and the module-level session helpers), the JSON project file, the top-level network factory functions (create_network, create_bus, create_branch, create_source, create_fault), the fault solver (run_fault), the outage / what-if and inverse-rho analysis helpers, the transient study workflow and the matplotlib plotting helpers. All symbols re-exported here are available as groundinsight.<name> and are listed in :data:__all__.

This module holds no implementation: imports, __all__, __version__ and the PEP 562 __getattr__ that resolves deprecated names, so importing the package binds names and nothing else. Everything else lives in a module of its own -- the logging default and :func:set_log_level in _logging, :func:show_versions in _versions, the persistence in database.store and io.project_file.

NetworkFrequencyOrderWarning

NetworkFrequencyOrderWarning(
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
)

Bases: GroundinsightWarning

Warning category for non-strictly-monotone Network.frequencies.

Emitted by :class:Network when frequencies is supplied in a non-strictly-increasing order. The FFT transient solver (:mod:groundinsight.simulation.transient) uses the order of Network.frequencies to map spectral bins to the impedance dictionary; a descending or shuffled list produces a transient with the spectral bins reversed and is almost always a user error.

Mirrors :class:groundfield.solver.engine.EngineFrequencyOrderWarning so users get consistent diagnostics across the three packages of the earthing-platform stack.

Notes

Suppress with warnings.simplefilter('ignore', NetworkFrequencyOrderWarning); surface only once per Python process by combining it with simplefilter('once', ...).

Examples:

>>> import warnings
>>> import groundinsight as gi
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always")
...     net = gi.create_network(name="n", frequencies=[250.0, 50.0])
>>> [w.category.__name__ for w in caught]
['NetworkFrequencyOrderWarning']
Source code in src/groundinsight/diagnostics.py
def __init__(
    self,
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
):
    super().__init__(*args)
    if severity not in _SEVERITIES:
        raise ValueError(
            f"severity must be one of {_SEVERITIES}, got {severity!r}"
        )
    self.code = code if code is not None else self.default_code
    self.elements = tuple((str(kind), str(name)) for kind, name in elements)
    self.severity = severity
    sink = _SINK.get()
    if sink is not None:
        sink.append(
            Diagnostic(
                code=self.code,
                severity=self.severity,
                category=type(self).__name__,
                message=str(self),
                elements=list(self.elements),
            )
        )

TransientModelWarning

TransientModelWarning(
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
)

Bases: GroundinsightWarning

Warning category for a transient run whose model is narrower than its input.

Emitted by :mod:groundinsight.simulation.transient when the network carries something a solver path cannot represent, and the result is therefore quantitatively different from what the same network yields elsewhere. It is deliberately not an error: the remaining physics is still solved correctly and the answer is often the one the user wants, but the difference has to be visible rather than inferred from a documentation chapter.

Current cases:

  • the FFT solver meeting a branch with mutual coupling, which it does not evaluate (the stationary solver and the state-space solver do),
  • either transient solver meeting an active fault with per-frequency scalings other than 1, which is a frequency-domain concept the time-domain source waveform replaces,
  • a mutual inductance larger than the branch's own L_self, which is not physically realisable for two coupled conductors and is almost always a mH/H unit slip,
  • the state-space solver meeting a voltage source that reaches the fault, whose coupling it does not model (code TRANSIENT_COUPLING_SKIPPED), or a purely resistive branch carrying mutual data (TRANSIENT_RESISTIVE_COUPLING_IGNORED).
Notes

Suppress with warnings.simplefilter('ignore', TransientModelWarning); turn into an error with simplefilter('error', TransientModelWarning).

Examples:

>>> import groundinsight as gi
>>> issubclass(gi.TransientModelWarning, gi.GroundinsightWarning)
True
Source code in src/groundinsight/diagnostics.py
def __init__(
    self,
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
):
    super().__init__(*args)
    if severity not in _SEVERITIES:
        raise ValueError(
            f"severity must be one of {_SEVERITIES}, got {severity!r}"
        )
    self.code = code if code is not None else self.default_code
    self.elements = tuple((str(kind), str(name)) for kind, name in elements)
    self.severity = severity
    sink = _SINK.get()
    if sink is not None:
        sink.append(
            Diagnostic(
                code=self.code,
                severity=self.severity,
                category=type(self).__name__,
                message=str(self),
                elements=list(self.elements),
            )
        )

DCLimitWarning

DCLimitWarning(
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
)

Bases: GroundinsightWarning

Something about a formula at 0 Hz needed a decision rather than a value.

Raised in four situations, all of them at f = 0 only:

  • the imaginary part at DC is dropped and is not small enough to be numerical dust -- a reactance cannot survive at DC, so the value is a modelling statement that the real-part fallback silently overrides;
  • the limit is not well resolved, i.e. the last decade of the approach sequence still moved the real part appreciably and the step did not shrink at least five-fold from the decade before -- how sqrt(f) or log(f) behave near DC;
  • the approach sequence diverges and the element is treated as an open circuit;
  • an impedance is zero (or too small to invert) at DC and is replaced by the small finite substitute of :func:dc_substitute_impedance.

It is a warning and not an error on purpose: in every one of the four cases there is a defensible value to continue with, and a DC study that stops on the first unusual formula is of no use. Promote it with warnings.simplefilter("error", DCLimitWarning) to make a study strict.

A real part of minus infinity -- log(f) at 0 Hz -- is deliberately not a fifth case: it is the limit of a negative resistance, there is no defensible value to continue with, and :func:check_passive_impedance refuses it like any negative real part.

Examples:

>>> import groundinsight as gi
>>> issubclass(gi.DCLimitWarning, gi.GroundinsightWarning)
True
Source code in src/groundinsight/diagnostics.py
def __init__(
    self,
    *args,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
):
    super().__init__(*args)
    if severity not in _SEVERITIES:
        raise ValueError(
            f"severity must be one of {_SEVERITIES}, got {severity!r}"
        )
    self.code = code if code is not None else self.default_code
    self.elements = tuple((str(kind), str(name)) for kind, name in elements)
    self.severity = severity
    sink = _SINK.get()
    if sink is not None:
        sink.append(
            Diagnostic(
                code=self.code,
                severity=self.severity,
                category=type(self).__name__,
                message=str(self),
                elements=list(self.elements),
            )
        )

set_log_level

set_log_level(
    level: Union[int, str] = "INFO",
) -> logging.Logger

Enable console logging for the groundinsight package.

Convenience helper for interactive use (notebooks, scripts). Attaches a single :class:logging.StreamHandler with a simple formatter to the groundinsight package logger and sets the requested level. Subsequent calls only adjust the level on the same handler instance, so it is safe to call this helper repeatedly without accumulating duplicate console handlers — even across mixed set_log_level("DEBUG") -> set_log_level("INFO") toggles, and even when logging.basicConfig(...) has been called at the root logger.

Parameters:

Name Type Description Default
level int or str

Log level either as a numeric constant (e.g. logging.INFO) or as a string name ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"). Defaults to "INFO".

'INFO'

Returns:

Type Description
Logger

The configured groundinsight package logger, for further adjustments by the caller if desired.

Notes

If you have also called :func:logging.basicConfig at the root logger level, every record will be emitted twice: once through the package handler installed here and once through the root handler installed by basicConfig. To suppress the duplicate either call logging.getLogger("groundinsight").propagate = False explicitly, or rely solely on basicConfig and do not call :func:set_log_level.

Examples:

>>> import groundinsight as gi
>>> gi.set_log_level("INFO")
<Logger groundinsight (INFO)>
Source code in src/groundinsight/_logging.py
def set_log_level(level: Union[int, str] = "INFO") -> logging.Logger:
    """
    Enable console logging for the ``groundinsight`` package.

    Convenience helper for interactive use (notebooks, scripts). Attaches a
    single :class:`logging.StreamHandler` with a simple formatter to the
    ``groundinsight`` package logger and sets the requested level.
    Subsequent calls only adjust the level on the *same* handler instance,
    so it is safe to call this helper repeatedly without accumulating
    duplicate console handlers — even across mixed
    ``set_log_level("DEBUG") -> set_log_level("INFO")`` toggles, and even
    when ``logging.basicConfig(...)`` has been called at the root logger.

    Parameters
    ----------
    level : int or str, optional
        Log level either as a numeric constant (e.g. ``logging.INFO``) or
        as a string name (``"DEBUG"``, ``"INFO"``, ``"WARNING"``,
        ``"ERROR"``, ``"CRITICAL"``). Defaults to ``"INFO"``.

    Returns
    -------
    logging.Logger
        The configured ``groundinsight`` package logger, for further
        adjustments by the caller if desired.

    Notes
    -----
    If you have also called :func:`logging.basicConfig` at the root logger
    level, every record will be emitted twice: once through the package
    handler installed here and once through the root handler installed by
    ``basicConfig``. To suppress the duplicate either call
    ``logging.getLogger("groundinsight").propagate = False`` explicitly,
    or rely solely on ``basicConfig`` and do not call
    :func:`set_log_level`.

    Examples
    --------
    >>> import groundinsight as gi
    >>> gi.set_log_level("INFO")  # doctest: +ELLIPSIS
    <Logger groundinsight (INFO)>
    """
    pkg_logger = logging.getLogger(PACKAGE_LOGGER)
    pkg_logger.setLevel(level)

    # Keep the marked handler of an earlier call and remove every other
    # StreamHandler of the package logger (one attached by user code, for
    # instance), so that a record is not printed twice.
    marked = [
        h for h in pkg_logger.handlers if getattr(h, _GI_HANDLER_MARK, False)
    ]
    for h in list(pkg_logger.handlers):
        if (
            isinstance(h, logging.StreamHandler)
            and not isinstance(h, logging.NullHandler)
            and not getattr(h, _GI_HANDLER_MARK, False)
        ):
            pkg_logger.removeHandler(h)

    if marked:
        # Re-use the existing marked handler — just align its level so
        # filtering happens at both the logger and the handler level.
        handler = marked[0]
        # Defensive: if more than one marked handler is attached, keep only
        # the first.
        for extra in marked[1:]:
            pkg_logger.removeHandler(extra)
        handler.setLevel(level)
    else:
        handler = logging.StreamHandler()
        handler.setFormatter(
            logging.Formatter("%(levelname)s [%(name)s] %(message)s")
        )
        handler.setLevel(level)
        setattr(handler, _GI_HANDLER_MARK, True)
        pkg_logger.addHandler(handler)

    return pkg_logger

show_versions

show_versions() -> Dict[str, str]

Return version information for groundinsight and its peers.

Cross-repo convention helper introduced for the seventh 2026-05-18 review pass roadmap entry "ADR-0013 — Cross-repo show_versions convention". The returned mapping always contains a "groundinsight" key with the value of :data:__version__; optional peers "groundfield" and "groundmeas" are added when the respective package is installed in the active interpreter. Python and platform information are reported under the "python" and "platform" keys so a bug report can include the full earthing-platform stack in a single call.

Returns:

Type Description
dict of str to str

A mapping {"groundinsight": <__version__>, "python": "3.14.6", "platform": "Linux-...", ...}. The first value is always :data:__version__; no version literal is repeated here so the docstring cannot drift away from the release. The dict is freshly built on every call and safe to mutate.

Examples:

>>> import groundinsight as gi
>>> info = gi.show_versions()
>>> info["groundinsight"] == gi.__version__
True
Source code in src/groundinsight/_versions.py
def show_versions() -> Dict[str, str]:
    """Return version information for ``groundinsight`` and its peers.

    Cross-repo convention helper introduced for the *seventh
    2026-05-18 review pass* roadmap entry "ADR-0013 — Cross-repo
    `show_versions` convention". The returned mapping always contains
    a ``"groundinsight"`` key with the value of :data:`__version__`;
    optional peers ``"groundfield"`` and ``"groundmeas"`` are added
    when the respective package is installed in the active
    interpreter. Python and platform information are reported under
    the ``"python"`` and ``"platform"`` keys so a bug report can
    include the full earthing-platform stack in a single call.

    Returns
    -------
    dict of str to str
        A mapping ``{"groundinsight": <__version__>, "python": "3.14.6",
        "platform": "Linux-...", ...}``. The first value is always
        :data:`__version__`; no version literal is repeated here so the
        docstring cannot drift away from the release. The dict is freshly
        built on every call and safe to mutate.

    Examples
    --------
    >>> import groundinsight as gi
    >>> info = gi.show_versions()
    >>> info["groundinsight"] == gi.__version__
    True
    """
    import platform
    import sys

    # The package ``__init__`` imports this module before it defines
    # ``__version__``; read it at call time.
    from . import __version__

    info: Dict[str, str] = {
        "groundinsight": __version__,
        "python": sys.version.split()[0],
        "platform": platform.platform(),
    }
    for peer in ("groundfield", "groundmeas"):
        try:
            mod = __import__(peer)
        except ImportError:
            continue
        peer_version = getattr(mod, "__version__", None)
        if peer_version is not None:
            info[peer] = str(peer_version)
    return info