Skip to content

Service functions

Functions for code that holds a network on behalf of someone else — a GUI session, a server answering requests, a study that has to hand the network back unchanged. They answer the questions such a caller asks before and during a calculation without the side effects of the interactive API:

Question Function
What would run_fault return — without touching my network? gi.solve
What is wrong with this network, all at once, as data? gi.check_network
How far is this study, and can I stop it? progress / should_cancel
How do I get a network from a spreadsheet, and back? gi.network_from_tables / Network.to_tables
Which spelling of a parameter is the current one? canonical names
Which conditions qualify a result, by code? diagnostic codes
How does a GUI or a server hold a project, edit it with undo and run jobs? groundinsight.api
How do I solve or check a project file without writing Python? groundinsight run / check

Solve without side effects

gi.run_fault(net, fault) activates the fault, may drop or rebuild net.paths, attaches the assembled electrical network and stores the result in net.results — convenient in a notebook, where net.res_buses() follows. gi.solve(net, fault) runs the same pipeline on an overlay that shares the bus, branch and source objects of net (a solve only reads them) and owns everything a solve writes. The numbers are therefore bit-identical to run_fault, and net is the same object afterwards: same JSON, same stored results, same active fault, same paths, same assembled system — also when the solve raises.

run_fault solve
returns the Result yes yes (a new object)
net.results[fault] replaced unchanged
net.active_fault set to fault unchanged
net.paths may be dropped or rebuilt unchanged
net.electrical_network replaced (read by bus_response, analyze_cuts) unchanged
Result.diagnostics yes yes, identical
Result.input_digest stamped stamped, identical
# fragment: assumes a network `net` with the fault "F1"
import groundinsight as gi

result = gi.solve(net, "F1")              # net is left as it was
epr = {bus.name: bus.uepr for bus in result.buses}

net.results["F1"] = result                # keep it after all, if wanted
net.res_buses(fault="F1")
net.stale_results()                       # [] -- current until the next edit

Do not modify the network while a solve runs, and do not solve the same Network object from several threads at once. Different networks can be solved in parallel: the path search keeps its settings and memo per network (see Pathfinder). Reading the network from another thread meanwhile is safe.

Pre-flight check

gi.check_network(net) returns every problem of a network as a list of Diagnostic records — the same type as Result.diagnostics — and never raises. Each record has a stable code, the elements it is about as (kind, name) pairs, and a severity:

  • error — run_fault would raise, or would return an answer that does not describe the network: a branch whose end names an unknown bus, or a source on such a bus, is dropped by the solver without a word and the result reads 0 V. The editing API refuses such a reference, but a network loaded from a hand-edited file or filled in by a script can carry one.
  • warning — the network solves, but part of the input has no effect or a documented default stands in for a missing value.
# fragment: assumes a network `net` with the fault "F1"
issues = gi.check_network(net)
blocking = [d for d in issues if d.severity == "error"]
for d in issues:
    print(d.severity, d.code, d.elements, d.message)

gi.check_network(net, fault="F1")         # fault checks for F1 only

The check is structural — no assembly, no solve — so an editor can run it after every change. Where the solver already validates something, the check calls that code and converts its exception or warning, so the two cannot disagree. Conditions only a solve can detect (a heuristic phase-current split, for example) arrive with the result in Result.diagnostics. Package warnings raised during the check keep their own codes (FREQUENCY_ORDER, DC_LIMIT).

Code Severity Meaning
NOT_A_NETWORK error The argument is not a Network.
CHECK_FAILED error A check raised on an unforeseen malformation; the others still ran.
ELEMENT_INVALID error An entry of buses/branches/sources/faults is not an element of the expected type.
FREQUENCIES_INVALID error Empty frequency list, duplicates, non-finite or negative values (in-place edits bypass the validator).
NO_ACTIVE_BUS error No active bus.
NO_SOURCE error No source.
NO_FAULT error No fault.
FAULT_UNKNOWN error The fault= argument names no fault of the network.
BRANCH_UNKNOWN_BUS error A branch end names an unknown bus; the solver would drop the branch.
SOURCE_UNKNOWN_BUS error A source names an unknown bus; the solver would ignore it.
FAULT_UNKNOWN_BUS error A fault names an unknown bus.
FAULT_BUS_INACTIVE error A fault sits on an inactive bus.
SOURCE_BUS_INACTIVE warning A source sits on an inactive bus and injects nothing.
IMPEDANCE_MISSING error An element of the nodal system has no impedance at a network frequency.
FORMULA_ERROR error No stored impedance, and the type formula cannot be evaluated.
IMPEDANCE_NOT_PASSIVE error An inverted impedance is zero, too small to invert or has a negative real part.
IMPEDANCE_NOT_FINITE error An impedance is NaN at a network frequency.
SOURCE_FREQUENCY_NONE error A source has a value at none of the network frequencies.
SOURCE_FREQUENCY_GAP warning A source has no value at some network frequencies.
SOURCE_FREQUENCY_OUTSIDE_NETWORK warning A source has values at frequencies the network does not solve.
SOURCE_VALUE_NOT_FINITE error A source value is NaN or infinite.
SCALINGS_INCOMPLETE warning A fault's scalings miss network frequencies (scaled with 1.0).
FAULT_NOT_REACHED warning No source reaches the fault over active elements; every potential is 0 V.
ISOLATED_BUS warning An active bus has no active branch to any other bus.
FLOATING_ISLAND error Buses joined by grounding conductors with no reference to earth.

Progress and cancellation

The five long-running entry points — run_sweep, run_outage_study, find_max_rho_scaling, find_max_rho_f_scaling and TransientStudy.solve — take two optional keyword arguments:

  • progress(done, total, label) is called after every unit of work: a sweep point, an outage scenario (the base case included), one solve of a bisection search (one bus solve of the rho-f search), a batch of FFT bins (at most 512, fewer under a tight fft_block_bytes), a stage of the state-space solver. done counts up by one, label names the unit, done <= total holds at every call.
  • should_cancel() is asked before every unit. A true answer raises gi.StudyCancelled (a RuntimeError with .done and .total), and the network is back in the state it had when the study was called — JSON, stored results, active fault, paths and assembled system.
# fragment: assumes a network `net` with the fault "F1" and sweep points `points`
import threading

stop = threading.Event()

def report(done, total, label):
    print(f"{done}/{total} {label}")      # a GUI forwards this to its event loop

try:
    study = gi.run_sweep(net, fault="F1", points=points,
                         progress=report, should_cancel=stop.is_set)
except gi.StudyCancelled as cancelled:
    print(f"stopped after {cancelled.done} of {cancelled.total} points")

Cancellation is cooperative: it takes effect at the next unit boundary. The integration step of the state-space solver is a single library call and runs to its end once started. Both callbacks run in the study's thread; an exception raised by a callback propagates unchanged.

total is fixed for sweeps, outage studies and transients. A bisection search announces the evaluations its bracket and tolerance require — a log-bisection needs the same number of halvings wherever the threshold lies — and ends below that when it stops early (a fully admissible bracket).

Diagnostic codes

Every condition that changes how a result has to be read is raised as a structured warning — a subclass of gi.GroundinsightWarning with a stable code, a severity and the elements it is about — and not only logged: the library's logging default is a NullHandler, so a log line reaches nobody who has not configured logging. Inside run_fault (and gi.solve) the records are collected into Result.diagnostics; around any other call a program collects them with groundinsight.diagnostics.collecting():

# fragment: assumes a pandapower net `pp_net` and import defaults `defaults`
from groundinsight.diagnostics import collecting

with collecting() as records:
    network = gi.from_pandapower(pp_net, defaults=defaults, voltage_level_kV=20.0)
for record in records:
    print(record.code, record.elements, record.message)

A program that reads warnings from its log can route them there with logging.captureWarnings(True): they arrive at the logger py.warnings as formatted text, while code and elements stay with the records.

What stays a log line reports what the library does — sessions, migrations, caches, costs — or summarises something the returned object already carries (a status field, a failures map, a table column). The codes, with the category and the function whose docstring describes the condition:

Code Category Raised by
DC_LIMIT DCLimitWarning impedance evaluation at 0 Hz
EARTH_GROUP_SPREAD ModelAssumptionWarning run_fault: electrode currents spread in angle, I_E and r_current describe the dominant direction only
EARTH_GROUP_UNDEFINED ModelAssumptionWarning run_fault: no electrode carries a non-noise share of the fault current
EARTHING_IMPEDANCE_UNDEFINED ModelAssumptionWarning run_fault: Z_E undefined at a frequency
FREQUENCY_ORDER NetworkFrequencyOrderWarning Network.frequencies not strictly increasing
IMPORT_BUS_SKIPPED InputWarning from_pandapower / preview: a bus with an unparsable vn_kv
IMPORT_ELEMENT_NOT_IMPORTED InputWarning from_pandapower: transformers and impedance elements
IMPORT_EMPTY InputWarning from_pandapower: no bus or no branch imported
IMPORT_LENGTH_DEFAULT InputWarning from_pandapower / preview: a line without usable length got the fallback
IMPORT_LINE_SKIPPED InputWarning from_pandapower / preview: a self-loop, or a length that cannot be imported
IMPORT_LINE_SWITCH_OPEN InputWarning from_pandapower: a line imported with an open phase conductor because of an open line switch
IMPORT_SWITCH_NOT_IMPORTED InputWarning from_pandapower: closed bus-to-bus switches without switch_branch_type
IMPORT_VOLTAGE_LEVEL_MISMATCH InputWarning from_pandapower: the default bus type declares another voltage level
PARALLEL_COEFFICIENT_DEFAULT ModelAssumptionWarning run_fault(phase_current_mode="paths"): parallel routes with default coefficients
PHASE_PROXY ModelAssumptionWarning run_fault: a meshed phase network split with proxy impedances
PROJECT_FILE_LEGACY_ENCODING InputWarning load_network_from_json: a file that is not UTF-8
REDUCTION_FACTOR_UNDEFINED ModelAssumptionWarning run_fault: r_epr undefined at a frequency
SC_DATA_INCOMPLETE InputWarning resolve_fault_sc_characteristics: sources without IEC 60909 data
SC_KAPPA_MISSING InputWarning read_shortcircuit_results: no kappa derivable for a bus
SC_KAPPA_MIXED ModelAssumptionWarning resolve_fault_sc_characteristics: sources of different R/X
SC_KAPPA_OUT_OF_RANGE InputWarning read_shortcircuit_results: pandapower's ip/ikss imply kappa outside (1, 2]
SC_ROW_AMBIGUOUS InputWarning apply_shortcircuit_characteristics: several matching rows
SC_SPLIT_EQUAL InputWarning apply_shortcircuit_characteristics: I_k'' split equally
SC_VALUE_REPLACED InputWarning apply_shortcircuit_characteristics: a different t_k_s / n_factor replaced
SC_VOLTAGE_SOURCE_SKIPPED InputWarning apply_shortcircuit_characteristics: a voltage source keeps its values
SCALINGS_INCOMPLETE InputWarning run_fault: a fault's scalings miss network frequencies
SOURCE_FREQUENCY_GAP InputWarning run_fault: a source misses network frequencies
SOURCE_FREQUENCY_OUTSIDE_NETWORK InputWarning Network.add_source: values at frequencies the network does not solve
SOURCE_WITHOUT_PHASE_PATH ModelAssumptionWarning run_fault: a source with no phase-conductor path to the fault
THERMAL_DATA_INCOMPLETE InputWarning check_conductor_limits / check_node_limits: half-declared thermal data
THERMAL_DC_EXCLUDED ModelAssumptionWarning check_conductor_limits / check_node_limits: 0 Hz left out of the adiabatic check
THEVENIN_COUPLING ModelAssumptionWarning run_fault: a Thevenin source drives coupled branches
TRANSIENT_BRANCH_SKIPPED InputWarning TransientStudy.solve (state space): branches without R_self/L_self
TRANSIENT_COUPLING_SKIPPED TransientModelWarning TransientStudy.solve (state space): coupling of voltage sources
TRANSIENT_MODEL TransientModelWarning TransientStudy.solve: the model is narrower than the input
TRANSIENT_PHASE_SPLIT ModelAssumptionWarning TransientStudy.solve (state space): frequency-dependent phase split
TRANSIENT_RESISTIVE_COUPLING_IGNORED TransientModelWarning TransientStudy.solve (state space): mutual data on resistive branches
TRANSIENT_SOURCE_NOT_CONNECTED InputWarning TransientStudy.solve (FFT): a source without connection to the fault

gi.check_network returns its own codes, listed above; SCALINGS_INCOMPLETE, SOURCE_FREQUENCY_GAP and SOURCE_FREQUENCY_OUTSIDE_NETWORK mean the same there. What each code means and what to do about it: Warnings and diagnostics.

Canonical parameter names

Every concept of the public API has one parameter name. The former names still work as keyword arguments and raise a DeprecationWarning that names the replacement; positional calls are unaffected. Following the project's deprecation policy, an old name keeps working for at least two releases and six months after the release that deprecated it.

Concept Name Former name(s) Where
fault fault fault_name run_fault, set_active_fault, Network.set_active_fault, Network.sources_reaching, TransientStudy, find_max_rho_scaling, check_conductor_limits, check_node_limits, resolve_fault_sc_characteristics, apply_shortcircuit_characteristics
EPR limit u_limit u_max find_max_rho_scaling
fault duration t_k_s t_k check_conductor_limits, check_node_limits, admissible_short_circuit_current, iec60909_m
AC heat factor n_factor n check_conductor_limits, check_node_limits, thermal_equivalent_current
frequency frequency f, freq check_conductor_limits, check_node_limits, iec60909_m, read_shortcircuit_results, BusResponse.voltages, .voltages_no_mutual, .driving_point, .worst_case_electrode
# fragment: assumes a network `net` with the fault "F1"
gi.run_fault(net, fault="F1")             # current spelling
gi.run_fault(net, "F1")                   # positional: unchanged
gi.run_fault(net, fault_name="F1")        # works, DeprecationWarning

Service layer for front ends: groundinsight.api

groundinsight.api is what a front end imports -- the NiceGUI app of the separate groundinsight-gui distribution, the command line, a later REST server. It wraps the functions above into what a user interface needs and a notebook does not, and adds no physics:

Building block What it does
ProjectSession One open project: open/save, edit commands with undo/redo and a revision counter, a type catalogue, resource limits, results, jobs.
Commands (AddBus, UpdateBranch, RemoveFault, SetFrequencies, ...) Every edit, atomic and undoable, through the library's editing API.
JobRunner Solves and studies off the caller's thread, in a thread or a process, with progress, cancel and a runtime limit.
DTOs (FaultResultDTO, NetworkTablesDTO, JobStatusDTO, ...) The only data shape towards a front end: JSON-safe, versioned, with JSON schemas.
EXAMPLES The documented example networks (quickstart, minimal, mv_ring) as project templates.

The names are exported from groundinsight.api, not from the top-level namespace, which stays the library's.

Design rules

The service-layer tests hold these rules; a front end built on the layer inherits them.

# Rule
R1 A front end imports groundinsight.api and the top-level groundinsight namespace only (the GUI and the command line are checked for it).
R2 No physics in a front end: every number comes from a DTO, the front end only formats it.
R3 DTOs are the only data shape between library and front end: pydantic models, strictly JSON-safe (a non-finite number is null), each with dto_schema_version.
R4 Every change is a command: atomic (a rejected command changes nothing, not even the revision), undoable, through the library's editing API.
R5 Library work that can take longer than a moment runs as a job, never in a user interface's event loop.
R6 The diagnostics of a run belong to its result: they arrive in the DTO with code, severity and the elements they concern.
R7 The project file is the library's network JSON -- UTF-8, written atomically, with schema_version -- without stored results and without view state.
R8 The service layer imports no UI or web toolkit and keeps no module state: one session per user and project, two sessions never share state.
R9 Every number a front end shows is checked against the library two independent ways (the DTOs of the documented examples against the res_* frames of run_fault and against an independent reference solver; thread against process execution).
R10 A result is bound to the revision it was computed from; whether it is stale is the library's verdict (Network.is_result_stale), so undoing an edit makes a result current again.

A session

from groundinsight.api import ProjectSession, UpdateBus

session = ProjectSession.from_example("quickstart")   # or .from_file("projekt.json")
result = session.solve("fault_at_remote_bus")          # a FaultResultDTO
rms = result.key_figures.rms()                         # the RMS row of res_fault
print(rms.EPR_fault_V, rms.I_E_A, [d.code for d in result.diagnostics])

report = session.apply(UpdateBus(name="bus_fault",
                                 fields={"specific_earth_resistance": 250.0}))
report.revision, session.is_stale("fault_at_remote_bus")    # (1, True)
session.undo()
session.is_stale("fault_at_remote_bus")                      # False: current again

session.save("projekt.json")      # UTF-8, atomic, schema-versioned, no results
session.close()

A session owns one network. Front ends read it through the DTO methods -- summary(), tables() (the ten tables of Network.to_tables, plus catalogue types nobody uses yet), check() (the pre-flight check), result(fault) -- and change it only through apply(command). revision identifies an input state: a new command gets a new number, undo and redo return to the number of the state they restore. dirty compares it with the last opened or saved revision.

Opening and saving use the library's project-file functions, so a file written by the GUI opens in a notebook and the other way round. Results are left out of the file (they are derived and go stale with the next edit); a file that carries results keeps them on open, and the library says whether they are stale. A server keeps projects in a ProjectStore instead: a MemoryStore, or a DatabaseStore over a gi.Database (ProjectSession.from_store(store, key), session.save_to(store, key)).

The constructor takes the resource limits a server sets per user: max_buses, max_branches (a larger file is refused on open, a command that would exceed them is rejected), max_job_runtime_s (every job of the session), max_undo (history depth) and max_paths, the cap of the path enumeration of the "paths" phase-current mode. max_paths becomes the network's own gi.PathfinderSettings (see Pathfinder), so two sessions with different caps share nothing.

Commands

Element Add Update (fields) Remove
bus AddBus UpdateBus (Network.update_bus) RemoveBus
branch AddBranch UpdateBranch (Network.update_branch) RemoveBranch
source AddSource UpdateSource (a validated replacement) RemoveSource
fault AddFault UpdateFault (validated, then assigned) RemoveFault
bus type AddBusType UpdateBusType RemoveBusType
branch type AddBranchType UpdateBranchType RemoveBranchType
frequencies -- SetFrequencies --

A command calls the library's own editing API, so the library validates the input and re-derives the impedances; a rejected command raises CommandError and changes nothing -- not the network, not the revision, not the history. Undo runs the inverse operations through the same API and restores what the library dropped as a side effect (the stored result and active state of a removed fault, the position of a re-added element): after an undo the serialised network is identical to the one before the command. Elements refer to types by name; types are read-only in the library, so a type edit creates a changed copy and swaps it into every element of that type, all or nothing. The commands are pydantic models with a discriminator op, so parse_command({"op": "update_bus", "name": "b1", "fields": {"active": False}}) builds one from JSON; COMMAND_OPS lists the op value of every command.

Jobs

# fragment: assumes an open session whose project has the fault "F1"
handle = session.submit_solve("F1")              # returns at once
status = handle.status()                         # JobStatusDTO: state, progress, elapsed
dto = handle.result(timeout=60)                  # FaultResultDTO, or JobCancelled/JobTimeout/JobFailed

session.submit(request) takes a job request -- SolveRequestDTO, SolveAllRequestDTO, SweepRequestDTO, OutageStudyRequestDTO, MaxRhoRequestDTO -- and runs it on a snapshot of the network taken at submission, so editing can go on meanwhile. Progress and cancellation use the studies' progress/should_cancel hooks (above); handle.cancel() and the runtime limit both end a study at its next unit boundary with gi.StudyCancelled (JobCancelled and JobTimeout subclass it). JobRunner(backend="process") runs jobs in a spawned process instead of a thread: it costs the interpreter start, needs inputs that pickle, and can stop a job hard. Both backends run the same task code and return identical DTOs. A job that completes stores its fault results on the network; a result computed from an older revision is stale at once, and it never replaces a current one.

DTOs and JSON schemas

Every DTO is a pydantic model with dto_schema_version; model_dump_json() is the wire format and never contains NaN or Infinity. groundinsight.api.schemas.json_schemas() returns the JSON schema of every DTO plus Command (all edit commands) and JobRequest (all job requests) -- the request and response schemas of a future REST API. The key figures are the rows of Network.res_fault (KeyFigureRowDTO has its columns), the per-element results those of res_buses/res_branches, the element tables those of Network.to_tables.

Command line

Installing groundinsight installs the console script groundinsight; python -m groundinsight is the same without the script.

groundinsight run projekt.json --fault F1                # readable report
groundinsight run projekt.json --fault F1 --format json  # FaultResultDTO
groundinsight run projekt.json --format csv              # res_fault rows; the only fault
groundinsight check projekt.json                         # the pre-flight check

run opens the file in a ProjectSession, runs the pre-flight check for the fault, solves it and prints the result: table (default) the key figures per frequency and RMS with the diagnostics, json the FaultResultDTO, csv the key-figure rows with the columns of RES_FAULT_SCHEMA (the diagnostics then go to stderr). --phase-current-mode paths selects the legacy mode. Without --fault, a project with exactly one fault solves that one. check prints every finding of check_network, as table, json (CheckReportDTO) or csv.

Exit code Meaning
0 Success.
1 A diagnostic of severity error: the check found the network unsolvable as described (run then solves nothing and prints the check), the solve failed, or the result carries an error record.
2 A usage error: invalid arguments, a file that is not a project, an unknown fault, or run without --fault on a project with several faults.

