gridplan 0.1.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.
gridplan/__init__.py ADDED
@@ -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
+ ]
gridplan/congestion.py ADDED
@@ -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
+ )
gridplan/expansion.py ADDED
@@ -0,0 +1,154 @@
1
+ """
2
+ Transmission expansion planning (TEP): a MILP that decides which candidate
3
+ lines to build, jointly across all given snapshots, using the standard
4
+ disjunctive/big-M formulation for the candidate lines' power-flow equations.
5
+ """
6
+ from dataclasses import dataclass, field
7
+
8
+ import pyomo.environ as pyo
9
+
10
+ from .congestion import BASE_MVA, VOLL, DEFAULT_SOLVER
11
+
12
+ BIG_M = 500 # MW-equivalent big-M; should exceed any plausible angle-driven flow
13
+
14
+
15
+ @dataclass
16
+ class ExpansionResult:
17
+ status: str
18
+ objective_usd: float
19
+ lines_to_build: list
20
+ build_decision: dict # candidate line_id -> bool
21
+ total_capital_cost_million_usd: float
22
+ total_unserved_mwh_sample: float
23
+ annualization_factor: float
24
+
25
+ def summary(self) -> str:
26
+ lines = [f"status={self.status} objective=${self.objective_usd:,.0f}"]
27
+ if self.lines_to_build:
28
+ lines.append(f" build: {', '.join(self.lines_to_build)} "
29
+ f"(${self.total_capital_cost_million_usd}M capital)")
30
+ else:
31
+ lines.append(" build: none recommended")
32
+ return "\n".join(lines)
33
+
34
+
35
+ def _build_tep_model(net, snapshots, annualization_factor, slack_bus=None):
36
+ all_lines = net.lines
37
+ existing = net.existing_lines()
38
+ candidates = net.candidate_lines()
39
+ buses = net.buses
40
+ gens = net.generators
41
+
42
+ if slack_bus is None:
43
+ slack_bus = next(iter(buses))
44
+
45
+ m = pyo.ConcreteModel(name="TEP")
46
+ m.BUS = pyo.Set(initialize=list(buses.keys()))
47
+ m.LINE = pyo.Set(initialize=list(all_lines.keys()))
48
+ m.EXISTING = pyo.Set(initialize=list(existing.keys()))
49
+ m.CANDIDATE = pyo.Set(initialize=list(candidates.keys()))
50
+ m.GEN = pyo.Set(initialize=list(gens.keys()))
51
+ m.SNAP = pyo.Set(initialize=list(snapshots))
52
+
53
+ m.build = pyo.Var(m.CANDIDATE, within=pyo.Binary)
54
+ m.gen_mw = pyo.Var(m.GEN, m.SNAP, within=pyo.NonNegativeReals)
55
+ m.angle = pyo.Var(m.BUS, m.SNAP, within=pyo.Reals, bounds=(-1.571, 1.571))
56
+ m.flow = pyo.Var(m.LINE, m.SNAP, within=pyo.Reals)
57
+ m.unserved_mw = pyo.Var(m.BUS, m.SNAP, within=pyo.NonNegativeReals)
58
+
59
+ def gen_limit_rule(m, g, s):
60
+ return m.gen_mw[g, s] <= gens[g].capacity_mw
61
+ m.gen_limit = pyo.Constraint(m.GEN, m.SNAP, rule=gen_limit_rule)
62
+
63
+ def slack_rule(m, s):
64
+ return m.angle[slack_bus, s] == 0
65
+ m.slack_angle = pyo.Constraint(m.SNAP, rule=slack_rule)
66
+
67
+ def exist_flow_eq_rule(m, l, s):
68
+ ln = existing[l]
69
+ return m.flow[l, s] == BASE_MVA * (m.angle[ln.from_bus, s] - m.angle[ln.to_bus, s]) / ln.reactance_pu
70
+ m.exist_flow_eq = pyo.Constraint(m.EXISTING, m.SNAP, rule=exist_flow_eq_rule)
71
+
72
+ def exist_upper_rule(m, l, s):
73
+ return m.flow[l, s] <= existing[l].capacity_mw
74
+ m.exist_upper = pyo.Constraint(m.EXISTING, m.SNAP, rule=exist_upper_rule)
75
+
76
+ def exist_lower_rule(m, l, s):
77
+ return m.flow[l, s] >= -existing[l].capacity_mw
78
+ m.exist_lower = pyo.Constraint(m.EXISTING, m.SNAP, rule=exist_lower_rule)
79
+
80
+ def cand_upper_bigM_rule(m, l, s):
81
+ ln = candidates[l]
82
+ phys = BASE_MVA * (m.angle[ln.from_bus, s] - m.angle[ln.to_bus, s]) / ln.reactance_pu
83
+ return m.flow[l, s] - phys <= BIG_M * (1 - m.build[l])
84
+ m.cand_upper_bigM = pyo.Constraint(m.CANDIDATE, m.SNAP, rule=cand_upper_bigM_rule)
85
+
86
+ def cand_lower_bigM_rule(m, l, s):
87
+ ln = candidates[l]
88
+ phys = BASE_MVA * (m.angle[ln.from_bus, s] - m.angle[ln.to_bus, s]) / ln.reactance_pu
89
+ return m.flow[l, s] - phys >= -BIG_M * (1 - m.build[l])
90
+ m.cand_lower_bigM = pyo.Constraint(m.CANDIDATE, m.SNAP, rule=cand_lower_bigM_rule)
91
+
92
+ def cand_cap_upper_rule(m, l, s):
93
+ return m.flow[l, s] <= candidates[l].capacity_mw * m.build[l]
94
+ m.cand_cap_upper = pyo.Constraint(m.CANDIDATE, m.SNAP, rule=cand_cap_upper_rule)
95
+
96
+ def cand_cap_lower_rule(m, l, s):
97
+ return m.flow[l, s] >= -candidates[l].capacity_mw * m.build[l]
98
+ m.cand_cap_lower = pyo.Constraint(m.CANDIDATE, m.SNAP, rule=cand_cap_lower_rule)
99
+
100
+ def balance_rule(m, b, s):
101
+ gen_at_bus = sum(m.gen_mw[g, s] for g in gens if gens[g].bus_id == b)
102
+ inflow = sum(m.flow[l, s] for l in all_lines if all_lines[l].to_bus == b) \
103
+ - sum(m.flow[l, s] for l in all_lines if all_lines[l].from_bus == b)
104
+ d = net.loads.get(s, {}).get(b, 0.0)
105
+ return gen_at_bus + inflow + m.unserved_mw[b, s] == d
106
+ m.balance = pyo.Constraint(m.BUS, m.SNAP, rule=balance_rule)
107
+
108
+ def obj_rule(m):
109
+ invest_cost = sum(m.build[l] * candidates[l].cost_million_usd * 1e6 for l in m.CANDIDATE)
110
+ op_cost = annualization_factor * sum(
111
+ m.gen_mw[g, s] * gens[g].marginal_cost_per_mwh for g in m.GEN for s in m.SNAP)
112
+ shed_cost = annualization_factor * sum(
113
+ m.unserved_mw[b, s] * VOLL for b in m.BUS for s in m.SNAP)
114
+ return invest_cost + op_cost + shed_cost
115
+ m.obj = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
116
+
117
+ return m
118
+
119
+
120
+ def solve_expansion(network, snapshots=None, annualization_factor=None,
121
+ solver_name=DEFAULT_SOLVER) -> ExpansionResult:
122
+ """
123
+ Solve the transmission expansion planning MILP: which candidate lines
124
+ to build to minimize capital + annualized operating/reliability cost.
125
+
126
+ annualization_factor: scales operating/shed cost (computed from your
127
+ sample snapshots) up to be comparable with one-time capital costs.
128
+ Defaults to 8760 / len(snapshots), i.e. treats your snapshots as a
129
+ representative sample standing in for a full year.
130
+ """
131
+ if snapshots is None:
132
+ snapshots = network.snapshots
133
+ if annualization_factor is None:
134
+ annualization_factor = 8760 / len(snapshots)
135
+
136
+ m = _build_tep_model(network, snapshots, annualization_factor)
137
+ solver = pyo.SolverFactory(solver_name)
138
+ result = solver.solve(m)
139
+ status = str(result.solver.termination_condition)
140
+
141
+ built = {l: bool(round(pyo.value(m.build[l]))) for l in m.CANDIDATE}
142
+ total_shed = sum(pyo.value(m.unserved_mw[b, s]) for b in m.BUS for s in m.SNAP)
143
+ invest = sum(pyo.value(m.build[l]) * network.candidate_lines()[l].cost_million_usd
144
+ for l in m.CANDIDATE)
145
+
146
+ return ExpansionResult(
147
+ status=status,
148
+ objective_usd=round(pyo.value(m.obj), 2),
149
+ lines_to_build=[l for l, b in built.items() if b],
150
+ build_decision=built,
151
+ total_capital_cost_million_usd=round(invest, 2),
152
+ total_unserved_mwh_sample=round(total_shed, 2),
153
+ annualization_factor=annualization_factor,
154
+ )