Engines#
PandaPower engine implementation for power flow analysis in GridForge.
- exception gridforge.engines.pandapower_engine.PandaPowerControllerNotConverged[source]#
Bases:
PandaPowerNotConverged,ControllerNotConvergedRaised by PandaPowerEngine.run_power_flow when the controllers do not converge.
As PandaPowerNotConverged, and pandapower’s ControllerNotConverged as well.
- class gridforge.engines.pandapower_engine.PandaPowerEngine(config: dict[str, Any] | None = None)[source]#
Bases:
PowerFlowEngineInterface to PandaPower for power flow calculations and network analysis.
This engine provides methods to:
Load network models
Run power flow calculations
Apply network modifications
Check constraint violations
Extract results and metrics
Buses, lines and transformers are identified by their name: in the violations, the sensitivities, the actions of the strategies and the paths they search. Loads and static generators are identified by their index (get_flexibility_data, apply_flexibility_action, the flexibility actions), but flexibility_settings is keyed by their name. Each of these elements must therefore have a name (not None, NaN or “”), and two buses, two lines, two transformers, two loads or two static generators must not have the same, which check_names checks, and run_power_flow before each run; elements of different tables may share one (a bus and a line, a load and a static generator). fill_missing_names names the elements that have no name.
The ZIP shares of a load (const_z_p_percent, const_z_q_percent, const_i_p_percent and const_i_q_percent, in percent of its power) must be numbers, not missing (NaN, None or pd.NA), for each load that is in the power flow (in service, at a bus that is not dead): pandapower’s power flow does not converge on NaN, and does not say why, so check_zip_shares refuses such a network, and run_power_flow before each run. 0 means constant power, the default of create_load: simbench, which leaves them NaN, needs them filled with 0. A column that is missing is not NaN: pandapower raises a KeyError that names it, while the loads are voltage-dependent.
- add_bus(like_bus: int, coordinates: tuple[float, float] | None = None, name: str | None = None) int[source]#
Create a bus with every column of the bus row of like_bus (nominal voltage, type, zone, in service, voltage limits) but its name and coordinates, not connected to anything.
- Parameters:
like_bus (int) – Index of the bus whose row the new bus copies.
coordinates (tuple[float, float] | None) – Its (longitude, latitude); none if None.
name (str | None) – Its name, followed by
_2,_3… when another bus has it.<name of like_bus>_newif None.
- Returns:
Index of the new bus.
- Return type:
int
- Raises:
ValueError – If no network is loaded, if like_bus is not in the network, or if the coordinates are not two finite numbers.
- add_line(from_bus: int, to_bus: int, line_type: str, length_km: float, geometry: list[tuple[float, float]] | None = None, name: str | None = None) str[source]#
Create a line of a standard type between two buses of the same nominal voltage, with one conductor.
- Parameters:
from_bus (int) – Index of its from_bus.
to_bus (int) – Index of its to_bus, another bus.
line_type (str) – Its standard type.
length_km (float) – Its length, more than 0.
geometry (list[tuple[float, float]] | None) – Its route, two points or more from from_bus to to_bus, as a list, a tuple or a numpy array; none if None. Each point is a sequence of longitude, latitude and possibly more coordinates (an altitude), of which the first two are kept, as get_line_geometry reads them. The length is not taken from it.
name (str | None) – Its name, followed by
_2,_3… when another line has it.new_line_<from bus>_to_<to bus>if None.
- Returns:
Name of the new line.
- Return type:
str
- Raises:
ValueError – If no network is loaded, if a bus is not in the network, if the two buses are the same or of different nominal voltages, if the type is unknown, if the length is not more than 0, or if the route is not a list of two points or more, each two finite numbers; before anything is created.
- add_parallel_line(line_id: str) int[source]#
Add a parallel line.
- Parameters:
line_id (str) – Name of the line to add a conductor to.
- Returns:
Number of parallel conductors of the line after the addition.
- Return type:
int
- Raises:
ValueError – If no line has that name, or several do.
- add_parallel_transformer(trafo_id: str) int[source]#
Add a parallel transformer.
- Parameters:
trafo_id (str) – Name of the transformer to add a unit to.
- Returns:
Number of parallel units of the transformer after the addition.
- Return type:
int
- Raises:
ValueError – If no transformer has that name, or several do.
- add_transformer(hv_bus: int, lv_bus: int, transformer_type: str, tap_pos: float | None, like: str | None = None, name: str | None = None) str[source]#
Create a transformer of a standard type between two buses, at a tap position.
With like, the unit takes the vector group (
shift_degree,vector_group) and the tap changer (tap_side,tap_neutral,tap_min,tap_max,tap_step_percent,tap_step_degree,tap_changer_type) of that transformer, where its table has them: a unit added next to it in the same network is connected and tapped as it is. The rest (rating, impedance, rated voltages) is the type’s, and the unit has no tap-dependent impedance (tap_dependency_table), which belongs to a type.- Parameters:
hv_bus (int) – Index of its HV bus.
lv_bus (int) – Index of its LV bus, of a lower nominal voltage.
transformer_type (str) – Its standard type.
tap_pos (float | None) – Its tap position, a whole number within its tap range (
tap_mintotap_max). A unit without a range (NaN, as one like a unit without a tap changer has) takes None or NaN, and has no position (NaN), or itstap_neutralwhen it has one.like (str | None) – Name of the transformer whose vector group and tap changer it takes; those of the type if None.
name (str | None) – Its name, followed by
_2,_3… when another transformer has it.new_trafo_<hv bus>_to_<lv bus>if None.
- Returns:
Name of the new transformer.
- Return type:
str
- Raises:
ValueError – If no network is loaded, if a bus is not in the network or the HV bus is not of a higher nominal voltage than the LV bus, if the type is unknown, if no transformer is called like or several are, or if the tap position is outside the range; before anything is created.
- analyze_thermal_violation(element_type: str, element_id: str) dict[str, Any][source]#
Analyze a thermal violation to determine downstream topology and flow conditions.
- Parameters:
element_type (str) – “Line” or “Transformer”.
element_id (str) – Name of the element.
- Returns:
Dictionary with analysis results.
- Return type:
Dict[str, Any]
- analyze_violations()[source]#
Calls the NetworkConstraint analyze_violations method.
- Returns:
The summary of violations.
- Return type:
Any
- apply_flexibility_action(element_type: str, element_index: int, new_p_mw: float, new_q_mvar: float | None = None) None[source]#
Apply flexibility action.
The powers are those on the network, as get_flexibility_data gives them: the p_mw and q_mvar written in the table of the network are divided by the scaling of the element, by which pandapower multiplies them.
The method does not check the service state of the element, nor whether its bus is energised: it writes to the element it is given, even when that element is out of service or at a de-energised bus. A caller acting outside FlexibilityStrategy, which never selects such an element, must filter them out itself.
- Parameters:
element_type (str) – ‘load’ or ‘sgen’.
element_index (int) – Index of the element.
new_p_mw (float) – New active power value in MW.
new_q_mvar (Optional[float], optional) – New reactive power of a load, in MVAr. Defaults to None, which keeps the power factor of the load. That cannot undo a load that was shed down to zero, as the power factor is lost with the active power: restoring such a load needs its reactive power.
- apply_tap_change(trafo_id: str, tap_pos_shift: int) bool[source]#
Change the tap position of a transformer by a number of steps.
The shift is applied whole or not at all: a shift that would take the position outside the tap range of the unit (
tap_mintotap_max) is refused, from inside the range as well as from its end, and so is any shift of a unit without a range or a position (NaN). A position thus never leaves the range by a tap change; upgrade_transformer brings it into the range of a new type.- Parameters:
trafo_id (str) – Name of the transformer.
tap_pos_shift (int) – Number of steps added to the current tap position, negative to lower it; TapChangeStrategy passes shifts of several steps.
- Returns:
- True if the position moved by tap_pos_shift, False if nothing
changed because the new position would be outside the range.
- Return type:
bool
- Raises:
ValueError – If no transformer has that name, or several do.
- calculate_branch_loading_sensitivities(element_type: str, element_name: str) DataFrame[source]#
Calculate sensitivity of branch loading to active power injections using Jacobian.
Returns DataFrame with bus_names as index and one column,
sensitivity, containing d(Loading%)/dP_mw for the specific branch, in % per MW of active power injected at the bus.The loading differentiated is the one pandapower reports in
res_line.loading_percentandres_trafo.loading_percent: it is proportional to the magnitude of the current at the end of the branch where it is the highest (for a transformer, relative to the rated current of each side; to the apparent power of that end withtrafo_loading="power"). The current comes from the branch admittances of the solved case, which carry the tap ratio and the phase shift of a transformer and the charging of a line:\(I = \sum_k Y_k V_k\), over the two ends \(k\) of the branch
\(\frac{d(\text{Loading}\%)}{d(\theta,V)} = \text{Loading}\% \times \frac{\Re(\bar{I}\, dI/d(\theta,V))}{|I|^2}\)
\(\frac{d(\text{Loading}\%)}{dP_{bus}} = \frac{d(\text{Loading}\%)} {d(\theta,V)} \frac{d(\theta,V)}{dP_{bus}}\), the last factor being a column of the inverse of the Jacobian. All the buses are obtained from one transposed solve.
The value is the plain derivative of the loading with respect to the active power injected at the bus, at constant reactive injection: positive means that injecting more at the bus raises the loading of the branch, negative that it lowers it, whatever the direction of the flow in the branch. Shedding a load raises the injection at its bus, curtailing a generator lowers it.
The voltage-dependent share of the loads (
const_i_*_percent,const_z_*_percent) is not in the Jacobian, and so not in these sensitivities: see the limit in calculate_voltage_power_sensitivities.Buses joined by a closed bus-bus switch have the same sensitivity. The slack bus, the buses fused with it and the buses out of service have none. The result is empty if there is no converged run of the engine (run_power_flow; the results of pp.runpp are not used, as in the voltage sensitivities), if the branch is unknown or out of service, or if a bus, a line or a transformer has been created or dropped since the last power flow: the branch could not be found in its results.
- calculate_voltage_line_change_effects(changes: dict[str, tuple[float, float, int]], buses: list[str] | None = None) DataFrame[source]#
Predict the bus voltage-magnitude change (p.u.) brought by a finite change of each line.
Unlike the resistance sensitivity, the response is linearised in the finite change of the series impedance (r and x of the parallel-combined line) with one Newton step, so the prediction stays accurate for large steps (a new conductor type, one more parallel conductor) on radial feeders, where the voltage drop is nearly linear in impedance.
The voltage-dependent share of the loads (
const_i_*_percent,const_z_*_percent) is not in this Jacobian: see the limit in calculate_voltage_power_sensitivities.- Parameters:
changes (Dict[str, Tuple[float, float, int]]) – line name -> (new r_ohm_per_km, new x_ohm_per_km, new parallel count).
buses (Optional[List[str]], optional) – Only compute the response at these buses.
- Returns:
- index = bus names, columns = names of the lines of changes
that conduct (in service, no open line switch, between buses in service and supplied) between buses of the solution, values = predicted dV (p.u.). A line without series impedance, like one of zero length, has no voltage drop to change: its column is 0.
- Return type:
pd.DataFrame
- Raises:
RuntimeError – If there is no converged run of the engine (run_power_flow; the results of pp.runpp are not used), or if a bus, a line or a transformer has been created or dropped since the last one.
- calculate_voltage_line_change_effects_of_steps(steps: list[tuple[str, float, float, int]], buses: list[str] | None = None) DataFrame[source]#
Predicted bus voltage-magnitude change (p.u.) for each of steps, each a finite change of one line taken alone: (line name, new r_ohm_per_km, new x_ohm_per_km, new parallel count), several steps of a line allowed.
Each step is a column of the response of calculate_voltage_line_change_effects, computed from the same factors of the Jacobian, and the column of a step does not depend on the other steps: all are predicted with one solve, whatever the number of steps a line has.
- Returns:
- index = bus names, or buses when given; columns = the
positions in steps of the steps whose line conducts (see calculate_voltage_line_change_effects), in order.
- Return type:
pd.DataFrame
- Raises:
RuntimeError – As calculate_voltage_line_change_effects.
- calculate_voltage_line_resistance_sensitivities(line_names: list[str] | None = None) DataFrame[source]#
Computes the sensitivity of bus voltage magnitudes to small changes in line RESISTANCE (r_pu) using the inverse of the Jacobian matrix from pandapower’s power flow solution.
The computation is vectorised over the lines and can be restricted to a subset of lines, which keeps it cheap on large feeders when only one galvanic zone is of interest.
The voltage-dependent share of the loads (
const_i_*_percent,const_z_*_percent) is not in this Jacobian: see the limit in calculate_voltage_power_sensitivities.- Parameters:
line_names (Optional[List[str]], optional) – Names of the lines to consider. Defaults to all lines that conduct.
- Returns:
- DataFrame with bus names as index and line names as columns.
Each value represents dV_mag_pu / dr_line_pu (equivalent resistance of the parallel-combined line).
- Return type:
pd.DataFrame
- Raises:
RuntimeError – If there is no converged run of the engine (run_power_flow; the results of pp.runpp are not used), or if a bus, a line or a transformer has been created or dropped since the last one.
- calculate_voltage_power_sensitivities(buses: list[str] | None = None) DataFrame[source]#
Calculate sensitivity of bus voltage magnitudes to active power injection.
The rows are rows of the inverse of the Jacobian, J^-1. Each is computed from the transposed system J^T y = e, so asking only for the buses that are needed costs one solve per bus instead of the whole inverse.
Limit, voltage-dependent loads: the sensitivities of the engine, of voltage and of loading alike, are those of loads of constant power. The Jacobian they come from, which the engine builds from pandapower’s admittance matrix, holds every load as a constant power: the constant-current and constant-impedance share of a load (
const_i_p_percent,const_i_q_percent,const_z_p_percent,const_z_q_percent) is not in it, so that the sensitivities ignore how such a load follows the voltage. With such a share they are off, by an amount that grows with the share, with the loading of the network and from one metric to another, and they are not corrected. Against central differences of power flows on52_MVFeeder1118, every load at 100 % of the model (median relative errors;benchmarks/zip_load_sensitivities.py, and the table in the methodology documentation): at load x1.0, constant current 2.4 to 3.8 % for the voltage (whole column to buses over 20 % of the largest) and 4.3 % for the loading, constant impedance 4.8 to 7.5 % and 8.5 %; at load x2.5, the factor of the case study, constant current 7.6 to 19 % (at the bus itself to buses over 20 % of the largest) and 21 %, constant impedance 14 to 36 % and 39 %; under 0.01 % with loads of constant power. The feeders of the case study have these columns at 0.- Parameters:
buses (Optional[List[str]]) – Names of the buses whose voltage sensitivities are needed. Defaults to None, for all PQ buses. Names that are not PQ buses of the solution (slack or PV buses, unknown names) are left out.
- Returns:
- DataFrame with index=bus_names (the requested PQ buses),
columns=bus_names (the PV and PQ buses). Values are d|V|_i / dP_j, in pu per MW of active power injected at bus j. Buses joined by a closed bus-bus switch are one bus for the power flow: each of them has the row and the column of that bus.
- Return type:
pd.DataFrame
- Raises:
RuntimeError – If there is no converged run of the engine (run_power_flow; the results of pp.runpp are not used), or if a bus, a line or a transformer has been created or dropped since the last one, whose results are then those of another network.
- check_names() None[source]#
Refuse a network in which a bus, a line, a transformer, a load or a static generator has no name, or the name of another element of its table.
Everything the engine answers by name would otherwise silently mix them up: the sensitivities give one row for two buses, a parallel conductor goes on two lines at once, a line to a bus named as the source of the feeder is a line to the source in the path search. Elements without a name (None, NaN or “”) cannot be told apart either: the voltage sensitivities give all the unnamed buses of a network the same name, NaN. Loads and static generators are identified by their index, but their flexibility settings are kept by name (flexibility_settings): two loads of one name would get the same flexibility, whatever was meant for each. Elements of different tables may share a name.
run_power_flow calls it before each run; call it right after loading a network to know at once, before any power flow. Nothing is renamed: fill_missing_names names the elements that have no name, and shared names are for the caller to change.
- Raises:
ValueError – Giving, for each table, the indices of up to five elements without a name, and up to five shared names, each with the indices of the elements that have it, or if no network is loaded.
- check_violations() dict[str, Any][source]#
Check if the network violates specified constraints.
The voltages and loadings checked are those of the result tables, which hold the solution after the Newton step that ends each run (_take_one_more_newton_step): the violations, and the decisions taken on them, do not depend on where the solver started or stopped. A value at its limit is not a violation. Each violation has the level of its network (ConstraintViolation.level): that of its bus, of the from bus of its line, of the LV side of its transformer.
- Returns:
Dictionary with constraint violations.
- Return type:
Dict[str, Any]
Refuse a network in which a load that is in the power flow has a missing ZIP share: NaN, None or pd.NA.
pandapower’s power flow does not converge on NaN shares, and the error does not say that the shares are the cause (on the SimBench network of #77, “did not converge after 50 iterations”). With None or a nullable NA it converges only if all the other shares are 0, which switches the voltage-dependent loads off, and fails otherwise, with a LoadflowNotConverged or a TypeError: they are refused as missing values too. simbench 1.6 leaves all four shares NaN on every load. 0 means constant power, as it does for a load made by create_load.
run_power_flow calls it before each run; call it right after loading a network to know at once. Nothing is filled in: that is for the caller to do, for instance with net.load[ZIP_SHARES] = net.load[ZIP_SHARES].fillna(0.0).
A load that is not in the power flow is left alone: one out of service, or at a bus that is out of service or in an island with no source (_energised). So is a network solved with voltage_depend_loads False, which does not read the shares: in power_flow_specific_settings, or, if they do not say, in net.user_pf_options. The check applies whatever the algorithm: pandapower converges on NaN shares with gs and fdbx, and not with nr, bfsw and iwamoto_nr (which fails with a LinAlgError), and a network that one algorithm solves is not one to rely on for the others. A column that is missing is not NaN: while the loads are voltage-dependent, pandapower raises a KeyError that names it, and it is not checked here. The static generators have no shares in pandapower 3.2. A nullable boolean in_service with a missing value is not handled: pandapower cannot solve such a network either.
A load out of service that has NaN shares does not reach the solution, but pandapower then keeps the voltage-dependent loads on (it switches them off only when all the shares are 0), and leaves NaN in res_load for that load and in res_bus.p_mw at its bus. Fill the shares of such a load to avoid it.
- Raises:
ValueError – Giving the indices of up to five of the loads concerned and the columns that are NaN, or if no network is loaded.
- create_bus(name: str, nominal_voltage_v: float, **kwargs: Any)[source]#
Create a new bus in the PandaPower network.
- Parameters:
name (str) – Name of the bus.
nominal_voltage_v (float) – Nominal voltage of the bus in kV.
**kwargs – Additional parameters for the bus.
- Returns:
Index of the created bus.
- Return type:
int
- create_empty_network(name: str = 'grid-forge-network', f_hz: float = 50.0) None[source]#
Create an empty pandapower network.
- Parameters:
name (str, optional) – Name of the network. Defaults to “grid-forge-network”.
f_hz (float, optional) – System frequency in Hz. Defaults to 50.0.
- create_ext_grid(bus_name: str, name: str, voltage_reference_pu: float, angle_reference_degree: float = 0, **kwargs: Any)[source]#
Create a new external grid connection in the PandaPower network.
- Parameters:
bus_name (str) – Name of the bus where the external grid is connected.
name (str) – Name of the external grid.
voltage_reference_pu (float) – Voltage magnitude in per unit.
angle_reference_degree (float, optional) – Voltage angle in degrees. Defaults to 0.
**kwargs – Additional parameters for the external grid.
- Returns:
Index of the created external grid.
- Return type:
int
- create_generator(bus_name: str, name: str, active_power_w: float, reactive_power_var: float, **kwargs: Any)[source]#
Create a new static generator in the PandaPower network.
- Parameters:
bus_name (str) – Name of the bus where the generator is connected.
name (str) – Name of the generator.
active_power_w (float) – Active power of the generator in W.
reactive_power_var (float) – Reactive power of the generator in VAr.
**kwargs – Additional parameters for the generator. max_flex_pct is the share of its active power, in percent, that FlexibilityStrategy can take off, counted from its power as each run starts, or at each call of a strategy used on its own (see FlexibilityStrategy.initial_power for a strategy called several times).
- Returns:
Index of the created generator.
- Return type:
int
- Raises:
ValueError – If name is None, NaN or “”, or the name of a static generator already in the network, before anything is created: its max_flex_pct would be stored under the name of the other generator, whose flexibility it would change, and check_names refuses such a network anyway.
- create_line(name: str, from_bus: str, to_bus: str, length_km: float, line_type: str, **kwargs: Any)[source]#
Create a new line in the PandaPower network.
- Parameters:
name (str) – Name of the line.
from_bus (int) – ID of the starting bus.
to_bus (int) – ID of the ending bus.
length_km (float) – Length of the line in kilometers.
line_type (str) – Type of the line (refers to standard types in pandapower).
**kwargs – Additional parameters for the line.
- Returns:
Index of the created line.
- Return type:
int
- create_load(bus_name: str, name: str, active_power_w: float, reactive_power_var: float, **kwargs: Any)[source]#
Create a new load in the PandaPower network.
- Parameters:
bus_name (str) – Name of the bus where the load is connected.
name (str) – Name of the load.
active_power_w (float) – Active power of the load in W.
reactive_power_var (float) – Reactive power of the load in VAr.
**kwargs – Additional parameters for the load. max_flex_pct is the share of its active power, in percent, that FlexibilityStrategy can take off, counted from its power as each run starts, or at each call of a strategy used on its own (see FlexibilityStrategy.initial_power for a strategy called several times).
- Returns:
Index of the created load.
- Return type:
int
- Raises:
ValueError – If name is None, NaN or “”, or the name of a load already in the network, before anything is created: its max_flex_pct would be stored under the name of the other load, whose flexibility it would change, and check_names refuses such a network anyway.
- create_topology_graph() Any[source]#
Create a NetworkX graph representing the network topology.
- Returns:
NetworkX graph object.
- Return type:
networkx.Graph
- create_transformer(name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any)[source]#
Create a new transformer in the PandaPower network.
- Parameters:
name (str) – Name of the transformer.
hv_bus (str) – Name of the high voltage bus.
lv_bus (str) – Name of the low voltage bus.
transformer_type (str) – Type of the transformer (refers to standard types in pandapower).
**kwargs – Additional parameters for the transformer.
- Returns:
Index of the created transformer.
- Return type:
int
- fill_missing_names()[source]#
Name the buses, lines, transformers, loads and static generators that have no name (None, NaN or “”).
The names are
bus_<index>,line_<index>_<from bus>_to_<to bus>,trafo_<index>_<hv bus>_to_<lv bus>,load_<index>_<bus>andsgen_<index>_<bus>, after the buses are named. A name that another element of the same table already has is followed by_2(or_3, and so on, until it is free), so that the names given are never shared: a bus without a name at index 3 next to a bus calledbus_3is calledbus_3_2. Names already there, shared or not, are left as they are: check_names reports the shared ones, which are for the caller to change. Call it before the first power flow: check_names refuses unnamed elements.A load or a static generator named here has no entry in flexibility_settings, and so no flexibility, until one is given under its new name.
- get_bus_coordinates(bus_ids: Iterable[int]) dict[int, tuple[float, float] | None][source]#
Coordinates (longitude, latitude) of buses, None for a bus that has none.
They are read from the
xandyof the bus_geodata table of the network, when it has one with a row for the bus, otherwise from the GeoJSON point of thegeocolumn of the bus table (a string, as pandapower writes it, or a dict), the two sources create_topology_graph reads. A bus without geodata, with a point that cannot be read, or with a coordinate that is not a finite number (NaN, as the slack bus of the feeder files has), has None.- Parameters:
bus_ids (Iterable[int]) – Indices of the buses.
- Returns:
The coordinates of each bus.
- Return type:
dict[int, tuple[float, float] | None]
- Raises:
ValueError – If no network is loaded or a bus is not in the network.
- get_buses_info() DataFrame[source]#
Every bus, indexed by its index: name, vn_kv, in_service; from the latest power flow vm_pu, and p_mw and q_mvar injected at the bus (the opposite of pandapower’s res_bus, which counts a load as positive), NaN without a converged run of the engine, or for a bus added since; and from the tables, consumption_mw and production_mw, the active power drawn and produced by the loads, storage units, static generators and generators in service at the bus, times their scaling: a load or a storage unit of negative power produces, a generator of negative power consumes. 0 at a bus out of service or that no source reaches.
- Raises:
ValueError – If no network is loaded.
- get_closed_bus_switches() list[tuple[str, str]][source]#
Pairs of bus names joined by a closed bus-bus switch (galvanic links that are not lines).
- get_customer_buses() set[str][source]#
Names of the buses with a customer: an element in service of the tables of loads, static generators, generators, storage units, asymmetric loads or asymmetric static generators, whatever its power at the moment.
- get_flexibility_data(element_type: str) DataFrame[source]#
Get flexibility data for loads or sgens.
Only the elements that carry power are given: those in service, at a bus that a power flow reaches. One that is out of service, at a bus out of service, or at a bus of an island that no source reaches (_dead_buses) has no power on the network, so there is nothing to shed or curtail on it, and it is not part of the load or the generation that the shares of a run are taken of. This is read from the topology of the network at each call, with or without a power flow run since. The index is that of the table of the network, whatever is left out.
The powers are those on the network: pandapower multiplies the p_mw and q_mvar of a load or a static generator by its scaling, and so do the powers given here. apply_flexibility_action takes powers on the same footing.
- Parameters:
element_type (str) – ‘load’ or ‘sgen’.
- Returns:
DataFrame with flexibility data.
- Return type:
pd.DataFrame
- get_line_base_impedance(line_id: int | str) float[source]#
Get the per-unit base impedance (ohm) of a line, from its from-bus voltage and the network base power.
- get_line_endpoints(line_ids: list[str] | None = None) DataFrame[source]#
Names of the end buses (columns from_bus, to_bus) of the lines that conduct (in service, no open line switch, between buses in service and supplied), indexed by line name.
- get_line_geometry(line_id: str) list[tuple[float, float]] | None[source]#
Route of a line, from the GeoJSON line string of the
geocolumn of the line table, as (longitude, latitude) points running from its from_bus to its to_bus.A route stored the other way (its first point nearer the to_bus than the from_bus, both ends having coordinates) is reversed; every line of the three feeders checked is stored from its from_bus. None for a line without a route, with one that cannot be read, or with fewer than two points or a coordinate that is not a finite number.
- Raises:
ValueError – If no network is loaded, or no line has that name, or several do.
- get_line_ids() list[str][source]#
Names of the lines that conduct: in service, no open line switch, between buses in service and supplied.
- get_line_imax(line_type)[source]#
Fetches and returns the maximum intensity for a given line type.
- Parameters:
line_type (str) – Specifies the type of line for which the maximum value is to be retrieved.
- Returns:
The maximum intensity associated with the specified line type.
- Return type:
float
- get_line_length(line_id: int | str) float[source]#
Get the length of a line by its ID.
- Parameters:
line_id (Union[int, str]) – The ID of the line.
- Returns:
The length of the line in kilometers.
- Return type:
float
- Raises:
ValueError – If the network is not initialized or if the line is not found.
- get_line_parallel(line_id: int | str) int[source]#
Get the number of parallel conductors of a line (1 for a single line).
- get_line_r_ohm_per_km(line_type: str) float[source]#
Get the resistance per unit length for a given line type.
- Parameters:
line_type (str) – The type of the line.
- Returns:
The resistance per unit length (Ohm/km).
- Return type:
float
- get_line_rating(line_id: int | str) float | None[source]#
Get the rating (A) of one conductor of a line, as the line table holds it (max_i_ka), whether or not it is that of its type. The loading the engine reports is relative to it, times the derating factor df and the parallel conductors.
- Returns:
- The rating of one conductor, None if the line is not
found or has none.
- Return type:
Optional[float]
- get_line_type(line_id: str) str[source]#
Returns the type of a line based on the provided line ID.
- Parameters:
line_id (str) – The unique identifier (name) of the line.
- Returns:
The standard type of the line.
- Return type:
str
- Raises:
ValueError – If the network is not initialized or if the line is not found.
- get_line_x_ohm_per_km(line_type: str) float[source]#
Get the reactance per unit length for a given line type.
- get_lines_info(line_ids: list[str] | None = None) DataFrame[source]#
Type, length (km), parallel count and impedance per conductor (r_ohm_per_km, x_ohm_per_km) of lines, indexed by line name (vectorised lookup), with the current (current_a, A) the whole line carries in the latest power flow (NaN before one), and the derating factor (df, 1 where the table has none), which pandapower multiplies the rating of the line by for its loading.
The impedance is that of the line table, which a line has whether or not its type is in the standard types.
- get_losses() dict[str, float][source]#
Calculate network losses.
- Returns:
Dictionary with active and reactive power losses.
- Return type:
Dict[str, float]
- get_network_metrics() dict[str, Any][source]#
Get various network metrics.
- Returns:
Dictionary with network metrics.
- Return type:
Dict[str, Any]
- get_open_links() list[tuple[str, str]][source]#
Pairs of bus names that an open switch alone keeps apart: the ends of a line in service opened by a line switch (a normally open point of a loop), and the buses of an open bus-bus switch.
- get_source_buses() set[str][source]#
Names of the buses that feed a galvanic zone: buses of the external grids in service and LV buses of the transformers in service that no open switch disconnects.
- get_transformer_max_power(transformer_type: str) float[source]#
Retrieves the maximum power rating of a specified transformer type.
This method returns the maximum power rating (in VA) for the requested transformer type by looking up the standard type information in the PandaPower network model.
- Parameters:
transformer_type (str) – The type of the transformer for which the maximum power rating has to be determined.
- Returns:
The maximum power rating for the specified transformer type in VA.
- Return type:
float
- Raises:
ValueError – If the transformer type is not found in the standard types.
- get_transformer_parallel(transformer_id: str) int[source]#
Get the number of parallel units of a transformer (1 for a single unit).
- get_transformer_parameters(transformer_id: str) dict[str, Any][source]#
Parameters of a two-winding transformer from its row of the transformer table, and its loading_percent, p_hv_mw and q_hv_mvar of the latest power flow (see PowerFlowEngine).
- Raises:
ValueError – If no network is loaded, or no transformer has that name, or several do.
- get_transformer_rating(transformer_id: str) float | None[source]#
Get the rating (VA) of one unit of a transformer, as the transformer table holds it, whether or not the unit has a catalogued type.
- Returns:
- The rating of one unit (sn_mva, not multiplied by the
parallel units), or None if the transformer is not found.
- Return type:
Optional[float]
- get_transformer_tap_position(transformer_id: str) float | None[source]#
The tap position of a transformer, None if it has none (NaN).
- Raises:
ValueError – If no transformer has that name, or several do.
- get_transformer_tap_positions(transformer_id: int | str) ndarray[source]#
Get all available tap positions for a given transformer in per unit voltage values.
This method returns all possible tap positions that can be set for the specified transformer, expressed as per unit voltage values (e.g., [-0.05, -0.025, 0, 0.025, 0.05]).
- Parameters:
transformer_id (Union[int, str]) – The ID of the transformer to get tap positions for.
- Returns:
Array of all available tap positions as per unit voltage values, typically sorted from lowest to highest.
- Return type:
np.ndarray
- Raises:
ValueError – If the transformer does not exist or if tap positions cannot be determined.
- get_transformer_type(transformer_id: str) str[source]#
Returns the type of a transformer based on the provided transformer ID.
- Parameters:
transformer_id (str) – The unique identifier (name) of the transformer.
- Returns:
The standard type of the transformer.
- Return type:
str
- Raises:
ValueError – If the network is not initialized or if the transformer is not found.
- get_transformer_type_parameters(transformer_type: str) dict[str, Any][source]#
Rating and impedance of a standard transformer type of the network.
- Raises:
ValueError – If no network is loaded, or the type is not a standard type.
- get_transformer_types_in_place() set[str | None][source]#
Get the standard types of the transformers in service of the network, None for those that have no type: a std_type of None, NaN or ‘’, as pandapower writes it for a unit created from its parameters.
- get_transformers_info() DataFrame[source]#
Type (std_type, as the table holds it) and number of units in parallel (parallel) of the two-winding transformers, in service or not, indexed by name.
- get_voltage_magnitude_range(component_id: int) dict[str, float][source]#
Get the minimum and maximum voltage magnitudes in a specific network component.
This method determines the voltage magnitude bounds within a given network component identified by its component_id.
- Parameters:
component_id (int) – The ID of the component to analyze.
- Returns:
Dictionary containing ‘min’ and ‘max’ voltage magnitude values in per unit.
- Return type:
Dict[str, float]
- Raises:
ValueError – If the network is not initialized, power flow hasn’t been run,
or if the component ID is invalid. –
- load_network(source: str | dict) None[source]#
Load a network from file or dictionary.
The results of the last run and the caches of the engine are forgotten, as whenever a network is assigned to network: a power flow must be run again.
- Parameters:
source (Union[str, Dict]) – Path to network file (.json, .p) or network dictionary.
- property network: Any#
The pandapower network of the engine.
- open_line(line_id: str, bus: int) None[source]#
Open a line by an open line switch at its end bus, as a normally-open point: the line stays in the network, in service, and carries no current (get_line_ids and get_line_endpoints leave it out, partition_network separates its ends).
A switch the line already has at that end is opened; otherwise one is created, of type
LBS, named<line>_open_at_<bus>(followed by_2… when a switch has that name).- Parameters:
line_id (str) – Name of the line.
bus (int) – Index of the end bus of the line the switch is at.
- Raises:
ValueError – If no network is loaded, if no line has that name or several do, or if bus is not one of its ends.
- partition_network() dict[int, Any][source]#
Partition the network into galvanically connected components.
This method identifies separate electrical areas in the network that are not connected to each other by power lines or other conducting elements, but can be connected by transformers.
- Returns:
Dictionary mapping component IDs to lists of elements (buses, lines, etc.) in each connected component.
- Return type:
Dict[int, Any]
- restore_line(line_id: str, saved: DataFrame) None[source]#
Give the line named line_id back the row save_line saved for it, every column as it was, its type and parameters as well as its conductors.
- Raises:
ValueError – If no network is loaded, or if saved is not the row of the line of that name.
- restore_solution(saved: dict[str, Any]) None[source]#
Put back the solution save_solution saved: copies of its result tables, so that it can be put back again, and what the run left besides them.
- Raises:
ValueError – If no network is loaded.
- restore_transformer(transformer_id: str, saved: DataFrame) None[source]#
Give the transformer named transformer_id back the row save_transformer saved for it, every column as it was, its type and parameters as well as its units.
- Raises:
ValueError – If no network is loaded, or if saved is not the row of the transformer of that name.
- run_power_flow(warm_start=False) dict[str, Any][source]#
Run power flow calculation on the current network.
- Parameters:
warm_start (bool, optional) – If True, start from the previous solution, which saves iterations after a small change. The run starts from scratch instead if there is no previous solution, if an angle that a transformer or an external grid applies has changed since it (see _phase_shifts), or if the warm start fails before any controller has acted. Warm and cold runs stop at the same tolerance, at different points within it, and end at the same solution after the Newton step below. Defaults to False.
Every run that converges ends with one more Newton step, from the power mismatch the solver left and the Jacobian at its solution (see _take_one_more_newton_step): the voltages, currents and loadings of the result tables, and the internal voltages from which the sensitivities are computed, are those of the solution after it.
- Returns:
Dictionary with power flow results and statistics.
- Return type:
Dict[str, Any]
- Raises:
PowerFlowNotConverged – If the power flow, or a controller run with it, does not converge. Whatever the way a run fails, the result tables of the network are then unusable and latest_results[“converged”] is False. The exception is a PandaPowerNotConverged, which is also pandapower’s LoadflowNotConverged (and its ControllerNotConverged when the controllers are what failed), so either can be caught.
ValueError – If a bus, a line, a transformer, a load or a static generator has no name, or the same name as another of its table (see check_names), or a load in service has a NaN ZIP share (see check_zip_shares), before any power flow; latest_results[“converged”] is then False.
- save_line(line_id: str) DataFrame[source]#
Save the row of the line table of the line named line_id, for restore_line.
- Returns:
A copy of the row, with its index.
- Return type:
pd.DataFrame
- Raises:
ValueError – If no network is loaded or no line has that name.
- save_network(target: str) None[source]#
Save the current network to a file.
- Parameters:
target (str) – Path where to save the network (.json, .p).
- save_solution() dict[str, Any][source]#
Save the solution of the latest power flow, for restore_solution: a copy of every result table (res_*), and what the engine and pandapower keep of the run, which the next run replaces rather than changes: the internal case (_ppc) and its lookups, from which the sensitivities are computed, the convergence flags, latest_results, and the Jacobian and its factors.
A power flow whose controllers act (run_control in the settings, with a controller in service) changes the network as well as its results: a tap moved by a controller in the power flow after a step would stay moved when the step is undone, and the solution put back would no longer be that of the network. Such a solution is not saved: the strategies then take their steps unchecked, as on an engine that cannot save a solution.
- Returns:
The saved solution.
- Return type:
dict
- Raises:
ValueError – If no network is loaded.
NotImplementedError – If the controllers act in the power flow.
- save_transformer(transformer_id: str) DataFrame[source]#
Save the row of the transformer table of the transformer named transformer_id, for restore_transformer.
- Returns:
A copy of the row, with its index.
- Return type:
pd.DataFrame
- Raises:
ValueError – If no network is loaded or no transformer has that name.
- set_line_parallel(line_id: str, parallel: int) int[source]#
Set the number of parallel conductors of the line named line_id, fewer than it has or more.
- Parameters:
line_id (str) – Name of the line.
parallel (int) – Its number of conductors, a whole number of 1 or more: an integer, or a float without a fractional part, of any numeric type, but not a boolean or a string.
- Returns:
The number of conductors of the line.
- Return type:
int
- Raises:
ValueError – If no network is loaded, if no line has that name, or if parallel is not a whole number of 1 or more.
- set_transformer_parallel(transformer_id: str, parallel: int) int[source]#
Set the number of parallel units of the transformer named transformer_id, fewer than it has or more.
- Parameters:
transformer_id (str) – Name of the transformer.
parallel (int) – Its number of units, a whole number of 1 or more: an integer, or a float without a fractional part, of any numeric type, but not a boolean or a string.
- Returns:
The number of units of the transformer.
- Return type:
int
- Raises:
ValueError – If no network is loaded, if no transformer has that name or several do, or if parallel is not a whole number of 1 or more.
- split_line(line_id: str, fraction: float) int[source]#
Put a new bus inside a line, at fraction of its length from its from_bus.
The line keeps its name, its index and every parameter, and runs from its from_bus to the new bus, over fraction of its length. A new line, a copy of its row (type, conductors in parallel, impedance, rating, derating factor, state), runs from the new bus to its to_bus over the rest. A switch of the line at its to_bus goes to the new line, which ends there. The new bus is a copy of the from_bus (add_bus).
The route of the line (get_line_geometry) is cut at fraction of its length, measured in a local equirectangular projection (the longitude scaled by the cosine of the latitude of the first point), each part running from the from_bus of its line; the new bus is at the cut. Without a route, the parts have none and the new bus no coordinates. The route and the electrical length are cut at the same fraction, even where the route is not as long as the line.
The new bus is
<line>_split_busand the new line<line>_split_line, followed by_2,_3… when another bus or line has that name.- Parameters:
line_id (str) – Name of the line.
fraction (float) – Where the new bus is, strictly between 0 and 1: a bus at an end would join the new bus to it by a line of no length.
- Returns:
Index of the new bus.
- Return type:
int
- Raises:
ValueError – If no network is loaded, if no line has that name or several do, or if fraction is not strictly between 0 and 1.
- unresolved_power_mva() float | None[source]#
The largest power mismatch, in MVA, that the last run left at a bus: the power that its solution does not resolve.
After the Newton step that ends a run (_take_one_more_newton_step), the rounding floor of the power balance at its solution (_rounding_floor), an upper bound of what the step leaves: 1.4e-11 to 3.5e-9 MVA on the MV/LV feeders at the load of the case study, whatever the tolerance. Where no step is taken, the bound of the solver, which compares the mismatch with its tolerance in per unit of the base power of the network, sn_mva: 1e-6 MVA (1 W) for the default 1e-8 at 100 MVA. None without a converged run of the engine.
- upgrade_line(line_id: str, new_type: str) None[source]#
Upgrade a line with new parameters.
- Parameters:
line_id (str) – Name of the line to upgrade.
new_type (str) – Type of the new line (must exist in standard_types).
- Raises:
ValueError – If the type is unknown, or no line has that name, or several do.
- upgrade_transformer(trafo_id: str, new_type: str) None[source]#
Upgrade a transformer with new parameters.
The units take every parameter of the new type but the vector group of the units in place: their phase shift (
shift_degree) and, where the table has the column, its name (vector_group), whatever the type is catalogued with. A replacement unit is one of the new rating, connected as the one it replaces: the network beyond it is not turned by the difference of shifts, 180 degrees from a Dyn11 unit to a Dyn5 type (#56). Three-winding transformers are not upgraded.Tap. A type change keeps what the tap position of the unit does to its LV voltage (#80). Where the tap changer of the new type gives a position the effect the unit’s gives it (the same side, neutral position, step and changer type, or neither applied by pandapower), the unit takes it. Where it does not, the unit keeps its own tap changer, as it keeps its vector group: a unit tapped on the LV side taken to a type tapped on the HV side (pandapower’s change_std_type copies the tap changer of the type and keeps the position) had the effect of its position reversed. Such a unit is one built like another (add_transformer with like), or one whose changer the data set apart from its type’s. If both are ratio tap changers that pandapower applies, without a phase shift per step, the range of the unit becomes the positions of its changer whose ratio is within the reach of the new type’s, to half a step of its own, whatever range it had: a type of -2 to 2 steps of 2.5 % on the HV side gives a unit of steps of 2.5 % on the LV side the range -2 to 2. The range then depends on the type the unit ends with, not on the types it went through; a position that a type in between could not reach was brought within that type’s range then (below), and stays there. A type whose changer pandapower does not apply (no side, a step of NaN or 0, no changer type: SimBench’s types), or one that is not a ratio changer or shifts the phase (a “Symmetrical” one, for instance), leaves the unit its own changer whole, with the range it has then: one that a type in between cut stays cut (the unit’s range from before is not kept).
A unit whose own tap changer pandapower does not apply (no changer type, as pandapower’s create_transformer_from_parameters leaves it, for instance) takes the type’s if it has no position (NaN) or is at the type’s neutral position, which changes no voltage. At another position, which does nothing now and would move its LV voltage on the type’s changer, it keeps its own, which stays inert, with a warning: set its position to neutral first to give it the type’s. The change of changer is logged.
The unit keeps its tap position, which is brought into the tap range it then has (
tap_mintotap_max) when it is outside, with a warning that names the transformer and both positions. Nothing changes, and nothing is logged, for a position within the range, or when the table has no range or position (NaN). A type without tap columns leaves the unit the range it had, and its position: pandapower’s change_std_type keeps the tap columns of the row then.- Parameters:
trafo_id (str) – Name of the transformer to upgrade.
new_type (str) – Type of the new transformer (must exist in standard_types).
- Raises:
ValueError – If the type is unknown, or no transformer has that name, or several do.
- exception gridforge.engines.pandapower_engine.PandaPowerNotConverged[source]#
Bases:
PowerFlowNotConverged,LoadflowNotConvergedRaised by PandaPowerEngine.run_power_flow when the power flow does not converge.
It is both the engine-independent PowerFlowNotConverged and pandapower’s LoadflowNotConverged, so that code written against pandapower, which catches the latter around a power flow, still sees a divergence.
- gridforge.engines.pandapower_engine.ZIP_SHARES = ['const_z_p_percent', 'const_z_q_percent', 'const_i_p_percent', 'const_i_q_percent']#
The shares of a load that are constant impedance and constant current, in percent of its power, in the names of pandapower 3: the rest is constant power. pandapower 3.2 has no such shares for the static generators, and ignores
const_z_percentandconst_i_percent, the names of pandapower 2. A list, not a tuple: pandas reads a tuple as one column label, so thatnet.load[ZIP_SHARES]selects the four columns.