API reference

service

Service functions: results without side effects on the input network.

:func:groundinsight.run_fault is a stateful convenience. It activates the fault, drops or rebuilds network.paths, attaches the assembled :class:~groundinsight.electrical_network.ElectricalNetwork and stores the :class:~groundinsight.models.core_models.Result in network.results. That is what a notebook wants -- net.res_buses() right after the call -- and it is the wrong default for every caller that holds on to the network while something else computes on it: a GUI that redraws its tables while a worker thread solves, a server that answers several requests from one project, a study that has to hand the network back unchanged. Each of them would have to restore the network after every solve, and every such restore is one more place for a mistake.

:func:solve is the side-effect-free twin. It runs the unchanged run_fault pipeline on an overlay: a second :class:Network object that shares the element objects of the input -- buses, branches and sources, which a solve reads but never writes -- and owns every container a solve does write to: results, paths, the fault objects whose active flag is switched, the private path fingerprint and the assembled system. Same code, same element objects in the same order, hence the same floating-point operations: the numbers are bit-identical to run_fault by construction, not within a tolerance.

Two alternatives were rejected:

  • Mutate and restore -- run run_fault on the input and put everything back in a finally block. The input would visibly change while the solve runs (a GUI thread reading it would see the fault's stored result vanish), and every private attribute a later release adds to Network would need a restore line of its own -- the failure mode the studies kept running into.
  • Deep copy -- copying every ComplexNumber of every element costs elements x frequencies model validations per solve, which on a large network is more than the solve itself, to protect objects the solve never writes to.

solve

solve(
    network: Network,
    fault: str,
    *,
    phase_current_mode: str = "auto",
) -> Result

Solve one fault and return its result without modifying network.

Runs the same pipeline as :func:groundinsight.run_fault -- fault activation, path handling, assembly, nodal solve, branch currents, reduction factors, grounding impedance, diagnostics -- but on an overlay of network (see the module docstring), so nothing of the input is written: not its fields, not its stored results, not its active fault, not its path set or assembled system. Its path-search memo is not touched either: the overlay is a different network and gets a memo of its own (see :meth:~groundinsight.models.core_models.Network.path_cache), which goes with it.

Parameters:

Name Type Description Default
network Network

The network to solve. It is the same, unchanged object afterwards -- also when the solve raises.

required
fault str

Name of the fault to solve.

required
phase_current_mode (auto, paths)

How the phase current per branch is determined, exactly as in :func:groundinsight.run_fault. Defaults to "auto".

"auto"

Returns:

Type Description
Result

A new result object with the same numbers -- bit for bit --, the same diagnostics and the same input_digest as the one run_fault would store under network.results[fault]. It is not stored on network.

Raises:

Type Description
ValueError

Whatever :func:groundinsight.run_fault raises for this network and fault: an unknown fault, a network with no source or no fault at all, an invalid phase_current_mode, or a network the solver rejects (missing impedances, no reference to earth, ...).

Notes

Threads. solve never writes to network, but it reads the network's buses, branches and sources while it runs. Do not modify the network during a solve, and do not solve the same Network object from several threads at once -- that is not designed for. Different networks can be solved in parallel: the path search keeps its settings and memo per network. Reading the network from another thread while a solve runs is safe.

solve or run_fault. run_fault stays the convenient call for interactive work: afterwards network.res_buses(), :func:~groundinsight.bus_response and :func:~groundinsight.analyze_cuts read the solved state straight off the network. solve is for code that holds the network on behalf of someone else -- a GUI session, a server, a study -- and must hand it back as it was. To keep a result from solve on the network after all, store it explicitly (network.results[fault] = result); the res_* accessors tabulate it when called with fault=. It carries the digest of the inputs it was computed from, so :meth:Network.stale_results <groundinsight.models.core_models.Network.stale_results> reports it as current until the network is edited.

Examples:

>>> import groundinsight as gi
>>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
...                       impedance_formula="0.01*rho")
>>> cable = gi.BranchType(name="K", grounding_conductor=True,
...                       self_impedance_formula="(0.25+0.6*j)*l",
...                       mutual_impedance_formula="0.6*j*l")
>>> net = gi.create_network(name="demo", frequencies=[50.0])
>>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
>>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
>>> _ = gi.create_branch(name="k", type=cable, from_bus="b0", to_bus="b1",
...                      length=1.0, network=net)
>>> _ = gi.create_source(name="q", bus="b0", values={50.0: 100.0}, network=net)
>>> _ = gi.create_fault(name="ef", bus="b1", scalings={50.0: 1.0}, network=net)
>>> result = gi.solve(net, "ef")
>>> result.fault, net.results, net.active_fault
('ef', {}, None)
Source code in src/groundinsight/service.py
def solve(
    network: Network, fault: str, *, phase_current_mode: str = "auto"
) -> Result:
    """
    Solve one fault and return its result without modifying ``network``.

    Runs the same pipeline as :func:`groundinsight.run_fault` -- fault
    activation, path handling, assembly, nodal solve, branch currents,
    reduction factors, grounding impedance, diagnostics -- but on an overlay
    of ``network`` (see the module docstring), so nothing of the input is
    written: not its fields, not its stored results, not its active fault, not
    its path set or assembled system. Its path-search memo is not touched
    either: the overlay is a different network and gets a memo of its own
    (see :meth:`~groundinsight.models.core_models.Network.path_cache`), which
    goes with it.

    Parameters
    ----------
    network : Network
        The network to solve. It is the same, unchanged object afterwards --
        also when the solve raises.
    fault : str
        Name of the fault to solve.
    phase_current_mode : {"auto", "paths"}, optional
        How the phase current per branch is determined, exactly as in
        :func:`groundinsight.run_fault`. Defaults to ``"auto"``.

    Returns
    -------
    Result
        A new result object with the same numbers -- bit for bit --, the same
        ``diagnostics`` and the same ``input_digest`` as the one ``run_fault``
        would store under ``network.results[fault]``. It is *not* stored on
        ``network``.

    Raises
    ------
    ValueError
        Whatever :func:`groundinsight.run_fault` raises for this network and
        fault: an unknown fault, a network with no source or no fault at all,
        an invalid ``phase_current_mode``, or a network the solver rejects
        (missing impedances, no reference to earth, ...).

    Notes
    -----
    **Threads.** ``solve`` never writes to ``network``, but it reads the
    network's buses, branches and sources while it runs. Do not modify the
    network during a solve, and do not solve the *same* ``Network`` object
    from several threads at once -- that is not designed for. Different
    networks can be solved in parallel: the path search keeps its settings
    and memo per network. Reading the network from
    another thread while a solve runs is safe.

    **solve or run_fault.** ``run_fault`` stays the convenient call for
    interactive work: afterwards ``network.res_buses()``,
    :func:`~groundinsight.bus_response` and :func:`~groundinsight.analyze_cuts`
    read the solved state straight off the network. ``solve`` is for code that
    holds the network on behalf of someone else -- a GUI session, a server, a
    study -- and must hand it back as it was. To keep a result from ``solve``
    on the network after all, store it explicitly
    (``network.results[fault] = result``); the ``res_*`` accessors tabulate it
    when called with ``fault=``. It carries the digest of the inputs it was
    computed from, so :meth:`Network.stale_results
    <groundinsight.models.core_models.Network.stale_results>` reports it as
    current until the network is edited.

    Examples
    --------
    >>> import groundinsight as gi
    >>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
    ...                       impedance_formula="0.01*rho")
    >>> cable = gi.BranchType(name="K", grounding_conductor=True,
    ...                       self_impedance_formula="(0.25+0.6*j)*l",
    ...                       mutual_impedance_formula="0.6*j*l")
    >>> net = gi.create_network(name="demo", frequencies=[50.0])
    >>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
    >>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
    >>> _ = gi.create_branch(name="k", type=cable, from_bus="b0", to_bus="b1",
    ...                      length=1.0, network=net)
    >>> _ = gi.create_source(name="q", bus="b0", values={50.0: 100.0}, network=net)
    >>> _ = gi.create_fault(name="ef", bus="b1", scalings={50.0: 1.0}, network=net)
    >>> result = gi.solve(net, "ef")
    >>> result.fault, net.results, net.active_fault
    ('ef', {}, None)
    """
    overlay = _overlay(network)
    try:
        return run_fault(overlay, fault, phase_current_mode=phase_current_mode)
    finally:
        # The overlay's path-search memo is its own (``Network.path_cache``
        # checks the owner, and the overlay shares its private attributes
        # with the input only until that check) and goes with the overlay.
        overlay.electrical_network = None

checks

Pre-flight check of a network: every problem at once, as data.

run_fault and the create_* factories report a problem as the first ValueError they meet. That suits a script, which fixes one thing and runs again; it does not suit a form-based editor, which has to show every problem of the network before the user presses "solve", each next to the element it is about. Worse, a few problems are not reported at all: a branch whose end names a bus that does not exist, or a source on such a bus, is dropped by the solver without a word and the result reads 0 V. The editing API refuses such a reference on an element that belongs to a network, but a network loaded from a hand-edited project file, from a database written by another tool or from dictionaries a script filled itself is not checked when it is loaded.

:func:check_network answers the editor's question. It returns a list of :class:~groundinsight.diagnostics.Diagnostic records -- the same type as Result.diagnostics -- with a stable code from :data:CHECK_CODES, the elements concerned and a severity:

"error" run_fault would raise, or would return an answer that does not describe the network (an element silently dropped). "warning" The network solves, but part of the input has no effect or a documented default stands in for a missing value.

It never raises: a check that cannot run on a network malformed in some way nobody anticipated is reported as CHECK_FAILED and the other checks still run.

Design

Wherever the solver already has a validation path, the check calls it and turns its exception or warning into a record, so the two cannot disagree: the Network.frequencies validator, the passivity rule (:func:~groundinsight.utils.impedance_calculator.check_passive_impedance), the formula evaluation of Bus/Branch.calculate_impedance (run on a copy) and the reachability search Network.sources_reaching. Package warnings raised along the way are collected with :func:~groundinsight.diagnostics.collecting and keep their own codes. The selection of elements mirrors the solver's: only what enters the nodal system is judged (an inactive bus may carry any impedance it likes). New code exists only for what has no code path yet -- references to buses that do not exist, the frequency coverage of sources, isolated buses and earthing islands without any reference to earth.

The check is structural: it neither assembles nor solves. That keeps it cheap enough to run after every edit (linear in elements x frequencies), and it is also its limit -- conditions only a solve can see, such as the model assumption behind a phase-current proxy, arrive with the result in Result.diagnostics.

CHECK_CODES module-attribute

CHECK_CODES: Dict[str, Tuple[str, str]] = {
    "NOT_A_NETWORK": (
        _ERROR,
        "The argument is not a Network.",
    ),
    "CHECK_FAILED": (
        _ERROR,
        "A check raised unexpectedly; that aspect of the network could not be judged.",
    ),
    "ELEMENT_INVALID": (
        _ERROR,
        "An entry of buses, branches, sources or faults is not an element of the expected type.",
    ),
    "FREQUENCIES_INVALID": (
        _ERROR,
        "The frequency list is empty or holds duplicates, non-finite or negative values.",
    ),
    "NO_ACTIVE_BUS": (
        _ERROR,
        "The network has no active bus.",
    ),
    "NO_SOURCE": (_ERROR, "The network defines no source."),
    "NO_FAULT": (_ERROR, "The network defines no fault."),
    "FAULT_UNKNOWN": (
        _ERROR,
        "The fault passed as fault= does not exist.",
    ),
    "BRANCH_UNKNOWN_BUS": (
        _ERROR,
        "A branch end names a bus that does not exist; the solver would drop the branch.",
    ),
    "SOURCE_UNKNOWN_BUS": (
        _ERROR,
        "A source names a bus that does not exist; the solver would ignore it.",
    ),
    "FAULT_UNKNOWN_BUS": (
        _ERROR,
        "A fault names a bus that does not exist.",
    ),
    "FAULT_BUS_INACTIVE": (
        _ERROR,
        "A fault sits on an inactive bus.",
    ),
    "SOURCE_BUS_INACTIVE": (
        _WARNING,
        "A source sits on an inactive bus and injects nothing.",
    ),
    "IMPEDANCE_MISSING": (
        _ERROR,
        "An element of the nodal system has no impedance at a network frequency.",
    ),
    "FORMULA_ERROR": (
        _ERROR,
        "An element has no stored impedance and its type formula cannot be evaluated.",
    ),
    "IMPEDANCE_NOT_PASSIVE": (
        _ERROR,
        "An impedance that is inverted is zero, too small to invert or has a negative real part.",
    ),
    "IMPEDANCE_NOT_FINITE": (
        _ERROR,
        "An impedance is NaN at a network frequency.",
    ),
    "SOURCE_FREQUENCY_NONE": (
        _ERROR,
        "A source has a value at none of the network frequencies.",
    ),
    "SOURCE_FREQUENCY_GAP": (
        _WARNING,
        "A source has no value at some network frequencies; it injects nothing there.",
    ),
    "SOURCE_FREQUENCY_OUTSIDE_NETWORK": (
        _WARNING,
        "A source has values at frequencies the network does not solve; they are ignored.",
    ),
    "SOURCE_VALUE_NOT_FINITE": (
        _ERROR,
        "A source value is NaN or infinite at a network frequency.",
    ),
    "SCALINGS_INCOMPLETE": (
        _WARNING,
        "A fault's scalings miss network frequencies, which are scaled with 1.0.",
    ),
    "FAULT_NOT_REACHED": (
        _WARNING,
        "No source reaches the fault over active elements; every potential is 0 V.",
    ),
    "ISOLATED_BUS": (
        _WARNING,
        "An active bus has no active branch to any other active bus.",
    ),
    "FLOATING_ISLAND": (
        _ERROR,
        "A group of buses joined by grounding conductors has no reference to earth; its potential is undefined.",
    ),
}

Every code :func:check_network produces itself, mapped to its severity ("error" or "warning") and meaning. Package warnings collected during the check (FREQUENCY_ORDER, DC_LIMIT) keep their own codes. Programs branch on the code, never on the message text.

check_network

check_network(
    network: Network, *, fault: Optional[str] = None
) -> List[Diagnostic]

Every problem of a network, as data, without raising.

Runs the structural checks listed in :data:CHECK_CODES -- elements and references, frequencies, excitation, the impedances the solver will invert, source coverage, fault location and reachability, isolated buses and earthing islands without a reference to earth -- and returns all findings at once. Package warnings raised along the way (for example the FREQUENCY_ORDER warning of the frequency validator) are included with their own codes.

Parameters:

Name Type Description Default
network Network

The network to check. It is not modified; formulas that have to be evaluated are evaluated on copies of the elements.

required
fault str

Restrict the fault-specific checks (location, scalings, reachability) to this fault. Defaults to every fault of the network. A name that is not a fault of the network is reported as FAULT_UNKNOWN.

None

Returns:

Type Description
list of Diagnostic

One record per problem, network-level ones first, then per element in the network's order; empty for a network that is ready to solve. severity is "error" where run_fault would raise or return an answer that does not describe the network, and "warning" where the network solves but part of the input has no effect or a default stands in.

Notes

The function never raises. An argument that is not a network yields a single NOT_A_NETWORK record; a check that crashes on an unexpected malformation yields CHECK_FAILED and the remaining checks still run.

The checks are structural and cheap (no assembly, no solve), so a GUI can run them after every edit. Conditions that only the solve can detect -- model assumptions such as a heuristic phase-current split -- are reported with the result in Result.diagnostics.

Examples:

>>> import groundinsight as gi
>>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
...                       impedance_formula="0.01*rho")
>>> net = gi.create_network(name="demo", frequencies=[50.0])
>>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
>>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
>>> [(d.code, d.severity) for d in gi.check_network(net)]
[('NO_SOURCE', 'error'), ('NO_FAULT', 'error'), ('ISOLATED_BUS', 'warning'), ('ISOLATED_BUS', 'warning')]
Source code in src/groundinsight/checks.py
def check_network(network: Network, *, fault: Optional[str] = None) -> List[Diagnostic]:
    """
    Every problem of a network, as data, without raising.

    Runs the structural checks listed in :data:`CHECK_CODES` -- elements and
    references, frequencies, excitation, the impedances the solver will invert,
    source coverage, fault location and reachability, isolated buses and
    earthing islands without a reference to earth -- and returns all findings
    at once. Package warnings raised along the way (for example the
    ``FREQUENCY_ORDER`` warning of the frequency validator) are included with
    their own codes.

    Parameters
    ----------
    network : Network
        The network to check. It is not modified; formulas that have to be
        evaluated are evaluated on copies of the elements.
    fault : str, optional
        Restrict the fault-specific checks (location, scalings, reachability)
        to this fault. Defaults to every fault of the network. A name that is
        not a fault of the network is reported as ``FAULT_UNKNOWN``.

    Returns
    -------
    list of Diagnostic
        One record per problem, network-level ones first, then per element in
        the network's order; empty for a network that is ready to solve.
        ``severity`` is ``"error"`` where ``run_fault`` would raise or return
        an answer that does not describe the network, and ``"warning"`` where
        the network solves but part of the input has no effect or a default
        stands in.

    Notes
    -----
    The function never raises. An argument that is not a network yields a
    single ``NOT_A_NETWORK`` record; a check that crashes on an unexpected
    malformation yields ``CHECK_FAILED`` and the remaining checks still run.

    The checks are structural and cheap (no assembly, no solve), so a GUI can
    run them after every edit. Conditions that only the solve can detect --
    model assumptions such as a heuristic phase-current split -- are reported
    with the result in ``Result.diagnostics``.

    Examples
    --------
    >>> import groundinsight as gi
    >>> bus_type = gi.BusType(name="BT", system_type="MV", voltage_level=20.0,
    ...                       impedance_formula="0.01*rho")
    >>> net = gi.create_network(name="demo", frequencies=[50.0])
    >>> _ = gi.create_bus(name="b0", type=bus_type, network=net)
    >>> _ = gi.create_bus(name="b1", type=bus_type, network=net)
    >>> [(d.code, d.severity) for d in gi.check_network(net)]
    [('NO_SOURCE', 'error'), ('NO_FAULT', 'error'), ('ISOLATED_BUS', 'warning'), ('ISOLATED_BUS', 'warning')]
    """
    if not isinstance(network, Network):
        return [
            Diagnostic(
                code="NOT_A_NETWORK",
                severity=CHECK_CODES["NOT_A_NETWORK"][0],
                category="InputWarning",
                message=(
                    "check_network() needs a groundinsight Network, got "
                    f"{type(network).__name__}."
                ),
                elements=[],
            )
        ]

    report = _Report(network)
    report.run("elements", _check_elements)
    report.run("frequency", _check_frequencies)
    report.run("excitation", _check_excitation)
    report.run("reference", _check_references)
    if fault is None:
        report.checked_faults = list(report.faults)
    elif fault in report.faults:
        report.checked_faults = [fault]
    else:
        report.add(
            "FAULT_UNKNOWN",
            f"Fault '{fault}' does not exist in network '{report.name}'. "
            f"Available: {sorted(report.faults)}.",
            [("fault", fault)],
        )
    report.run("impedance", _check_impedances)
    report.run("source", _check_sources)
    report.run("fault", _check_faults)
    report.run("topology", _check_topology)
    return unique(report.records)

progress

Progress reports and cooperative cancellation for long-running studies.

A GUI runs a study in a worker thread, draws a progress bar and offers a cancel button; a server reports job progress and honours a client's abort. Python cannot stop a thread from outside, so cancellation has to be cooperative: the study asks, between two units of work, whether it should go on. Without such a hook a thread running a sweep could only be waited for.

The protocol is shared by :func:~groundinsight.run_sweep, :func:~groundinsight.run_outage_study, :func:~groundinsight.find_max_rho_scaling, :func:~groundinsight.find_max_rho_f_scaling and :meth:TransientStudy.solve <groundinsight.TransientStudy.solve>, each of which takes two optional keyword arguments:

progress(done, total, label) Called after every unit of work: a sweep point, an outage scenario (the base case included), one solve of a bisection search, a block of FFT bins, a stage of the state-space solver. done counts the finished units from 1, label names the unit. total is fixed for sweeps, outage studies and transients. A bisection search announces the evaluations its bracket and tolerance require; it ends below that when it stops early (a fully admissible bracket) and raises it if a floating-point boundary case needs one step more. done <= total holds at every call. should_cancel() Asked before every unit, the first one included. A true answer ends the study with :class:StudyCancelled.

On cancellation the network is restored to the state it had when the study was called -- its serialised form, stored results, active fault, paths and assembled electrical network -- and nothing is returned. Both callbacks run in the study's own thread; a GUI hands the values over to its event loop itself. A callback must not edit the network while the study runs: the study restores it afterwards anyway, and the inverse searches re-solve their trials on the assembly of their first solve (:mod:groundinsight.analysis._session), which an edit in between would not reach. An exception raised by a callback propagates unchanged, after the study's usual clean-up.

Why two plain callables rather than a token or job object: they are what every caller already has (a threading.Event.is_set, a lambda over a GUI flag, a tqdm.update), they keep the library free of any execution model, and a service layer can wrap them into whatever job abstraction it uses.

StudyCancelled

StudyCancelled(
    message: str = "study cancelled",
    *,
    done: int = 0,
    total: int = 0,
)

Bases: RuntimeError

A study stopped because its should_cancel() callback returned true.

The network the study ran on is back in the state it had when the study was called; there is no partial result.

Parameters:

Name Type Description Default
message str

