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_faultwould 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 tightfft_block_bytes), a stage of the state-space solver.donecounts up by one,labelnames the unit,done <= totalholds at every call.should_cancel()is asked before every unit. A true answer raisesgi.StudyCancelled(aRuntimeErrorwith.doneand.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_faulton the input and put everything back in afinallyblock. 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 toNetworkwould need a restore line of its own -- the failure mode the studies kept running into. - Deep copy -- copying every
ComplexNumberof every element costselements x frequenciesmodel validations per solve, which on a large network is more than the solve itself, to protect objects the solve never writes to.
solve ¶
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: |
"auto"
|
Returns:
| Type | Description |
|---|---|
Result
|
A new result object with the same numbers -- bit for bit --, the same
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Whatever :func: |
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
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
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 ¶
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 |
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.
|
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
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | |
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 ¶
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
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: |
required |
total
|
int
|
Number of units the study plans. |
required |
progress
|
callable
|
|
None
|
should_cancel
|
callable
|
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in src/groundinsight/progress.py
advance ¶
Count one finished unit and report it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Name of the unit, passed on to |
required |
Source code in src/groundinsight/progress.py
checkpoint ¶
Ask should_cancel() and stop the study if it says so.
Raises:
| Type | Description |
|---|---|
StudyCancelled
|
If |
Source code in src/groundinsight/progress.py
plan ¶
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
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:
GroundinsightWarningis the base class of every warning the package emits. It carriescode,severityandelements(tuples(kind, name)such as("branch", "L1")). Constructing one -- which :func:warnings.warndoes 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:
collectingopens 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:
emitis 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. |
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 |
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
|
None
|
elements
|
sequence of tuple of str
|
Network elements the warning is about, as |
()
|
severity
|
(info, warning, error)
|
Defaults to |
"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
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
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
collecting ¶
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
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: |
required |
message
|
str
|
The text shown to the user. |
required |
code
|
str
|
Stable identifier; defaults to the category's |
None
|
elements
|
sequence of tuple of str
|
|
()
|
severity
|
(info, warning, error)
|
Defaults to |
"info"
|
stacklevel
|
int
|
As for :func: |
2
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in src/groundinsight/diagnostics.py
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: |
required |
message
|
str
|
The text shown to the user. |
required |
code
|
str
|
Stable identifier; defaults to the category's |
None
|
elements
|
sequence of tuple of str
|
|
()
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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
unique ¶
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 |
Source code in src/groundinsight/diagnostics.py
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 ¶
Accept the old keyword names of renamed parameters, with a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**renames
|
str
|
|
{}
|
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: |
Raises:
| Type | Description |
|---|---|
TypeError
|
At decoration time, if |
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
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
warn_stacklevel ¶
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: |
required |
Returns:
| Type | Description |
|---|---|
int
|
The level to pass to :func: |
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
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 ¶
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
keys ¶
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
load ¶
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
save ¶
Store network under its name (see :meth:ProjectStore.save).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The network name; it has to equal |
required |
network
|
Network
|
The network; a stored network of that name is replaced. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundinsight/api/session.py
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:
Source code in src/groundinsight/api/session.py
keys ¶
The stored project keys (see :meth:ProjectStore.keys).
Returns:
| Type | Description |
|---|---|
list of str
|
Sorted keys. |
load ¶
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 |
Source code in src/groundinsight/api/session.py
save ¶
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
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: |
required |
path
|
str
|
Project file the network belongs to (used by :meth: |
None
|
store
|
ProjectStore
|
Store the network belongs to, with |
None
|
key
|
str
|
Key in |
None
|
runner
|
JobRunner
|
Runner for :meth: |
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
|
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 |
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
can_redo
property
¶
Whether :meth:redo would do something.
Returns:
| Type | Description |
|---|---|
bool
|
|
can_undo
property
¶
Whether :meth:undo would do something.
Returns:
| Type | Description |
|---|---|
bool
|
|
dirty
property
¶
True when the network differs from the last opened or saved state.
Returns:
| Type | Description |
|---|---|
bool
|
Whether there are unsaved changes. |
limits
property
¶
The session's resource limits.
Returns:
| Type | Description |
|---|---|
SessionLimitsDTO
|
The limits the session was opened with. |
location
property
¶
Where the project is stored.
Returns:
| Type | Description |
|---|---|
str or None
|
The project file path, |
network
property
¶
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
¶
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
¶
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 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: |
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
check ¶
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; |
Source code in src/groundinsight/api/session.py
close ¶
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
fault_names ¶
Names of the faults, in network order.
Returns:
| Type | Description |
|---|---|
list of str
|
The fault names. |
from_example
classmethod
¶
A new, unsaved project from one of the documented examples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of :data: |
required |
**options
|
Any
|
Keyword arguments of the constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
ProjectSession
|
A session without location. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundinsight/api/session.py
from_file
classmethod
¶
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 |
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
from_store
classmethod
¶
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 |
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
history ¶
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
is_stale ¶
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no result is stored for |
Source code in src/groundinsight/api/session.py
redo ¶
Apply the last undone command again.
Returns:
| Type | Description |
|---|---|
CommandResultDTO or None
|
The command and the session state afterwards; |
Source code in src/groundinsight/api/session.py
result ¶
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
|
|
Source code in src/groundinsight/api/session.py
save ¶
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: |
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
save_to ¶
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
|
|
Raises:
| Type | Description |
|---|---|
ProjectError
|
If the store refuses the project. |
Source code in src/groundinsight/api/session.py
solve ¶
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: |
"auto"
|
Returns:
| Type | Description |
|---|---|
FaultResultDTO
|
The result, bound to the current revision. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Whatever :func: |
Source code in src/groundinsight/api/session.py
stale_results ¶
Faults whose stored result no longer matches the network.
Returns:
| Type | Description |
|---|---|
list of str
|
The library's :meth: |
Source code in src/groundinsight/api/session.py
submit ¶
Run a job request off the caller's thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
job request DTO or dict
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
JobHandle
|
Poll :meth: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the request is invalid. |
RuntimeError
|
If the session is closed. |
Source code in src/groundinsight/api/session.py
submit_solve ¶
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: |
"auto"
|
Returns:
| Type | Description |
|---|---|
JobHandle
|
The job; its result is a :class: |
Source code in src/groundinsight/api/session.py
summary ¶
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
table ¶
One of the tables of :meth:tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
TableDTO
|
The table. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Source code in src/groundinsight/api/session.py
tables ¶
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
undo ¶
Revert the last applied command.
Returns:
| Type | Description |
|---|---|
CommandResultDTO or None
|
The reverted command and the session state afterwards; |
Source code in src/groundinsight/api/session.py
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, |
keys ¶
The stored project keys.
Returns:
| Type | Description |
|---|---|
list of str
|
Sorted keys. |
load ¶
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 |
Source code in src/groundinsight/api/session.py
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
|
|
parallel_coefficient |
(float, optional)
|
For |
active |
bool
|
Whether the branch takes part in the solve. |
description |
(str, optional)
|
Free text. |
label
property
¶
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
|
|
active |
bool
|
Whether the bus takes part in the solve. |
description |
(str, optional)
|
Free text. |
label
property
¶
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
¶
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, voltage, source_impedance |
dict of float to Phasor, optional
|
RMS phasors per frequency, as plain numbers or |
i_k_a, r_to_x, kappa |
(float, optional)
|
IEC 60909 characteristics (metadata, not solved). |
description |
(str, optional)
|
Free text. |
label
property
¶
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
¶
Human-readable description for the undo history.
Returns:
| Type | Description |
|---|---|
str
|
The operation name; a concrete command names its element as well. |
apply ¶
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
revert ¶
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
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
catalogue ¶
The catalogue of one element kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
(bus, branch)
|
The element kind. |
"bus"
|
Returns:
| Type | Description |
|---|---|
dict
|
:attr: |
Source code in src/groundinsight/api/commands.py
check_room ¶
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 |
Source code in src/groundinsight/api/commands.py
type_named ¶
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 |
Source code in src/groundinsight/api/commands.py
CommandError ¶
Bases: ValueError
A command was rejected; the session is unchanged.
The message names the command and the library's reason.
RemoveBranch ¶
RemoveBranchType ¶
Bases: _RemoveType
Remove an unused branch type; see :class:_RemoveType.
RemoveBus ¶
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
¶
remove fault '<name>'.
Returns:
| Type | Description |
|---|---|
str
|
The label in the undo history. |
RemoveSource ¶
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
¶
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 ¶
Build a command from its JSON form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict or Command
|
A mapping with an |
required |
Returns:
| Type | Description |
|---|---|
Command
|
The command object. |
Raises:
| Type | Description |
|---|---|
CommandError
|
If |
Examples:
Source code in src/groundinsight/api/commands.py
rejection_reason ¶
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
COMMAND_OPS
module-attribute
¶
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 ¶
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
JobFailed ¶
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
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 |
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; |
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
done
property
¶
True once the job has ended, in whatever state.
Returns:
| Type | Description |
|---|---|
bool
|
Whether the state is one of :data: |
state
property
¶
The job's state.
Returns:
| Type | Description |
|---|---|
{queued, running, done, failed, cancelled, timeout}
|
The current state; the last four are final. |
cancel ¶
Ask the job to stop.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/groundinsight/api/jobs.py
result ¶
Wait for the job and return its DTO.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Seconds to wait; |
None
|
Returns:
| Type | Description |
|---|---|
BaseModel
|
The result DTO of a |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If the job has not ended within |
JobTimeout
|
If the runtime limit stopped it. |
JobCancelled
|
If it was cancelled. |
JobFailed
|
If it raised; |
Source code in src/groundinsight/api/jobs.py
status ¶
A JSON-safe snapshot of the job.
Returns:
| Type | Description |
|---|---|
JobStatusDTO
|
State, progress, timing and error. |
Source code in src/groundinsight/api/jobs.py
wait ¶
Block until the job has ended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Seconds; |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/groundinsight/api/jobs.py
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: |
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: |
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
get ¶
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
jobs ¶
The jobs the runner knows, oldest first.
Returns:
| Type | Description |
|---|---|
list of JobHandle
|
Queued, running and recently finished jobs. |
shutdown ¶
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
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: |
required |
network
|
Network
|
The network to compute on. |
required |
label
|
str
|
Description for the status; default |
None
|
revision
|
int
|
Session revision of |
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: |
None
|
copy_network
|
bool
|
Compute on a snapshot (:func: |
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
JobTimeout ¶
Bases: JobCancelled
The job's runtime limit stopped it.
Source code in src/groundinsight/progress.py
snapshot_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
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 finitefloat,None, or a list/dict of those. A non-finite number -- the infinite impedance of an open end (formula"nan"), an undefined ratio -- becomesNonewhen the DTO is built, in Python as well as in JSON: a browser'sJSON.parserejectsNaNandInfinity, and aNonecannot 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_schemasreturns the JSON schema of every DTO, of the edit commands (:mod:groundinsight.api.commands, one discriminated union keyed byop) and of the job requests (keyed bytask). - 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 ofres_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
¶
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: |
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
|
|
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 ( |
dtype |
{str, float, int, bool, null}
|
The value type of the column. |
unit |
(str, optional)
|
Physical unit where the name does not carry one ( |
CommandResultDTO ¶
Bases: BaseDTO
Outcome of an applied, undone or redone command.
Attributes:
| Name | Type | Description |
|---|---|---|
op |
str
|
The command's operation ( |
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 ¶
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; |
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
|
|
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;
|
input_digest |
(str, optional)
|
:attr: |
phase_current_mode |
(str, optional)
|
|
stale |
bool
|
|
key_figures |
KeyFiguresDTO
|
The rows of |
buses, branches |
TableDTO
|
The rows of |
diagnostics |
list of DiagnosticDTO
|
:attr: |
groundinsight_version |
str
|
Library version that served the result. |
duration_s |
(float, optional)
|
Wall time of the solve; |
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 ( |
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
|
|
label |
str
|
Human-readable description. |
backend |
{thread, process}
|
Where the job runs. |
state |
{queued, running, done, failed, cancelled, timeout}
|
|
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; |
is_rms |
bool
|
Whether this is the RMS row over all frequencies. |
I_F_A, I_F_degree |
float or None
|
The fault current |
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_A |
float or None
|
The earth-return current |
U_E_V |
float or None
|
The earthing voltage |
Z_E_Ohm, Z_E_degree |
float or None
|
The earthing impedance |
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 |
at ¶
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 |
Source code in src/groundinsight/api/schemas.py
rms ¶
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: |
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: |
revision |
int
|
Current session revision. |
dirty |
bool
|
|
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 |
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
|
|
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: |
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)
|
|
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; |
max_job_runtime_s |
(float, optional)
|
Wall-clock limit of one job; |
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
|
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; |
phase_current_mode |
{auto, paths}
|
As in :func: |
SolveRequestDTO ¶
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 ( |
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 ( |
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 |
bus_impedance |
dict of str to dict of float to Phasor
|
Impedance tables written onto |
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: |
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 ( |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
On construction, if a row's keys differ from the column names. |
finite_or_none ¶
A number as a finite float, or None when that is impossible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
A number ( |
required |
Returns:
| Type | Description |
|---|---|
Optional[float]
|
|
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
json_schemas ¶
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 |
Examples:
>>> schemas = json_schemas()
>>> "dto_schema_version" in schemas["FaultResultDTO"]["properties"]
True
Source code in src/groundinsight/api/schemas.py
parse_job_request ¶
Build a job request from its JSON form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict or BaseModel
|
A mapping with a |
required |
Returns:
| Type | Description |
|---|---|
BaseModel
|
The request DTO. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/groundinsight/api/schemas.py
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 ofdocs/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 atb01, faultF1atb10.
Each builder returns a fresh, unsolved :class:~groundinsight.Network and
touches no global state.
build_minimal ¶
The three-bus cable line of the minimal example.
Returns:
| Type | Description |
|---|---|
Network
|
|
Examples:
Source code in src/groundinsight/api/examples.py
build_mv_ring ¶
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
For fewer than three stations. |
Examples:
Source code in src/groundinsight/api/examples.py
build_quickstart ¶
The network of the first tutorial, at five frequencies.
Returns:
| Type | Description |
|---|---|
Network
|
|
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
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_USAGE
module-attribute
¶
Exit code: a usage error (arguments, project file, fault name).
main ¶
Run the command line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list of str
|
The arguments without the program name; default |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The exit code (see the module docstring). Invalid arguments make
|
Examples: