Skip to content

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 ...

sc_results = gi.read_shortcircuit_results(net_pp)  # amperes, one row per bus

... 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_split
  • branch_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_C
  • buses: name, type (a bus_types name), specific_earth_resistance (Ω·m), active, description
  • branches: name, type (a branch_types name), from_bus, to_bus, length (km), specific_earth_resistance, parallel_coefficient, active, description
  • sources: name, bus, source_type (current or voltage), i_k_a, r_to_x, kappa, description
  • source_values: source, quantity, frequency_Hz, real, imag — long format, one row per source, quantity and frequency; quantity is current for a current source and voltage / impedance for a Thevenin source; the values are RMS phasors in A, V or Ω.
  • faults: name, bus, t_k_s, n_factor, description
  • fault_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_tables and :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:Bus and :class:Branch (Ohm * m). Source tools do not encode soil parameters, so a single project-wide value is taken from the user.

frequencies list of float

Frequencies at which impedance values are evaluated. Becomes Network.frequencies; bus and branch impedance dicts are sized accordingly.

default_bus_type BusType

Default :class:BusType assigned to every imported bus on the selected voltage level.

default_branch_type BranchType

Default :class:BranchType assigned to every imported line / cable on the selected voltage level.

switch_branch_type (BranchType, optional)

:class:BranchType used for a closed bus-bus switch. A closed switch bonds two grounding systems; dropping it makes the bus behind it look galvanically isolated and report 0 V, which is the one answer a grounding study must never produce by accident. With None (the default) the switch is not imported, and the importer says so and lists it in :func:~groundinsight.io.preview_pandapower_import as a skipped "switch" row.

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 0.001 km (1 m), which is negligible against any real cable section.

derive_phase_impedance bool

Derive a per-line phase_impedance_formula from the pandapower columns r_ohm_per_km / x_ohm_per_km. The phase-conductor network is what phase_current_mode="auto" solves; without a formula every imported mesh falls back to the path-based proxy. The earth-return (shield) formulas cannot be derived this way -- they depend on the soil and the cable geometry, neither of which pandapower carries -- so they stay at default_branch_type. Defaults to False, which reproduces the previous behaviour.

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:read_shortcircuit_results) or a frame previously returned by it.

required
fault str

Name of the :class:Fault in network the results belong to. The former keyword fault_name is accepted as a deprecated alias.

required
pp_bus int

pandapower bus index to read the characteristics from. Defaults to the row whose bus_name equals the fault's bus, which is the natural match for a network built by :func:~groundinsight.io.from_pandapower.

None
bus_name str

Alternative to pp_bus: select the row by name. Mutually exclusive with pp_bus.

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 True, also overwrite Source.values at frequency with each source's share of I_k''.

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 sc_results, and is the way to set one when the short-circuit run carries none.

None
n_factor float

Overrides the AC heat factor from sc_results, and is the way to set one at all — n is not a pandapower quantity.

None

Returns:

Type Description
DataFrame

An audit trail with one row per updated source: fault_name, source_name, bus, frequency, i_k_total_a, share, i_k_previous_a, i_k_a, r_to_x, kappa, kappa_origin, t_k_s, n_factor and values_updated. i_k_previous_a is the magnitude the source injected before the call, so a review can see exactly what changed. t_k_s and n_factor report the values in effect on the fault after the call, which for an untouched quantity is the one that was already there.

Raises:

Type Description
ValueError

If the fault does not exist, if both pp_bus and bus_name are given, if no matching row is found in sc_results, or if no source is eligible for the update.

Warns:

Type Description
InputWarning