Human-readable description.

'study cancelled'
done int

Units of work completed before the cancellation took effect.

0
total int

Units of work the study had planned at that moment.

0

Attributes:

Name Type Description
done int

As passed.

total int

As passed.

Examples:

>>> import groundinsight as gi
>>> error = gi.StudyCancelled("sweep cancelled", done=3, total=10)
>>> isinstance(error, RuntimeError), error.done, error.total
(True, 3, 10)
Source code in src/groundinsight/progress.py
def __init__(self, message: str = "study cancelled", *, done: int = 0, total: int = 0):
    super().__init__(message)
    self.done = done
    self.total = total

StudyHooks

StudyHooks(
    study: str,
    total: int,
    progress: Optional[ProgressCallback] = None,
    should_cancel: Optional[CancelCallback] = None,
)

The two callbacks of one study run, with the bookkeeping behind them.

Library-internal: the studies create one per call. A study calls :meth:checkpoint before and :meth:advance after every unit of work.

Parameters:

Name Type Description Default
study str

Name of the study, used in the :class:StudyCancelled message.

required
total int

Number of units the study plans.

required
progress callable

progress(done, total, label).

None
should_cancel callable

should_cancel() -> bool.

None

Raises:

Type Description
TypeError

If progress or should_cancel is neither None nor callable. The check runs before the study starts, so a wrong argument does not surface only after the first, possibly long, unit of work.

Source code in src/groundinsight/progress.py
def __init__(
    self,
    study: str,
    total: int,
    progress: Optional[ProgressCallback] = None,
    should_cancel: Optional[CancelCallback] = None,
) -> None:
    for name, callback in (("progress", progress), ("should_cancel", should_cancel)):
        if callback is not None and not callable(callback):
            raise TypeError(
                f"{name} must be callable or None, got "
                f"{type(callback).__name__}."
            )
    self.study = study
    self.done = 0
    self.total = max(int(total), 0)
    self._progress = progress
    self._should_cancel = should_cancel

advance

advance(label: str) -> None

Count one finished unit and report it.

Parameters:

Name Type Description Default
label str

Name of the unit, passed on to progress.

required
Source code in src/groundinsight/progress.py
def advance(self, label: str) -> None:
    """
    Count one finished unit and report it.

    Parameters
    ----------
    label : str
        Name of the unit, passed on to ``progress``.
    """
    self.done += 1
    if self.done > self.total:
        self.total = self.done
    if self._progress is not None:
        self._progress(self.done, self.total, str(label))

checkpoint

checkpoint() -> None

Ask should_cancel() and stop the study if it says so.

Raises:

Type Description
StudyCancelled

If should_cancel() returns a true value.

Source code in src/groundinsight/progress.py
def checkpoint(self) -> None:
    """
    Ask ``should_cancel()`` and stop the study if it says so.

    Raises
    ------
    StudyCancelled
        If ``should_cancel()`` returns a true value.
    """
    if self._should_cancel is not None and self._should_cancel():
        raise StudyCancelled(
            f"{self.study} was cancelled after {self.done} of {self.total} "
            "steps; the network is back in the state it had when the "
            "study was called.",
            done=self.done,
            total=self.total,
        )

plan

plan(total: int) -> None

Announce the number of units once the study knows it.

Parameters:

Name Type Description Default
total int

The planned number of units; never set below the units already done.

required
Source code in src/groundinsight/progress.py
def plan(self, total: int) -> None:
    """
    Announce the number of units once the study knows it.

    Parameters
    ----------
    total : int
        The planned number of units; never set below the units already
        done.
    """
    self.total = max(int(total), self.done)

diagnostics

Structured warnings and the diagnostics that belong to a single run.

groundinsight reports conditions that change how a result must be read -- a heuristic phase split in a ring, a frequency the fault scalings do not cover, a reactance that has no meaning at 0 Hz -- as warnings rather than as log lines, because the library's logging default is a NullHandler and a log line therefore reaches nobody who has not configured logging. A plain warning is still not enough for two kinds of consumer:

  • a program (a study script, a GUI, a server) needs a stable code and the elements a message is about, not only a sentence to show;
  • a message must stay with the result it belongs to. The obvious tool, :func:warnings.catch_warnings, cannot provide that: it swaps process-wide state, is documented as not thread-safe, and in a server that solves two networks at once it would hand each run the other's messages.

This module provides both without changing how the warnings look to a user who only reads them:

  • :class:GroundinsightWarning is the base class of every warning the package emits. It carries code, severity and elements (tuples (kind, name) such as ("branch", "L1")). Constructing one -- which :func:warnings.warn does before it consults the warning filters -- also records it in the active collection sink, so a warning that a user filters out is still part of the result it belongs to.
  • :func:collecting opens such a sink for one run. The sink lives in a :class:contextvars.ContextVar, which is per thread and per asyncio task, so concurrent runs never see each other's diagnostics.
  • :func:emit is the preferred way to raise one: it builds the warning with its code and element references and hands it to :func:warnings.warn.

:func:groundinsight.run_fault collects every package warning raised during the run and stores them as :class:Diagnostic records in Result.diagnostics.

Diagnostic

Bases: BaseModel

One structured message attached to a result.

Attributes:

Name Type Description
code str

Stable, upper-case identifier of the condition, e.g. "PHASE_PROXY". Programs should branch on the code, never on the message text.

severity {info, warning, error}

How strongly the condition affects the reading of the result.

category str

Name of the warning class that carried the message.

message str

The human-readable text, identical to the warning's message.

elements list of tuple of str

The network elements the message is about, as (kind, name) pairs; kind is one of "bus", "branch", "source", "fault", "bus_type", "branch_type" or "network".

Examples:

>>> import warnings
>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_quickstart
>>> with warnings.catch_warnings():
...     warnings.simplefilter("ignore", gi.InputWarning)
...     result = gi.run_fault(build_quickstart(), "fault_at_remote_bus")
>>> diagnostic = result.diagnostics[0]
>>> diagnostic.code, diagnostic.category, diagnostic.severity, diagnostic.elements
('SCALINGS_INCOMPLETE', 'InputWarning', 'warning', [('fault', 'fault_at_remote_bus')])

GroundinsightWarning

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

Bases: UserWarning

Base class of every warning emitted by groundinsight.

Parameters:

Name Type Description Default
*args

The message, as for any warning.

()
code str

Stable identifier of the condition. Defaults to the class attribute default_code.

None
elements sequence of tuple of str

Network elements the warning is about, as (kind, name) pairs.

()
severity (info, warning, error)

Defaults to "warning".

"info"
Notes

The constructor records the warning in the active :func:collecting sink. :func:warnings.warn instantiates the category before it applies the filters, so the record is made even when the warning is ignored or shown only once -- the result always carries its full set of messages, independent of how the caller configured the warning machinery.

Examples:

>>> import groundinsight as gi
>>> warning = gi.InputWarning("no scaling at 250 Hz", code="SCALINGS_INCOMPLETE",
...                           elements=[("fault", "F1")])
>>> warning.code, warning.elements, warning.severity
('SCALINGS_INCOMPLETE', (('fault', 'F1'),), 'warning')
>>> isinstance(warning, 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),
            )
        )

InputWarning

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

Bases: GroundinsightWarning

The input is incomplete or inconsistent but can still be solved.

Example: Fault.scalings does not cover every network frequency, so the missing ones are scaled with the documented default of 1.0.

Examples:

The quickstart fault gives a scaling at 50 Hz only:

>>> import warnings
>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_quickstart
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always")
...     result = gi.run_fault(build_quickstart(), "fault_at_remote_bus")
>>> [w.category.__name__ for w in caught], [d.code for d in result.diagnostics]
(['InputWarning'], ['SCALINGS_INCOMPLETE'])
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),
            )
        )

ModelAssumptionWarning

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

Bases: GroundinsightWarning

A result rests on a modelling assumption or heuristic the user must know.

Example: the phase current of a ring is split with a proxy impedance because the branch types declare no phase_impedance_formula.

Examples:

A ring without phase-conductor impedances solves with a heuristic phase split; the result carries the diagnostic whether or not the warning is shown:

>>> import warnings
>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_mv_ring
>>> with warnings.catch_warnings():
...     warnings.simplefilter("ignore", gi.ModelAssumptionWarning)
...     result = gi.run_fault(build_mv_ring(), "F1")
>>> [d.code for d in result.diagnostics]
['PHASE_PROXY']
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),
            )
        )

collecting

collecting() -> Iterator[List[Diagnostic]]

Collect the package warnings raised inside the with block.

Yields:

Type Description
list of Diagnostic

Filled while the block runs, in the order the warnings were raised.

Notes

Blocks nest: the innermost sink receives the records. The sink is bound to the current thread or asyncio task through a context variable, so collecting in one thread never sees warnings raised in another.

Source code in src/groundinsight/diagnostics.py
@contextlib.contextmanager
def collecting() -> Iterator[List[Diagnostic]]:
    """Collect the package warnings raised inside the ``with`` block.

    Yields
    ------
    list of Diagnostic
        Filled while the block runs, in the order the warnings were raised.

    Notes
    -----
    Blocks nest: the innermost sink receives the records. The sink is bound
    to the current thread or asyncio task through a context variable, so
    collecting in one thread never sees warnings raised in another.
    """
    sink: List[Diagnostic] = []
    token = _SINK.set(sink)
    try:
        yield sink
    finally:
        _SINK.reset(token)

emit

emit(
    category: type,
    message: str,
    *,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
    stacklevel: int = 2,
) -> None

Emit a structured package warning.

Parameters:

Name Type Description Default
category type

A subclass of :class:GroundinsightWarning.

required
message str

The text shown to the user.

required
code str

Stable identifier; defaults to the category's default_code.

None
elements sequence of tuple of str

(kind, name) pairs of the elements concerned.

()
severity (info, warning, error)

Defaults to "warning".

"info"
stacklevel int

As for :func:warnings.warn, counted from the caller of emit. The frames of the parameter-alias wrapper are not counted (see :func:groundinsight.utils.compat.warn_stacklevel), so a level aimed at the caller of a public function reaches it whether or not the function has a renamed parameter.

2

Raises:

Type Description
TypeError

If category is not a :class:GroundinsightWarning subclass.

Source code in src/groundinsight/diagnostics.py
def emit(
    category: type,
    message: str,
    *,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
    severity: str = "warning",
    stacklevel: int = 2,
) -> None:
    """Emit a structured package warning.

    Parameters
    ----------
    category : type
        A subclass of :class:`GroundinsightWarning`.
    message : str
        The text shown to the user.
    code : str, optional
        Stable identifier; defaults to the category's ``default_code``.
    elements : sequence of tuple of str, optional
        ``(kind, name)`` pairs of the elements concerned.
    severity : {"info", "warning", "error"}, optional
        Defaults to ``"warning"``.
    stacklevel : int, optional
        As for :func:`warnings.warn`, counted from the caller of ``emit``.
        The frames of the parameter-alias wrapper are not counted (see
        :func:`groundinsight.utils.compat.warn_stacklevel`), so a level aimed
        at the caller of a public function reaches it whether or not the
        function has a renamed parameter.

    Raises
    ------
    TypeError
        If ``category`` is not a :class:`GroundinsightWarning` subclass.
    """
    if not (isinstance(category, type) and issubclass(category, GroundinsightWarning)):
        raise TypeError(
            "emit() takes a GroundinsightWarning subclass, got "
            f"{category!r}"
        )
    warning = category(message, code=code, elements=elements, severity=severity)
    warnings.warn(warning, stacklevel=warn_stacklevel(stacklevel + 1))

note

note(
    category: type,
    message: str,
    *,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
) -> None

Record an informational diagnostic on the current run, without a warning.

Some findings explain a result without casting doubt on it -- a fault on the bus of its only source has no reduction factor by definition, not by accident. Raising those as warnings would make every study that places trial faults on every bus repeat them, and a strict warnings filter would turn a correct result into an error. They belong on the result only: note appends a :class:Diagnostic with severity "info" to the active :func:collecting sink and does nothing outside one.

Parameters:

Name Type Description Default
category type

A subclass of :class:GroundinsightWarning; its name is recorded as the diagnostic's category.

required
message str

The text shown to the user.

required
code str

Stable identifier; defaults to the category's default_code.

None
elements sequence of tuple of str

(kind, name) pairs of the elements concerned.

()

Raises:

Type Description
TypeError

If category is not a :class:GroundinsightWarning subclass.

Examples:

>>> import warnings
>>> with collecting() as sink:
...     with warnings.catch_warnings():
...         warnings.simplefilter("error")
...         note(ModelAssumptionWarning, "explains a result", code="EXAMPLE_INFO")
>>> [(d.code, d.severity) for d in sink]
[('EXAMPLE_INFO', 'info')]
Source code in src/groundinsight/diagnostics.py
def note(
    category: type,
    message: str,
    *,
    code: Optional[str] = None,
    elements: Sequence[ElementRef] = (),
) -> None:
    """Record an informational diagnostic on the current run, without a warning.

    Some findings explain a result without casting doubt on it -- a fault on
    the bus of its only source has no reduction factor by definition, not by
    accident. Raising those as warnings would make every study that places
    trial faults on every bus repeat them, and a strict warnings filter would
    turn a correct result into an error. They belong on the result only:
    ``note`` appends a :class:`Diagnostic` with severity ``"info"`` to the
    active :func:`collecting` sink and does nothing outside one.

    Parameters
    ----------
    category : type
        A subclass of :class:`GroundinsightWarning`; its name is recorded as
        the diagnostic's ``category``.
    message : str
        The text shown to the user.
    code : str, optional
        Stable identifier; defaults to the category's ``default_code``.
    elements : sequence of tuple of str, optional
        ``(kind, name)`` pairs of the elements concerned.

    Raises
    ------
    TypeError
        If ``category`` is not a :class:`GroundinsightWarning` subclass.

    Examples
    --------
    >>> import warnings
    >>> with collecting() as sink:
    ...     with warnings.catch_warnings():
    ...         warnings.simplefilter("error")
    ...         note(ModelAssumptionWarning, "explains a result", code="EXAMPLE_INFO")
    >>> [(d.code, d.severity) for d in sink]
    [('EXAMPLE_INFO', 'info')]
    """
    if not (isinstance(category, type) and issubclass(category, GroundinsightWarning)):
        raise TypeError(
            "note() takes a GroundinsightWarning subclass, got "
            f"{category!r}"
        )
    sink = _SINK.get()
    if sink is None:
        return
    sink.append(
        Diagnostic(
            code=code if code is not None else category.default_code,
            severity="info",
            category=category.__name__,
            message=message,
            elements=[(str(kind), str(name)) for kind, name in elements],
        )
    )

unique

unique(
    diagnostics: Sequence[Diagnostic],
) -> List[Diagnostic]

Drop exact repetitions while keeping the first-seen order.

Parameters:

Name Type Description Default
diagnostics sequence of Diagnostic

Records as collected; a warning raised once per element or per frequency may appear several times with identical content.

required

Returns:

Type Description
list of Diagnostic

One record per distinct (category, code, message, elements).

Source code in src/groundinsight/diagnostics.py
def unique(diagnostics: Sequence[Diagnostic]) -> List[Diagnostic]:
    """Drop exact repetitions while keeping the first-seen order.

    Parameters
    ----------
    diagnostics : sequence of Diagnostic
        Records as collected; a warning raised once per element or per
        frequency may appear several times with identical content.

    Returns
    -------
    list of Diagnostic
        One record per distinct ``(category, code, message, elements)``.
    """
    seen = set()
    kept: List[Diagnostic] = []
    for record in diagnostics:
        key = (record.category, record.code, record.message, tuple(record.elements))
        if key in seen:
            continue
        seen.add(key)
        kept.append(record)
    return kept

compat

Keyword aliases for renamed public parameters.

Every concept of the public API has one parameter name. The fault is fault; an EPR limit is u_limit, a fault duration t_k_s, the IEC 60909 AC heat factor n_factor and a frequency frequency -- the names of the model fields (Fault.t_k_s, Fault.n_factor). A user who learned one call can guess the next one; mixed names would make every call a lookup.

Renaming a public parameter breaks every call site that passes it by keyword, so the old names keep working for a while. :func:renamed_parameters maps an old keyword onto the new one and says so with a :class:DeprecationWarning that names both spellings and the removal policy (:data:DEPRECATION_POLICY). Positional calls never warn -- the position did not change.

A decorator rather than **kwargs in each signature, because

  • the signature stays the real one: :func:inspect.signature, IDEs, type checkers and the API reference show only the new names;
  • the alias handling, including the refusal of a value for both spellings, exists exactly once instead of once per function;
  • the mapping stays inspectable through __deprecated_parameters__, which is what the test that pins the rename inventory walks.

renamed_parameters

renamed_parameters(**renames: str) -> Callable[[F], F]

Accept the old keyword names of renamed parameters, with a warning.

Parameters:

Name Type Description Default
**renames str

old_name="new_name" pairs. new_name must be a parameter of the decorated function and old_name must not be.

{}

Returns:

Type Description
callable

A decorator. The function it returns behaves exactly like the decorated one, except that a keyword argument under an old name is passed on under its new name after a :class:DeprecationWarning. It carries the mapping as __deprecated_parameters__.

Raises:

Type Description
TypeError

At decoration time, if renames is empty, if a new name is not a parameter of the decorated function or if an old name still is one. At call time, if a value is passed under the new name -- by keyword or by position -- and under its old name, which is ambiguous in the same way as passing one argument twice.

Notes

The warning is raised with stacklevel=2, so it points at the caller's line. :class:DeprecationWarning is shown by default for code run as __main__ (scripts, notebook cells) and under pytest; library code that calls through with an old name stays quiet unless the warning filters are opened.

Examples:

>>> import warnings
>>> from groundinsight.utils.compat import renamed_parameters
>>> @renamed_parameters(fault_name="fault")
... def solve_one(network, fault):
...     return fault
>>> solve_one(None, "F1")
'F1'
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always")
...     solve_one(None, fault_name="F1")
'F1'
>>> caught[0].category.__name__
'DeprecationWarning'
>>> solve_one.__deprecated_parameters__
{'fault_name': 'fault'}
Source code in src/groundinsight/utils/compat.py
def renamed_parameters(**renames: str) -> Callable[[F], F]:
    """
    Accept the old keyword names of renamed parameters, with a warning.

    Parameters
    ----------
    **renames : str
        ``old_name="new_name"`` pairs. ``new_name`` must be a parameter of the
        decorated function and ``old_name`` must not be.

    Returns
    -------
    callable
        A decorator. The function it returns behaves exactly like the
        decorated one, except that a keyword argument under an old name is
        passed on under its new name after a :class:`DeprecationWarning`. It
        carries the mapping as ``__deprecated_parameters__``.

    Raises
    ------
    TypeError
        At decoration time, if ``renames`` is empty, if a new name is not a
        parameter of the decorated function or if an old name still is one.
        At call time, if a value is passed under the new name -- by keyword or
        by position -- *and* under its old name, which is ambiguous in the
        same way as passing one argument twice.

    Notes
    -----
    The warning is raised with ``stacklevel=2``, so it points at the caller's
    line. :class:`DeprecationWarning` is shown by default for code run as
    ``__main__`` (scripts, notebook cells) and under ``pytest``; library code
    that calls through with an old name stays quiet unless the warning
    filters are opened.

    Examples
    --------
    >>> import warnings
    >>> from groundinsight.utils.compat import renamed_parameters
    >>> @renamed_parameters(fault_name="fault")
    ... def solve_one(network, fault):
    ...     return fault
    >>> solve_one(None, "F1")
    'F1'
    >>> with warnings.catch_warnings(record=True) as caught:
    ...     warnings.simplefilter("always")
    ...     solve_one(None, fault_name="F1")
    'F1'
    >>> caught[0].category.__name__
    'DeprecationWarning'
    >>> solve_one.__deprecated_parameters__
    {'fault_name': 'fault'}
    """
    if not renames:
        raise TypeError("renamed_parameters() needs at least one old='new' pair.")

    def decorate(func: F) -> F:
        """
        Wrap ``func`` so that its old keyword names keep working.

        Parameters
        ----------
        func : callable
            The function whose parameters were renamed.

        Returns
        -------
        callable
            The wrapper described in :func:`renamed_parameters`.

        Raises
        ------
        TypeError
            If a new name is not a parameter of ``func`` or an old name still
            is one.
        """
        parameters = inspect.signature(func).parameters
        display = _display_name(func)
        for old, new in renames.items():
            if new not in parameters:
                raise TypeError(
                    f"{display}() has no parameter {new!r}; cannot declare "
                    f"{old!r} as its deprecated alias."
                )
            if old in parameters:
                raise TypeError(
                    f"{display}() still has a parameter {old!r}; an alias "
                    "cannot shadow a real parameter."
                )
        # Where each new name sits when passed positionally, so that
        # ``f(net, "F", fault_name="G")`` is caught as a double value.
        positions: Dict[str, int] = {
            name: index
            for index, (name, parameter) in enumerate(parameters.items())
            if parameter.kind in _POSITIONAL_KINDS
        }

        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            """
            Call ``func`` with every old keyword passed under its new name.

            ``functools.wraps`` replaces this docstring with ``func``'s at
            runtime; it documents the wrapper for the reader of this module.

            Parameters
            ----------
            *args, **kwargs
                The arguments of ``func``.

            Returns
            -------
            object
                What ``func`` returns.

            Raises
            ------
            TypeError
                If a value is passed under a new name and under its old name.
            """
            for old, new in renames.items():
                if old not in kwargs:
                    continue
                value = kwargs.pop(old)
                position = positions.get(new)
                if new in kwargs or (position is not None and len(args) > position):
                    raise TypeError(
                        f"{display}() got a value for {new!r} and for its "
                        f"deprecated alias {old!r}; pass only {new!r}."
                    )
                warnings.warn(
                    f"{display}(): the keyword {old!r} is deprecated, use "
                    f"{new!r} instead. {DEPRECATION_POLICY}",
                    DeprecationWarning,
                    stacklevel=2,
                )
                kwargs[new] = value
            return func(*args, **kwargs)

        wrapper.__deprecated_parameters__ = dict(renames)
        return wrapper  # type: ignore[return-value]

    return decorate

