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,314 @@
1
+ import logging
2
+ import multiprocessing
3
+ import sys
4
+ import traceback
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import pandapower as pp
10
+ from tqdm import tqdm
11
+
12
+ from gridforge import PowerFlowNotConverged, data_path
13
+ from gridforge.case_study.config import MV_LV_FEEDER
14
+ from gridforge.core.cost_model import CostModel
15
+ from gridforge.core.grid_enhancement import (
16
+ EnhancementStrategyRegistry,
17
+ GridEnhancementAlgorithm,
18
+ )
19
+ from gridforge.engines.pandapower_engine import PandaPowerEngine
20
+ from gridforge.strategies.flexibility import FlexibilityStrategy
21
+ from gridforge.strategies.line_upgrade import LineUpgradeStrategy
22
+ from gridforge.strategies.transformer_upgrade import TransformerUpgradeStrategy
23
+ from gridforge.utils.interactive_plot import create_enhancement_visualisation
24
+ from gridforge.utils.logging import setup_logging
25
+
26
+ warnings.filterwarnings("ignore")
27
+
28
+ setup_logging(logging.INFO)
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def make_shared_names_unique(network, label=""):
33
+ """
34
+ Rename the loads and static generators that share a name with another of their
35
+ table, which `PandaPowerEngine.check_names` refuses.
36
+
37
+ Of the elements of one name, the first in the order of the table keeps it, and the
38
+ others are given it followed by ``_2``, ``_3``..., in that order, skipping any
39
+ name already in the table. The renamed elements are logged at warning level, with
40
+ `label` (the feeder) in front. A network without shared names is left as it is.
41
+
42
+ Of the 150 feeders of the case study, only ``84_MVFeeder4049`` has some: 4 names
43
+ on 2 loads each, all at the same bus, whose second load is renamed. As the case
44
+ study gives every load the same flexibility, no decision changes.
45
+
46
+ Returns:
47
+ dict[str, dict[int, tuple[str, str]]]: For each table renamed in, the index of
48
+ each renamed element with its former and its new name.
49
+ """
50
+ renamed: dict[str, dict[int, tuple[str, str]]] = {}
51
+ for element in ("load", "sgen"):
52
+ table = getattr(network, element, None)
53
+ if table is None or table.empty or "name" not in table.columns:
54
+ continue
55
+ names = table["name"]
56
+ present = names.notna() & (names != "")
57
+ repeated = names[present & names.duplicated(keep="first")]
58
+ if repeated.empty:
59
+ continue
60
+ taken = set(names[present])
61
+ changes = {}
62
+ for index, name in repeated.items():
63
+ k = 2
64
+ while f"{name}_{k}" in taken:
65
+ k += 1
66
+ new = f"{name}_{k}"
67
+ taken.add(new)
68
+ changes[index] = (name, new)
69
+ table.loc[list(changes), "name"] = [new for _, new in changes.values()]
70
+ renamed[element] = changes
71
+ logger.warning(
72
+ f"{label}: {len(changes)} {element} name(s) shared with another of the "
73
+ "table made unique: "
74
+ + ", ".join(
75
+ f"{index} {old!r} -> {new!r}" for index, (old, new) in changes.items()
76
+ )
77
+ )
78
+ return renamed
79
+
80
+
81
+ def load_network(network_path, load_factor):
82
+ """
83
+ Load a pandapower network and prepare it for testing.
84
+
85
+ Loads and static generators that share a name are renamed first
86
+ (`make_shared_names_unique`), as the engine refuses them.
87
+ """
88
+ # Initialize the engine
89
+ pf_engine = PandaPowerEngine()
90
+
91
+ # Load the network
92
+ network = pp.from_json(network_path)
93
+ make_shared_names_unique(network, Path(network_path).stem)
94
+
95
+ # Set the network in the engine
96
+ pf_engine.network = network
97
+
98
+ # Modify the network to create some violations
99
+ # Increase load at some buses to create voltage violations
100
+ if hasattr(network, "load"):
101
+ network.load["p_mw"] *= load_factor
102
+ network.load["q_mvar"] *= load_factor
103
+
104
+ if hasattr(network, "asymmetric_load"):
105
+ for col in ["p_a_mw", "p_b_mw", "p_c_mw", "q_a_mvar", "q_b_mvar", "q_c_mvar"]:
106
+ if col in network.asymmetric_load.columns:
107
+ network.asymmetric_load[col] *= load_factor
108
+
109
+ return pf_engine
110
+
111
+
112
+ def create_strategy_registry(with_flex=True):
113
+ """Create a strategy registry with voltage and loading strategies."""
114
+ registry = EnhancementStrategyRegistry()
115
+
116
+ # Add loading strategies
117
+ line_upgrade_strategy = LineUpgradeStrategy(
118
+ line_types=MV_LV_FEEDER.line_types,
119
+ max_iterations=MV_LV_FEEDER.line_upgrade_max_iterations,
120
+ min_voltage_sensitivity=MV_LV_FEEDER.line_upgrade_min_voltage_sensitivity,
121
+ )
122
+ registry.register_strategy(line_upgrade_strategy)
123
+
124
+ # Add custom transformer upgrade strategy
125
+ transformer_upgrade_strategy = TransformerUpgradeStrategy(MV_LV_FEEDER.trafo_types)
126
+ registry.register_strategy(transformer_upgrade_strategy)
127
+ if with_flex:
128
+ registry.register_strategy(
129
+ FlexibilityStrategy(n_activation=MV_LV_FEEDER.flexibility_n_activation)
130
+ )
131
+
132
+ return registry
133
+
134
+
135
+ def create_cost_model():
136
+ """Create a cost model for evaluating strategies."""
137
+ return CostModel(MV_LV_FEEDER.unit_costs)
138
+
139
+
140
+ def run_grid_enhancement(
141
+ network_path,
142
+ strategy_registry,
143
+ cost_model,
144
+ load_factor,
145
+ flexibility_pct,
146
+ output_dir,
147
+ ):
148
+ """
149
+ Helper function to run grid enhancement tests with the example network.
150
+
151
+ Args:
152
+ network_path: Path to the network json file
153
+ strategy_registry: Registry of enhancement strategies
154
+ cost_model: Cost model for evaluating strategies
155
+ load_factor: Factor to increase load
156
+ flexibility_pct: Percentage of flexibility
157
+ output_dir: Directory to save results
158
+ """
159
+ power_flow_engine = load_network(network_path, load_factor)
160
+ output_path = (
161
+ output_dir / f"{network_path.stem}_flex_{int(flexibility_pct)}_pct.html"
162
+ )
163
+ return enhance_network(
164
+ power_flow_engine, strategy_registry, cost_model, flexibility_pct, output_path
165
+ )
166
+
167
+
168
+ def enhance_network(
169
+ power_flow_engine, strategy_registry, cost_model, flexibility_pct, output_path
170
+ ):
171
+ """
172
+ Run the enhancement algorithm on a loaded network and write its visualisation.
173
+
174
+ Args:
175
+ power_flow_engine: Engine holding the network, as `load_network` returns it
176
+ strategy_registry: Registry of enhancement strategies
177
+ cost_model: Cost model for evaluating strategies
178
+ flexibility_pct: Percentage of flexibility of the loads
179
+ output_path: Path of the HTML visualisation of the run
180
+ """
181
+ if hasattr(power_flow_engine.network, "load"):
182
+ power_flow_engine.flexibility_settings["load"] = {
183
+ name: flexibility_pct
184
+ for name in power_flow_engine.network.load["name"].tolist()
185
+ }
186
+
187
+ # Configure the algorithm
188
+ algorithm = GridEnhancementAlgorithm(
189
+ power_flow_engine=power_flow_engine,
190
+ strategy_registry=strategy_registry,
191
+ cost_model=cost_model,
192
+ max_iterations=MV_LV_FEEDER.algorithm_max_iterations,
193
+ )
194
+ # Run the grid enhancement algorithm
195
+ success, results = algorithm.run()
196
+
197
+ create_enhancement_visualisation(algorithm, str(output_path))
198
+ return results
199
+
200
+
201
+ def process_single_network(args) -> dict[str, Any]:
202
+ """Run one network/flexibility combination, reporting success or failure.
203
+
204
+ Runs in a worker process, so failures can't just propagate to the caller — instead
205
+ of being logged and silently dropped, they're returned so the caller can collect
206
+ and report every failure once all networks have been processed.
207
+
208
+ The record also tells whether the power flow diverged: either along the way (the run
209
+ is then still a success, with a partial or complete solution) or on the initial
210
+ power flow (the run is then a failure, as there is no solution at all).
211
+ """
212
+ network_path, load_factor, flexibility_pct, output_dir = args
213
+ # Re-create registry and cost model for each process to avoid shared state issues
214
+ with_flex = flexibility_pct > 0
215
+ strategy_registry = create_strategy_registry(with_flex)
216
+ cost_model = create_cost_model()
217
+
218
+ result = {
219
+ "network": network_path.name,
220
+ "flexibility_pct": flexibility_pct,
221
+ "success": False,
222
+ "diverged": False,
223
+ "error": None,
224
+ }
225
+ try:
226
+ results = run_grid_enhancement(
227
+ network_path,
228
+ strategy_registry,
229
+ cost_model,
230
+ load_factor,
231
+ flexibility_pct,
232
+ output_dir,
233
+ )
234
+ result["success"] = True
235
+ result["diverged"] = results["diverged"]
236
+ except Exception as exc:
237
+ error = traceback.format_exc()
238
+ logging.error(f"Error processing {network_path.name}:\n{error}")
239
+ result["error"] = error
240
+ result["diverged"] = isinstance(exc, PowerFlowNotConverged)
241
+ return result
242
+
243
+
244
+ if __name__ == "__main__":
245
+ # Create output directory
246
+ output_dir = Path("results")
247
+ output_dir.mkdir(exist_ok=True)
248
+
249
+ # Get all network files
250
+ network_files = sorted(data_path["pandapower"].glob("*.json"))
251
+ if not network_files:
252
+ # The feeder files are not part of the installed package
253
+ raise FileNotFoundError(
254
+ f"No feeder file (*.json) in {data_path['pandapower']}. The case study needs "
255
+ f"the feeder data of the repository: run it from a clone of gridforge."
256
+ )
257
+
258
+ # Parameters
259
+ load_factor = 2.5
260
+ flex_scenarios = [0.0, 30.0]
261
+ # flex_scenarios = [0.]
262
+
263
+ failures: list[dict[str, Any]] = []
264
+ diverged_runs: list[dict[str, Any]] = []
265
+
266
+ for flexibility_pct in flex_scenarios:
267
+ logging.info(f"--- Running scenario with {flexibility_pct}% flexibility ---")
268
+
269
+ # Prepare arguments for parallel execution
270
+ args_list = [
271
+ (f, load_factor, flexibility_pct, output_dir) for f in network_files
272
+ ]
273
+
274
+ # Run in parallel
275
+ num_processes = multiprocessing.cpu_count()
276
+ logging.info(
277
+ f"Starting parallel processing with {num_processes} processes for {len(network_files)} networks."
278
+ )
279
+
280
+ with multiprocessing.Pool(processes=num_processes) as pool:
281
+ # Use tqdm for progress bar by wrapping pool.imap_unordered
282
+ scenario_results = list(
283
+ tqdm(
284
+ pool.imap_unordered(process_single_network, args_list),
285
+ total=len(args_list),
286
+ )
287
+ )
288
+
289
+ failures.extend(r for r in scenario_results if not r["success"])
290
+ diverged_runs.extend(r for r in scenario_results if r["diverged"])
291
+
292
+ total_runs = len(network_files) * len(flex_scenarios)
293
+ if diverged_runs:
294
+ logging.warning(
295
+ f"{len(diverged_runs)}/{total_runs} network run(s) hit a power flow divergence:"
296
+ )
297
+ for run in diverged_runs:
298
+ outcome = (
299
+ "initial power flow, no result"
300
+ if not run["success"]
301
+ else "strategy undone, run continued"
302
+ )
303
+ logging.warning(
304
+ f" - {run['network']} (flexibility={run['flexibility_pct']}%): {outcome}"
305
+ )
306
+ if failures:
307
+ logging.error(f"{len(failures)}/{total_runs} network run(s) failed:")
308
+ for failure in failures:
309
+ logging.error(
310
+ f" - {failure['network']} (flexibility={failure['flexibility_pct']}%)"
311
+ )
312
+ sys.exit(1)
313
+ else:
314
+ logging.info(f"All {total_runs} network runs completed successfully.")
@@ -0,0 +1,168 @@
1
+ import logging
2
+
3
+ import networkx as nx
4
+ import pandapower as pp
5
+ import pandas as pd
6
+ import simbench as sb
7
+
8
+ from gridforge.case_study.config import SIMBENCH
9
+ from gridforge.core.cost_model import CostModel
10
+ from gridforge.core.grid_enhancement import (
11
+ EnhancementStrategyRegistry,
12
+ GridEnhancementAlgorithm,
13
+ )
14
+ from gridforge.engines.pandapower_engine import PandaPowerEngine
15
+ from gridforge.strategies.flexibility import FlexibilityStrategy
16
+ from gridforge.strategies.line_upgrade import LineUpgradeStrategy
17
+ from gridforge.strategies.tap_change import TapChangeStrategy
18
+ from gridforge.strategies.transformer_upgrade import TransformerUpgradeStrategy
19
+ from gridforge.utils.logging import setup_logging
20
+
21
+ setup_logging(logging.INFO)
22
+
23
+
24
+ def import_network():
25
+ sb_code1 = "1-LV-rural2--0-sw"
26
+ net = sb.get_simbench_net(sb_code1)
27
+ net["trafo"]["tap_changer_type"] = "Ratio"
28
+ print(net.loadcases)
29
+ return net
30
+
31
+
32
+ def get_downstream_buses(net, target_bus):
33
+ # 1. Find the root of the radial network (the slack bus / external grid)
34
+ # Assuming there is only one external grid for this radial network
35
+ slack_bus = net.ext_grid.bus.values[0]
36
+
37
+ # 2. Convert the pandapower network into a networkx graph
38
+ # respect_switches=True ensures open switches don't create false paths
39
+ mg = pp.topology.create_nxgraph(net, respect_switches=True)
40
+
41
+ # 3. Create a directed tree originating from the slack bus
42
+ # This automatically gives directionality flowing away from the source
43
+ directed_tree = nx.bfs_tree(mg, source=slack_bus)
44
+
45
+ # 4. Find all downstream buses (descendants in the directed tree)
46
+ # nx.descendants returns a set of nodes, we convert it to a list
47
+ downstream_buses = list(nx.descendants(directed_tree, target_bus))
48
+
49
+ return downstream_buses
50
+
51
+
52
+ def apply_load_scaling(net, scale_factor):
53
+ net["load"]["p_mw"] *= scale_factor
54
+ net["load"]["q_mvar"] *= scale_factor
55
+
56
+
57
+ def apply_absolute_values(net, absolute_values_dict, case_or_time_step):
58
+ for elm_param in absolute_values_dict.keys():
59
+ if absolute_values_dict[elm_param].shape[1]:
60
+ elm = elm_param[0]
61
+ param = elm_param[1]
62
+ net[elm].loc[:, param] = absolute_values_dict[elm_param].loc[
63
+ case_or_time_step
64
+ ]
65
+
66
+
67
+ def create_case_study(load_scale=1.5, flexibility_pct=10.0):
68
+ net = import_network()
69
+ loadcases = sb.get_absolute_values(net, profiles_instead_of_study_cases=False)
70
+ apply_absolute_values(net, loadcases, "hL")
71
+ apply_load_scaling(net, load_scale)
72
+ engine = PandaPowerEngine()
73
+ engine.network = net
74
+ bus_with_flex = get_downstream_buses(net, 73)
75
+ loads_with_flex = net["load"].loc[net["load"]["bus"].isin(bus_with_flex)]
76
+ engine.flexibility_settings["load"] = {
77
+ name: flexibility_pct for name in loads_with_flex["name"].tolist()
78
+ }
79
+ engine.run_power_flow()
80
+ engine.check_violations()
81
+ engine.plot_network_violations(
82
+ show_ids=False,
83
+ rc_params={
84
+ "figure": {"size": (10, 10)},
85
+ "bus": {
86
+ "size": 100.0,
87
+ },
88
+ },
89
+ )
90
+
91
+ return engine
92
+
93
+
94
+ def create_strategy(
95
+ line_upgrade=True, transformer_upgrade=True, flexibility=True, tap_change=True
96
+ ):
97
+ registry = EnhancementStrategyRegistry()
98
+ # Add line upgrade strategies
99
+ line_upgrade_strategy = LineUpgradeStrategy(
100
+ line_types=SIMBENCH.line_types,
101
+ max_iterations=SIMBENCH.line_upgrade_max_iterations,
102
+ min_voltage_sensitivity=SIMBENCH.line_upgrade_min_voltage_sensitivity,
103
+ )
104
+
105
+ # Add custom transformer upgrade strategy
106
+ transformer_upgrade_strategy = TransformerUpgradeStrategy(
107
+ transformer_types=SIMBENCH.trafo_types
108
+ )
109
+ if transformer_upgrade:
110
+ registry.register_strategy(transformer_upgrade_strategy)
111
+ if line_upgrade:
112
+ registry.register_strategy(line_upgrade_strategy)
113
+ if flexibility:
114
+ registry.register_strategy(
115
+ FlexibilityStrategy(n_activation=SIMBENCH.flexibility_n_activation)
116
+ )
117
+ if tap_change:
118
+ registry.register_strategy(TapChangeStrategy())
119
+
120
+ return registry
121
+
122
+
123
+ def create_cost_model():
124
+ return CostModel(SIMBENCH.unit_costs)
125
+
126
+
127
+ def run_case_study(
128
+ load_scale=1.7,
129
+ flexibility_pct=10.0,
130
+ line_upgrade=True,
131
+ transformer_upgrade=True,
132
+ flexibility=True,
133
+ tap_change=True,
134
+ ):
135
+ engine = create_case_study(load_scale, flexibility_pct)
136
+ registry = create_strategy(
137
+ line_upgrade, transformer_upgrade, flexibility, tap_change
138
+ )
139
+ cost_model = create_cost_model()
140
+ ge = GridEnhancementAlgorithm(
141
+ power_flow_engine=engine,
142
+ cost_model=cost_model,
143
+ max_iterations=SIMBENCH.algorithm_max_iterations,
144
+ strategy_registry=registry,
145
+ )
146
+ success, results = ge.run()
147
+ engine.plot_network_violations(
148
+ show_ids=False,
149
+ enhancement_results=results,
150
+ rc_params={
151
+ "figure": {"size": (10, 10)},
152
+ "bus": {
153
+ "size": 100.0,
154
+ },
155
+ },
156
+ )
157
+ return results["summary"]
158
+
159
+
160
+ if __name__ == "__main__":
161
+ res_list = []
162
+ for flex in [0.0, 25.0]:
163
+ res = run_case_study(flexibility_pct=flex, load_scale=1.5)
164
+ res["flexibility_pct"] = flex
165
+ res_list.append(res)
166
+
167
+ res_total = pd.DataFrame.from_records(res_list)
168
+ res_total.to_csv("test_case_results.csv")
File without changes