SC_ROW_AMBIGUOUS (several short-circuit rows match; the first one is used), SC_SPLIT_EQUAL (the sources inject nothing at the frequency, so I_k'' is split equally), SC_VOLTAGE_SOURCE_SKIPPED (a voltage source keeps its values) and SC_VALUE_REPLACED (a different t_k_s or n_factor on the fault was replaced).

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
@renamed_parameters(fault_name="fault")
def 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
    ----------
    network : Network
        The groundinsight network to update, in place.
    sc_results : pandapower.auxiliary.pandapowerNet or polars.DataFrame
        Either a solved pandapower net (passed through
        :func:`read_shortcircuit_results`) or a frame previously returned
        by it.
    fault : str
        Name of the :class:`Fault` in ``network`` the results belong to.
        The former keyword ``fault_name`` is accepted as a deprecated
        alias.
    pp_bus : int, optional
        pandapower bus index to read the characteristics from. Defaults to
        the row whose ``bus_name`` equals the fault's bus, which is the
        natural match for a network built by
        :func:`~groundinsight.io.from_pandapower`.
    bus_name : str, optional
        Alternative to ``pp_bus``: select the row by name. Mutually
        exclusive with ``pp_bus``.
    sources : sequence of str, optional
        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.
    set_source_values : bool, default False
        If ``True``, also overwrite ``Source.values`` at ``frequency``
        with each source's share of ``I_k''``.
    frequency : float, optional
        Frequency at which the shares are computed and, if requested,
        written. Defaults to the lowest positive network frequency.
    t_k_s : float, optional
        Overrides the clearing time from ``sc_results``, and is the way to
        set one when the short-circuit run carries none.
    n_factor : float, optional
        Overrides the AC heat factor from ``sc_results``, and is the way
        to set one at all — ``n`` is not a pandapower quantity.

    Returns
    -------
    polars.DataFrame
        An audit trail with one row per updated source: ``fault_name``,
        ``source_name``, ``bus``, ``frequency``, ``i_k_total_a``,
        ``share``, ``i_k_previous_a``, ``i_k_a``, ``r_to_x``, ``kappa``,
        ``kappa_origin``, ``t_k_s``, ``n_factor`` and ``values_updated``.
        ``i_k_previous_a`` is the magnitude the source injected *before*
        the call, so a review can see exactly what changed. ``t_k_s`` and
        ``n_factor`` report the values *in effect on the fault after* the
        call, which for an untouched quantity is the one that was already
        there.

    Raises
    ------
    ValueError
        If the fault does not exist, if both ``pp_bus`` and ``bus_name``
        are given, if no matching row is found in ``sc_results``, or if
        no source is eligible for the update.

    Warns
    -----
    InputWarning
        ``SC_ROW_AMBIGUOUS`` (several short-circuit rows match; the first one
        is used), ``SC_SPLIT_EQUAL`` (the sources inject nothing at the
        frequency, so ``I_k''`` is split equally), ``SC_VOLTAGE_SOURCE_SKIPPED``
        (a voltage source keeps its values) and ``SC_VALUE_REPLACED`` (a
        different ``t_k_s`` or ``n_factor`` on the fault was replaced).

    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")  # doctest: +SKIP
    >>> rep.select("source_name", "i_k_previous_a", "i_k_a", "kappa")  # doctest: +SKIP
    """
    if pp_bus is not None and bus_name is not None:
        raise ValueError("Provide at most one of 'pp_bus' or 'bus_name'.")

    fault_obj = network.faults.get(fault)
    if fault_obj is None:
        raise ValueError(
            f"Fault {fault!r} is not in network {network.name!r}. "
            f"Available: {sorted(network.faults)}."
        )

    frame = (
        sc_results
        if isinstance(sc_results, pl.DataFrame)
        else read_shortcircuit_results(sc_results)
    )
    if frame.height == 0:
        raise ValueError("The short-circuit result frame is empty.")

    # --- pick the row describing the fault location --------------------
    target = bus_name if bus_name is not None else fault_obj.bus
    if pp_bus is not None:
        matches = frame.filter(pl.col("pp_bus_index") == int(pp_bus))
        selector = f"pp_bus={pp_bus}"
    else:
        matches = frame.filter(pl.col("bus_name") == target)
        selector = f"bus_name={target!r}"
    if matches.height == 0:
        raise ValueError(
            f"No short-circuit result for {selector}. Available buses: "
            f"{frame['bus_name'].to_list()}. Pass pp_bus=... or bus_name=... "
            "if the groundinsight bus names differ from the pandapower ones."
        )
    if matches.height > 1:
        emit(
            InputWarning,
            f"{matches.height} short-circuit rows match {selector}; using the "
            f"first one.",
            code="SC_ROW_AMBIGUOUS",
            elements=[("fault", fault), ("bus", target)],
            stacklevel=2,
        )
    row = matches.to_dicts()[0]

    i_k_total = row.get("i_k_a")
    if i_k_total is None:
        raise ValueError(
            f"The short-circuit result for {selector} has no I_k''; nothing to apply."
        )
    kappa = row.get("kappa")
    r_to_x = row.get("r_to_x")
    kappa_origin = row.get("kappa_origin")

    # --- the protection-side quantities belong to the fault ------------
    # An explicit argument always wins. Otherwise the frame is only
    # believed where it can actually have learnt something: a ``t_k_s``
    # that survived _tk_s_from_options, and an ``n_factor`` that is not the
    # neutral default (pandapower does not model ``n``, so a 1.0 in the
    # frame is the argument default of read_shortcircuit_results and says
    # nothing about this fault).
    t_k = float(t_k_s) if t_k_s is not None else row.get("t_k_s")
    if n_factor is not None:
        n_val = float(n_factor)
    else:
        frame_n = row.get("n_factor")
        n_val = (
            frame_n
            if frame_n is not None and frame_n != _NEUTRAL_N_FACTOR
            else None
        )
    _adopt_fault_value(fault_obj, "t_k_s", t_k, fault)
    _adopt_fault_value(fault_obj, "n_factor", n_val, fault)
    # Report what is in effect afterwards, not what was offered.
    effective_t_k = fault_obj.t_k_s
    effective_n = fault_obj.n_factor

    if frequency is None:
        frequency = next((float(x) for x in network.frequencies if x > 0), 50.0)
    frequency = float(frequency)

    # --- pick the sources to update ------------------------------------
    if sources is not None:
        names = list(sources)
        unknown = [s for s in names if s not in network.sources]
        if unknown:
            raise ValueError(
                f"Unknown source(s) {unknown} in network {network.name!r}."
            )
    else:
        names = sources_feeding(network, fault)
    if not names:
        raise ValueError(
            f"No sources are eligible for fault {fault!r}. Build the paths "
            "(run_fault / build_paths) or pass sources=[...] explicitly."
        )

    # --- distribute I_k'' proportionally to the present injection ------
    previous: Dict[str, float] = {}
    for name in names:
        src = network.sources[name]
        values = src.values or {}
        entry = values.get(frequency)
        if entry is None:
            previous[name] = 0.0
        else:
            previous[name] = abs(complex(entry.real, entry.imag))

    total_previous = sum(previous.values())
    if total_previous > 0:
        shares = {name: previous[name] / total_previous for name in names}
    else:
        shares = {name: 1.0 / len(names) for name in names}
        if len(names) > 1:
            emit(
                InputWarning,
                f"Sources {names} inject nothing at f={frequency:.4g} Hz; "
                f"splitting I_k'' equally. Set the relative infeed shares first "
                f"if the split is not uniform.",
                code="SC_SPLIT_EQUAL",
                elements=[("source", name) for name in names] + [("fault", fault)],
                stacklevel=2,
            )

    rows: List[Dict[str, Any]] = []
    for name in names:
        src = network.sources[name]
        share = shares[name]
        i_k_share = i_k_total * share

        src.i_k_a = i_k_share if i_k_share > 0 else None
        src.r_to_x = r_to_x
        src.kappa = kappa

        updated = False
        if set_source_values and src.source_type == "current":
            values = dict(src.values or {})
            values[frequency] = ComplexNumber(real=i_k_share, imag=0.0)
            src.values = values
            updated = True
        elif set_source_values:
            emit(
                InputWarning,
                f"Source '{name}' is a voltage source; its injection was not "
                f"overwritten (set_source_values only applies to current "
                f"sources).",
                code="SC_VOLTAGE_SOURCE_SKIPPED",
                elements=[("source", name)],
                stacklevel=2,
            )

        rows.append(
            {
                "fault_name": fault,
                "source_name": name,
                "bus": src.bus,
                "frequency": frequency,
                "i_k_total_a": i_k_total,
                "share": share,
                "i_k_previous_a": previous[name],
                "i_k_a": i_k_share,
                "r_to_x": r_to_x,
                "kappa": kappa,
                "kappa_origin": kappa_origin,
                "t_k_s": effective_t_k,
                "n_factor": effective_n,
                "values_updated": updated,
            }
        )

    logger.info(
        "Applied IEC 60909 characteristics of bus '%s' to fault '%s': "
        "I_k''=%.1f A, kappa=%s (%s), T_k=%s s over %d source(s).",
        row.get("bus_name"), fault, i_k_total,
        "n/a" if kappa is None else f"{kappa:.4f}", kappa_origin,
        effective_t_k, len(names),
    )

    return pl.DataFrame(rows, schema=_REPORT_SCHEMA)

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.bus rows whose vn_kv matches voltage_level_kV become :class:~groundinsight.models.core_models.Bus instances using defaults.default_bus_type. in_service=False propagates to Bus.active=False so the outage helpers can reason over them.
  • pp.line rows whose endpoints both lie on the target voltage level become :class:~groundinsight.models.core_models.Branch instances using defaults.default_branch_type with length=length_km. in_service=False propagates to Branch.active=False. With defaults.derive_phase_impedance=True each line additionally gets a phase_impedance_formula derived from its r_ohm_per_km / x_ohm_per_km, which is what phase_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_type is 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 with phase_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 legacy phase_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.impedance elements are skipped (and reported); include_trafos=True is reserved and raises NotImplementedError.

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:ImportDefaults.

required
voltage_level_kV float

Voltage level (vn_kv) of the buses to keep. Lines that bridge to a different level are skipped.

required
network_name str

Name for the resulting Network. Defaults to net.name if set, otherwise "pandapower_import".

None
include_trafos bool

Reserved for a future release. Setting this to True raises :class:NotImplementedError.

False

Returns:

Type Description
Network

A new groundinsight Network containing the imported buses and branches, with frequencies = defaults.frequencies.

Raises:

Type Description
ImportError

If pandapower is not installed.

ValueError

If defaults.frequencies is empty, or if a line that would be imported carries a zero or negative length_km.

NotImplementedError

If include_trafos=True.

Warns:

Type Description
InputWarning

Whatever the import had to decide on the user's behalf, each with the elements concerned: IMPORT_LENGTH_DEFAULT (a line without usable length got the fallback length), IMPORT_BUS_SKIPPED (a bus with an unparsable vn_kv), IMPORT_LINE_SKIPPED (a self-loop, or a line whose length cannot be imported), IMPORT_SWITCH_NOT_IMPORTED (closed bus-to-bus switches without switch_branch_type), IMPORT_LINE_SWITCH_OPEN (severity info: a line imported with an open phase conductor because of an open line switch; elements: the branch and the switches), IMPORT_ELEMENT_NOT_IMPORTED (transformers and impedance elements), IMPORT_VOLTAGE_LEVEL_MISMATCH (the default bus type declares another voltage level) and IMPORT_EMPTY (no bus or no branch was imported). A GUI collects them with :func:groundinsight.diagnostics.collecting.

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
def 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.bus`` rows whose ``vn_kv`` matches ``voltage_level_kV`` become
      :class:`~groundinsight.models.core_models.Bus` instances using
      ``defaults.default_bus_type``. ``in_service=False`` propagates to
      ``Bus.active=False`` so the outage helpers can reason over them.
    - ``pp.line`` rows whose endpoints both lie on the target voltage
      level become :class:`~groundinsight.models.core_models.Branch`
      instances using ``defaults.default_branch_type`` with
      ``length=length_km``. ``in_service=False`` propagates to
      ``Branch.active=False``. With
      ``defaults.derive_phase_impedance=True`` each line additionally gets
      a ``phase_impedance_formula`` derived from its ``r_ohm_per_km`` /
      ``x_ohm_per_km``, which is what ``phase_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_type`` is 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 with ``phase_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 legacy
      ``phase_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.impedance`` elements are skipped (and reported);
      ``include_trafos=True`` is reserved and raises
      ``NotImplementedError``.

    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
    ----------
    net : pandapowerNet
        A pandapower network object (the type is not imported eagerly to
        keep pandapower optional).
    defaults : ImportDefaults
        Project-level defaults; see :class:`ImportDefaults`.
    voltage_level_kV : float
        Voltage level (``vn_kv``) of the buses to keep. Lines that bridge
        to a different level are skipped.
    network_name : str, optional
        Name for the resulting Network. Defaults to ``net.name`` if set,
        otherwise ``"pandapower_import"``.
    include_trafos : bool, optional
        Reserved for a future release. Setting this to ``True`` raises
        :class:`NotImplementedError`.

    Returns
    -------
    Network
        A new groundinsight Network containing the imported buses and
        branches, with ``frequencies = defaults.frequencies``.

    Raises
    ------
    ImportError
        If pandapower is not installed.
    ValueError
        If ``defaults.frequencies`` is empty, or if a line that would be
        imported carries a zero or negative ``length_km``.
    NotImplementedError
        If ``include_trafos=True``.

    Warns
    -----
    InputWarning
        Whatever the import had to decide on the user's behalf, each with the
        elements concerned: ``IMPORT_LENGTH_DEFAULT`` (a line without usable
        length got the fallback length), ``IMPORT_BUS_SKIPPED`` (a bus with
        an unparsable ``vn_kv``), ``IMPORT_LINE_SKIPPED`` (a self-loop, or a
        line whose length cannot be imported), ``IMPORT_SWITCH_NOT_IMPORTED``
        (closed bus-to-bus switches without ``switch_branch_type``),
        ``IMPORT_LINE_SWITCH_OPEN`` (severity ``info``: a line imported with an
        open phase conductor because of an open line switch; elements: the
        branch and the switches),
        ``IMPORT_ELEMENT_NOT_IMPORTED`` (transformers and impedance
        elements), ``IMPORT_VOLTAGE_LEVEL_MISMATCH`` (the default bus type
        declares another voltage level) and ``IMPORT_EMPTY`` (no bus or no
        branch was imported). A GUI collects them with
        :func:`groundinsight.diagnostics.collecting`.

    Examples
    --------
    >>> import pandapower as pp                                      # doctest: +SKIP
    >>> from groundinsight.io import ImportDefaults, from_pandapower  # doctest: +SKIP
    >>> net = pp.networks.create_kerber_landnetz_freileitung_1()      # doctest: +SKIP
    >>> network = from_pandapower(                                    # doctest: +SKIP
    ...     net,
    ...     defaults=defaults,
    ...     voltage_level_kV=0.4,
    ...     network_name="kerber_lv",
    ... )
    """
    require_pandapower()

    if include_trafos:
        raise NotImplementedError(
            "include_trafos=True is reserved for a future release; trafos "
            "are not imported yet."
        )
    if not defaults.frequencies:
        raise ValueError("ImportDefaults.frequencies must not be empty.")

    _check_voltage_level_consistency(defaults, voltage_level_kV)

    name = network_name or getattr(net, "name", None) or "pandapower_import"
    network = Network(name=str(name), frequencies=list(defaults.frequencies))

    bus_name_by_index = bus_index_to_name(net)
    line_name_by_index = _line_index_to_name(net)
    kept_bus_indices, _ = _classify_buses(net, voltage_level_kV)
    kept_bus_set = set(kept_bus_indices)

    # Buses
    for idx in kept_bus_indices:
        row = net.bus.loc[idx]
        bus = Bus(
            name=bus_name_by_index[idx],
            description=str(row.get("name") or "") or None,
            type=defaults.default_bus_type,
            impedance={},
            specific_earth_resistance=float(defaults.rho),
            active=_bus_in_service(row),
        )
        network.add_bus(bus)

    # Branches
    kept_lines, skipped_lines = _classify_lines(
        net, kept_bus_set, bus_name_by_index, line_name_by_index
    )
    _reject_unusable_lengths(skipped_lines)
    open_switches, _, _ = _classify_line_switches(
        net, set(kept_lines), bus_name_by_index
    )
    phase_open_type = _phase_open_type(defaults) if open_switches else None
    derived_types: Dict[str, Any] = {}
    for idx in kept_lines:
        row = net.line.loc[idx]
        from_idx = int(row["from_bus"])
        to_idx = int(row["to_bus"])
        if int(idx) in open_switches:
            branch_type = phase_open_type
        else:
            branch_type = _branch_type_for_line(defaults, row, derived_types)
        branch = Branch(
            name=line_name_by_index[int(idx)],
            description=str(row.get("name") or "") or None,
            type=branch_type,
            length=_length_km(
                row, name=line_name_by_index[int(idx)], pp_index=int(idx)
            ),
            from_bus=bus_name_by_index[from_idx],
            to_bus=bus_name_by_index[to_idx],
            self_impedance={},
            mutual_impedance={},
            specific_earth_resistance=float(defaults.rho),
            active=_bus_in_service(row),
        )
        network.add_branch(branch)
    _warn_about_open_line_switches(open_switches, line_name_by_index)

    # Closed bus-to-bus switches: a bond, not a line -- see _classify_switches.
    kept_switches, skipped_switches = _classify_switches(
        net, kept_bus_set, bus_name_by_index, defaults
    )
    for record in kept_switches:
        network.add_branch(
            Branch(
                name=record["name"],
                description="closed bus-to-bus switch",
                type=defaults.switch_branch_type,
                length=float(defaults.switch_length_km),
                from_bus=record["from_bus"],
                to_bus=record["to_bus"],
                self_impedance={},
                mutual_impedance={},
                specific_earth_resistance=float(defaults.rho),
                active=True,
            )
        )
    _warn_about_unimported(skipped_switches, _unmodelled_elements(net))

    if derived_types:
        logger.info(
            "Derived %d phase-impedance branch type(s) from r_ohm_per_km / "
            "x_ohm_per_km; the earth-return formulas stay at '%s'.",
            len(derived_types),
            defaults.default_branch_type.name,
        )

    if not network.buses or not network.branches:
        # Promote the zero-bus / zero-branch case to a warning so the
        # user notices that the import produced an unusable result
        # (typically because of a wrong ``voltage_level_kV`` argument).
        emit(
            InputWarning,
            f"Imported pandapower net into '{network.name}': "
            f"{len(network.buses)} buses, {len(network.branches)} branches at "
            f"{float(voltage_level_kV):.3f} kV — result is empty or "
            f"branch-less; verify the voltage_level_kV argument.",
            code="IMPORT_EMPTY",
            elements=[("network", network.name)],
            stacklevel=2,
        )
    else:
        logger.info(
            "Imported pandapower net into '%s': %d buses, %d branches at %.3f kV.",
            network.name,
            len(network.buses),
            len(network.branches),
            float(voltage_level_kV),
        )
    return network

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:network_to_tables or by pl.read_excel(path, sheet_id=0) -- or the path of a directory holding <table>.csv files. The table names and their columns are listed in :data:TABLE_SCHEMAS; frequencies, bus_types and buses are required, the others optional.