warn_stacklevel

warn_stacklevel(stacklevel: int) -> int

The stacklevel for a :func:warnings.warn call, alias wrappers not counted.

:func:renamed_parameters puts one frame of this module between a caller and the decorated function. A warning that the function raises with a stacklevel aimed at its caller would stop at that frame -- and a DeprecationWarning attributed to the package instead of __main__ is hidden by Python's default filters. Call this function from the frame that calls :func:warnings.warn and pass the level that would be right without any wrapper; the result counts the wrapper frames in between as well. (warnings.warn(skip_file_prefixes=...) does the same on Python 3.14, but Python 3.12 never matches a prefix that is a complete file name, so the count is done here.)

Parameters:

Name Type Description Default
stacklevel int

The level as for :func:warnings.warn, counted from the calling frame (1), with the wrapper frames of this module left out.

required

Returns:

Type Description
int

The level to pass to :func:warnings.warn from the calling frame.

Examples:

A warning meant for the caller of a function with a renamed parameter:

>>> import warnings
>>> @renamed_parameters(old_name="name")
... def api(name=None):
...     warnings.warn("for the caller", UserWarning, stacklevel=warn_stacklevel(2))
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always")
...     api()
>>> caught[0].filename.startswith("<doctest")  # not this module
True
Source code in src/groundinsight/utils/compat.py
def warn_stacklevel(stacklevel: int) -> int:
    """
    The ``stacklevel`` for a :func:`warnings.warn` call, alias wrappers not counted.

    :func:`renamed_parameters` puts one frame of this module between a caller
    and the decorated function. A warning that the function raises with a
    ``stacklevel`` aimed at its caller would stop at that frame -- and a
    ``DeprecationWarning`` attributed to the package instead of ``__main__``
    is hidden by Python's default filters. Call this function from the frame
    that calls :func:`warnings.warn` and pass the level that would be right
    without any wrapper; the result counts the wrapper frames in between as
    well. (``warnings.warn(skip_file_prefixes=...)`` does the same on Python
    3.14, but Python 3.12 never matches a prefix that is a complete file
    name, so the count is done here.)

    Parameters
    ----------
    stacklevel : int
        The level as for :func:`warnings.warn`, counted from the calling
        frame (``1``), with the wrapper frames of this module left out.

    Returns
    -------
    int
        The level to pass to :func:`warnings.warn` from the calling frame.

    Examples
    --------
    A warning meant for the caller of a function with a renamed parameter:

    >>> import warnings
    >>> @renamed_parameters(old_name="name")
    ... def api(name=None):
    ...     warnings.warn("for the caller", UserWarning, stacklevel=warn_stacklevel(2))
    >>> with warnings.catch_warnings(record=True) as caught:
    ...     warnings.simplefilter("always")
    ...     api()
    >>> caught[0].filename.startswith("<doctest")  # not this module
    True
    """
    frame = sys._getframe(1)
    level = 1
    remaining = int(stacklevel) - 1
    while remaining > 0 and frame.f_back is not None:
        frame = frame.f_back
        level += 1
        if frame.f_code.co_filename == __file__:
            continue  # a wrapper frame of renamed_parameters: not counted
        remaining -= 1
    return level

groundinsight.api

session

:class:ProjectSession -- one open project, as a front end works with it.

A session owns exactly one :class:~groundinsight.Network together with everything a user interface needs around it and a notebook does not:

  • a revision counter and undo/redo stacks of :mod:~groundinsight.api.commands. Each new command gets a fresh revision number; undo and redo return to the number of the state they restore, so a revision identifies an input state (an ETag, in REST terms) and a job's result names the state it was computed from;
  • a location: a project file (local use) or a key in a :class:ProjectStore -- an in-memory store or a :class:~groundinsight.Database (server use). Opening and saving go through the library's project-file functions, so a GUI project is a library project: UTF-8, atomic, schema-versioned. The file holds the network only -- no stored results (they are derived, go stale with the next edit and make a file useless in a diff) and no view state;
  • the type catalogue by name (see :mod:~groundinsight.api.commands);
  • resource limits (network size, job runtime, undo depth) given to the constructor, so a server can set them per user;
  • results: kept on the network as the library keeps them (network.results), so their staleness is the library's (:meth:Network.is_result_stale <groundinsight.Network.is_result_stale>, input digests compared by content) and not a second bookkeeping that could disagree. Undoing an edit therefore makes a result current again.

Multi-user and REST-ready by construction: the module holds no state, a session holds no reference to another session, every method returns a DTO, and a session is safe to use from a UI thread while its jobs run in worker threads (an internal lock guards every access to the network; a job works on its own copy). Two sessions in two threads share nothing but the library's immutable code. A session is not meant to be driven by two users at once -- a server keeps one session per user and project.

Jobs (:mod:~groundinsight.api.jobs) take a snapshot of the network when they are submitted -- a deep copy without stored results and enumerated paths, which is cheaper than the solve it protects -- and compute on it. The user can keep editing meanwhile; the result arrives bound to the revision it was computed from and is stored on the network, where the library reports it as stale if the network has moved on. A result never replaces a stored result that is current with one that is stale.

DatabaseStore

DatabaseStore(database: Database)

Bases: ProjectStore

Projects in a :class:groundinsight.Database (SQLite), keyed by network name.

The database keys networks by their name, so the store key must be the network's name. Saving replaces a stored network of that name; the database stores no results.

Parameters:

Name Type Description Default
database Database

An open database.

required
Source code in src/groundinsight/api/session.py
def __init__(self, database: "gi.Database") -> None:
    self.database = database

keys

keys() -> List[str]

The names of the stored networks (see :meth:ProjectStore.keys).

Returns:

Type Description
list of str

The network names, in the database's order.

Source code in src/groundinsight/api/session.py
def keys(self) -> List[str]:
    """
    The names of the stored networks (see :meth:`ProjectStore.keys`).

    Returns
    -------
    list of str
        The network names, in the database's order.
    """
    return list(self.database.list_networks())

load

load(key: str) -> gi.Network

Load the network named key (see :meth:ProjectStore.load).

Parameters:

Name Type Description Default
key str

The network name.

required

Returns:

Type Description
Network

A fresh network object, loaded from the database.

Raises:

Type Description
KeyError

If the database holds no network of that name.

Source code in src/groundinsight/api/session.py
def load(self, key: str) -> gi.Network:
    """
    Load the network named ``key`` (see :meth:`ProjectStore.load`).

    Parameters
    ----------
    key : str
        The network name.

    Returns
    -------
    Network
        A fresh network object, loaded from the database.

    Raises
    ------
    KeyError
        If the database holds no network of that name.
    """
    if key not in self.database.list_networks():
        raise KeyError(f"no network '{key}' in {self.database.path}")
    return self.database.load_network(key)

save

save(key: str, network: Network) -> None

Store network under its name (see :meth:ProjectStore.save).

Parameters:

Name Type Description Default
key str

The network name; it has to equal network.name.

required
network Network

The network; a stored network of that name is replaced.

required

Raises:

Type Description
ValueError

If key is not the network's name.

Source code in src/groundinsight/api/session.py
def save(self, key: str, network: gi.Network) -> None:
    """
    Store ``network`` under its name (see :meth:`ProjectStore.save`).

    Parameters
    ----------
    key : str
        The network name; it has to equal ``network.name``.
    network : Network
        The network; a stored network of that name is replaced.

    Raises
    ------
    ValueError
        If ``key`` is not the network's name.
    """
    if key != network.name:
        raise ValueError(
            f"a database stores a network under its name; key '{key}' differs "
            f"from the network name '{network.name}'"
        )
    self.database.save_network(network, overwrite=True)

MemoryStore

MemoryStore()

Bases: ProjectStore

Projects in memory, as their JSON text -- for a demo server and for tests.

Saving stores model_dump_json() of the network; loading validates it into a new object, so a loaded project shares nothing with the saved one, exactly as with a file.

Examples:

>>> store = MemoryStore()
>>> store.keys()
[]
Source code in src/groundinsight/api/session.py
def __init__(self) -> None:
    self._projects: Dict[str, str] = {}
    self._lock = threading.Lock()

keys

keys() -> List[str]

The stored project keys (see :meth:ProjectStore.keys).

Returns:

Type Description
list of str

Sorted keys.

Source code in src/groundinsight/api/session.py
def keys(self) -> List[str]:
    """
    The stored project keys (see :meth:`ProjectStore.keys`).

    Returns
    -------
    list of str
        Sorted keys.
    """
    with self._lock:
        return sorted(self._projects)

load

load(key: str) -> gi.Network

Load the network stored under key (see :meth:ProjectStore.load).

Parameters:

Name Type Description Default
key str

The project key.

required

Returns:

Type Description
Network

A fresh network object, parsed from the stored JSON.

Raises:

Type Description
KeyError

If no project is stored under key.

Source code in src/groundinsight/api/session.py
def load(self, key: str) -> gi.Network:
    """
    Load the network stored under ``key`` (see :meth:`ProjectStore.load`).

    Parameters
    ----------
    key : str
        The project key.

    Returns
    -------
    Network
        A fresh network object, parsed from the stored JSON.

    Raises
    ------
    KeyError
        If no project is stored under ``key``.
    """
    with self._lock:
        text = self._projects.get(key)
    if text is None:
        raise KeyError(f"no project '{key}' in the memory store")
    return gi.Network.model_validate_json(text)

save

save(key: str, network: Network) -> None

Store network under key (see :meth:ProjectStore.save).

Parameters:

Name Type Description Default
key str

The project key; a project stored under it is replaced.

required
network Network

The network, kept as its JSON form.

required
Source code in src/groundinsight/api/session.py
def save(self, key: str, network: gi.Network) -> None:
    """
    Store ``network`` under ``key`` (see :meth:`ProjectStore.save`).

    Parameters
    ----------
    key : str
        The project key; a project stored under it is replaced.
    network : Network
        The network, kept as its JSON form.
    """
    text = network.model_dump_json()
    with self._lock:
        self._projects[key] = text

ProjectError

Bases: ValueError

A project could not be opened or saved.

The message names the location and the reason; the original exception (an OSError, a validation error) is chained as __cause__.

ProjectSession

ProjectSession(
    network: Network,
    *,
    path: Optional[str] = None,
    store: Optional[ProjectStore] = None,
    key: Optional[str] = None,
    runner: Optional[JobRunner] = None,
    max_buses: Optional[int] = None,
    max_branches: Optional[int] = None,
    max_job_runtime_s: Optional[float] = None,
    max_undo: Optional[int] = 500,
    max_paths: Optional[int] = None,
)

One open project: a network, its edit history, its results and its jobs.

Parameters:

Name Type Description Default
network Network

The network; the session takes ownership (edit it only through :meth:apply from now on).

required
path str

Project file the network belongs to (used by :meth:save).

None
store ProjectStore

Store the network belongs to, with key; mutually exclusive with path.

None
key str

Key in store.

None
runner JobRunner

Runner for :meth:submit. Default: a thread runner with one worker, created on first use and shut down by :meth:close. A server may share one runner between sessions; the session then does not shut it down.

None
max_buses int

Size limits; a larger network is refused, and so is a command that would exceed them.

None
max_branches int

Size limits; a larger network is refused, and so is a command that would exceed them.

None
max_job_runtime_s float

Runtime limit of every job of this session.

None
max_undo int

Number of commands kept for undo (default 500).

500
max_paths int

Cap of the path enumeration on this session's network (the "paths" phase-current mode, the transient solver): it becomes the network's own :class:groundinsight.PathfinderSettings, so other sessions in the process keep theirs. None leaves the network's settings as they are.

None

Raises:

Type Description
ValueError

If the network exceeds a limit, a limit is invalid, two different types share a name (the tables would lose one), or both path and store are given.

Examples:

>>> from groundinsight.api import ProjectSession, UpdateBranch
>>> session = ProjectSession.from_example("minimal")
>>> result = session.solve("fault")
>>> result.key_figures.rms().fault_bus
'bus3'
>>> _ = session.apply(UpdateBranch(name="b23", fields={"length": 2.0}))
>>> session.is_stale("fault"), session.revision
(True, 1)
>>> _ = session.undo()
>>> session.is_stale("fault"), session.revision
(False, 0)
>>> session.close()
Source code in src/groundinsight/api/session.py
def __init__(
    self,
    network: gi.Network,
    *,
    path: Optional[str] = None,
    store: Optional[ProjectStore] = None,
    key: Optional[str] = None,
    runner: Optional[JobRunner] = None,
    max_buses: Optional[int] = None,
    max_branches: Optional[int] = None,
    max_job_runtime_s: Optional[float] = None,
    max_undo: Optional[int] = 500,
    max_paths: Optional[int] = None,
) -> None:
    if not isinstance(network, gi.Network):
        raise TypeError(f"a session holds a groundinsight.Network, got {type(network).__name__}")
    if path is not None and store is not None:
        raise ValueError("a project lives in a file or in a store, not both")
    if (store is None) != (key is None):
        raise ValueError("a store location needs both store and key")
    self._limits = SessionLimitsDTO(
        max_buses=max_buses,
        max_branches=max_branches,
        max_job_runtime_s=max_job_runtime_s,
        max_undo=max_undo,
        max_paths=max_paths,
    )
    _check_size(network, self._limits)
    if self._limits.max_paths is not None:
        # Runtime settings of this network only: kept by the job snapshots
        # (copies and pickles keep them), not written to the project file.
        network.pathfinder_settings = gi.PathfinderSettings(
            max_paths=self._limits.max_paths,
            cache_size=network.pathfinder_settings.cache_size,
        )
    network.to_tables()  # refuses two different types of the same name
    self._network = network
    self._path = str(path) if path is not None else None
    self._store = store
    self._key = key
    self._bus_types = _catalogue(network.buses.values())
    self._branch_types = _catalogue(network.branches.values())
    self._lock = threading.RLock()
    self._revision = 0
    self._saved_revision = 0
    self._revisions = itertools.count(1)
    self._done: List[_Entry] = []
    self._undone: List[_Entry] = []
    self._runner = runner
    self._owns_runner = runner is None
    self._sequence = itertools.count(1)
    self._result_sequence: Dict[str, int] = {}
    self._result_revision: Dict[str, Optional[int]] = {}
    self._result_mode: Dict[str, Optional[str]] = {}
    self._handles: List[JobHandle] = []
    self._closed = False

can_redo property

can_redo: bool

Whether :meth:redo would do something.

Returns:

Type Description
bool

True when there is an undone command to redo.

can_undo property

can_undo: bool

Whether :meth:undo would do something.

Returns:

Type Description
bool

True when there is a command to undo.

dirty property

dirty: bool

True when the network differs from the last opened or saved state.

Returns:

Type Description
bool

Whether there are unsaved changes.

limits property

limits: SessionLimitsDTO

The session's resource limits.

Returns:

Type Description
SessionLimitsDTO

The limits the session was opened with.

location property

location: Optional[str]

Where the project is stored.

Returns:

Type Description
str or None

The project file path, "<scheme>:<key>" for a store, or None for a project that was never saved.

network property

network: Network

The session's network, for reading (notebooks, tests).

Front ends use the DTO methods; every change goes through :meth:apply.

Returns:

Type Description
Network

The session's working network (not a copy).

revision property

revision: int

Identifier of the current input state (see the module docstring).

Returns:

Type Description
int

The revision; it changes with every applied, undone or redone command.

runner property

runner: JobRunner

The job runner (created on first use when none was given).

Returns:

Type Description
JobRunner

The runner that executes the session's jobs.

apply

apply(
    command: Union[Command, Dict[str, Any]],
) -> CommandResultDTO

Apply an edit command and record it for undo.

Parameters:

Name Type Description Default
command Command or dict

The command, or its JSON form (see :func:~groundinsight.api.commands.parse_command). The session applies a copy, so one command object can be applied to several sessions.

required

Returns:

Type Description
CommandResultDTO

The new revision, the library warnings the command raised (a frequency order, a source value outside the network frequencies), the stale results and the history state.

Raises:

Type Description
CommandError

If the command is rejected; network, catalogue, revision and history are unchanged.

Source code in src/groundinsight/api/session.py
def apply(self, command: Union[Command, Dict[str, Any]]) -> CommandResultDTO:
    """
    Apply an edit command and record it for undo.

    Parameters
    ----------
    command : Command or dict
        The command, or its JSON form (see
        :func:`~groundinsight.api.commands.parse_command`). The session
        applies a copy, so one command object can be applied to several
        sessions.

    Returns
    -------
    CommandResultDTO
        The new revision, the library warnings the command raised (a
        frequency order, a source value outside the network frequencies),
        the stale results and the history state.

    Raises
    ------
    CommandError
        If the command is rejected; network, catalogue, revision and
        history are unchanged.
    """
    command = parse_command(command).model_copy(deep=True)
    with self._lock:
        self._require_open()
        paths_before = self._network.paths
        with collecting() as records:
            command.apply(self._context())
        entry = _Entry(command, self._revision, next(self._revisions), paths_before)
        self._done.append(entry)
        self._undone.clear()
        limit = self._limits.max_undo
        if limit is not None and len(self._done) > limit:
            del self._done[: len(self._done) - limit]
        self._revision = entry.after
        return self._command_result(command, records)

check

check(fault: Optional[str] = None) -> CheckReportDTO

The pre-flight check (:func:groundinsight.check_network).

Parameters:

Name Type Description Default
fault str

Restrict the fault-specific checks to this fault.

None

Returns:

Type Description
CheckReportDTO

Every finding, with counts; ok is false when one of them is an error.

Source code in src/groundinsight/api/session.py
def check(self, fault: Optional[str] = None) -> CheckReportDTO:
    """
    The pre-flight check (:func:`groundinsight.check_network`).

    Parameters
    ----------
    fault : str, optional
        Restrict the fault-specific checks to this fault.

    Returns
    -------
    CheckReportDTO
        Every finding, with counts; ``ok`` is false when one of them is
        an error.
    """
    with self._lock:
        records = gi.check_network(self._network, fault=fault)
        return check_report_dto(records, revision=self._revision, fault=fault)

close

close() -> None

Cancel this session's jobs and shut down its own runner.

A runner passed to the constructor is left running (it may serve other sessions); jobs of this session on it are cancelled.

Source code in src/groundinsight/api/session.py
def close(self) -> None:
    """
    Cancel this session's jobs and shut down its own runner.

    A runner passed to the constructor is left running (it may serve
    other sessions); jobs of this session on it are cancelled.
    """
    with self._lock:
        if self._closed:
            return
        self._closed = True
        runner = self._runner
        handles = list(self._handles)
    if runner is None:
        return
    if self._owns_runner:
        runner.shutdown(wait=True)
        return
    for handle in handles:
        handle.cancel()

fault_names

fault_names() -> List[str]

Names of the faults, in network order.

Returns:

Type Description
list of str

The fault names.

Source code in src/groundinsight/api/session.py
def fault_names(self) -> List[str]:
    """
    Names of the faults, in network order.

    Returns
    -------
    list of str
        The fault names.
    """
    with self._lock:
        return list(self._network.faults)

from_example classmethod

from_example(name: str, **options: Any) -> ProjectSession

A new, unsaved project from one of the documented examples.

Parameters:

Name Type Description Default
name str

A key of :data:groundinsight.api.EXAMPLES.

required
**options Any

Keyword arguments of the constructor.

{}

Returns:

Type Description
ProjectSession

A session without location.

Raises:

Type Description
ValueError

If name is not an example.

Source code in src/groundinsight/api/session.py
@classmethod
def from_example(cls, name: str, **options: Any) -> "ProjectSession":
    """
    A new, unsaved project from one of the documented examples.

    Parameters
    ----------
    name : str
        A key of :data:`groundinsight.api.EXAMPLES`.
    **options
        Keyword arguments of the constructor.

    Returns
    -------
    ProjectSession
        A session without location.

    Raises
    ------
    ValueError
        If ``name`` is not an example.
    """
    if name not in EXAMPLES:
        raise ValueError(f"unknown example '{name}'; examples: {', '.join(EXAMPLES)}")
    return cls(EXAMPLES[name](), **options)

from_file classmethod

from_file(path: str, **options: Any) -> ProjectSession

Open a project file (:func:groundinsight.load_network_from_json).

Parameters:

Name Type Description Default
path str

The project file.

required
**options Any

Keyword arguments of the constructor (limits, runner).

{}

Returns:

Type Description
ProjectSession

A session located at path. Results stored in the file are kept on the network (the library reports whether they are stale).

Raises:

Type Description
ProjectError

If the file cannot be read, is not a project file, or exceeds the session's limits.

