gridplan 0.1.0__tar.gz

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.
gridplan-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bonnie Bingham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: gridplan
3
+ Version: 0.1.0
4
+ Summary: DC-OPF congestion analysis and MILP-based transmission expansion planning
5
+ Author: Bonnie Bingham
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/bbplus3/gridplan
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Scientific/Engineering
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pyomo>=6.7
16
+ Requires-Dist: highspy>=1.7
17
+ Provides-Extra: viz
18
+ Requires-Dist: matplotlib; extra == "viz"
19
+ Requires-Dist: networkx; extra == "viz"
20
+ Requires-Dist: pyvis; extra == "viz"
21
+ Provides-Extra: gnn
22
+ Requires-Dist: torch; extra == "gnn"
23
+ Provides-Extra: app
24
+ Requires-Dist: streamlit; extra == "app"
25
+ Requires-Dist: pandas; extra == "app"
26
+ Requires-Dist: matplotlib; extra == "app"
27
+ Requires-Dist: networkx; extra == "app"
28
+ Requires-Dist: pyvis; extra == "app"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Provides-Extra: all
32
+ Requires-Dist: matplotlib; extra == "all"
33
+ Requires-Dist: networkx; extra == "all"
34
+ Requires-Dist: pyvis; extra == "all"
35
+ Requires-Dist: torch; extra == "all"
36
+ Requires-Dist: streamlit; extra == "all"
37
+ Requires-Dist: pandas; extra == "all"
38
+ Requires-Dist: pytest; extra == "all"
39
+ Dynamic: license-file
40
+
41
+ # gridplan
42
+
43
+ DC-OPF congestion analysis and MILP-based transmission expansion planning,
44
+ built on [Pyomo](https://www.pyomo.org/). Answers two questions:
45
+
46
+ 1. **Given today's grid, where's it congested, and what's that costing us?**
47
+ 2. **Given a list of candidate new lines and their price tags, which ones are
48
+ actually worth building?**
49
+
50
+ ```python
51
+ from gridplan import Network, solve_congestion, solve_expansion
52
+
53
+ net = Network.from_csv("examples/sample_data")
54
+
55
+ result = solve_congestion(net, "summer_peak_h17")
56
+ print(result.summary())
57
+ print("Overloaded lines:", result.lines_over(90))
58
+ print("LMPs ($/MWh):", result.lmps)
59
+
60
+ plan = solve_expansion(net)
61
+ print(plan.summary())
62
+ ```
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ git clone https://github.com/bbplus3/gridplan.git
68
+ cd gridplan
69
+ pip install -e . # core: Network, solve_congestion, solve_expansion
70
+ pip install -e ".[viz]" # + static/interactive network diagrams
71
+ pip install -e ".[gnn]" # + GNN power-flow surrogate (needs torch)
72
+ pip install -e ".[app]" # + Streamlit browser app
73
+ pip install -e ".[all]" # everything
74
+ ```
75
+
76
+ No separate solver binary needed — `highspy` (the HiGHS solver, pure pip
77
+ install) is a core dependency, used by default for both the LP congestion
78
+ model and the MILP expansion planning model.
79
+
80
+ ## Quickstart
81
+
82
+ ```bash
83
+ python examples/quickstart.py
84
+ ```
85
+
86
+ or generate a browser diagram / run the full app:
87
+
88
+ ```bash
89
+ pip install -e ".[app]"
90
+ streamlit run app.py
91
+ ```
92
+
93
+ ## How the model works
94
+
95
+ **DC power flow approximation.** Like virtually all transmission planning
96
+ tools (PyPSA, PLEXOS, Google Tapestry, etc.), this uses the linearized "DC"
97
+ power flow model rather than full AC power flow: flow on a line is
98
+ proportional to the voltage-angle difference across it, divided by the
99
+ line's reactance. Standard for planning studies — fast, always solves to a
100
+ clean global optimum, and captures the loop-flow effects that actually
101
+ drive congestion — but not adequate for detailed voltage/operational
102
+ studies (use `pandapower` or `PyPSA` with an AC solver for that).
103
+
104
+ **Congestion model (`gridplan.congestion`).** For a given snapshot, minimizes
105
+ generation cost subject to power balance at every bus and flow limits on
106
+ every existing line — a linear program, solved to global optimality via
107
+ simplex. The dual value on each bus's power-balance constraint is that
108
+ bus's locational marginal price (LMP); this falls straight out of the
109
+ solve, no separate computation needed. `CongestionResult` wraps the answer
110
+ with convenience methods: `.lines_over(pct)`, `.binding_lines()`,
111
+ `.is_feasible`, `.summary()`.
112
+
113
+ **Expansion planning model (`gridplan.expansion`).** Adds a binary
114
+ build/don't-build decision per candidate line, solved jointly across every
115
+ snapshot you give it (a mixed-integer linear program). Uses the standard
116
+ disjunctive/big-M formulation: a candidate line's power-flow equation is
117
+ only enforced when its build variable is 1. The objective weighs one-time
118
+ capital cost against annualized operating + reliability cost.
119
+
120
+ ## Package layout
121
+
122
+ ```
123
+ src/gridplan/
124
+ network.py - Bus, Line, Generator, Network (Network.from_csv(...))
125
+ congestion.py - solve_congestion(), summarize_congestion(), CongestionResult
126
+ expansion.py - solve_expansion(), ExpansionResult
127
+ visualize.py - static PNG network diagrams (needs [viz])
128
+ interactive.py - draggable HTML network diagrams via pyvis (needs [viz])
129
+ gnn.py - GNN power-flow surrogate (needs [gnn]; see module docstring
130
+ for an honest discussion of when this technique actually helps)
131
+ examples/
132
+ sample_data/ - a fictional 9-bus, 3-zone utility system
133
+ generate_sample_data.py
134
+ quickstart.py
135
+ tests/
136
+ test_gridplan.py - hand-checkable 2-bus cases + sanity checks on the sample network
137
+ app.py - Streamlit browser app (needs [app])
138
+ ```
139
+
140
+ ## Bringing your own network
141
+
142
+ Replace `examples/sample_data/*.csv` (or point `Network.from_csv()` at your
143
+ own directory) with four CSVs in this schema:
144
+
145
+ | File | Columns | Notes |
146
+ |---|---|---|
147
+ | `buses.csv` | `bus_id, name, zone, base_kv` | one row per substation/bus |
148
+ | `lines.csv` | `line_id, from_bus, to_bus, reactance_pu, capacity_mw, status, length_km, cost_million_usd` | `status` is `existing` or `candidate`; cost only needed for candidates |
149
+ | `generators.csv` | `gen_id, bus_id, name, capacity_mw, marginal_cost_per_mwh, fuel_type` | one row per generating unit |
150
+ | `loads.csv` | `snapshot, bus_id, hour, season, demand_mw` | one row per (snapshot, bus); a "snapshot" is any label for an hour/condition |
151
+
152
+ `reactance_pu` needs a consistent MVA base across all lines (default 100
153
+ MVA — change `BASE_MVA` in `gridplan/congestion.py` and `gridplan/expansion.py`
154
+ if yours differs). For renewable generators, note `capacity_mw` is treated
155
+ as a hard cap; if you want per-snapshot availability (e.g. wind/solar
156
+ capacity factors), that's a small, contained change to the generator-limit
157
+ constraint in both modules.
158
+
159
+ ## Running tests
160
+
161
+ ```bash
162
+ pip install -e ".[dev]"
163
+ pytest
164
+ ```
165
+
166
+ ## License
167
+
168
+ MIT — see `LICENSE`.
@@ -0,0 +1,128 @@
1
+ # gridplan
2
+
3
+ DC-OPF congestion analysis and MILP-based transmission expansion planning,
4
+ built on [Pyomo](https://www.pyomo.org/). Answers two questions:
5
+
6
+ 1. **Given today's grid, where's it congested, and what's that costing us?**
7
+ 2. **Given a list of candidate new lines and their price tags, which ones are
8
+ actually worth building?**
9
+
10
+ ```python
11
+ from gridplan import Network, solve_congestion, solve_expansion
12
+
13
+ net = Network.from_csv("examples/sample_data")
14
+
15
+ result = solve_congestion(net, "summer_peak_h17")
16
+ print(result.summary())
17
+ print("Overloaded lines:", result.lines_over(90))
18
+ print("LMPs ($/MWh):", result.lmps)
19
+
20
+ plan = solve_expansion(net)
21
+ print(plan.summary())
22
+ ```
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ git clone https://github.com/bbplus3/gridplan.git
28
+ cd gridplan
29
+ pip install -e . # core: Network, solve_congestion, solve_expansion
30
+ pip install -e ".[viz]" # + static/interactive network diagrams
31
+ pip install -e ".[gnn]" # + GNN power-flow surrogate (needs torch)
32
+ pip install -e ".[app]" # + Streamlit browser app
33
+ pip install -e ".[all]" # everything
34
+ ```
35
+
36
+ No separate solver binary needed — `highspy` (the HiGHS solver, pure pip
37
+ install) is a core dependency, used by default for both the LP congestion
38
+ model and the MILP expansion planning model.
39
+
40
+ ## Quickstart
41
+
42
+ ```bash
43
+ python examples/quickstart.py
44
+ ```
45
+
46
+ or generate a browser diagram / run the full app:
47
+
48
+ ```bash
49
+ pip install -e ".[app]"
50
+ streamlit run app.py
51
+ ```
52
+
53
+ ## How the model works
54
+
55
+ **DC power flow approximation.** Like virtually all transmission planning
56
+ tools (PyPSA, PLEXOS, Google Tapestry, etc.), this uses the linearized "DC"
57
+ power flow model rather than full AC power flow: flow on a line is
58
+ proportional to the voltage-angle difference across it, divided by the
59
+ line's reactance. Standard for planning studies — fast, always solves to a
60
+ clean global optimum, and captures the loop-flow effects that actually
61
+ drive congestion — but not adequate for detailed voltage/operational
62
+ studies (use `pandapower` or `PyPSA` with an AC solver for that).
63
+
64
+ **Congestion model (`gridplan.congestion`).** For a given snapshot, minimizes
65
+ generation cost subject to power balance at every bus and flow limits on
66
+ every existing line — a linear program, solved to global optimality via
67
+ simplex. The dual value on each bus's power-balance constraint is that
68
+ bus's locational marginal price (LMP); this falls straight out of the
69
+ solve, no separate computation needed. `CongestionResult` wraps the answer
70
+ with convenience methods: `.lines_over(pct)`, `.binding_lines()`,
71
+ `.is_feasible`, `.summary()`.
72
+
73
+ **Expansion planning model (`gridplan.expansion`).** Adds a binary
74
+ build/don't-build decision per candidate line, solved jointly across every
75
+ snapshot you give it (a mixed-integer linear program). Uses the standard
76
+ disjunctive/big-M formulation: a candidate line's power-flow equation is
77
+ only enforced when its build variable is 1. The objective weighs one-time
78
+ capital cost against annualized operating + reliability cost.
79
+
80
+ ## Package layout
81
+
82
+ ```
83
+ src/gridplan/
84
+ network.py - Bus, Line, Generator, Network (Network.from_csv(...))
85
+ congestion.py - solve_congestion(), summarize_congestion(), CongestionResult
86
+ expansion.py - solve_expansion(), ExpansionResult
87
+ visualize.py - static PNG network diagrams (needs [viz])
88
+ interactive.py - draggable HTML network diagrams via pyvis (needs [viz])
89
+ gnn.py - GNN power-flow surrogate (needs [gnn]; see module docstring
90
+ for an honest discussion of when this technique actually helps)
91
+ examples/
92
+ sample_data/ - a fictional 9-bus, 3-zone utility system
93
+ generate_sample_data.py
94
+ quickstart.py
95
+ tests/
96
+ test_gridplan.py - hand-checkable 2-bus cases + sanity checks on the sample network
97
+ app.py - Streamlit browser app (needs [app])
98
+ ```
99
+
100
+ ## Bringing your own network
101
+
102
+ Replace `examples/sample_data/*.csv` (or point `Network.from_csv()` at your
103
+ own directory) with four CSVs in this schema:
104
+
105
+ | File | Columns | Notes |
106
+ |---|---|---|
107
+ | `buses.csv` | `bus_id, name, zone, base_kv` | one row per substation/bus |
108
+ | `lines.csv` | `line_id, from_bus, to_bus, reactance_pu, capacity_mw, status, length_km, cost_million_usd` | `status` is `existing` or `candidate`; cost only needed for candidates |
109
+ | `generators.csv` | `gen_id, bus_id, name, capacity_mw, marginal_cost_per_mwh, fuel_type` | one row per generating unit |
110
+ | `loads.csv` | `snapshot, bus_id, hour, season, demand_mw` | one row per (snapshot, bus); a "snapshot" is any label for an hour/condition |
111
+
112
+ `reactance_pu` needs a consistent MVA base across all lines (default 100
113
+ MVA — change `BASE_MVA` in `gridplan/congestion.py` and `gridplan/expansion.py`
114
+ if yours differs). For renewable generators, note `capacity_mw` is treated
115
+ as a hard cap; if you want per-snapshot availability (e.g. wind/solar
116
+ capacity factors), that's a small, contained change to the generator-limit
117
+ constraint in both modules.
118
+
119
+ ## Running tests
120
+
121
+ ```bash
122
+ pip install -e ".[dev]"
123
+ pytest
124
+ ```
125
+
126
+ ## License
127
+
128
+ MIT — see `LICENSE`.
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gridplan"
7
+ version = "0.1.0"
8
+ description = "DC-OPF congestion analysis and MILP-based transmission expansion planning"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Bonnie Bingham" }]
12
+ requires-python = ">=3.9"
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Scientific/Engineering",
18
+ ]
19
+ dependencies = [
20
+ "pyomo>=6.7",
21
+ "highspy>=1.7",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ viz = ["matplotlib", "networkx", "pyvis"]
26
+ gnn = ["torch"]
27
+ app = ["streamlit", "pandas", "matplotlib", "networkx", "pyvis"]
28
+ dev = ["pytest"]
29
+ all = ["matplotlib", "networkx", "pyvis", "torch", "streamlit", "pandas", "pytest"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/bbplus3/gridplan"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,31 @@
1
+ """
2
+ gridplan: DC-OPF congestion analysis and MILP-based transmission expansion
3
+ planning, built on Pyomo.
4
+
5
+ from gridplan import Network, solve_congestion, solve_expansion
6
+
7
+ net = Network.from_csv("data/")
8
+ result = solve_congestion(net, "summer_peak_h17")
9
+ print(result.summary())
10
+ print("Overloaded lines:", result.lines_over(90))
11
+
12
+ plan = solve_expansion(net)
13
+ print(plan.summary())
14
+
15
+ Optional extras (not imported by default, so `import gridplan` stays
16
+ lightweight):
17
+ from gridplan import visualize # static PNG diagrams (needs matplotlib, networkx)
18
+ from gridplan import interactive # draggable HTML diagrams (needs pyvis)
19
+ from gridplan import gnn # GNN power-flow surrogate (needs torch)
20
+ """
21
+ from .network import Network, Bus, Line, Generator
22
+ from .congestion import solve_congestion, summarize_congestion, CongestionResult, CongestionSummary, LineFlow
23
+ from .expansion import solve_expansion, ExpansionResult
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "Network", "Bus", "Line", "Generator",
29
+ "solve_congestion", "summarize_congestion", "CongestionResult", "CongestionSummary", "LineFlow",
30
+ "solve_expansion", "ExpansionResult",
31
+ ]
@@ -0,0 +1,192 @@
1
+ """
2
+ DC-OPF congestion analysis. See docs/theory.md (or the top-level README)
3
+ for the physics and optimization behind this - in short: minimizes
4
+ generation cost subject to power balance and line-flow limits, and the
5
+ solve's dual values double as locational marginal prices (LMPs).
6
+ """
7
+ import math
8
+ from dataclasses import dataclass, field
9
+ from typing import Optional
10
+
11
+ import pyomo.environ as pyo
12
+
13
+ BASE_MVA = 100.0
14
+ DEFAULT_SOLVER = "appsi_highs" # pure-pip solver (via the `highspy` package) - no separate binary needed
15
+ VOLL = 5000 # value of lost load, $/MWh
16
+
17
+
18
+ @dataclass
19
+ class LineFlow:
20
+ line_id: str
21
+ flow_mw: float
22
+ capacity_mw: float
23
+ loading_pct: float
24
+ binding: bool
25
+
26
+
27
+ @dataclass
28
+ class CongestionResult:
29
+ """Result of solving one snapshot's DC-OPF. Prefer the helper methods
30
+ below over digging through the raw dicts directly."""
31
+ snapshot: str
32
+ status: str
33
+ total_cost: float
34
+ gen_dispatch: dict # gen_id -> MW
35
+ line_flows: dict # line_id -> LineFlow
36
+ lmps: dict # bus_id -> $/MWh
37
+ unserved_load: dict # bus_id -> MW (only entries > 0)
38
+
39
+ @property
40
+ def is_feasible(self) -> bool:
41
+ """True if the network could fully serve demand without shedding load."""
42
+ return not self.unserved_load
43
+
44
+ @property
45
+ def total_unserved_mw(self) -> float:
46
+ return sum(self.unserved_load.values())
47
+
48
+ def lines_over(self, pct: float = 90.0):
49
+ """Line IDs loaded above `pct`% of thermal capacity."""
50
+ return [lid for lid, lf in self.line_flows.items() if lf.loading_pct >= pct]
51
+
52
+ def binding_lines(self):
53
+ """Line IDs at (or essentially at) their thermal limit."""
54
+ return [lid for lid, lf in self.line_flows.items() if lf.binding]
55
+
56
+ def summary(self) -> str:
57
+ lines = [f"[{self.snapshot}] status={self.status} total_cost=${self.total_cost:,.0f}"]
58
+ if not self.is_feasible:
59
+ lines.append(f" UNSERVED LOAD: {self.total_unserved_mw:.1f} MW")
60
+ binding = self.binding_lines()
61
+ if binding:
62
+ lines.append(f" binding lines: {', '.join(binding)}")
63
+ return "\n".join(lines)
64
+
65
+
66
+ def _build_dcopf_model(net, snapshot, slack_bus=None):
67
+ lines = net.existing_lines()
68
+ buses = net.buses
69
+ gens = net.generators
70
+ demand = net.loads.get(snapshot, {})
71
+
72
+ if slack_bus is None:
73
+ slack_bus = next(iter(buses))
74
+
75
+ m = pyo.ConcreteModel(name=f"DCOPF_{snapshot}")
76
+ m.BUS = pyo.Set(initialize=list(buses.keys()))
77
+ m.LINE = pyo.Set(initialize=list(lines.keys()))
78
+ m.GEN = pyo.Set(initialize=list(gens.keys()))
79
+
80
+ m.gen_mw = pyo.Var(m.GEN, within=pyo.NonNegativeReals)
81
+ m.angle = pyo.Var(m.BUS, within=pyo.Reals, bounds=(-math.pi / 2, math.pi / 2))
82
+ m.unserved_mw = pyo.Var(m.BUS, within=pyo.NonNegativeReals)
83
+
84
+ def gen_limit_rule(m, g):
85
+ return m.gen_mw[g] <= gens[g].capacity_mw
86
+ m.gen_limit = pyo.Constraint(m.GEN, rule=gen_limit_rule)
87
+
88
+ m.slack_angle = pyo.Constraint(expr=m.angle[slack_bus] == 0)
89
+
90
+ def flow_expr(m, l):
91
+ ln = lines[l]
92
+ return BASE_MVA * (m.angle[ln.from_bus] - m.angle[ln.to_bus]) / ln.reactance_pu
93
+ m.flow = pyo.Expression(m.LINE, rule=flow_expr)
94
+
95
+ def flow_upper_rule(m, l):
96
+ return m.flow[l] <= lines[l].capacity_mw
97
+ m.flow_upper = pyo.Constraint(m.LINE, rule=flow_upper_rule)
98
+
99
+ def flow_lower_rule(m, l):
100
+ return m.flow[l] >= -lines[l].capacity_mw
101
+ m.flow_lower = pyo.Constraint(m.LINE, rule=flow_lower_rule)
102
+
103
+ def balance_rule(m, b):
104
+ gen_at_bus = sum(m.gen_mw[g] for g in gens if gens[g].bus_id == b)
105
+ inflow = sum(m.flow[l] for l in lines if lines[l].to_bus == b) \
106
+ - sum(m.flow[l] for l in lines if lines[l].from_bus == b)
107
+ d = demand.get(b, 0.0)
108
+ return gen_at_bus + inflow + m.unserved_mw[b] == d
109
+ m.balance = pyo.Constraint(m.BUS, rule=balance_rule)
110
+
111
+ def obj_rule(m):
112
+ gen_cost = sum(m.gen_mw[g] * gens[g].marginal_cost_per_mwh for g in gens)
113
+ shed_cost = sum(m.unserved_mw[b] * VOLL for b in buses)
114
+ return gen_cost + shed_cost
115
+ m.obj = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
116
+
117
+ m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
118
+ return m
119
+
120
+
121
+ def solve_congestion(network, snapshot, solver_name=DEFAULT_SOLVER) -> CongestionResult:
122
+ """Solve DC-OPF for one snapshot and return a CongestionResult."""
123
+ m = _build_dcopf_model(network, snapshot)
124
+ solver = pyo.SolverFactory(solver_name)
125
+ result = solver.solve(m)
126
+ status = str(result.solver.termination_condition)
127
+
128
+ lines = network.existing_lines()
129
+ line_flows = {}
130
+ for l in m.LINE:
131
+ flow = pyo.value(m.flow[l])
132
+ cap = lines[l].capacity_mw
133
+ pct = 100 * abs(flow) / cap if cap else 0
134
+ line_flows[l] = LineFlow(line_id=l, flow_mw=round(flow, 2), capacity_mw=cap,
135
+ loading_pct=round(pct, 1), binding=pct >= 99.5)
136
+
137
+ lmps = {}
138
+ for b in m.BUS:
139
+ try:
140
+ lmps[b] = round(m.dual[m.balance[b]], 3)
141
+ except (KeyError, ValueError):
142
+ lmps[b] = None
143
+
144
+ unserved = {b: round(pyo.value(m.unserved_mw[b]), 2) for b in m.BUS
145
+ if pyo.value(m.unserved_mw[b]) > 1e-3}
146
+ gen_dispatch = {g: round(pyo.value(m.gen_mw[g]), 2) for g in m.GEN}
147
+
148
+ return CongestionResult(
149
+ snapshot=snapshot, status=status, total_cost=round(pyo.value(m.obj), 2),
150
+ gen_dispatch=gen_dispatch, line_flows=line_flows, lmps=lmps, unserved_load=unserved,
151
+ )
152
+
153
+
154
+ @dataclass
155
+ class CongestionSummary:
156
+ n_snapshots: int
157
+ binding_count_by_line: dict
158
+ max_loading_pct_by_line: dict
159
+ total_unserved_mwh: float
160
+ per_snapshot_results: list = field(default_factory=list)
161
+
162
+ def worst_lines(self, top_n: int = 5):
163
+ """Line IDs most often binding, most-congested first."""
164
+ return sorted(self.binding_count_by_line, key=lambda l: -self.binding_count_by_line[l])[:top_n]
165
+
166
+
167
+ def summarize_congestion(network, snapshots=None, solver_name=DEFAULT_SOLVER) -> CongestionSummary:
168
+ """Solve every snapshot (or a given subset) and summarize which lines bind most often."""
169
+ if snapshots is None:
170
+ snapshots = network.snapshots
171
+
172
+ binding_counts = {l: 0 for l in network.existing_lines()}
173
+ max_loading = {l: 0.0 for l in network.existing_lines()}
174
+ total_shed = 0.0
175
+ results = []
176
+
177
+ for snap in snapshots:
178
+ r = solve_congestion(network, snap, solver_name=solver_name)
179
+ results.append(r)
180
+ for lid, lf in r.line_flows.items():
181
+ if lf.binding:
182
+ binding_counts[lid] += 1
183
+ max_loading[lid] = max(max_loading[lid], lf.loading_pct)
184
+ total_shed += r.total_unserved_mw
185
+
186
+ return CongestionSummary(
187
+ n_snapshots=len(snapshots),
188
+ binding_count_by_line=binding_counts,
189
+ max_loading_pct_by_line={l: round(v, 1) for l, v in max_loading.items()},
190
+ total_unserved_mwh=round(total_shed, 2),
191
+ per_snapshot_results=results,
192
+ )