fpowerkit 0.1.1__tar.gz → 0.1.2__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.1 → fpowerkit-0.1.2}/PKG-INFO +2 -2
- fpowerkit-0.1.2/fpowerkit/__init__.py +5 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/cases.py +20 -20
- fpowerkit-0.1.2/fpowerkit/ess.py +255 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/grid.py +69 -4
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/line.py +7 -4
- fpowerkit-0.1.2/fpowerkit/solbase.py +26 -0
- fpowerkit-0.1.1/fpowerkit/solver.py → fpowerkit-0.1.2/fpowerkit/soldist.py +54 -197
- fpowerkit-0.1.2/fpowerkit/solnt.py +156 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/utils.py +5 -4
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit.egg-info/PKG-INFO +2 -2
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit.egg-info/SOURCES.txt +4 -1
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit.egg-info/requires.txt +1 -1
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/setup.py +2 -2
- fpowerkit-0.1.1/fpowerkit/__init__.py +0 -3
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/LICENSE +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/README.md +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/bus.py +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/gen.py +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit/pvwind.py +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit.egg-info/dependency_links.txt +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/fpowerkit.egg-info/top_level.txt +0 -0
- {fpowerkit-0.1.1 → fpowerkit-0.1.2}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: fpowerkit
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: A Distflow PDN solver based on Gurobi.
|
|
5
5
|
Author: fmy_xfk
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -9,7 +9,7 @@ Classifier: Operating System :: OS Independent
|
|
|
9
9
|
Requires-Python: >=3.8
|
|
10
10
|
Description-Content-Type: text/markdown
|
|
11
11
|
License-File: LICENSE
|
|
12
|
-
Requires-Dist: feasytools>=0.0.
|
|
12
|
+
Requires-Dist: feasytools>=0.0.21
|
|
13
13
|
Requires-Dist: gurobipy>=9.1.0
|
|
14
14
|
Requires-Dist: numpy>=1.20.0
|
|
15
15
|
|
|
@@ -260,29 +260,29 @@ def _get_buses(
|
|
|
260
260
|
Sb_KVA:float, grid_repeat:int,
|
|
261
261
|
LOAD:'list[tuple[int,float,float]]',
|
|
262
262
|
changeable_load:bool,
|
|
263
|
-
|
|
263
|
+
load_fluc:'list[tuple[int,float]]',
|
|
264
264
|
load_repeat:int,
|
|
265
265
|
load_period:int,
|
|
266
266
|
):
|
|
267
267
|
if changeable_load:
|
|
268
|
-
if len(
|
|
269
|
-
for
|
|
270
|
-
|
|
271
|
-
load_fluctuation.append((_DEFAULT_LOAD_SCALE[j][0] + 86400 * i, _DEFAULT_LOAD_SCALE[j][1]))
|
|
268
|
+
if len(load_fluc) == 0:
|
|
269
|
+
for j in range(24):
|
|
270
|
+
load_fluc.append((_DEFAULT_LOAD_SCALE[j][0], _DEFAULT_LOAD_SCALE[j][1]))
|
|
272
271
|
else:
|
|
273
|
-
ls =
|
|
274
|
-
|
|
275
|
-
for
|
|
276
|
-
|
|
277
|
-
load_fluctuation.append((ls[j][0] + load_period * i, ls[j][1]))
|
|
272
|
+
ls = load_fluc
|
|
273
|
+
load_fluc = []
|
|
274
|
+
for j in range(24):
|
|
275
|
+
load_fluc.append((ls[j][0], ls[j][1]))
|
|
278
276
|
if grid_repeat == 1:
|
|
279
|
-
B = [Bus("B"+str(p[0]), _create_load(p[1]/Sb_KVA,
|
|
280
|
-
_create_load(p[2]/Sb_KVA,
|
|
277
|
+
B = [Bus("B"+str(p[0]), _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
|
|
278
|
+
_create_load(p[2]/Sb_KVA,load_fluc).repeat(load_repeat,load_period),
|
|
279
|
+
min_v_pu=0.9,max_v_pu=1.1) for p in LOAD]
|
|
281
280
|
else:
|
|
282
281
|
B = []
|
|
283
282
|
for i in range(grid_repeat):
|
|
284
|
-
B.extend([Bus(f"B{i}_{p[0]}", _create_load(p[1]/Sb_KVA,
|
|
285
|
-
_create_load(p[2]/Sb_KVA,
|
|
283
|
+
B.extend([Bus(f"B{i}_{p[0]}", _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
|
|
284
|
+
_create_load(p[2]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
|
|
285
|
+
min_v_pu=0.9,max_v_pu=1.1) for p in LOAD])
|
|
286
286
|
else:
|
|
287
287
|
if grid_repeat == 1:
|
|
288
288
|
B = [Bus("B"+str(p[0]), p[1]/Sb_KVA, p[2]/Sb_KVA,min_v_pu=0.9,max_v_pu=1.1) for p in LOAD]
|
|
@@ -324,16 +324,16 @@ class PDNCases:
|
|
|
324
324
|
default_gen:GeneratorModel=_DEFAULT_GENERATOR,
|
|
325
325
|
grid_repeat:int = 1,
|
|
326
326
|
changeable_load:bool = False,
|
|
327
|
-
|
|
327
|
+
load_fluc:'list[tuple[int, float]]' = [],
|
|
328
328
|
load_repeat:int = 8,
|
|
329
329
|
load_period:int = 86400
|
|
330
330
|
):
|
|
331
331
|
'''IEEE 33-bus distribution network'''
|
|
332
332
|
return Grid(Sb_MVA, Ub_kV,
|
|
333
|
-
_get_buses(Sb_MVA*1000, grid_repeat, _IEEE33_LOAD, changeable_load,
|
|
333
|
+
_get_buses(Sb_MVA*1000, grid_repeat, _IEEE33_LOAD, changeable_load, load_fluc, load_repeat, load_period),
|
|
334
334
|
_get_lines(Ub_kV**2/Sb_MVA, _IEEE33_LINE, grid_repeat),
|
|
335
335
|
_get_gens(default_gen, gen_pos, grid_repeat),
|
|
336
|
-
[]
|
|
336
|
+
[],[]
|
|
337
337
|
)
|
|
338
338
|
|
|
339
339
|
@staticmethod
|
|
@@ -344,14 +344,14 @@ class PDNCases:
|
|
|
344
344
|
default_gen:GeneratorModel=_DEFAULT_GENERATOR,
|
|
345
345
|
grid_repeat:int = 1,
|
|
346
346
|
changeable_load:bool = False,
|
|
347
|
-
|
|
347
|
+
load_fluc:'list[tuple[int, float]]' = [],
|
|
348
348
|
load_repeat:int = 8,
|
|
349
349
|
load_period:int = 86400
|
|
350
350
|
):
|
|
351
351
|
'''IEEE 69-bus distribution network'''
|
|
352
352
|
return Grid(Sb_MVA, Ub_kV,
|
|
353
|
-
_get_buses(Sb_MVA*1000, grid_repeat, _IEEE69_LOAD, changeable_load,
|
|
353
|
+
_get_buses(Sb_MVA*1000, grid_repeat, _IEEE69_LOAD, changeable_load, load_fluc, load_repeat, load_period),
|
|
354
354
|
_get_lines(Ub_kV**2/Sb_MVA, _IEEE69_LINE, grid_repeat),
|
|
355
355
|
_get_gens(default_gen, gen_pos, grid_repeat),
|
|
356
|
-
[]
|
|
356
|
+
[],[]
|
|
357
357
|
)
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
from enum import IntEnum
|
|
2
|
+
import math
|
|
3
|
+
from feasytools import RangeList
|
|
4
|
+
from .utils import *
|
|
5
|
+
|
|
6
|
+
class ESSPolicy(IntEnum):
|
|
7
|
+
Manual = 0 # Charging/discharging manually
|
|
8
|
+
Time = 1 # Charging/discharging at given period
|
|
9
|
+
Price = 2 # Charging at low price, discharging at high price
|
|
10
|
+
|
|
11
|
+
class ESSManualState(IntEnum):
|
|
12
|
+
Idle = 0
|
|
13
|
+
Charge = 1
|
|
14
|
+
Discharge = 2
|
|
15
|
+
|
|
16
|
+
class ESS:
|
|
17
|
+
'''Model of an Energy Storage System'''
|
|
18
|
+
def __init__(self, id: str, busid: str, cap_puh: float, ec:float, ed:float, pc_max:float, pd_max:float,
|
|
19
|
+
pf:float, policy:ESSPolicy, ctime:Optional[RangeList]=None, dtime:Optional[RangeList]=None,
|
|
20
|
+
cprice:NFloat=None, dprice:NFloat=None, Lat: NFloat=None, Lon: NFloat=None, init_elec_puh: float=0.0):
|
|
21
|
+
'''
|
|
22
|
+
Initialize
|
|
23
|
+
id: ESS ID
|
|
24
|
+
busid: ID of the bus where the ESS is located
|
|
25
|
+
cap_puh: Capacity of the ESS, puh
|
|
26
|
+
ec: Charging efficiency
|
|
27
|
+
ed: Discharging efficiency
|
|
28
|
+
pc_max: Maximum charging power, pu
|
|
29
|
+
pd_max: Maximum discharging power, pu
|
|
30
|
+
pf: Power factor, cos(phi). Reactive output Q = P * sqrt(1 - PF**2)
|
|
31
|
+
policy: ESSPolicy
|
|
32
|
+
c_cond: Charging condition
|
|
33
|
+
d_cond: Discharging condition
|
|
34
|
+
Lat: Latitude of the ESS
|
|
35
|
+
Lon: Longitude of the ESS
|
|
36
|
+
'''
|
|
37
|
+
self._id = id
|
|
38
|
+
self._bus = busid
|
|
39
|
+
self._cap = cap_puh
|
|
40
|
+
self._ec = ec
|
|
41
|
+
self._ed = ed
|
|
42
|
+
self._pc_max = pc_max
|
|
43
|
+
self._pd_max = pd_max
|
|
44
|
+
self._pf = pf
|
|
45
|
+
self.Lat = Lat
|
|
46
|
+
self.Lon = Lon
|
|
47
|
+
self._elec = init_elec_puh
|
|
48
|
+
self._policy = policy
|
|
49
|
+
self._ctime = ctime
|
|
50
|
+
self._dtime = dtime
|
|
51
|
+
self._cprice = cprice
|
|
52
|
+
self._dprice = dprice
|
|
53
|
+
self._manstate = ESSManualState.Idle
|
|
54
|
+
self.P:FloatVar = None
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def Q(self) -> float:
|
|
58
|
+
'''Reactive power output'''
|
|
59
|
+
return self.__q(self.P) if self.P is not None else 0.0
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def SOC(self) -> float:
|
|
63
|
+
'''State of charge'''
|
|
64
|
+
return self._elec / self._cap
|
|
65
|
+
|
|
66
|
+
def Apply(self, dur_s:int):
|
|
67
|
+
if self.P is not None:
|
|
68
|
+
dur = dur_s / 3600
|
|
69
|
+
if self.P < 0:
|
|
70
|
+
return self.Discharge(-self.P, dur)
|
|
71
|
+
else:
|
|
72
|
+
return self.Charge(self.P, dur)
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
def __q(self, P: float) -> float:
|
|
76
|
+
'''Calculate reactive power'''
|
|
77
|
+
return P * math.sqrt(1 - self._pf**2)
|
|
78
|
+
|
|
79
|
+
def GetLoad(self, t: int, cprice:float, dprice:float) -> tuple[float, float]:
|
|
80
|
+
if self._policy == ESSPolicy.Manual:
|
|
81
|
+
if self._manstate == ESSManualState.Charge and self._elec < self._cap:
|
|
82
|
+
return self._pc_max, self.__q(self._pc_max)
|
|
83
|
+
elif self._manstate == ESSManualState.Discharge and self._elec > 0:
|
|
84
|
+
return -self._pd_max, -self.__q(self._pd_max)
|
|
85
|
+
elif self._policy == ESSPolicy.Time:
|
|
86
|
+
if self._ctime is not None and t in self._ctime and self._elec < self._cap:
|
|
87
|
+
return self._pc_max, self.__q(self._pc_max)
|
|
88
|
+
elif self._dtime is not None and t in self._dtime and self._elec > 0:
|
|
89
|
+
return -self._pd_max, -self.__q(self._pd_max)
|
|
90
|
+
elif self._policy == ESSPolicy.Price:
|
|
91
|
+
if self._cprice is not None and self._dprice is not None:
|
|
92
|
+
if self._cprice < cprice and self._elec < self._cap:
|
|
93
|
+
return self._pc_max, self.__q(self._pc_max)
|
|
94
|
+
elif self._dprice > dprice and self._elec > 0:
|
|
95
|
+
return -self._pd_max, -self.__q(self._pd_max)
|
|
96
|
+
return 0, 0
|
|
97
|
+
|
|
98
|
+
def Charge(self, P: float, dt: float):
|
|
99
|
+
'''Charge the ESS with power P for time dt'''
|
|
100
|
+
old = self._elec
|
|
101
|
+
self._elec = min(self._cap, self._elec + P * self._ec * dt)
|
|
102
|
+
return self._elec - old
|
|
103
|
+
|
|
104
|
+
def Discharge(self, P: float, dt: float):
|
|
105
|
+
'''Discharge the ESS with power P for time dt'''
|
|
106
|
+
old = self._elec
|
|
107
|
+
self._elec = max(0, self._elec - P / self._ed * dt)
|
|
108
|
+
return self._elec - old
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def ID(self):
|
|
112
|
+
'''Name of the ESS'''
|
|
113
|
+
return self._id
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def BusID(self):
|
|
117
|
+
'''ID of the bus where the ESS is located'''
|
|
118
|
+
return self._bus
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def MaxPc(self):
|
|
122
|
+
'''Maximum charging power, pu'''
|
|
123
|
+
return self._pc_max
|
|
124
|
+
@MaxPc.setter
|
|
125
|
+
def MaxPc(self, pc: float):
|
|
126
|
+
self._pc_max = pc
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def MaxPd(self):
|
|
130
|
+
'''Maximum discharging power, pu'''
|
|
131
|
+
return self._pd_max
|
|
132
|
+
@MaxPd.setter
|
|
133
|
+
def MaxPd(self, pd: float):
|
|
134
|
+
self._pd_max = pd
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def Cap(self):
|
|
138
|
+
'''Capacity of the ESS, puh'''
|
|
139
|
+
return self._cap
|
|
140
|
+
@Cap.setter
|
|
141
|
+
def Cap(self, cap: float):
|
|
142
|
+
self._cap = cap
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def EC(self):
|
|
146
|
+
'''Charging efficiency'''
|
|
147
|
+
return self._ec
|
|
148
|
+
@EC.setter
|
|
149
|
+
def EC(self, ec: float):
|
|
150
|
+
assert 0 <= ec <= 1, "Charging efficiency must be in [0, 1]"
|
|
151
|
+
self._ec = ec
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def ED(self):
|
|
155
|
+
'''Discharging efficiency'''
|
|
156
|
+
return self._ed
|
|
157
|
+
@ED.setter
|
|
158
|
+
def ED(self, ed: float):
|
|
159
|
+
assert 0 <= ed <= 1, "Discharging efficiency must be in [0, 1]"
|
|
160
|
+
self._ed = ed
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def PF(self):
|
|
164
|
+
'''Power factor, cos(phi). Reactive output Q = P * sqrt(1 - PF**2)'''
|
|
165
|
+
return self._pf
|
|
166
|
+
@PF.setter
|
|
167
|
+
def PF(self, pf: float):
|
|
168
|
+
assert -1 <= pf <= 1, "Power factor must be in [-1, 1]"
|
|
169
|
+
self._pf = pf
|
|
170
|
+
|
|
171
|
+
def position(self):
|
|
172
|
+
'''Return the position of the ESS'''
|
|
173
|
+
return (self.Lat, self.Lon)
|
|
174
|
+
|
|
175
|
+
def LonLat(self):
|
|
176
|
+
'''Return the position of the ESS'''
|
|
177
|
+
return (self.Lon, self.Lat)
|
|
178
|
+
|
|
179
|
+
def __repr__(self) -> str:
|
|
180
|
+
return (f"ESS(id='{self.ID}', busid='{self.BusID}', "+
|
|
181
|
+
f"pc_max={self.MaxPc:.6f}, pd_max={self.MaxPd:.6f}, pf={self.PF:.6f}, "+
|
|
182
|
+
f"ec={self.EC:.6f}, ed={self.ED:.6f}, Lat={self.Lat:.6f}, Lon={self.Lon:.6f})")
|
|
183
|
+
|
|
184
|
+
def __str__(self) -> str:
|
|
185
|
+
return repr(self)
|
|
186
|
+
|
|
187
|
+
def str_t(self, _t: int) -> str:
|
|
188
|
+
return repr(self)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def fromXML(node: 'Element', Sb_MVA: float, Ub_kV: float) -> 'ESS':
|
|
192
|
+
'''
|
|
193
|
+
Load ESS from XML node
|
|
194
|
+
node: XML node
|
|
195
|
+
'''
|
|
196
|
+
id = node.attrib["ID"]
|
|
197
|
+
busid = node.attrib["Bus"]
|
|
198
|
+
cap = ReadConst(node.attrib["cap"], Sb_MVA, Ub_kV)
|
|
199
|
+
ec = float(node.attrib["ec"])
|
|
200
|
+
ed = float(node.attrib["ed"])
|
|
201
|
+
pc_max = ReadConst(node.attrib["pc_max"], Sb_MVA, Ub_kV)
|
|
202
|
+
pd_max = ReadConst(node.attrib["pd_max"], Sb_MVA, Ub_kV)
|
|
203
|
+
pf = float(node.attrib["pf"])
|
|
204
|
+
policy = ESSPolicy(int(node.attrib["policy"])) if "policy" in node.attrib else ESSPolicy.Manual
|
|
205
|
+
ctime_node = node.find("ctime")
|
|
206
|
+
if ctime_node is not None:
|
|
207
|
+
ctime = RangeList(ctime_node)
|
|
208
|
+
else:
|
|
209
|
+
ctime = None
|
|
210
|
+
dtime_node = node.find("dtime")
|
|
211
|
+
if dtime_node is not None:
|
|
212
|
+
dtime = RangeList(dtime_node)
|
|
213
|
+
else:
|
|
214
|
+
dtime = None
|
|
215
|
+
cprice = ReadConst(node.attrib["cprice"], Sb_MVA, Ub_kV) if "cprice" in node.attrib else None
|
|
216
|
+
dprice = ReadConst(node.attrib["dprice"], Sb_MVA, Ub_kV) if "dprice" in node.attrib else None
|
|
217
|
+
lat = float(node.attrib["Lat"]) if "Lat" in node.attrib else None
|
|
218
|
+
lon = float(node.attrib["Lon"]) if "Lon" in node.attrib else None
|
|
219
|
+
init = ReadConst(node.attrib["init_elec"], Sb_MVA, Ub_kV) if "init_elec" in node.attrib else 0.0
|
|
220
|
+
return ESS(id, busid, cap, ec, ed, pc_max, pd_max, pf, policy,
|
|
221
|
+
ctime, dtime, cprice, dprice, lat, lon, init)
|
|
222
|
+
|
|
223
|
+
def toXMLNode(self, Sb_MVA:Optional[float] = None, Sb_kVA:Optional[float] = None) -> 'Element':
|
|
224
|
+
'''Convert to XML node'''
|
|
225
|
+
e = Element("ess", {
|
|
226
|
+
"ID": self.ID,
|
|
227
|
+
"Bus": self.BusID,
|
|
228
|
+
"ec": str(self.EC),
|
|
229
|
+
"ed": str(self.ED),
|
|
230
|
+
"pf": str(self.PF),
|
|
231
|
+
})
|
|
232
|
+
if self.Lat is not None: e.attrib["Lat"] = f"{self.Lat:.6f}"
|
|
233
|
+
if self.Lon is not None: e.attrib["Lon"] = f"{self.Lon:.6f}"
|
|
234
|
+
if self._ctime is not None:
|
|
235
|
+
e.append(self._ctime.toXMLNode("ctime"))
|
|
236
|
+
if self._dtime is not None:
|
|
237
|
+
e.append(self._dtime.toXMLNode("dtime"))
|
|
238
|
+
if Sb_MVA is not None and Sb_kVA is not None:
|
|
239
|
+
raise ValueError("Provide only ONE of Sb_MVA or Sb_kVA.")
|
|
240
|
+
if Sb_MVA is not None:
|
|
241
|
+
mul = Sb_MVA
|
|
242
|
+
unit = ["MWh", "MW", "$/MWh"]
|
|
243
|
+
elif Sb_kVA is not None:
|
|
244
|
+
mul = Sb_kVA
|
|
245
|
+
unit = ["kWh", "kW", "$/kWh"]
|
|
246
|
+
else:
|
|
247
|
+
mul = 1
|
|
248
|
+
unit = ["puh", "pu", "$/puh"]
|
|
249
|
+
e.attrib["cap"] = str(self._cap*mul) + unit[0]
|
|
250
|
+
e.attrib["pc_max"] = str(self._pc_max*mul) + unit[1]
|
|
251
|
+
e.attrib["pd_max"] = str(self._pd_max*mul) + unit[1]
|
|
252
|
+
e.attrib["init_elec"] = str(self._elec*mul) + unit[0]
|
|
253
|
+
if self._cprice: e.attrib["cprice"] = str(self._cprice*mul) + unit[2]
|
|
254
|
+
if self._dprice: e.attrib["dprice"] = str(self._dprice*mul) + unit[2]
|
|
255
|
+
return e
|
|
@@ -10,7 +10,7 @@ from .bus import *
|
|
|
10
10
|
from .line import *
|
|
11
11
|
from .gen import *
|
|
12
12
|
from .pvwind import *
|
|
13
|
-
|
|
13
|
+
from .ess import *
|
|
14
14
|
|
|
15
15
|
BusID = str
|
|
16
16
|
LineID = str
|
|
@@ -52,7 +52,8 @@ class Grid:
|
|
|
52
52
|
return self.Sb / (self.Ub * (3 ** 0.5))
|
|
53
53
|
|
|
54
54
|
def __init__(self, Sb_MVA: float, Ub_kV: float, buses: 'Iterable[Bus]', lines: 'Iterable[Line]',
|
|
55
|
-
gens: 'Iterable[Generator]', pvws: 'Iterable[PVWind]',
|
|
55
|
+
gens: 'Iterable[Generator]', pvws: 'Iterable[PVWind]', esss: 'Iterable[ESS]',
|
|
56
|
+
cprice: FloatLike = 0, dprice: FloatLike = 0, holdShadowPrice: bool = False):
|
|
56
57
|
'''
|
|
57
58
|
Initialize
|
|
58
59
|
Sb_MVA: base power, MVA
|
|
@@ -61,6 +62,9 @@ class Grid:
|
|
|
61
62
|
lines: list of lines
|
|
62
63
|
gens: list of generators
|
|
63
64
|
pvws: list of PVWinds
|
|
65
|
+
esss: list of ESSs
|
|
66
|
+
cprice: charge price of the whole grid, $/puh
|
|
67
|
+
dprice: discharge price of the whole grid, $/puh
|
|
64
68
|
holdShadowPrice: whether to hold the shadow price of the buses of the last time when failed to solve this time
|
|
65
69
|
'''
|
|
66
70
|
self.Sb = Sb_MVA
|
|
@@ -70,6 +74,9 @@ class Grid:
|
|
|
70
74
|
self._lines = {line.ID: line for line in lines}
|
|
71
75
|
self._gens = {gen.ID: gen for gen in gens}
|
|
72
76
|
self._pvws = {pvw.ID: pvw for pvw in pvws}
|
|
77
|
+
self._esss = {ess.ID: ess for ess in esss}
|
|
78
|
+
self._cp = Float2Func(cprice)
|
|
79
|
+
self._dp = Float2Func(dprice)
|
|
73
80
|
self._holdShadowPrice = holdShadowPrice
|
|
74
81
|
|
|
75
82
|
self._bnames = list(self._buses.keys())
|
|
@@ -77,6 +84,7 @@ class Grid:
|
|
|
77
84
|
self._ladjtb: 'dict[str, list[Line]]' = {bus.ID: [] for bus in self._buses.values()}
|
|
78
85
|
self._gatb: 'dict[str, list[Generator]]' = {bus.ID: [] for bus in self._buses.values()}
|
|
79
86
|
self._patb: 'dict[str, list[PVWind]]' = {bus.ID: [] for bus in self._buses.values()}
|
|
87
|
+
self._eatb: 'dict[str, list[ESS]]' = {bus.ID: [] for bus in self._buses.values()}
|
|
80
88
|
for line in self._lines.values():
|
|
81
89
|
if not line.fBus in self._bnames: raise ValueError(f"Bus {line.fBus} undefined")
|
|
82
90
|
if not line.tBus in self._bnames: raise ValueError(f"Bus {line.tBus} undefined")
|
|
@@ -87,8 +95,19 @@ class Grid:
|
|
|
87
95
|
self._gatb[gen.BusID].append(gen)
|
|
88
96
|
for pvw in self._pvws.values():
|
|
89
97
|
assert pvw.BusID in self._bnames
|
|
90
|
-
self._patb[pvw.BusID].append(pvw)
|
|
98
|
+
self._patb[pvw.BusID].append(pvw)
|
|
99
|
+
for ess in self._esss.values():
|
|
100
|
+
assert ess.BusID in self._bnames
|
|
101
|
+
self._eatb[ess.BusID].append(ess)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def ChargePrice(self):
|
|
105
|
+
return self._cp
|
|
91
106
|
|
|
107
|
+
@property
|
|
108
|
+
def DischargePrice(self):
|
|
109
|
+
return self._dp
|
|
110
|
+
|
|
92
111
|
def AddGen(self, g: Generator):
|
|
93
112
|
'''Add a generator'''
|
|
94
113
|
self._gens[g.ID] = g
|
|
@@ -146,6 +165,15 @@ class Grid:
|
|
|
146
165
|
'''Delete a PVWind'''
|
|
147
166
|
p = self._pvws.pop(id)
|
|
148
167
|
self._patb[p.BusID].remove(p)
|
|
168
|
+
|
|
169
|
+
def AddESS(self, e: ESS):
|
|
170
|
+
'''Add an ESS'''
|
|
171
|
+
self._esss[e.ID] = e
|
|
172
|
+
|
|
173
|
+
def ApplyAllESS(self, dur: int):
|
|
174
|
+
'''Apply all ESSs'''
|
|
175
|
+
for e in self._esss.values():
|
|
176
|
+
e.Apply(dur)
|
|
149
177
|
|
|
150
178
|
@property
|
|
151
179
|
def BusNames(self) -> 'list[str]':
|
|
@@ -237,6 +265,24 @@ class Grid:
|
|
|
237
265
|
self._bnames.remove(old_id)
|
|
238
266
|
self._bnames.append(new_id)
|
|
239
267
|
|
|
268
|
+
def ChangeESSID(self, old_id:str, new_id:str):
|
|
269
|
+
if old_id == new_id: return
|
|
270
|
+
if new_id in self._esss.keys():
|
|
271
|
+
raise ValueError(f"Duplicated ESS name: {new_id}")
|
|
272
|
+
e = self._esss.pop(old_id)
|
|
273
|
+
e._id = new_id
|
|
274
|
+
self._esss[new_id] = e
|
|
275
|
+
|
|
276
|
+
def ChangeESSBus(self, ess_id:str, new_bus_id:str):
|
|
277
|
+
if new_bus_id not in self._bnames:
|
|
278
|
+
raise ValueError(f"Invalid bus name: {new_bus_id}")
|
|
279
|
+
e = self._esss.get(ess_id)
|
|
280
|
+
if not e: raise ValueError(f"Invalid ESS name: {ess_id}")
|
|
281
|
+
if e.BusID == new_bus_id: return
|
|
282
|
+
self._eatb[e.BusID].remove(e)
|
|
283
|
+
e._bus = new_bus_id
|
|
284
|
+
self._eatb[e.BusID].append(e)
|
|
285
|
+
|
|
240
286
|
@property
|
|
241
287
|
def Buses(self):
|
|
242
288
|
return self._buses.values()
|
|
@@ -279,6 +325,16 @@ class Grid:
|
|
|
279
325
|
def PVWindNames(self) -> 'list[str]':
|
|
280
326
|
return list(self._pvws.keys())
|
|
281
327
|
|
|
328
|
+
@property
|
|
329
|
+
def ESSs(self):
|
|
330
|
+
return self._esss.values()
|
|
331
|
+
|
|
332
|
+
def ESS(self, id: str) -> 'ESS':
|
|
333
|
+
return self._esss[id]
|
|
334
|
+
|
|
335
|
+
def ESSsAtBus(self, busid: str) -> 'list[ESS]':
|
|
336
|
+
return self._eatb[busid]
|
|
337
|
+
|
|
282
338
|
def __repr__(self):
|
|
283
339
|
b = '\n '.join(map(str, self._buses.values()))
|
|
284
340
|
l = '\n '.join(map(str, self._lines.values()))
|
|
@@ -343,7 +399,10 @@ class Grid:
|
|
|
343
399
|
lines:list[Line] = []
|
|
344
400
|
gens:list[Generator] = []
|
|
345
401
|
pvws:list[PVWind] = []
|
|
402
|
+
esss:list[ESS] = []
|
|
346
403
|
#Read buses, lines and generators
|
|
404
|
+
cp = 0
|
|
405
|
+
dp = 0
|
|
347
406
|
|
|
348
407
|
gen_models:dict[str, GeneratorModel] = {}
|
|
349
408
|
for e in rt:
|
|
@@ -362,9 +421,15 @@ class Grid:
|
|
|
362
421
|
gen_models[e.attrib["name"]] = GeneratorModel.fromXML(e, Sb, Ub)
|
|
363
422
|
elif e.tag == "pv" or e.tag == "wind":
|
|
364
423
|
pvws.append(PVWind.fromXML(e, Sb, Ub))
|
|
424
|
+
elif e.tag == "ess":
|
|
425
|
+
esss.append(ESS.fromXML(e, Sb, Ub))
|
|
426
|
+
elif e.tag == "cprice":
|
|
427
|
+
cp = ReadFloatLike(e, Sb, Ub)
|
|
428
|
+
elif e.tag == "dprice":
|
|
429
|
+
dp = ReadFloatLike(e, Sb, Ub)
|
|
365
430
|
else:
|
|
366
431
|
raise ValueError(f"Unknown XML node: {e.tag}")
|
|
367
|
-
return Grid(Sb, Ub, buses, lines, gens, pvws, holdShadowPrice)
|
|
432
|
+
return Grid(Sb, Ub, buses, lines, gens, pvws, esss, cp, dp, holdShadowPrice)
|
|
368
433
|
|
|
369
434
|
def YMat(self):
|
|
370
435
|
'''Return the admittance matrix of the grid'''
|
|
@@ -9,8 +9,8 @@ class Line:
|
|
|
9
9
|
Q: FloatVar # pu
|
|
10
10
|
I: FloatVar # pu
|
|
11
11
|
|
|
12
|
-
def __init__(self, id: str, fbus: str, tbus: str, r_pu: float, x_pu: float,
|
|
13
|
-
|
|
12
|
+
def __init__(self, id: str, fbus: str, tbus: str, r_pu: float, x_pu: float, i_pu: NFloat = None,
|
|
13
|
+
p_pu: NFloat = None, q_pu: NFloat = None, max_I_kA: float = math.inf, length_km: NFloat = None):
|
|
14
14
|
'''
|
|
15
15
|
Initialize
|
|
16
16
|
id: Line ID
|
|
@@ -28,6 +28,7 @@ class Line:
|
|
|
28
28
|
self._max_I = max_I_kA
|
|
29
29
|
self.P = p_pu
|
|
30
30
|
self.Q = q_pu
|
|
31
|
+
self.L = length_km
|
|
31
32
|
|
|
32
33
|
@property
|
|
33
34
|
def ID(self) -> str:
|
|
@@ -83,7 +84,8 @@ class Line:
|
|
|
83
84
|
x, xu = ReadVal(node.attrib["X"])
|
|
84
85
|
if xu.lower() == "ohm": x = float(x) / Zb_Ohm
|
|
85
86
|
max_I = float(node.attrib.get("MaxIkA", math.inf))
|
|
86
|
-
|
|
87
|
+
l = float(node.attrib.get("Length_km", -1))
|
|
88
|
+
return Line(id, f, t, r, x, max_I_kA=max_I, length_km=l)
|
|
87
89
|
|
|
88
90
|
def toXMLNode(self, Zb_Ohm: Optional[float] = None) -> 'Element':
|
|
89
91
|
return Element("line", {
|
|
@@ -92,5 +94,6 @@ class Line:
|
|
|
92
94
|
"To": self.tBus,
|
|
93
95
|
"R": f"{self.R*Zb_Ohm:.6f}ohm" if Zb_Ohm is not None else f"{self.R:.8f}pu",
|
|
94
96
|
"X": f"{self.X*Zb_Ohm:.6f}ohm" if Zb_Ohm is not None else f"{self.X:.8f}pu",
|
|
95
|
-
"MaxIkA": str(self.max_I)
|
|
97
|
+
"MaxIkA": str(self.max_I),
|
|
98
|
+
"Length_km": str(self.L)
|
|
96
99
|
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from enum import IntEnum
|
|
3
|
+
from .grid import *
|
|
4
|
+
|
|
5
|
+
DEFAULT_SAVETO = "./fpowerkit_logs/"
|
|
6
|
+
|
|
7
|
+
class GridSolveResult(IntEnum):
|
|
8
|
+
'''Result of grid solving'''
|
|
9
|
+
Failed = 0
|
|
10
|
+
OK = 1
|
|
11
|
+
OKwithoutVICons = 2
|
|
12
|
+
SubOKwithoutVICons = 3
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SolverBase(ABC):
|
|
16
|
+
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, **kwargs):
|
|
17
|
+
self.grid = grid
|
|
18
|
+
self.eps = eps
|
|
19
|
+
self.saveto = default_saveto
|
|
20
|
+
|
|
21
|
+
def SetErrorSaveTo(self, path:str = DEFAULT_SAVETO):
|
|
22
|
+
self.saveto = path
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def solve(self, grid:Grid, _t:int, /, **kwargs):
|
|
26
|
+
raise NotImplementedError
|
|
@@ -1,193 +1,13 @@
|
|
|
1
|
-
from abc import ABC, abstractmethod
|
|
2
|
-
from dataclasses import dataclass
|
|
3
|
-
from enum import Enum, IntEnum
|
|
4
|
-
import math
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
from typing import Optional, Union
|
|
7
|
-
import warnings
|
|
8
1
|
from gurobipy import GRB, Constr, LinExpr, Model, Var
|
|
9
2
|
from gurobipy import quicksum as Qs
|
|
10
|
-
|
|
11
|
-
from
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional, Union
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import warnings, math
|
|
7
|
+
from .solbase import *
|
|
12
8
|
|
|
13
9
|
VF = Union[Var, float]
|
|
14
|
-
DEFAULT_SAVETO = "./fpowerkit_logs/"
|
|
15
|
-
|
|
16
|
-
class GridSolveResult(IntEnum):
|
|
17
|
-
'''Result of grid solving'''
|
|
18
|
-
Failed = 0
|
|
19
|
-
OK = 1
|
|
20
|
-
OKwithoutVICons = 2
|
|
21
|
-
SubOKwithoutVICons = 3
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
class SolverBase(ABC):
|
|
25
|
-
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, **kwargs):
|
|
26
|
-
self.grid = grid
|
|
27
|
-
self.eps = eps
|
|
28
|
-
self.saveto = default_saveto
|
|
29
|
-
|
|
30
|
-
def SetErrorSaveTo(self, path:str = DEFAULT_SAVETO):
|
|
31
|
-
self.saveto = path
|
|
32
|
-
|
|
33
|
-
@abstractmethod
|
|
34
|
-
def solve(self, grid:Grid, _t:int, /, **kwargs):
|
|
35
|
-
raise NotImplementedError
|
|
36
|
-
|
|
37
|
-
class BusType(IntEnum):
|
|
38
|
-
PQ = 0
|
|
39
|
-
PV = 1
|
|
40
|
-
Slack = 2
|
|
41
|
-
|
|
42
|
-
class NewtonSolver(SolverBase):
|
|
43
|
-
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100):
|
|
44
|
-
super().__init__(grid, eps, default_saveto)
|
|
45
|
-
self.Y = grid.YMat()
|
|
46
|
-
self.G, self.B = self.Y.real, self.Y.imag
|
|
47
|
-
self.max_iter = max_iter
|
|
48
|
-
|
|
49
|
-
def CheckBusType(self, _t:int):
|
|
50
|
-
'''Check the bus type'''
|
|
51
|
-
busType:dict[BusID, BusType] = {}
|
|
52
|
-
slack_cnt = 0
|
|
53
|
-
eq_P:list[int] = []
|
|
54
|
-
eq_Q:list[int] = []
|
|
55
|
-
self.Ps = []
|
|
56
|
-
self.Qs = []
|
|
57
|
-
for i, bus in enumerate(self.grid._busl):
|
|
58
|
-
fixp = fixq = True
|
|
59
|
-
p = -bus.Pd(_t)
|
|
60
|
-
q = -bus.Qd(_t)
|
|
61
|
-
for g in self.grid.GensAtBus(bus.ID):
|
|
62
|
-
if not g.FixedP: fixp = False
|
|
63
|
-
else:
|
|
64
|
-
assert g.P is not None
|
|
65
|
-
if isinstance(g.P, TimeFunc): p += g.P(_t)
|
|
66
|
-
else: p += g.P
|
|
67
|
-
if not g.FixedQ: fixq = False
|
|
68
|
-
else:
|
|
69
|
-
assert g.Q is not None
|
|
70
|
-
if isinstance(g.Q, TimeFunc): q += g.Q(_t)
|
|
71
|
-
else: q += g.Q
|
|
72
|
-
if bus.FixedV:
|
|
73
|
-
if fixp and fixq:
|
|
74
|
-
raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
|
|
75
|
-
elif fixp:
|
|
76
|
-
busType[bus.ID] = BusType.PV
|
|
77
|
-
eq_P.append(i)
|
|
78
|
-
elif fixq:
|
|
79
|
-
raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
|
|
80
|
-
else:
|
|
81
|
-
busType[bus.ID] = BusType.Slack
|
|
82
|
-
slack_cnt += 1
|
|
83
|
-
if slack_cnt > 1:
|
|
84
|
-
raise ValueError('Only one slack bus is allowed')
|
|
85
|
-
else:
|
|
86
|
-
if fixp and fixq:
|
|
87
|
-
busType[bus.ID] = BusType.PQ
|
|
88
|
-
bus.V = 1.0
|
|
89
|
-
eq_P.append(i)
|
|
90
|
-
eq_Q.append(i)
|
|
91
|
-
elif fixp:
|
|
92
|
-
raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
|
|
93
|
-
elif fixq:
|
|
94
|
-
raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
|
|
95
|
-
else:
|
|
96
|
-
raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
|
|
97
|
-
self.Ps.append(p)
|
|
98
|
-
self.Qs.append(q)
|
|
99
|
-
self.busType = busType
|
|
100
|
-
if slack_cnt == 0:
|
|
101
|
-
raise ValueError('No slack bus is found')
|
|
102
|
-
return eq_P + eq_Q, len(eq_P)
|
|
103
|
-
|
|
104
|
-
def dt(self, i:int, j:int) -> float:
|
|
105
|
-
return self.grid._busl[i].theta -self.grid._busl[j].theta
|
|
106
|
-
|
|
107
|
-
def V(self, i:int) -> float:
|
|
108
|
-
r = self.grid._busl[i].V
|
|
109
|
-
assert isinstance(r, float)
|
|
110
|
-
return r
|
|
111
|
-
|
|
112
|
-
def P(self,i:int):
|
|
113
|
-
return self.V(i)*sum(self.V(j)*(
|
|
114
|
-
self.G[i,j]*math.cos(self.dt(i,j))+
|
|
115
|
-
self.B[i,j]*math.sin(self.dt(i,j))
|
|
116
|
-
) for j in range(self.m))
|
|
117
|
-
|
|
118
|
-
def Q(self,i:int):
|
|
119
|
-
return self.V(i)*sum(self.V(j)*(
|
|
120
|
-
self.G[i,j]*math.sin(self.dt(i,j))-
|
|
121
|
-
self.B[i,j]*math.cos(self.dt(i,j))
|
|
122
|
-
) for j in range(self.m))
|
|
123
|
-
|
|
124
|
-
def H(self, i:int, j:int) -> float:
|
|
125
|
-
if i == j: return self.Q(i)+self.V(i)**2*self.B[i,i]
|
|
126
|
-
return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
|
|
127
|
-
|
|
128
|
-
def N(self, i:int, j:int) -> float:
|
|
129
|
-
if i == j: return -self.P(i)-self.V(i)**2*self.G[i,i]
|
|
130
|
-
return -self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
|
|
131
|
-
|
|
132
|
-
def M(self, i:int, j:int) -> float:
|
|
133
|
-
if i == j: return -self.P(i)+self.V(i)**2*self.G[i,i]
|
|
134
|
-
return self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
|
|
135
|
-
|
|
136
|
-
def L(self, i:int, j:int) -> float:
|
|
137
|
-
if i == j: return -self.Q(i)+self.V(i)**2*self.B[i,i]
|
|
138
|
-
return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
|
|
139
|
-
|
|
140
|
-
def _solve(self) -> int:
|
|
141
|
-
cnt = 0
|
|
142
|
-
while cnt<self.max_iter:
|
|
143
|
-
y = np.zeros(self.n, dtype=np.float64)
|
|
144
|
-
for i, b in enumerate(self.eqs):
|
|
145
|
-
y[i] = self.Ps[b] - self.P(b) if i < self.n_P else self.Qs[b] - self.Q(b)
|
|
146
|
-
if np.abs(y).max() < self.eps:
|
|
147
|
-
break
|
|
148
|
-
cnt += 1
|
|
149
|
-
J = np.zeros((self.n, self.n), dtype=np.float64)
|
|
150
|
-
for i, b0 in enumerate(self.eqs):
|
|
151
|
-
for j, b1 in enumerate(self.eqs):
|
|
152
|
-
if i < self.n_P and j <self. n_P: #dp/dθ
|
|
153
|
-
J[i,j] = self.H(b0, b1)
|
|
154
|
-
elif i < self.n_P and j >= self.n_P: #V*dp/dV
|
|
155
|
-
J[i,j] = self.N(b0, b1)
|
|
156
|
-
elif i >= self.n_P and j < self.n_P: #dp/dV
|
|
157
|
-
J[i,j] = self.M(b0, b1)
|
|
158
|
-
elif i >= self.n_P and j >= self.n_P: #V*dq/dV
|
|
159
|
-
J[i,j] = self.L(b0, b1)
|
|
160
|
-
x = np.linalg.solve(J, -y)
|
|
161
|
-
for i, (x0, b) in enumerate(zip(x, self.eqs)):
|
|
162
|
-
if i < self.n_P: # Δθ
|
|
163
|
-
self.grid._busl[b].theta += x0
|
|
164
|
-
else: # ΔU/U
|
|
165
|
-
self.grid._busl[b].V += self.V(b) * x0
|
|
166
|
-
if cnt >= self.max_iter:
|
|
167
|
-
raise ValueError("Bad solution")
|
|
168
|
-
return cnt
|
|
169
10
|
|
|
170
|
-
def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
|
|
171
|
-
'''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
|
|
172
|
-
self.eqs, self.n_P = self.CheckBusType(_t)
|
|
173
|
-
self.n = len(self.eqs)
|
|
174
|
-
self.m = len(self.grid._bnames)
|
|
175
|
-
try:
|
|
176
|
-
self._solve()
|
|
177
|
-
except ValueError:
|
|
178
|
-
return GridSolveResult.Failed, -1
|
|
179
|
-
for l in self.grid.Lines:
|
|
180
|
-
vi = self.grid.Bus(l.fBus).V_cpx
|
|
181
|
-
vj = self.grid.Bus(l.tBus).V_cpx
|
|
182
|
-
assert vi is not None and vj is not None
|
|
183
|
-
i = (vi-vj)/l.Z
|
|
184
|
-
l.I = abs(i)
|
|
185
|
-
s = vi*i.conjugate()
|
|
186
|
-
l.P = s.real
|
|
187
|
-
l.Q = s.imag
|
|
188
|
-
return GridSolveResult.OK, 0
|
|
189
|
-
|
|
190
|
-
|
|
191
11
|
@dataclass
|
|
192
12
|
class LoadReduceModule:
|
|
193
13
|
'''Load Reduce module'''
|
|
@@ -197,20 +17,45 @@ class LoadReduceModule:
|
|
|
197
17
|
|
|
198
18
|
class DistFlowSolver(SolverBase):
|
|
199
19
|
'''DistFlow solver'''
|
|
200
|
-
def __init__(self, grid:Grid, eps:float = 1e-6,
|
|
201
|
-
default_saveto:str = DEFAULT_SAVETO, /, * ,
|
|
202
|
-
mlrp:float = 0.5):
|
|
20
|
+
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, /, *, mlrp:float = 0.5):
|
|
203
21
|
'''
|
|
204
22
|
Initialize
|
|
205
23
|
grid: Grid object
|
|
206
24
|
default_saveto: Default path to save the results
|
|
207
25
|
mlrp: Maximum proportion of load reduction
|
|
208
|
-
crp: Penalty of PV or solar curtailment rate, $/pu
|
|
209
26
|
'''
|
|
210
27
|
super().__init__(grid, eps, default_saveto)
|
|
211
|
-
self.
|
|
28
|
+
self._decb:dict[BusID, LoadReduceModule] = {}
|
|
212
29
|
self.C = 1e9
|
|
213
|
-
self.
|
|
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
|
|
214
59
|
|
|
215
60
|
def solve(self, _t: int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
|
|
216
61
|
'''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
|
|
@@ -275,12 +120,23 @@ class DistFlowSolver(SolverBase):
|
|
|
275
120
|
# Bind GEN vars to Bus
|
|
276
121
|
pg: dict[str, list[VF]] = {bus.ID: [] for bus in self.grid.Buses}
|
|
277
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}
|
|
278
125
|
for g in self.grid.Gens:
|
|
279
126
|
pg[g.BusID].append(pg0[g.ID])
|
|
280
127
|
qg[g.BusID].append(qg0[g.ID])
|
|
281
128
|
for p in self.grid.PVWinds:
|
|
282
129
|
pg[p.BusID].append(pvwp[p.ID])
|
|
283
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
|
|
284
140
|
|
|
285
141
|
# Create BUS vars
|
|
286
142
|
has_slack = 0
|
|
@@ -325,7 +181,7 @@ class DistFlowSolver(SolverBase):
|
|
|
325
181
|
self.grid.Lines}
|
|
326
182
|
|
|
327
183
|
Pdec = {bus: model.addVar(name=f"Pdec_{bus}", vtype='C',
|
|
328
|
-
lb=0, ub=lim.Limit(_t) * self.
|
|
184
|
+
lb=0, ub=lim.Limit(_t) * self._mlrp) for bus,lim in self._decb.items()}
|
|
329
185
|
|
|
330
186
|
# ----------Constraints-----------
|
|
331
187
|
Pcons: dict[str, Constr] = {}
|
|
@@ -335,11 +191,11 @@ class DistFlowSolver(SolverBase):
|
|
|
335
191
|
j = bus.ID
|
|
336
192
|
flow_in = self.grid.LinesOfTBus(j)
|
|
337
193
|
flow_out = self.grid.LinesOfFBus(j)
|
|
338
|
-
dec = Pdec[j] if j in self.
|
|
194
|
+
dec = Pdec[j] if j in self._decb else 0
|
|
339
195
|
Pcons[j] = model.addConstr(Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in) + Qs(pg[j]) == Qs(
|
|
340
|
-
P[ln.ID] for ln in flow_out) +
|
|
196
|
+
P[ln.ID] for ln in flow_out) + pd[j] - dec, f"Pcons_{j}")
|
|
341
197
|
Qcons[j] = model.addConstr(Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in) + Qs(qg[j]) == Qs(
|
|
342
|
-
Q[ln.ID] for ln in flow_out) +
|
|
198
|
+
Q[ln.ID] for ln in flow_out) + qd[j], f"Qcons_{j}")
|
|
343
199
|
|
|
344
200
|
for line in self.grid.Lines:
|
|
345
201
|
i, j = line.pair
|
|
@@ -391,9 +247,10 @@ class DistFlowSolver(SolverBase):
|
|
|
391
247
|
for p in self.grid.PVWinds:
|
|
392
248
|
p._pr = pvwp[p.ID].X
|
|
393
249
|
p._qr = pvwq[p.ID].X
|
|
394
|
-
|
|
250
|
+
pgen = p.P(_t)
|
|
251
|
+
p._cr = 1 - p._pr / pgen if pgen > 0 else 0
|
|
395
252
|
|
|
396
|
-
for bus,lim in self.
|
|
253
|
+
for bus,lim in self._decb.items():
|
|
397
254
|
lim.Reduction = Pdec[bus].X
|
|
398
255
|
if lim.Reduction < 1e-8: lim.Reduction = 0
|
|
399
256
|
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import math
|
|
3
|
+
from .solbase import *
|
|
4
|
+
|
|
5
|
+
class BusType(IntEnum):
|
|
6
|
+
PQ = 0
|
|
7
|
+
PV = 1
|
|
8
|
+
Slack = 2
|
|
9
|
+
|
|
10
|
+
class NewtonSolver(SolverBase):
|
|
11
|
+
def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100):
|
|
12
|
+
super().__init__(grid, eps, default_saveto)
|
|
13
|
+
self.Y = grid.YMat()
|
|
14
|
+
self.G, self.B = self.Y.real, self.Y.imag
|
|
15
|
+
self.max_iter = max_iter
|
|
16
|
+
|
|
17
|
+
def CheckBusType(self, _t:int):
|
|
18
|
+
'''Check the bus type'''
|
|
19
|
+
busType:dict[BusID, BusType] = {}
|
|
20
|
+
slack_cnt = 0
|
|
21
|
+
eq_P:list[int] = []
|
|
22
|
+
eq_Q:list[int] = []
|
|
23
|
+
self.Ps = []
|
|
24
|
+
self.Qs = []
|
|
25
|
+
for i, bus in enumerate(self.grid._busl):
|
|
26
|
+
fixp = fixq = True
|
|
27
|
+
p = -bus.Pd(_t)
|
|
28
|
+
q = -bus.Qd(_t)
|
|
29
|
+
for g in self.grid.GensAtBus(bus.ID):
|
|
30
|
+
if not g.FixedP: fixp = False
|
|
31
|
+
else:
|
|
32
|
+
assert g.P is not None
|
|
33
|
+
if isinstance(g.P, TimeFunc): p += g.P(_t)
|
|
34
|
+
else: p += g.P
|
|
35
|
+
if not g.FixedQ: fixq = False
|
|
36
|
+
else:
|
|
37
|
+
assert g.Q is not None
|
|
38
|
+
if isinstance(g.Q, TimeFunc): q += g.Q(_t)
|
|
39
|
+
else: q += g.Q
|
|
40
|
+
if bus.FixedV:
|
|
41
|
+
if fixp and fixq:
|
|
42
|
+
raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
|
|
43
|
+
elif fixp:
|
|
44
|
+
busType[bus.ID] = BusType.PV
|
|
45
|
+
eq_P.append(i)
|
|
46
|
+
elif fixq:
|
|
47
|
+
raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
|
|
48
|
+
else:
|
|
49
|
+
busType[bus.ID] = BusType.Slack
|
|
50
|
+
slack_cnt += 1
|
|
51
|
+
if slack_cnt > 1:
|
|
52
|
+
raise ValueError('Only one slack bus is allowed')
|
|
53
|
+
else:
|
|
54
|
+
if fixp and fixq:
|
|
55
|
+
busType[bus.ID] = BusType.PQ
|
|
56
|
+
bus.V = 1.0
|
|
57
|
+
eq_P.append(i)
|
|
58
|
+
eq_Q.append(i)
|
|
59
|
+
elif fixp:
|
|
60
|
+
raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
|
|
61
|
+
elif fixq:
|
|
62
|
+
raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
|
|
63
|
+
else:
|
|
64
|
+
raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
|
|
65
|
+
self.Ps.append(p)
|
|
66
|
+
self.Qs.append(q)
|
|
67
|
+
self.busType = busType
|
|
68
|
+
if slack_cnt == 0:
|
|
69
|
+
raise ValueError('No slack bus is found')
|
|
70
|
+
return eq_P + eq_Q, len(eq_P)
|
|
71
|
+
|
|
72
|
+
def dt(self, i:int, j:int) -> float:
|
|
73
|
+
return self.grid._busl[i].theta -self.grid._busl[j].theta
|
|
74
|
+
|
|
75
|
+
def V(self, i:int) -> float:
|
|
76
|
+
r = self.grid._busl[i].V
|
|
77
|
+
assert isinstance(r, float)
|
|
78
|
+
return r
|
|
79
|
+
|
|
80
|
+
def P(self,i:int):
|
|
81
|
+
return self.V(i)*sum(self.V(j)*(
|
|
82
|
+
self.G[i,j]*math.cos(self.dt(i,j))+
|
|
83
|
+
self.B[i,j]*math.sin(self.dt(i,j))
|
|
84
|
+
) for j in range(self.m))
|
|
85
|
+
|
|
86
|
+
def Q(self,i:int):
|
|
87
|
+
return self.V(i)*sum(self.V(j)*(
|
|
88
|
+
self.G[i,j]*math.sin(self.dt(i,j))-
|
|
89
|
+
self.B[i,j]*math.cos(self.dt(i,j))
|
|
90
|
+
) for j in range(self.m))
|
|
91
|
+
|
|
92
|
+
def H(self, i:int, j:int) -> float:
|
|
93
|
+
if i == j: return self.Q(i)+self.V(i)**2*self.B[i,i]
|
|
94
|
+
return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
|
|
95
|
+
|
|
96
|
+
def N(self, i:int, j:int) -> float:
|
|
97
|
+
if i == j: return -self.P(i)-self.V(i)**2*self.G[i,i]
|
|
98
|
+
return -self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
|
|
99
|
+
|
|
100
|
+
def M(self, i:int, j:int) -> float:
|
|
101
|
+
if i == j: return -self.P(i)+self.V(i)**2*self.G[i,i]
|
|
102
|
+
return self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
|
|
103
|
+
|
|
104
|
+
def L(self, i:int, j:int) -> float:
|
|
105
|
+
if i == j: return -self.Q(i)+self.V(i)**2*self.B[i,i]
|
|
106
|
+
return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
|
|
107
|
+
|
|
108
|
+
def _solve(self) -> int:
|
|
109
|
+
cnt = 0
|
|
110
|
+
while cnt<self.max_iter:
|
|
111
|
+
y = np.zeros(self.n, dtype=np.float64)
|
|
112
|
+
for i, b in enumerate(self.eqs):
|
|
113
|
+
y[i] = self.Ps[b] - self.P(b) if i < self.n_P else self.Qs[b] - self.Q(b)
|
|
114
|
+
if np.abs(y).max() < self.eps:
|
|
115
|
+
break
|
|
116
|
+
cnt += 1
|
|
117
|
+
J = np.zeros((self.n, self.n), dtype=np.float64)
|
|
118
|
+
for i, b0 in enumerate(self.eqs):
|
|
119
|
+
for j, b1 in enumerate(self.eqs):
|
|
120
|
+
if i < self.n_P and j <self. n_P: #dp/dθ
|
|
121
|
+
J[i,j] = self.H(b0, b1)
|
|
122
|
+
elif i < self.n_P and j >= self.n_P: #V*dp/dV
|
|
123
|
+
J[i,j] = self.N(b0, b1)
|
|
124
|
+
elif i >= self.n_P and j < self.n_P: #dp/dV
|
|
125
|
+
J[i,j] = self.M(b0, b1)
|
|
126
|
+
elif i >= self.n_P and j >= self.n_P: #V*dq/dV
|
|
127
|
+
J[i,j] = self.L(b0, b1)
|
|
128
|
+
x = np.linalg.solve(J, -y)
|
|
129
|
+
for i, (x0, b) in enumerate(zip(x, self.eqs)):
|
|
130
|
+
if i < self.n_P: # Δθ
|
|
131
|
+
self.grid._busl[b].theta += x0
|
|
132
|
+
else: # ΔU/U
|
|
133
|
+
self.grid._busl[b].V += self.V(b) * x0
|
|
134
|
+
if cnt >= self.max_iter:
|
|
135
|
+
raise ValueError("Bad solution")
|
|
136
|
+
return cnt
|
|
137
|
+
|
|
138
|
+
def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
|
|
139
|
+
'''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
|
|
140
|
+
self.eqs, self.n_P = self.CheckBusType(_t)
|
|
141
|
+
self.n = len(self.eqs)
|
|
142
|
+
self.m = len(self.grid._bnames)
|
|
143
|
+
try:
|
|
144
|
+
self._solve()
|
|
145
|
+
except ValueError:
|
|
146
|
+
return GridSolveResult.Failed, -1
|
|
147
|
+
for l in self.grid.Lines:
|
|
148
|
+
vi = self.grid.Bus(l.fBus).V_cpx
|
|
149
|
+
vj = self.grid.Bus(l.tBus).V_cpx
|
|
150
|
+
assert vi is not None and vj is not None
|
|
151
|
+
i = (vi-vj)/l.Z
|
|
152
|
+
l.I = abs(i)
|
|
153
|
+
s = vi*i.conjugate()
|
|
154
|
+
l.P = s.real
|
|
155
|
+
l.Q = s.imag
|
|
156
|
+
return GridSolveResult.OK, 0
|
|
@@ -3,6 +3,7 @@ from feasytools import TimeFunc, SegFunc, ConstFunc, makeFunc
|
|
|
3
3
|
from xml.etree.ElementTree import Element
|
|
4
4
|
from typing import TextIO
|
|
5
5
|
|
|
6
|
+
|
|
6
7
|
FloatVar = Optional[float]
|
|
7
8
|
NFloat = Optional[float]
|
|
8
9
|
FloatLike = Union[int, float, TimeFunc, 'list[tuple[int, float]]']
|
|
@@ -19,12 +20,12 @@ def Float2Func(v: FloatLike) -> TimeFunc:
|
|
|
19
20
|
return SegFunc(v)
|
|
20
21
|
|
|
21
22
|
def Func2Elem(f: TimeFunc, tag: str, mul:float = 1, unit:str = "") -> Element:
|
|
22
|
-
e = Element(tag)
|
|
23
23
|
if isinstance(f, ConstFunc):
|
|
24
|
-
e
|
|
24
|
+
e = Element(tag,{
|
|
25
|
+
"const": str(f(0)*mul) + unit
|
|
26
|
+
})
|
|
25
27
|
elif isinstance(f, SegFunc):
|
|
26
|
-
|
|
27
|
-
e.append(Element("item", {"time": str(t), "value": f"{v*mul:.4f}{unit}"}))
|
|
28
|
+
e = f.toXMLNode(tag, "item", "time", "value", lambda t, v: f"{v*mul:.4f}{unit}")
|
|
28
29
|
else:
|
|
29
30
|
raise ValueError("Unknown function type")
|
|
30
31
|
return e
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: fpowerkit
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: A Distflow PDN solver based on Gurobi.
|
|
5
5
|
Author: fmy_xfk
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -9,7 +9,7 @@ Classifier: Operating System :: OS Independent
|
|
|
9
9
|
Requires-Python: >=3.8
|
|
10
10
|
Description-Content-Type: text/markdown
|
|
11
11
|
License-File: LICENSE
|
|
12
|
-
Requires-Dist: feasytools>=0.0.
|
|
12
|
+
Requires-Dist: feasytools>=0.0.21
|
|
13
13
|
Requires-Dist: gurobipy>=9.1.0
|
|
14
14
|
Requires-Dist: numpy>=1.20.0
|
|
15
15
|
|
|
@@ -4,11 +4,14 @@ setup.py
|
|
|
4
4
|
fpowerkit/__init__.py
|
|
5
5
|
fpowerkit/bus.py
|
|
6
6
|
fpowerkit/cases.py
|
|
7
|
+
fpowerkit/ess.py
|
|
7
8
|
fpowerkit/gen.py
|
|
8
9
|
fpowerkit/grid.py
|
|
9
10
|
fpowerkit/line.py
|
|
10
11
|
fpowerkit/pvwind.py
|
|
11
|
-
fpowerkit/
|
|
12
|
+
fpowerkit/solbase.py
|
|
13
|
+
fpowerkit/soldist.py
|
|
14
|
+
fpowerkit/solnt.py
|
|
12
15
|
fpowerkit/utils.py
|
|
13
16
|
fpowerkit.egg-info/PKG-INFO
|
|
14
17
|
fpowerkit.egg-info/SOURCES.txt
|
|
@@ -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.
|
|
8
|
+
version="0.1.2",
|
|
9
9
|
author="fmy_xfk",
|
|
10
10
|
packages=find_packages(),
|
|
11
11
|
description="A Distflow PDN solver based on Gurobi.",
|
|
@@ -17,5 +17,5 @@ setup(
|
|
|
17
17
|
"Operating System :: OS Independent",
|
|
18
18
|
],
|
|
19
19
|
python_requires=">=3.8",
|
|
20
|
-
install_requires=["feasytools>=0.0.
|
|
20
|
+
install_requires=["feasytools>=0.0.21", "gurobipy>=9.1.0", "numpy>=1.20.0"],
|
|
21
21
|
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|