Source code in src/groundinsight/api/session.py
@classmethod
def from_file(cls, path: str, **options: Any) -> "ProjectSession":
    """
    Open a project file (:func:`groundinsight.load_network_from_json`).

    Parameters
    ----------
    path : str
        The project file.
    **options
        Keyword arguments of the constructor (limits, runner).

    Returns
    -------
    ProjectSession
        A session located at ``path``. Results stored in the file are kept
        on the network (the library reports whether they are stale).

    Raises
    ------
    ProjectError
        If the file cannot be read, is not a project file, or exceeds the
        session's limits.
    """
    try:
        network = gi.load_network_from_json(path)
    except (OSError, ValueError) as exc:
        raise ProjectError(f"cannot open '{path}': {rejection_reason(exc)}") from exc
    try:
        return cls(network, path=path, **options)
    except ValueError as exc:
        raise ProjectError(f"cannot open '{path}': {rejection_reason(exc)}") from exc

from_store classmethod

from_store(
    store: ProjectStore, key: str, **options: Any
) -> ProjectSession

Open a project from a store.

Parameters:

Name Type Description Default
store ProjectStore

The store.

required
key str

The project key.

required
**options Any

Keyword arguments of the constructor.

{}

Returns:

Type Description
ProjectSession

A session located at (store, key).

Raises:

Type Description
ProjectError

If the store has no such project, it does not load, or it exceeds the session's limits.

Source code in src/groundinsight/api/session.py
@classmethod
def from_store(cls, store: ProjectStore, key: str, **options: Any) -> "ProjectSession":
    """
    Open a project from a store.

    Parameters
    ----------
    store : ProjectStore
        The store.
    key : str
        The project key.
    **options
        Keyword arguments of the constructor.

    Returns
    -------
    ProjectSession
        A session located at ``(store, key)``.

    Raises
    ------
    ProjectError
        If the store has no such project, it does not load, or it exceeds
        the session's limits.
    """
    location = f"{store.scheme}:{key}"
    try:
        network = store.load(key)
    except (KeyError, OSError, ValueError, RuntimeError) as exc:
        raise ProjectError(f"cannot open '{location}': {rejection_reason(exc)}") from exc
    try:
        return cls(network, store=store, key=key, **options)
    except ValueError as exc:
        raise ProjectError(f"cannot open '{location}': {rejection_reason(exc)}") from exc

history

history() -> List[str]

Labels of the commands that :meth:undo can revert, oldest first.

Returns:

Type Description
list of str

One label per command.

Source code in src/groundinsight/api/session.py
def history(self) -> List[str]:
    """
    Labels of the commands that :meth:`undo` can revert, oldest first.

    Returns
    -------
    list of str
        One label per command.
    """
    with self._lock:
        return [entry.command.label for entry in self._done]

is_stale

is_stale(fault: str) -> bool

Whether the stored result of fault no longer matches the network.

Parameters:

Name Type Description Default
fault str

A fault with a stored result.

required

Returns:

Type Description
bool

The library's answer (:meth:Network.is_result_stale <groundinsight.Network.is_result_stale>).

Raises:

Type Description
ValueError

If no result is stored for fault.

Source code in src/groundinsight/api/session.py
def is_stale(self, fault: str) -> bool:
    """
    Whether the stored result of ``fault`` no longer matches the network.

    Parameters
    ----------
    fault : str
        A fault with a stored result.

    Returns
    -------
    bool
        The library's answer (:meth:`Network.is_result_stale
        <groundinsight.Network.is_result_stale>`).

    Raises
    ------
    ValueError
        If no result is stored for ``fault``.
    """
    with self._lock:
        return self._network.is_result_stale(fault)

redo

redo() -> Optional[CommandResultDTO]

Apply the last undone command again.

Returns:

Type Description
CommandResultDTO or None

The command and the session state afterwards; None when there is nothing to redo.

Source code in src/groundinsight/api/session.py
def redo(self) -> Optional[CommandResultDTO]:
    """
    Apply the last undone command again.

    Returns
    -------
    CommandResultDTO or None
        The command and the session state afterwards; ``None`` when there
        is nothing to redo.
    """
    with self._lock:
        self._require_open()
        if not self._undone:
            return None
        entry = self._undone.pop()
        entry.paths = self._network.paths
        with collecting() as records:
            entry.command.apply(self._context())
        self._done.append(entry)
        self._revision = entry.after
        return self._command_result(entry.command, records)

result

result(fault: str) -> Optional[FaultResultDTO]

The stored result of a fault, as a DTO.

Parameters:

Name Type Description Default
fault str

The fault.

required

Returns:

Type Description
FaultResultDTO or None

None when no result is stored. revision is the revision the result was computed from (None for one that came with the project file); stale is the library's verdict now.

Source code in src/groundinsight/api/session.py
def result(self, fault: str) -> Optional[FaultResultDTO]:
    """
    The stored result of a fault, as a DTO.

    Parameters
    ----------
    fault : str
        The fault.

    Returns
    -------
    FaultResultDTO or None
        ``None`` when no result is stored. ``revision`` is the revision
        the result was computed from (``None`` for one that came with the
        project file); ``stale`` is the library's verdict now.
    """
    with self._lock:
        if fault not in self._network.results or fault not in self._network.faults:
            return None
        return fault_result_dto(
            self._network,
            fault,
            revision=self._result_revision.get(fault),
            phase_current_mode=self._result_mode.get(fault),
            stale=self._network.is_result_stale(fault),
        )

save

save(path: Optional[str] = None) -> str

Save the project -- to path ("save as") or to its location.

Parameters:

Name Type Description Default
path str

A project file. Without it, the session's file or store location.

None

Returns:

Type Description
str

The location saved to (:attr:location).

Raises:

Type Description
ProjectError

If there is no location, or writing fails; an existing file is then unchanged (the library writes atomically) and the session stays dirty.

Source code in src/groundinsight/api/session.py
def save(self, path: Optional[str] = None) -> str:
    """
    Save the project -- to ``path`` ("save as") or to its location.

    Parameters
    ----------
    path : str, optional
        A project file. Without it, the session's file or store location.

    Returns
    -------
    str
        The location saved to (:attr:`location`).

    Raises
    ------
    ProjectError
        If there is no location, or writing fails; an existing file is
        then unchanged (the library writes atomically) and the session
        stays dirty.
    """
    with self._lock:
        self._require_open()
        if path is None and self._path is None and self._store is None:
            raise ProjectError("the project has no location yet; pass a path")
        view = _without_results(self._network)
        if path is not None or self._store is None:
            target = str(path) if path is not None else self._path
            try:
                gi.save_network_to_json(view, target)
            except (OSError, ValueError) as exc:
                raise ProjectError(f"cannot save '{target}': {rejection_reason(exc)}") from exc
            self._path, self._store, self._key = target, None, None
        else:
            self._save_to_store(self._store, self._key, view)
        self._saved_revision = self._revision
        return self.location

save_to

save_to(store: ProjectStore, key: str) -> str

Save the project into a store ("save as"); the store becomes its location.

Parameters:

Name Type Description Default
store ProjectStore

The store.

required
key str

The project key.

required

Returns:

Type Description
str

"<scheme>:<key>".

Raises:

Type Description
ProjectError

If the store refuses the project.

Source code in src/groundinsight/api/session.py
def save_to(self, store: ProjectStore, key: str) -> str:
    """
    Save the project into a store ("save as"); the store becomes its location.

    Parameters
    ----------
    store : ProjectStore
        The store.
    key : str
        The project key.

    Returns
    -------
    str
        ``"<scheme>:<key>"``.

    Raises
    ------
    ProjectError
        If the store refuses the project.
    """
    with self._lock:
        self._require_open()
        self._save_to_store(store, key, _without_results(self._network))
        self._path, self._store, self._key = None, store, key
        self._saved_revision = self._revision
        return self.location

solve

solve(
    fault: str, *, phase_current_mode: str = "auto"
) -> FaultResultDTO

Solve one fault in the calling thread and store the result.

For scripts and the command-line interface. A user interface uses :meth:submit_solve, which keeps its event loop free.

Parameters:

Name Type Description Default
fault str

The fault.

required
phase_current_mode (auto, paths)

As in :func:groundinsight.run_fault.

"auto"

Returns:

Type Description
FaultResultDTO

The result, bound to the current revision.

Raises:

Type Description
ValueError

Whatever :func:groundinsight.solve raises (unknown fault, no source, a network the solver rejects).

Source code in src/groundinsight/api/session.py
def solve(self, fault: str, *, phase_current_mode: str = "auto") -> FaultResultDTO:
    """
    Solve one fault in the calling thread and store the result.

    For scripts and the command-line interface. A user interface uses
    :meth:`submit_solve`, which keeps its event loop free.

    Parameters
    ----------
    fault : str
        The fault.
    phase_current_mode : {"auto", "paths"}
        As in :func:`groundinsight.run_fault`.

    Returns
    -------
    FaultResultDTO
        The result, bound to the current revision.

    Raises
    ------
    ValueError
        Whatever :func:`groundinsight.solve` raises (unknown fault, no
        source, a network the solver rejects).
    """
    request = SolveRequestDTO(fault=fault, phase_current_mode=phase_current_mode)
    with self._lock:
        self._require_open()
        snapshot = snapshot_network(self._network)
        revision = self._revision
        sequence = next(self._sequence)
    outcome = run_task(request, snapshot, revision=revision)
    return self._bind(outcome, sequence, revision, request)

stale_results

stale_results() -> List[str]

Faults whose stored result no longer matches the network.

Returns:

Type Description
list of str

The library's :meth:Network.stale_results <groundinsight.Network.stale_results>.

Source code in src/groundinsight/api/session.py
def stale_results(self) -> List[str]:
    """
    Faults whose stored result no longer matches the network.

    Returns
    -------
    list of str
        The library's :meth:`Network.stale_results
        <groundinsight.Network.stale_results>`.
    """
    with self._lock:
        return self._network.stale_results()

submit

submit(request: Any) -> JobHandle

Run a job request off the caller's thread.

Parameters:

Name Type Description Default
request job request DTO or dict

A :class:~groundinsight.api.schemas.SolveRequestDTO, SolveAllRequestDTO, SweepRequestDTO, OutageStudyRequestDTO or MaxRhoRequestDTO, or its JSON form.

required

Returns:

Type Description
JobHandle

Poll :meth:JobHandle.status, wait with :meth:JobHandle.result, stop with :meth:JobHandle.cancel. Fault results are stored on the network when the job finishes (see the module docstring).

Raises:

Type Description
ValueError

If the request is invalid.

RuntimeError

If the session is closed.

Source code in src/groundinsight/api/session.py
def submit(self, request: Any) -> JobHandle:
    """
    Run a job request off the caller's thread.

    Parameters
    ----------
    request : job request DTO or dict
        A :class:`~groundinsight.api.schemas.SolveRequestDTO`,
        ``SolveAllRequestDTO``, ``SweepRequestDTO``,
        ``OutageStudyRequestDTO`` or ``MaxRhoRequestDTO``, or its JSON
        form.

    Returns
    -------
    JobHandle
        Poll :meth:`JobHandle.status`, wait with :meth:`JobHandle.result`,
        stop with :meth:`JobHandle.cancel`. Fault results are stored on
        the network when the job finishes (see the module docstring).

    Raises
    ------
    ValueError
        If the request is invalid.
    RuntimeError
        If the session is closed.
    """
    request = parse_job_request(request)
    with self._lock:
        self._require_open()
        snapshot = snapshot_network(self._network)
        revision = self._revision
        sequence = next(self._sequence)
    handle = self.runner.submit(
        request,
        snapshot,
        revision=revision,
        max_runtime_s=self._limits.max_job_runtime_s,
        on_success=lambda outcome: self._bind(outcome, sequence, revision, request),
        copy_network=False,
    )
    with self._lock:
        self._handles = [h for h in self._handles if not h.done]
        self._handles.append(handle)
    return handle

submit_solve

submit_solve(
    fault: str, *, phase_current_mode: str = "auto"
) -> JobHandle

Solve one fault as a job; shorthand for :meth:submit.

Parameters:

Name Type Description Default
fault str

The fault.

required
phase_current_mode (auto, paths)

As in :func:groundinsight.run_fault.

"auto"

Returns:

Type Description
JobHandle

The job; its result is a :class:FaultResultDTO.

Source code in src/groundinsight/api/session.py
def submit_solve(self, fault: str, *, phase_current_mode: str = "auto") -> JobHandle:
    """
    Solve one fault as a job; shorthand for :meth:`submit`.

    Parameters
    ----------
    fault : str
        The fault.
    phase_current_mode : {"auto", "paths"}
        As in :func:`groundinsight.run_fault`.

    Returns
    -------
    JobHandle
        The job; its result is a :class:`FaultResultDTO`.
    """
    return self.submit(SolveRequestDTO(fault=fault, phase_current_mode=phase_current_mode))

summary

summary() -> NetworkSummaryDTO

What a header bar shows: name, counts, history and save state.

Returns:

Type Description
NetworkSummaryDTO

The summary.

Source code in src/groundinsight/api/session.py
def summary(self) -> NetworkSummaryDTO:
    """
    What a header bar shows: name, counts, history and save state.

    Returns
    -------
    NetworkSummaryDTO
        The summary.
    """
    with self._lock:
        network = self._network
        return NetworkSummaryDTO(
            name=network.name,
            description=network.description,
            frequencies=[float(f) for f in network.frequencies],
            n_buses=len(network.buses),
            n_branches=len(network.branches),
            n_sources=len(network.sources),
            n_faults=len(network.faults),
            bus_types=list(self._bus_types),
            branch_types=list(self._branch_types),
            faults=list(network.faults),
            results=list(network.results),
            stale_results=network.stale_results(),
            revision=self._revision,
            dirty=self.dirty,
            can_undo=bool(self._done),
            can_redo=bool(self._undone),
            undo_label=self._done[-1].command.label if self._done else None,
            redo_label=self._undone[-1].command.label if self._undone else None,
            location=self.location,
            limits=self._limits,
            groundinsight_version=gi.__version__,
        )

table

table(name: str) -> TableDTO

One of the tables of :meth:tables.

Parameters:

Name Type Description Default
name str

"buses", "branches", ...

required

Returns:

Type Description
TableDTO

The table.

Raises:

Type Description
KeyError

If name is not a table.

Source code in src/groundinsight/api/session.py
def table(self, name: str) -> TableDTO:
    """
    One of the tables of :meth:`tables`.

    Parameters
    ----------
    name : str
        ``"buses"``, ``"branches"``, ...

    Returns
    -------
    TableDTO
        The table.

    Raises
    ------
    KeyError
        If ``name`` is not a table.
    """
    return self.tables().tables[name]

tables

tables() -> NetworkTablesDTO

The network's input as the ten tables of Network.to_tables.

Returns:

Type Description
NetworkTablesDTO

The tables; the type tables also list catalogue types without users.

Source code in src/groundinsight/api/session.py
def tables(self) -> NetworkTablesDTO:
    """
    The network's input as the ten tables of ``Network.to_tables``.

    Returns
    -------
    NetworkTablesDTO
        The tables; the type tables also list catalogue types without
        users.
    """
    with self._lock:
        used_bus = {b.type.name for b in self._network.buses.values()}
        used_branch = {b.type.name for b in self._network.branches.values()}
        return element_tables_dto(
            self._network,
            revision=self._revision,
            extra_bus_types=[t for n, t in self._bus_types.items() if n not in used_bus],
            extra_branch_types=[t for n, t in self._branch_types.items() if n not in used_branch],
        )

undo

undo() -> Optional[CommandResultDTO]

Revert the last applied command.

Returns:

Type Description
CommandResultDTO or None

The reverted command and the session state afterwards; None when there is nothing to undo.

Source code in src/groundinsight/api/session.py
def undo(self) -> Optional[CommandResultDTO]:
    """
    Revert the last applied command.

    Returns
    -------
    CommandResultDTO or None
        The reverted command and the session state afterwards; ``None``
        when there is nothing to undo.
    """
    with self._lock:
        self._require_open()
        if not self._done:
            return None
        entry = self._done[-1]
        try:
            with collecting() as records:
                entry.command.revert(self._context())
                if self._network.paths is not entry.paths:
                    self._network.paths = entry.paths
        except Exception:
            # Reverting restores a state the library accepted before, so
            # this is a defect, not a user error: keep the entry; the
            # exception reaches the caller.
            logger.debug("undo of '%s' failed", entry.command.label, exc_info=True)
            raise
        self._done.pop()
        self._undone.append(entry)
        self._revision = entry.before
        return self._command_result(entry.command, records)

ProjectStore

Where a server keeps projects: load and save networks by key.

Subclasses implement :meth:load, :meth:save and :meth:keys. A store receives networks without stored results and returns fresh objects that share nothing with what was saved.

Attributes:

Name Type Description
scheme str

Prefix of the session location, "<scheme>:<key>".

keys

keys() -> List[str]

The stored project keys.

Returns:

Type Description
list of str

Sorted keys.

Source code in src/groundinsight/api/session.py
def keys(self) -> List[str]:  # pragma: no cover - abstract
    """
    The stored project keys.

    Returns
    -------
    list of str
        Sorted keys.
    """
    raise NotImplementedError

load

load(key: str) -> gi.Network

Load the network stored under key.

Parameters:

Name Type Description Default
key str

The project key.

required

Returns:

Type Description
Network

A fresh network object.

Raises:

Type Description
KeyError

If no project is stored under key.

Source code in src/groundinsight/api/session.py
def load(self, key: str) -> gi.Network:  # pragma: no cover - abstract
    """
    Load the network stored under ``key``.

    Parameters
    ----------
    key : str
        The project key.

    Returns
    -------
    Network
        A fresh network object.

    Raises
    ------
    KeyError
        If no project is stored under ``key``.
    """
    raise NotImplementedError

save

save(key: str, network: Network) -> None

Store network under key, replacing what was there.

Parameters:

Name Type Description Default
key str

The project key.

required
network Network

The network, without stored results.

required
Source code in src/groundinsight/api/session.py
def save(self, key: str, network: gi.Network) -> None:  # pragma: no cover - abstract
    """
    Store ``network`` under ``key``, replacing what was there.

    Parameters
    ----------
    key : str
        The project key.
    network : Network
        The network, without stored results.
    """
    raise NotImplementedError

commands

Edit commands: every change of a project, atomic and undoable.

A front end never assigns to a model field itself. It builds a command -- UpdateBus(name="b1", fields={"specific_earth_resistance": 250.0}) -- and hands it to :meth:ProjectSession.apply <groundinsight.api.ProjectSession.apply>. Three properties hold for every command:

It goes through the library. A command calls the library's own editing API -- Network.add_*, update_bus, update_branch, remove_*, assignment of Network.frequencies and of attached elements' fields -- which validates the input, re-derives the impedances through the same code path as create_bus and keeps the network's invariants (no dangling bus reference, no rename of an attached element). The command adds no physics and no second validation that could disagree with the library's.

It is atomic. A rejected command raises :class:CommandError and leaves the network, the session's type catalogue, the revision and the history exactly as they were. The library methods are atomic themselves; where a command needs several of them (a type edit re-derives every element of that type), it rolls back the steps already done before it re-raises.

It is undoable. Undo runs inverse operations through the same library API -- remove_bus undoes add_bus and vice versa -- rather than restoring a snapshot of the whole network, which would cost a deep copy of every impedance table per keystroke. What a library call drops as a side effect is put back explicitly: the stored result and the active state of a removed fault, the position of a re-added element in its dictionary, and derived values the user had overridden by assignment. The session tests check the outcome the strict way: after undo, the serialised network is identical to the one before the command, so a result computed before the command is current again (the library compares input digests by content).

Types. BusType and BranchType are read-only in the library: a type is evaluated into every element that uses it, so a changed type is a new type, swapped into its users with update_bus/update_branch. Elements refer to types by name in the tables a front end edits, so the session keeps a catalogue of types by name -- the types in use plus types added for later use -- and the type commands edit it. All of that lives in :class:_TypeCommand: should the maintainer decide that editing a type re-derives its users in place, only that class changes.

The commands are pydantic models with a discriminator field op, so they are also the request bodies of a future REST endpoint; :func:parse_command builds one from its JSON form.

AddBranch

Bases: Command

Add a branch of a catalogue type (Network.add_branch).

Attributes:

Name Type Description
name str

Name of the new branch.

type str

Name of its branch type in the session's catalogue.

from_bus, to_bus str

The buses it connects.

length float

Length in km.

specific_earth_resistance float

rho in Ohm*m; default 100.

parallel_coefficient (float, optional)

For phase_current_mode="paths"; default 1.0.

active bool

Whether the branch takes part in the solve.

description (str, optional)

Free text.

label property

label: str

add branch '<name>'.

Returns:

Type Description
str

The label in the undo history.

AddBranchType

Bases: _AddType

Add a branch type to the catalogue; see :class:_AddType.

AddBus

Bases: Command

Add a bus of a catalogue type (Network.add_bus).

Attributes:

Name Type Description
name str

Name of the new bus.

type str

Name of its bus type in the session's catalogue.

specific_earth_resistance float

rho in Ohm*m; default 100.

active bool

Whether the bus takes part in the solve.

description (str, optional)

Free text.

label property

label: str

add bus '<name>'.

Returns:

Type Description
str

The label in the undo history.

AddBusType

Bases: _AddType

Add a bus type to the catalogue; see :class:_AddType.

AddFault

Bases: Command

Add a fault (Network.add_fault).

Attributes:

Name Type Description
name str

Name of the new fault.

bus str

The faulted bus.

scalings dict of float to float, optional

Factor per frequency; a missing frequency is scaled with 1.0.

t_k_s (float, optional)

IEC 60909 short-circuit duration in s.

n_factor float

IEC 60909 AC heat factor.

description (str, optional)

Free text.

label property

label: str

add fault '<name>'.

Returns:

Type Description
str

