fpowerkit 0.1.3__tar.gz → 0.1.4__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.
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/PKG-INFO +1 -1
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/solbase.py +3 -2
- fpowerkit-0.1.4/fpowerkit/soldist.py +368 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit.egg-info/PKG-INFO +1 -1
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/setup.py +1 -1
- fpowerkit-0.1.3/fpowerkit/soldist.py +0 -257
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/LICENSE +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/README.md +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/__init__.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/bus.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/cases.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/ess.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/gen.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/grid.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/line.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/pvwind.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/soldss.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/solnt.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit/utils.py +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit.egg-info/SOURCES.txt +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit.egg-info/dependency_links.txt +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit.egg-info/requires.txt +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/fpowerkit.egg-info/top_level.txt +0 -0
- {fpowerkit-0.1.3 → fpowerkit-0.1.4}/setup.cfg +0 -0
|
@@ -8,8 +8,9 @@ class GridSolveResult(IntEnum):
|
|
|
8
8
|
'''Result of grid solving'''
|
|
9
9
|
Failed = 0
|
|
10
10
|
OK = 1
|
|
11
|
-
OKwithoutVICons = 2
|
|
12
|
-
SubOKwithoutVICons = 3
|
|
11
|
+
OKwithoutVICons = 2 # Deprecated
|
|
12
|
+
SubOKwithoutVICons = 3 # Deprecated
|
|
13
|
+
PartialOK = 4
|
|
13
14
|
|
|
14
15
|
|
|
15
16
|
class SolverBase(ABC):
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
from itertools import chain
|
|
2
|
+
from gurobipy import GRB, Constr, LinExpr, Model, Var
|
|
3
|
+
from gurobipy import quicksum as Qs
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional, Union
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from collections import deque
|
|
8
|
+
import warnings, math
|
|
9
|
+
from .solbase import *
|
|
10
|
+
|
|
11
|
+
VF = Union[Var, float]
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class LoadReduceModule:
|
|
15
|
+
'''Load Reduce module'''
|
|
16
|
+
Bus:BusID
|
|
17
|
+
Limit:TimeFunc
|
|
18
|
+
Reduction:FloatVar = None
|
|
19
|
+
|
|
20
|
+
class _Island:
|
|
21
|
+
def __init__(self, g:Grid, buses:Iterable[BusID], cutlines:set[LineID]):
|
|
22
|
+
self.grid = g
|
|
23
|
+
self.Buses:set[str] = set()
|
|
24
|
+
self.Gens:set[str] = set()
|
|
25
|
+
self.Lines:set[str] = set()
|
|
26
|
+
self.PVWs:set[str] = set()
|
|
27
|
+
self.ESSs:set[str] = set()
|
|
28
|
+
for b in buses:
|
|
29
|
+
self.Buses.add(b)
|
|
30
|
+
self.Gens.update(gen.ID for gen in g._gatb[b])
|
|
31
|
+
self.Lines.update(ln.ID for ln in g._ladjfb[b] if ln.ID not in cutlines)
|
|
32
|
+
self.Lines.update(ln.ID for ln in g._ladjtb[b] if ln.ID not in cutlines)
|
|
33
|
+
self.PVWs.update(p.ID for p in g._patb[b])
|
|
34
|
+
self.ESSs.update(e.ID for e in g._eatb[b])
|
|
35
|
+
|
|
36
|
+
def __repr__(self):
|
|
37
|
+
return f"Island: {self.Buses}\nGens: {self.Gens}\nLines: {self.Lines}\nPVWs: {self.PVWs}\nESSs: {self.ESSs}"
|
|
38
|
+
|
|
39
|
+
def __str__(self):
|
|
40
|
+
return self.__repr__()
|
|
41
|
+
|
|
42
|
+
def BusItems(self):
|
|
43
|
+
for b in self.Buses:
|
|
44
|
+
yield b, self.grid.Bus(b)
|
|
45
|
+
|
|
46
|
+
def GenItems(self):
|
|
47
|
+
for g in self.Gens:
|
|
48
|
+
yield g, self.grid.Gen(g)
|
|
49
|
+
|
|
50
|
+
def LineItems(self):
|
|
51
|
+
for l in self.Lines:
|
|
52
|
+
yield l, self.grid.Line(l)
|
|
53
|
+
|
|
54
|
+
def PVWItems(self):
|
|
55
|
+
for p in self.PVWs:
|
|
56
|
+
yield p, self.grid.PVWind(p)
|
|
57
|
+
|
|
58
|
+
def ESSItems(self):
|
|
59
|
+
for e in self.ESSs:
|
|
60
|
+
yield e, self.grid.ESS(e)
|
|
61
|
+
|
|
62
|
+
class IslandResult(IntEnum):
|
|
63
|
+
Undefined = -1
|
|
64
|
+
OK = 0 # The island is solved without overflow
|
|
65
|
+
OverFlow = 1 # The island is solved but overflow
|
|
66
|
+
Failed = 2 # No island is solved
|
|
67
|
+
|
|
68
|
+
class DistFlowSolver(SolverBase):
|
|
69
|
+
'''DistFlow solver'''
|
|
70
|
+
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, /, *, mlrp:float = 0.5):
|
|
71
|
+
'''
|
|
72
|
+
Initialize
|
|
73
|
+
grid: Grid object
|
|
74
|
+
default_saveto: Default path to save the results
|
|
75
|
+
mlrp: Maximum proportion of load reduction
|
|
76
|
+
'''
|
|
77
|
+
super().__init__(grid, eps, default_saveto)
|
|
78
|
+
self._decb:dict[BusID, LoadReduceModule] = {}
|
|
79
|
+
self.C = 1e9
|
|
80
|
+
self._mlrp = mlrp
|
|
81
|
+
self._oflines:set[LineID] = set()
|
|
82
|
+
self._ofbuses:set[BusID] = set()
|
|
83
|
+
self.UpdateGrid()
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def OverflowLines(self):
|
|
87
|
+
return self._oflines
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def OverflowBuses(self):
|
|
91
|
+
return self._ofbuses
|
|
92
|
+
|
|
93
|
+
def UpdateGrid(self, cut_overflow_lines:bool = False):
|
|
94
|
+
self._islands = tuple(
|
|
95
|
+
_Island(self.grid, il, self._oflines) for il in self.__detect_islands(cut_overflow_lines)
|
|
96
|
+
)
|
|
97
|
+
self._island_res = [(IslandResult.Undefined, -1.0) for _ in range(len(self._islands))]
|
|
98
|
+
|
|
99
|
+
def __detect_islands(self, cutofl:bool):
|
|
100
|
+
'''Detect islands'''
|
|
101
|
+
q:deque[BusID] = deque()
|
|
102
|
+
visited:set[BusID] = set()
|
|
103
|
+
islands:list[set[BusID]] = []
|
|
104
|
+
for bus in self.grid.BusNames:
|
|
105
|
+
if bus in visited: continue
|
|
106
|
+
q.append(bus)
|
|
107
|
+
island:set[BusID] = set()
|
|
108
|
+
while len(q) > 0:
|
|
109
|
+
b = q.popleft()
|
|
110
|
+
if b in visited: continue
|
|
111
|
+
visited.add(b)
|
|
112
|
+
island.add(b)
|
|
113
|
+
for line in self.grid._ladjfb[b]:
|
|
114
|
+
if cutofl and line.ID in self._oflines: continue
|
|
115
|
+
if line._tBus in visited: continue
|
|
116
|
+
q.append(line._tBus)
|
|
117
|
+
for line in self.grid._ladjtb[b]:
|
|
118
|
+
if cutofl and line.ID in self._oflines: continue
|
|
119
|
+
if line._fBus in visited: continue
|
|
120
|
+
q.append(line._fBus)
|
|
121
|
+
islands.append(island)
|
|
122
|
+
return islands
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def Islands(self):
|
|
126
|
+
return self._islands
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def IslandResults(self):
|
|
130
|
+
return self._island_res
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def MLRP(self):
|
|
134
|
+
'''Get the maximum load reduction proportion'''
|
|
135
|
+
return self._mlrp
|
|
136
|
+
@MLRP.setter
|
|
137
|
+
def MLRP(self, v:float):
|
|
138
|
+
'''Set the maximum load reduction proportion'''
|
|
139
|
+
if v < 0 or v > 1:
|
|
140
|
+
raise ValueError("Invalid maximum load reduction proportion")
|
|
141
|
+
self._mlrp = v
|
|
142
|
+
|
|
143
|
+
def AddReduce(self, bus:BusID, limit:TimeFunc, reduction:Optional[FloatVar] = None):
|
|
144
|
+
'''Add a load reduction module'''
|
|
145
|
+
self._decb[bus] = LoadReduceModule(bus, limit, reduction)
|
|
146
|
+
|
|
147
|
+
def RemoveReduce(self, bus:BusID):
|
|
148
|
+
'''Remove a load reduction module'''
|
|
149
|
+
if bus in self._decb:
|
|
150
|
+
del self._decb[bus]
|
|
151
|
+
|
|
152
|
+
def GetReduce(self, bus:BusID) -> LoadReduceModule:
|
|
153
|
+
'''Get the load reduction module'''
|
|
154
|
+
return self._decb[bus]
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def DecBuses(self):
|
|
158
|
+
return self._decb
|
|
159
|
+
|
|
160
|
+
def solve(self, _t: int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
|
|
161
|
+
'''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
|
|
162
|
+
allOK = True
|
|
163
|
+
allFail = True
|
|
164
|
+
val = 0
|
|
165
|
+
for i, il in enumerate(self._islands):
|
|
166
|
+
self._island_res[i] = self.__solve(_t, il, timeout_s)
|
|
167
|
+
if self._island_res[i][0] != IslandResult.Failed:
|
|
168
|
+
allFail = False
|
|
169
|
+
val += self._island_res[i][1]
|
|
170
|
+
if self._island_res[i][0] != IslandResult.OK: allOK = False
|
|
171
|
+
if allOK:
|
|
172
|
+
return GridSolveResult.OK, val
|
|
173
|
+
elif allFail:
|
|
174
|
+
print(f"Failed to solve at time {_t}")
|
|
175
|
+
if self.saveto != "":
|
|
176
|
+
p = Path(self.saveto)
|
|
177
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
178
|
+
self.grid.savePQofBus(str(p/f"{_t}_load.csv"), _t)
|
|
179
|
+
return GridSolveResult.Failed, val
|
|
180
|
+
else:
|
|
181
|
+
return GridSolveResult.PartialOK, val
|
|
182
|
+
|
|
183
|
+
def __solve(self, _t: int, island:_Island, timeout_s:float) -> 'tuple[IslandResult, float]':
|
|
184
|
+
model = Model("model")
|
|
185
|
+
|
|
186
|
+
''' ---------Variables----------
|
|
187
|
+
pg0[k]: Generator active power
|
|
188
|
+
qg0[k]: Generator reactive power
|
|
189
|
+
pvwp[k]: PVWind active power
|
|
190
|
+
--> pg[j]: Active power of all generators at the bus
|
|
191
|
+
--> qg[j]: Reactive power of all generators at the bus
|
|
192
|
+
v[j]: Bus voltage ** 2
|
|
193
|
+
l[i,j]: Line current ** 2
|
|
194
|
+
P[i,j]: Line active power
|
|
195
|
+
Q[i,j]: Line reactive power
|
|
196
|
+
'''
|
|
197
|
+
# Create GEN vars
|
|
198
|
+
pg0: dict[str, VF] = {}
|
|
199
|
+
qg0: dict[str, VF] = {}
|
|
200
|
+
for gID, g in island.GenItems():
|
|
201
|
+
if g.FixedP:
|
|
202
|
+
assert g.P is not None
|
|
203
|
+
pg0[gID] = g.P(_t) if isinstance(g.P, TimeFunc) else g.P
|
|
204
|
+
elif g.Pmin is not None and g.Pmax is not None:
|
|
205
|
+
pg0[gID] = model.addVar(name=f"pg_{gID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t))
|
|
206
|
+
else:
|
|
207
|
+
raise ValueError(f"Generator {gID} provides neither P or (pmin, pmax)")
|
|
208
|
+
if g.FixedQ:
|
|
209
|
+
assert g.Q is not None
|
|
210
|
+
qg0[gID] = g.Q(_t) if isinstance(g.Q, TimeFunc) else g.Q
|
|
211
|
+
elif g.Qmin is not None and g.Qmax is not None:
|
|
212
|
+
qg0[gID] = model.addVar(name=f"qg_{gID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t))
|
|
213
|
+
else:
|
|
214
|
+
raise ValueError(f"Generator {g.ID} provides neither Q or (qmin, qmax)")
|
|
215
|
+
|
|
216
|
+
pvwp: dict[str, Var] = {pID: model.addVar(
|
|
217
|
+
name=f"pvw_{pID}", vtype='C', lb=0, ub=p.P(_t)
|
|
218
|
+
) for pID, p in island.PVWItems()}
|
|
219
|
+
pvwq: dict[str, Var] = {pID: model.addVar(
|
|
220
|
+
name=f"pvw_{pID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY
|
|
221
|
+
) for pID in island.PVWs}
|
|
222
|
+
|
|
223
|
+
# Bind GEN vars to Bus
|
|
224
|
+
pg: dict[str, list[VF]] = {b: [] for b in island.Buses}
|
|
225
|
+
qg: dict[str, list[VF]] = {b: [] for b in island.Buses}
|
|
226
|
+
pd: dict[str, float] = {bID: b.Pd(_t) for bID, b in island.BusItems()}
|
|
227
|
+
qd: dict[str, float] = {bID: b.Qd(_t) for bID, b in island.BusItems()}
|
|
228
|
+
for gID, g in island.GenItems():
|
|
229
|
+
pg[g.BusID].append(pg0[gID])
|
|
230
|
+
qg[g.BusID].append(qg0[gID])
|
|
231
|
+
for pID, p in island.PVWItems():
|
|
232
|
+
pg[p.BusID].append(pvwp[pID])
|
|
233
|
+
qg[p.BusID].append(pvwq[pID])
|
|
234
|
+
for eID, e in island.ESSItems():
|
|
235
|
+
p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
|
|
236
|
+
e.P = p
|
|
237
|
+
if p > 0:
|
|
238
|
+
pg[e.BusID].append(p)
|
|
239
|
+
qg[e.BusID].append(q)
|
|
240
|
+
elif p < 0:
|
|
241
|
+
pd[e.BusID] -= p
|
|
242
|
+
qd[e.BusID] -= q
|
|
243
|
+
|
|
244
|
+
# Create BUS vars
|
|
245
|
+
v = {bID: model.addVar(name=f"v_{bID}", vtype='C') for bID in island.Buses}
|
|
246
|
+
dvmin:dict[str, Var] = {}
|
|
247
|
+
dvmax:dict[str, Var] = {}
|
|
248
|
+
for bid, b in island.BusItems():
|
|
249
|
+
if b.FixedV:
|
|
250
|
+
assert b.V is not None, f"Bus {bid} has fixed voltage but not set"
|
|
251
|
+
model.addConstr(v[bid] == b.V ** 2)
|
|
252
|
+
else:
|
|
253
|
+
dvmin[bid] = model.addVar(name=f"dvmin_{bid}", vtype='C', lb=0)
|
|
254
|
+
dvmax[bid] = model.addVar(name=f"dvmax_{bid}", vtype='C', lb=0)
|
|
255
|
+
model.addConstr(v[bid] >= b.MinV ** 2 - dvmin[bid])
|
|
256
|
+
model.addConstr(v[bid] <= b.MaxV ** 2 + dvmax[bid])
|
|
257
|
+
|
|
258
|
+
# Create Line vars
|
|
259
|
+
dlmax:dict[str, Var] = {}
|
|
260
|
+
l = {lID: model.addVar(name=f"l_{lID}", vtype='C', lb=0) for lID in island.Lines}
|
|
261
|
+
for lID, ln in island.LineItems():
|
|
262
|
+
dlmax[lID] = model.addVar(name=f"dlmax_{lID}", vtype='C', lb=0)
|
|
263
|
+
model.addConstr(l[lID] <= (ln.max_I/island.grid.Ib) ** 2 + dlmax[lID])
|
|
264
|
+
|
|
265
|
+
P = {lID: model.addVar(name=f"P_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
|
|
266
|
+
island.Lines}
|
|
267
|
+
Q = {lID: model.addVar(name=f"Q_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
|
|
268
|
+
island.Lines}
|
|
269
|
+
|
|
270
|
+
Pdec:dict[BusID, Var] = {bus: model.addVar(name=f"Pdec_{bus}", vtype='C',
|
|
271
|
+
lb=0, ub=lim.Limit(_t) * self._mlrp) for bus, lim in self._decb.items()}
|
|
272
|
+
|
|
273
|
+
# ----------Constraints-----------
|
|
274
|
+
Pcons: dict[str, Constr] = {}
|
|
275
|
+
Qcons: dict[str, Constr] = {}
|
|
276
|
+
|
|
277
|
+
for j, bus in island.BusItems():
|
|
278
|
+
flow_in = island.grid.LinesOfTBus(j)
|
|
279
|
+
flow_out = island.grid.LinesOfFBus(j)
|
|
280
|
+
dec = Pdec[j] if j in Pdec else 0
|
|
281
|
+
Pcons[j] = model.addConstr(
|
|
282
|
+
Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(pg[j]) == Qs(
|
|
283
|
+
P[ln.ID] for ln in flow_out if ln.ID in island.Lines) + pd[j] - dec, f"Pcons_{j}")
|
|
284
|
+
Qcons[j] = model.addConstr(
|
|
285
|
+
Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(qg[j]) == Qs(
|
|
286
|
+
Q[ln.ID] for ln in flow_out if ln.ID in island.Lines) + qd[j], f"Qcons_{j}")
|
|
287
|
+
|
|
288
|
+
for lid, line in island.LineItems():
|
|
289
|
+
i, j = line.pair
|
|
290
|
+
lid = line.ID
|
|
291
|
+
model.addConstr(
|
|
292
|
+
v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
|
|
293
|
+
f"ΔU2_cons_{lid}")
|
|
294
|
+
model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
|
|
295
|
+
|
|
296
|
+
for pID, p in island.PVWItems():
|
|
297
|
+
model.addConstr(pvwp[pID] * math.sqrt(1 - p.PF**2) == pvwq[pID])
|
|
298
|
+
|
|
299
|
+
decs = self.C * (Qs(Pdec.values()) + Qs(dvmin.values()) + Qs(dvmax.values()) + Qs(dlmax.values()))
|
|
300
|
+
crpe = Qs(p.CC*(p.P(_t)-pvwp[pID]) for pID, p in island.PVWItems())
|
|
301
|
+
goal = Qs(g.CostA(_t) * pg0[gID] ** 2 + g.CostB(_t) * pg0[gID] + g.CostC(_t) for gID, g in island.GenItems())
|
|
302
|
+
|
|
303
|
+
model.setObjective(decs + goal + crpe, GRB.MINIMIZE)
|
|
304
|
+
model.setParam(GRB.Param.OutputFlag, 0)
|
|
305
|
+
model.setParam(GRB.Param.QCPDual, 1)
|
|
306
|
+
model.setParam(GRB.Param.TimeLimit, timeout_s)
|
|
307
|
+
model.setParam(GRB.Param.OptimalityTol, 1e-6)
|
|
308
|
+
model.update()
|
|
309
|
+
model.optimize()
|
|
310
|
+
|
|
311
|
+
if model.Status != GRB.Status.OPTIMAL and model.Status != GRB.Status.SUBOPTIMAL:
|
|
312
|
+
for bID, bus in island.BusItems():
|
|
313
|
+
bus._v = bus.ShadowPrice = 0
|
|
314
|
+
for pID, p in island.PVWItems():
|
|
315
|
+
p._pr = p._qr = p._cr = 0
|
|
316
|
+
for lid, line in island.LineItems():
|
|
317
|
+
line.I = line.P = line.Q = 0
|
|
318
|
+
for j, gen in island.GenItems():
|
|
319
|
+
if not gen.FixedP: gen._p = 0
|
|
320
|
+
if not gen.FixedQ: gen._q = 0
|
|
321
|
+
for eID, e in island.ESSItems():
|
|
322
|
+
e.P = 0
|
|
323
|
+
return IslandResult.Failed, -1
|
|
324
|
+
|
|
325
|
+
for j, bus in island.BusItems():
|
|
326
|
+
j = bus.ID
|
|
327
|
+
bus._v = v[j].X ** 0.5
|
|
328
|
+
try:
|
|
329
|
+
sp = Pcons[j].Pi
|
|
330
|
+
except:
|
|
331
|
+
sp = None if not self.grid._holdShadowPrice else bus.ShadowPrice
|
|
332
|
+
bus.ShadowPrice = sp
|
|
333
|
+
|
|
334
|
+
for lid, line in island.LineItems():
|
|
335
|
+
line.I = l[lid].X ** 0.5
|
|
336
|
+
line.P = P[lid].X
|
|
337
|
+
line.Q = Q[lid].X
|
|
338
|
+
|
|
339
|
+
for j, gen in island.GenItems():
|
|
340
|
+
p = pg0[j]
|
|
341
|
+
if isinstance(p, Var): gen._p = p.X
|
|
342
|
+
q = qg0[j]
|
|
343
|
+
if isinstance(q, Var): gen._q = q.X
|
|
344
|
+
|
|
345
|
+
for pID, p in island.PVWItems():
|
|
346
|
+
p._pr = pvwp[pID].X
|
|
347
|
+
p._qr = pvwq[pID].X
|
|
348
|
+
pgen = p.P(_t)
|
|
349
|
+
p._cr = 1 - p._pr / pgen if pgen > 0 else 0
|
|
350
|
+
|
|
351
|
+
overflow = False
|
|
352
|
+
self._ofbuses.clear()
|
|
353
|
+
for bID, bv in chain(dvmax.items(), dvmin.items()):
|
|
354
|
+
if bv.X > 1e-6:
|
|
355
|
+
overflow = True
|
|
356
|
+
self._ofbuses.add(bID)
|
|
357
|
+
|
|
358
|
+
self._oflines.clear()
|
|
359
|
+
for lID, lv in dlmax.items():
|
|
360
|
+
if lv.X > 1e-6:
|
|
361
|
+
overflow = True
|
|
362
|
+
self._oflines.add(lID)
|
|
363
|
+
|
|
364
|
+
for bus, lim in self._decb.items():
|
|
365
|
+
lim.Reduction = Pdec[bus].X
|
|
366
|
+
if lim.Reduction < 1e-8: lim.Reduction = 0
|
|
367
|
+
|
|
368
|
+
return IslandResult.OverFlow if overflow else IslandResult.OK, goal.getValue()
|
|
@@ -1,257 +0,0 @@
|
|
|
1
|
-
from gurobipy import GRB, Constr, LinExpr, Model, Var
|
|
2
|
-
from gurobipy import quicksum as Qs
|
|
3
|
-
from pathlib import Path
|
|
4
|
-
from typing import Optional, Union
|
|
5
|
-
from dataclasses import dataclass
|
|
6
|
-
import warnings, math
|
|
7
|
-
from .solbase import *
|
|
8
|
-
|
|
9
|
-
VF = Union[Var, float]
|
|
10
|
-
|
|
11
|
-
@dataclass
|
|
12
|
-
class LoadReduceModule:
|
|
13
|
-
'''Load Reduce module'''
|
|
14
|
-
Bus:BusID
|
|
15
|
-
Limit:TimeFunc
|
|
16
|
-
Reduction:FloatVar = None
|
|
17
|
-
|
|
18
|
-
class DistFlowSolver(SolverBase):
|
|
19
|
-
'''DistFlow solver'''
|
|
20
|
-
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, /, *, mlrp:float = 0.5):
|
|
21
|
-
'''
|
|
22
|
-
Initialize
|
|
23
|
-
grid: Grid object
|
|
24
|
-
default_saveto: Default path to save the results
|
|
25
|
-
mlrp: Maximum proportion of load reduction
|
|
26
|
-
'''
|
|
27
|
-
super().__init__(grid, eps, default_saveto)
|
|
28
|
-
self._decb:dict[BusID, LoadReduceModule] = {}
|
|
29
|
-
self.C = 1e9
|
|
30
|
-
self._mlrp = mlrp
|
|
31
|
-
|
|
32
|
-
@property
|
|
33
|
-
def MLRP(self):
|
|
34
|
-
'''Get the maximum load reduction proportion'''
|
|
35
|
-
return self._mlrp
|
|
36
|
-
@MLRP.setter
|
|
37
|
-
def MLRP(self, v:float):
|
|
38
|
-
'''Set the maximum load reduction proportion'''
|
|
39
|
-
if v < 0 or v > 1:
|
|
40
|
-
raise ValueError("Invalid maximum load reduction proportion")
|
|
41
|
-
self._mlrp = v
|
|
42
|
-
|
|
43
|
-
def AddReduce(self, bus:BusID, limit:TimeFunc, reduction:Optional[FloatVar] = None):
|
|
44
|
-
'''Add a load reduction module'''
|
|
45
|
-
self._decb[bus] = LoadReduceModule(bus, limit, reduction)
|
|
46
|
-
|
|
47
|
-
def RemoveReduce(self, bus:BusID):
|
|
48
|
-
'''Remove a load reduction module'''
|
|
49
|
-
if bus in self._decb:
|
|
50
|
-
del self._decb[bus]
|
|
51
|
-
|
|
52
|
-
def GetReduce(self, bus:BusID) -> LoadReduceModule:
|
|
53
|
-
'''Get the load reduction module'''
|
|
54
|
-
return self._decb[bus]
|
|
55
|
-
|
|
56
|
-
@property
|
|
57
|
-
def DecBuses(self):
|
|
58
|
-
return self._decb
|
|
59
|
-
|
|
60
|
-
def solve(self, _t: int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
|
|
61
|
-
'''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
|
|
62
|
-
ok, val = self.__solve(_t, False, False, timeout_s)
|
|
63
|
-
if ok == GRB.Status.OPTIMAL:
|
|
64
|
-
return GridSolveResult.OK, val
|
|
65
|
-
else:
|
|
66
|
-
ok, val = self.__solve(_t, True, True, timeout_s)
|
|
67
|
-
if ok == GRB.Status.OPTIMAL:
|
|
68
|
-
return GridSolveResult.OKwithoutVICons, val
|
|
69
|
-
elif ok == GRB.Status.SUBOPTIMAL:
|
|
70
|
-
return GridSolveResult.SubOKwithoutVICons, val
|
|
71
|
-
else:
|
|
72
|
-
print(f"Failed to solve at time {_t}: {ok}")
|
|
73
|
-
if self.saveto != "":
|
|
74
|
-
p = Path(self.saveto)
|
|
75
|
-
p.mkdir(parents=True, exist_ok=True)
|
|
76
|
-
self.grid.savePQofBus(str(p/f"{_t}_load.csv"), _t)
|
|
77
|
-
return GridSolveResult.Failed, val
|
|
78
|
-
|
|
79
|
-
def __solve(self, _t: int, relax_V: bool, relax_I: bool, timeout_s:float) -> 'tuple[int, float]':
|
|
80
|
-
model = Model("model")
|
|
81
|
-
|
|
82
|
-
''' ---------Variables----------
|
|
83
|
-
pg0[k]: Generator active power
|
|
84
|
-
qg0[k]: Generator reactive power
|
|
85
|
-
pvwp[k]: PVWind active power
|
|
86
|
-
--> pg[j]: Active power of all generators at the bus
|
|
87
|
-
--> qg[j]: Reactive power of all generators at the bus
|
|
88
|
-
v[j]: Bus voltage ** 2
|
|
89
|
-
l[i,j]: Line current ** 2
|
|
90
|
-
P[i,j]: Line active power
|
|
91
|
-
Q[i,j]: Line reactive power
|
|
92
|
-
'''
|
|
93
|
-
|
|
94
|
-
# Create GEN vars
|
|
95
|
-
pg0: dict[str, VF] = {}
|
|
96
|
-
qg0: dict[str, VF] = {}
|
|
97
|
-
for g in self.grid.Gens:
|
|
98
|
-
if g.FixedP:
|
|
99
|
-
assert g.P is not None
|
|
100
|
-
pg0[g.ID] = g.P(_t) if isinstance(g.P, TimeFunc) else g.P
|
|
101
|
-
elif g.Pmin is not None and g.Pmax is not None:
|
|
102
|
-
pg0[g.ID] = model.addVar(name=f"pg_{g.ID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t))
|
|
103
|
-
else:
|
|
104
|
-
raise ValueError(f"Generator {g.ID} provides neither P or (pmin, pmax)")
|
|
105
|
-
if g.FixedQ:
|
|
106
|
-
assert g.Q is not None
|
|
107
|
-
qg0[g.ID] = g.Q(_t) if isinstance(g.Q, TimeFunc) else g.Q
|
|
108
|
-
elif g.Qmin is not None and g.Qmax is not None:
|
|
109
|
-
qg0[g.ID] = model.addVar(name=f"qg_{g.ID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t))
|
|
110
|
-
else:
|
|
111
|
-
raise ValueError(f"Generator {g.ID} provides neither Q or (qmin, qmax)")
|
|
112
|
-
|
|
113
|
-
pvwp: dict[str, Var] = {p.ID: model.addVar(
|
|
114
|
-
name=f"pvw_{p.ID}", vtype='C', lb=0, ub=p.P(_t)
|
|
115
|
-
) for p in self.grid.PVWinds}
|
|
116
|
-
pvwq: dict[str, Var] = {p.ID: model.addVar(
|
|
117
|
-
name=f"pvw_{p.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY
|
|
118
|
-
) for p in self.grid.PVWinds}
|
|
119
|
-
|
|
120
|
-
# Bind GEN vars to Bus
|
|
121
|
-
pg: dict[str, list[VF]] = {bus.ID: [] for bus in self.grid.Buses}
|
|
122
|
-
qg: dict[str, list[VF]] = {bus.ID: [] for bus in self.grid.Buses}
|
|
123
|
-
pd: dict[str, float] = {bus.ID: bus.Pd(_t) for bus in self.grid.Buses}
|
|
124
|
-
qd: dict[str, float] = {bus.ID: bus.Qd(_t) for bus in self.grid.Buses}
|
|
125
|
-
for g in self.grid.Gens:
|
|
126
|
-
pg[g.BusID].append(pg0[g.ID])
|
|
127
|
-
qg[g.BusID].append(qg0[g.ID])
|
|
128
|
-
for p in self.grid.PVWinds:
|
|
129
|
-
pg[p.BusID].append(pvwp[p.ID])
|
|
130
|
-
qg[p.BusID].append(pvwq[p.ID])
|
|
131
|
-
for e in self.grid.ESSs:
|
|
132
|
-
p, q = e.GetLoad(_t, self.grid.ChargePrice(_t), self.grid.DischargePrice(_t))
|
|
133
|
-
e.P = p
|
|
134
|
-
if p > 0:
|
|
135
|
-
pg[e.BusID].append(p)
|
|
136
|
-
qg[e.BusID].append(q)
|
|
137
|
-
elif p < 0:
|
|
138
|
-
pd[e.BusID] -= p
|
|
139
|
-
qd[e.BusID] -= q
|
|
140
|
-
|
|
141
|
-
# Create BUS vars
|
|
142
|
-
has_slack = 0
|
|
143
|
-
v = {bus.ID: model.addVar(name=f"v_{bus.ID}", vtype='C') for bus in self.grid.Buses}
|
|
144
|
-
dvmin = {}
|
|
145
|
-
dvmax = {}
|
|
146
|
-
for bus in self.grid.Buses:
|
|
147
|
-
bid = bus._id
|
|
148
|
-
if bus.FixedV:
|
|
149
|
-
assert bus.V is not None, f"Bus {bid} has fixed voltage but not set"
|
|
150
|
-
model.addConstr(v[bid] == bus.V ** 2)
|
|
151
|
-
has_slack += 1
|
|
152
|
-
elif relax_V:
|
|
153
|
-
dvmin[bid] = model.addVar(name=f"dvmin_{bid}", vtype='C', lb=0)
|
|
154
|
-
dvmax[bid] = model.addVar(name=f"dvmax_{bid}", vtype='C', lb=0)
|
|
155
|
-
model.addConstr(v[bid] >= bus.MinV ** 2 - dvmin[bid])
|
|
156
|
-
model.addConstr(v[bid] <= bus.MaxV ** 2 + dvmax[bid])
|
|
157
|
-
else:
|
|
158
|
-
v[bid].LB = bus.MinV ** 2
|
|
159
|
-
v[bid].UB = bus.MaxV ** 2
|
|
160
|
-
|
|
161
|
-
if has_slack == 0:
|
|
162
|
-
raise ValueError("No slack bus found.")
|
|
163
|
-
elif has_slack > 1:
|
|
164
|
-
warnings.warn("More than 1 slack bus. May lead to unfeasible result.")
|
|
165
|
-
|
|
166
|
-
# Create Line vars
|
|
167
|
-
dlmax = {}
|
|
168
|
-
if relax_I:
|
|
169
|
-
l = {line.ID: model.addVar(name=f"l_{line.ID}", vtype='C', lb=0) for line in self.grid.Lines}
|
|
170
|
-
for line in self.grid.Lines:
|
|
171
|
-
dlmax[line.ID] = model.addVar(name=f"dlmax_{line.ID}", vtype='C', lb=0)
|
|
172
|
-
model.addConstr(l[line.ID] <= (line.max_I/self.grid.Ib) ** 2 + dlmax[line.ID])
|
|
173
|
-
else:
|
|
174
|
-
l = {line.ID: model.addVar(
|
|
175
|
-
name=f"l_{line.ID}", vtype='C', lb=0, ub=(line.max_I/self.grid.Ib) ** 2
|
|
176
|
-
) for line in self.grid.Lines}
|
|
177
|
-
|
|
178
|
-
P = {line.ID: model.addVar(name=f"P_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
179
|
-
self.grid.Lines}
|
|
180
|
-
Q = {line.ID: model.addVar(name=f"Q_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
181
|
-
self.grid.Lines}
|
|
182
|
-
|
|
183
|
-
Pdec = {bus: model.addVar(name=f"Pdec_{bus}", vtype='C',
|
|
184
|
-
lb=0, ub=lim.Limit(_t) * self._mlrp) for bus,lim in self._decb.items()}
|
|
185
|
-
|
|
186
|
-
# ----------Constraints-----------
|
|
187
|
-
Pcons: dict[str, Constr] = {}
|
|
188
|
-
Qcons: dict[str, Constr] = {}
|
|
189
|
-
|
|
190
|
-
for bus in self.grid.Buses:
|
|
191
|
-
j = bus.ID
|
|
192
|
-
flow_in = self.grid.LinesOfTBus(j)
|
|
193
|
-
flow_out = self.grid.LinesOfFBus(j)
|
|
194
|
-
dec = Pdec[j] if j in self._decb else 0
|
|
195
|
-
Pcons[j] = model.addConstr(Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in) + Qs(pg[j]) == Qs(
|
|
196
|
-
P[ln.ID] for ln in flow_out) + pd[j] - dec, f"Pcons_{j}")
|
|
197
|
-
Qcons[j] = model.addConstr(Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in) + Qs(qg[j]) == Qs(
|
|
198
|
-
Q[ln.ID] for ln in flow_out) + qd[j], f"Qcons_{j}")
|
|
199
|
-
|
|
200
|
-
for line in self.grid.Lines:
|
|
201
|
-
i, j = line.pair
|
|
202
|
-
lid = line.ID
|
|
203
|
-
model.addConstr(
|
|
204
|
-
v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
|
|
205
|
-
f"ΔU2_cons_{lid}")
|
|
206
|
-
model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
|
|
207
|
-
|
|
208
|
-
for p in self.grid.PVWinds:
|
|
209
|
-
model.addConstr(pvwp[p.ID] * math.sqrt(1 - p.PF**2) == pvwq[p.ID])
|
|
210
|
-
|
|
211
|
-
decs = self.C * (Qs(Pdec.values()) + Qs(dvmin.values()) + Qs(dvmax.values()) + Qs(dlmax.values()))
|
|
212
|
-
crpe = Qs(p.CC*(p.P(_t)-pvwp[p.ID]) for p in self.grid.PVWinds)
|
|
213
|
-
goal = Qs(g.CostA(_t) * pg0[g.ID] ** 2 + g.CostB(_t) * pg0[g.ID] + g.CostC(_t) for g in self.grid.Gens)
|
|
214
|
-
|
|
215
|
-
model.setObjective(decs + goal + crpe, GRB.MINIMIZE)
|
|
216
|
-
model.setParam(GRB.Param.OutputFlag, 0)
|
|
217
|
-
model.setParam(GRB.Param.QCPDual, 1)
|
|
218
|
-
model.setParam(GRB.Param.TimeLimit, timeout_s)
|
|
219
|
-
model.setParam(GRB.Param.OptimalityTol, 1e-6)
|
|
220
|
-
model.update()
|
|
221
|
-
model.optimize()
|
|
222
|
-
if model.Status != GRB.Status.OPTIMAL:
|
|
223
|
-
return model.Status, -1
|
|
224
|
-
|
|
225
|
-
for bus in self.grid.Buses:
|
|
226
|
-
j = bus.ID
|
|
227
|
-
bus.V = v[j].X ** 0.5
|
|
228
|
-
try:
|
|
229
|
-
sp = Pcons[j].Pi
|
|
230
|
-
except:
|
|
231
|
-
sp = None if not self.grid._holdShadowPrice else bus.ShadowPrice
|
|
232
|
-
bus.ShadowPrice = sp
|
|
233
|
-
|
|
234
|
-
for line in self.grid.Lines:
|
|
235
|
-
lid = line.ID
|
|
236
|
-
line.I = l[lid].X ** 0.5
|
|
237
|
-
line.P = P[lid].X
|
|
238
|
-
line.Q = Q[lid].X
|
|
239
|
-
|
|
240
|
-
for gen in self.grid.Gens:
|
|
241
|
-
j = gen.ID
|
|
242
|
-
p = pg0[j]
|
|
243
|
-
if isinstance(p, Var): gen._p = p.X
|
|
244
|
-
q = qg0[j]
|
|
245
|
-
if isinstance(q, Var): gen._q = q.X
|
|
246
|
-
|
|
247
|
-
for p in self.grid.PVWinds:
|
|
248
|
-
p._pr = pvwp[p.ID].X
|
|
249
|
-
p._qr = pvwq[p.ID].X
|
|
250
|
-
pgen = p.P(_t)
|
|
251
|
-
p._cr = 1 - p._pr / pgen if pgen > 0 else 0
|
|
252
|
-
|
|
253
|
-
for bus,lim in self._decb.items():
|
|
254
|
-
lim.Reduction = Pdec[bus].X
|
|
255
|
-
if lim.Reduction < 1e-8: lim.Reduction = 0
|
|
256
|
-
|
|
257
|
-
return model.Status, goal.getValue()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|