fpowerkit 0.1.3__tar.gz → 0.1.5__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.
Files changed (24) hide show
  1. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/PKG-INFO +1 -1
  2. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/README.md +2 -0
  3. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/solbase.py +5 -2
  4. fpowerkit-0.1.5/fpowerkit/soldist.py +389 -0
  5. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit.egg-info/PKG-INFO +1 -1
  6. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/setup.py +1 -1
  7. fpowerkit-0.1.3/fpowerkit/soldist.py +0 -257
  8. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/LICENSE +0 -0
  9. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/__init__.py +0 -0
  10. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/bus.py +0 -0
  11. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/cases.py +0 -0
  12. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/ess.py +0 -0
  13. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/gen.py +0 -0
  14. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/grid.py +0 -0
  15. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/line.py +0 -0
  16. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/pvwind.py +0 -0
  17. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/soldss.py +0 -0
  18. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/solnt.py +0 -0
  19. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit/utils.py +0 -0
  20. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit.egg-info/SOURCES.txt +0 -0
  21. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit.egg-info/dependency_links.txt +0 -0
  22. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit.egg-info/requires.txt +0 -0
  23. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/fpowerkit.egg-info/top_level.txt +0 -0
  24. {fpowerkit-0.1.3 → fpowerkit-0.1.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fpowerkit
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -1,6 +1,8 @@
1
1
  # FPowerKit 配电网运算组件
2
2
  **本仓库已上线PyPI**,您可以通过`pip install fpowerkit`直接以Python包的形式安装使用本仓库的代码!
3
3
 
4
+ 这个项目是[V2Sim](https://gitee.com/fmy_xfk/v2sim)的附属项目。V2Sim的论文请见arXiv: https://arxiv.org/abs/2412.09808
5
+
4
6
  IEEE33和IEEE69节点的配网数据从公开渠道收集。除配网数据以外,本仓库代码均遵循LGPL3.0协议使用。
5
7
 
6
8
  ## 简介
@@ -1,5 +1,6 @@
1
1
  from abc import ABC, abstractmethod
2
2
  from enum import IntEnum
3
+ from pathlib import Path
3
4
  from .grid import *
4
5
 
5
6
  DEFAULT_SAVETO = "./fpowerkit_logs/"
@@ -8,8 +9,9 @@ class GridSolveResult(IntEnum):
8
9
  '''Result of grid solving'''
9
10
  Failed = 0
10
11
  OK = 1
11
- OKwithoutVICons = 2
12
- SubOKwithoutVICons = 3
12
+ OKwithoutVICons = 2 # Deprecated
13
+ SubOKwithoutVICons = 3 # Deprecated
14
+ PartialOK = 4
13
15
 
14
16
 
15
17
  class SolverBase(ABC):
@@ -20,6 +22,7 @@ class SolverBase(ABC):
20
22
 
21
23
  def SetErrorSaveTo(self, path:str = DEFAULT_SAVETO):
22
24
  self.saveto = path
25
+ Path(path).mkdir(parents=True, exist_ok = True)
23
26
 
24
27
  @abstractmethod
25
28
  def solve(self, grid:Grid, _t:int, /, **kwargs):
@@ -0,0 +1,389 @@
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, /,
71
+ *, mlrp:float = 0.5, secondary_cost:bool = True):
72
+ '''
73
+ Initialize
74
+ grid: Grid object
75
+ default_saveto: Default path to save the results
76
+ mlrp: Maximum proportion of load reduction
77
+ secondary_cost: Whether to include the secondary cost.
78
+ If False, the cost is calculated as CostB * Pg + CostC;
79
+ If True, the cost is calculated as CostA * Pg^2 + CostB * Pg + CostC,
80
+ which is likely to induce numerical instability.
81
+ '''
82
+ super().__init__(grid, eps, default_saveto)
83
+ self._decb:dict[BusID, LoadReduceModule] = {}
84
+ self.C = 1e9
85
+ self._mlrp = mlrp
86
+ self._oflines:set[LineID] = set()
87
+ self._ofbuses:set[BusID] = set()
88
+ self._sec_cost = secondary_cost
89
+ self.UpdateGrid()
90
+
91
+ @property
92
+ def OverflowLines(self):
93
+ return self._oflines
94
+
95
+ @property
96
+ def OverflowBuses(self):
97
+ return self._ofbuses
98
+
99
+ def UpdateGrid(self, cut_overflow_lines:bool = False):
100
+ self._islands = tuple(
101
+ _Island(self.grid, il, self._oflines) for il in self.__detect_islands(cut_overflow_lines)
102
+ )
103
+ self._island_res = [(IslandResult.Undefined, -1.0) for _ in range(len(self._islands))]
104
+ self.__il_relax = [False] * len(self._islands)
105
+
106
+ def __detect_islands(self, cutofl:bool):
107
+ '''Detect islands'''
108
+ q:deque[BusID] = deque()
109
+ visited:set[BusID] = set()
110
+ islands:list[set[BusID]] = []
111
+ for bus in self.grid.BusNames:
112
+ if bus in visited: continue
113
+ q.append(bus)
114
+ island:set[BusID] = set()
115
+ while len(q) > 0:
116
+ b = q.popleft()
117
+ if b in visited: continue
118
+ visited.add(b)
119
+ island.add(b)
120
+ for line in self.grid._ladjfb[b]:
121
+ if cutofl and line.ID in self._oflines: continue
122
+ if line._tBus in visited: continue
123
+ q.append(line._tBus)
124
+ for line in self.grid._ladjtb[b]:
125
+ if cutofl and line.ID in self._oflines: continue
126
+ if line._fBus in visited: continue
127
+ q.append(line._fBus)
128
+ islands.append(island)
129
+ return islands
130
+
131
+ @property
132
+ def Islands(self):
133
+ return self._islands
134
+
135
+ @property
136
+ def IslandResults(self):
137
+ return self._island_res
138
+
139
+ @property
140
+ def MLRP(self):
141
+ '''Get the maximum load reduction proportion'''
142
+ return self._mlrp
143
+ @MLRP.setter
144
+ def MLRP(self, v:float):
145
+ '''Set the maximum load reduction proportion'''
146
+ if v < 0 or v > 1:
147
+ raise ValueError("Invalid maximum load reduction proportion")
148
+ self._mlrp = v
149
+
150
+ def AddReduce(self, bus:BusID, limit:TimeFunc, reduction:Optional[FloatVar] = None):
151
+ '''Add a load reduction module'''
152
+ self._decb[bus] = LoadReduceModule(bus, limit, reduction)
153
+
154
+ def RemoveReduce(self, bus:BusID):
155
+ '''Remove a load reduction module'''
156
+ if bus in self._decb:
157
+ del self._decb[bus]
158
+
159
+ def GetReduce(self, bus:BusID) -> LoadReduceModule:
160
+ '''Get the load reduction module'''
161
+ return self._decb[bus]
162
+
163
+ @property
164
+ def DecBuses(self):
165
+ return self._decb
166
+
167
+ def solve(self, _t: int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
168
+ '''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
169
+ allOK = True
170
+ allFail = True
171
+ val = 0
172
+ for i, il in enumerate(self._islands):
173
+ relax = self.__il_relax[i]
174
+ self._island_res[i] = self.__solve(_t, il, timeout_s, relax, relax)
175
+ if self._island_res[i][0] == IslandResult.Failed:
176
+ self.__il_relax[i] = True
177
+ self._island_res[i] = self.__solve(_t, il, timeout_s, True, True)
178
+ if self._island_res[i][0] != IslandResult.Failed:
179
+ allFail = False
180
+ val += self._island_res[i][1]
181
+ if self._island_res[i][0] != IslandResult.OK: allOK = False
182
+ if self._island_res[i][0] == IslandResult.OverFlow: self.__il_relax[i] = False
183
+ if allOK:
184
+ return GridSolveResult.OK, val
185
+ elif allFail:
186
+ print(f"Failed to solve at time {_t}")
187
+ if self.saveto != "":
188
+ p = Path(self.saveto)
189
+ p.mkdir(parents=True, exist_ok=True)
190
+ self.grid.savePQofBus(str(p/f"{_t}_load.csv"), _t)
191
+ return GridSolveResult.Failed, val
192
+ else:
193
+ return GridSolveResult.PartialOK, val
194
+
195
+ def __solve(self, _t: int, island:_Island, timeout_s:float, relaxV:bool, relaxI:bool, clear_results:bool=False) -> 'tuple[IslandResult, float]':
196
+ model = Model("model")
197
+
198
+ ''' ---------Variables----------
199
+ pg0[k]: Generator active power
200
+ qg0[k]: Generator reactive power
201
+ pvwp[k]: PVWind active power
202
+ --> pg[j]: Active power of all generators at the bus
203
+ --> qg[j]: Reactive power of all generators at the bus
204
+ v[j]: Bus voltage ** 2
205
+ l[i,j]: Line current ** 2
206
+ P[i,j]: Line active power
207
+ Q[i,j]: Line reactive power
208
+ '''
209
+ # Create GEN vars
210
+ pg0: dict[str, VF] = {}
211
+ qg0: dict[str, VF] = {}
212
+ for gID, g in island.GenItems():
213
+ if g.FixedP:
214
+ assert g.P is not None
215
+ pg0[gID] = g.P(_t) if isinstance(g.P, TimeFunc) else g.P
216
+ elif g.Pmin is not None and g.Pmax is not None:
217
+ pg0[gID] = model.addVar(name=f"pg_{gID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t))
218
+ else:
219
+ raise ValueError(f"Generator {gID} provides neither P or (pmin, pmax)")
220
+ if g.FixedQ:
221
+ assert g.Q is not None
222
+ qg0[gID] = g.Q(_t) if isinstance(g.Q, TimeFunc) else g.Q
223
+ elif g.Qmin is not None and g.Qmax is not None:
224
+ qg0[gID] = model.addVar(name=f"qg_{gID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t))
225
+ else:
226
+ raise ValueError(f"Generator {g.ID} provides neither Q or (qmin, qmax)")
227
+
228
+ pvwp: dict[str, Var] = {pID: model.addVar(
229
+ name=f"pvw_{pID}", vtype='C', lb=0, ub=p.P(_t)
230
+ ) for pID, p in island.PVWItems()}
231
+ pvwq: dict[str, Var] = {pID: model.addVar(
232
+ name=f"pvw_{pID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY
233
+ ) for pID in island.PVWs}
234
+
235
+ # Bind GEN vars to Bus
236
+ pg: dict[str, list[VF]] = {b: [] for b in island.Buses}
237
+ qg: dict[str, list[VF]] = {b: [] for b in island.Buses}
238
+ pd: dict[str, float] = {bID: b.Pd(_t) for bID, b in island.BusItems()}
239
+ qd: dict[str, float] = {bID: b.Qd(_t) for bID, b in island.BusItems()}
240
+ for gID, g in island.GenItems():
241
+ pg[g.BusID].append(pg0[gID])
242
+ qg[g.BusID].append(qg0[gID])
243
+ for pID, p in island.PVWItems():
244
+ pg[p.BusID].append(pvwp[pID])
245
+ qg[p.BusID].append(pvwq[pID])
246
+ for eID, e in island.ESSItems():
247
+ p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
248
+ e.P = p
249
+ if p > 0:
250
+ pd[e.BusID] += p
251
+ qd[e.BusID] += q
252
+ elif p < 0:
253
+ pg[e.BusID].append(-p)
254
+ qg[e.BusID].append(-q)
255
+
256
+ # Create BUS vars
257
+ v = {bID: model.addVar(name=f"v_{bID}", vtype='C') for bID in island.Buses}
258
+ dvmin:dict[str, Var] = {}
259
+ dvmax:dict[str, Var] = {}
260
+ for bid, b in island.BusItems():
261
+ if b.FixedV:
262
+ assert b.V is not None, f"Bus {bid} has fixed voltage but not set"
263
+ model.addConstr(v[bid] == b.V ** 2)
264
+ elif relaxV:
265
+ dvmin[bid] = model.addVar(name=f"dvmin_{bid}", vtype='C', lb=0)
266
+ dvmax[bid] = model.addVar(name=f"dvmax_{bid}", vtype='C', lb=0)
267
+ model.addConstr(v[bid] >= b.MinV ** 2 - dvmin[bid])
268
+ model.addConstr(v[bid] <= b.MaxV ** 2 + dvmax[bid])
269
+ else:
270
+ model.addConstr(v[bid] >= b.MinV ** 2)
271
+ model.addConstr(v[bid] <= b.MaxV ** 2)
272
+
273
+ # Create Line vars
274
+ dlmax:dict[str, Var] = {}
275
+ l = {lID: model.addVar(name=f"l_{lID}", vtype='C', lb=0) for lID in island.Lines}
276
+ for lID, ln in island.LineItems():
277
+ if relaxI:
278
+ dlmax[lID] = model.addVar(name=f"dlmax_{lID}", vtype='C', lb=0)
279
+ model.addConstr(l[lID] <= (ln.max_I/island.grid.Ib) ** 2 + dlmax[lID])
280
+ else:
281
+ model.addConstr(l[lID] <= (ln.max_I/island.grid.Ib) ** 2)
282
+
283
+ P = {lID: model.addVar(name=f"P_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
284
+ island.Lines}
285
+ Q = {lID: model.addVar(name=f"Q_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
286
+ island.Lines}
287
+
288
+ Pdec:dict[BusID, Var] = {bus: model.addVar(name=f"Pdec_{bus}", vtype='C',
289
+ lb=0, ub=lim.Limit(_t) * self._mlrp) for bus, lim in self._decb.items()}
290
+
291
+ # ----------Constraints-----------
292
+ Pcons: dict[str, Constr] = {}
293
+ Qcons: dict[str, Constr] = {}
294
+
295
+ for j, bus in island.BusItems():
296
+ flow_in = island.grid.LinesOfTBus(j)
297
+ flow_out = island.grid.LinesOfFBus(j)
298
+ dec = Pdec[j] if j in Pdec else 0
299
+ Pcons[j] = model.addConstr(
300
+ Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(pg[j]) == Qs(
301
+ P[ln.ID] for ln in flow_out if ln.ID in island.Lines) + pd[j] - dec, f"Pcons_{j}")
302
+ Qcons[j] = model.addConstr(
303
+ Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(qg[j]) == Qs(
304
+ Q[ln.ID] for ln in flow_out if ln.ID in island.Lines) + qd[j], f"Qcons_{j}")
305
+
306
+ for lid, line in island.LineItems():
307
+ i, j = line.pair
308
+ lid = line.ID
309
+ model.addConstr(
310
+ v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
311
+ f"ΔU2_cons_{lid}")
312
+ model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
313
+
314
+ for pID, p in island.PVWItems():
315
+ model.addConstr(pvwp[pID] * math.sqrt(1 - p.PF**2) == pvwq[pID])
316
+
317
+ decs = self.C * (Qs(Pdec.values()) + Qs(dvmin.values()) + Qs(dvmax.values()) + Qs(dlmax.values()))
318
+ crpe = Qs(p.CC*(p.P(_t)-pvwp[pID]) for pID, p in island.PVWItems())
319
+ if self._sec_cost:
320
+ goal = Qs(g.CostA(_t) * pg0[gID] ** 2 + g.CostB(_t) * pg0[gID] + g.CostC(_t) for gID, g in island.GenItems())
321
+ else:
322
+ goal = Qs(g.CostB(_t) * pg0[gID] + g.CostC(_t) for gID, g in island.GenItems())
323
+
324
+ model.setObjective(decs + goal + crpe, GRB.MINIMIZE)
325
+ model.setParam(GRB.Param.OutputFlag, 0)
326
+ model.setParam(GRB.Param.QCPDual, 1)
327
+ model.setParam(GRB.Param.TimeLimit, timeout_s)
328
+ model.setParam(GRB.Param.OptimalityTol, 1e-6)
329
+ model.update()
330
+ model.optimize()
331
+
332
+ if model.Status != GRB.Status.OPTIMAL and model.Status != GRB.Status.SUBOPTIMAL:
333
+ for _, bus in island.BusItems():
334
+ if not bus.FixedV: bus._v = 0
335
+ bus.ShadowPrice = 0
336
+ for _, p in island.PVWItems():
337
+ p._pr = p._qr = p._cr = 0
338
+ for _, line in island.LineItems():
339
+ line.I = line.P = line.Q = 0
340
+ for j, gen in island.GenItems():
341
+ if not gen.FixedP: gen._p = 0
342
+ if not gen.FixedQ: gen._q = 0
343
+ for _, e in island.ESSItems():
344
+ e.P = 0
345
+ return IslandResult.Failed, -1
346
+
347
+ for j, bus in island.BusItems():
348
+ bus._v = v[j].X ** 0.5
349
+ try:
350
+ sp = Pcons[j].Pi
351
+ except:
352
+ sp = None if not self.grid._holdShadowPrice else bus.ShadowPrice
353
+ bus.ShadowPrice = sp
354
+
355
+ for lid, line in island.LineItems():
356
+ line.I = l[lid].X ** 0.5
357
+ line.P = P[lid].X
358
+ line.Q = Q[lid].X
359
+
360
+ for j, gen in island.GenItems():
361
+ p = pg0[j]
362
+ if isinstance(p, Var): gen._p = p.X
363
+ q = qg0[j]
364
+ if isinstance(q, Var): gen._q = q.X
365
+
366
+ for pID, p in island.PVWItems():
367
+ p._pr = pvwp[pID].X
368
+ p._qr = pvwq[pID].X
369
+ pgen = p.P(_t)
370
+ p._cr = 1 - p._pr / pgen if pgen > 0 else 0
371
+
372
+ overflow = False
373
+ self._ofbuses.clear()
374
+ for bID, bv in chain(dvmax.items(), dvmin.items()):
375
+ if bv.X > 1e-8:
376
+ overflow = True
377
+ self._ofbuses.add(bID)
378
+
379
+ self._oflines.clear()
380
+ for lID, lv in dlmax.items():
381
+ if lv.X > 1e-8:
382
+ overflow = True
383
+ self._oflines.add(lID)
384
+
385
+ for bus, lim in self._decb.items():
386
+ lim.Reduction = Pdec[bus].X
387
+ if lim.Reduction < 1e-8: lim.Reduction = 0
388
+
389
+ return IslandResult.OverFlow if overflow else IslandResult.OK, goal.getValue()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fpowerkit
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -5,7 +5,7 @@ with open("desc.md", "r", encoding="utf8") as f:
5
5
 
6
6
  setup(
7
7
  name="fpowerkit",
8
- version="0.1.3",
8
+ version="0.1.5",
9
9
  author="fmy_xfk",
10
10
  packages=find_packages(),
11
11
  description="A Distflow PDN solver based on Gurobi.",
@@ -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