distgridforge 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. distgridforge-0.3.0.dist-info/METADATA +266 -0
  2. distgridforge-0.3.0.dist-info/RECORD +38 -0
  3. distgridforge-0.3.0.dist-info/WHEEL +5 -0
  4. distgridforge-0.3.0.dist-info/licenses/LICENCE.txt +21 -0
  5. distgridforge-0.3.0.dist-info/top_level.txt +1 -0
  6. gridforge/__init__.py +32 -0
  7. gridforge/case_study/config.py +158 -0
  8. gridforge/case_study/dickert_lv_network_script.py +109 -0
  9. gridforge/case_study/mv_lv_feeder.py +314 -0
  10. gridforge/case_study/simbench_network_test_case.py +168 -0
  11. gridforge/core/__init__.py +0 -0
  12. gridforge/core/constraints.py +421 -0
  13. gridforge/core/cost_model.py +363 -0
  14. gridforge/core/grid_enhancement.py +1932 -0
  15. gridforge/core/power_flow.py +1146 -0
  16. gridforge/core/strategy.py +297 -0
  17. gridforge/engines/__init__.py +0 -0
  18. gridforge/engines/gridlabd_engine.py +527 -0
  19. gridforge/engines/opendss_engine.py +885 -0
  20. gridforge/engines/pandapower_engine.py +3766 -0
  21. gridforge/engines/roseau_engine.py +1234 -0
  22. gridforge/examples/__init__.py +0 -0
  23. gridforge/examples/quick_start.py +85 -0
  24. gridforge/main.py +0 -0
  25. gridforge/strategies/__init__.py +0 -0
  26. gridforge/strategies/flexibility.py +1476 -0
  27. gridforge/strategies/line_upgrade.py +1846 -0
  28. gridforge/strategies/path_to_source.py +596 -0
  29. gridforge/strategies/sizing.py +210 -0
  30. gridforge/strategies/step_check.py +183 -0
  31. gridforge/strategies/tap_change.py +267 -0
  32. gridforge/strategies/transformer_upgrade.py +622 -0
  33. gridforge/utils/__init__.py +0 -0
  34. gridforge/utils/config.py +55 -0
  35. gridforge/utils/interactive_plot.py +700 -0
  36. gridforge/utils/logging.py +86 -0
  37. gridforge/utils/plot.py +1078 -0
  38. gridforge/utils/reporting.py +0 -0