The label in the undo history.

AddSource

Bases: Command

Add a source (Network.add_source).

Attributes:

Name Type Description
name str

Name of the new source.

bus str

The bus it feeds.

source_type {current, voltage}

Current source (values) or Thevenin source (voltage and source_impedance).

values, voltage, source_impedance dict of float to Phasor, optional

RMS phasors per frequency, as plain numbers or {"real", "imag"}.

i_k_a, r_to_x, kappa (float, optional)

IEC 60909 characteristics (metadata, not solved).

description (str, optional)

Free text.

label property

label: str

add source '<name>'.

Returns:

Type Description
str

The label in the undo history.

Command

Bases: BaseDTO

Base of every edit command.

Subclasses define their fields, a :attr:label and the two methods _apply/_revert; this class turns the library's ValueError, TypeError, KeyError and AttributeError into :class:CommandError. _apply must leave everything unchanged when it raises; _revert undoes a successful _apply and must not fail.

Attributes:

Name Type Description
op str

The operation, the discriminator of the JSON form.

label property

label: str

Human-readable description for the undo history.

Returns:

Type Description
str

The operation name; a concrete command names its element as well.

apply

apply(context: CommandContext) -> None

Apply the command.

Parameters:

Name Type Description Default
context CommandContext

Network, type catalogue and limits of the session.

required

Raises:

Type Description
CommandError

If the library rejects the change; nothing has changed then.

Source code in src/groundinsight/api/commands.py
def apply(self, context: CommandContext) -> None:
    """
    Apply the command.

    Parameters
    ----------
    context : CommandContext
        Network, type catalogue and limits of the session.

    Raises
    ------
    CommandError
        If the library rejects the change; nothing has changed then.
    """
    try:
        self._apply(context)
    except CommandError:
        raise
    except (ValueError, TypeError, KeyError, AttributeError) as exc:
        raise CommandError(f"{self.label}: {rejection_reason(exc)}") from exc

revert

revert(context: CommandContext) -> None

Undo a successful :meth:apply.

Parameters:

Name Type Description Default
context CommandContext

The same context the command was applied to.

required

Raises:

Type Description
RuntimeError

If the command was not applied.

Source code in src/groundinsight/api/commands.py
def revert(self, context: CommandContext) -> None:
    """
    Undo a successful :meth:`apply`.

    Parameters
    ----------
    context : CommandContext
        The same context the command was applied to.

    Raises
    ------
    RuntimeError
        If the command was not applied.
    """
    if self._undo is None:
        raise RuntimeError(f"cannot revert '{self.label}': it was not applied")
    self._revert(context)
    self._undo = None

CommandContext

CommandContext(
    network: Network,
    bus_types: Dict[str, BusType],
    branch_types: Dict[str, BranchType],
    limits: SessionLimitsDTO,
)

What a command acts on: the network, the type catalogue and the limits.

Parameters:

Name Type Description Default
network Network

The session's network.

required
bus_types dict of str to BusType / BranchType

The session's type catalogue by name. Commands edit these dictionaries in place.

required
branch_types dict of str to BusType / BranchType

The session's type catalogue by name. Commands edit these dictionaries in place.

required
limits SessionLimitsDTO

The session's resource limits.

required
Source code in src/groundinsight/api/commands.py
def __init__(
    self,
    network: gi.Network,
    bus_types: Dict[str, gi.BusType],
    branch_types: Dict[str, gi.BranchType],
    limits: SessionLimitsDTO,
) -> None:
    self.network = network
    self.bus_types = bus_types
    self.branch_types = branch_types
    self.limits = limits

catalogue

catalogue(kind: str) -> Dict[str, Any]

The catalogue of one element kind.

Parameters:

Name Type Description Default
kind (bus, branch)

The element kind.

"bus"

Returns:

Type Description
dict

:attr:bus_types or :attr:branch_types.

Source code in src/groundinsight/api/commands.py
def catalogue(self, kind: str) -> Dict[str, Any]:
    """
    The catalogue of one element kind.

    Parameters
    ----------
    kind : {"bus", "branch"}
        The element kind.

    Returns
    -------
    dict
        :attr:`bus_types` or :attr:`branch_types`.
    """
    return self.bus_types if kind == "bus" else self.branch_types

check_room

check_room(collection: str) -> None

Refuse one more element beyond the session's size limit.

Parameters:

Name Type Description Default
collection (buses, branches)

The element collection that is about to grow by one.

"buses"

Raises:

Type Description
CommandError

If the collection already holds max_buses/max_branches elements.

Source code in src/groundinsight/api/commands.py
def check_room(self, collection: str) -> None:
    """
    Refuse one more element beyond the session's size limit.

    Parameters
    ----------
    collection : {"buses", "branches"}
        The element collection that is about to grow by one.

    Raises
    ------
    CommandError
        If the collection already holds ``max_buses``/``max_branches``
        elements.
    """
    limit_name = {"buses": "max_buses", "branches": "max_branches"}[collection]
    limit = getattr(self.limits, limit_name)
    size = len(getattr(self.network, collection))
    if limit is not None and size >= limit:
        raise CommandError(
            f"the network already has {size} {collection}; this session "
            f"allows at most {limit} ({limit_name})"
        )

type_named

type_named(kind: str, name: Any)

Look up a type of the catalogue by name.

Parameters:

Name Type Description Default
kind (bus, branch)

The element kind.

"bus"
name str

The type name.

required

Returns:

Type Description
BusType or BranchType

The catalogue's type object.

Raises:

Type Description
CommandError

If name is not a string or names no type of the catalogue.

Source code in src/groundinsight/api/commands.py
def type_named(self, kind: str, name: Any):
    """
    Look up a type of the catalogue by name.

    Parameters
    ----------
    kind : {"bus", "branch"}
        The element kind.
    name : str
        The type name.

    Returns
    -------
    BusType or BranchType
        The catalogue's type object.

    Raises
    ------
    CommandError
        If ``name`` is not a string or names no type of the catalogue.
    """
    catalogue = self.catalogue(kind)
    if not isinstance(name, str):
        raise CommandError(
            f"a {kind} type is referred to by its name, got {type(name).__name__}"
        )
    if name not in catalogue:
        raise CommandError(
            f"{kind} type '{name}' is not in the catalogue "
            f"(known: {', '.join(sorted(catalogue)) or 'none'})"
        )
    return catalogue[name]

CommandError

Bases: ValueError

A command was rejected; the session is unchanged.

The message names the command and the library's reason.

RemoveBranch

Bases: Command

Remove a branch (Network.remove_branch).

Attributes:

Name Type Description
name str

The branch.

label property

label: str

remove branch '<name>'.

Returns:

Type Description
str

The label in the undo history.

RemoveBranchType

Bases: _RemoveType

Remove an unused branch type; see :class:_RemoveType.

RemoveBus

Bases: Command

Remove a bus that nothing refers to (Network.remove_bus).

Attributes:

Name Type Description
name str

The bus.

label property

label: str

remove bus '<name>'.

Returns:

Type Description
str

The label in the undo history.

RemoveBusType

Bases: _RemoveType

Remove an unused bus type; see :class:_RemoveType.

RemoveFault

Bases: Command

Remove a fault (Network.remove_fault).

The library drops the fault's stored result with it, and clears the active fault if it was this one; undo puts both back, so a result that was current before is current again.

Attributes:

Name Type Description
name str

The fault.

label property

label: str

remove fault '<name>'.

Returns:

Type Description
str

The label in the undo history.

RemoveSource

Bases: Command

Remove a source (Network.remove_source).

Attributes:

Name Type Description
name str

The source.

label property

label: str

remove source '<name>'.

Returns:

Type Description
str

The label in the undo history.

SetFrequencies

Bases: Command

Replace the network frequencies (assignment of Network.frequencies).

The library re-derives every bus and branch at the new frequencies, all or nothing, and refuses an empty list, duplicates and non-finite or negative values; a list that is not increasing is accepted with the FREQUENCY_ORDER warning, which the command returns.

Attributes:

Name Type Description
frequencies list of float

The new frequencies in Hz.

label property

label: str

set frequencies: [...].

Returns:

Type Description
str

The label in the undo history.

UpdateBranch

Bases: _UpdateFields

Change fields of a branch, all or nothing (Network.update_branch).

fields may hold type (a catalogue type name), length, specific_earth_resistance, from_bus, to_bus, parallel_coefficient, active and description.

UpdateBranchType

Bases: _UpdateType

Change a branch type and swap it into its branches; see :class:_UpdateType.

UpdateBus

Bases: _UpdateFields

Change fields of a bus, all or nothing (Network.update_bus).

fields may hold type (a catalogue type name), specific_earth_resistance, active and description; the impedances are re-derived by the library.

UpdateBusType

Bases: _UpdateType

Change a bus type and swap it into its buses; see :class:_UpdateType.

UpdateFault

Bases: _UpdateFields

Change fields of a fault, all or nothing.

The values are validated on a detached copy first (and bus against the network); only then are they assigned to the fault, which the library validates again. The fault object stays the same, so it stays the active fault if it was.

UpdateSource

Bases: _UpdateFields

Change fields of a source, all or nothing.

The library has no update_source: a source's fields depend on each other (source_type decides which of values/voltage must be set), so they cannot be assigned one by one. The command validates a complete replacement through the model and swaps it in with Network.add_source(..., overwrite=True), which keeps the source's position; undo swaps the former object back the same way.

parse_command

parse_command(data: Any) -> Command

Build a command from its JSON form.

Parameters:

Name Type Description Default
data dict or Command

A mapping with an op key, or a command, which is returned as is.

required

Returns:

Type Description
Command

The command object.

Raises:

Type Description
CommandError

If op names no command or a field is missing or invalid.

Examples:

>>> parse_command({"op": "remove_bus", "name": "b7"}).label
"remove bus 'b7'"
Source code in src/groundinsight/api/commands.py
def parse_command(data: Any) -> Command:
    """
    Build a command from its JSON form.

    Parameters
    ----------
    data : dict or Command
        A mapping with an ``op`` key, or a command, which is returned as is.

    Returns
    -------
    Command
        The command object.

    Raises
    ------
    CommandError
        If ``op`` names no command or a field is missing or invalid.

    Examples
    --------
    >>> parse_command({"op": "remove_bus", "name": "b7"}).label
    "remove bus 'b7'"
    """
    if isinstance(data, Command):
        return data
    op = data.get("op") if isinstance(data, dict) else None
    if op not in COMMAND_OPS:
        raise CommandError(
            f"unknown command op {op!r}; known ops: {', '.join(COMMAND_OPS)}"
        )
    try:
        return COMMAND_ADAPTER.validate_python(data)
    except ValidationError as exc:
        raise CommandError(f"invalid '{op}' command: {rejection_reason(exc)}") from exc

rejection_reason

rejection_reason(exc: BaseException) -> str

The library's reason for a rejection, as a front end shows it.

Internal API: the session words its project errors with it, too; not exported, may change in any release.

A pydantic ValidationError renders as a multi-line report (error count, model name, input echo, a link to pydantic's documentation) around the one sentence the library wrote. Front ends show the reason verbatim, so only the messages are kept, each with its field when the message does not name it already.

Parameters:

Name Type Description Default
exc BaseException

The exception the library raised.

required

Returns:

Type Description
str

One line per message, joined with "; ".

Source code in src/groundinsight/api/commands.py
def rejection_reason(exc: BaseException) -> str:
    """
    The library's reason for a rejection, as a front end shows it.

    Internal API: the session words its project errors with it, too; not
    exported, may change in any release.

    A pydantic ``ValidationError`` renders as a multi-line report (error
    count, model name, input echo, a link to pydantic's documentation) around
    the one sentence the library wrote. Front ends show the reason verbatim,
    so only the messages are kept, each with its field when the message does
    not name it already.

    Parameters
    ----------
    exc : BaseException
        The exception the library raised.

    Returns
    -------
    str
        One line per message, joined with ``"; "``.
    """
    if not isinstance(exc, ValidationError):
        return str(exc)
    parts = []
    for error in exc.errors(include_url=False):
        message = str(error.get("msg", "")).removeprefix("Value error, ")
        location = ".".join(str(part) for part in error.get("loc", ()))
        parts.append(f"{location}: {message}" if location and location not in message else message)
    return "; ".join(parts) or str(exc)

COMMAND_OPS module-attribute

COMMAND_OPS = tuple(
    cls.model_fields["op"].default for cls in COMMAND_TYPES
)

jobs

Jobs: library work off the caller's thread, with progress, cancel and limits.

A user interface has one rule for long work: the event loop that draws the window never waits for a solve. A server has a second one: one user's study must not run forever on a shared machine. :class:JobRunner serves both. It runs a job request (:mod:groundinsight.api.schemas, task = "solve", "solve_all", "sweep", "outage", "max_rho") on a network copy in a worker and hands back a :class:JobHandle that a UI timer or an HTTP handler polls (:meth:JobHandle.status is a plain DTO).

Two backends, one computation

backend="thread" (default) runs the task in a worker thread of this process: no start-up cost, the right choice for a fault solve that takes milliseconds to seconds and spends its time in NumPy/SciPy. backend="process" pickles the request and the network copy into a freshly spawned process: it costs the interpreter start (about a second) and needs inputs that pickle (a network does), and in return the job can be stopped hard and cannot take the caller's process down. Both run the same task function of :mod:groundinsight.api.tasks on equal inputs, and the tests compare their DTOs field by field.

Progress, cancel, runtime limit

Progress and cancellation use the library's study hooks: progress(done, total, label) is forwarded into the handle (from a child process through a pipe), and should_cancel() answers true once :meth:JobHandle.cancel was called or the runtime limit has passed. The study then raises :class:groundinsight.StudyCancelled at its next unit boundary and the job ends "cancelled" or "timeout" -- with no partial result. Cancellation is cooperative in a thread, because Python cannot stop a thread from outside: a single solve, which has no hook inside, runs to its end and its result is then discarded. In a process the runner asks the same way first and terminates the process if it has not stopped cancel_grace_s later, so a process job never runs much beyond its limit. A queued job that is cancelled never starts.

A job either completes ("done", with its DTO) or it does not ("cancelled", "timeout", "failed") -- a result that arrives after its cancel request or its limit is not delivered. A failure is data (:class:~groundinsight.api.schemas.JobErrorDTO: exception type and message), never an exception in the polling thread; :meth:JobHandle.result re-raises it as :class:JobFailed for code that waits.

The runner keeps no state outside its instances; a server may share one runner between sessions (each job carries its own limit) or give each session its own.

JobCancelled

JobCancelled(
    message: str = "study cancelled",
    *,
    done: int = 0,
    total: int = 0,
)

Bases: StudyCancelled

The job was cancelled -- before it started or at a unit boundary.

A subclass of :class:groundinsight.StudyCancelled, so code that handles a cancelled study handles a cancelled job too.

Source code in src/groundinsight/progress.py
def __init__(self, message: str = "study cancelled", *, done: int = 0, total: int = 0):
    super().__init__(message)
    self.done = done
    self.total = total

JobFailed

JobFailed(
    message: str,
    *,
    error_type: str = "",
    error_message: str = "",
)

Bases: RuntimeError

The job raised an exception.

The original exception is the __cause__ where it is available (thread backend).

Parameters:

Name Type Description Default
message str

The exception message.

required
error_type str

Class name of the original exception.

''
error_message str

Its message.

''

Attributes:

Name Type Description
error_type str

Class name of the original exception.

error_message str

Its message.

Source code in src/groundinsight/api/jobs.py
def __init__(self, message: str, *, error_type: str = "", error_message: str = "") -> None:
    super().__init__(message)
    self.error_type = error_type
    self.error_message = error_message

JobHandle

JobHandle(
    job_id: str,
    request: Any,
    backend: str,
    revision: Optional[int],
    max_runtime_s: Optional[float],
    label: str,
)

Observable state of one submitted job.

Created by :meth:JobRunner.submit; thread-safe.

Parameters:

Name Type Description Default
job_id str

Identifier, unique within the runner.

required
request BaseModel

The job request; its task names the task.

required
backend (thread, process)

Where the job runs.

"thread"
revision int or None

Session revision of the job's input.

required
max_runtime_s float or None

Runtime limit; None for none.

required
label str

Human-readable description of the job.

required

Attributes:

Name Type Description
job_id str

Identifier, unique within the runner.

task str

The request's task.

request BaseModel

The job request.

revision (int, optional)

Session revision of the job's input.

backend {thread, process}

Where the job runs.

max_runtime_s (float, optional)

Runtime limit.

label str

Human-readable description of the job.

Source code in src/groundinsight/api/jobs.py
def __init__(
    self,
    job_id: str,
    request: Any,
    backend: str,
    revision: Optional[int],
    max_runtime_s: Optional[float],
    label: str,
) -> None:
    self.job_id = job_id
    self.request = request
    self.task = request.task
    self.backend = backend
    self.revision = revision
    self.max_runtime_s = max_runtime_s
    self.label = label
    self._lock = threading.Lock()
    self._state = "queued"
    self._progress = ProgressDTO()
    self._started: Optional[float] = None
    self._finished: Optional[float] = None
    self._error: Optional[JobErrorDTO] = None
    self._exception: Optional[BaseException] = None
    self._result: Any = None
    self._cancel = threading.Event()
    self._ended = threading.Event()

done property

done: bool

True once the job has ended, in whatever state.

Returns:

Type Description
bool

Whether the state is one of :data:FINAL_STATES.

state property

state: str

The job's state.

Returns:

Type Description
{queued, running, done, failed, cancelled, timeout}

The current state; the last four are final.

cancel

cancel() -> bool

Ask the job to stop.

Returns:

Type Description
bool

True if the job will not complete: a queued job is cancelled at once, a running one stops at its next unit boundary (a process is terminated if it does not). False if it has already ended.

Source code in src/groundinsight/api/jobs.py
def cancel(self) -> bool:
    """
    Ask the job to stop.

    Returns
    -------
    bool
        ``True`` if the job will not complete: a queued job is cancelled
        at once, a running one stops at its next unit boundary (a process
        is terminated if it does not). ``False`` if it has already ended.
    """
    with self._lock:
        if self._state in FINAL_STATES:
            return False
        self._cancel.set()
        if self._state == "queued":
            self._state = "cancelled"
            self._finished = time.monotonic()
            self._ended.set()
        return True

result

result(timeout: Optional[float] = None) -> Any

Wait for the job and return its DTO.

Parameters:

Name Type Description Default
timeout float

Seconds to wait; None waits indefinitely.

None

Returns:

Type Description
BaseModel

The result DTO of a "done" job.

Raises:

Type Description
TimeoutError

If the job has not ended within timeout.

JobTimeout

If the runtime limit stopped it.

JobCancelled

If it was cancelled.

JobFailed

If it raised; __cause__ is the original exception where available.

Source code in src/groundinsight/api/jobs.py
def result(self, timeout: Optional[float] = None) -> Any:
    """
    Wait for the job and return its DTO.

    Parameters
    ----------
    timeout : float, optional
        Seconds to wait; ``None`` waits indefinitely.

    Returns
    -------
    BaseModel
        The result DTO of a ``"done"`` job.

    Raises
    ------
    TimeoutError
        If the job has not ended within ``timeout``.
    JobTimeout
        If the runtime limit stopped it.
    JobCancelled
        If it was cancelled.
    JobFailed
        If it raised; ``__cause__`` is the original exception where
        available.
    """
    if not self._ended.wait(timeout):
        raise TimeoutError(f"job {self.job_id} ({self.label}) has not ended yet")
    with self._lock:
        state, error, exception, result = self._state, self._error, self._exception, self._result
        progress = self._progress
    if state == "done":
        return result
    if state == "timeout":
        raise JobTimeout(
            f"job {self.job_id} ({self.label}) exceeded its runtime limit of "
            f"{self.max_runtime_s} s",
            done=progress.done,
            total=progress.total,
        )
    if state == "cancelled":
        raise JobCancelled(
            f"job {self.job_id} ({self.label}) was cancelled",
            done=progress.done,
            total=progress.total,
        )
    message = f"job {self.job_id} ({self.label}) failed: {error.type}: {error.message}"
    raise JobFailed(message, error_type=error.type, error_message=error.message) from exception

status

status() -> JobStatusDTO

A JSON-safe snapshot of the job.

Returns:

Type Description
JobStatusDTO

State, progress, timing and error.

Source code in src/groundinsight/api/jobs.py
def status(self) -> JobStatusDTO:
    """
    A JSON-safe snapshot of the job.

    Returns
    -------
    JobStatusDTO
        State, progress, timing and error.
    """
    with self._lock:
        elapsed = None
        if self._started is not None:
            elapsed = (self._finished or time.monotonic()) - self._started
        return JobStatusDTO(
            job_id=self.job_id,
            task=self.task,
            label=self.label,
            backend=self.backend,
            state=self._state,
            revision=self.revision,
            progress=self._progress,
            elapsed_s=elapsed,
            max_runtime_s=self.max_runtime_s,
            error=self._error,
        )

wait

wait(timeout: Optional[float] = None) -> bool

Block until the job has ended.

Parameters:

Name Type Description Default
timeout float

Seconds; None waits indefinitely.

None

Returns:

Type Description
bool

True if the job has ended.

Source code in src/groundinsight/api/jobs.py
def wait(self, timeout: Optional[float] = None) -> bool:
    """
    Block until the job has ended.

    Parameters
    ----------
    timeout : float, optional
        Seconds; ``None`` waits indefinitely.

    Returns
    -------
    bool
        ``True`` if the job has ended.
    """
    return self._ended.wait(timeout)

JobRunner

JobRunner(
    backend: str = "thread",
    *,
    max_workers: int = 1,
    max_runtime_s: Optional[float] = None,
    cancel_grace_s: float = 5.0,
    poll_interval_s: float = 0.05,
    keep_finished: int = 200,
)

Runs job requests in worker threads or worker processes.

Parameters:

Name Type Description Default
backend (thread, process)

Where jobs run (see the module docstring).

"thread"
max_workers int

Jobs that run at the same time; further jobs wait in the queue. Default 1.

1
max_runtime_s float

Default runtime limit of a job; :meth:submit can set one per job.

None
cancel_grace_s float

Process backend: seconds between the cooperative cancel request and terminating the process. Default 5.

5.0
poll_interval_s float

Process backend: how often the pipe and the limits are checked.

0.05
keep_finished int

Finished jobs kept for :meth:get/:meth:jobs; older ones are forgotten. Default 200.

200

Raises:

Type Description
ValueError

For an unknown backend or a non-positive worker count.

Examples:

>>> from groundinsight.api import EXAMPLES, JobRunner, SolveRequestDTO
>>> runner = JobRunner()
>>> handle = runner.submit(SolveRequestDTO(fault="fault"), EXAMPLES["minimal"]())
>>> handle.result(timeout=60).key_figures.fault_bus
'bus3'
>>> handle.status().state
'done'
>>> runner.shutdown()
Source code in src/groundinsight/api/jobs.py
def __init__(
    self,
    backend: str = "thread",
    *,
    max_workers: int = 1,
    max_runtime_s: Optional[float] = None,
    cancel_grace_s: float = 5.0,
    poll_interval_s: float = 0.05,
    keep_finished: int = 200,
) -> None:
    if backend not in ("thread", "process"):
        raise ValueError(f"backend must be 'thread' or 'process', got {backend!r}")
    if not isinstance(max_workers, int) or max_workers < 1:
        raise ValueError(f"max_workers must be a positive integer, got {max_workers!r}")
    self.backend = backend
    self.max_runtime_s = max_runtime_s
    self.cancel_grace_s = float(cancel_grace_s)
    self.poll_interval_s = float(poll_interval_s)
    self.keep_finished = int(keep_finished)
    self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="gi-job")
    self._jobs: Dict[str, JobHandle] = {}
    self._lock = threading.Lock()
    self._closed = False
    self._counter = itertools.count(1)