None
name str

Name of the network. Overrides the network table; defaults to "network" without one.

None
ignore_extra_columns bool

Drop columns that are not part of the schema instead of reporting them. Defaults to False: an unknown column is usually a typo (lenght), and silently ignoring it would silently drop the value.

False
**named_tables TableSource

Tables passed by name, e.g. buses=frame. They override entries of tables.

{}

Returns:

Type Description
Network

The network, with every impedance evaluated from its type formulas (exactly as create_bus/create_branch do) and the active fault of the network table activated. No results, no paths.

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
def network_from_tables(
    tables: Optional[Union[Mapping[str, TableSource], str, "os.PathLike[str]"]] = None,
    *,
    name: Optional[str] = None,
    ignore_extra_columns: bool = False,
    **named_tables: TableSource,
) -> Network:
    """
    Build a network from tables.

    Parameters
    ----------
    tables : mapping or str or os.PathLike, optional
        Either a mapping of table name to table -- a Polars frame or the path
        of a CSV file, as returned by :func:`network_to_tables` or by
        ``pl.read_excel(path, sheet_id=0)`` -- or the path of a directory
        holding ``<table>.csv`` files. The table names and their columns are
        listed in :data:`TABLE_SCHEMAS`; ``frequencies``, ``bus_types`` and
        ``buses`` are required, the others optional.
    name : str, optional
        Name of the network. Overrides the ``network`` table; defaults to
        ``"network"`` without one.
    ignore_extra_columns : bool, optional
        Drop columns that are not part of the schema instead of reporting
        them. Defaults to ``False``: an unknown column is usually a typo
        (``lenght``), and silently ignoring it would silently drop the value.
    **named_tables
        Tables passed by name, e.g. ``buses=frame``. They override entries of
        ``tables``.

    Returns
    -------
    Network
        The network, with every impedance evaluated from its type formulas
        (exactly as ``create_bus``/``create_branch`` do) and the active fault
        of the ``network`` table activated. No results, no paths.

    Raises
    ------
    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)
    """
    problems = _Problems()
    sources: Dict[str, Any] = {}
    if tables is None:
        pass
    elif isinstance(tables, Mapping):
        sources.update(tables)
    elif isinstance(tables, (str, os.PathLike)) and _FilePath(tables).is_dir():
        for table in TABLE_SCHEMAS:
            path = _FilePath(tables) / f"{table}.csv"
            if path.exists():
                sources[table] = path
    else:
        problems.add(
            "tables",
            f"expected a mapping of table name to table or a directory of CSV "
            f"files, got {tables!r}.",
        )
    sources.update(named_tables)

    for table in sources:
        if table not in TABLE_SCHEMAS:
            problems.add(
                table,
                f"unknown table; the tables are {list(TABLE_SCHEMAS)}.",
            )
    for table in REQUIRED_TABLES:
        if table not in sources:
            problems.add(table, "required table is missing.")

    frames: Dict[str, Optional[pl.DataFrame]] = {}
    for table in TABLE_SCHEMAS:
        if table not in sources:
            frames[table] = None
            continue
        frame = _read(sources[table], table, problems)
        frames[table] = (
            None if frame is None else _coerce(frame, table, problems, ignore_extra_columns)
        )

    network = _build(frames, name, problems)
    problems.raise_if_any()
    return network

