Network importers (I/O)¶
External-network importers convert existing power-system models from
third-party tools into a groundinsight.Network. They do not build
grounding networks from scratch — instead they project an existing
distribution-network topology onto the bus / branch primitives that
groundinsight solves for, while the user supplies the grounding-side
impedance formulas via an ImportDefaults object. The first
inhabitant is the pandapower importer; PowerFactory .dgs and the
live PowerFactory Python API are on the roadmap.
Two kinds of import are on this page. The topology import
(preview_pandapower_import, from_pandapower) answers which buses
and branches exist. The short-circuit result import
(read_shortcircuit_results, apply_shortcircuit_characteristics)
answers how hard the fault drives them — it takes a case already
solved by pandapower.shortcircuit.calc_sc and turns it into the
IEC 60909 excitation of the grounding model. The two are independent:
a hand-built Network can take the short-circuit import just as well,
as long as its bus names match.
The package's own file format — the JSON project file written by
gi.save_network_to_json — is described at the end of this page under
Project files (JSON).
Physical / modelling context¶
Distribution-network databases (pandapower, PowerFactory, NEPLAN,
PSS®E) carry the electrical topology: buses, lines, transformers,
their resistance and reactance per phase. They do not carry the
grounding-side model — neither the bus grounding impedance
\(Z_{\text{B}}(\rho_E, f)\) nor the cable-shield self / mutual
impedance \(Z_{\text{self}}, Z_{\text{mutual}}\) that
groundinsight needs. The importer therefore adopts the pandapower
topology (which buses exist, which lines connect them, how long the
lines are) and asks the user to supply the grounding-side
parameters via ImportDefaults. That separation keeps the importer
schema-stable across tools — every importer accepts the same
ImportDefaults shape — and lets the user attach the same set of
grounding formulas to networks coming from different sources.
The active flag (default True) is propagated from
pandapower.in_service so that out-of-service equipment is excluded
from the nodal solve straight away — see the
outage-study reference for the runtime equivalent.
Example¶
pandapower.networks.example_simple() has a 110 kV and a 20 kV level joined by
a transformer. The 20 kV level is imported; its MV Transformer Bus reaches the
MV Main Bus only through a closed bus-to-bus switch, which
switch_branch_type turns into a short branch — without it that bus would be
isolated and read 0 V (see below). The earthing types are illustrative; the
complete script and its output are in the how-to
Import from pandapower.
net_pp = pn.example_simple()
station = gi.BusType(name="MV station", system_type="Station", voltage_level=20.0,
impedance_formula="2*rho/(3*1.13*sqrt(100.0))")
cable_system = gi.BranchType(
name="3x NA2XS(F)2Y 1x300RM/25 12/20 kV, trefoil",
grounding_conductor=True,
self_impedance_formula=(
"(0.727/3 + pi**2*1e-4*f + j*4*pi*1e-4*f*log(658*sqrt(rho/f)/0.03151272))*l"
),
mutual_impedance_formula=(
"(pi**2*1e-4*f + j*4*pi*1e-4*f*log(658*sqrt(rho/f)/0.03151272))*l"
),
)
bond = gi.BranchType(name="busbar bond", grounding_conductor=True,
self_impedance_formula="(0.05 + j*2*pi*f*1e-3)*l",
mutual_impedance_formula="0")
defaults = gi.ImportDefaults(
rho=100.0,
frequencies=[50.0],
default_bus_type=station,
default_branch_type=cable_system,
switch_branch_type=bond, # closed bus-to-bus switches become 1 m branches
derive_phase_impedance=True, # phase_impedance_formula from r/x of each line
)
preview = gi.preview_pandapower_import(net_pp, voltage_level_kV=20.0, defaults=defaults)
counts = preview.group_by("status", "kind").len().sort("status", "kind")
with collecting() as records:
net = gi.from_pandapower(net_pp, defaults=defaults, voltage_level_kV=20.0,
network_name="example_simple, 20 kV")
The import keeps 4 buses and 4 branches (Line 2, Line 3, Line 4 and the
bond switch_bus_1) and skips the three 110 kV buses, the 110 kV line, the
other switches and the transformer. Line 3 is open at its line switch at
MV Bus 2: it is imported with an open phase conductor and its screen
(IMPORT_LINE_SWITCH_OPEN).
The pandapower extra is optional; install with
pip install 'groundinsight[pandapower]' (or
poetry install --extras pandapower).
Skip-reason vocabulary¶
preview_pandapower_import lists every pandapower row it keeps or skips; the
reason column of a skipped row is one of the following. from_pandapower
skips the same rows and announces them as InputWarnings with a code
(IMPORT_BUS_SKIPPED, IMPORT_LINE_SKIPPED, IMPORT_SWITCH_NOT_IMPORTED,
IMPORT_ELEMENT_NOT_IMPORTED; see Warnings and diagnostics).
One reason appears on kept rows: line_switch_open, on an open line switch
and on the row of its line, which is imported with an open phase conductor
(IMPORT_LINE_SWITCH_OPEN).
| Reason | Element | Trigger |
|---|---|---|
voltage_level_mismatch |
bus | vn_kv is not voltage_level_kV: math.isclose(vn_kv, voltage_level_kV, rel_tol=1e-9) is false. |
vn_kv_unparsable |
bus | vn_kv is missing, None or NaN. |
endpoint_off_target_voltage_level |
line, switch | An end sits on another voltage level. |
endpoint_bus_missing |
line, switch | An end bus could not be resolved. |
self_loop |
line, switch | Both ends are the same bus. |
zero_length |
line | length_km is 0. from_pandapower refuses the import with a ValueError: a branch without series impedance would act as an open circuit, not as the short it represents. |
negative_length |
line | length_km is negative; refused like zero_length. |
no_switch_branch_type |
switch | A closed bus-to-bus switch, but no ImportDefaults.switch_branch_type to build it with. |
switch_open |
switch | An open bus-to-bus switch — not a connection. |
line_switch_open |
switch, line (kept) | An open line switch (et="l") of an imported line: the line is imported with an open phase conductor (phase_impedance_formula = "nan"), its screen stays connected at both ends. |
line_switch_closed |
switch | A closed line switch — it changes nothing. |
line_not_imported |
switch | A line switch whose line is not imported. |
switch_not_bus_to_bus |
switch | A switch at a transformer terminal (et="t", "t3"): the switching state of an element that is not modelled. |
trafos_are_not_modelled |
trafo | net.trafo / net.trafo3w. |
impedance_elements_are_not_modelled |
impedance | net.impedance. |
A line without a usable length_km is kept with a length of 1 km and
announced (IMPORT_LENGTH_DEFAULT). An import that produces no bus or no
branch is announced as well (IMPORT_EMPTY), so a wrong voltage_level_kV
fails loudly rather than silently.
Closed switches bond grounding systems¶
Changed after 0.6.0
A closed bus-to-bus switch (et="b", closed=True) bonds two
grounding systems. Up to 0.6.0 it was discarded without a word, so a
bus reachable only through a switch came out galvanically isolated
and the solver reported 0 V for it — which reads as a safe
station. Set ImportDefaults.switch_branch_type (and optionally
switch_length_km, default 1 m) to import such switches as short
branches. Without it the behaviour is unchanged, but the omission is
announced (IMPORT_SWITCH_NOT_IMPORTED) and appears in the preview.
Deriving the phase-conductor impedance¶
ImportDefaults.derive_phase_impedance=True builds a per-line
phase_impedance_formula from the pandapower columns r_ohm_per_km
and x_ohm_per_km, i.e. (r + I*x) * l. That is what the default
phase_current_mode="auto" solve needs; without it every imported
mesh is split with proxy impedances (PHASE_PROXY). Lines that share r
and x share one derived branch type. Two approximations come with it:
the formula is the positive-sequence impedance R₁ + jX₁, while the phase
network wants the reduced impedance Z_red of the phase conductor with the
screen's return — exact only when all parallel routes are of the same
construction —, and the reactance is pandapower's value at its network
frequency, used at every frequency. See
Import from pandapower.
The earth-return formulas (self_impedance_formula,
mutual_impedance_formula) are deliberately not derived. They depend
on the soil resistivity and the cable geometry, neither of which
pandapower carries, and inventing them would produce a network that
solves cleanly and is wrong. They stay exactly as the caller set them
on default_branch_type.
Voltage level¶
voltage_level_kV selects which pandapower buses are imported;
default_bus_type.voltage_level states which level the type was
written for. The two are independent, but a mismatch is announced
(IMPORT_VOLTAGE_LEVEL_MISMATCH), because every imported bus carries the
type's value and that is what an assessment reads. Both comparisons use
math.isclose with a relative tolerance of 1e-9 rather than ==, so
rounding noise from a CSV or DGS export no longer reports the whole target
level as a mismatch.
Short-circuit characteristics (IEC 60909-0)¶
The grounding model is excited by a fault current, and a limit check
needs more than its RMS magnitude: the peak current \(i_p\) and the
thermally equivalent current \(I_{th}\) both depend on the fault-loop
\(R/X\) and the clearing time \(t_k\). Those follow from the phase-side
short-circuit calculation, which pandapower already performs. Rather
than re-implementing IEC 60909 next to it, groundinsight reads the
solved case.
read_shortcircuit_results converts net.res_bus_sc into a tidy,
unit-explicit Polars frame — one row per bus, currents in amperes
(not kA) to match the rest of the package. The fault type, case and
clearing time are taken from net._options, so a solved net is
self-describing and the call usually needs no arguments.
apply_shortcircuit_characteristics then writes the row belonging to
the fault bus onto the model: the loop \(R/X\) and \(\kappa\) go to every
source feeding the fault, together with that source's share of
\(I_k''\); the clearing time \(t_k\) and the AC heat factor \(n\) go to the
Fault, where they belong — they describe the protection, not the
infeed. With set_source_values=True the source injections are
overwritten by those shares as well, which is off by default so a
hand-tuned excitation is never silently replaced. The returned frame
is an audit trail: it carries i_k_previous_a next to i_k_a, so a
review sees exactly what changed.
The example builds a 20 kV feeder in pandapower with the minimum data an
earth-fault calculation (fault="1ph") needs — the short-circuit power
s_sc_max_mva and the ratios rx_max, x0x_max, r0x0_max of the external grid, and the
positive- and zero-sequence data r_ohm_per_km, x_ohm_per_km,
c_nf_per_km, r0_ohm_per_km, x0_ohm_per_km, c0_nf_per_km of the
lines — and solves it with ip=True, ith=True and a clearing time:
net_pp = pp.create_empty_network(f_hz=50.0)
names = ["UW", "S1", "S2", "S3"]
index = {name: pp.create_bus(net_pp, vn_kv=20.0, name=name) for name in names}
pp.create_ext_grid(net_pp, index["UW"],
s_sc_max_mva=300.0, # short-circuit power of the infeed
rx_max=0.1, # R/X, positive sequence
x0x_max=1.0, # X0/X1
r0x0_max=11.0) # R0/X0 -- low-resistance earthing
for i, (a, b) in enumerate(zip(names[:-1], names[1:], strict=True), start=1):
pp.create_line_from_parameters(
net_pp, index[a], index[b], length_km=1.2, name=f"K{i}",
r_ohm_per_km=0.100, x_ohm_per_km=0.110, c_nf_per_km=400.0, max_i_ka=0.5,
r0_ohm_per_km=0.400, x0_ohm_per_km=0.350, c0_nf_per_km=400.0)
sc.calc_sc(net_pp, fault="1ph", case="max", ip=True, ith=True, tk_s=0.5)
Inspect the case first ...
... then write it onto the grounding model and check the conductors:
cable_system = gi.BranchType(
name="3x NA2XS(F)2Y 1x300RM/25 12/20 kV, trefoil",
grounding_conductor=True,
self_impedance_formula=(
"(0.727/3 + pi**2*1e-4*f + j*4*pi*1e-4*f*log(658*sqrt(rho/f)/0.03151272))*l"
),
mutual_impedance_formula=(
"(pi**2*1e-4*f + j*4*pi*1e-4*f*log(658*sqrt(rho/f)/0.03151272))*l"
),
conductor_material="Cu", cross_section_mm2=69.7, # three 25 mm2 screens, see the data-sheet how-to
theta_final_C=gi.final_temperature("Cu", "XLPE"),
)
station = gi.BusType(name="station", system_type="Station", voltage_level=20.0,
impedance_formula="2*rho/(3*1.13*sqrt(100.0))")
defaults = gi.ImportDefaults(rho=100.0, frequencies=[50.0], default_bus_type=station,
default_branch_type=cable_system)
net = gi.from_pandapower(net_pp, defaults=defaults, voltage_level_kV=20.0)
gi.create_source(name="infeed", bus="UW", values={50.0: 1000.0}, network=net)
gi.create_fault(name="F", bus="S2", network=net)
with collecting() as records:
report = gi.apply_shortcircuit_characteristics(net, net_pp, "F", set_source_values=True)
gi.run_fault(net, "F")
limits = gi.check_conductor_limits(net, "F")
The script is pandapower_shortcircuit.py;
its output and a hand check of \(I_k''\), \(R/X\) and \(\kappa\) are in
Import from pandapower.
Two deliberate deviations from pandapower¶
Both are documented in the module docstring of
groundinsight.io.pandapower_sc and are visible in the output, not
hidden:
fault="1ph" — the case relevant for grounding studies — leaves
pandapower's ip_ka and ith_ka entirely NaN; the quantities are
only published for the polyphase faults. read_shortcircuit_results
fills them in from the closed form
\(\kappa = 1.02 + 0.98\,e^{-3R/X}\), evaluated on the earth-fault
loop \(R/X = (2R_1 + R_0)/(2X_1 + X_0)\) rather than on the
positive-sequence ratio \(R_1/X_1\) — the loop the earth-fault current
actually traverses. Where pandapower does publish ip_ka (the
polyphase cases), its topology-aware value is used unchanged. The
kappa_origin column records which of the two applied
("pandapower", "iec_closed_form" or "unavailable"); keep it in
reports, it is the difference between a reproducible study and a magic
number.
I_th is recomputed rather than taken over, because pandapower's
_calc_ith sets the DC heat factor \(m\) to zero for \(\kappa > 1.99\),
where the analytic limit is \(m \to 2\). A vanishing \(m\) makes \(I_{th}\)
too small — the unsafe direction for a limit check — and precisely
in the high-\(\kappa\), DC-dominated cases where the thermal stress is
worst.
Networks as tables¶
gi.network_from_tables(...) builds a network from ten tables — Polars
frames, CSV files or a directory of <table>.csv files — and
Network.to_tables() exports one in exactly that form. The schema is pinned
in groundinsight.io.TABLE_SCHEMAS (column order and dtype); required
columns are in bold, every other column may be absent or empty, which means
the model default (None where the field accepts it).
network:name,description,active_fault— one row.frequencies:frequency_Hz— one row per frequency, in solve order.bus_types:name,description,system_type,voltage_level,impedance_formula,R_formula,L_formula,C_formula,earthing_conductor_material,earthing_conductor_cross_section_mm2,earthing_conductor_theta_initial_C,earthing_conductor_theta_final_C,earthing_conductor_current_split,electrode_material,electrode_cross_section_mm2,electrode_theta_initial_C,electrode_theta_final_C,electrode_current_splitbranch_types:name,description,grounding_conductor,self_impedance_formula,mutual_impedance_formula,phase_impedance_formula,R_self_formula,L_self_formula,C_self_formula,R_mutual_formula,M_mutual_formula,conductor_material,cross_section_mm2,theta_initial_C,theta_final_Cbuses:name,type(abus_typesname),specific_earth_resistance(Ω·m),active,descriptionbranches:name,type(abranch_typesname),from_bus,to_bus,length(km),specific_earth_resistance,parallel_coefficient,active,descriptionsources:name,bus,source_type(currentorvoltage),i_k_a,r_to_x,kappa,descriptionsource_values:source,quantity,frequency_Hz,real,imag— long format, one row per source, quantity and frequency;quantityiscurrentfor a current source andvoltage/impedancefor a Thevenin source; the values are RMS phasors in A, V or Ω.faults:name,bus,t_k_s,n_factor,descriptionfault_scalings:fault,frequency_Hz,scaling— long format; a fault without rows scales every frequency with 1.0.
Only frequencies, bus_types and buses are required. The tables hold
input only: the impedance dictionaries are evaluated from the type
formulas on the way in — through the same Network.add_* path as
create_bus / create_branch, so every formula passes the formula guard —
and results and enumerated paths are not exported. A network whose
impedances follow from its types therefore survives the round trip
unchanged; one whose impedance dictionaries were overwritten by hand keeps
the formula, not the overwritten values.
import groundinsight as gi
from pathlib import Path
folder = Path("ring_tables")
folder.mkdir(exist_ok=True)
for name, frame in net.to_tables().items():
frame.write_csv(folder / f"{name}.csv") # one CSV per table, UTF-8
same = gi.network_from_tables(folder) # or a dict of frames / paths
Malformed tables raise one ValueError that lists every problem with
its table, row (counted from 1, header excluded) and column: missing tables
or columns, unknown columns (a typo such as lenght would otherwise drop
the value silently — pass ignore_extra_columns=True for sheets with
comment columns), cells that are not a number (a decimal comma is named as
such) or a boolean, duplicate names, references to buses, types, sources or
faults that do not exist, and every model validation error. Problems of a
well-formed network — a source that reaches no fault, partial scalings — are
what gi.check_network reports afterwards.
Excel. Polars reads .xlsx through the optional engine fastexcel,
which groundinsight does not depend on. With it installed,
pl.read_excel("network.xlsx", sheet_id=0) returns a dict of sheet name to
frame — one sheet per table — which gi.network_from_tables takes as it
is. Integer columns from a spreadsheet are accepted where floats are
expected.
Walkthrough notebook¶
The end-to-end example for the pandapower importer is shipped as Pandapower import in the Examples section. It shows the full preview → commit flow on a real MV ring net and is the recommended starting point for case-study setups based on existing distribution-network models.
API reference¶
io ¶
External-network importers.
This sub-package converts existing power-system models from third-party
tools (pandapower today, PowerFactory .dgs next) into a
:class:groundinsight.models.core_models.Network. Importers do not
build grounding networks from scratch -- they project an existing
distribution-network topology onto the bus/branch primitives that
groundinsight solves for, and let the user supply the impedance
formulas via :class:ImportDefaults.
Beyond the topology, the sub-package also imports results: a solved pandapower short-circuit case can be read as IEC 60909 characteristic quantities and applied to the sources and faults of an existing groundinsight model, which is what feeds the thermal conductor check.
Public API:
- :class:
ImportDefaults - :func:
groundinsight.io.pandapower_import.from_pandapower - :func:
groundinsight.io.pandapower_import.preview_pandapower_import - :func:
groundinsight.io.pandapower_sc.read_shortcircuit_results - :func:
groundinsight.io.pandapower_sc.apply_shortcircuit_characteristics - :func:
groundinsight.io.tables.network_from_tablesand :func:groundinsight.io.tables.network_to_tables-- networks as Polars tables or CSV files, with the pinned schema :data:groundinsight.io.tables.TABLE_SCHEMAS
The importers themselves live in tool-specific submodules so that the optional third-party dependency is loaded lazily.
TABLE_SCHEMAS
module-attribute
¶
TABLE_SCHEMAS: Dict[str, Dict[str, Any]] = {
"network": {
"name": _TEXT,
"description": _TEXT,
"active_fault": _TEXT,
},
"frequencies": {"frequency_Hz": _FLOAT},
"bus_types": {
"name": _TEXT,
"description": _TEXT,
"system_type": _TEXT,
"voltage_level": _FLOAT,
"impedance_formula": _TEXT,
"R_formula": _TEXT,
"L_formula": _TEXT,
"C_formula": _TEXT,
"earthing_conductor_material": _TEXT,
"earthing_conductor_cross_section_mm2": _FLOAT,
"earthing_conductor_theta_initial_C": _FLOAT,
"earthing_conductor_theta_final_C": _FLOAT,
"earthing_conductor_current_split": _FLOAT,
"electrode_material": _TEXT,
"electrode_cross_section_mm2": _FLOAT,
"electrode_theta_initial_C": _FLOAT,
"electrode_theta_final_C": _FLOAT,
"electrode_current_split": _FLOAT,
},
"branch_types": {
"name": _TEXT,
"description": _TEXT,
"grounding_conductor": _BOOL,
"self_impedance_formula": _TEXT,
"mutual_impedance_formula": _TEXT,
"phase_impedance_formula": _TEXT,
"R_self_formula": _TEXT,
"L_self_formula": _TEXT,
"C_self_formula": _TEXT,
"R_mutual_formula": _TEXT,
"M_mutual_formula": _TEXT,
"conductor_material": _TEXT,
"cross_section_mm2": _FLOAT,
"theta_initial_C": _FLOAT,
"theta_final_C": _FLOAT,
},
"buses": {
"name": _TEXT,
"type": _TEXT,
"specific_earth_resistance": _FLOAT,
"active": _BOOL,
"description": _TEXT,
},
"branches": {
"name": _TEXT,
"type": _TEXT,
"from_bus": _TEXT,
"to_bus": _TEXT,
"length": _FLOAT,
"specific_earth_resistance": _FLOAT,
"parallel_coefficient": _FLOAT,
"active": _BOOL,
"description": _TEXT,
},
"sources": {
"name": _TEXT,
"bus": _TEXT,
"source_type": _TEXT,
"i_k_a": _FLOAT,
"r_to_x": _FLOAT,
"kappa": _FLOAT,
"description": _TEXT,
},
"source_values": {
"source": _TEXT,
"quantity": _TEXT,
"frequency_Hz": _FLOAT,
"real": _FLOAT,
"imag": _FLOAT,
},
"faults": {
"name": _TEXT,
"bus": _TEXT,
"t_k_s": _FLOAT,
"n_factor": _FLOAT,
"description": _TEXT,
},
"fault_scalings": {
"fault": _TEXT,
"frequency_Hz": _FLOAT,
"scaling": _FLOAT,
},
}
Column layout of every table, in output order, with its Polars dtype.
Pinned so that a table written by :func:network_to_tables -- or by hand, or
by a GUI -- has one documented shape: an empty table is an empty frame with
these columns, never a 0x0 frame. Element columns carry the names of the
model fields (specific_earth_resistance, length in km, t_k_s);
frequency columns are frequency_Hz. In source_values the column
quantity is "current" for a current source and "voltage" or
"impedance" for a Thevenin source; real/imag are the RMS phasor
(A, V or Ohm).
ImportDefaults ¶
Bases: BaseModel
Per-import defaults shared by every external-network importer.
Attributes:
| Name | Type | Description |
|---|---|---|
rho |
float
|
Specific earth resistance applied to every imported :class: |
frequencies |
list of float
|
Frequencies at which impedance values are evaluated. Becomes
|
default_bus_type |
BusType
|
Default :class: |
default_branch_type |
BranchType
|
Default :class: |
switch_branch_type |
(BranchType, optional)
|
:class: |
switch_length_km |
float
|
Length assigned to a branch created from a closed switch. A switch
has no length; a small non-zero value is used because a zero-length
branch has no series impedance at all and is rejected by the
importer. Defaults to |
derive_phase_impedance |
bool
|
Derive a per-line |
Examples:
>>> from groundinsight.models.core_models import BusType, BranchType
>>> from groundinsight.io import ImportDefaults
>>> defaults = ImportDefaults(
... rho=100.0,
... frequencies=[50.0],
... default_bus_type=BusType(
... name="ImportedBus",
... system_type="Grounded",
... voltage_level=20.0,
... impedance_formula="rho * 0 + 1.0 + I * f * 0",
... ),
... default_branch_type=BranchType(
... name="ImportedCable",
... grounding_conductor=True,
... self_impedance_formula="(0.25 + I * 0.6) * l",
... mutual_impedance_formula="(0.0 + I * 0.6) * l",
... ),
... )
apply_shortcircuit_characteristics ¶
apply_shortcircuit_characteristics(
network: Network,
sc_results,
fault: str,
*,
pp_bus: Optional[int] = None,
bus_name: Optional[str] = None,
sources: Optional[Sequence[str]] = None,
set_source_values: bool = False,
frequency: Optional[float] = None,
t_k_s: Optional[float] = None,
n_factor: Optional[float] = None,
) -> pl.DataFrame
Write pandapower short-circuit characteristics onto a groundinsight model.
Takes the IEC 60909 quantities computed at the fault bus and
distributes them over the sources that feed that fault: every source
receives the loop's r_to_x and kappa, and a share of I_k''
proportional to its present injection. The clearing time T_k and
the AC heat factor n are written onto the :class:Fault, where
they belong — they describe the protection, not the infeed.
With set_source_values=True the source injections themselves are
overwritten with those shares, turning a pandapower earth-fault result
directly into the excitation of the grounding model. This is off by
default so an existing, hand-tuned excitation is never silently
replaced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The groundinsight network to update, in place. |
required |
sc_results
|
pandapowerNet or DataFrame
|
Either a solved pandapower net (passed through
:func: |
required |
fault
|
str
|
Name of the :class: |
required |
pp_bus
|
int
|
pandapower bus index to read the characteristics from. Defaults to
the row whose |
None
|
bus_name
|
str
|
Alternative to |
None
|
sources
|
sequence of str
|
Restrict the update to these sources. Defaults to every source with a path to the fault, or — if no paths are built — every active source in the network. |
None
|
set_source_values
|
bool
|
If |
False
|
frequency
|
float
|
Frequency at which the shares are computed and, if requested, written. Defaults to the lowest positive network frequency. |
None
|
t_k_s
|
float
|
Overrides the clearing time from |
None
|
n_factor
|
float
|
Overrides the AC heat factor from |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
An audit trail with one row per updated source: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the fault does not exist, if both |
Warns:
| Type | Description |
|---|---|
InputWarning
|
|
Notes
Only the linear quantities are distributed. i_p and I_th are
deliberately not written per source: they are non-linear in the
current and must be evaluated on the aggregate, which is what
:func:~groundinsight.analysis.shortcircuit.resolve_fault_sc_characteristics
does.
Fault.t_k_s and Fault.n_factor describe the protection, and a
short-circuit run only occasionally knows anything about it. They are
therefore updated conservatively: a clearing time is written only if
the calc_sc run genuinely carried one (see
:func:_tk_s_from_options) or t_k_s=... is passed here, and an AC
heat factor only if it differs from the neutral 1.0 or n_factor=...
is passed here. Anything else leaves the value on the fault untouched
instead of resetting it to a pandapower placeholder — a shortened
T_k raises the admissible current by 1/sqrt(t_k) and would make
an undersized conductor pass. Whenever a value is replaced by a
different one, an InputWarning SC_VALUE_REPLACED names both.
Examples:
>>> rep = gi.apply_shortcircuit_characteristics(net_gi, net_pp, "F1")
>>> rep.select("source_name", "i_k_previous_a", "i_k_a", "kappa")
Source code in src/groundinsight/io/pandapower_sc.py
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 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 879 880 | |
from_pandapower ¶
from_pandapower(
net,
*,
defaults: ImportDefaults,
voltage_level_kV: float,
network_name: Optional[str] = None,
include_trafos: bool = False,
) -> Network
Build a :class:~groundinsight.models.core_models.Network from pandapower.
The import is restricted to a single voltage level of the pandapower
net.
The mapping is intentionally narrow:
pp.busrows whosevn_kvmatchesvoltage_level_kVbecome :class:~groundinsight.models.core_models.Businstances usingdefaults.default_bus_type.in_service=Falsepropagates toBus.active=Falseso the outage helpers can reason over them.pp.linerows whose endpoints both lie on the target voltage level become :class:~groundinsight.models.core_models.Branchinstances usingdefaults.default_branch_typewithlength=length_km.in_service=Falsepropagates toBranch.active=False. Withdefaults.derive_phase_impedance=Trueeach line additionally gets aphase_impedance_formuladerived from itsr_ohm_per_km/x_ohm_per_km, which is whatphase_current_mode="auto"needs; the earth-return formulas stay as the caller set them.- Closed bus-to-bus switches become short branches when
defaults.switch_branch_typeis set. Without it they are not imported, and the omission is logged and listed by :func:preview_pandapower_import, because a bus reachable only through a switch otherwise appears galvanically isolated and reports 0 V. - Open line switches (
et == "l") open the phase conductor of their line: it is imported withphase_impedance_formula = "nan"and carries no fault current, while its screen stays connected at both stations, as it does when a line switch opens. A ring operated open at a line switch therefore arrives open. The legacyphase_current_mode="paths"enumerates routes over every active branch and does not see an open phase conductor; the default mode does. Switches at transformer terminals change nothing: transformers are not imported. - ext_grids, sgens, loads etc. are ignored. Trafos, three-winding
trafos and
net.impedanceelements are skipped (and reported);include_trafos=Trueis reserved and raisesNotImplementedError.
No fault, source or path is created — those are left to the caller.
length = length_km holds literally: a length is never rescaled.
A line whose length_km is missing (None / NaN / inf /
unparsable) is imported with a fallback of 1.0 km and an
InputWarning IMPORT_LENGTH_DEFAULT naming the row, because that fallback silently
rescales every impedance of the branch. A line whose length_km is
zero or negative is not importable at all and raises ValueError;
see :func:_reject_unusable_lengths for the reasoning and
:func:preview_pandapower_import for listing the affected rows
beforehand.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
net
|
pandapowerNet
|
A pandapower network object (the type is not imported eagerly to keep pandapower optional). |
required |
defaults
|
ImportDefaults
|
Project-level defaults; see :class: |
required |
voltage_level_kV
|
float
|
Voltage level ( |
required |
network_name
|
str
|
Name for the resulting Network. Defaults to |
None
|
include_trafos
|
bool
|
Reserved for a future release. Setting this to |
False
|
Returns:
| Type | Description |
|---|---|
Network
|
A new groundinsight Network containing the imported buses and
branches, with |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandapower is not installed. |
ValueError
|
If |
NotImplementedError
|
If |
Warns:
| Type | Description |
|---|---|
InputWarning
|
Whatever the import had to decide on the user's behalf, each with the
elements concerned: |
Examples:
>>> import pandapower as pp
>>> from groundinsight.io import ImportDefaults, from_pandapower
>>> net = pp.networks.create_kerber_landnetz_freileitung_1()
>>> network = from_pandapower(
... net,
... defaults=defaults,
... voltage_level_kV=0.4,
... network_name="kerber_lv",
... )
Source code in src/groundinsight/io/pandapower_import.py
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 | |
network_from_tables ¶
network_from_tables(
tables: Optional[
Union[Mapping[str, TableSource], str, PathLike[str]]
] = None,
*,
name: Optional[str] = None,
ignore_extra_columns: bool = False,
**named_tables: TableSource,
) -> Network
Build a network from tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
mapping or str or PathLike
|
Either a mapping of table name to table -- a Polars frame or the path
of a CSV file, as returned by :func: |
None
|
name
|
str
|
Name of the network. Overrides the |
None
|
ignore_extra_columns
|
bool
|
Drop columns that are not part of the schema instead of reporting
them. Defaults to |
False
|
**named_tables
|
TableSource
|
Tables passed by name, e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
Network
|
The network, with every impedance evaluated from its type formulas
(exactly as |
Raises:
| Type | Description |
|---|---|
ValueError
|
One error listing every problem found, each with table, row and column: missing tables or columns, unknown columns or tables, cells that are not a number or boolean, empty or duplicate names, references to buses, types, sources or faults that do not exist, a source value that does not fit the source type, and every model validation error -- including a formula the formula guard rejects. |
Examples:
>>> import polars as pl
>>> import groundinsight as gi
>>> net = gi.network_from_tables(
... name="demo",
... frequencies=pl.DataFrame({"frequency_Hz": [50.0]}),
... bus_types=pl.DataFrame({
... "name": ["rod"], "system_type": ["MV"], "voltage_level": [20.0],
... "impedance_formula": ["0.01*rho"]}),
... buses=pl.DataFrame({"name": ["B1", "B2"], "type": ["rod", "rod"],
... "specific_earth_resistance": [100.0, 400.0]}),
... )
>>> net.buses["B2"].impedance[50.0]
ComplexNumber(real=4.0, imag=0.0)
Source code in src/groundinsight/io/tables.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
network_to_tables ¶
Export a network as the tables :func:network_from_tables reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The network to export. |
required |
Returns:
| Type | Description |
|---|---|
dict of str to polars.DataFrame
|
One frame per table of :data: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If two different bus types, or two different branch types, share a name. |
Notes
Only input data is exported -- see the module docstring. The impedance dictionaries are left out because they are evaluated from the type formulas on the way back in; results and enumerated paths are left out because they are derived from everything else.
Examples:
>>> import groundinsight as gi
>>> net = gi.create_network(name="demo", frequencies=[50.0, 250.0])
>>> tables = gi.network_from_tables(net.to_tables(), name="copy").to_tables()
>>> tables["frequencies"]["frequency_Hz"].to_list()
[50.0, 250.0]
Source code in src/groundinsight/io/tables.py
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 | |
preview_pandapower_import ¶
preview_pandapower_import(
net,
*,
voltage_level_kV: float,
include_trafos: bool = False,
defaults: Optional[ImportDefaults] = None,
) -> pl.DataFrame
Describe what :func:from_pandapower would import, without importing.
The Polars DataFrame describes the import of this net at this voltage
level; no Network is built.
The frame has the following columns:
kind--"bus","line","switch","trafo"or"impedance". The last two are alwaysstatus="skip"; a"switch"row is"keep"for a closed bus-to-bus switch when adefaultswith aswitch_branch_typeis passed, and for an open line switch of an imported line.status--"keep"or"skip".pp_index-- The pandapower index of the row.name-- Resolved groundinsight name (with fallback).vn_kv-- Bus voltage level (Nonefor lines).from_bus-- Resolved from-bus name (lines only).to_bus-- Resolved to-bus name (lines only).length_km-- Line length in km (lines only). For a kept line this is the length :func:from_pandapowerwould assign, so preview and commit never disagree — including the_MISSING_LENGTH_FALLBACK_KMsubstitution (with the same warning) when pandapower carries no usable number. For a skipped line it is the raw parsed value,Nonewhen unusable.in_service-- Boolean flag from pandapower (best effort).reason-- Skip reason ifstatus == "skip",Noneotherwise -- except"line_switch_open"on the kept row of an open line switch and on the row of its line, which is imported with an open phase conductor.
The dtypes are pinned by _PREVIEW_SCHEMA rather than inferred, so
the frame is identical in shape for a two-bus net and for a
thousand-bus one, and an all-None column keeps a usable dtype.
Use this before committing to a full import to validate the mapping
or diagnose unexpectedly skipped elements. Unlike
:func:from_pandapower, this function never raises on bad data: a
line whose length_km is zero or negative — which aborts the
commit — is reported here as status="skip" with
reason="zero_length" / "negative_length", so every affected
row can be enumerated in one go before the import is attempted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
net
|
pandapowerNet
|
The pandapower network to inspect. |
required |
voltage_level_kV
|
float
|
Voltage level to keep ( |
required |
include_trafos
|
bool
|
Mirrors the parameter of :func: |
False
|
defaults
|
ImportDefaults
|
The same defaults that will be passed to :func: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bus and one per line, with the dtypes of
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
Examples:
>>> import polars as pl
>>> import pandapower.networks as pn
>>> import groundinsight as gi
>>> frame = gi.preview_pandapower_import(
... pn.example_simple(), voltage_level_kV=20.0)
>>> frame.filter(pl.col("status") == "skip")
Source code in src/groundinsight/io/pandapower_import.py
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 | |
read_shortcircuit_results ¶
read_shortcircuit_results(
net,
*,
t_k_s: Optional[float] = None,
n_factor: float = 1.0,
frequency: float = 50.0,
buses: Optional[Sequence[int]] = None,
) -> pl.DataFrame
Read a solved pandapower short-circuit case as IEC 60909 quantities.
Converts net.res_bus_sc into a tidy, unit-explicit
:class:polars.DataFrame in which the quantities missing from
pandapower's single line-to-earth path (kappa, i_p, I_th)
are filled in, and I_th is recomputed with a DC heat factor that is
correct in the kappa -> 2 limit. See the module docstring for the
reasoning.
The fault type, case and clearing time are taken from net._options
(written by calc_sc) so that a solved net is self-describing; the
t_k_s and n_factor arguments override them. The clearing time
is adopted only when the calc_sc run genuinely carried one --
pandapower stores its signature default tk_s=1.0 even for a run
that asked for no thermal current at all, and passing that placeholder
off as a protection setting is unsafe; see :func:_tk_s_from_options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
net
|
pandapowerNet
|
A pandapower network on which |
required |
t_k_s
|
float
|
Short-circuit duration |
None
|
n_factor
|
float
|
IEC 60909-0 AC heat factor |
1.0
|
frequency
|
float
|
System frequency in Hz used in the |
50.0
|
buses
|
sequence of int
|
Restrict the output to these pandapower bus indices. Defaults to
every bus in |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bus with the columns |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandapower is not installed. |
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
InputWarning
|
|
Notes
kappa_origin documents where each peak factor came from:
"pandapower" (recovered from ip_ka, topology-aware),
"iec_closed_form" (1.02 + 0.98*exp(-3*R/X)) or
"unavailable". Keep it in reports — it is the difference between a
reproducible study and a magic number.
Examples:
>>> import pandapower.shortcircuit as sc
>>> sc.calc_sc(net, fault="1ph", case="max", tk_s=0.5)
>>> gi.read_shortcircuit_results(net).select("bus_name", "i_k_a", "kappa")
Source code in src/groundinsight/io/pandapower_sc.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
Project files (JSON)¶
gi.save_network_to_json(network, path) writes one network to a project
file, and gi.load_network_from_json(path) reads it back. The file is the
network's own model_dump_json(indent=4) with two header keys in front:
{
"schema_version": 1,
"groundinsight_version": "2026.11.0",
"name": "Umspannwerk Süd",
"description": null,
"frequencies": [50.0, 250.0],
...
}
- UTF-8 on every platform. Names such as
"Umspannwerk Süd Ω"are stored as UTF-8 regardless of the locale; up to 0.6.0 the locale decided, which on Windows (cp1252) meant aUnicodeEncodeErrorforΩ/ρand mojibake for a file written on macOS. A UTF-8 byte-order mark is accepted on reading. A file that is not UTF-8 can only come from 0.6.0 or earlier on a non-UTF-8 system; it is read with the platform's preferred encoding, as 0.6.0 did, and anInputWarningwith the codePROJECT_FILE_LEGACY_ENCODINGsays so. Saving it again writes UTF-8. - Atomic. The network is serialised completely, written to a temporary
file in the target directory, flushed and
fsync-ed, and only then moved over the target withos.replace. A failure at any point leaves an existing project file byte-identical. The replaced file keeps its permission bits, a read-only file is refused, and a symbolic link keeps pointing at the saved file. - Versioned.
schema_versionis the version of the file layout,groundinsight_versionthe release that wrote it (see the table below).
schema_version |
Written by | Content |
|---|---|---|
| (absent) | 0.6.0 and earlier | the model dump only — read unchanged |
1 |
the first release after 0.6.0 and later | the two header keys plus the model dump |
A file with a newer schema_version than the running release supports is
refused with a ValueError that names both versions, instead of being read
with whatever the newer release added silently dropped. The version is
incremented whenever a release writes something an earlier release would
ignore or misread.
The header keys sit next to the model fields rather than in an envelope on
purpose: Network ignores unknown keys, so
gi.Network.model_validate_json(text) still reads a project file — and a
0.6.0 installation still opens a file written by a newer release of the same
schema. load_network_from_json removes the two keys before validation and
therefore does not depend on that. The names schema_version and
groundinsight_version are reserved; Network never gets fields of that
name.
project_file ¶
The JSON project file: one network per file, UTF-8, written atomically.
A project file is what :func:save_network_to_json writes and
:func:load_network_from_json reads -- the network's own
model_dump_json(indent=4) with two header keys in front::
{
"schema_version": 1,
"groundinsight_version": "2026.11.0",
"name": "...",
...
}
Three properties are guaranteed, because a desktop application and a server open and save these files on every platform:
Encoding
The file is UTF-8 on every platform. Without an explicit encoding the
locale decides: on Windows (cp1252) a name containing Ω or ρ
raises UnicodeEncodeError on save, and a file with "Süd" written
on macOS comes back as mojibake. Reading
accepts a UTF-8 byte-order mark, which Windows editors add when a file is
edited by hand. A file that is not UTF-8 can only have been written by
0.6.0 or earlier with a non-UTF-8 locale; it is decoded with the
platform's preferred encoding -- exactly what 0.6.0 did on that machine --
and an :class:~groundinsight.InputWarning with the code
PROJECT_FILE_LEGACY_ENCODING says so. Saving it again writes UTF-8.
Atomicity
The network is serialised completely before anything touches the disk,
then written to a temporary file in the target directory, flushed and
fsync-ed, and moved over the target with :func:os.replace. A failure
at any point -- an exception in the serialiser, a full disk, a crash --
leaves an existing file byte-identical and removes the temporary file.
The 0.6.0 writer truncated the target first, so the same failures left an
empty or half-written project. The replaced file keeps the permission
bits of the old one (a new file gets the usual 0o666 & ~umask), a
read-only target is refused like open("w") refuses it, and a
symbolic link is followed so the link keeps pointing at the saved file.
Schema version
schema_version (an int) is the version of the file layout;
groundinsight_version (a str) names the release that wrote it.
A reader refuses a schema_version newer than :data:SCHEMA_VERSION
with a :class:ValueError that names both numbers, instead of silently
dropping whatever the newer release added. Files without the keys --
plain model_dump_json dumps, the format of groundinsight 0.6.0 and
earlier -- load as a network without metadata.
When to increment :data:SCHEMA_VERSION
Whenever a release writes something an earlier release would ignore or misread -- a new field that changes a result, a changed meaning of an existing one, a different shape of a stored value. The older release then refuses the file instead of computing with a silently reduced model. A change that older releases read correctly (a new optional field they may safely ignore) does not need a new version.
The validation itself is the model's: after the metadata check the parsed
object goes through Network.model_validate, the same validators and
formula guard as every other way of building a network. (Validating the
parsed dictionary gives the same model as Network.model_validate_json on
the text -- the tests compare both on every value shape that serialises
specially -- and is faster, because the file is parsed once.)
METADATA_KEYS
module-attribute
¶
The top-level keys of a project file that are file metadata, not fields of
:class:~groundinsight.Network, in the order they are written.
SCHEMA_VERSION
module-attribute
¶
Version of the project-file layout this release writes, and the newest one it reads. See the module docstring for when it is incremented.
load_network_from_json ¶
Load a network from a JSON project file.
Reads files of every release: files with the current or an older
schema_version, and files without one (written by 0.6.0 or earlier).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or PathLike
|
The project file. |
required |
Returns:
| Type | Description |
|---|---|
Network
|
The validated network, including any stored results. |
Raises:
| Type | Description |
|---|---|
OSError
|
If the file cannot be read. |
ValueError
|
If the file is not valid JSON, is not a JSON object, is neither UTF-8
nor in the platform's preferred encoding, carries an invalid or a
newer |
Warns:
| Type | Description |
|---|---|
InputWarning
|
Code |
Examples:
Source code in src/groundinsight/io/project_file.py
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 | |
save_network_to_json ¶
Save a network to a JSON project file, atomically and as UTF-8.
The file is the network's model_dump_json(indent=4) preceded by the
header keys schema_version (:data:SCHEMA_VERSION) and
groundinsight_version. Stored results are included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The network to save. |
required |
path
|
str or PathLike
|
Target file. An existing file is replaced as a whole or not at all;
if |
required |
Raises:
| Type | Description |
|---|---|
OSError
|
If the file cannot be written (directory missing, disk full, read-only target, ...). An existing file is then left byte-identical and no temporary file remains. |
Exception
|
Whatever the serialiser raises; the disk is not touched in that case. |
Notes
The new content is written to a temporary file next to the target,
flushed and fsync-ed, and then moved over the target with
:func:os.replace, which is atomic on POSIX and Windows. The directory
entry is fsync-ed afterwards where the platform supports it.
Examples:
>>> import groundinsight as gi
>>> net = gi.create_network(name="Süd", frequencies=[50.0])
>>> gi.save_network_to_json(net, "sued.json")
>>> gi.load_network_from_json("sued.json").name
'Süd'