get

get(job_id: str) -> JobHandle

A job by its identifier.

Parameters:

Name Type Description Default
job_id str

The identifier.

required

Returns:

Type Description
JobHandle

The job.

Raises:

Type Description
KeyError

If the runner does not know the job (any more).

Source code in src/groundinsight/api/jobs.py
def get(self, job_id: str) -> JobHandle:
    """
    A job by its identifier.

    Parameters
    ----------
    job_id : str
        The identifier.

    Returns
    -------
    JobHandle
        The job.

    Raises
    ------
    KeyError
        If the runner does not know the job (any more).
    """
    with self._lock:
        return self._jobs[job_id]

jobs

jobs() -> List[JobHandle]

The jobs the runner knows, oldest first.

Returns:

Type Description
list of JobHandle

Queued, running and recently finished jobs.

Source code in src/groundinsight/api/jobs.py
def jobs(self) -> List[JobHandle]:
    """
    The jobs the runner knows, oldest first.

    Returns
    -------
    list of JobHandle
        Queued, running and recently finished jobs.
    """
    with self._lock:
        return list(self._jobs.values())

shutdown

shutdown(wait: bool = True) -> None

Cancel every job that has not ended and stop the workers.

Parameters:

Name Type Description Default
wait bool

Wait until running jobs have stopped.

True
Source code in src/groundinsight/api/jobs.py
def shutdown(self, wait: bool = True) -> None:
    """
    Cancel every job that has not ended and stop the workers.

    Parameters
    ----------
    wait : bool
        Wait until running jobs have stopped.
    """
    with self._lock:
        self._closed = True
        handles = list(self._jobs.values())
    for handle in handles:
        handle.cancel()
    self._executor.shutdown(wait=wait, cancel_futures=True)

submit

submit(
    request: Any,
    network: Network,
    *,
    label: Optional[str] = None,
    revision: Optional[int] = None,
    max_runtime_s: Optional[float] = None,
    on_success: Optional[
        Callable[[TaskOutcome], Any]
    ] = None,
    copy_network: bool = True,
) -> JobHandle

Queue a job.

Parameters:

Name Type Description Default
request job request DTO or dict

What to compute (:func:~groundinsight.api.schemas.parse_job_request).

required
network Network

The network to compute on.

required
label str

Description for the status; default "<task> <fault>".

None
revision int

Session revision of network, written into the DTOs.

None
max_runtime_s float

This job's runtime limit; default the runner's.

None
on_success callable

Called in the worker with the :class:TaskOutcome of a completed job; its return value becomes the job's result (the session uses it to store fault results on its network). Default: the outcome's DTO.

None
copy_network bool

Compute on a snapshot (:func:snapshot_network) instead of network itself. Default True; pass False only for a network the caller no longer touches.

True

Returns:

Type Description
JobHandle

The job.

Raises:

Type Description
RuntimeError

If the runner has been shut down.

ValueError

If the request is invalid.

Source code in src/groundinsight/api/jobs.py
def submit(
    self,
    request: Any,
    network: gi.Network,
    *,
    label: Optional[str] = None,
    revision: Optional[int] = None,
    max_runtime_s: Optional[float] = None,
    on_success: Optional[Callable[[TaskOutcome], Any]] = None,
    copy_network: bool = True,
) -> JobHandle:
    """
    Queue a job.

    Parameters
    ----------
    request : job request DTO or dict
        What to compute (:func:`~groundinsight.api.schemas.parse_job_request`).
    network : Network
        The network to compute on.
    label : str, optional
        Description for the status; default ``"<task> <fault>"``.
    revision : int, optional
        Session revision of ``network``, written into the DTOs.
    max_runtime_s : float, optional
        This job's runtime limit; default the runner's.
    on_success : callable, optional
        Called in the worker with the :class:`TaskOutcome` of a completed
        job; its return value becomes the job's result (the session uses
        it to store fault results on its network). Default: the outcome's
        DTO.
    copy_network : bool
        Compute on a snapshot (:func:`snapshot_network`) instead of
        ``network`` itself. Default ``True``; pass ``False`` only for a
        network the caller no longer touches.

    Returns
    -------
    JobHandle
        The job.

    Raises
    ------
    RuntimeError
        If the runner has been shut down.
    ValueError
        If the request is invalid.
    """
    request = parse_job_request(request)
    if copy_network:
        network = snapshot_network(network)
    limit = max_runtime_s if max_runtime_s is not None else self.max_runtime_s
    fault = getattr(request, "fault", None)
    text = label or (f"{request.task} {fault}" if fault else request.task)
    job_id = f"{next(self._counter)}-{uuid.uuid4().hex[:8]}"
    handle = JobHandle(job_id, request, self.backend, revision, limit, text)
    with self._lock:
        if self._closed:
            raise RuntimeError("the job runner has been shut down")
        self._jobs[job_id] = handle
        self._forget_old()
        worker = self._run_in_process if self.backend == "process" else self._run_in_thread
        self._executor.submit(worker, handle, network, on_success)
    return handle

JobTimeout

JobTimeout(
    message: str = "study cancelled",
    *,
    done: int = 0,
    total: int = 0,
)

Bases: JobCancelled

The job's runtime limit stopped it.

Source code in src/groundinsight/progress.py
def __init__(self, message: str = "study cancelled", *, done: int = 0, total: int = 0):
    super().__init__(message)
    self.done = done
    self.total = total

snapshot_network

snapshot_network(network: Network) -> gi.Network

An independent copy of a network's inputs, for a job to compute on.

copy.deepcopy with a memo that maps the stored results and the enumerated paths to empty dictionaries skips both: they are the bulk of a solved network and a solve needs neither (empty paths are rebuilt on demand). The copy's elements are attached to the copy, so a study that edits it re-derives correctly, and a result computed on it carries the same input digest as one computed on the original.

Parameters:

Name Type Description Default
network Network

The network.

required

Returns:

Type Description
Network

The copy.

Examples:

>>> import groundinsight as gi
>>> net = gi.create_network(name="n", frequencies=[50.0])
>>> copy_ = snapshot_network(net)
>>> copy_ is net, copy_.name
(False, 'n')
Source code in src/groundinsight/api/jobs.py
def snapshot_network(network: gi.Network) -> gi.Network:
    """
    An independent copy of a network's inputs, for a job to compute on.

    ``copy.deepcopy`` with a memo that maps the stored results and the
    enumerated paths to empty dictionaries skips both: they are the bulk of a
    solved network and a solve needs neither (empty paths are rebuilt on
    demand). The copy's elements are attached to the copy, so a study that
    edits it re-derives correctly, and a result computed on it carries the
    same input digest as one computed on the original.

    Parameters
    ----------
    network : Network
        The network.

    Returns
    -------
    Network
        The copy.

    Examples
    --------
    >>> import groundinsight as gi
    >>> net = gi.create_network(name="n", frequencies=[50.0])
    >>> copy_ = snapshot_network(net)
    >>> copy_ is net, copy_.name
    (False, 'n')
    """
    memo = {id(network.results): {}, id(network.paths): {}}
    return copy.deepcopy(network, memo)

schemas

Data transfer objects (DTOs) between the service layer and a front end.

They are the only data shape that crosses that boundary.

A front end -- the NiceGUI app, the command-line interface, a later REST server and its web client -- must not reach into :class:~groundinsight.Network or the Result models to draw something. Those are the library's working objects: they carry ComplexNumber phasors, frequency-keyed dictionaries and private solver state, and their shape follows the physics. A screen that picks numbers out of them is where "physics in the GUI" starts (a wrong field, a magnitude taken of the wrong phasor). The models in this module are what a front end gets instead, and they are deliberately plain:

  • Strictly JSON-safe. Every value is str, bool, int, a finite float, None, or a list/dict of those. A non-finite number -- the infinite impedance of an open end (formula "nan"), an undefined ratio -- becomes None when the DTO is built, in Python as well as in JSON: a browser's JSON.parse rejects NaN and Infinity, and a None cannot be mistaken for a number by a template either.
  • Versioned. Every DTO carries dto_schema_version (:data:DTO_SCHEMA_VERSION). A change that a reader of the previous version would misread increments it; a validator refuses a DTO of another version instead of guessing.
  • Schemas of a REST API. The DTOs are pydantic models, so they are the request and response schemas of a future HTTP layer as they stand: :func:json_schemas returns the JSON schema of every DTO, of the edit commands (:mod:groundinsight.api.commands, one discriminated union keyed by op) and of the job requests (keyed by task).
  • Tables are tables. A table is a list of columns plus a list of row dictionaries keyed by column name -- what an AG Grid, a CSV writer and a test assertion all consume without an adapter. The element tables use the pinned schema of :meth:Network.to_tables <groundinsight.Network.to_tables>, the result tables those of res_buses/res_branches, and the key figures the columns of :meth:Network.res_fault <groundinsight.Network.res_fault> -- the same names a notebook sees.