@@ -0,0 +1,3766 @@
1
+ """
2
+ PandaPower engine implementation for power flow analysis in GridForge.
3
+ """
4
+
5
+ import copy
6
+ import numbers
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandapower as pp
11
+ import pandas as pd
12
+ from pandas.api.types import infer_dtype
13
+ from scipy import sparse
14
+ from scipy.sparse.linalg import splu
15
+
16
+ from gridforge.core.power_flow import PowerFlowEngine, PowerFlowNotConverged
17
+
18
+ # Error of the sensitivities without a converged run of the engine for the network
19
+ _NO_CONVERGED_RUN = (
20
+ "No converged power flow of the engine for this network: call run_power_flow "
21
+ "before calculating sensitivities. They answer only from the engine's own run, whose "
22
+ "controllers converged and whose network passed check_names, not from the results "
23
+ "of a power flow run on the network outside the engine (pp.runpp)."
24
+ )
25
+
26
+ # Error of the sensitivities of a network that has changed since the last run
27
+ _STALE_TABLES = (
28
+ "The buses, lines or transformers of the network are not those of the last power "
29
+ "flow: run a power flow before calculating sensitivities."
30
+ )
31
+
32
+ # The tables and columns from which pandapower's topology graph (`create_nxgraph`, as
33
+ # `unsupplied_buses` calls it in pandapower 3.2) tells which buses no source supplies:
34
+ # its nodes, its edges, the switches it respects and the sources. The dead buses of the
35
+ # engine are recomputed whenever one of them changes, and only then.
36
+ _TOPOLOGY_TABLES = (
37
+ "bus",
38
+ "line",
39
+ "trafo",
40
+ "trafo3w",
41
+ "impedance",
42
+ "dcline",
43
+ "tcsc",
44
+ "vsc",
45
+ "line_dc",
46
+ "bus_dc",
47
+ "switch",
48
+ "ext_grid",
49
+ "gen",
50
+ )
51
+ _TOPOLOGY_COLUMNS = (
52
+ "in_service",
53
+ "bus",
54
+ "from_bus",
55
+ "to_bus",
56
+ "hv_bus",
57
+ "mv_bus",
58
+ "lv_bus",
59
+ "bus_dc",
60
+ "from_bus_dc",
61
+ "to_bus_dc",
62
+ "element",
63
+ "et",
64
+ "closed",
65
+ "slack",
66
+ "control_mode_ac",
67
+ )
68
+
69
+
70
+ class PandaPowerNotConverged(PowerFlowNotConverged, pp.LoadflowNotConverged):
71
+ """
72
+ Raised by `PandaPowerEngine.run_power_flow` when the power flow does not converge.
73
+
74
+ It is both the engine-independent `PowerFlowNotConverged` and pandapower's
75
+ `LoadflowNotConverged`, so that code written against pandapower, which catches the
76
+ latter around a power flow, still sees a divergence.
77
+ """
78
+
79
+
80
+ class PandaPowerControllerNotConverged(
81
+ PandaPowerNotConverged, pp.ControllerNotConverged
82
+ ):
83
+ """
84
+ Raised by `PandaPowerEngine.run_power_flow` when the controllers do not converge.
85
+
86
+ As `PandaPowerNotConverged`, and pandapower's `ControllerNotConverged` as well.
87
+ """
88
+
89
+
90
+ class PandaPowerEngine(PowerFlowEngine):
91
+ """
92
+ Interface to PandaPower for power flow calculations and network analysis.
93
+
94
+ This engine provides methods to:
95
+
96
+ 1. Load network models
97
+ 2. Run power flow calculations
98
+ 3. Apply network modifications
99
+ 4. Check constraint violations
100
+ 5. Extract results and metrics
101
+
102
+ Buses, lines and transformers are identified by their name: in the violations, the
103
+ sensitivities, the actions of the strategies and the paths they search. Loads and
104
+ static generators are identified by their index (`get_flexibility_data`,
105
+ `apply_flexibility_action`, the flexibility actions), but `flexibility_settings` is
106
+ keyed by their name. Each of these elements must therefore have a name (not None,
107
+ NaN or ""), and two buses, two lines, two transformers, two loads or two static
108
+ generators must not have the same, which `check_names` checks, and `run_power_flow`
109
+ before each run; elements of different tables may share one (a bus and a line, a
110
+ load and a static generator). `fill_missing_names` names the elements that have no
111
+ name.
112
+ """
113
+
114
+ def __init__(self, config: dict[str, Any] | None = None):
115
+ """
116
+ Initialize PandaPower engine.
117
+
118
+ Args:
119
+ config (Optional[Dict[str, Any]], optional): Configuration dictionary with PandaPower specific settings. Defaults to None.
120
+ """
121
+ # Jacobian at the solution of the last run, with the voltages it was built at
122
+ self._jacobian_cache: tuple[np.ndarray, sparse.csr_matrix] | None = None
123
+ # LU factors of that Jacobian, with the Jacobian they factorise
124
+ self._jacobian_lu_cache: tuple[sparse.csr_matrix, Any] | None = None
125
+ # Dead buses (see `_dead_buses`), with the topology they were found in
126
+ self._dead_buses_cache: tuple[tuple, frozenset[int]] | None = None
127
+ super().__init__(config)
128
+
129
+ @property
130
+ def network(self) -> Any:
131
+ """The pandapower network of the engine."""
132
+ return self._network
133
+
134
+ @network.setter
135
+ def network(self, network: Any) -> None:
136
+ # What the engine remembers of the last run describes the former network: with
137
+ # the same buses, its results would otherwise pass for those of the new one, in
138
+ # `check_violations` and as the starting point of a warm start. To put back a
139
+ # network together with its results, assign `latest_results` after it.
140
+ self._network = network
141
+ self.latest_results = None
142
+ self.network_partition = None
143
+ self._jacobian_cache = None
144
+ self._jacobian_lu_cache = None
145
+ self._dead_buses_cache = None
146
+
147
+ def __getstate__(self) -> dict[str, Any]:
148
+ """
149
+ State of the engine for `pickle` and `copy`, without the caches.
150
+
151
+ The LU factors of the Jacobian cannot be pickled, and the caches are rebuilt on
152
+ demand from the solution and the topology, which the network carries.
153
+ """
154
+ state = self.__dict__.copy()
155
+ state["_jacobian_cache"] = None
156
+ state["_jacobian_lu_cache"] = None
157
+ state["_dead_buses_cache"] = None
158
+ return state
159
+
160
+ def __setstate__(self, state: dict[str, Any]) -> None:
161
+ """
162
+ Restore an engine, including one pickled by a gridforge that had fewer caches.
163
+
164
+ A cache the state lacks starts empty, as `__getstate__` leaves the others.
165
+ """
166
+ self.__dict__.update(state)
167
+ for cache in ("_jacobian_cache", "_jacobian_lu_cache", "_dead_buses_cache"):
168
+ self.__dict__.setdefault(cache, None)
169
+
170
+ def fill_missing_names(self):
171
+ """
172
+ Name the buses, lines, transformers, loads and static generators that have no
173
+ name (None, NaN or "").
174
+
175
+ The names are ``bus_<index>``, ``line_<index>_<from bus>_to_<to bus>``,
176
+ ``trafo_<index>_<hv bus>_to_<lv bus>``, ``load_<index>_<bus>`` and
177
+ ``sgen_<index>_<bus>``, after the buses are named. A name that another element
178
+ of the same table already has is followed by ``_2`` (or ``_3``, and so on,
179
+ until it is free), so that the names given are never shared: a bus without a
180
+ name at index 3 next to a bus called ``bus_3`` is called ``bus_3_2``. Names
181
+ already there, shared or not, are left as they are: `check_names` reports the
182
+ shared ones, which are for the caller to change. Call it before the first power
183
+ flow: `check_names` refuses unnamed elements.
184
+
185
+ A load or a static generator named here has no entry in `flexibility_settings`,
186
+ and so no flexibility, until one is given under its new name.
187
+ """
188
+ net = self.network
189
+
190
+ def fill(table: pd.DataFrame, names_of) -> None:
191
+ column = table.get("name")
192
+ if column is None:
193
+ column = pd.Series(None, index=table.index, dtype=object)
194
+ missing = column.isna() | (column == "")
195
+ if not missing.any():
196
+ return
197
+ # A missing column, or one that cannot take a new string (categorical, all
198
+ # NaN as a float), becomes a column of objects
199
+ if column.dtype != object:
200
+ column = column.astype(object)
201
+ table["name"] = column
202
+ taken = set(column[~missing])
203
+ given = []
204
+ for name in names_of(table.loc[missing]):
205
+ free, k = name, 1
206
+ while free in taken:
207
+ k += 1
208
+ free = f"{name}_{k}"
209
+ taken.add(free)
210
+ given.append(free)
211
+ table.loc[missing, "name"] = given
212
+
213
+ def bus_names(buses: pd.Series) -> list[str]:
214
+ return net.bus.loc[buses, "name"].astype(str).tolist()
215
+
216
+ fill(net.bus, lambda rows: [f"bus_{i}" for i in rows.index])
217
+ # After the buses, whose names are in those of the branches
218
+ fill(
219
+ net.line,
220
+ lambda rows: [
221
+ f"line_{i}_{f}_to_{t}"
222
+ for i, f, t in zip(
223
+ rows.index,
224
+ bus_names(rows["from_bus"]),
225
+ bus_names(rows["to_bus"]),
226
+ strict=True,
227
+ )
228
+ ],
229
+ )
230
+ fill(
231
+ net.trafo,
232
+ lambda rows: [
233
+ f"trafo_{i}_{hv}_to_{lv}"
234
+ for i, hv, lv in zip(
235
+ rows.index,
236
+ bus_names(rows["hv_bus"]),
237
+ bus_names(rows["lv_bus"]),
238
+ strict=True,
239
+ )
240
+ ],
241
+ )
242
+ for element in ("load", "sgen"):
243
+ table = getattr(net, element, None)
244
+ if table is None or table.empty:
245
+ continue
246
+ fill(
247
+ table,
248
+ lambda rows, element=element: [
249
+ f"{element}_{i}_{bus}"
250
+ for i, bus in zip(rows.index, bus_names(rows["bus"]), strict=True)
251
+ ],
252
+ )
253
+
254
+ def create_empty_network(
255
+ self, name: str = "grid-forge-network", f_hz: float = 50.0
256
+ ) -> None:
257
+ """
258
+ Create an empty pandapower network.
259
+
260
+ Args:
261
+ name (str, optional): Name of the network. Defaults to "grid-forge-network".
262
+ f_hz (float, optional): System frequency in Hz. Defaults to 50.0.
263
+ """
264
+ self.network = pp.create_empty_network(name=name, f_hz=f_hz)
265
+ self.logger.info(f"Created empty network: {name}")
266
+
267
+ def create_bus(self, name: str, nominal_voltage_v: float, **kwargs: Any):
268
+ """
269
+ Create a new bus in the PandaPower network.
270
+
271
+ Args:
272
+ name (str): Name of the bus.
273
+ nominal_voltage_v (float): Nominal voltage of the bus in kV.
274
+ **kwargs: Additional parameters for the bus.
275
+
276
+ Returns:
277
+ int: Index of the created bus.
278
+ """
279
+ if self.network is None:
280
+ raise ValueError("Network not initialized. Create or load a network first.")
281
+
282
+ # Convert generic parameters to pandapower-specific parameters
283
+ pp_params = {"name": name, "vn_kv": nominal_voltage_v * 1.0e-3}
284
+
285
+ # Add any additional parameters
286
+ pp_params.update(kwargs)
287
+
288
+ # Create the bus in the pandapower network
289
+ return pp.create_bus(self.network, **pp_params)
290
+
291
+ def create_load(
292
+ self,
293
+ bus_name: str,
294
+ name: str,
295
+ active_power_w: float,
296
+ reactive_power_var: float,
297
+ **kwargs: Any,
298
+ ):
299
+ """
300
+ Create a new load in the PandaPower network.
301
+
302
+ Args:
303
+ bus_name (str): Name of the bus where the load is connected.
304
+ name (str): Name of the load.
305
+ active_power_w (float): Active power of the load in W.
306
+ reactive_power_var (float): Reactive power of the load in VAr.
307
+ **kwargs: Additional parameters for the load. `max_flex_pct` is the
308
+ share of its active power, in percent, that `FlexibilityStrategy` can
309
+ take off, counted from its power as each run starts, or at each call
310
+ of a strategy used on its own (see `FlexibilityStrategy.initial_power`
311
+ for a strategy called several times).
312
+
313
+ Returns:
314
+ int: Index of the created load.
315
+
316
+ Raises:
317
+ ValueError: If `name` is None, NaN or "", or the name of a load already in
318
+ the network, before anything is created: its `max_flex_pct` would be
319
+ stored under the name of the other load, whose flexibility it would
320
+ change, and `check_names` refuses such a network anyway.
321
+ """
322
+ if self.network is None:
323
+ raise ValueError("Network not initialized. Create or load a network first.")
324
+ self._refuse_name_of_a_new_element("load", "load", name)
325
+
326
+ buses = self.network.bus
327
+ bus_id = buses.loc[buses["name"] == bus_name].index[0]
328
+ # Convert generic parameters to pandapower-specific parameters
329
+ pp_params = {
330
+ "bus": bus_id,
331
+ "name": name,
332
+ "p_mw": round(active_power_w * 1.0e-6, 6),
333
+ "q_mvar": round(reactive_power_var * 1.0e-6, 6),
334
+ }
335
+
336
+ # Store flexibility setting if provided
337
+ if "max_flex_pct" in kwargs:
338
+ self.flexibility_settings["load"][name] = kwargs.pop("max_flex_pct")
339
+
340
+ # Add any additional parameters
341
+ pp_params.update(kwargs)
342
+
343
+ # Create the load in the pandapower network
344
+ return pp.create_load(self.network, **pp_params)
345
+
346
+ def create_generator(
347
+ self,
348
+ bus_name: str,
349
+ name: str,
350
+ active_power_w: float,
351
+ reactive_power_var: float,
352
+ **kwargs: Any,
353
+ ):
354
+ """
355
+ Create a new static generator in the PandaPower network.
356
+
357
+ Args:
358
+ bus_name (str): Name of the bus where the generator is connected.
359
+ name (str): Name of the generator.
360
+ active_power_w (float): Active power of the generator in W.
361
+ reactive_power_var (float): Reactive power of the generator in VAr.
362
+ **kwargs: Additional parameters for the generator. `max_flex_pct` is the
363
+ share of its active power, in percent, that `FlexibilityStrategy` can
364
+ take off, counted from its power as each run starts, or at each call
365
+ of a strategy used on its own (see `FlexibilityStrategy.initial_power`
366
+ for a strategy called several times).
367
+
368
+ Returns:
369
+ int: Index of the created generator.
370
+
371
+ Raises:
372
+ ValueError: If `name` is None, NaN or "", or the name of a static generator
373
+ already in the network, before anything is created: its `max_flex_pct`
374
+ would be stored under the name of the other generator, whose flexibility
375
+ it would change, and `check_names` refuses such a network anyway.
376
+ """
377
+ if self.network is None:
378
+ raise ValueError("Network not initialized. Create or load a network first.")
379
+ self._refuse_name_of_a_new_element("sgen", "static generator", name)
380
+
381
+ buses = self.network.bus
382
+ bus_id = buses.loc[buses["name"] == bus_name].index[0]
383
+
384
+ # Convert generic parameters to pandapower-specific parameters
385
+ pp_params = {
386
+ "bus": bus_id,
387
+ "name": name,
388
+ "p_mw": round(active_power_w * 1.0e-6, 6),
389
+ "q_mvar": round(reactive_power_var * 1.0e-6, 6),
390
+ }
391
+
392
+ # Store flexibility setting if provided
393
+ if "max_flex_pct" in kwargs:
394
+ self.flexibility_settings["sgen"][name] = kwargs.pop("max_flex_pct")
395
+
396
+ # Add any additional parameters
397
+ pp_params.update(kwargs)
398
+
399
+ # Create the static generator in the pandapower network
400
+ return pp.create_sgen(self.network, **pp_params)
401
+
402
+ def _refuse_name_of_a_new_element(
403
+ self, element: str, label: str, name: Any
404
+ ) -> None:
405
+ """
406
+ Raise a ValueError if an element of the table `element` cannot be created with
407
+ `name`: it is None, NaN or "", or another element of the table has it.
408
+ """
409
+ # pd.isna first: NA (pd.NA) cannot be compared with ""
410
+ if (
411
+ name is None
412
+ or (pd.api.types.is_scalar(name) and pd.isna(name))
413
+ or name == ""
414
+ ):
415
+ raise ValueError(
416
+ f"A {label} must have a name (not None, NaN or ''), by which its "
417
+ "flexibility settings are kept and `check_names` tells it apart."
418
+ )
419
+ table = getattr(self.network, element, None)
420
+ if table is None or "name" not in table.columns:
421
+ return
422
+ taken = table.index[table["name"] == name]
423
+ if len(taken):
424
+ raise ValueError(
425
+ f"A {label} named {name!r} is already in the network (index "
426
+ f"{', '.join(str(i) for i in taken)}): two {label}s must not share a name, "
427
+ "by which their flexibility settings are kept."
428
+ )
429
+
430
+ def create_line(
431
+ self,
432
+ name: str,
433
+ from_bus: str,
434
+ to_bus: str,
435
+ length_km: float,
436
+ line_type: str,
437
+ **kwargs: Any,
438
+ ):
439
+ """
440
+ Create a new line in the PandaPower network.
441
+
442
+ Args:
443
+ name (str): Name of the line.
444
+ from_bus (int): ID of the starting bus.
445
+ to_bus (int): ID of the ending bus.
446
+ length_km (float): Length of the line in kilometers.
447
+ line_type (str): Type of the line (refers to standard types in pandapower).
448
+ **kwargs: Additional parameters for the line.
449
+
450
+ Returns:
451
+ int: Index of the created line.
452
+ """
453
+ if self.network is None:
454
+ raise ValueError("Network not initialized. Create or load a network first.")
455
+
456
+ buses = self.network.bus
457
+ from_bus_id = buses.loc[buses["name"] == from_bus].index[0]
458
+ to_bus_id = buses.loc[buses["name"] == to_bus].index[0]
459
+ # Convert generic parameters to pandapower-specific parameters
460
+ pp_params = {
461
+ "name": name,
462
+ "from_bus": from_bus_id,
463
+ "to_bus": to_bus_id,
464
+ "length_km": length_km,
465
+ "std_type": line_type,
466
+ }
467
+
468
+ # Add any additional parameters
469
+ pp_params.update(kwargs)
470
+
471
+ # Create the line in the pandapower network
472
+ return pp.create_line(self.network, **pp_params)
473
+
474
+ def create_ext_grid(
475
+ self,
476
+ bus_name: str,
477
+ name: str,
478
+ voltage_reference_pu: float,
479
+ angle_reference_degree: float = 0,
480
+ **kwargs: Any,
481
+ ):
482
+ """
483
+ Create a new external grid connection in the PandaPower network.
484
+
485
+ Args:
486
+ bus_name (str): Name of the bus where the external grid is connected.
487
+ name (str): Name of the external grid.
488
+ voltage_reference_pu (float): Voltage magnitude in per unit.
489
+ angle_reference_degree (float, optional): Voltage angle in degrees. Defaults to 0.
490
+ **kwargs: Additional parameters for the external grid.
491
+
492
+ Returns:
493
+ int: Index of the created external grid.
494
+ """
495
+ if self.network is None:
496
+ raise ValueError("Network not initialized. Create or load a network first.")
497
+
498
+ buses = self.network.bus
499
+ bus_id = buses.loc[buses["name"] == bus_name].index[0]
500
+
501
+ # Convert generic parameters to pandapower-specific parameters
502
+ pp_params = {
503
+ "bus": bus_id,
504
+ "name": name,
505
+ "vm_pu": voltage_reference_pu,
506
+ "va_degree": angle_reference_degree,
507
+ }
508
+
509
+ # Add any additional parameters
510
+ pp_params.update(kwargs)
511
+
512
+ # Create the external grid in the pandapower network
513
+ return pp.create_ext_grid(self.network, **pp_params)
514
+
515
+ def create_transformer(
516
+ self, name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any
517
+ ):
518
+ """
519
+ Create a new transformer in the PandaPower network.
520
+
521
+ Args:
522
+ name (str): Name of the transformer.
523
+ hv_bus (str): Name of the high voltage bus.
524
+ lv_bus (str): Name of the low voltage bus.
525
+ transformer_type (str): Type of the transformer (refers to standard types in pandapower).
526
+ **kwargs: Additional parameters for the transformer.
527
+
528
+ Returns:
529
+ int: Index of the created transformer.
530
+ """
531
+ if self.network is None:
532
+ raise ValueError("Network not initialized. Create or load a network first.")
533
+
534
+ buses = self.network.bus
535
+ hv_bus_id = buses.loc[buses["name"] == hv_bus].index[0]
536
+ lv_bus_id = buses.loc[buses["name"] == lv_bus].index[0]
537
+
538
+ # Convert generic parameters to pandapower-specific parameters
539
+ pp_params = {
540
+ "name": name,
541
+ "hv_bus": hv_bus_id,
542
+ "lv_bus": lv_bus_id,
543
+ "std_type": transformer_type,
544
+ }
545
+
546
+ # Add any additional parameters
547
+ pp_params.update(kwargs)
548
+
549
+ # Create the transformer in the pandapower network
550
+ return pp.create_transformer(self.network, **pp_params)
551
+
552
+ def load_network(self, source: str | dict) -> None:
553
+ """
554
+ Load a network from file or dictionary.
555
+
556
+ The results of the last run and the caches of the engine are forgotten, as
557
+ whenever a network is assigned to `network`: a power flow must be run again.
558
+
559
+ Args:
560
+ source (Union[str, Dict]): Path to network file (.json, .p) or network dictionary.
561
+ """
562
+ self.logger.info("Loading network")
563
+
564
+ if isinstance(source, str):
565
+ if source.endswith(".json"):
566
+ self.network = pp.from_json(source)
567
+ elif source.endswith(".p"):
568
+ self.network = pp.from_pickle(source)
569
+ elif source.endswith(".xlsx"):
570
+ self.network = pp.from_excel(source)
571
+ else:
572
+ raise ValueError(f"Unsupported file format: {source}")
573
+
574
+ elif isinstance(source, dict):
575
+ self.network = pp.from_json_dict(source)
576
+
577
+ else:
578
+ raise TypeError("Source must be a file path or network dictionary")
579
+
580
+ self.logger.info(
581
+ f"Loaded network with {len(self.network.bus)} buses, "
582
+ f"{len(self.network.line)} lines, and {len(self.network.trafo)} transformers"
583
+ )
584
+
585
+ def save_network(self, target: str) -> None:
586
+ """
587
+ Save the current network to a file.
588
+
589
+ Args:
590
+ target (str): Path where to save the network (.json, .p).
591
+ """
592
+ if not self.network:
593
+ raise ValueError("No network loaded to save")
594
+
595
+ if target.endswith(".json"):
596
+ pp.to_json(self.network, target)
597
+ elif target.endswith(".p"):
598
+ pp.to_pickle(self.network, target)
599
+ elif target.endswith(".xlsx"):
600
+ pp.to_excel(self.network, target)
601
+ else:
602
+ raise ValueError(f"Unsupported file format: {target}")
603
+
604
+ self.logger.info(f"Network saved to {target}")
605
+
606
+ def run_power_flow(self, warm_start=False) -> dict[str, Any]:
607
+ """
608
+ Run power flow calculation on the current network.
609
+
610
+ Args:
611
+ warm_start (bool, optional): If True, start from the previous solution, which
612
+ saves iterations after a small change. The run starts from scratch
613
+ instead if there is no previous solution, if an angle that a
614
+ transformer or an external grid applies has changed since it (see
615
+ `_phase_shifts`), or if the warm start fails before any
616
+ controller has acted. Warm and cold runs stop at the same
617
+ tolerance, at different points within it, and end at the same
618
+ solution after the Newton step below. Defaults to False.
619
+
620
+ Every run that converges ends with one more Newton step, from the power
621
+ mismatch the solver left and the Jacobian at its solution (see
622
+ `_take_one_more_newton_step`): the voltages, currents and loadings of the result
623
+ tables, and the internal voltages from which the sensitivities are computed,
624
+ are those of the solution after it.
625
+
626
+ Returns:
627
+ Dict[str, Any]: Dictionary with power flow results and statistics.
628
+
629
+ Raises:
630
+ PowerFlowNotConverged: If the power flow, or a controller run with it, does not
631
+ converge. Whatever the way a run fails, the result tables of the network
632
+ are then unusable and `latest_results["converged"]` is False. The
633
+ exception is a `PandaPowerNotConverged`, which is also pandapower's
634
+ `LoadflowNotConverged` (and its `ControllerNotConverged` when the
635
+ controllers are what failed), so either can be caught.
636
+ ValueError: If a bus, a line, a transformer, a load or a static generator
637
+ has no name, or the same name as another of its table (see
638
+ `check_names`), before any power flow;
639
+ `latest_results["converged"]` is then False.
640
+ """
641
+ if not self.network:
642
+ raise ValueError("No network loaded for power flow calculation")
643
+
644
+ self.logger.info("Running power flow calculation")
645
+
646
+ # Until this run succeeds, the results of the previous one must not pass for the
647
+ # current ones: a run that fails, in whatever way, leaves unusable (NaN) result
648
+ # tables, and `check_violations` would otherwise still read them as converged.
649
+ # Nothing that can fail runs before: what the warm start needs of them is kept
650
+ # here.
651
+ previous = self.latest_results
652
+ self.latest_results = {"converged": False, "iterations": None, "time": None}
653
+ # The Jacobian of the previous solution will not be needed again
654
+ self._jacobian_cache = None
655
+ self._jacobian_lu_cache = None
656
+ # Start from the previous solution only if there is one for this network: a failed
657
+ # run leaves NaN result tables, which are no starting point, and a solution with
658
+ # other applied angles is the new one rotated (see `_phase_shifts`).
659
+ shifts = self._phase_shifts()
660
+ warm_start = (
661
+ warm_start
662
+ and self._has_solution(previous)
663
+ and self._same_phase_shifts(previous.get("_phase_shifts"), shifts)
664
+ )
665
+ # After the line above, so that a refused network has no results to answer from
666
+ self.check_names()
667
+
668
+ try:
669
+ # pandapower raises LoadflowNotConverged instead of returning a non-converged
670
+ # network.
671
+ # A warm start must not make a network fail that a cold one solves, so a
672
+ # failed one is retried from scratch, but only on the network the caller
673
+ # asked to solve: once the controllers have acted (tap positions,
674
+ # setpoints), a failure is final. With controllers, the warm start is
675
+ # therefore first tried without them, at the cost of one more run, which
676
+ # starts at the solution.
677
+ controlled = warm_start and self._controllers_act()
678
+ try:
679
+ self._run_pandapower(warm_start, with_controllers=not controlled)
680
+ except pp.LoadflowNotConverged:
681
+ # Not ControllerNotConverged: a failed controller loop has already
682
+ # changed the network.
683
+ if not warm_start:
684
+ raise
685
+ self.logger.info("Warm-started power flow failed, solving from scratch")
686
+ warm_start = False
687
+ self._run_pandapower(warm_start)
688
+ else:
689
+ if controlled:
690
+ self._run_pandapower(warm_start)
691
+
692
+ residual = self._take_one_more_newton_step()
693
+ if residual is None:
694
+ # No step: the solver's own bound
695
+ residual = self.pf_settings["generic"]["tolerance"]
696
+
697
+ # Store results for later use
698
+ self.latest_results = {
699
+ "converged": self.network.converged,
700
+ "iterations": self.network._ppc.get("iterations", None),
701
+ "time": self.network._ppc.get("et", 0.0), # execution time
702
+ # The power mismatch left at a bus, MVA (see `unresolved_power_mva`)
703
+ "unresolved_mva": float(residual) * float(self.network.sn_mva),
704
+ # What the solution was solved with, for the next warm start: it comes
705
+ # back with the results when a network is put back with them
706
+ "_phase_shifts": shifts,
707
+ }
708
+
709
+ self.logger.info(
710
+ f"Power flow calculation finished: converged={self.network.converged}, "
711
+ f"iterations={self.latest_results['iterations']}"
712
+ )
713
+
714
+ return self.latest_results
715
+
716
+ except (pp.LoadflowNotConverged, pp.ControllerNotConverged) as e:
717
+ # ControllerNotConverged comes from `run_control=True` in the power flow
718
+ # settings; it is a sibling of LoadflowNotConverged, not a subclass.
719
+ self.logger.warning(f"Power flow did not converge: {str(e)}")
720
+ error = (
721
+ PandaPowerControllerNotConverged
722
+ if isinstance(e, pp.ControllerNotConverged)
723
+ else PandaPowerNotConverged
724
+ )
725
+ raise error(str(e)) from e
726
+
727
+ except Exception as e:
728
+ self.logger.error(f"Power flow calculation failed: {str(e)}")
729
+ raise
730
+
731
+ def _has_solution(self, results: dict[str, Any] | None = None) -> bool:
732
+ """
733
+ Tell whether the result tables hold a converged solution of every bus of this network.
734
+
735
+ A converged run leaves NaN voltages at the buses it found isolated. If a strategy
736
+ has since reconnected one, a warm start would start Newton from NaN and fail.
737
+
738
+ Args:
739
+ results: The results of the run that left the tables, `latest_results`
740
+ if not given.
741
+ """
742
+ net = self.network
743
+ results = self.latest_results if results is None else results
744
+ return bool(
745
+ net is not None
746
+ and results
747
+ and results.get("converged")
748
+ and net.res_bus.index.equals(net.bus.index)
749
+ and not net.res_bus[["vm_pu", "va_degree"]].isna().to_numpy().any()
750
+ )
751
+
752
+ # The elements that apply an angle, with the columns of the angle they apply: the
753
+ # transformers, the three-winding transformers, and the external grids
754
+ _ANGLE_ELEMENTS = (
755
+ ("trafo", ("shift_degree",)),
756
+ ("trafo3w", ("shift_mv_degree", "shift_lv_degree")),
757
+ ("ext_grid", ("va_degree",)),
758
+ )
759
+
760
+ def _phase_shifts(self) -> tuple:
761
+ """
762
+ What the angles of the voltages of the next run are set by, to tell whether
763
+ the previous solution is a start for it:
764
+
765
+ - whether the power flow calculates the angles at all
766
+ (``calculate_voltage_angles``);
767
+ - what connects the network and supplies it (`_topology_key`): the service
768
+ state of the buses, lines, transformers, impedances, DC lines and sources,
769
+ the buses each joins, the state of every switch, which generator is the
770
+ slack;
771
+ - for each transformer, three-winding transformer and external grid, keyed by
772
+ its index, the angle it applies (``shift_degree``, ``shift_mv_degree`` and
773
+ ``shift_lv_degree``, ``va_degree``) and, for a transformer whose tap adds an
774
+ angle (`_tap_angle_rows`), every column of its tap changer (``tap_*``,
775
+ ``tap2_*``, ``id_characteristic_table``).
776
+
777
+ Missing values are None, so that the values, in tuples and dictionaries,
778
+ compare as values, and results that hold them do as well.
779
+
780
+ A change of the angle an element applies rotates the voltages of every bus
781
+ beyond it by that angle, and a change of what connects them can move buses
782
+ behind a source of another angle: the previous solution, rotated, is the new
783
+ one. Newton-Raphson started from the previous solution unrotated starts that
784
+ far from it, 30 to 180 degrees for a change of vector group, and can converge to
785
+ another solution of the power flow equations: on a 1.6 MVA unit loaded at
786
+ 75 %, it reached one at 0.05 p.u. after a change of its shift by 90 or 180
787
+ degrees (and failed at 120 and 150), and on a three-winding transformer one at
788
+ 0.06 p.u. after 60 degrees (#56). The same happened when the supply moved to a
789
+ unit of another shift (in service, terminal switches), a feeder to a substation
790
+ of another shift (lines in and out of service, line or bus switches), and when
791
+ an ideal phase shifter of 5 degrees a step moved 10 steps at once. A warm start
792
+ is therefore not made after any change of what this gives (`run_power_flow`),
793
+ whatever the angle: no rule tells from the angle alone which start converges
794
+ where, and a cold start is always right. The inputs of the angles are compared,
795
+ not the angles pandapower computes from them, which only a run gives: a change
796
+ of them that turns the voltages little also starts from scratch. No strategy
797
+ changes the topology or the angles: their warm starts are kept.
798
+
799
+ Not seen: a change of the characteristic table of a tabular tap changer
800
+ (``trafo_characteristic_table``), whose rows are not compared.
801
+ """
802
+ net = self.network
803
+ angles = [
804
+ self.pf_settings["specific"].get("calculate_voltage_angles", True),
805
+ self._topology_key(),
806
+ ]
807
+ for element, columns in self._ANGLE_ELEMENTS:
808
+ table = getattr(net, element, None)
809
+ angles.append(
810
+ {}
811
+ if table is None or not len(table)
812
+ else self._applied_angles(table, columns)
813
+ )
814
+ return tuple(angles)
815
+
816
+ @classmethod
817
+ def _applied_angles(cls, table: pd.DataFrame, columns: tuple[str, ...]) -> dict:
818
+ """
819
+ The `columns` of each element of `table`, by index, with the columns of the
820
+ tap changer of those whose tap adds an angle (see `_phase_shifts`).
821
+ """
822
+ names = set(table.columns)
823
+ rows = list(
824
+ zip(
825
+ *(cls._plain(table[column]) for column in columns if column in names),
826
+ strict=True,
827
+ )
828
+ )
829
+ tap = cls._tap_angle_rows(table, names)
830
+ if tap.any():
831
+ tap_rows = list(
832
+ zip(
833
+ *(
834
+ cls._plain(table[column])
835
+ for column in table.columns
836
+ if column.startswith("tap")
837
+ or column == "id_characteristic_table"
838
+ ),
839
+ strict=True,
840
+ )
841
+ )
842
+ rows = [
843
+ row + tap_row if with_tap else row
844
+ for row, tap_row, with_tap in zip(rows, tap_rows, tap, strict=True)
845
+ ]
846
+ return dict(zip(table.index.tolist(), rows, strict=True))
847
+
848
+ @staticmethod
849
+ def _tap_angle_rows(table: pd.DataFrame, names: set[str]) -> np.ndarray:
850
+ """
851
+ Which transformers of `table` have a tap that adds an angle to their shift:
852
+ pandapower's ideal phase shifters (``tap_changer_type`` "Ideal"), tap changers
853
+ of another type whose step has an angle (``tap_step_degree`` other than 0 and
854
+ NaN), tabular ones (``tap_dependency_table``), and those of the former
855
+ ``tap_phase_shifter`` flag; for the second tap changer (``tap2_*``) as well. A
856
+ ratio tap changer of no angle, as those of the MV/LV feeders, is not one: its
857
+ tap moves the voltages a little, and does not rotate them.
858
+ """
859
+ rows = np.zeros(len(table), dtype=bool)
860
+ for tap in ("tap", "tap2"):
861
+ if f"{tap}_changer_type" in names:
862
+ kinds = table[f"{tap}_changer_type"].to_numpy(dtype=object)
863
+ rows |= kinds == "Ideal"
864
+ if f"{tap}_step_degree" in names:
865
+ degrees = table[f"{tap}_step_degree"].to_numpy(
866
+ dtype=float, na_value=np.nan
867
+ )
868
+ # Not 0, not NaN
869
+ stepped = (degrees != 0.0) & (degrees == degrees)
870
+ if stepped.any():
871
+ rows |= stepped & pd.notna(kinds)
872
+ for flag in (f"{tap}_dependency_table", f"{tap}_phase_shifter"):
873
+ if flag in names:
874
+ rows |= table[flag].to_numpy(dtype=object) == True # noqa: E712
875
+ return rows
876
+
877
+ @staticmethod
878
+ def _plain(column: pd.Series) -> list:
879
+ """
880
+ The values of `column` as Python values, None for a missing one (NaN, None,
881
+ pd.NA, NaT) whatever its type, nullable extension types included: pd.NA
882
+ cannot be compared.
883
+ """
884
+ dtype = column.dtype
885
+ if isinstance(dtype, np.dtype) and dtype.kind in "iub":
886
+ return column.tolist()
887
+ if isinstance(dtype, np.dtype) and dtype.kind == "f":
888
+ values = column.to_numpy()
889
+ plain = values.tolist()
890
+ if np.isnan(values).any():
891
+ plain = [None if v != v else v for v in plain]
892
+ return plain
893
+ missing = column.isna().to_numpy(dtype=bool)
894
+ plain = column.tolist()
895
+ if missing.any():
896
+ plain = [
897
+ None if gone else v for v, gone in zip(plain, missing, strict=True)
898
+ ]
899
+ return plain
900
+
901
+ def _same_phase_shifts(self, solved: tuple | None, current: tuple) -> bool:
902
+ """
903
+ Tell whether the angles a solution was `solved` with (`_phase_shifts`) are the
904
+ `current` ones, exactly. A solution whose angles are not known, as one of
905
+ another version of the engine, or that cannot be compared with them, is taken
906
+ for one with others: it is not started from. A comparison that fails is
907
+ reported, since every run would then start from scratch without a word.
908
+ """
909
+ if solved is None:
910
+ return False
911
+ try:
912
+ return bool(solved == current)
913
+ except (TypeError, ValueError) as error:
914
+ self.logger.warning(
915
+ "The angles of the previous solution cannot be compared with those of "
916
+ f"the network ({error}): the power flow starts from scratch"
917
+ )
918
+ return False
919
+
920
+ def check_names(self) -> None:
921
+ """
922
+ Refuse a network in which a bus, a line, a transformer, a load or a static
923
+ generator has no name, or the name of another element of its table.
924
+
925
+ Everything the engine answers by name would otherwise silently mix them up: the
926
+ sensitivities give one row for two buses, a parallel conductor goes on two lines
927
+ at once, a line to a bus named as the source of the feeder is a line to the
928
+ source in the path search. Elements without a name (None, NaN or "") cannot be
929
+ told apart either: the voltage sensitivities give all the unnamed buses of a
930
+ network the same name, NaN. Loads and static generators are identified by their
931
+ index, but their flexibility settings are kept by name (`flexibility_settings`):
932
+ two loads of one name would get the same flexibility, whatever was meant for
933
+ each. Elements of different tables may share a name.
934
+
935
+ `run_power_flow` calls it before each run; call it right after loading a network
936
+ to know at once, before any power flow. Nothing is renamed: `fill_missing_names`
937
+ names the elements that have no name, and shared names are for the caller to
938
+ change.
939
+
940
+ Raises:
941
+ ValueError: Giving, for each table, the indices of up to five elements
942
+ without a name, and up to five shared names, each with the indices of
943
+ the elements that have it, or if no network is loaded.
944
+ """
945
+ if not self.network:
946
+ raise ValueError("No network loaded for power flow calculation")
947
+
948
+ unnamed, shared = [], []
949
+ for element, label in (
950
+ ("bus", "buses"),
951
+ ("line", "lines"),
952
+ ("trafo", "transformers"),
953
+ ("load", "loads"),
954
+ ("sgen", "static generators"),
955
+ ):
956
+ table = getattr(self.network, element, None)
957
+ if table is None or table.empty:
958
+ continue
959
+ if "name" not in table.columns:
960
+ unnamed.append(f"{label}: all {len(table)}, which have no name column")
961
+ continue
962
+ column = table["name"]
963
+ values = column.to_numpy()
964
+ names = set(values.tolist())
965
+ # The quick test, before each power flow, on names that are all strings
966
+ # (no None, no NaN): 0.23 ms for the five tables of the case-study feeder
967
+ # with the most loads (2,470; 0.09 ms of it for them), against 13 ms for
968
+ # one of its warm power flows
969
+ if (
970
+ len(names) == len(values)
971
+ and "" not in names
972
+ and infer_dtype(values, skipna=False) == "string"
973
+ ):
974
+ continue
975
+ missing = column.isna() | (column == "")
976
+ if missing.any():
977
+ where = [str(index) for index in column.index[missing]]
978
+ listed = ", ".join(where[:5])
979
+ if len(where) > 5:
980
+ listed += f" and {len(where) - 5} more"
981
+ unnamed.append(f"{label}: {listed}")
982
+ present = column[~missing]
983
+ repeated = present[present.duplicated(keep=False)]
984
+ if repeated.empty:
985
+ continue
986
+ indices: dict[Any, list[str]] = {}
987
+ for index, name in repeated.items():
988
+ indices.setdefault(name, []).append(str(index))
989
+ listed = "; ".join(
990
+ f"{name!r} ({', '.join(where)})"
991
+ for name, where in list(indices.items())[:5]
992
+ )
993
+ if len(indices) > 5:
994
+ listed += f"; and {len(indices) - 5} more"
995
+ shared.append(f"{label}: {listed}")
996
+ if unnamed or shared:
997
+ problems = []
998
+ if unnamed:
999
+ problems.append(
1000
+ "Elements without a name (None, NaN or ''), by index: "
1001
+ + ". ".join(unnamed)
1002
+ + ". `PandaPowerEngine.fill_missing_names()` names them."
1003
+ )
1004
+ if shared:
1005
+ problems.append(
1006
+ "Names shared, with the indices of the elements that have them: "
1007
+ + ". ".join(shared)
1008
+ + "."
1009
+ )
1010
+ raise ValueError(
1011
+ "Buses, lines and transformers are identified by their name, and the "
1012
+ "flexibility settings of loads and static generators are kept by it: "
1013
+ "each must have one and not share it with another element of its "
1014
+ "table. " + " ".join(problems)
1015
+ )
1016
+
1017
+ def _has_converged_results(self) -> bool:
1018
+ """
1019
+ Tell whether the last run of the engine converged, for the sensitivities, which
1020
+ read its results.
1021
+
1022
+ Both flags are needed: `latest_results["converged"]` is False after any failed
1023
+ run, but pandapower leaves `net.converged` True when it is the controllers that
1024
+ do not converge, and it is False for a network that was never solved.
1025
+
1026
+ `latest_results` is set by `run_power_flow` and forgotten when a network is
1027
+ assigned, so the results of a power flow run outside the engine (`pp.runpp`,
1028
+ then the network assigned to the engine) are refused: whether their controllers
1029
+ converged is not known, and their network has not been through `check_names`,
1030
+ without which the sensitivities can name two buses alike. `check_violations`
1031
+ refuses them as well. A network put back with results of the engine's own run
1032
+ (`latest_results` assigned after it, as the snapshots of the algorithm do) is
1033
+ accepted.
1034
+ """
1035
+ net = self.network
1036
+ return bool(
1037
+ net is not None
1038
+ and net.converged
1039
+ and self.latest_results
1040
+ and self.latest_results.get("converged")
1041
+ )
1042
+
1043
+ def _tables_match_results(self) -> bool:
1044
+ """
1045
+ Tell whether the buses, lines and transformers are those of the last run.
1046
+
1047
+ The sensitivities read the Jacobian and the result tables of the last run, and
1048
+ find a bus or a branch in them by its place in the element tables. After a bus
1049
+ or a line has been created or dropped without a new run, the same place is
1050
+ another element, or none. Two things are compared, which a run leaves in the
1051
+ network itself, so that a network put back together with the results of a run
1052
+ of the engine (`latest_results` assigned after it) is checked as well; the
1053
+ results of a power flow run outside the engine are refused before, by
1054
+ `_has_converged_results`:
1055
+
1056
+ - the index of the element tables with that of the result tables, which a
1057
+ creation does not extend, and a drop with pandas (not `pp.drop_*`) does not
1058
+ shorten;
1059
+ - the number of lines and of transformers with the number of branches of each
1060
+ that the run solved, which `pp.drop_*` changes in both tables.
1061
+
1062
+ A line dropped with pandas and then a new one created at its index, or a bus
1063
+ without any branch dropped, pass this check.
1064
+ """
1065
+ net = self.network
1066
+ for element in ("bus", "line", "trafo"):
1067
+ if not getattr(net, element).index.equals(
1068
+ getattr(net, f"res_{element}").index
1069
+ ):
1070
+ return False
1071
+ solved = (getattr(net, "_pd2ppc_lookups", None) or {}).get("branch", {})
1072
+ return all(
1073
+ len(getattr(net, element)) == (solved[element][1] - solved[element][0])
1074
+ if element in solved
1075
+ else len(getattr(net, element)) == 0
1076
+ for element in ("line", "trafo")
1077
+ )
1078
+
1079
+ def _converged_jacobian(self) -> sparse.csr_matrix | None:
1080
+ """
1081
+ Get the Jacobian of the power flow equations at the solution of the last run,
1082
+ after the Newton step that ends it (`_take_one_more_newton_step`).
1083
+
1084
+ The sensitivities need it. pandapower keeps the Jacobian of its last Newton
1085
+ step, built before the final voltage update, and none at all when the run
1086
+ starts within tolerance, as a warm start can. The sensitivities would then
1087
+ depend on where the run started, and so would the decisions of the strategies.
1088
+
1089
+ Returns:
1090
+ Optional[sparse.csr_matrix]: The Jacobian, None if no run left a solution.
1091
+
1092
+ Raises:
1093
+ NotImplementedError: If the power flow uses a distributed slack, whose
1094
+ Jacobian has an extra row and column that the sensitivities do not handle.
1095
+ """
1096
+ if self.pf_settings["specific"].get("distributed_slack", False):
1097
+ raise NotImplementedError(
1098
+ "Sensitivities are not available with a distributed slack"
1099
+ )
1100
+ ppc = getattr(self.network, "_ppc", None) or {}
1101
+ internal = ppc.get("internal", {})
1102
+ voltages = internal.get("V")
1103
+ if voltages is None:
1104
+ return None
1105
+ if self._jacobian_cache is None or self._jacobian_cache[0] is not voltages:
1106
+ self._jacobian_cache = (voltages, self._jacobian_at(internal, voltages))
1107
+ return self._jacobian_cache[1]
1108
+
1109
+ @staticmethod
1110
+ def _jacobian_at(
1111
+ internal: dict[str, Any], voltages: np.ndarray
1112
+ ) -> sparse.csr_matrix:
1113
+ """
1114
+ The Jacobian of the power flow equations of `internal` at `voltages`.
1115
+
1116
+ Built by pandapower's numba builder, which its Newton-Raphson has compiled,
1117
+ 15 to 20 times faster than its Python one, which gives the same matrix and is
1118
+ used where numba is not available.
1119
+ """
1120
+ # Private to pandapower, so imported here: if a release changes it, only the
1121
+ # sensitivities break, not the whole engine.
1122
+ from pandapower.pf.create_jacobian import (
1123
+ _create_J_with_numba,
1124
+ _create_J_without_numba,
1125
+ get_fastest_jacobian_function,
1126
+ )
1127
+
1128
+ pv = np.asarray(internal["pv"], dtype=int)
1129
+ pq = np.asarray(internal["pq"], dtype=int)
1130
+ ref = np.asarray(internal["ref"], dtype=int)
1131
+ pvpq = np.r_[pv, pq]
1132
+ admittances = internal["Ybus"].tocsr()
1133
+ try:
1134
+ build = get_fastest_jacobian_function(pvpq, pq, True, False)
1135
+ lookup = np.zeros(int(admittances.indices.max()) + 1, dtype=np.int64)
1136
+ lookup[pvpq] = np.arange(len(pvpq))
1137
+ return _create_J_with_numba(
1138
+ admittances,
1139
+ voltages,
1140
+ np.r_[ref, pvpq],
1141
+ pvpq,
1142
+ pq,
1143
+ build,
1144
+ lookup,
1145
+ len(ref),
1146
+ len(pv),
1147
+ len(pq),
1148
+ None,
1149
+ False,
1150
+ ).tocsr()
1151
+ except (ImportError, NameError, TypeError, ValueError):
1152
+ return _create_J_without_numba(
1153
+ admittances, voltages, ref, pvpq, pq, None, False
1154
+ ).tocsr()
1155
+
1156
+ @staticmethod
1157
+ def _load_voltage_derivative(
1158
+ internal: dict[str, Any], magnitudes: np.ndarray, n_pv: int, pq: np.ndarray
1159
+ ) -> sparse.csr_matrix:
1160
+ """
1161
+ What the voltage-dependent loads add to the Jacobian of the power mismatch, in
1162
+ the columns of the voltage magnitudes of the PQ buses.
1163
+
1164
+ pandapower takes a load at the voltage `v` as ``P (cp + ci v + cz v^2)`` (and
1165
+ the same for Q with its own shares), ``ci`` and ``cz`` being the shares of
1166
+ constant current and constant impedance at the bus (``CID_*`` and ``CZD_*`` of
1167
+ the internal bus table). The mismatch is the power the network draws minus the
1168
+ injections, the generation less the loads, so its derivative with respect to
1169
+ `v` gains ``P (ci + 2 cz v)`` and ``Q (ci_q + 2 cz_q v)``, in per unit of the
1170
+ base power, on the diagonal of the bus. Zero for loads of constant power.
1171
+ """
1172
+ from pandapower.pypower.idx_bus import CID_P, CID_Q, CZD_P, CZD_Q, PD, QD
1173
+
1174
+ bus = internal["bus"]
1175
+ base = float(np.real(internal["baseMVA"]))
1176
+ v = magnitudes[pq]
1177
+ p = np.real(bus[pq, PD]) * (
1178
+ np.real(bus[pq, CID_P]) + 2.0 * np.real(bus[pq, CZD_P]) * v
1179
+ )
1180
+ q = np.real(bus[pq, QD]) * (
1181
+ np.real(bus[pq, CID_Q]) + 2.0 * np.real(bus[pq, CZD_Q]) * v
1182
+ )
1183
+ n_pvpq = n_pv + len(pq)
1184
+ size = n_pvpq + len(pq)
1185
+ columns = n_pvpq + np.arange(len(pq))
1186
+ rows = np.r_[n_pv + np.arange(len(pq)), columns]
1187
+ return sparse.csr_matrix(
1188
+ (np.r_[p, q] / base, (rows, np.r_[columns, columns])), shape=(size, size)
1189
+ )
1190
+
1191
+ def _jacobian_lu(self, jacobian: sparse.csr_matrix) -> Any:
1192
+ """
1193
+ LU factors of the Jacobian, computed once per solution.
1194
+
1195
+ Both J x = b and J^T y = c are solved from them (``solve(c, trans="T")``), so the
1196
+ sensitivities need one factorisation, however many of them are asked for.
1197
+ """
1198
+ if (
1199
+ self._jacobian_lu_cache is None
1200
+ or self._jacobian_lu_cache[0] is not jacobian
1201
+ ):
1202
+ self._jacobian_lu_cache = (jacobian, splu(jacobian.tocsc()))
1203
+ return self._jacobian_lu_cache[1]
1204
+
1205
+ def _ppc_bus_names(
1206
+ self, ppc_indices: np.ndarray, missing: str | None = "unknown"
1207
+ ) -> list[tuple[int, str]]:
1208
+ """
1209
+ Name the internal (ppc) buses at `ppc_indices`, as (position, name) pairs.
1210
+
1211
+ Buses that pandapower merges into one internal bus (joined by a closed bus-bus
1212
+ switch) all map to it: each gives a pair with the position of that internal
1213
+ bus, in the order of the bus table. A ppc bus with no bus of the network is
1214
+ named ``f"{missing}_{index}"``, or left out if `missing` is None.
1215
+ """
1216
+ net = self.network
1217
+ bus_lookup = net._pd2ppc_lookups["bus"]
1218
+ names_of: dict[int, list[str]] = {}
1219
+ for pd_idx, name in zip(net.bus.index, net.bus["name"], strict=True):
1220
+ if isinstance(bus_lookup, np.ndarray):
1221
+ ppc = bus_lookup[pd_idx] if 0 <= pd_idx < len(bus_lookup) else -1
1222
+ else:
1223
+ ppc = bus_lookup.get(pd_idx, -1)
1224
+ # Buses out of service have no internal bus (-1)
1225
+ if ppc >= 0:
1226
+ names_of.setdefault(int(ppc), []).append(name)
1227
+ result = []
1228
+ for position, ppc in enumerate(ppc_indices):
1229
+ names = names_of.get(int(ppc))
1230
+ if names is not None:
1231
+ result.extend((position, name) for name in names)
1232
+ elif missing is not None:
1233
+ result.append((position, f"{missing}_{ppc}"))
1234
+ return result
1235
+
1236
+ def _controllers_act(self) -> bool:
1237
+ """Tell whether a power flow also runs controllers, which change the network."""
1238
+ controllers = getattr(self.network, "controller", None)
1239
+ return bool(
1240
+ self.pf_settings["specific"].get("run_control", False)
1241
+ and controllers is not None
1242
+ and len(controllers)
1243
+ and controllers["in_service"].any()
1244
+ )
1245
+
1246
+ def _run_pandapower(self, warm_start: bool, with_controllers: bool = True) -> None:
1247
+ """
1248
+ Run pandapower's power flow with the settings of the engine.
1249
+
1250
+ Args:
1251
+ warm_start (bool): Start from the results of the previous run.
1252
+ with_controllers (bool): If False, do not run the controllers, whatever
1253
+ `run_control` in the settings.
1254
+ """
1255
+ specific = dict(self.pf_settings["specific"])
1256
+ if not with_controllers:
1257
+ specific["run_control"] = False
1258
+ # pandapower's keyword name: its value is per unit of sn_mva, not MVA
1259
+ tolerance = self.pf_settings["generic"]["tolerance"]
1260
+ pp.runpp(
1261
+ self.network,
1262
+ max_iteration=self.pf_settings["generic"]["max_iterations"],
1263
+ tolerance_mva=tolerance,
1264
+ init="results" if warm_start else "auto",
1265
+ **specific,
1266
+ )
1267
+
1268
+ def unresolved_power_mva(self) -> float | None:
1269
+ """
1270
+ The largest power mismatch, in MVA, that the last run left at a bus: the power
1271
+ that its solution does not resolve.
1272
+
1273
+ After the Newton step that ends a run (`_take_one_more_newton_step`), the
1274
+ rounding floor of the power balance at its solution (`_rounding_floor`), an
1275
+ upper bound of what the step leaves: 1.4e-11 to 3.5e-9 MVA on the MV/LV
1276
+ feeders at the load of the case study, whatever the tolerance. Where no step
1277
+ is taken, the bound of the solver, which
1278
+ compares the mismatch with its tolerance in per unit of the base power of the
1279
+ network, `sn_mva`: 1e-6 MVA (1 W) for the default 1e-8 at 100 MVA. None without a
1280
+ converged run of the engine.
1281
+ """
1282
+ if not self.latest_results or not self.latest_results.get("converged"):
1283
+ return None
1284
+ return self.latest_results.get("unresolved_mva")
1285
+
1286
+ def _take_one_more_newton_step(self) -> float | None:
1287
+ """
1288
+ End the run with one more Newton step, from the power mismatch the solver left
1289
+ and the Jacobian at its solution, and put the solution after it in the results.
1290
+
1291
+ The solver stops as soon as the power mismatch of every bus is under its
1292
+ tolerance, after a step that may have taken it just under, or far under. What it
1293
+ stops at differs from the exact solution by up to the response of the network
1294
+ to that mismatch, which depends on where the run started: on the MV/LV feeders
1295
+ at 1e-8, warm and cold runs of one network differ by up to 5.2e-6 p.u. of
1296
+ voltage and 3.5e-3 % of loading, and cold runs differ as much from the exact
1297
+ solution. One more step squares that error: the results agree to about 1e-10
1298
+ p.u. whatever the start, and so do the decisions taken on them (#18).
1299
+
1300
+ The step is that of pandapower's Newton-Raphson: the angles of the PV and PQ
1301
+ buses and the magnitudes of the PQ buses, with the injections of the loads at
1302
+ the voltage of the step's start when `voltage_depend_loads` is set. Its
1303
+ Jacobian is that of the sensitivities, plus, in that case, the derivative of the
1304
+ loads with the voltage (`_load_voltage_derivative`), so that the step squares
1305
+ the error with constant-current and constant-impedance loads too. The
1306
+ sensitivities themselves keep the loads at constant power.
1307
+
1308
+ After it, the internal voltages (``_ppc["internal"]["V"]``), from which the
1309
+ sensitivities are computed, the voltages of ``res_bus`` (``vm_pu``,
1310
+ ``va_degree``), the currents and loadings of ``res_line`` (``i_from_ka``,
1311
+ ``i_to_ka``, ``i_ka``, ``loading_percent``) and of ``res_trafo`` (``i_hv_ka``,
1312
+ ``i_lv_ka``, ``loading_percent``) are those of the solution after the step. The
1313
+ other results, the powers, the losses and those of the other elements, are the
1314
+ solver's, and differ from it by no more than the error of the solver.
1315
+
1316
+ Returns:
1317
+ The largest power mismatch the step can leave at a bus, in per unit of
1318
+ the base power: the rounding floor of the power balance at its solution
1319
+ (`_rounding_floor`). None if the step was not taken, and the results are
1320
+ the solver's,
1321
+ with another algorithm than Newton-Raphson (``nr``, ``iwamoto_nr``), with
1322
+ a distributed slack, FACTS devices or line temperatures in the power
1323
+ flow, which the Jacobian of the engine does not model, or if the Jacobian
1324
+ cannot be factorised.
1325
+ """
1326
+ net = self.network
1327
+ internal = (getattr(net, "_ppc", None) or {}).get("internal", {})
1328
+ voltages = internal.get("V")
1329
+ options = getattr(net, "_options", None) or {}
1330
+ if (
1331
+ voltages is None
1332
+ or not net.converged
1333
+ # The step is that of Newton-Raphson, on the data it leaves: the other
1334
+ # algorithms of pandapower leave other data, or none
1335
+ or options.get("algorithm", "nr") not in ("nr", "iwamoto_nr")
1336
+ or not options.get("ac", True)
1337
+ or self.pf_settings["specific"].get("distributed_slack", False)
1338
+ or options.get("tdpf")
1339
+ or any(
1340
+ len(internal.get(device, ()))
1341
+ for device in ("svc", "tcsc", "ssc", "vsc")
1342
+ )
1343
+ ):
1344
+ return None
1345
+ # Private to pandapower, as the Jacobian builder
1346
+ from pandapower.pypower.idx_brch import F_BUS, T_BUS
1347
+ from pandapower.pypower.makeSbus import makeSbus
1348
+
1349
+ pv = np.asarray(internal["pv"], dtype=int)
1350
+ pq = np.asarray(internal["pq"], dtype=int)
1351
+ pvpq = np.r_[pv, pq]
1352
+ magnitudes = np.abs(voltages)
1353
+ injections = makeSbus(
1354
+ internal["baseMVA"],
1355
+ internal["bus"],
1356
+ internal["gen"],
1357
+ vm=magnitudes if options.get("voltage_depend_loads") else None,
1358
+ )
1359
+ mismatch = voltages * np.conj(internal["Ybus"] @ voltages) - injections
1360
+ jacobian = self._jacobian_at(internal, voltages)
1361
+ if options.get("voltage_depend_loads"):
1362
+ jacobian = jacobian + self._load_voltage_derivative(
1363
+ internal, magnitudes, len(pv), pq
1364
+ )
1365
+ try:
1366
+ step = -splu(jacobian.tocsc()).solve(
1367
+ np.r_[mismatch[pvpq].real, mismatch[pq].imag]
1368
+ )
1369
+ except (RuntimeError, ValueError) as error:
1370
+ self.logger.warning(f"No Newton step after the power flow: {error}")
1371
+ return None
1372
+ old_angles = np.angle(voltages)
1373
+ angles = old_angles.copy()
1374
+ angles[pvpq] += step[: len(pvpq)]
1375
+ new_magnitudes = magnitudes.copy()
1376
+ new_magnitudes[pq] += step[len(pvpq) :]
1377
+ stepped = new_magnitudes * np.exp(1j * angles)
1378
+
1379
+ # Branches: what the step multiplies the current, or the apparent power, of
1380
+ # each end by, from the solver's voltages
1381
+ in_service = np.asarray(internal["branch_is"], dtype=bool)
1382
+ position = np.cumsum(in_service) - 1
1383
+ ends = []
1384
+ for admittances, end in (("Yf", F_BUS), ("Yt", T_BUS)):
1385
+ before = np.abs(internal[admittances] @ voltages)
1386
+ after = np.abs(internal[admittances] @ stepped)
1387
+ bus = internal["branch"][:, end].real.astype(int)
1388
+ ends.append((before, after, bus))
1389
+
1390
+ def ratios(element: str, count: int, by_power: bool) -> list[np.ndarray]:
1391
+ """The factor of each end of the branches of `element`, 1 out of service."""
1392
+ result = [np.ones(count), np.ones(count)]
1393
+ lookups = net._pd2ppc_lookups.get("branch", {})
1394
+ if element not in lookups or count == 0:
1395
+ return result
1396
+ branch = lookups[element][0] + np.arange(count)
1397
+ active = in_service[branch]
1398
+ rows = position[branch[active]]
1399
+ for side, (before, after, bus) in enumerate(ends):
1400
+ old, new = before[rows], after[rows]
1401
+ if by_power:
1402
+ old = old * magnitudes[bus[rows]]
1403
+ new = new * new_magnitudes[bus[rows]]
1404
+ with np.errstate(divide="ignore", invalid="ignore"):
1405
+ factor = np.where(old > 0.0, new / old, 1.0)
1406
+ result[side][active] = factor
1407
+ return result
1408
+
1409
+ def max_of_ends(first, second, ratio) -> np.ndarray:
1410
+ """The factor of the end that sets the loading, the larger after the step."""
1411
+ first, second = np.nan_to_num(first), np.nan_to_num(second)
1412
+ top = np.maximum(first, second)
1413
+ with np.errstate(divide="ignore", invalid="ignore"):
1414
+ return np.where(
1415
+ top > 0.0,
1416
+ np.maximum(first * ratio[0], second * ratio[1]) / top,
1417
+ 1.0,
1418
+ )
1419
+
1420
+ line, trafo = net.res_line, net.res_trafo
1421
+ line_ends = ratios("line", len(line), by_power=False)
1422
+ i_from = line["i_from_ka"].to_numpy(float)
1423
+ i_to = line["i_to_ka"].to_numpy(float)
1424
+ line_factor = max_of_ends(i_from, i_to, line_ends)
1425
+
1426
+ trafo_current = ratios("trafo", len(trafo), by_power=False)
1427
+ if options.get("trafo_loading", "current") == "power":
1428
+ hv = np.hypot(trafo["p_hv_mw"], trafo["q_hv_mvar"]).to_numpy(float)
1429
+ lv = np.hypot(trafo["p_lv_mw"], trafo["q_lv_mvar"]).to_numpy(float)
1430
+ trafo_factor = max_of_ends(
1431
+ hv, lv, ratios("trafo", len(trafo), by_power=True)
1432
+ )
1433
+ else:
1434
+ hv = (trafo["i_hv_ka"] * net.trafo["vn_hv_kv"]).to_numpy(float)
1435
+ lv = (trafo["i_lv_ka"] * net.trafo["vn_lv_kv"]).to_numpy(float)
1436
+ trafo_factor = max_of_ends(hv, lv, trafo_current)
1437
+
1438
+ # Buses: by the lookup of the engine's other methods (see `_ppc_bus_names`)
1439
+ lookup = net._pd2ppc_lookups["bus"]
1440
+ if isinstance(lookup, np.ndarray):
1441
+ index = net.bus.index.to_numpy()
1442
+ inside = (index >= 0) & (index < len(lookup))
1443
+ internal_bus = np.full(len(index), -1)
1444
+ internal_bus[inside] = lookup[index[inside]]
1445
+ else:
1446
+ internal_bus = np.array([lookup.get(i, -1) for i in net.bus.index])
1447
+ vm_pu = net.res_bus["vm_pu"].to_numpy(dtype=float).copy()
1448
+ va_degree = net.res_bus["va_degree"].to_numpy(dtype=float).copy()
1449
+ known = (internal_bus >= 0) & np.isfinite(vm_pu)
1450
+ vm_pu[known] = new_magnitudes[internal_bus[known]]
1451
+ va_degree[known] += np.degrees((angles - old_angles)[internal_bus[known]])
1452
+ net.res_bus["vm_pu"] = vm_pu
1453
+ net.res_bus["va_degree"] = va_degree
1454
+
1455
+ line["i_from_ka"] = i_from * line_ends[0]
1456
+ line["i_to_ka"] = i_to * line_ends[1]
1457
+ # As pandapower: NaN where an end has no current (a line to an island)
1458
+ line["i_ka"] = np.maximum(i_from * line_ends[0], i_to * line_ends[1])
1459
+ line["loading_percent"] = line["loading_percent"].to_numpy(float) * line_factor
1460
+ trafo["i_hv_ka"] = trafo["i_hv_ka"].to_numpy(float) * trafo_current[0]
1461
+ trafo["i_lv_ka"] = trafo["i_lv_ka"].to_numpy(float) * trafo_current[1]
1462
+ trafo["loading_percent"] = (
1463
+ trafo["loading_percent"].to_numpy(float) * trafo_factor
1464
+ )
1465
+
1466
+ # A new array: what is cached for the solver's voltages is not taken for these
1467
+ internal["V"] = stepped
1468
+
1469
+ # What the step leaves: the rounding floor of the power balance at its solution
1470
+ injections = makeSbus(
1471
+ internal["baseMVA"],
1472
+ internal["bus"],
1473
+ internal["gen"],
1474
+ vm=new_magnitudes if options.get("voltage_depend_loads") else None,
1475
+ )
1476
+ return self._rounding_floor(internal["Ybus"], stepped, injections, pvpq)
1477
+
1478
+ @staticmethod
1479
+ def _rounding_floor(
1480
+ admittances: Any, voltages: np.ndarray, injections: np.ndarray, rows: np.ndarray
1481
+ ) -> float:
1482
+ """
1483
+ The largest error, in per unit of the base power, with which the power balance
1484
+ of a bus of `rows` can be computed in floating point at `voltages`.
1485
+
1486
+ The mismatch of bus i, ``V_i conj(sum_j Y_ij V_j) - S_i``, sums the terms of
1487
+ row i of the admittance matrix, and two more for the product with ``V_i`` and
1488
+ the injection. A sum of n products is computed within ``gamma_n`` of the sum of
1489
+ their magnitudes, ``gamma_n = n u / (1 - n u)``, u being the unit roundoff
1490
+ (half the machine epsilon): the error of bus i is at most
1491
+ ``gamma_(n_i + 2) (|V_i| sum_j |Y_ij| |V_j| + |S_i|)``. It is a smooth function
1492
+ of the state, not a sample of the noise: the same state reached by a warm or a
1493
+ cold run gives the same floor to 1e-11 relative, where the mismatch measured
1494
+ after the step differed by a factor of up to 2.7. It bounds what the step leaves:
1495
+ on 30 feeders of the MV/LV case study, warm and cold, and up to voltage collapse
1496
+ (0.48 p.u.), the mismatch measured after the step was at most 0.42 of it.
1497
+ """
1498
+ admittances = admittances.tocsr()
1499
+ magnitudes = np.abs(voltages)
1500
+ terms = magnitudes * (abs(admittances) @ magnitudes) + np.abs(injections)
1501
+ unit = np.finfo(float).eps / 2.0
1502
+ n = np.diff(admittances.indptr) + 2
1503
+ gamma = n * unit / (1.0 - n * unit)
1504
+ return float((gamma * terms)[rows].max(initial=0.0))
1505
+
1506
+ def check_violations(self) -> dict[str, Any]:
1507
+ """
1508
+ Check if the network violates specified constraints.
1509
+
1510
+ The voltages and loadings checked are those of the result tables, which hold
1511
+ the solution after the Newton step that ends each run
1512
+ (`_take_one_more_newton_step`): the violations, and the decisions taken on them,
1513
+ do not depend on where the solver started or stopped. A value at its limit is
1514
+ not a violation.
1515
+
1516
+ Returns:
1517
+ Dict[str, Any]: Dictionary with constraint violations.
1518
+ """
1519
+ if (
1520
+ not self.network
1521
+ or not self.latest_results
1522
+ or not self.latest_results.get("converged", False)
1523
+ ):
1524
+ raise ValueError("Need a converged power flow solution to check violations")
1525
+
1526
+ bus_data = (
1527
+ self.network.bus[["name", "vn_kv"]]
1528
+ .join(self.network.res_bus[["vm_pu"]])
1529
+ .rename(columns={"name": "bus_id"})
1530
+ )
1531
+ bus_data["voltage_level"] = np.where(bus_data["vn_kv"] <= 1.0, "lv", "mv")
1532
+
1533
+ line_data = (
1534
+ self.network.line[["name"]]
1535
+ .join(self.network.res_line[["loading_percent", "i_ka"]])
1536
+ .rename(columns={"name": "line_id", "i_ka": "current"})
1537
+ )
1538
+ line_data["current"] *= 1000.0 # convert to A
1539
+
1540
+ transformer_data = self.network.trafo[["name"]].join(
1541
+ self.network.res_trafo[["loading_percent", "p_hv_mw", "q_hv_mvar"]]
1542
+ )
1543
+ # Apparent power at the HV side, in VA: transformer ratings (sn_mva) are apparent
1544
+ # powers, so the upgrade sizing must compare like with like.
1545
+ transformer_data["power"] = (
1546
+ np.hypot(transformer_data["p_hv_mw"], transformer_data["q_hv_mvar"]) * 1.0e6
1547
+ )
1548
+ transformer_data = transformer_data[
1549
+ ["name", "loading_percent", "power"]
1550
+ ].rename(columns={"name": "transformer_id"})
1551
+
1552
+ violations = self.constraints.check_violations(
1553
+ bus_data=bus_data,
1554
+ line_data=line_data,
1555
+ transformer_data=transformer_data,
1556
+ )
1557
+
1558
+ return violations
1559
+
1560
+ def analyze_violations(self):
1561
+ """
1562
+ Calls the NetworkConstraint analyze_violations method.
1563
+
1564
+ Returns:
1565
+ Any: The summary of violations.
1566
+ """
1567
+
1568
+ return self.constraints.analyze_violations()
1569
+
1570
+ def _element_index(self, table: str, name: str) -> int:
1571
+ """
1572
+ Index in the pandapower table `table` ("line" or "trafo") of the element
1573
+ called `name`, which the methods that modify an element resolve it by.
1574
+
1575
+ Raises:
1576
+ ValueError: If no element of the table has that name, or several do (the
1577
+ name check of `run_power_flow` refuses such a network): a modification
1578
+ is never made to the first match, or to all of them.
1579
+ """
1580
+ label = {"line": "Line", "trafo": "Transformer"}[table]
1581
+ elements = getattr(self.network, table)
1582
+ indices = elements.index[elements.name == name].tolist()
1583
+ if not indices:
1584
+ raise ValueError(f"{label} with name '{name}' not found in the network")
1585
+ if len(indices) > 1:
1586
+ raise ValueError(
1587
+ f"{label} name '{name}' is shared by {len(indices)} elements "
1588
+ f"(indices {', '.join(map(str, indices))}): it does not tell which "
1589
+ "to modify"
1590
+ )
1591
+ return indices[0]
1592
+
1593
+ def apply_tap_change(self, trafo_id: str, tap_pos_shift: int) -> bool:
1594
+ """
1595
+ Change the tap position of a transformer by a number of steps.
1596
+
1597
+ The shift is applied whole or not at all: a shift that would take the position
1598
+ outside the tap range of the unit (``tap_min`` to ``tap_max``) is refused,
1599
+ from inside the range as well as from its end, and so is any shift of a unit
1600
+ without a range or a position (NaN). A position thus never leaves the range by
1601
+ a tap change; `upgrade_transformer` brings it into the range of a new type.
1602
+
1603
+ Args:
1604
+ trafo_id (str): Name of the transformer.
1605
+ tap_pos_shift (int): Number of steps added to the current tap position,
1606
+ negative to lower it; `TapChangeStrategy` passes shifts of several
1607
+ steps.
1608
+
1609
+ Returns:
1610
+ bool: True if the position moved by `tap_pos_shift`, False if nothing
1611
+ changed because the new position would be outside the range.
1612
+
1613
+ Raises:
1614
+ ValueError: If no transformer has that name, or several do.
1615
+ """
1616
+ if not self.network:
1617
+ raise ValueError("No network loaded")
1618
+
1619
+ try:
1620
+ eid = self._element_index("trafo", trafo_id)
1621
+ table = self.network.trafo
1622
+ current, low, high = (
1623
+ table.at[eid, column] for column in ("tap_pos", "tap_min", "tap_max")
1624
+ )
1625
+ if pd.isna(current) or pd.isna(low) or pd.isna(high):
1626
+ self.logger.info(
1627
+ f"Transformer {trafo_id} has no tap range or position: tap "
1628
+ "position not changed"
1629
+ )
1630
+ return False
1631
+ new = current + tap_pos_shift
1632
+ if not low <= new <= high:
1633
+ self.logger.info(
1634
+ f"Tap position of transformer {trafo_id} not changed by "
1635
+ f"{tap_pos_shift}: {new:g} is outside the range {low:g} to {high:g}"
1636
+ )
1637
+ return False
1638
+ table.at[eid, "tap_pos"] = new
1639
+ self.logger.info(
1640
+ f"Changed tap position of transformer {trafo_id} from {current:g} to "
1641
+ f"{new:g}"
1642
+ )
1643
+ return True
1644
+ except Exception as e:
1645
+ self.logger.error(f"Failed to change tap position: {str(e)}")
1646
+ raise
1647
+
1648
+ def get_transformer_tap_position(self, transformer_id: str) -> float | None:
1649
+ """
1650
+ The tap position of a transformer, None if it has none (NaN).
1651
+
1652
+ Raises:
1653
+ ValueError: If no transformer has that name, or several do.
1654
+ """
1655
+ if not self.network:
1656
+ raise ValueError("No network loaded")
1657
+ eid = self._element_index("trafo", transformer_id)
1658
+ position = self.network.trafo.at[eid, "tap_pos"]
1659
+ return None if pd.isna(position) else float(position)
1660
+
1661
+ def upgrade_line(self, line_id: str, new_type: str) -> None:
1662
+ """
1663
+ Upgrade a line with new parameters.
1664
+
1665
+ Args:
1666
+ line_id (str): Name of the line to upgrade.
1667
+ new_type (str): Type of the new line (must exist in standard_types).
1668
+
1669
+ Raises:
1670
+ ValueError: If the type is unknown, or no line has that name, or several do.
1671
+ """
1672
+ if not self.network:
1673
+ raise ValueError("No network loaded")
1674
+
1675
+ try:
1676
+ # Check if the standard type exists
1677
+ if new_type not in self.network.std_types["line"]:
1678
+ raise ValueError(f"Line type '{new_type}' not found in standard types")
1679
+
1680
+ eid = self._element_index("line", line_id)
1681
+ current_type = self.network.line.at[eid, "std_type"]
1682
+ # Apply the new type
1683
+ pp.change_std_type(self.network, eid, new_type, element="line")
1684
+ self.logger.info(
1685
+ f"Upgraded line {line_id} from {current_type} to type {new_type}"
1686
+ )
1687
+ except Exception as e:
1688
+ self.logger.error(f"Failed to upgrade line: {str(e)}")
1689
+ raise
1690
+
1691
+ def add_parallel_line(self, line_id: str) -> int:
1692
+ """
1693
+ Add a parallel line.
1694
+
1695
+ Args:
1696
+ line_id (str): Name of the line to add a conductor to.
1697
+
1698
+ Returns:
1699
+ int: Number of parallel conductors of the line after the addition.
1700
+
1701
+ Raises:
1702
+ ValueError: If no line has that name, or several do.
1703
+ """
1704
+ if not self.network:
1705
+ raise ValueError("No network loaded")
1706
+
1707
+ try:
1708
+ eid = self._element_index("line", line_id)
1709
+ self.network.line.loc[eid, "parallel"] += 1
1710
+ self.logger.info(f"Added parallel line to {line_id}")
1711
+ return self.network.line.at[eid, "parallel"]
1712
+ except Exception as e:
1713
+ self.logger.error(f"Failed to add parallel line: {str(e)}")
1714
+ raise
1715
+
1716
+ def set_line_parallel(self, line_id: str, parallel: int) -> int:
1717
+ """
1718
+ Set the number of parallel conductors of the line named `line_id`, fewer
1719
+ than it has or more.
1720
+
1721
+ Args:
1722
+ line_id (str): Name of the line.
1723
+ parallel (int): Its number of conductors, a whole number of 1 or more:
1724
+ an integer, or a float without a fractional part, of any numeric
1725
+ type, but not a boolean or a string.
1726
+
1727
+ Returns:
1728
+ int: The number of conductors of the line.
1729
+
1730
+ Raises:
1731
+ ValueError: If no network is loaded, if no line has that name, or if
1732
+ `parallel` is not a whole number of 1 or more.
1733
+ """
1734
+ if not self.network:
1735
+ raise ValueError("No network loaded")
1736
+ # A whole number of any numeric type, not a boolean, a string or None
1737
+ if isinstance(parallel, numbers.Integral) and not isinstance(parallel, bool):
1738
+ whole = True
1739
+ elif isinstance(parallel, numbers.Real) and not isinstance(parallel, bool):
1740
+ whole = float(parallel).is_integer()
1741
+ else:
1742
+ whole = False
1743
+ if not whole or parallel < 1:
1744
+ raise ValueError(
1745
+ f"A line has a whole number of parallel conductors, 1 or more, not "
1746
+ f"{parallel!r}"
1747
+ )
1748
+ mask = self.network.line.name == line_id
1749
+ if not mask.any():
1750
+ raise ValueError(f"Line with name '{line_id}' not found in the network")
1751
+ self.network.line.loc[mask, "parallel"] = int(parallel)
1752
+ self.logger.info(f"Set line {line_id} to {int(parallel)} parallel conductors")
1753
+ return int(parallel)
1754
+
1755
+ def save_line(self, line_id: str) -> pd.DataFrame:
1756
+ """
1757
+ Save the row of the line table of the line named `line_id`, for
1758
+ `restore_line`.
1759
+
1760
+ Returns:
1761
+ pd.DataFrame: A copy of the row, with its index.
1762
+
1763
+ Raises:
1764
+ ValueError: If no network is loaded or no line has that name.
1765
+ """
1766
+ if not self.network:
1767
+ raise ValueError("No network loaded")
1768
+ mask = self.network.line.name == line_id
1769
+ if not mask.any():
1770
+ raise ValueError(f"Line with name '{line_id}' not found in the network")
1771
+ return self.network.line.loc[mask].copy()
1772
+
1773
+ def restore_line(self, line_id: str, saved: pd.DataFrame) -> None:
1774
+ """
1775
+ Give the line named `line_id` back the row `save_line` saved for it, every
1776
+ column as it was, its type and parameters as well as its conductors.
1777
+
1778
+ Raises:
1779
+ ValueError: If no network is loaded, or if `saved` is not the row of the
1780
+ line of that name.
1781
+ """
1782
+ if not self.network:
1783
+ raise ValueError("No network loaded")
1784
+ line = self.network.line
1785
+ mask = line.name == line_id
1786
+ if (
1787
+ not isinstance(saved, pd.DataFrame)
1788
+ or not mask.any()
1789
+ or list(line.index[mask]) != list(saved.index)
1790
+ or (saved["name"] != line_id).any()
1791
+ ):
1792
+ raise ValueError(f"What is given is not a saved row of line '{line_id}'")
1793
+ for column in saved.columns:
1794
+ line.loc[saved.index, column] = saved[column]
1795
+ self.logger.info(f"Restored line {line_id}")
1796
+
1797
+ def save_transformer(self, transformer_id: str) -> pd.DataFrame:
1798
+ """
1799
+ Save the row of the transformer table of the transformer named
1800
+ `transformer_id`, for `restore_transformer`.
1801
+
1802
+ Returns:
1803
+ pd.DataFrame: A copy of the row, with its index.
1804
+
1805
+ Raises:
1806
+ ValueError: If no network is loaded or no transformer has that name.
1807
+ """
1808
+ if not self.network:
1809
+ raise ValueError("No network loaded")
1810
+ mask = self.network.trafo.name == transformer_id
1811
+ if not mask.any():
1812
+ raise ValueError(
1813
+ f"Transformer with name '{transformer_id}' not found in the network"
1814
+ )
1815
+ return self.network.trafo.loc[mask].copy()
1816
+
1817
+ def restore_transformer(self, transformer_id: str, saved: pd.DataFrame) -> None:
1818
+ """
1819
+ Give the transformer named `transformer_id` back the row `save_transformer`
1820
+ saved for it, every column as it was, its type and parameters as well as its
1821
+ units.
1822
+
1823
+ Raises:
1824
+ ValueError: If no network is loaded, or if `saved` is not the row of the
1825
+ transformer of that name.
1826
+ """
1827
+ if not self.network:
1828
+ raise ValueError("No network loaded")
1829
+ trafo = self.network.trafo
1830
+ mask = trafo.name == transformer_id
1831
+ if (
1832
+ not isinstance(saved, pd.DataFrame)
1833
+ or not mask.any()
1834
+ or list(trafo.index[mask]) != list(saved.index)
1835
+ or (saved["name"] != transformer_id).any()
1836
+ ):
1837
+ raise ValueError(
1838
+ f"What is given is not a saved row of transformer '{transformer_id}'"
1839
+ )
1840
+ for column in saved.columns:
1841
+ trafo.loc[saved.index, column] = saved[column]
1842
+ self.logger.info(f"Restored transformer {transformer_id}")
1843
+
1844
+ # What pandapower keeps of a run besides the result tables: the internal case and
1845
+ # its lookups, which each run replaces by new objects, and the convergence flag
1846
+ _SOLUTION_KEYS = (
1847
+ "_ppc",
1848
+ "_pd2ppc_lookups",
1849
+ "_options",
1850
+ "_is_elements",
1851
+ "_is_elements_final",
1852
+ "_isolated_buses",
1853
+ "_isolated_buses_dc",
1854
+ "_impedance_bb_switches",
1855
+ "_gen_order",
1856
+ "converged",
1857
+ )
1858
+
1859
+ def save_solution(self) -> dict[str, Any]:
1860
+ """
1861
+ Save the solution of the latest power flow, for `restore_solution`: a copy of
1862
+ every result table (`res_*`), and what the engine and pandapower keep of the
1863
+ run, which the next run replaces rather than changes: the internal case
1864
+ (`_ppc`) and its lookups, from which the sensitivities are computed, the
1865
+ convergence flags, `latest_results`, and the Jacobian and its factors.
1866
+
1867
+ A power flow whose controllers act (`run_control` in the settings, with a
1868
+ controller in service) changes the network as well as its results: a tap
1869
+ moved by a controller in the power flow after a step would stay moved when
1870
+ the step is undone, and the solution put back would no longer be that of the
1871
+ network. Such a solution is not saved: the strategies then take their steps
1872
+ unchecked, as on an engine that cannot save a solution.
1873
+
1874
+ Returns:
1875
+ dict: The saved solution.
1876
+
1877
+ Raises:
1878
+ ValueError: If no network is loaded.
1879
+ NotImplementedError: If the controllers act in the power flow.
1880
+ """
1881
+ if not self.network:
1882
+ raise ValueError("No network loaded")
1883
+ if self._controllers_act():
1884
+ raise NotImplementedError(
1885
+ "The solution of a power flow whose controllers act is not saved: "
1886
+ "undoing a step would not undo what the controllers changed"
1887
+ )
1888
+ net = self.network
1889
+ return {
1890
+ # None for a table that is empty, as most are
1891
+ "tables": {
1892
+ key: net[key].copy() if len(net[key]) else None
1893
+ for key in net.keys()
1894
+ if key.startswith("res_") and isinstance(net[key], pd.DataFrame)
1895
+ },
1896
+ "kept": {key: net[key] for key in self._SOLUTION_KEYS if key in net},
1897
+ "latest_results": copy.copy(self.latest_results),
1898
+ "caches": (self._jacobian_cache, self._jacobian_lu_cache),
1899
+ }
1900
+
1901
+ def restore_solution(self, saved: dict[str, Any]) -> None:
1902
+ """
1903
+ Put back the solution `save_solution` saved: copies of its result tables, so
1904
+ that it can be put back again, and what the run left besides them.
1905
+
1906
+ Raises:
1907
+ ValueError: If no network is loaded.
1908
+ """
1909
+ if not self.network:
1910
+ raise ValueError("No network loaded")
1911
+ net = self.network
1912
+ for key, table in saved["tables"].items():
1913
+ if table is not None:
1914
+ net[key] = table.copy()
1915
+ elif len(net[key]):
1916
+ net[key] = net[key].iloc[0:0].copy()
1917
+ for key, value in saved["kept"].items():
1918
+ net[key] = value
1919
+ self.latest_results = copy.copy(saved["latest_results"])
1920
+ self._jacobian_cache, self._jacobian_lu_cache = saved["caches"]
1921
+
1922
+ # The parameters of a transformer that its replacement keeps: the vector group seen
1923
+ # by the network, as its phase shift and as its name
1924
+ _KEPT_BY_A_TYPE_CHANGE = ("shift_degree", "vector_group")
1925
+
1926
+ def upgrade_transformer(self, trafo_id: str, new_type: str) -> None:
1927
+ """
1928
+ Upgrade a transformer with new parameters.
1929
+
1930
+ The units take every parameter of the new type but the vector group of the
1931
+ units in place: their phase shift (``shift_degree``) and, where the table has
1932
+ the column, its name (``vector_group``), whatever the type is catalogued with.
1933
+ A replacement unit is one of the new rating, connected as the one it replaces:
1934
+ the network beyond it is not turned by the difference of shifts, 180 degrees
1935
+ from a Dyn11 unit to a Dyn5 type (#56). Three-winding transformers are not
1936
+ upgraded.
1937
+
1938
+ The unit keeps its tap position, which is brought into the tap range of the new
1939
+ type (``tap_min`` to ``tap_max``) when it is outside, with a warning that names
1940
+ the transformer and both positions. Nothing changes, and nothing is logged, for
1941
+ a position within the range, or when the table has no range or position (NaN).
1942
+ A type without tap columns leaves the unit the range it had, and its position:
1943
+ pandapower's `change_std_type` keeps the tap columns of the row then.
1944
+
1945
+ Args:
1946
+ trafo_id (str): Name of the transformer to upgrade.
1947
+ new_type (str): Type of the new transformer (must exist in standard_types).
1948
+
1949
+ Raises:
1950
+ ValueError: If the type is unknown, or no transformer has that name, or
1951
+ several do.
1952
+ """
1953
+ if not self.network:
1954
+ raise ValueError("No network loaded")
1955
+
1956
+ try:
1957
+ # Check if the standard type exists
1958
+ if new_type not in self.network.std_types["trafo"]:
1959
+ raise ValueError(
1960
+ f"Transformer type '{new_type}' not found in standard types"
1961
+ )
1962
+
1963
+ table = self.network.trafo
1964
+ eid = self._element_index("trafo", trafo_id)
1965
+ kept = {
1966
+ column: table.at[eid, column]
1967
+ for column in self._KEPT_BY_A_TYPE_CHANGE
1968
+ if column in table
1969
+ }
1970
+ # Apply the new type
1971
+ pp.change_std_type(self.network, eid, new_type, element="trafo")
1972
+ for column, value in kept.items():
1973
+ table.at[eid, column] = value
1974
+ self.logger.info(f"Upgraded transformer {trafo_id} to type {new_type}")
1975
+ self._clamp_tap_position(trafo_id, eid, new_type)
1976
+ except Exception as e:
1977
+ self.logger.error(f"Failed to upgrade transformer: {str(e)}")
1978
+ raise
1979
+
1980
+ def _clamp_tap_position(self, trafo_id: str, eid: int, new_type: str) -> None:
1981
+ """
1982
+ Bring the tap position of the transformer at `eid` into the tap range its table
1983
+ row has, which a type change has just replaced by that of the new type: the unit
1984
+ keeps its position, which another range can leave outside it. Logs a warning
1985
+ when it moves it. A row without a range or a position (NaN) is left alone. A
1986
+ type without tap columns does not give the row one: pandapower's
1987
+ `change_std_type` then keeps the ``tap_min``, ``tap_max``, ``tap_neutral`` and
1988
+ ``tap_step_*`` the row had, so that the unit keeps its range and its position.
1989
+ """
1990
+ table = self.network.trafo
1991
+ if not {"tap_pos", "tap_min", "tap_max"} <= set(table.columns):
1992
+ return
1993
+ position, low, high = (
1994
+ table.at[eid, c] for c in ("tap_pos", "tap_min", "tap_max")
1995
+ )
1996
+ if pd.isna(position) or pd.isna(low) or pd.isna(high) or low > high:
1997
+ return
1998
+ clamped = min(max(position, low), high)
1999
+ if clamped == position:
2000
+ return
2001
+ table.at[eid, "tap_pos"] = clamped
2002
+ self.logger.warning(
2003
+ f"Tap position of transformer {trafo_id} moved from {position:g} to "
2004
+ f"{clamped:g}, into the range {low:g} to {high:g} of type {new_type}"
2005
+ )
2006
+
2007
+ def add_parallel_transformer(self, trafo_id: str) -> int:
2008
+ """
2009
+ Add a parallel transformer.
2010
+
2011
+ Args:
2012
+ trafo_id (str): Name of the transformer to add a unit to.
2013
+
2014
+ Returns:
2015
+ int: Number of parallel units of the transformer after the addition.
2016
+
2017
+ Raises:
2018
+ ValueError: If no transformer has that name, or several do.
2019
+ """
2020
+ if not self.network:
2021
+ raise ValueError("No network loaded")
2022
+
2023
+ try:
2024
+ eid = self._element_index("trafo", trafo_id)
2025
+ self.network.trafo.loc[eid, "parallel"] += 1
2026
+ self.logger.info(f"Added parallel transformer to {trafo_id}")
2027
+ return self.network.trafo.at[eid, "parallel"]
2028
+ except Exception as e:
2029
+ self.logger.error(f"Failed to add parallel transformer: {str(e)}")
2030
+ raise
2031
+
2032
+ def get_losses(self) -> dict[str, float]:
2033
+ """
2034
+ Calculate network losses.
2035
+
2036
+ Returns:
2037
+ Dict[str, float]: Dictionary with active and reactive power losses.
2038
+ """
2039
+ if (
2040
+ not self.network
2041
+ or not self.latest_results
2042
+ or not self.latest_results.get("converged", False)
2043
+ ):
2044
+ raise ValueError("Need a converged power flow solution to calculate losses")
2045
+
2046
+ # Calculate total losses
2047
+ p_losses = 0.0
2048
+ q_losses = 0.0
2049
+
2050
+ # Line losses
2051
+ if "pl_mw" in self.network.res_line:
2052
+ p_losses += self.network.res_line.pl_mw.sum()
2053
+ if "ql_mvar" in self.network.res_line:
2054
+ q_losses += self.network.res_line.ql_mvar.sum()
2055
+
2056
+ # Transformer losses
2057
+ if "pl_mw" in self.network.res_trafo:
2058
+ p_losses += self.network.res_trafo.pl_mw.sum()
2059
+ if "ql_mvar" in self.network.res_trafo:
2060
+ q_losses += self.network.res_trafo.ql_mvar.sum()
2061
+
2062
+ return {"p_loss_mw": p_losses, "q_loss_mvar": q_losses}
2063
+
2064
+ def get_network_metrics(self) -> dict[str, Any]:
2065
+ """
2066
+ Get various network metrics.
2067
+
2068
+ Returns:
2069
+ Dict[str, Any]: Dictionary with network metrics.
2070
+ """
2071
+ if not self.network:
2072
+ raise ValueError("No network loaded")
2073
+
2074
+ metrics = {
2075
+ "network_size": {
2076
+ "buses": len(self.network.bus),
2077
+ "lines": len(self.network.line),
2078
+ "transformers": len(self.network.trafo),
2079
+ "loads": len(self.network.load) if hasattr(self.network, "load") else 0,
2080
+ "generators": len(self.network.gen)
2081
+ if hasattr(self.network, "gen")
2082
+ else 0,
2083
+ "sgens": len(self.network.sgen) if hasattr(self.network, "sgen") else 0,
2084
+ }
2085
+ }
2086
+
2087
+ # Add voltage statistics if power flow results are available
2088
+ if self.latest_results and self.latest_results.get("converged", False):
2089
+ metrics["voltage"] = self.network.res_bus.vm_pu.describe().to_dict()
2090
+
2091
+ # Add loading statistics
2092
+ if "loading_percent" in self.network.res_line:
2093
+ metrics["line_loading"] = (
2094
+ self.network.res_line.loading_percent.describe().to_dict()
2095
+ )
2096
+
2097
+ if "loading_percent" in self.network.res_trafo:
2098
+ metrics["trafo_loading"] = (
2099
+ self.network.res_trafo.loading_percent.describe().to_dict()
2100
+ )
2101
+
2102
+ # Add loss metrics
2103
+ losses = self.get_losses()
2104
+ metrics["losses"] = losses
2105
+
2106
+ return metrics
2107
+
2108
+ def create_topology_graph(self) -> Any:
2109
+ """
2110
+ Create a NetworkX graph representing the network topology.
2111
+
2112
+ Returns:
2113
+ networkx.Graph: NetworkX graph object.
2114
+ """
2115
+ try:
2116
+ import networkx as nx
2117
+ except ImportError:
2118
+ self.logger.error(
2119
+ "NetworkX is required for topology graph creation but not installed"
2120
+ )
2121
+ raise ImportError("NetworkX is required for topology graph creation")
2122
+
2123
+ if not self.network:
2124
+ raise ValueError("No network loaded")
2125
+
2126
+ # Create undirected graph
2127
+ G = nx.Graph()
2128
+
2129
+ # Prefer explicit pandapower geodata tables when available.
2130
+ bus_geodata = None
2131
+ if hasattr(self.network, "bus_geodata"):
2132
+ if (
2133
+ self.network.bus_geodata is not None
2134
+ and not self.network.bus_geodata.empty
2135
+ ):
2136
+ bus_geodata = self.network.bus_geodata
2137
+
2138
+ # Fall back to the "geo" column in the bus table when bus_geodata is missing.
2139
+ use_bus_geo_column = False
2140
+ if bus_geodata is None and "geo" in self.network.bus.columns:
2141
+ if self.network.bus["geo"].notna().any():
2142
+ use_bus_geo_column = True
2143
+
2144
+ # Add buses as nodes
2145
+ for i, bus in self.network.bus.iterrows():
2146
+ node_attrs = {
2147
+ "type": "bus",
2148
+ "voltage": bus.vn_kv,
2149
+ "name": bus.get("name"),
2150
+ }
2151
+ # Use coordinates from bus_geodata if present.
2152
+ if bus_geodata is not None and i in bus_geodata.index:
2153
+ x = float(bus_geodata.at[i, "x"])
2154
+ y = float(bus_geodata.at[i, "y"])
2155
+ node_attrs["x"] = x
2156
+ node_attrs["y"] = y
2157
+ node_attrs["pos"] = (x, y)
2158
+ elif use_bus_geo_column:
2159
+ # Parse GeoJSON points from the "geo" column.
2160
+ geo = bus.get("geo")
2161
+ if isinstance(geo, str):
2162
+ try:
2163
+ import json
2164
+
2165
+ geo = json.loads(geo)
2166
+ except Exception:
2167
+ geo = None
2168
+ if isinstance(geo, dict) and geo.get("type") == "Point":
2169
+ coords = geo.get("coordinates", [])
2170
+ if isinstance(coords, list | tuple) and len(coords) >= 2:
2171
+ x = float(coords[0])
2172
+ y = float(coords[1])
2173
+ node_attrs["x"] = x
2174
+ node_attrs["y"] = y
2175
+ node_attrs["pos"] = (x, y)
2176
+ G.add_node(i, **node_attrs)
2177
+
2178
+ # Pull line geodata if present to draw polylines.
2179
+ line_geodata = None
2180
+ if hasattr(self.network, "line_geodata"):
2181
+ if (
2182
+ self.network.line_geodata is not None
2183
+ and not self.network.line_geodata.empty
2184
+ ):
2185
+ line_geodata = self.network.line_geodata
2186
+ # Fall back to the "geo" column in the line table when line_geodata is missing.
2187
+ use_line_geo_column = False
2188
+ if line_geodata is None and "geo" in self.network.line.columns:
2189
+ if self.network.line["geo"].notna().any():
2190
+ use_line_geo_column = True
2191
+
2192
+ # Add lines as edges
2193
+ for i, line in self.network.line.iterrows():
2194
+ from_bus = line.from_bus
2195
+ to_bus = line.to_bus
2196
+ edge_attrs = {
2197
+ "type": "line",
2198
+ "id": i,
2199
+ "name": line.get("name"),
2200
+ }
2201
+ # Attach explicit line coordinates if available.
2202
+ if line_geodata is not None and i in line_geodata.index:
2203
+ coords = line_geodata.at[i, "coords"]
2204
+ if coords is not None:
2205
+ edge_attrs["coords"] = coords
2206
+ elif use_line_geo_column:
2207
+ # Parse GeoJSON lines from the "geo" column.
2208
+ geo = line.get("geo")
2209
+ if isinstance(geo, str):
2210
+ try:
2211
+ import json
2212
+
2213
+ geo = json.loads(geo)
2214
+ except Exception:
2215
+ geo = None
2216
+ if isinstance(geo, dict) and geo.get("type") == "LineString":
2217
+ coords = geo.get("coordinates", [])
2218
+ if coords is not None:
2219
+ edge_attrs["coords"] = coords
2220
+ G.add_edge(from_bus, to_bus, **edge_attrs)
2221
+
2222
+ # Add transformers as edges
2223
+ for i, trafo in self.network.trafo.iterrows():
2224
+ hv_bus = trafo.hv_bus
2225
+ lv_bus = trafo.lv_bus
2226
+ edge_attrs = {
2227
+ "type": "transformer",
2228
+ "id": i,
2229
+ "name": trafo.get("name"),
2230
+ }
2231
+ # Compute a midpoint for transformer markers when bus positions are known.
2232
+ if bus_geodata is not None:
2233
+ if hv_bus in bus_geodata.index and lv_bus in bus_geodata.index:
2234
+ x1 = float(bus_geodata.at[hv_bus, "x"])
2235
+ y1 = float(bus_geodata.at[hv_bus, "y"])
2236
+ x2 = float(bus_geodata.at[lv_bus, "x"])
2237
+ y2 = float(bus_geodata.at[lv_bus, "y"])
2238
+ edge_attrs["midpoint"] = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
2239
+ elif use_bus_geo_column:
2240
+ hv_geo = self.network.bus.at[hv_bus, "geo"]
2241
+ lv_geo = self.network.bus.at[lv_bus, "geo"]
2242
+ for name, value in (("hv", hv_geo), ("lv", lv_geo)):
2243
+ if isinstance(value, str):
2244
+ try:
2245
+ import json
2246
+
2247
+ value = json.loads(value)
2248
+ except Exception:
2249
+ value = None
2250
+ if name == "hv":
2251
+ hv_geo = value
2252
+ else:
2253
+ lv_geo = value
2254
+ # Parse GeoJSON points for transformer midpoint computation.
2255
+ if (
2256
+ isinstance(hv_geo, dict)
2257
+ and hv_geo.get("type") == "Point"
2258
+ and isinstance(lv_geo, dict)
2259
+ and lv_geo.get("type") == "Point"
2260
+ ):
2261
+ hv_coords = hv_geo.get("coordinates", [])
2262
+ lv_coords = lv_geo.get("coordinates", [])
2263
+ if (
2264
+ isinstance(hv_coords, list | tuple)
2265
+ and len(hv_coords) >= 2
2266
+ and isinstance(lv_coords, list | tuple)
2267
+ and len(lv_coords) >= 2
2268
+ ):
2269
+ x1 = float(hv_coords[0])
2270
+ y1 = float(hv_coords[1])
2271
+ x2 = float(lv_coords[0])
2272
+ y2 = float(lv_coords[1])
2273
+ edge_attrs["midpoint"] = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
2274
+ G.add_edge(hv_bus, lv_bus, **edge_attrs)
2275
+
2276
+ return G
2277
+
2278
+ def get_line_imax(self, line_type):
2279
+ """
2280
+ Fetches and returns the maximum intensity for a given line type.
2281
+
2282
+ Args:
2283
+ line_type (str): Specifies the type of line for which the maximum value is to be retrieved.
2284
+
2285
+ Returns:
2286
+ float: The maximum intensity associated with the specified line type.
2287
+ """
2288
+
2289
+ try:
2290
+ line_std_type = self.network.std_types["line"][line_type]
2291
+ except KeyError:
2292
+ self.logger.error(f"Line type '{line_type}' not found in standard types")
2293
+ raise ValueError(f"Line type '{line_type}' not found in standard types")
2294
+
2295
+ return line_std_type["max_i_ka"] * 1000.0 # pandapower stores data in kA
2296
+
2297
+ def get_line_r_ohm_per_km(self, line_type: str) -> float:
2298
+ """
2299
+ Get the resistance per unit length for a given line type.
2300
+
2301
+ Args:
2302
+ line_type (str): The type of the line.
2303
+
2304
+ Returns:
2305
+ float: The resistance per unit length (Ohm/km).
2306
+ """
2307
+ if self.network is None:
2308
+ raise ValueError("Network not initialized. Create or load a network first.")
2309
+
2310
+ try:
2311
+ line_std_type = self.network.std_types["line"][line_type]
2312
+ return line_std_type["r_ohm_per_km"]
2313
+ except KeyError:
2314
+ self.logger.error(f"Line type '{line_type}' not found in standard types")
2315
+ raise ValueError(f"Line type '{line_type}' not found in standard types")
2316
+
2317
+ def get_line_type(self, line_id: str) -> str:
2318
+ """
2319
+ Returns the type of a line based on the provided line ID.
2320
+
2321
+ Args:
2322
+ line_id (str): The unique identifier (name) of the line.
2323
+
2324
+ Returns:
2325
+ str: The standard type of the line.
2326
+
2327
+ Raises:
2328
+ ValueError: If the network is not initialized or if the line is not found.
2329
+ """
2330
+ if self.network is None:
2331
+ raise ValueError("Network not initialized. Create or load a network first.")
2332
+
2333
+ try:
2334
+ # Find the line with the given name and return the standard type of the line
2335
+ return self.network.line.loc[
2336
+ self.network.line.name == line_id, "std_type"
2337
+ ].iloc[0]
2338
+ except (IndexError, KeyError):
2339
+ self.logger.error(f"Line with name '{line_id}' not found in the network")
2340
+ raise ValueError(f"Line with name '{line_id}' not found in the network")
2341
+
2342
+ def get_line_length(self, line_id: int | str) -> float:
2343
+ """
2344
+ Get the length of a line by its ID.
2345
+
2346
+ Args:
2347
+ line_id (Union[int, str]): The ID of the line.
2348
+
2349
+ Returns:
2350
+ float: The length of the line in kilometers.
2351
+
2352
+ Raises:
2353
+ ValueError: If the network is not initialized or if the line is not found.
2354
+ """
2355
+ if self.network is None:
2356
+ raise ValueError("Network not initialized. Create or load a network first.")
2357
+
2358
+ try:
2359
+ # Find the line with the given name and return its length
2360
+ return self.network.line.loc[
2361
+ self.network.line.name == line_id, "length_km"
2362
+ ].iloc[0]
2363
+ except (IndexError, KeyError):
2364
+ self.logger.error(f"Line with name '{line_id}' not found in the network")
2365
+ raise ValueError(f"Line with name '{line_id}' not found in the network")
2366
+
2367
+ def get_line_parallel(self, line_id: int | str) -> int:
2368
+ """
2369
+ Get the number of parallel conductors of a line (1 for a single line).
2370
+ """
2371
+ try:
2372
+ return int(
2373
+ self.network.line.loc[
2374
+ self.network.line.name == line_id, "parallel"
2375
+ ].iloc[0]
2376
+ )
2377
+ except (IndexError, KeyError):
2378
+ return 1
2379
+
2380
+ def get_line_rating(self, line_id: int | str) -> float | None:
2381
+ """
2382
+ Get the rating (A) of one conductor of a line, as the line table holds it
2383
+ (`max_i_ka`), whether or not it is that of its type. The loading the engine
2384
+ reports is relative to it, times the derating factor `df` and the parallel
2385
+ conductors.
2386
+
2387
+ Returns:
2388
+ Optional[float]: The rating of one conductor, None if the line is not
2389
+ found or has none.
2390
+ """
2391
+ try:
2392
+ rating = float(
2393
+ self.network.line.loc[
2394
+ self.network.line.name == line_id, "max_i_ka"
2395
+ ].iloc[0]
2396
+ )
2397
+ except (IndexError, KeyError, AttributeError, TypeError, ValueError):
2398
+ return None
2399
+ return rating * 1000.0 if rating > 0.0 else None
2400
+
2401
+ def get_line_base_impedance(self, line_id: int | str) -> float:
2402
+ """
2403
+ Get the per-unit base impedance (ohm) of a line, from its from-bus voltage and the network base power.
2404
+ """
2405
+ line = self.network.line.loc[self.network.line.name == line_id].iloc[0]
2406
+ vn_kv = float(self.network.bus.at[int(line.from_bus), "vn_kv"])
2407
+ return vn_kv**2 / float(self.network.sn_mva)
2408
+
2409
+ def get_transformer_type(self, transformer_id: str) -> str:
2410
+ """
2411
+ Returns the type of a transformer based on the provided transformer ID.
2412
+
2413
+ Args:
2414
+ transformer_id (str): The unique identifier (name) of the transformer.
2415
+
2416
+ Returns:
2417
+ str: The standard type of the transformer.
2418
+
2419
+ Raises:
2420
+ ValueError: If the network is not initialized or if the transformer is not found.
2421
+ """
2422
+ if self.network is None:
2423
+ raise ValueError("Network not initialized. Create or load a network first.")
2424
+
2425
+ try:
2426
+ # Find the line with the given name and return the standard type of the line
2427
+ return self.network.trafo.loc[
2428
+ self.network.trafo.name == transformer_id, "std_type"
2429
+ ].iloc[0]
2430
+ except (IndexError, KeyError):
2431
+ self.logger.error(
2432
+ f"Transformer with name '{transformer_id}' not found in the network"
2433
+ )
2434
+ raise ValueError(
2435
+ f"Transformer with name '{transformer_id}' not found in the network"
2436
+ )
2437
+
2438
+ def get_transformer_types_in_place(self) -> set[str | None]:
2439
+ """
2440
+ Get the standard types of the transformers in service of the network, None for
2441
+ those that have no type: a `std_type` of None, NaN or '', as pandapower writes
2442
+ it for a unit created from its parameters.
2443
+ """
2444
+ if self.network is None or "std_type" not in self.network.trafo:
2445
+ return set()
2446
+ trafo = self.network.trafo
2447
+ types = trafo.std_type[trafo.in_service.astype(bool)]
2448
+ return {t if isinstance(t, str) and t else None for t in types.unique()}
2449
+
2450
+ def get_transformers_info(self) -> pd.DataFrame:
2451
+ """
2452
+ Type (`std_type`, as the table holds it) and number of units in parallel
2453
+ (`parallel`) of the two-winding transformers, in service or not, indexed by
2454
+ name.
2455
+ """
2456
+ trafo = self.network.trafo
2457
+ info = pd.DataFrame(
2458
+ {
2459
+ "std_type": trafo["std_type"].to_numpy()
2460
+ if "std_type" in trafo
2461
+ else None,
2462
+ "parallel": trafo["parallel"].to_numpy() if "parallel" in trafo else 1,
2463
+ },
2464
+ index=trafo["name"].to_numpy(),
2465
+ )
2466
+ return info
2467
+
2468
+ def get_transformer_parallel(self, transformer_id: str) -> int:
2469
+ """
2470
+ Get the number of parallel units of a transformer (1 for a single unit).
2471
+ """
2472
+ try:
2473
+ return int(
2474
+ self.network.trafo.loc[
2475
+ self.network.trafo.name == transformer_id, "parallel"
2476
+ ].iloc[0]
2477
+ )
2478
+ except (IndexError, KeyError):
2479
+ return 1
2480
+
2481
+ def get_transformer_rating(self, transformer_id: str) -> float | None:
2482
+ """
2483
+ Get the rating (VA) of one unit of a transformer, as the transformer table
2484
+ holds it, whether or not the unit has a catalogued type.
2485
+
2486
+ Returns:
2487
+ Optional[float]: The rating of one unit (`sn_mva`, not multiplied by the
2488
+ parallel units), or None if the transformer is not found.
2489
+ """
2490
+ try:
2491
+ return float(
2492
+ self.network.trafo.loc[
2493
+ self.network.trafo.name == transformer_id, "sn_mva"
2494
+ ].iloc[0]
2495
+ * 1.0e6
2496
+ )
2497
+ except (IndexError, KeyError, AttributeError):
2498
+ return None
2499
+
2500
+ def get_transformer_max_power(self, transformer_type: str) -> float:
2501
+ """
2502
+ Retrieves the maximum power rating of a specified transformer type.
2503
+
2504
+ This method returns the maximum power rating (in VA) for the requested transformer type
2505
+ by looking up the standard type information in the PandaPower network model.
2506
+
2507
+ Args:
2508
+ transformer_type (str): The type of the transformer for which the maximum power rating has to be determined.
2509
+
2510
+ Returns:
2511
+ float: The maximum power rating for the specified transformer type in VA.
2512
+
2513
+ Raises:
2514
+ ValueError: If the transformer type is not found in the standard types.
2515
+ """
2516
+ if self.network is None:
2517
+ raise ValueError("Network not initialized. Create or load a network first.")
2518
+
2519
+ try:
2520
+ # Look up the transformer type in the standard types dictionary
2521
+ trafo_std_type = self.network.std_types["trafo"][transformer_type]
2522
+ except KeyError:
2523
+ self.logger.debug(
2524
+ f"Transformer type '{transformer_type}' not found in standard types"
2525
+ )
2526
+ raise ValueError(
2527
+ f"Transformer type '{transformer_type}' not found in standard types"
2528
+ )
2529
+
2530
+ # PandaPower stores transformer ratings in MVA, convert to VA
2531
+ return trafo_std_type["sn_mva"] * 1.0e6 # Convert MVA to VA
2532
+
2533
+ def partition_network(self) -> dict[int, Any]:
2534
+ """
2535
+ Partition the network into galvanically connected components.
2536
+
2537
+ This method identifies separate electrical areas in the network that are not
2538
+ connected to each other by power lines or other conducting elements, but can
2539
+ be connected by transformers.
2540
+
2541
+ Returns:
2542
+ Dict[int, Any]: Dictionary mapping component IDs to lists of elements (buses, lines, etc.)
2543
+ in each connected component.
2544
+ """
2545
+ if not self.network:
2546
+ raise ValueError("No network loaded")
2547
+
2548
+ try:
2549
+ import networkx as nx
2550
+ from pandapower.topology import create_nxgraph
2551
+ except ImportError:
2552
+ self.logger.error(
2553
+ "NetworkX is required for network partitioning but not installed"
2554
+ )
2555
+ raise ImportError("NetworkX is required for network partitioning")
2556
+
2557
+ net = self.network
2558
+ # Undirected graph of the network without transformers: galvanic connections
2559
+ G = create_nxgraph(net, include_trafos=False)
2560
+ component_of_bus: dict[int, int] = {}
2561
+ for i, component in enumerate(nx.connected_components(G)):
2562
+ for bus in component:
2563
+ component_of_bus[int(bus)] = i + 1 # component IDs start from 1
2564
+ n_components = len(set(component_of_bus.values()))
2565
+
2566
+ result = {
2567
+ component_id: {
2568
+ "buses": [],
2569
+ "lines": [],
2570
+ "transformers": [],
2571
+ "loads": [],
2572
+ "generators": [],
2573
+ "static_generators": [],
2574
+ }
2575
+ for component_id in range(1, n_components + 1)
2576
+ }
2577
+
2578
+ def comp(bus_values):
2579
+ return pd.Series(bus_values).map(component_of_bus)
2580
+
2581
+ bus_comp = comp(net.bus.index.to_numpy())
2582
+ for name, c in zip(net.bus["name"], bus_comp, strict=True):
2583
+ if pd.notna(c):
2584
+ result[int(c)]["buses"].append(name)
2585
+
2586
+ if not net.line.empty:
2587
+ c_from = comp(net.line["from_bus"].to_numpy())
2588
+ c_to = comp(net.line["to_bus"].to_numpy())
2589
+ same = (c_from == c_to) & c_from.notna()
2590
+ for name, c in zip(
2591
+ net.line["name"][same.to_numpy()], c_from[same], strict=False
2592
+ ):
2593
+ result[int(c)]["lines"].append(name)
2594
+
2595
+ for table, key, bus_col in (
2596
+ ("trafo", "transformers", "lv_bus"),
2597
+ ("load", "loads", "bus"),
2598
+ ("gen", "generators", "bus"),
2599
+ ("sgen", "static_generators", "bus"),
2600
+ ):
2601
+ df = getattr(net, table, None)
2602
+ if df is None or df.empty:
2603
+ continue
2604
+ c = comp(df[bus_col].to_numpy())
2605
+ for name, ci in zip(df["name"], c, strict=True):
2606
+ if pd.notna(ci):
2607
+ result[int(ci)][key].append(name)
2608
+
2609
+ self.logger.info(
2610
+ f"Network partitioned into {len(result)} galvanically connected components"
2611
+ )
2612
+ self.network_partition = result
2613
+ return result
2614
+
2615
+ def get_voltage_magnitude_range(self, component_id: int) -> dict[str, float]:
2616
+ """
2617
+ Get the minimum and maximum voltage magnitudes in a specific network component.
2618
+
2619
+ This method determines the voltage magnitude bounds within a given network
2620
+ component identified by its component_id.
2621
+
2622
+ Args:
2623
+ component_id (int): The ID of the component to analyze.
2624
+
2625
+ Returns:
2626
+ Dict[str, float]: Dictionary containing 'min' and 'max' voltage magnitude values in per unit.
2627
+
2628
+ Raises:
2629
+ ValueError: If the network is not initialized, power flow hasn't been run,
2630
+ or if the component ID is invalid.
2631
+ """
2632
+ if self.network is None:
2633
+ raise ValueError("Network not initialized. Create or load a network first.")
2634
+
2635
+ if not self.latest_results or not self.latest_results.get("converged", False):
2636
+ raise ValueError(
2637
+ "Need a converged power flow solution to get voltage magnitudes"
2638
+ )
2639
+
2640
+ if self.network_partition is None:
2641
+ self.logger.info("Network not yet partitioned. Partitioning now.")
2642
+ self.partition_network()
2643
+
2644
+ if component_id not in self.network_partition:
2645
+ raise ValueError(
2646
+ f"Component ID {component_id} not found in network partition"
2647
+ )
2648
+
2649
+ # Get all bus names in the component
2650
+ component_buses = self.network_partition[component_id]["buses"]
2651
+
2652
+ if not component_buses:
2653
+ raise ValueError(f"No buses found in component {component_id}")
2654
+
2655
+ # Create a mask for buses in this component
2656
+ mask = self.network.bus["name"].isin(component_buses)
2657
+
2658
+ # Get indices of buses in this component
2659
+ bus_indices = self.network.bus.loc[mask].index
2660
+
2661
+ if len(bus_indices) == 0:
2662
+ raise ValueError(f"No matching buses found for component {component_id}")
2663
+
2664
+ # Extract voltage magnitudes for these buses
2665
+ voltage_magnitudes = self.network.res_bus.loc[bus_indices, "vm_pu"]
2666
+
2667
+ # Return min and max values
2668
+ return {
2669
+ "min": float(voltage_magnitudes.min()),
2670
+ "max": float(voltage_magnitudes.max()),
2671
+ }
2672
+
2673
+ def get_transformer_tap_positions(self, transformer_id: int | str) -> np.ndarray:
2674
+ """
2675
+ Get all available tap positions for a given transformer in per unit voltage values.
2676
+
2677
+ This method returns all possible tap positions that can be set for the specified
2678
+ transformer, expressed as per unit voltage values (e.g., [-0.05, -0.025, 0, 0.025, 0.05]).
2679
+
2680
+ Args:
2681
+ transformer_id (Union[int, str]): The ID of the transformer to get tap positions for.
2682
+
2683
+ Returns:
2684
+ np.ndarray: Array of all available tap positions as per unit voltage values,
2685
+ typically sorted from lowest to highest.
2686
+
2687
+ Raises:
2688
+ ValueError: If the transformer does not exist or if tap positions cannot be determined.
2689
+ """
2690
+ if self.network is None:
2691
+ raise ValueError("Network not initialized. Create or load a network first.")
2692
+
2693
+ try:
2694
+ import numpy as np
2695
+
2696
+ # Find the transformer by name
2697
+ mask = self.network.trafo["name"] == transformer_id
2698
+
2699
+ if not any(mask):
2700
+ raise ValueError(
2701
+ f"Transformer with ID '{transformer_id}' not found in the network"
2702
+ )
2703
+
2704
+ # Get transformer parameters related to tap changing
2705
+ tap_min = self.network.trafo.loc[mask, "tap_min"].values[0]
2706
+ tap_max = self.network.trafo.loc[mask, "tap_max"].values[0]
2707
+ tap_step_percent = self.network.trafo.loc[mask, "tap_step_percent"].values[
2708
+ 0
2709
+ ]
2710
+ tap_neutral = self.network.trafo.loc[mask, "tap_neutral"].values[0]
2711
+ tap_side = self.network.trafo.loc[mask, "tap_side"].values[0]
2712
+
2713
+ # Create numpy array of all possible tap positions
2714
+ tap_positions = np.arange(int(tap_min), int(tap_max) + 1)
2715
+
2716
+ # Calculate per unit voltage change for each tap position
2717
+ step_pu = tap_step_percent / 100.0
2718
+ voltage_pu_changes = (tap_positions - tap_neutral) * step_pu
2719
+
2720
+ # For tap changer on the HV side, the voltage effect is inverted
2721
+ # when viewed from the LV side
2722
+ if tap_side == "hv":
2723
+ voltage_pu_changes = -voltage_pu_changes
2724
+
2725
+ # Round to avoid floating point precision issues
2726
+ return np.round(voltage_pu_changes, 6)
2727
+
2728
+ except Exception as e:
2729
+ self.logger.error(f"Failed to get transformer tap positions: {str(e)}")
2730
+ raise ValueError(
2731
+ f"Error retrieving tap positions for transformer '{transformer_id}': {str(e)}"
2732
+ )
2733
+
2734
+ def _jacobian_context(self) -> dict[str, Any]:
2735
+ """
2736
+ Collect the converged Newton-Raphson state needed by the linearised voltage responses.
2737
+ """
2738
+ net = self.network
2739
+ if not self._has_converged_results():
2740
+ raise RuntimeError(_NO_CONVERGED_RUN)
2741
+ if not self._tables_match_results():
2742
+ raise RuntimeError(_STALE_TABLES)
2743
+ if not hasattr(net, "_ppc") or net._ppc is None or "internal" not in net._ppc:
2744
+ raise RuntimeError(
2745
+ "Pandapower network internal PPC structure not available. Run a power flow."
2746
+ )
2747
+ ppc_int = net._ppc["internal"]
2748
+ pq = np.asarray(ppc_int.get("pq", []), dtype=int)
2749
+ pv = np.asarray(ppc_int.get("pv", []), dtype=int)
2750
+ J_sparse = self._converged_jacobian()
2751
+ if J_sparse is None or J_sparse.shape == (0, 0) or J_sparse.nnz == 0:
2752
+ raise ValueError(
2753
+ "Jacobian matrix J is not available or empty in net._ppc['internal']. Has a power flow been run with 'calculate_voltage_angles=True' and appropriate algorithm settings?"
2754
+ )
2755
+ V_complex = ppc_int.get("V")
2756
+ if V_complex is None:
2757
+ raise ValueError("Complex voltages 'V' not found in net._ppc['internal'].")
2758
+ n_p_eq = len(pv) + len(pq)
2759
+ n_q_eq = len(pq)
2760
+ if n_p_eq + n_q_eq == 0:
2761
+ raise ValueError(
2762
+ "No PQ or PV buses found for sensitivity calculation (excluding slack bus equations)."
2763
+ )
2764
+ if J_sparse.shape[0] != n_p_eq + n_q_eq:
2765
+ raise ValueError(
2766
+ f"Jacobian rows {J_sparse.shape[0]} do not match the number of equations {n_p_eq + n_q_eq}."
2767
+ )
2768
+ n_ppc = len(V_complex)
2769
+ # Equation ordering of the Newton-Raphson Jacobian: P rows for (pv, pq), Q rows for pq
2770
+ pos_p = np.full(n_ppc, -1, dtype=int)
2771
+ pos_p[np.concatenate([pv, pq])] = np.arange(n_p_eq)
2772
+ pos_q = np.full(n_ppc, -1, dtype=int)
2773
+ pos_q[pq] = np.arange(n_q_eq)
2774
+ return {
2775
+ "J": J_sparse,
2776
+ "V": V_complex,
2777
+ "n_ppc": n_ppc,
2778
+ "n_p_eq": n_p_eq,
2779
+ "n_q_eq": n_q_eq,
2780
+ "pos_p": pos_p,
2781
+ "pos_q": pos_q,
2782
+ "bus_lookup": np.asarray(net._pd2ppc_lookups["bus"]),
2783
+ }
2784
+
2785
+ def _select_lines(self, line_names: list[str] | None) -> pd.DataFrame:
2786
+ """
2787
+ Lines that conduct: in service, with no open line switch at either end, and between
2788
+ two buses that are in service and supplied.
2789
+
2790
+ A line opened by a switch (a normally-open point, for instance) carries no
2791
+ current, so changing it changes no voltage and it is on no path to a source. The
2792
+ same goes for a line to a bus out of service, and for one in an island that no
2793
+ external grid reaches (through lines, transformers and closed switches), which
2794
+ pandapower leaves without a solution.
2795
+ """
2796
+ lines = self.network.line
2797
+ if "in_service" in lines.columns:
2798
+ lines = lines[lines["in_service"].astype(bool)]
2799
+ switches = self.network.switch
2800
+ if not switches.empty:
2801
+ opened = switches.loc[
2802
+ (switches["et"] == "l") & ~switches["closed"].astype(bool), "element"
2803
+ ]
2804
+ if not opened.empty:
2805
+ lines = lines[~lines.index.isin(opened)]
2806
+ if not lines.empty:
2807
+ dead = self._dead_buses()
2808
+ if dead:
2809
+ lines = lines[
2810
+ ~(lines["from_bus"].isin(dead) | lines["to_bus"].isin(dead))
2811
+ ]
2812
+ if line_names is not None:
2813
+ lines = lines[lines["name"].isin(line_names)]
2814
+ return lines
2815
+
2816
+ def _dead_buses(self) -> frozenset[int]:
2817
+ """
2818
+ Indices of the buses that no line can connect to a solution: those out of service
2819
+ and those of an island with no source (no external grid, in service, reaches them).
2820
+
2821
+ Finding the islands builds pandapower's topology graph, which takes a few
2822
+ milliseconds on a feeder, more than the rest of `_select_lines`. The result is
2823
+ kept with the topology it was found in (`_topology_key`), and found again only
2824
+ when that topology has changed, whether a power flow was run since or not: a
2825
+ bus put out of service or a switch opened between two calls is seen at once.
2826
+ """
2827
+ key = self._topology_key()
2828
+ if self._dead_buses_cache is not None and self._dead_buses_cache[0] == key:
2829
+ return self._dead_buses_cache[1]
2830
+
2831
+ # Imported here, as the other uses of the topology module of pandapower
2832
+ import pandapower.topology as ppt
2833
+
2834
+ net = self.network
2835
+ in_service = net.bus["in_service"].astype(bool)
2836
+ dead = frozenset(int(bus) for bus in net.bus.index[~in_service]) | frozenset(
2837
+ int(bus) for bus in ppt.unsupplied_buses(net)
2838
+ )
2839
+ self._dead_buses_cache = (key, dead)
2840
+ return dead
2841
+
2842
+ def _topology_key(self) -> tuple:
2843
+ """
2844
+ What the topology graph of the network is built from (`_TOPOLOGY_TABLES`,
2845
+ `_TOPOLOGY_COLUMNS`): equal keys give the same dead buses. About 0.05 ms on the
2846
+ largest feeder.
2847
+ """
2848
+ net = self.network
2849
+ parts: list[Any] = []
2850
+ for name in _TOPOLOGY_TABLES:
2851
+ table = net.get(name)
2852
+ if not isinstance(table, pd.DataFrame) or len(table.index) == 0:
2853
+ continue
2854
+ present = set(table.columns)
2855
+ columns = [c for c in _TOPOLOGY_COLUMNS if c in present]
2856
+ for label, values in zip(
2857
+ [name, *columns],
2858
+ [table.index.to_numpy(), *(table[c].to_numpy() for c in columns)],
2859
+ strict=True,
2860
+ ):
2861
+ if values.dtype.kind in "biuf":
2862
+ parts.append((label, values.dtype.str, values.tobytes()))
2863
+ else:
2864
+ parts.append((label, tuple(values.tolist())))
2865
+ return tuple(parts)
2866
+
2867
+ def _line_pu_parameters(
2868
+ self, lines: pd.DataFrame
2869
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
2870
+ """
2871
+ Equivalent (parallel-combined) per-unit series resistance and reactance of `lines`, and z_base.
2872
+ """
2873
+ net = self.network
2874
+ f_pd = lines["from_bus"].to_numpy(dtype=int)
2875
+ v_base = (
2876
+ net.bus["vn_kv"].to_numpy(dtype=float)[net.bus.index.get_indexer(f_pd)]
2877
+ * 1e3
2878
+ )
2879
+ z_base = v_base**2 / (net.sn_mva * 1e6)
2880
+ parallel = (
2881
+ lines["parallel"].to_numpy(dtype=float)
2882
+ if "parallel" in lines.columns
2883
+ else 1.0
2884
+ )
2885
+ length = lines["length_km"].to_numpy(dtype=float)
2886
+ r_pu = lines["r_ohm_per_km"].to_numpy(dtype=float) * length / parallel / z_base
2887
+ x_pu = lines["x_ohm_per_km"].to_numpy(dtype=float) * length / parallel / z_base
2888
+ return r_pu, x_pu, z_base
2889
+
2890
+ def _voltage_response(
2891
+ self,
2892
+ lines: pd.DataFrame,
2893
+ dG: np.ndarray,
2894
+ dB: np.ndarray,
2895
+ ctx: dict[str, Any],
2896
+ buses: list[str] | None = None,
2897
+ ) -> pd.DataFrame:
2898
+ """
2899
+ Linearised voltage-magnitude response (one column per line) to a change (dG, dB) of each
2900
+ line's series admittance: dx = -J^-1 dS, with dS the induced change of the bus mismatches.
2901
+
2902
+ When `buses` is given, only those rows are computed, through the transposed system
2903
+ J^T Y = E (one right-hand side per requested bus), which is much cheaper than a full
2904
+ solve when few buses are of interest.
2905
+ """
2906
+ net = self.network
2907
+ V_complex, bus_lookup, n_ppc = ctx["V"], ctx["bus_lookup"], ctx["n_ppc"]
2908
+ n_p_eq, pos_p, pos_q = ctx["n_p_eq"], ctx["pos_p"], ctx["pos_q"]
2909
+ f_ppc = bus_lookup[lines["from_bus"].to_numpy(dtype=int)]
2910
+ t_ppc = bus_lookup[lines["to_bus"].to_numpy(dtype=int)]
2911
+ valid = (f_ppc >= 0) & (f_ppc < n_ppc) & (t_ppc >= 0) & (t_ppc < n_ppc)
2912
+ if not valid.all():
2913
+ self.logger.warning(
2914
+ f"{(~valid).sum()} lines skipped in the sensitivity computation (buses not in the ppc)."
2915
+ )
2916
+ lines, dG, dB = lines[valid], dG[valid], dB[valid]
2917
+ f_ppc, t_ppc = f_ppc[valid], t_ppc[valid]
2918
+ Vi = np.abs(V_complex[f_ppc])
2919
+ Vj = np.abs(V_complex[t_ppc])
2920
+ delta = np.angle(V_complex[f_ppc]) - np.angle(V_complex[t_ppc])
2921
+ cos_d, sin_d = np.cos(delta), np.sin(delta)
2922
+ dP_f = Vi**2 * dG - Vi * Vj * (dG * cos_d + dB * sin_d)
2923
+ dQ_f = -(Vi**2) * dB - Vi * Vj * (dG * sin_d - dB * cos_d)
2924
+ dP_t = Vj**2 * dG - Vi * Vj * (dG * cos_d - dB * sin_d)
2925
+ dQ_t = -(Vj**2) * dB + Vi * Vj * (dG * sin_d + dB * cos_d)
2926
+
2927
+ n_ln = len(lines)
2928
+ n_eq = ctx["n_p_eq"] + ctx["n_q_eq"]
2929
+ cols = np.arange(n_ln)
2930
+ rows_list, cols_list, vals_list = [], [], []
2931
+ for ppc_idx, values, pos, offset in (
2932
+ (f_ppc, dP_f, pos_p, 0),
2933
+ (t_ppc, dP_t, pos_p, 0),
2934
+ (f_ppc, dQ_f, pos_q, n_p_eq),
2935
+ (t_ppc, dQ_t, pos_q, n_p_eq),
2936
+ ):
2937
+ rows = pos[ppc_idx]
2938
+ m = rows >= 0
2939
+ rows_list.append(rows[m] + offset)
2940
+ cols_list.append(cols[m])
2941
+ vals_list.append(values[m])
2942
+ dS = sparse.coo_matrix(
2943
+ (
2944
+ np.concatenate(vals_list),
2945
+ (np.concatenate(rows_list), np.concatenate(cols_list)),
2946
+ ),
2947
+ shape=(n_eq, n_ln),
2948
+ ).tocsc()
2949
+
2950
+ if buses is None:
2951
+ bus_names = net.bus.name.tolist()
2952
+ bus_pd = net.bus.index.to_numpy(dtype=int)
2953
+ else:
2954
+ name_to_idx = pd.Series(
2955
+ net.bus.index.to_numpy(dtype=int), index=net.bus["name"]
2956
+ )
2957
+ bus_names = [b for b in buses if b in name_to_idx.index]
2958
+ bus_pd = name_to_idx.loc[bus_names].to_numpy(dtype=int)
2959
+ bus_ppc = bus_lookup[bus_pd]
2960
+ ok = (bus_ppc >= 0) & (bus_ppc < n_ppc)
2961
+ q_rows = np.full(len(bus_pd), -1, dtype=int)
2962
+ q_rows[ok] = pos_q[bus_ppc[ok]]
2963
+ has_q = q_rows >= 0
2964
+ result = np.zeros((len(bus_pd), n_ln))
2965
+
2966
+ # The factors of the Jacobian are those of the other sensitivities of this
2967
+ # solution: both systems below are solved from them, without a factorisation.
2968
+ lu = self._jacobian_lu(ctx["J"])
2969
+ if buses is None or has_q.sum() > n_ln:
2970
+ dx = -lu.solve(dS.toarray())
2971
+ dVmag_pq = dx[n_p_eq:, :] # rows ordered like `pq`
2972
+ result[has_q, :] = dVmag_pq[q_rows[has_q], :]
2973
+ elif has_q.any():
2974
+ # rows of J^-1 for the requested PQ buses: J^T Y = E
2975
+ E = np.zeros((n_eq, int(has_q.sum())))
2976
+ E[n_p_eq + q_rows[has_q], np.arange(int(has_q.sum()))] = 1.0
2977
+ Y = lu.solve(E, trans="T") # n_eq x n_b
2978
+ result[has_q, :] = -(dS.T @ Y).T
2979
+ return pd.DataFrame(result, index=bus_names, columns=lines["name"].tolist())
2980
+
2981
+ def calculate_voltage_line_resistance_sensitivities(
2982
+ self, line_names: list[str] | None = None
2983
+ ) -> pd.DataFrame:
2984
+ """
2985
+ Computes the sensitivity of bus voltage magnitudes to small changes in line RESISTANCE (r_pu)
2986
+ using the inverse of the Jacobian matrix from pandapower's power flow solution.
2987
+
2988
+ The computation is vectorised over the lines and can be restricted to a subset of lines,
2989
+ which keeps it cheap on large feeders when only one galvanic zone is of interest.
2990
+
2991
+ The voltage-dependent share of the loads (``const_i_*_percent``,
2992
+ ``const_z_*_percent``) is not in this Jacobian: see the limit in
2993
+ `calculate_voltage_power_sensitivities`.
2994
+
2995
+ Args:
2996
+ line_names (Optional[List[str]], optional): Names of the lines to consider. Defaults to
2997
+ all lines that conduct.
2998
+
2999
+ Returns:
3000
+ pd.DataFrame: DataFrame with bus names as index and line names as columns.
3001
+ Each value represents dV_mag_pu / dr_line_pu (equivalent resistance of
3002
+ the parallel-combined line).
3003
+
3004
+ Raises:
3005
+ RuntimeError: If there is no converged run of the engine (`run_power_flow`;
3006
+ the results of `pp.runpp` are not used), or if a bus, a line or a
3007
+ transformer has been created or dropped since the last one.
3008
+ """
3009
+ ctx = self._jacobian_context()
3010
+ lines = self._select_lines(line_names)
3011
+ if lines.empty:
3012
+ return pd.DataFrame(0.0, index=self.network.bus.name.tolist(), columns=[])
3013
+ r_pu, x_pu, _ = self._line_pu_parameters(lines)
3014
+ z2_pu = r_pu**2 + x_pu**2
3015
+ zero = np.isclose(z2_pu, 0.0, rtol=0, atol=1.0e-15)
3016
+ if zero.any():
3017
+ raise ValueError(
3018
+ f"Per unit impedance squared (z2_pu) is zero for lines {lines['name'].to_numpy()[zero][:5]}."
3019
+ )
3020
+ dG_dr = (x_pu**2 - r_pu**2) / z2_pu**2
3021
+ dB_dr = (2.0 * r_pu * x_pu) / z2_pu**2
3022
+ return self._voltage_response(lines, dG_dr, dB_dr, ctx)
3023
+
3024
+ def calculate_voltage_line_change_effects(
3025
+ self,
3026
+ changes: dict[str, tuple[float, float, int]],
3027
+ buses: list[str] | None = None,
3028
+ ) -> pd.DataFrame:
3029
+ """
3030
+ Predict the bus voltage-magnitude change (p.u.) brought by a finite change of each line.
3031
+
3032
+ Unlike the resistance sensitivity, the response is linearised in the finite change of
3033
+ the series impedance (r and x of the parallel-combined line) with one Newton step, so
3034
+ the prediction stays accurate for large steps (a new conductor type, one more parallel
3035
+ conductor) on radial feeders, where the voltage drop is nearly linear in impedance.
3036
+
3037
+ The voltage-dependent share of the loads (``const_i_*_percent``,
3038
+ ``const_z_*_percent``) is not in this Jacobian: see the limit in
3039
+ `calculate_voltage_power_sensitivities`.
3040
+
3041
+ Args:
3042
+ changes (Dict[str, Tuple[float, float, int]]): line name -> (new r_ohm_per_km,
3043
+ new x_ohm_per_km, new parallel count).
3044
+ buses (Optional[List[str]], optional): Only compute the response at these buses.
3045
+
3046
+ Returns:
3047
+ pd.DataFrame: index = bus names, columns = names of the lines of `changes`
3048
+ that conduct (in service, no open line switch, between buses in
3049
+ service and supplied) between buses of the
3050
+ solution, values = predicted dV (p.u.). A line without series impedance,
3051
+ like one of zero length, has no voltage drop to change: its column is 0.
3052
+
3053
+ Raises:
3054
+ RuntimeError: If there is no converged run of the engine (`run_power_flow`;
3055
+ the results of `pp.runpp` are not used), or if a bus, a line or a
3056
+ transformer has been created or dropped since the last one.
3057
+ """
3058
+ lines = self._select_lines(list(changes)) if changes else None
3059
+ if lines is None or lines.empty:
3060
+ return pd.DataFrame(
3061
+ 0.0,
3062
+ index=self.network.bus.name.tolist() if buses is None else buses,
3063
+ columns=[],
3064
+ )
3065
+ ctx = self._jacobian_context()
3066
+ new = np.array([changes[name] for name in lines["name"]], dtype=float)
3067
+ dy = self._line_change_admittance(lines, new)
3068
+ return self._voltage_response(lines, dy.real, dy.imag, ctx, buses=buses)
3069
+
3070
+ def calculate_voltage_line_change_effects_of_steps(
3071
+ self,
3072
+ steps: list[tuple[str, float, float, int]],
3073
+ buses: list[str] | None = None,
3074
+ ) -> pd.DataFrame:
3075
+ """
3076
+ Predicted bus voltage-magnitude change (p.u.) for each of `steps`, each a finite
3077
+ change of one line taken alone: (line name, new r_ohm_per_km, new x_ohm_per_km,
3078
+ new parallel count), several steps of a line allowed.
3079
+
3080
+ Each step is a column of the response of `calculate_voltage_line_change_effects`,
3081
+ computed from the same factors of the Jacobian, and the column of a step does not
3082
+ depend on the other steps: all are predicted with one solve, whatever the number
3083
+ of steps a line has.
3084
+
3085
+ Returns:
3086
+ pd.DataFrame: index = bus names, or `buses` when given; columns = the
3087
+ positions in `steps` of the steps whose line conducts (see
3088
+ `calculate_voltage_line_change_effects`), in order.
3089
+
3090
+ Raises:
3091
+ RuntimeError: As `calculate_voltage_line_change_effects`.
3092
+ """
3093
+ names = list(dict.fromkeys(step[0] for step in steps))
3094
+ lines = self._select_lines(names) if steps else None
3095
+ if lines is None or lines.empty:
3096
+ return pd.DataFrame(
3097
+ 0.0,
3098
+ index=self.network.bus.name.tolist() if buses is None else buses,
3099
+ columns=[],
3100
+ )
3101
+ ctx = self._jacobian_context()
3102
+ row_of = {name: i for i, name in enumerate(lines["name"])}
3103
+ # The steps of the lines between buses of the solution, as
3104
+ # `_voltage_response` keeps them
3105
+ bus_lookup, n_ppc = ctx["bus_lookup"], ctx["n_ppc"]
3106
+ f_ppc = bus_lookup[lines["from_bus"].to_numpy(dtype=int)]
3107
+ t_ppc = bus_lookup[lines["to_bus"].to_numpy(dtype=int)]
3108
+ valid = (f_ppc >= 0) & (f_ppc < n_ppc) & (t_ppc >= 0) & (t_ppc < n_ppc)
3109
+ kept = [
3110
+ position
3111
+ for position, step in enumerate(steps)
3112
+ if step[0] in row_of and valid[row_of[step[0]]]
3113
+ ]
3114
+ if len(kept) < len(steps) and not valid.all():
3115
+ self.logger.warning(
3116
+ f"{int((~valid).sum())} lines skipped in the sensitivity computation "
3117
+ "(buses not in the ppc)."
3118
+ )
3119
+ rows = lines.iloc[[row_of[steps[position][0]] for position in kept]]
3120
+ new = np.array([steps[position][1:] for position in kept], dtype=float)
3121
+ new = new.reshape(len(kept), 3)
3122
+ dy = self._line_change_admittance(rows, new)
3123
+ effects = self._voltage_response(rows, dy.real, dy.imag, ctx, buses=buses)
3124
+ effects.columns = kept
3125
+ return effects
3126
+
3127
+ def _line_change_admittance(
3128
+ self, lines: pd.DataFrame, new: np.ndarray
3129
+ ) -> np.ndarray:
3130
+ """
3131
+ Change of the series admittance (p.u.) of each of `lines` when its conductors
3132
+ change to `new` (one row per line: r_ohm_per_km, x_ohm_per_km, parallel count),
3133
+ to first order in the change of its impedance.
3134
+ """
3135
+ r_pu, x_pu, z_base = self._line_pu_parameters(lines)
3136
+ length = lines["length_km"].to_numpy(dtype=float)
3137
+ r_new = new[:, 0] * length / new[:, 2] / z_base
3138
+ x_new = new[:, 1] * length / new[:, 2] / z_base
3139
+ z_old = r_pu + 1j * x_pu
3140
+ conducts = ~np.isclose(np.abs(z_old) ** 2, 0.0, atol=1e-15)
3141
+ # First order in the impedance change, dy = -y^2 dz: the bus currents barely move
3142
+ # with one line's impedance, so the voltage drop (I z) is close to linear in z.
3143
+ # Linearising in the admittance instead overestimates large steps (about twice the
3144
+ # true effect for one more parallel conductor).
3145
+ y_old = np.zeros_like(z_old)
3146
+ y_old[conducts] = 1.0 / z_old[conducts]
3147
+ return -(y_old**2) * ((r_new - r_pu) + 1j * (x_new - x_pu))
3148
+
3149
+ def get_lines_info(self, line_ids: list[str] | None = None) -> pd.DataFrame:
3150
+ """
3151
+ Type, length (km), parallel count and impedance per conductor (`r_ohm_per_km`,
3152
+ `x_ohm_per_km`) of lines, indexed by line name (vectorised lookup), with the
3153
+ current (`current_a`, A) the whole line carries in the latest power flow (NaN
3154
+ before one), and the derating factor (`df`, 1 where the table has none), which
3155
+ pandapower multiplies the rating of the line by for its loading.
3156
+
3157
+ The impedance is that of the line table, which a line has whether or not its type
3158
+ is in the standard types.
3159
+ """
3160
+ lines = self.network.line
3161
+ if line_ids is not None:
3162
+ lines = lines[lines["name"].isin(line_ids)]
3163
+ info = lines[
3164
+ ["name", "std_type", "length_km", "r_ohm_per_km", "x_ohm_per_km"]
3165
+ ].copy()
3166
+ info["parallel"] = (
3167
+ lines["parallel"].to_numpy() if "parallel" in lines.columns else 1
3168
+ )
3169
+ info["df"] = (
3170
+ lines["df"].fillna(1.0).to_numpy() if "df" in lines.columns else 1.0
3171
+ )
3172
+ info["current_a"] = self.network.res_line["i_ka"].reindex(lines.index) * 1000.0
3173
+ return info.set_index("name")
3174
+
3175
+ def get_line_endpoints(self, line_ids: list[str] | None = None) -> pd.DataFrame:
3176
+ """
3177
+ Names of the end buses (columns `from_bus`, `to_bus`) of the lines that conduct (in
3178
+ service, no open line switch, between buses in service and supplied), indexed by line name.
3179
+ """
3180
+ lines = self._select_lines(line_ids)
3181
+ bus_name = self.network.bus["name"]
3182
+ return pd.DataFrame(
3183
+ {
3184
+ "from_bus": bus_name.loc[lines["from_bus"]].to_numpy(),
3185
+ "to_bus": bus_name.loc[lines["to_bus"]].to_numpy(),
3186
+ },
3187
+ index=lines["name"].to_numpy(),
3188
+ )
3189
+
3190
+ def get_closed_bus_switches(self) -> list[tuple[str, str]]:
3191
+ """
3192
+ Pairs of bus names joined by a closed bus-bus switch (galvanic links that are not lines).
3193
+ """
3194
+ sw = self.network.switch
3195
+ if sw.empty:
3196
+ return []
3197
+ sw = sw[(sw["et"] == "b") & sw["closed"].astype(bool)]
3198
+ bus_name = self.network.bus["name"]
3199
+ return list(
3200
+ zip(bus_name.loc[sw["bus"]], bus_name.loc[sw["element"]], strict=True)
3201
+ )
3202
+
3203
+ def get_source_buses(self) -> set[str]:
3204
+ """
3205
+ Names of the buses that feed a galvanic zone: buses of the external grids in service
3206
+ and LV buses of the transformers in service that no open switch disconnects.
3207
+ """
3208
+ net = self.network
3209
+ buses = set(net.ext_grid.loc[net.ext_grid["in_service"].astype(bool), "bus"])
3210
+ if not net.trafo.empty:
3211
+ feeding = net.trafo["in_service"].astype(bool)
3212
+ switch = net.switch
3213
+ if not switch.empty:
3214
+ opened = switch.loc[
3215
+ (switch["et"] == "t") & ~switch["closed"].astype(bool), "element"
3216
+ ]
3217
+ feeding &= ~net.trafo.index.isin(opened)
3218
+ buses |= set(net.trafo.loc[feeding, "lv_bus"])
3219
+ return set(net.bus.loc[sorted(buses), "name"])
3220
+
3221
+ def get_line_ids(self) -> list[str]:
3222
+ """
3223
+ Names of the lines that conduct: in service, no open line switch, between buses in
3224
+ service and supplied.
3225
+ """
3226
+ return self._select_lines(None)["name"].tolist()
3227
+
3228
+ def get_line_x_ohm_per_km(self, line_type: str) -> float:
3229
+ """
3230
+ Get the reactance per unit length for a given line type.
3231
+ """
3232
+ try:
3233
+ return self.network.std_types["line"][line_type]["x_ohm_per_km"]
3234
+ except KeyError:
3235
+ raise ValueError(f"Line type '{line_type}' not found in standard types")
3236
+
3237
+ def get_flexibility_data(self, element_type: str) -> pd.DataFrame:
3238
+ """
3239
+ Get flexibility data for loads or sgens.
3240
+
3241
+ Only the elements that carry power are given: those in service, at a bus that a
3242
+ power flow reaches. One that is out of service, at a bus out of service, or at a
3243
+ bus of an island that no source reaches (`_dead_buses`) has no power on the
3244
+ network, so there is nothing to shed or curtail on it, and it is not part of the
3245
+ load or the generation that the shares of a run are taken of. This is read from
3246
+ the topology of the network at each call, with or without a power flow run since.
3247
+ The index is that of the table of the network, whatever is left out.
3248
+
3249
+ The powers are those on the network: pandapower multiplies the `p_mw` and
3250
+ `q_mvar` of a load or a static generator by its `scaling`, and so do the powers
3251
+ given here. `apply_flexibility_action` takes powers on the same footing.
3252
+
3253
+ Args:
3254
+ element_type (str): 'load' or 'sgen'.
3255
+
3256
+ Returns:
3257
+ pd.DataFrame: DataFrame with flexibility data.
3258
+ """
3259
+ if element_type == "load" and hasattr(self.network, "load"):
3260
+ table = self.network.load
3261
+ df = self._energised(table)[["name", "bus", "p_mw", "q_mvar"]].copy()
3262
+ if "scaling" in table.columns:
3263
+ scaling = table["scaling"].fillna(1.0)
3264
+ df["p_mw"] *= scaling
3265
+ df["q_mvar"] *= scaling
3266
+ flex_settings = self.flexibility_settings.get("load", {})
3267
+ df["bus_name"] = df["bus"].map(self.network.bus["name"])
3268
+ df["max_flex_pct"] = df["name"].map(flex_settings).fillna(0.0)
3269
+ return df
3270
+ elif element_type == "sgen" and hasattr(self.network, "sgen"):
3271
+ table = self.network.sgen
3272
+ df = self._energised(table)[["name", "bus", "p_mw"]].copy()
3273
+ if "scaling" in table.columns:
3274
+ df["p_mw"] *= table["scaling"].fillna(1.0)
3275
+ flex_settings = self.flexibility_settings.get("sgen", {})
3276
+ df["bus_name"] = df["bus"].map(self.network.bus["name"])
3277
+ df["max_flex_pct"] = df["name"].map(flex_settings).fillna(0.0)
3278
+ return df
3279
+ return pd.DataFrame()
3280
+
3281
+ def _energised(self, table: pd.DataFrame) -> pd.DataFrame:
3282
+ """
3283
+ The rows of a table of elements at a bus (loads, static generators) that are in
3284
+ service and at a bus that is not dead (`_dead_buses`).
3285
+ """
3286
+ # On the whole columns, and without copying a table that has nothing to leave
3287
+ # out: this is called at each step of a run, on networks that, most of the time,
3288
+ # have no element out of service and no dead bus
3289
+ if "in_service" in table.columns:
3290
+ in_service = table["in_service"].to_numpy()
3291
+ if in_service.dtype != bool:
3292
+ in_service = in_service.astype(bool)
3293
+ if not in_service.all():
3294
+ table = table[in_service]
3295
+ dead = self._dead_buses()
3296
+ if dead and len(table.index) > 0:
3297
+ table = table[~table["bus"].isin(dead)]
3298
+ return table
3299
+
3300
+ def apply_flexibility_action(
3301
+ self,
3302
+ element_type: str,
3303
+ element_index: int,
3304
+ new_p_mw: float,
3305
+ new_q_mvar: float | None = None,
3306
+ ) -> None:
3307
+ """
3308
+ Apply flexibility action.
3309
+
3310
+ The powers are those on the network, as `get_flexibility_data` gives them: the
3311
+ `p_mw` and `q_mvar` written in the table of the network are divided by the
3312
+ `scaling` of the element, by which pandapower multiplies them.
3313
+
3314
+ The method does not check the service state of the element, nor whether its bus
3315
+ is energised: it writes to the element it is given, even when that element is out
3316
+ of service or at a de-energised bus. A caller acting outside `FlexibilityStrategy`,
3317
+ which never selects such an element, must filter them out itself.
3318
+
3319
+ Args:
3320
+ element_type (str): 'load' or 'sgen'.
3321
+ element_index (int): Index of the element.
3322
+ new_p_mw (float): New active power value in MW.
3323
+ new_q_mvar (Optional[float], optional): New reactive power of a load, in MVAr.
3324
+ Defaults to None, which keeps the power factor of the load. That cannot
3325
+ undo a load that was shed down to zero, as the power factor is lost with
3326
+ the active power: restoring such a load needs its reactive power.
3327
+ """
3328
+ if element_type not in ("load", "sgen"):
3329
+ return
3330
+ table = self.network.load if element_type == "load" else self.network.sgen
3331
+ scaling = 1.0
3332
+ if "scaling" in table.columns:
3333
+ value = table.at[element_index, "scaling"]
3334
+ if pd.notna(value):
3335
+ scaling = float(value)
3336
+ if scaling == 0.0:
3337
+ # An element scaled to nothing has no power on the network to set, and
3338
+ # its table values, which no power on the network gives back, are kept
3339
+ return
3340
+
3341
+ # Simple check to ensure we are not going below 0
3342
+ if new_p_mw < 0:
3343
+ new_p_mw = 0.0
3344
+ original_p = table.at[element_index, "p_mw"]
3345
+ table.at[element_index, "p_mw"] = new_p_mw / scaling
3346
+
3347
+ if element_type == "load":
3348
+ original_q = table.at[element_index, "q_mvar"]
3349
+ if new_q_mvar is None:
3350
+ # Keep the power factor, which a load without active power does not have
3351
+ table.at[element_index, "q_mvar"] = (
3352
+ original_q * (new_p_mw / scaling) / original_p
3353
+ if original_p != 0
3354
+ else original_q
3355
+ )
3356
+ else:
3357
+ table.at[element_index, "q_mvar"] = new_q_mvar / scaling
3358
+
3359
+ label = "Load" if element_type == "load" else "SGen"
3360
+ self.logger.info(
3361
+ f"Modified {label} {element_index}: {original_p * scaling:.5f} MW -> {new_p_mw:.5f} MW"
3362
+ )
3363
+
3364
+ def calculate_voltage_power_sensitivities(
3365
+ self, buses: list[str] | None = None
3366
+ ) -> pd.DataFrame:
3367
+ """
3368
+ Calculate sensitivity of bus voltage magnitudes to active power injection.
3369
+
3370
+ The rows are rows of the inverse of the Jacobian, J^-1. Each is computed from the
3371
+ transposed system J^T y = e, so asking only for the buses that are needed costs
3372
+ one solve per bus instead of the whole inverse.
3373
+
3374
+ Limit, voltage-dependent loads: the sensitivities of the engine, of voltage and
3375
+ of loading alike, are those of loads of constant power. The Jacobian they come
3376
+ from, which the engine builds from pandapower's admittance matrix, holds every
3377
+ load as a constant power: the constant-current and constant-impedance share of
3378
+ a load (``const_i_p_percent``, ``const_i_q_percent``, ``const_z_p_percent``,
3379
+ ``const_z_q_percent``) is not in it, so that the sensitivities ignore how such a
3380
+ load follows the voltage. With such a share they are off, by an amount that
3381
+ grows with the share, with the loading of the network and from one metric to
3382
+ another, and they are not corrected. Against central differences of power
3383
+ flows on ``52_MVFeeder1118``, every load at 100 % of the model (median relative
3384
+ errors; ``benchmarks/zip_load_sensitivities.py``, and the table in the
3385
+ methodology documentation): at load x1.0, constant current 2.4 to 3.8 % for
3386
+ the voltage (whole column to buses over 20 % of the largest) and 4.3 % for the
3387
+ loading, constant impedance 4.8 to 7.5 % and 8.5 %; at load x2.5, the factor
3388
+ of the case study, constant current 7.6 to 19 % (at the bus itself to buses
3389
+ over 20 % of the largest) and 21 %, constant impedance 14 to 36 % and 39 %;
3390
+ under 0.01 % with loads of constant power. The feeders of the case study have
3391
+ these columns at 0.
3392
+
3393
+ Args:
3394
+ buses (Optional[List[str]]): Names of the buses whose voltage sensitivities
3395
+ are needed. Defaults to None, for all PQ buses. Names that are not PQ
3396
+ buses of the solution (slack or PV buses, unknown names) are left out.
3397
+
3398
+ Returns:
3399
+ pd.DataFrame: DataFrame with index=bus_names (the requested PQ buses),
3400
+ columns=bus_names (the PV and PQ buses). Values are d|V|_i / dP_j,
3401
+ in pu per MW of active power injected at bus j. Buses joined by a
3402
+ closed bus-bus switch are one bus for the power flow: each of them
3403
+ has the row and the column of that bus.
3404
+
3405
+ Raises:
3406
+ RuntimeError: If there is no converged run of the engine (`run_power_flow`;
3407
+ the results of `pp.runpp` are not used), or if a bus, a line or a
3408
+ transformer has been created or dropped since the last one, whose
3409
+ results are then those of another network.
3410
+ """
3411
+ net = self.network
3412
+ if not self._has_converged_results():
3413
+ raise RuntimeError(_NO_CONVERGED_RUN)
3414
+ if not self._tables_match_results():
3415
+ raise RuntimeError(_STALE_TABLES)
3416
+
3417
+ if not hasattr(net, "_ppc") or "internal" not in net._ppc:
3418
+ raise RuntimeError("Internal PPC structure not available.")
3419
+
3420
+ ppc_int = net._ppc["internal"]
3421
+ J_sparse = self._converged_jacobian()
3422
+
3423
+ if J_sparse is None:
3424
+ raise ValueError("Jacobian matrix not available.")
3425
+
3426
+ # Jacobian rows (equations): P for (pv, pq), then Q for pq. Columns (variables):
3427
+ # angles for (pv, pq), then magnitudes for pq. d|V|/dP is the block of J^-1 of
3428
+ # the magnitude rows and the P columns.
3429
+ pv = np.asarray(ppc_int["pv"], dtype=int)
3430
+ pq = np.asarray(ppc_int["pq"], dtype=int)
3431
+ n_p_eq = len(pv) + len(pq)
3432
+
3433
+ # Buses fused into one internal bus all get its row and its column
3434
+ rows = self._ppc_bus_names(pq)
3435
+ columns = self._ppc_bus_names(np.concatenate((pv, pq)))
3436
+ if buses is not None:
3437
+ wanted = set(buses)
3438
+ rows = [(position, name) for position, name in rows if name in wanted]
3439
+ solved = np.unique([position for position, _ in rows]).astype(int)
3440
+ solve_of = {position: k for k, position in enumerate(solved)}
3441
+
3442
+ try:
3443
+ lu = self._jacobian_lu(J_sparse)
3444
+ # Row r of J^-1 is y with J^T y = e_r
3445
+ unit = np.zeros((J_sparse.shape[0], len(solved)))
3446
+ unit[n_p_eq + solved, np.arange(len(solved))] = 1.0
3447
+ inverse_rows = lu.solve(unit, trans="T") if len(solved) else unit
3448
+ except Exception as e:
3449
+ self.logger.error(f"Failed to factorise the Jacobian: {e}")
3450
+ return pd.DataFrame()
3451
+
3452
+ # The Jacobian is in per-unit of the network's base power: d|V|/dP_pu, divided
3453
+ # by the base, is in pu per MW
3454
+ values = inverse_rows[:n_p_eq, :].T / float(net.sn_mva)
3455
+ values = values[[solve_of[position] for position, _ in rows], :]
3456
+ return pd.DataFrame(
3457
+ values[:, [position for position, _ in columns]],
3458
+ index=[name for _, name in rows],
3459
+ columns=[name for _, name in columns],
3460
+ )
3461
+
3462
+ def analyze_thermal_violation(
3463
+ self, element_type: str, element_id: str
3464
+ ) -> dict[str, Any]:
3465
+ """
3466
+ Analyze a thermal violation to determine downstream topology and flow conditions.
3467
+
3468
+ Args:
3469
+ element_type (str): "Line" or "Transformer".
3470
+ element_id (str): Name of the element.
3471
+
3472
+ Returns:
3473
+ Dict[str, Any]: Dictionary with analysis results.
3474
+ """
3475
+ if not self.network:
3476
+ return {}
3477
+
3478
+ try:
3479
+ import networkx as nx
3480
+ import pandapower.topology as ppt
3481
+ except ImportError:
3482
+ self.logger.error(
3483
+ "NetworkX and pandapower.topology are required for thermal analysis."
3484
+ )
3485
+ return {}
3486
+
3487
+ net = self.network
3488
+
3489
+ # Find slack bus (assuming single slack for simplicity)
3490
+ if net.ext_grid.empty:
3491
+ return {}
3492
+ slack_index = net.ext_grid.bus.iloc[0]
3493
+
3494
+ u_elem, v_elem = None, None
3495
+ rated_mva = 0.0
3496
+ p_flow = 0.0
3497
+ upstream = None
3498
+ downstream = None
3499
+
3500
+ # Identify element nodes and rating
3501
+ if element_type == "Line":
3502
+ mask = net.line.name == element_id
3503
+ if not mask.any():
3504
+ return {}
3505
+ idx = net.line[mask].index[0]
3506
+ line = net.line.loc[idx]
3507
+ u_elem, v_elem = line.from_bus, line.to_bus
3508
+
3509
+ # Rated MVA of the line as the engine rates it: the rating of the line
3510
+ # table (not that of its type) of each conductor, times the derating
3511
+ # factor and the parallel conductors
3512
+ derating = line.get("df", 1.0)
3513
+ parallel = line.get("parallel", 1)
3514
+ i_max_ka = (
3515
+ float(line.max_i_ka)
3516
+ * (1.0 if pd.isna(derating) else float(derating))
3517
+ * (1 if pd.isna(parallel) else int(parallel))
3518
+ )
3519
+
3520
+ elif element_type == "Transformer":
3521
+ mask = net.trafo.name == element_id
3522
+ if not mask.any():
3523
+ return {}
3524
+ idx = net.trafo[mask].index[0]
3525
+ trafo = net.trafo.loc[idx]
3526
+ u_elem, v_elem = trafo.hv_bus, trafo.lv_bus
3527
+ # Rated MVA of the transformer as the engine rates it, as for a line: the
3528
+ # rating of each unit, times the derating factor and the units in parallel
3529
+ derating = trafo.get("df", 1.0)
3530
+ parallel = trafo.get("parallel", 1)
3531
+ rated_mva = (
3532
+ float(trafo.sn_mva)
3533
+ * (1.0 if pd.isna(derating) else float(derating))
3534
+ * (1 if pd.isna(parallel) else int(parallel))
3535
+ )
3536
+ else:
3537
+ return {}
3538
+
3539
+ # Topology analysis
3540
+ mg = ppt.create_nxgraph(net, include_trafos=True)
3541
+
3542
+ # Determine Upstream/Downstream based on distance to slack
3543
+ try:
3544
+ dist_u = nx.shortest_path_length(mg, source=slack_index, target=u_elem)
3545
+ except nx.NetworkXNoPath:
3546
+ dist_u = float("inf")
3547
+
3548
+ try:
3549
+ dist_v = nx.shortest_path_length(mg, source=slack_index, target=v_elem)
3550
+ except nx.NetworkXNoPath:
3551
+ dist_v = float("inf")
3552
+
3553
+ if dist_u < dist_v:
3554
+ upstream, downstream = u_elem, v_elem
3555
+ else:
3556
+ upstream, downstream = v_elem, u_elem
3557
+
3558
+ # Calculate Flow and Rating (if line)
3559
+ if element_type == "Line":
3560
+ idx = net.line[mask].index[0]
3561
+ v_kv_base = net.bus.at[upstream, "vn_kv"]
3562
+ rated_mva = np.sqrt(3) * v_kv_base * i_max_ka
3563
+
3564
+ p_flow = (
3565
+ net.res_line.at[idx, "p_from_mw"]
3566
+ if net.line.at[idx, "from_bus"] == upstream
3567
+ else net.res_line.at[idx, "p_to_mw"]
3568
+ )
3569
+ elif element_type == "Transformer":
3570
+ idx = net.trafo[mask].index[0]
3571
+ p_flow = (
3572
+ net.res_trafo.at[idx, "p_hv_mw"]
3573
+ if net.trafo.at[idx, "hv_bus"] == upstream
3574
+ else net.res_trafo.at[idx, "p_lv_mw"]
3575
+ )
3576
+
3577
+ is_flow_towards_downstream = p_flow > 0
3578
+
3579
+ # Identify Downstream Buses
3580
+ if mg.has_edge(u_elem, v_elem):
3581
+ mg.remove_edge(u_elem, v_elem)
3582
+
3583
+ downstream_nodes = (
3584
+ list(nx.node_connected_component(mg, downstream))
3585
+ if downstream in mg
3586
+ else [downstream]
3587
+ )
3588
+ downstream_names = net.bus.loc[
3589
+ net.bus.index.isin(downstream_nodes), "name"
3590
+ ].tolist()
3591
+
3592
+ return {
3593
+ "downstream_buses": downstream_names,
3594
+ "flow_mw": p_flow,
3595
+ "rated_mva": rated_mva,
3596
+ "is_flow_towards_downstream": is_flow_towards_downstream,
3597
+ }
3598
+
3599
+ def calculate_branch_loading_sensitivities(
3600
+ self, element_type: str, element_name: str
3601
+ ) -> pd.DataFrame:
3602
+ r"""
3603
+ Calculate sensitivity of branch loading to active power injections using Jacobian.
3604
+
3605
+ Returns DataFrame with bus_names as index and one column, ``sensitivity``,
3606
+ containing d(Loading%)/dP_mw for the specific branch, in % per MW of active
3607
+ power injected at the bus.
3608
+
3609
+ The loading differentiated is the one pandapower reports in
3610
+ ``res_line.loading_percent`` and ``res_trafo.loading_percent``: it is
3611
+ proportional to the magnitude of the current at the end of the branch where it
3612
+ is the highest (for a transformer, relative to the rated current of each side;
3613
+ to the apparent power of that end with ``trafo_loading="power"``). The current
3614
+ comes from the branch admittances of the solved case, which carry the tap
3615
+ ratio and the phase shift of a transformer and the charging of a line:
3616
+
3617
+ - :math:`I = \sum_k Y_k V_k`, over the two ends :math:`k` of the branch
3618
+ - :math:`\frac{d(\text{Loading}\%)}{d(\theta,V)} = \text{Loading}\%
3619
+ \times \frac{\Re(\bar{I}\, dI/d(\theta,V))}{|I|^2}`
3620
+ - :math:`\frac{d(\text{Loading}\%)}{dP_{bus}} = \frac{d(\text{Loading}\%)}
3621
+ {d(\theta,V)} \frac{d(\theta,V)}{dP_{bus}}`, the last factor being a
3622
+ column of the inverse of the Jacobian. All the buses are obtained from one
3623
+ transposed solve.
3624
+
3625
+ The value is the plain derivative of the loading with respect to the active
3626
+ power injected at the bus, at constant reactive injection: positive means that
3627
+ injecting more at the bus raises the loading of the branch, negative that it
3628
+ lowers it, whatever the direction of the flow in the branch. Shedding a load
3629
+ raises the injection at its bus, curtailing a generator lowers it.
3630
+
3631
+ The voltage-dependent share of the loads (``const_i_*_percent``,
3632
+ ``const_z_*_percent``) is not in the Jacobian, and so not in these
3633
+ sensitivities: see the limit in `calculate_voltage_power_sensitivities`.
3634
+
3635
+ Buses joined by a closed bus-bus switch have the same sensitivity. The slack
3636
+ bus, the buses fused with it and the buses out of service have none. The
3637
+ result is empty if there is no converged run of the engine (`run_power_flow`;
3638
+ the results of `pp.runpp` are not used, as in the voltage sensitivities), if
3639
+ the branch is unknown or out of service, or if a bus, a line or a transformer
3640
+ has been created or dropped since the last power flow: the branch could not be
3641
+ found in its results.
3642
+ """
3643
+ if not self._has_converged_results():
3644
+ return pd.DataFrame()
3645
+
3646
+ net = self.network
3647
+ if not hasattr(net, "_ppc") or "internal" not in net._ppc:
3648
+ return pd.DataFrame()
3649
+ if not self._tables_match_results():
3650
+ self.logger.warning(_STALE_TABLES)
3651
+ return pd.DataFrame()
3652
+
3653
+ ppc_int = net._ppc["internal"]
3654
+ J_sparse = self._converged_jacobian()
3655
+
3656
+ if J_sparse is None:
3657
+ return pd.DataFrame()
3658
+
3659
+ try:
3660
+ lu = self._jacobian_lu(J_sparse)
3661
+ except Exception as e:
3662
+ self.logger.warning(f"Failed to factorize Jacobian: {e}")
3663
+ return pd.DataFrame()
3664
+
3665
+ V_complex = ppc_int.get("V")
3666
+ if V_complex is None:
3667
+ return pd.DataFrame()
3668
+
3669
+ pv = np.asarray(ppc_int["pv"], dtype=int)
3670
+ pq = np.asarray(ppc_int["pq"], dtype=int)
3671
+ n_p_eq = len(pv) + len(pq)
3672
+
3673
+ # The branch in the result tables of pandapower, with the columns that tell
3674
+ # which of its ends sets the loading
3675
+ if element_type == "Line":
3676
+ key, table, results = "line", net.line, net.res_line
3677
+ from_columns, to_columns = ("i_from_ka",), ("i_to_ka",)
3678
+ elif element_type == "Transformer":
3679
+ key, table, results = "trafo", net.trafo, net.res_trafo
3680
+ from_columns = ("i_hv_ka", "p_hv_mw", "q_hv_mvar")
3681
+ to_columns = ("i_lv_ka", "p_lv_mw", "q_lv_mvar")
3682
+ else:
3683
+ return pd.DataFrame()
3684
+ found = np.flatnonzero((table["name"] == element_name).to_numpy())
3685
+ if len(found) == 0 or key not in net._pd2ppc_lookups["branch"]:
3686
+ return pd.DataFrame()
3687
+ position = int(found[0])
3688
+ result = results.iloc[position]
3689
+ loading = float(result["loading_percent"])
3690
+ from_values = [float(result[column]) for column in from_columns]
3691
+ to_values = [float(result[column]) for column in to_columns]
3692
+
3693
+ # Its row in the branch admittances of the solved case, which leaves out the
3694
+ # branches out of service
3695
+ in_service = np.asarray(ppc_int["branch_is"], dtype=bool)
3696
+ branch = net._pd2ppc_lookups["branch"][key][0] + position
3697
+ if not in_service[branch]:
3698
+ return pd.DataFrame()
3699
+ internal_branch = int(np.count_nonzero(in_service[:branch]))
3700
+
3701
+ # The end pandapower takes the loading from, and whether it is its current or
3702
+ # its apparent power
3703
+ by_power = False
3704
+ if element_type == "Line":
3705
+ from_side = from_values[0] >= to_values[0]
3706
+ elif net._options.get("trafo_loading", "current") == "power":
3707
+ by_power = True
3708
+ from_side = np.hypot(*from_values[1:]) >= np.hypot(*to_values[1:])
3709
+ else:
3710
+ trafo = table.iloc[position]
3711
+ from_side = (
3712
+ from_values[0] * trafo["vn_hv_kv"] >= to_values[0] * trafo["vn_lv_kv"]
3713
+ )
3714
+ admittances = ppc_int["Yf" if from_side else "Yt"].tocsr()
3715
+ admittances = admittances.getrow(internal_branch)
3716
+ buses = admittances.indices
3717
+ terms = admittances.data * V_complex[buses] # I = sum(terms)
3718
+ current = terms.sum()
3719
+
3720
+ # Gradient of log(loading) with respect to the state [θ, |V|]: with
3721
+ # V_k = |V_k| exp(jθ_k), dI/dθ_k = j Y_k V_k and dI/d|V_k| = Y_k V_k / |V_k|,
3722
+ # and d log|I| = Re(conj(I) dI) / |I|^2
3723
+ pos_p = np.full(len(V_complex), -1, dtype=int)
3724
+ pos_p[np.concatenate((pv, pq))] = np.arange(n_p_eq)
3725
+ pos_q = np.full(len(V_complex), -1, dtype=int)
3726
+ pos_q[pq] = n_p_eq + np.arange(len(pq))
3727
+ gradient = np.zeros(J_sparse.shape[0])
3728
+ if abs(current) > 0.0 and np.isfinite(loading):
3729
+ relative = np.conj(current) * terms / abs(current) ** 2
3730
+ has_angle, has_magnitude = pos_p[buses] >= 0, pos_q[buses] >= 0
3731
+ np.add.at(gradient, pos_p[buses][has_angle], -relative.imag[has_angle])
3732
+ np.add.at(
3733
+ gradient,
3734
+ pos_q[buses][has_magnitude],
3735
+ (relative.real / np.abs(V_complex[buses]))[has_magnitude],
3736
+ )
3737
+ if by_power:
3738
+ # |S| = |V| |I| at the end of the branch
3739
+ from pandapower.pypower.idx_brch import F_BUS, T_BUS
3740
+
3741
+ end = int(
3742
+ ppc_int["branch"][
3743
+ internal_branch, F_BUS if from_side else T_BUS
3744
+ ].real
3745
+ )
3746
+ if pos_q[end] >= 0:
3747
+ gradient[pos_q[end]] += 1.0 / abs(V_complex[end])
3748
+ else:
3749
+ # No current: the loading is at its minimum, where it has no derivative
3750
+ loading = 0.0
3751
+
3752
+ # d(log loading)/dP_bus for every injection bus at once. With c the gradient
3753
+ # with respect to the state, it is c^T J^-1 e_bus, that is the entry of y for
3754
+ # the P equation of the bus, with J^T y = c: one solve instead of one per bus.
3755
+ # The Jacobian is in per-unit of the base power of the network.
3756
+ sensitivity_pct_per_mw = (
3757
+ loading * lu.solve(gradient, trans="T")[:n_p_eq] / float(net.sn_mva)
3758
+ )
3759
+ sensitivities = {
3760
+ name: sensitivity_pct_per_mw[position]
3761
+ for position, name in self._ppc_bus_names(
3762
+ np.concatenate((pv, pq)), missing=None
3763
+ )
3764
+ }
3765
+
3766
+ return pd.DataFrame({"sensitivity": sensitivities})