network_to_tables

network_to_tables(
    network: Network,
) -> Dict[str, pl.DataFrame]

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:TABLE_SCHEMAS, in that order and with that schema; a table without rows is an empty frame with the schema's columns. Write them with frame.write_csv(...) or a spreadsheet writer of your choice.

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
def network_to_tables(network: Network) -> Dict[str, pl.DataFrame]:
    """
    Export a network as the tables :func:`network_from_tables` reads.

    Parameters
    ----------
    network : Network
        The network to export.

    Returns
    -------
    dict of str to polars.DataFrame
        One frame per table of :data:`TABLE_SCHEMAS`, in that order and with
        that schema; a table without rows is an empty frame with the schema's
        columns. Write them with ``frame.write_csv(...)`` or a spreadsheet
        writer of your choice.

    Raises
    ------
    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]
    """
    rows: Dict[str, List[Dict[str, Any]]] = {table: [] for table in TABLE_SCHEMAS}
    rows["network"].append(
        {
            "name": network.name,
            "description": network.description,
            "active_fault": network.active_fault,
        }
    )
    rows["frequencies"] = [{"frequency_Hz": float(f)} for f in network.frequencies]
    rows["bus_types"] = _type_rows(network.buses, "bus type", TABLE_SCHEMAS["bus_types"])
    rows["branch_types"] = _type_rows(
        network.branches, "branch type", TABLE_SCHEMAS["branch_types"]
    )
    for name, bus in network.buses.items():
        rows["buses"].append(
            {
                "name": name,
                "type": bus.type.name,
                "specific_earth_resistance": bus.specific_earth_resistance,
                "active": bus.active,
                "description": bus.description,
            }
        )
    for name, branch in network.branches.items():
        rows["branches"].append(
            {
                "name": name,
                "type": branch.type.name,
                "from_bus": branch.from_bus,
                "to_bus": branch.to_bus,
                "length": branch.length,
                "specific_earth_resistance": branch.specific_earth_resistance,
                "parallel_coefficient": branch.parallel_coefficient,
                "active": branch.active,
                "description": branch.description,
            }
        )
    for name, source in network.sources.items():
        rows["sources"].append(
            {
                "name": name,
                "bus": source.bus,
                "source_type": source.source_type,
                "i_k_a": source.i_k_a,
                "r_to_x": source.r_to_x,
                "kappa": source.kappa,
                "description": source.description,
            }
        )
        for quantity, mapping in (
            ("current", source.values),
            ("voltage", source.voltage),
            ("impedance", source.source_impedance),
        ):
            for frequency, value in (mapping or {}).items():
                rows["source_values"].append(
                    {
                        "source": name,
                        "quantity": quantity,
                        "frequency_Hz": float(frequency),
                        "real": float(value.real),
                        "imag": float(value.imag),
                    }
                )
    for name, fault in network.faults.items():
        rows["faults"].append(
            {
                "name": name,
                "bus": fault.bus,
                "t_k_s": fault.t_k_s,
                "n_factor": fault.n_factor,
                "description": fault.description,
            }
        )
        for frequency, scaling in fault.scalings.items():
            rows["fault_scalings"].append(
                {"fault": name, "frequency_Hz": float(frequency), "scaling": float(scaling)}
            )
    return {
        table: pl.DataFrame(rows[table], schema=schema)
        if rows[table]
        else pl.DataFrame(schema=schema)
        for table, schema in TABLE_SCHEMAS.items()
    }

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 always status="skip"; a "switch" row is "keep" for a closed bus-to-bus switch when a defaults with a switch_branch_type is 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 (None for 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_pandapower would assign, so preview and commit never disagree — including the _MISSING_LENGTH_FALLBACK_KM substitution (with the same warning) when pandapower carries no usable number. For a skipped line it is the raw parsed value, None when unusable.
  • in_service -- Boolean flag from pandapower (best effort).
  • reason -- Skip reason if status == "skip", None otherwise -- 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 (pp.bus.vn_kv).

required
include_trafos bool

Mirrors the parameter of :func:from_pandapower. Reserved for a future release — setting this to True raises :class:NotImplementedError so that preview ↔ commit cannot disagree silently about trafo handling.

False
defaults ImportDefaults

The same defaults that will be passed to :func:from_pandapower. Only the switch handling depends on them: without a switch_branch_type no switch can be imported, so passing the defaults is what lets the preview show a closed bus-to-bus switch as status="keep" rather than as skipped. Everything else is independent of the defaults, so None still gives a correct bus/line preview.

None

Returns:

Type Description
DataFrame

One row per bus and one per line, with the dtypes of _PREVIEW_SCHEMA.

Raises:

Type Description
NotImplementedError

If include_trafos=True.

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
def 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 always
      ``status="skip"``; a ``"switch"`` row is ``"keep"`` for a closed
      bus-to-bus switch when a ``defaults`` with a ``switch_branch_type`` is
      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 (``None`` for 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_pandapower` would assign, so
      preview and commit never disagree — including the
      ``_MISSING_LENGTH_FALLBACK_KM`` substitution (with the same
      warning) when pandapower carries no usable number. For a skipped
      line it is the raw parsed value, ``None`` when unusable.
    - ``in_service``     -- Boolean flag from pandapower (best effort).
    - ``reason``         -- Skip reason if ``status == "skip"``,
      ``None`` otherwise -- 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
    ----------
    net : pandapowerNet
        The pandapower network to inspect.
    voltage_level_kV : float
        Voltage level to keep (``pp.bus.vn_kv``).
    include_trafos : bool, optional
        Mirrors the parameter of :func:`from_pandapower`. Reserved for a
        future release — setting this to ``True`` raises
        :class:`NotImplementedError` so that ``preview ↔ commit`` cannot
        disagree silently about trafo handling.
    defaults : ImportDefaults, optional
        The same defaults that will be passed to :func:`from_pandapower`.
        Only the switch handling depends on them: without a
        ``switch_branch_type`` no switch can be imported, so passing the
        defaults is what lets the preview show a closed bus-to-bus switch as
        ``status="keep"`` rather than as skipped. Everything else is
        independent of the defaults, so ``None`` still gives a correct
        bus/line preview.

    Returns
    -------
    polars.DataFrame
        One row per bus and one per line, with the dtypes of
        ``_PREVIEW_SCHEMA``.

    Raises
    ------
    NotImplementedError
        If ``include_trafos=True``.

    Examples
    --------
    >>> import polars as pl
    >>> import pandapower.networks as pn  # doctest: +SKIP
    >>> import groundinsight as gi
    >>> frame = gi.preview_pandapower_import(  # doctest: +SKIP
    ...     pn.example_simple(), voltage_level_kV=20.0)
    >>> frame.filter(pl.col("status") == "skip")  # doctest: +SKIP
    """
    require_pandapower()

    if include_trafos:
        raise NotImplementedError(
            "include_trafos=True is reserved for a future release; "
            "trafos are not previewed yet — matches the commit-side "
            "behaviour of from_pandapower()."
        )

    bus_name_by_index = bus_index_to_name(net)
    line_name_by_index = _line_index_to_name(net)
    kept_bus_indices, skipped_buses = _classify_buses(net, voltage_level_kV)
    kept_bus_set = set(kept_bus_indices)
    kept_lines, skipped_lines = _classify_lines(
        net, kept_bus_set, bus_name_by_index, line_name_by_index
    )
    kept_switches, skipped_switches = _classify_switches(
        net, kept_bus_set, bus_name_by_index, defaults
    )
    open_switches, open_line_switches, other_line_switches = _classify_line_switches(
        net, set(kept_lines), bus_name_by_index
    )

    rows: List[Dict[str, Any]] = []

    # Kept buses
    for idx in kept_bus_indices:
        row = net.bus.loc[idx]
        rows.append(
            {
                "kind": "bus",
                "status": "keep",
                "pp_index": int(idx),
                "name": bus_name_by_index[int(idx)],
                "vn_kv": float(row.get("vn_kv", 0.0) or 0.0),
                "from_bus": None,
                "to_bus": None,
                "length_km": None,
                "in_service": _bus_in_service(row),
                "reason": None,
            }
        )

    # Skipped buses
    for entry in skipped_buses:
        rows.append(
            {
                "kind": "bus",
                "status": "skip",
                "pp_index": entry["pp_index"],
                "name": entry["name"],
                "vn_kv": entry.get("vn_kv"),
                "from_bus": None,
                "to_bus": None,
                "length_km": None,
                "in_service": None,
                "reason": entry["reason"],
            }
        )

    # Kept lines
    for idx in kept_lines:
        row = net.line.loc[idx]
        rows.append(
            {
                "kind": "line",
                "status": "keep",
                "pp_index": int(idx),
                "name": line_name_by_index[int(idx)],
                "vn_kv": None,
                "from_bus": bus_name_by_index[int(row["from_bus"])],
                "to_bus": bus_name_by_index[int(row["to_bus"])],
                "length_km": _length_km(
                    row, name=line_name_by_index[int(idx)], pp_index=int(idx)
                ),
                "in_service": _bus_in_service(row),
                "reason": _PREVIEW_SWITCH_REASON_LINE_OPEN
                if int(idx) in open_switches
                else None,
            }
        )

    # Skipped lines
    for entry in skipped_lines:
        rows.append(
            {
                "kind": "line",
                "status": "skip",
                "pp_index": entry["pp_index"],
                "name": entry["name"],
                "vn_kv": None,
                "from_bus": entry.get("from_bus"),
                "to_bus": entry.get("to_bus"),
                "length_km": entry.get("length_km"),
                "in_service": None,
                "reason": entry["reason"],
            }
        )

    # Switches: kept only when a switch_branch_type was supplied.
    for record in kept_switches:
        rows.append(
            {
                "kind": "switch",
                "status": "keep",
                "pp_index": record["pp_index"],
                "name": record["name"],
                "vn_kv": None,
                "from_bus": record["from_bus"],
                "to_bus": record["to_bus"],
                "length_km": float(defaults.switch_length_km)
                if defaults is not None
                else None,
                "in_service": True,
                "reason": None,
            }
        )
    # Open line switches of imported lines: they open the phase conductor.
    for record in open_line_switches:
        rows.append(
            {
                "kind": "switch",
                "status": "keep",
                "pp_index": record["pp_index"],
                "name": record["name"],
                "vn_kv": None,
                "from_bus": record["from_bus"],
                "to_bus": None,
                "length_km": None,
                "in_service": True,
                "reason": record["reason"],
            }
        )
    for record in skipped_switches + other_line_switches:
        rows.append(
            {
                "kind": "switch",
                "status": "skip",
                "pp_index": record["pp_index"],
                "name": record["name"],
                "vn_kv": None,
                "from_bus": record.get("from_bus"),
                "to_bus": record.get("to_bus"),
                "length_km": None,
                "in_service": None,
                "reason": record["reason"],
            }
        )

    # Trafos and impedance elements: never imported, but now counted and named
    # instead of vanishing between the bus and the line tables.
    for record in _unmodelled_elements(net):
        rows.append(
            {
                "kind": record["kind"],
                "status": "skip",
                "pp_index": record["pp_index"],
                "name": record["name"],
                "vn_kv": None,
                "from_bus": None,
                "to_bus": None,
                "length_km": None,
                "in_service": None,
                "reason": record["reason"],
            }
        )

    # The schema is pinned, never inferred: polars would only look at the
    # first 100 dicts, which on a net with >= 100 buses are all bus rows
    # with a ``None`` from_bus / to_bus / length_km, and the first line row
    # would then fail to append with a ComputeError.
    return pl.DataFrame(rows, schema=_PREVIEW_SCHEMA)

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 pandapower.shortcircuit.calc_sc has already been run.

required
t_k_s float

Short-circuit duration T_k in seconds. Defaults to the tk_s of the calc_sc run, but only if that run requested a thermal-equivalent current (ith=True) or passed a tk_s other than pandapower's default of 1.0 s. Without it m and I_th cannot be computed and are reported as None.

None
n_factor float

IEC 60909-0 AC heat factor n. 1.0 is the far-from-generator case. pandapower does not model n, so this argument is the only source of a non-neutral value.

1.0
frequency float

System frequency in Hz used in the m factor. The former keyword f is accepted as a deprecated alias.

50.0
buses sequence of int

Restrict the output to these pandapower bus indices. Defaults to every bus in res_bus_sc.

None

Returns:

Type Description
DataFrame

One row per bus with the columns pp_bus_index, bus_name, vn_kv, fault_type, case, i_k_a (in amperes, not kA), r1_ohm, x1_ohm, r0_ohm, x0_ohm, r_to_x, kappa, kappa_origin, t_k_s, n_factor, m, i_p_a and i_th_a.

Raises:

Type Description
ImportError

If pandapower is not installed.

ValueError

If net carries no short-circuit results, or if buses references indices absent from them.

Warns:

Type Description
InputWarning

SC_KAPPA_OUT_OF_RANGE (a bus whose ip/ikss imply a kappa outside (1, 2]; the closed form is used) and SC_KAPPA_MISSING (buses for which no kappa can be derived).

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
@renamed_parameters(f="frequency")
def 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
    ----------
    net : pandapower.auxiliary.pandapowerNet
        A pandapower network on which ``pandapower.shortcircuit.calc_sc``
        has already been run.
    t_k_s : float, optional
        Short-circuit duration ``T_k`` in seconds. Defaults to the
        ``tk_s`` of the ``calc_sc`` run, but only if that run requested a
        thermal-equivalent current (``ith=True``) or passed a ``tk_s``
        other than pandapower's default of 1.0 s. Without it ``m`` and
        ``I_th`` cannot be computed and are reported as ``None``.
    n_factor : float, default 1.0
        IEC 60909-0 AC heat factor ``n``. ``1.0`` is the
        far-from-generator case. pandapower does not model ``n``, so this
        argument is the only source of a non-neutral value.
    frequency : float, default 50.0
        System frequency in Hz used in the ``m`` factor.
        The former keyword ``f`` is accepted as a deprecated alias.
    buses : sequence of int, optional
        Restrict the output to these pandapower bus indices. Defaults to
        every bus in ``res_bus_sc``.

    Returns
    -------
    polars.DataFrame
        One row per bus with the columns ``pp_bus_index``, ``bus_name``,
        ``vn_kv``, ``fault_type``, ``case``, ``i_k_a`` (in **amperes**,
        not kA), ``r1_ohm``, ``x1_ohm``, ``r0_ohm``, ``x0_ohm``,
        ``r_to_x``, ``kappa``, ``kappa_origin``, ``t_k_s``, ``n_factor``,
        ``m``, ``i_p_a`` and ``i_th_a``.

    Raises
    ------
    ImportError
        If pandapower is not installed.
    ValueError
        If ``net`` carries no short-circuit results, or if ``buses``
        references indices absent from them.

    Warns
    -----
    InputWarning
        ``SC_KAPPA_OUT_OF_RANGE`` (a bus whose ``ip``/``ikss`` imply a
        ``kappa`` outside ``(1, 2]``; the closed form is used) and
        ``SC_KAPPA_MISSING`` (buses for which no ``kappa`` can be derived).

    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  # doctest: +SKIP
    >>> sc.calc_sc(net, fault="1ph", case="max", tk_s=0.5)  # doctest: +SKIP
    >>> gi.read_shortcircuit_results(net).select("bus_name", "i_k_a", "kappa")  # doctest: +SKIP
    """
    require_pandapower()

    res = getattr(net, "res_bus_sc", None)
    if res is None or len(res) == 0:
        raise ValueError(
            "The pandapower net carries no short-circuit results. Run "
            "pandapower.shortcircuit.calc_sc(net, fault='1ph', case='max', "
            "ip=True, ith=True, tk_s=...) before calling "
            "read_shortcircuit_results()."
        )

    options: Dict[str, Any] = dict(getattr(net, "_options", None) or {})
    fault_type = str(options.get("fault", "unknown"))
    case = str(options.get("case", "unknown"))
    if t_k_s is None:
        t_k_s = _tk_s_from_options(options)
    if t_k_s is not None:
        t_k_s = float(t_k_s)
        if t_k_s <= 0:
            raise ValueError(f"t_k_s must be strictly positive, got {t_k_s!r}.")
    if not (0.0 < float(n_factor) <= 1.0):
        raise ValueError(f"n_factor must lie in (0, 1], got {n_factor!r}.")
    n_factor = float(n_factor)

    # ``fault="1ph"`` is the earth-fault case; anything reporting a
    # zero-sequence impedance is treated the same way.
    earth_fault = fault_type in _EARTH_FAULT_TYPES or "rk0_ohm" in res.columns

    index_to_name = bus_index_to_name(net)

    if buses is not None:
        wanted = [int(b) for b in buses]
        missing = [b for b in wanted if b not in res.index]
        if missing:
            raise ValueError(
                f"Bus indices {missing} have no short-circuit results. "
                f"Available: {sorted(int(i) for i in res.index)}."
            )
        selection = wanted
    else:
        selection = [int(i) for i in res.index]

    rows: List[Dict[str, Any]] = []
    for idx in selection:
        row = res.loc[idx]
        bus_name = index_to_name.get(idx, f"bus_{idx}")

        ikss_ka = _finite(row.get("ikss_ka"))
        i_k_a = None if ikss_ka is None else ikss_ka * 1000.0
        r1 = _finite(row.get("rk_ohm"))
        x1 = _finite(row.get("xk_ohm"))
        r0 = _finite(row.get("rk0_ohm"))
        x0 = _finite(row.get("xk0_ohm"))

        r_to_x = _loop_r_to_x(r1, x1, r0, x0, earth_fault)
        kappa, kappa_origin = _kappa_for_row(
            i_k_a, _finite(row.get("ip_ka")), r_to_x, bus_name
        )

        m = None
        i_p_a = None
        i_th_a = None
        if kappa is not None:
            if i_k_a is not None:
                i_p_a = peak_short_circuit_current(i_k_a, kappa)
            if t_k_s is not None:
                m = iec60909_m(kappa, frequency, t_k_s)
                if i_k_a is not None:
                    i_th_a = thermal_equivalent_current(i_k_a, m, n_factor)

        rows.append(
            {
                "pp_bus_index": int(idx),
                "bus_name": bus_name,
                "vn_kv": _finite(net.bus.at[idx, "vn_kv"]) if idx in net.bus.index else None,
                "fault_type": fault_type,
                "case": case,
                "i_k_a": i_k_a,
                "r1_ohm": r1,
                "x1_ohm": x1,
                "r0_ohm": r0,
                "x0_ohm": x0,
                "r_to_x": r_to_x,
                "kappa": kappa,
                "kappa_origin": kappa_origin,
                "t_k_s": t_k_s,
                "n_factor": n_factor,
                "m": m,
                "i_p_a": i_p_a,
                "i_th_a": i_th_a,
            }
        )

    unavailable = [r["bus_name"] for r in rows if r["kappa_origin"] == "unavailable"]
    if unavailable:
        emit(
            InputWarning,
            f"No kappa could be derived for {len(unavailable)} bus(es) "
            f"({unavailable}): neither ip_ka nor a usable R/X is available. For "
            f"fault='1ph' make sure the zero-sequence data (x0x_max, r0x0_max, "
            f"vk0_percent, r0_ohm_per_km, ...) is complete.",
            code="SC_KAPPA_MISSING",
            elements=[("bus", name) for name in unavailable],
            stacklevel=2,
        )

    return pl.DataFrame(rows, schema=_SC_SCHEMA)

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 a UnicodeEncodeError for Ω/ρ 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 an InputWarning with the code PROJECT_FILE_LEGACY_ENCODING says 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 with os.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_version is the version of the file layout, groundinsight_version the 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

METADATA_KEYS: Tuple[str, ...] = (
    "schema_version",
    "groundinsight_version",
)

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

SCHEMA_VERSION: int = 1

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_network_from_json(path: _PathLike) -> Network

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 schema_version than :data:SCHEMA_VERSION, or does not describe a valid network (pydantic.ValidationError is a ValueError).

Warns:

Type Description
InputWarning

Code PROJECT_FILE_LEGACY_ENCODING: the file is not UTF-8 and was decoded with the platform's preferred encoding, as 0.6.0 wrote it on that machine.

Examples:

>>> import groundinsight as gi
>>> net = gi.load_network_from_json("sued.json")
Source code in src/groundinsight/io/project_file.py
def load_network_from_json(path: _PathLike) -> Network:
    """
    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
    ----------
    path : str or os.PathLike
        The project file.

    Returns
    -------
    Network
        The validated network, including any stored results.

    Raises
    ------
    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 ``schema_version`` than :data:`SCHEMA_VERSION`, or does not
        describe a valid network (``pydantic.ValidationError`` is a
        ``ValueError``).

    Warns
    -----
    InputWarning
        Code ``PROJECT_FILE_LEGACY_ENCODING``: the file is not UTF-8 and was
        decoded with the platform's preferred encoding, as 0.6.0 wrote it on
        that machine.

    Examples
    --------
    >>> import groundinsight as gi
    >>> net = gi.load_network_from_json("sued.json")  # doctest: +SKIP
    """
    source = os.fspath(path)
    with open(source, "rb") as handle:
        raw = handle.read()
    text, legacy_encoding = _decode(raw, source)
    try:
        payload = json.loads(text)
    except json.JSONDecodeError as exc:
        raise ValueError(f"'{source}' is not a valid JSON file: {exc}") from exc
    if not isinstance(payload, dict):
        raise ValueError(
            f"'{source}' does not contain a groundinsight network: the "
            f"top-level JSON value is a {type(payload).__name__}, not an object."
        )
    schema_version, written_by = _pop_metadata(payload, source)
    if legacy_encoding is not None and schema_version is not None:
        # Every release that writes a schema version writes UTF-8, so a file
        # with one that is not UTF-8 has been re-encoded or damaged since.
        raise ValueError(
            f"'{source}' carries schema_version {schema_version} but is not "
            "valid UTF-8; project files with a schema version are always "
            "written as UTF-8. Re-encode the file as UTF-8."
        )
    network = Network.model_validate(payload)
    if legacy_encoding is not None:
        emit(
            InputWarning,
            f"'{source}' is not UTF-8 and was decoded with the platform's "
            f"preferred encoding '{legacy_encoding}', the way groundinsight "
            "0.6.0 and earlier wrote project files. Names may be garbled if "
            "the file was written on a computer with a different locale. "
            "Saving the network again writes UTF-8.",
            code="PROJECT_FILE_LEGACY_ENCODING",
            elements=[("network", network.name)],
        )
    logger.debug(
        "Loaded network '%s' from '%s' (schema version %s, written by "
        "groundinsight %s).",
        network.name,
        source,
        schema_version if schema_version is not None else "none",
        written_by if written_by is not None else "0.6.0 or earlier",
    )
    return network

save_network_to_json

save_network_to_json(
    network: Network, path: _PathLike
) -> None

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 path is a symbolic link, the file it points to is replaced.

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'
Source code in src/groundinsight/io/project_file.py
def save_network_to_json(network: Network, path: _PathLike) -> None:
    """
    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
    ----------
    network : Network
        The network to save.
    path : str or os.PathLike
        Target file. An existing file is replaced as a whole or not at all;
        if ``path`` is a symbolic link, the file it points to is replaced.

    Raises
    ------
    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")  # doctest: +SKIP
    >>> gi.load_network_from_json("sued.json").name  # doctest: +SKIP
    'Süd'
    """
    # Serialise first: a failure here must not have touched the disk.
    payload = _project_file_text(network).encode("utf-8")
    target = _resolve_target(os.fspath(path))
    _atomic_write(target, payload)
    logger.debug(
        "Saved network '%s' to '%s' (schema version %d).",
        network.name,
        target,
        SCHEMA_VERSION,
    )