Rejected alternatives: handing out Polars frames (a frame is not a wire format, and a front end holding one starts deriving numbers from it), and exposing the pydantic result models (couples every screen to the library's internal model and its ComplexNumber encoding).

DTO_SCHEMA_VERSION module-attribute

DTO_SCHEMA_VERSION = 1

Version of the DTO layout. Incremented when a field changes its meaning or shape, or a required field is added -- whenever a reader of the previous version would misread a DTO of this one.

BaseDTO

Bases: BaseModel

Base of every DTO: no unknown keys, a schema version, JSON-safe numbers.

Internal API: the command classes derive from it too; not exported, may change in any release.

Attributes:

Name Type Description
dto_schema_version int

:data:DTO_SCHEMA_VERSION; a DTO of another version is refused.

CheckReportDTO

Bases: BaseDTO

The pre-flight check of a network (:func:groundinsight.check_network).

Attributes:

Name Type Description
revision int

Session revision the check describes.

fault (str, optional)

The fault the fault-specific checks were restricted to, if any.

ok bool

True when no record has severity "error".

n_errors, n_warnings int

Record counts by severity.

diagnostics list of DiagnosticDTO

Every finding, in the library's order.

ColumnDTO

Bases: BaseDTO

One table column.

Attributes:

Name Type Description
name str

Key of the column in every row dictionary -- the library's column name (specific_earth_resistance, EPR_V, ...).

dtype {str, float, int, bool, null}

The value type of the column.

unit (str, optional)

Physical unit where the name does not carry one ("km" for length, "Ohm*m" for specific_earth_resistance).

CommandResultDTO

Bases: BaseDTO

Outcome of an applied, undone or redone command.

Attributes:

Name Type Description
op str

The command's operation ("update_bus", ...).

label str

Human-readable description, as listed in the history.

revision int

Session revision afterwards.

diagnostics list of DiagnosticDTO

Library warnings raised while the command ran (a frequency order, a source value at a frequency the network does not solve, a DC limit).

stale_results list of str

Faults whose stored result is stale afterwards.

can_undo, can_redo bool

History state afterwards.

ComplexDTO

Bases: BaseDTO

A complex value (a phasor or an impedance) as two finite numbers.

Attributes:

Name Type Description
real, imag float

Real and imaginary part; both must be finite.

to_complex

to_complex() -> complex

The value as a Python complex.

Returns:

Type Description
complex

real + 1j * imag.

Source code in src/groundinsight/api/schemas.py
def to_complex(self) -> complex:
    """
    The value as a Python ``complex``.

    Returns
    -------
    complex
        ``real + 1j * imag``.
    """
    return complex(self.real, self.imag)

DiagnosticDTO

Bases: BaseDTO

One structured message of the library (:class:groundinsight.Diagnostic).

Attributes:

Name Type Description
code str

Stable upper-case identifier; programs branch on it, not on the text.

severity {info, warning, error}

How strongly it affects the reading of a result; "error" in a pre-flight check means the network cannot be solved as described.

category str

Name of the warning class that carried the message.

message str

The library's text, unchanged.

elements list of ElementRefDTO

The elements the message is about -- what a GUI links to.

ElementRefDTO

Bases: BaseDTO

A reference to one network element.

Attributes:

Name Type Description
kind str

"bus", "branch", "source", "fault", "bus_type", "branch_type" or "network".

name str

The element's name.

FaultResultDTO

Bases: BaseDTO

Everything a front end shows of one solved fault.

Attributes:

Name Type Description
fault, fault_bus str

The fault and its bus.

revision (int, optional)

Session revision of the inputs the result was computed from; None for a result that came with the project file.

input_digest (str, optional)

:attr:Result.input_digest <groundinsight.Result.input_digest> -- the reproducibility anchor a report prints.

phase_current_mode (str, optional)

"auto" or "paths", as solved; None when not known.

stale bool

True when the network has changed since (the library's :meth:Network.is_result_stale <groundinsight.Network.is_result_stale>).

key_figures KeyFiguresDTO

The rows of res_fault.

buses, branches TableDTO

The rows of res_buses/res_branches (long format, one row per element and frequency plus one RMS row per element).

diagnostics list of DiagnosticDTO

:attr:Result.diagnostics <groundinsight.Result.diagnostics>.

groundinsight_version str

Library version that served the result.

duration_s (float, optional)

Wall time of the solve; None when not measured.

FaultResultsDTO

Bases: BaseDTO

The results of several faults (a fault sweep).

Attributes:

Name Type Description
results list of FaultResultDTO

One per fault, in the order solved.

JobErrorDTO

Bases: BaseDTO

Why a job failed.

Attributes:

Name Type Description
type str

Exception class name ("ValueError").

message str

The exception text, unchanged.

JobStatusDTO

Bases: BaseDTO

Snapshot of a job, safe to poll from a UI timer or an HTTP client.

Attributes:

Name Type Description
job_id str

Identifier, unique within the runner.

task str

"solve", "solve_all", "sweep", "outage" or "max_rho".

label str

Human-readable description.

backend {thread, process}

Where the job runs.

state {queued, running, done, failed, cancelled, timeout}

"timeout" means the runtime limit stopped the job.

revision (int, optional)

Session revision of the inputs the job computes on.

progress ProgressDTO

Last progress report.

elapsed_s (float, optional)

Wall time since the job started running.

max_runtime_s (float, optional)

The job's runtime limit.

error (JobErrorDTO, optional)

Set for a failed job.

KeyFigureRowDTO

Bases: BaseDTO

One row of :meth:Network.res_fault <groundinsight.Network.res_fault>.

The fields are the columns of :data:groundinsight.RES_FAULT_SCHEMA, with the same names, order and meaning; see that method for the definitions. frequency_Hz is None on the RMS row (is_rms true), and every number the result marks as undefined is None.

Attributes:

Name Type Description
fault, fault_bus str

The fault and the bus the result was computed for.

frequency_Hz float or None

The frequency of the row; None on the RMS row.

is_rms bool

Whether this is the RMS row over all frequencies.

I_F_A, I_F_degree float or None

The fault current I_F: magnitude in A, angle in degrees.

EPR_fault_V, EPR_fault_degree float or None

The EPR at the fault bus: magnitude in V, angle in degrees.

EPR_max_V float or None

The largest EPR in the network, in V.

EPR_max_bus str or None

The bus it occurs at.

r_epr, r_current float or None

The EPR-based reduction factor and the current-based one, |I_E| / |I_F|.

I_E_A float or None

The earth-return current |I_E|, in A.

U_E_V float or None

The earthing voltage |U_E| of EN 50522 (the EPR at the fault bus), in V.

Z_E_Ohm, Z_E_degree float or None

The earthing impedance Z_E, the driving-point impedance of the earthing network at the fault bus: magnitude in ohms, angle in degrees.

n_diagnostics int

The number of diagnostics of the result, the same on every row.

KeyFiguresDTO

Bases: BaseDTO

The key figures of one fault: one row per frequency plus the RMS row.

Attributes:

Name Type Description
fault, fault_bus str

The fault and its bus.

rows list of KeyFigureRowDTO

In the order of res_fault: the frequencies, then the RMS row.

at

at(frequency: float) -> Optional[KeyFigureRowDTO]

The row of one frequency.

Parameters:

Name Type Description Default
frequency float

The frequency in Hz.

required

Returns:

Type Description
KeyFigureRowDTO or None

The row of frequency, if the result covers it.

Source code in src/groundinsight/api/schemas.py
def at(self, frequency: float) -> Optional[KeyFigureRowDTO]:
    """
    The row of one frequency.

    Parameters
    ----------
    frequency : float
        The frequency in Hz.

    Returns
    -------
    KeyFigureRowDTO or None
        The row of ``frequency``, if the result covers it.
    """
    return next(
        (row for row in self.rows if not row.is_rms and row.frequency_Hz == frequency),
        None,
    )

rms

rms() -> Optional[KeyFigureRowDTO]

The RMS row.

Returns:

Type Description
KeyFigureRowDTO or None

The row with is_rms true, if any.

Source code in src/groundinsight/api/schemas.py
def rms(self) -> Optional[KeyFigureRowDTO]:
    """
    The RMS row.

    Returns
    -------
    KeyFigureRowDTO or None
        The row with ``is_rms`` true, if any.
    """
    return next((row for row in self.rows if row.is_rms), None)

MaxRhoRequestDTO

Bases: BaseDTO

The largest admissible rho scaling (:func:groundinsight.find_max_rho_scaling).

The result's values hold the scalar entries of the library's report (c_max, status, ...).

Attributes:

Name Type Description
task max_rho

Discriminator.

fault str

The fault.

bus_names list of str

Buses whose specific earth resistance is scaled.

u_limit float

EPR limit in volts.

c_bounds tuple of float

Search interval of the factor.

tol_rel float

Relative bracket tolerance.

max_iter int

Bisection step limit.

monotonicity_grid int

Points of the monotonicity scan.

phase_current_mode {auto, paths}

As in :func:groundinsight.run_fault.

NetworkSummaryDTO

Bases: BaseDTO

What a header bar or a project overview shows.

Attributes:

Name Type Description
name, description str

Of the network.

frequencies list of float

The network frequencies in Hz.

n_buses, n_branches, n_sources, n_faults int

Element counts.

bus_types, branch_types list of str

Names in the session's type catalogue.

faults list of str

Fault names, in network order.

results list of str

Faults with a stored result.

stale_results list of str

Faults whose stored result no longer matches the network (:meth:Network.stale_results <groundinsight.Network.stale_results>).

revision int

Current session revision.

dirty bool

True when the network differs from the last opened/saved state.

can_undo, can_redo bool

Whether undo/redo would do something.

undo_label, redo_label (str, optional)

Label of the command undo/redo would act on.

location (str, optional)

Where the project is stored (a file path or "<store>:<key>").

limits SessionLimitsDTO

The session's resource limits.

groundinsight_version str

Version of the library computing the results.

NetworkTablesDTO

Bases: BaseDTO

The input of a network as ten tables.

The tables are those of :meth:Network.to_tables <groundinsight.Network.to_tables>.

Attributes:

Name Type Description
revision int

Session revision the tables describe.

tables dict of str to TableDTO

network, frequencies, bus_types, branch_types, buses, branches, sources, source_values, faults, fault_scalings -- in that order and with the pinned schema of :data:groundinsight.io.TABLE_SCHEMAS. The type tables also list the session's catalogue types that no element uses yet.

OutageScenarioDTO

Bases: BaseDTO

One what-if scenario (:class:groundinsight.Outage).

Attributes:

Name Type Description
name str

Unique label.

disabled_buses, disabled_branches list of str

Elements switched off in the scenario.

description (str, optional)

Free text.

OutageStudyRequestDTO

Bases: BaseDTO

An outage study (:func:groundinsight.run_outage_study).

The result's tables are buses and branches, the long-format comparisons compare_buses()/compare_branches() of :class:groundinsight.OutageStudyResult.

Attributes:

Name Type Description
task outage

Discriminator.

fault str

The fault.

scenarios list of OutageScenarioDTO

The scenarios.

include_base bool

Also solve the unchanged network as the reference scenario.

phase_current_mode {auto, paths}

As in :func:groundinsight.run_fault.

ProgressDTO

Bases: BaseDTO

Progress of a job, as the library reports it (progress(done, total, label)).

Attributes:

Name Type Description
done, total int

Units finished and planned.

label str

Name of the last finished unit.

fraction (float, optional)

done / total in [0, 1]; None while total is 0.

SessionLimitsDTO

Bases: BaseDTO

Resource limits of a session (a server sets them per user).

Attributes:

Name Type Description
max_buses, max_branches (int, optional)

Largest network the session opens or edits into; None is no limit.

max_job_runtime_s (float, optional)

Wall-clock limit of one job; None is no limit.

max_undo (int, optional)

Number of commands kept for undo; older ones are dropped.

max_paths (int, optional)

Cap of the path enumeration on the session's network (its PathfinderSettings.max_paths); None keeps the network's settings.

SolveAllRequestDTO

Bases: BaseDTO

Solve several faults in turn, cancellable between faults.

Attributes:

Name Type Description
task solve_all

Discriminator.

faults list of str, optional

The faults; None solves every fault of the network.

phase_current_mode {auto, paths}

As in :func:groundinsight.run_fault.

SolveRequestDTO

Bases: BaseDTO

Solve one fault (:func:groundinsight.solve).

Attributes:

Name Type Description
task solve

Discriminator.

fault str

The fault.

phase_current_mode {auto, paths}

As in :func:groundinsight.run_fault.

StudyResultDTO

Bases: BaseDTO

The result of a study (sweep, outage study, rho search).

Attributes:

Name Type Description
study str

The job task that produced it ("sweep", "outage", "max_rho").

fault (str, optional)

The fault studied.

revision (int, optional)

Session revision of the inputs.

tables dict of str to TableDTO

The study's result frames, unchanged (see the job request).

values dict of str to Cell

Scalar results (c_max, status, point counts).

failures dict of str to str

Points or scenarios that raised, with the exception text.

diagnostics list of DiagnosticDTO

Library warnings raised during the study, without repetitions.

groundinsight_version str

Library version.

duration_s (float, optional)

Wall time of the study.

SweepPointDTO

Bases: BaseDTO

One point of a parameter sweep (:class:groundinsight.SweepPoint).

Attributes:

Name Type Description
label str

Unique label of the point.

bus_rho dict of str to float

New specific_earth_resistance per bus.

bus_impedance dict of str to dict of float to Phasor

Impedance tables written onto Bus.impedance per frequency.

fault (str, optional)

Another fault for this point.

fault_scalings dict of float to float, optional

Replacement scalings of the fault.

parameters dict of str to Cell

Free values copied into the result rows.

SweepRequestDTO

Bases: BaseDTO

A parameter sweep (:func:groundinsight.run_sweep).

The result's tables are buses, impedances and, with collect_branches, branches -- the frames of :class:groundinsight.SweepResult.

Attributes:

Name Type Description
task sweep

Discriminator.

fault str

The fault solved at every point (unless a point names its own).

points list of SweepPointDTO

The parameter points.

phase_current_mode {auto, paths}

As in :func:groundinsight.run_fault.

collect_branches bool

Also collect the branch results.

TableDTO

Bases: BaseDTO

A table as columns plus row dictionaries.

Attributes:

Name Type Description
name str

Identifier of the table ("buses", "bus_results", ...).

columns list of ColumnDTO

The columns, in order.

rows list of dict

One dictionary per row, keyed by column name, with exactly the columns' keys. Non-finite numbers are stored as None.

Raises:

Type Description
ValueError

On construction, if a row's keys differ from the column names.

finite_or_none

finite_or_none(value: Any) -> Optional[float]

A number as a finite float, or None when that is impossible.

Parameters:

Name Type Description Default
value Any

A number (int, float, NumPy scalar), None, or anything else.

required

Returns:

Type Description
Optional[float]

float(value) when it is finite; None for None, for NaN/inf, and for a value that is not a number.

Examples:

>>> finite_or_none(1.5)
1.5
>>> finite_or_none(float("inf")) is None, finite_or_none(None) is None
(True, True)
Source code in src/groundinsight/api/schemas.py
def finite_or_none(value: Any) -> Optional[float]:
    """
    A number as a finite ``float``, or ``None`` when that is impossible.

    Parameters
    ----------
    value : Any
        A number (``int``, ``float``, NumPy scalar), ``None``, or anything
        else.

    Returns
    -------
    Optional[float]
        ``float(value)`` when it is finite; ``None`` for ``None``, for
        ``NaN``/``inf``, and for a value that is not a number.

    Examples
    --------
    >>> finite_or_none(1.5)
    1.5
    >>> finite_or_none(float("inf")) is None, finite_or_none(None) is None
    (True, True)
    """
    if value is None or isinstance(value, bool):
        return None
    try:
        number = float(value)
    except (TypeError, ValueError):
        return None
    return number if math.isfinite(number) else None

json_schemas

json_schemas() -> Dict[str, dict]

The JSON schema of every DTO, of the commands and of the job requests.

These are the request and response schemas of a future REST API; a test checks that every DTO round-trips through JSON against them.

Returns:

Type Description
dict of str to dict

DTO class name to its JSON schema, plus "Command" (the union of every edit command, discriminated by op) and "JobRequest" (the union of the job requests, discriminated by task).

Examples:

>>> schemas = json_schemas()
>>> "dto_schema_version" in schemas["FaultResultDTO"]["properties"]
True
Source code in src/groundinsight/api/schemas.py
def json_schemas() -> Dict[str, dict]:
    """
    The JSON schema of every DTO, of the commands and of the job requests.

    These are the request and response schemas of a future REST API; a test
    checks that every DTO round-trips through JSON against them.

    Returns
    -------
    dict of str to dict
        DTO class name to its JSON schema, plus ``"Command"`` (the union of
        every edit command, discriminated by ``op``) and ``"JobRequest"``
        (the union of the job requests, discriminated by ``task``).

    Examples
    --------
    >>> schemas = json_schemas()
    >>> "dto_schema_version" in schemas["FaultResultDTO"]["properties"]
    True
    """
    from .commands import COMMAND_ADAPTER  # local: commands builds on this module

    schemas: Dict[str, dict] = {}
    for name in __all__:
        cls = globals()[name]
        if isinstance(cls, type) and issubclass(cls, BaseDTO):
            schemas[name] = cls.model_json_schema()
    schemas["Command"] = COMMAND_ADAPTER.json_schema()
    schemas["JobRequest"] = _JOB_REQUEST_ADAPTER.json_schema()
    return schemas

parse_job_request

parse_job_request(data: Any) -> BaseModel

Build a job request from its JSON form.

Parameters:

Name Type Description Default
data dict or BaseModel

A mapping with a task key ("solve", "solve_all", "sweep", "outage", "max_rho"), or a request DTO, which is returned unchanged.

required

Returns:

Type Description
BaseModel

The request DTO.

Raises:

Type Description
ValueError

If task is unknown or a field is invalid (pydantic.ValidationError is a ValueError).

Examples:

>>> parse_job_request({"task": "solve", "fault": "F1"}).phase_current_mode
'auto'
Source code in src/groundinsight/api/schemas.py
def parse_job_request(data: Any) -> BaseModel:
    """
    Build a job request from its JSON form.

    Parameters
    ----------
    data : dict or BaseModel
        A mapping with a ``task`` key (``"solve"``, ``"solve_all"``,
        ``"sweep"``, ``"outage"``, ``"max_rho"``), or a request DTO, which is
        returned unchanged.

    Returns
    -------
    BaseModel
        The request DTO.

    Raises
    ------
    ValueError
        If ``task`` is unknown or a field is invalid
        (``pydantic.ValidationError`` is a ``ValueError``).

    Examples
    --------
    >>> parse_job_request({"task": "solve", "fault": "F1"}).phase_current_mode
    'auto'
    """
    if isinstance(data, BaseModel) and getattr(data, "task", None) is not None:
        return data
    return _JOB_REQUEST_ADAPTER.validate_python(data)

examples

The documented example networks, as project templates.

A user interface offers "new project from template", and the service-layer tests need networks whose numbers are documented. Both use the networks of the documentation, rebuilt here through the public API exactly as the pages build them:

  • "quickstart" -- the network of docs/getting-started/first-calculation.md (two substations, one cable), at five frequencies and with a fault whose scalings cover 50 Hz only;
  • "minimal" -- docs/examples/minimal.ipynb: a three-bus cable line at 50 Hz whose reduction factor has a closed form;
  • "mv_ring" -- docs/examples/mv_ring.ipynb: a 20-station 20 kV cable ring, 1 kA at 50 Hz fed at b01, fault F1 at b10.

Each builder returns a fresh, unsolved :class:~groundinsight.Network and touches no global state.

build_minimal

build_minimal() -> gi.Network

The three-bus cable line of the minimal example.

Returns:

Type Description
Network

SmokeTest: bus1-bus2-bus3 with 1 km cables b12 and b23, 100 A at 50 Hz fed at bus1, fault fault at bus3.

Examples:

>>> net = build_minimal()
>>> list(net.branches), net.frequencies
(['b12', 'b23'], [50.0])
Source code in src/groundinsight/api/examples.py
def build_minimal() -> gi.Network:
    """
    The three-bus cable line of the minimal example.

    Returns
    -------
    Network
        ``SmokeTest``: ``bus1``-``bus2``-``bus3`` with 1 km cables ``b12`` and
        ``b23``, 100 A at 50 Hz fed at ``bus1``, fault ``fault`` at ``bus3``.

    Examples
    --------
    >>> net = build_minimal()
    >>> list(net.branches), net.frequencies
    (['b12', 'b23'], [50.0])
    """
    net = gi.create_network(
        name="SmokeTest", frequencies=[50], description="3-bus MV-cable line, single frequency"
    )
    bus_type = gi.BusType(
        name="BusUnit",
        description="Unit-like bus impedance for plausibility tests",
        system_type="Grounded",
        voltage_level=20.0,
        impedance_formula="rho * 0 + 1.0 + I * f * 0",
    )
    cable = gi.BranchType(
        name="MSCable",
        description="MV cable reference branch",
        grounding_conductor=True,
        self_impedance_formula="(rho * 0 + 0.25 + I * 0.6)*l",
        mutual_impedance_formula="(rho * 0 + 0.0 + I * 0.6)*l",
    )
    for i in range(1, 4):
        gi.create_bus(name=f"bus{i}", type=bus_type, network=net)
    gi.create_branch(name="b12", type=cable, from_bus="bus1", to_bus="bus2", length=1.0, network=net)
    gi.create_branch(name="b23", type=cable, from_bus="bus2", to_bus="bus3", length=1.0, network=net)
    gi.create_source(name="src", bus="bus1", values={50: 100.0}, network=net)
    gi.create_fault(name="fault", bus="bus3", scalings={50: 1.0}, network=net)
    return net

build_mv_ring

build_mv_ring(n_buses: int = 20) -> gi.Network

The 20 kV cable ring of the mv_ring example.

Per section: NA2XS(F)2Y 1x300 RM/25, 0.5 km, R = 0.25 Ohm/km, L = 1.9 mH/km, Carson mutual 0.05 Ohm/km + 1.85 mH/km; every station 5 Ohm in parallel with the lumped cable capacitance (150 nF).

Parameters:

Name Type Description Default
n_buses int

Number of stations; the documented network has 20.

20

Returns:

Type Description
Network

mv_ring_<n> at 50 Hz: buses b01 ... , branches L_01_02 ..., source src (1 kA at b01), fault F1 at the opposite station (b10 for 20 stations).

Raises:

Type Description
ValueError

For fewer than three stations.

Examples:

>>> net = build_mv_ring()
>>> len(net.buses), net.faults["F1"].bus
(20, 'b10')
Source code in src/groundinsight/api/examples.py
def build_mv_ring(n_buses: int = 20) -> gi.Network:
    """
    The 20 kV cable ring of the ``mv_ring`` example.

    Per section: NA2XS(F)2Y 1x300 RM/25, 0.5 km, ``R = 0.25 Ohm/km``,
    ``L = 1.9 mH/km``, Carson mutual ``0.05 Ohm/km + 1.85 mH/km``; every
    station 5 Ohm in parallel with the lumped cable capacitance (150 nF).

    Parameters
    ----------
    n_buses : int, optional
        Number of stations; the documented network has 20.

    Returns
    -------
    Network
        ``mv_ring_<n>`` at 50 Hz: buses ``b01`` ... , branches
        ``L_01_02`` ..., source ``src`` (1 kA at ``b01``), fault ``F1`` at
        the opposite station (``b10`` for 20 stations).

    Raises
    ------
    ValueError
        For fewer than three stations.

    Examples
    --------
    >>> net = build_mv_ring()
    >>> len(net.buses), net.faults["F1"].bus
    (20, 'b10')
    """
    if n_buses < 3:
        raise ValueError(f"a ring needs at least 3 stations, got {n_buses}")
    r_per_km, l_per_km, c_per_km = 0.25, 1.9e-3, 300e-9
    r_mut_per_km, m_per_km = 0.05, 1.85e-3
    section_km, r_bus = 0.5, 5.0
    c_bus = c_per_km * section_km
    bus_type = gi.BusType(
        name="MV_substation",
        description="20 kV substation grounding, 5 ohm; cable C lumped automatically",
        system_type="Substation",
        voltage_level=20.0,
        impedance_formula=f"((rho * 0 + {r_bus}) / (1 + I * 2 * pi * f * {r_bus} * {c_bus}))",
        R_formula=f"rho * 0 + {r_bus}",
    )
    branch_type = gi.BranchType(
        name="NA2XS_300_25",
        description="NA2XS(F)2Y 1x300 RM/25 with Carson mutual coupling",
        grounding_conductor=True,
        self_impedance_formula=f"((rho * 0 + {r_per_km}) + I * 2 * pi * f * {l_per_km}) * l",
        mutual_impedance_formula=f"((rho * 0 + {r_mut_per_km}) + I * 2 * pi * f * {m_per_km}) * l",
        R_self_formula=f"({r_per_km}) * l",
        L_self_formula=f"({l_per_km}) * l",
        C_self_formula=f"({c_per_km}) * l",
        R_mutual_formula=f"({r_mut_per_km}) * l",
        M_mutual_formula=f"({m_per_km}) * l",
    )
    net = gi.create_network(name=f"mv_ring_{n_buses}", frequencies=[50.0])
    for k in range(1, n_buses + 1):
        gi.create_bus(name=f"b{k:02d}", type=bus_type, network=net)
    for k in range(1, n_buses + 1):
        nxt = (k % n_buses) + 1
        gi.create_branch(
            name=f"L_{k:02d}_{nxt:02d}",
            type=branch_type,
            from_bus=f"b{k:02d}",
            to_bus=f"b{nxt:02d}",
            length=section_km,
            network=net,
        )
    gi.create_source(name="src", bus="b01", values={50.0: 1000.0 + 0.0j}, network=net)
    gi.create_fault(name="F1", bus=f"b{n_buses // 2:02d}", scalings={50.0: 1.0}, network=net)
    return net

build_quickstart

build_quickstart() -> gi.Network

The network of the first tutorial, at five frequencies.

Returns:

Type Description
Network

QuickstartNet: buses bus_source and bus_fault, cable cable_1 (5 km), source substation_infeed (1000 A at 50 Hz plus harmonics), fault fault_at_remote_bus.

Examples:

>>> net = build_quickstart()
>>> sorted(net.buses), list(net.faults)
(['bus_fault', 'bus_source'], ['fault_at_remote_bus'])
Source code in src/groundinsight/api/examples.py
def build_quickstart() -> gi.Network:
    """
    The network of the first tutorial, at five frequencies.

    Returns
    -------
    Network
        ``QuickstartNet``: buses ``bus_source`` and ``bus_fault``, cable
        ``cable_1`` (5 km), source ``substation_infeed`` (1000 A at 50 Hz plus
        harmonics), fault ``fault_at_remote_bus``.

    Examples
    --------
    >>> net = build_quickstart()
    >>> sorted(net.buses), list(net.faults)
    (['bus_fault', 'bus_source'], ['fault_at_remote_bus'])
    """
    net = gi.create_network(name="QuickstartNet", frequencies=[50, 250, 350, 450, 550])
    bus_type = gi.BusType(
        name="SubstationBus",
        description="Lumped substation grounding grid",
        system_type="Substation",
        voltage_level=20,
        impedance_formula="rho * 0.01 + j * f * 1/50 * 0.1",
    )
    cable_type = gi.BranchType(
        name="MSCable",
        description="20 kV single-core cable with shield",
        grounding_conductor=True,
        self_impedance_formula="(0.25 + j * f * 0.012) * l",
        mutual_impedance_formula="(0.0  + j * f * 0.012) * l",
    )
    for name in ("bus_source", "bus_fault"):
        gi.create_bus(name=name, type=bus_type, network=net, specific_earth_resistance=100.0)
    gi.create_branch(
        name="cable_1",
        type=cable_type,
        from_bus="bus_source",
        to_bus="bus_fault",
        length=5.0,
        specific_earth_resistance=100.0,
        network=net,
    )
    gi.create_source(
        name="substation_infeed",
        bus="bus_source",
        values={50: 1000.0, 250: 200.0, 350: 100.0, 450: 50.0, 550: 25.0},
        network=net,
    )
    gi.create_fault(
        name="fault_at_remote_bus",
        bus="bus_fault",
        description="Single-phase-to-ground fault at bus_fault",
        scalings={50: 1.0},
        network=net,
    )
    return net

EXAMPLES module-attribute

EXAMPLES: Dict[str, Callable[[], Network]] = {
    "quickstart": build_quickstart,
    "minimal": build_minimal,
    "mv_ring": build_mv_ring,
}

Command line

cli

The groundinsight command line: solve and check a project file.

::

groundinsight run projekt.json --fault F1 [--format table|json|csv]
groundinsight check projekt.json [--fault F1] [--format table|json|csv]
python -m groundinsight ...            # the same, without the script

Why a command line, and why first: it is the smallest front end that needs everything a GUI needs -- open a project, check it, solve a fault, report the key figures and the diagnostics -- so it is the first consumer of the service layer :mod:groundinsight.api and proves its shape before a window does. It is also what a batch job, a CI pipeline or a colleague without Python experience runs.

It is built on the service layer only (the same rule the GUI follows): a :class:~groundinsight.api.ProjectSession opens the file, check prints the pre-flight check, run checks, solves through the session and prints the :class:~groundinsight.api.FaultResultDTO. No number is computed here; the table and CSV outputs only format the DTO's key figures, which are the rows of :meth:Network.res_fault <groundinsight.Network.res_fault>.

Output formats

table (default) A readable report: the key figures per frequency and RMS, then every diagnostic with its elements. json The DTO as JSON (strict RFC 8259: no NaN/Infinity) -- :class:~groundinsight.api.FaultResultDTO for run, :class:~groundinsight.api.CheckReportDTO for check and for a run the pre-flight check stopped. csv run: the key-figure rows with the columns of :data:groundinsight.RES_FAULT_SCHEMA; check: one row per finding. Diagnostics of a run go to stderr, so stdout stays pure CSV.

Exit codes

0 Success. 1 A diagnostic of severity error: the pre-flight check found the network unsolvable as described (run then solves nothing), the solve itself failed, or the result carries an error record. 2 A usage error: invalid arguments, a project file that cannot be opened, an unknown fault, or run without --fault on a network with several faults.

EXIT_ERRORS module-attribute

EXIT_ERRORS = 1

Exit code: a diagnostic of severity error.

EXIT_OK module-attribute

EXIT_OK = 0

Exit code: success.

EXIT_USAGE module-attribute

EXIT_USAGE = 2

Exit code: a usage error (arguments, project file, fault name).

main

main(argv: Optional[List[str]] = None) -> int

Run the command line.

Parameters:

Name Type Description Default
argv list of str

The arguments without the program name; default sys.argv[1:].

None

Returns:

Type Description
int

The exit code (see the module docstring). Invalid arguments make argparse exit with code 2 itself.

Examples:

>>> main(["--version"])
groundinsight 2026.11.0
Source code in src/groundinsight/cli.py
def main(argv: Optional[List[str]] = None) -> int:
    """
    Run the command line.

    Parameters
    ----------
    argv : list of str, optional
        The arguments without the program name; default ``sys.argv[1:]``.

    Returns
    -------
    int
        The exit code (see the module docstring). Invalid arguments make
        ``argparse`` exit with code 2 itself.

    Examples
    --------
    >>> main(["--version"])  # doctest: +SKIP
    groundinsight 2026.11.0
    """
    args = _parser().parse_args(argv)
    # The diagnostics are part of every report (the library records them on
    # the result whatever the warning filters say); printing each warning a
    # second time on stderr would only repeat them.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", GroundinsightWarning)
        try:
            return args.handler(args)
        except _UsageError as exc:
            _write(sys.stderr, f"groundinsight: error: {exc}\n")
            return EXIT_USAGE