fpowerkit 0.0.1__tar.gz → 0.0.3__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.0.1 → fpowerkit-0.0.3}/PKG-INFO +3 -3
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/README.md +1 -1
- fpowerkit-0.0.3/fpowerkit/grid.py +657 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/fpowerkit.egg-info/PKG-INFO +3 -3
- fpowerkit-0.0.3/fpowerkit.egg-info/requires.txt +2 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/setup.py +2 -2
- fpowerkit-0.0.1/fpowerkit/grid.py +0 -487
- fpowerkit-0.0.1/fpowerkit.egg-info/requires.txt +0 -2
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/LICENSE +0 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/fpowerkit/__init__.py +0 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/fpowerkit.egg-info/SOURCES.txt +0 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/fpowerkit.egg-info/dependency_links.txt +0 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/fpowerkit.egg-info/top_level.txt +0 -0
- {fpowerkit-0.0.1 → fpowerkit-0.0.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: fpowerkit
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
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.18
|
|
13
13
|
Requires-Dist: gurobipy>=9.1.0
|
|
14
14
|
|
|
15
15
|
# FPowerKit 配电网运算组件
|
|
@@ -22,7 +22,7 @@ Requires-Dist: gurobipy>=9.1.0
|
|
|
22
22
|
|
|
23
23
|
输入以下命令开始仿真:
|
|
24
24
|
```bash
|
|
25
|
-
python main.py -g cases/ieee33.zip
|
|
25
|
+
python main.py -g cases/ieee33.grid.zip
|
|
26
26
|
```
|
|
27
27
|
`ieee33`描述了IEEE 33节点配电网模型。换成`nodes3`则是一个极简版3节点辐射形配电网模型,结构如下:
|
|
28
28
|
|
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
import zipfile
|
|
2
|
+
from io import BytesIO, TextIOWrapper
|
|
3
|
+
from typing import Any, TextIO, Iterable, Optional, Union
|
|
4
|
+
from xml.etree.ElementTree import Element, ElementTree
|
|
5
|
+
from feasytools import TimeFunc, SegFunc, ConstFunc, makeFunc
|
|
6
|
+
from gurobipy import Model, GRB, quicksum, Var, Constr
|
|
7
|
+
|
|
8
|
+
FloatVar = Optional[float]
|
|
9
|
+
FloatLike = Union[int, float, TimeFunc, 'list[tuple[int, float]]']
|
|
10
|
+
Qs = quicksum
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _float2func(v: FloatLike) -> TimeFunc:
|
|
14
|
+
if isinstance(v, (float, int)):
|
|
15
|
+
return ConstFunc(v)
|
|
16
|
+
elif isinstance(v, TimeFunc):
|
|
17
|
+
return v
|
|
18
|
+
else:
|
|
19
|
+
return SegFunc(v)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _tfv(s: FloatVar): return "<unsolved>" if s is None else str(s)
|
|
23
|
+
|
|
24
|
+
def _readVal(s: str) -> 'tuple[float, str]':
|
|
25
|
+
if s.endswith("pu"):
|
|
26
|
+
return float(s[:-2]), "pu"
|
|
27
|
+
elif s.endswith("kVA"):
|
|
28
|
+
return float(s[:-3]), "kVA"
|
|
29
|
+
elif s.endswith("kvar"):
|
|
30
|
+
return float(s[:-4]), "kvar"
|
|
31
|
+
elif s.endswith("kW"):
|
|
32
|
+
return float(s[:-2]), "kW"
|
|
33
|
+
elif s.endswith("MVA"):
|
|
34
|
+
return float(s[:-3]), "MVA"
|
|
35
|
+
elif s.endswith("Mvar"):
|
|
36
|
+
return float(s[:-4]), "Mvar"
|
|
37
|
+
elif s.endswith("MW"):
|
|
38
|
+
return float(s[:-2]), "MW"
|
|
39
|
+
elif s.endswith("kV"):
|
|
40
|
+
return float(s[:-2]), "kV"
|
|
41
|
+
elif s.endswith("V"):
|
|
42
|
+
return float(s[:-1]), "V"
|
|
43
|
+
elif s.endswith("kA"):
|
|
44
|
+
return float(s[:-2]), "kA"
|
|
45
|
+
elif s.endswith("ohm"):
|
|
46
|
+
return float(s[:-3]), "ohm"
|
|
47
|
+
elif s.endswith("kWh"):
|
|
48
|
+
return float(s[:-3]), "kWh"
|
|
49
|
+
else:
|
|
50
|
+
return float(s), ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _readFloatLike(e: Element, sb_mva:float, ub_kv:float) -> FloatLike:
|
|
54
|
+
def _valconv(v:FloatLike, u:str) -> FloatLike:
|
|
55
|
+
if u == "pu":
|
|
56
|
+
return v
|
|
57
|
+
elif u == "kVA":
|
|
58
|
+
return v / (sb_mva * 1000)
|
|
59
|
+
elif u == "kvar":
|
|
60
|
+
return v / (sb_mva * 1000)
|
|
61
|
+
elif u == "kW":
|
|
62
|
+
return v / (sb_mva * 1000)
|
|
63
|
+
elif u == "MVA":
|
|
64
|
+
return v / sb_mva
|
|
65
|
+
elif u == "Mvar":
|
|
66
|
+
return v / sb_mva
|
|
67
|
+
elif u == "MW":
|
|
68
|
+
return v / sb_mva
|
|
69
|
+
elif u == "kV":
|
|
70
|
+
return v / ub_kv
|
|
71
|
+
elif u == "V":
|
|
72
|
+
return v / (ub_kv * 1000)
|
|
73
|
+
elif u == "kA":
|
|
74
|
+
return v / (sb_mva / (ub_kv * 3 ** 0.5))
|
|
75
|
+
elif u == "ohm":
|
|
76
|
+
return v * ub_kv ** 2 / sb_mva
|
|
77
|
+
elif u == "$/puh" or u == "$/puh2" or u == "$":
|
|
78
|
+
return v
|
|
79
|
+
elif u == "$/kWh":
|
|
80
|
+
return v * (sb_mva * 1000)
|
|
81
|
+
elif u == "$/MWh":
|
|
82
|
+
return v * sb_mva
|
|
83
|
+
elif u == "$/kWh2":
|
|
84
|
+
return v * (sb_mva * 1000 * sb_mva * 1000)
|
|
85
|
+
elif u == "$/MWh2":
|
|
86
|
+
return v * (sb_mva * sb_mva)
|
|
87
|
+
else:
|
|
88
|
+
return v
|
|
89
|
+
if "const" in e.attrib:
|
|
90
|
+
v, u = _readVal(e.attrib["const"])
|
|
91
|
+
if u == "": u = e.attrib.get("unit","")
|
|
92
|
+
return _valconv(v, u)
|
|
93
|
+
else:
|
|
94
|
+
repeat = int(e.attrib.get("repeat", "1"))
|
|
95
|
+
period = int(e.attrib.get("period", "0"))
|
|
96
|
+
sf = SegFunc()
|
|
97
|
+
for itm in e:
|
|
98
|
+
time = int(itm.attrib["time"])
|
|
99
|
+
v, u = _readVal(itm.attrib["value"])
|
|
100
|
+
sf.add(time, _valconv(v, u))
|
|
101
|
+
return sf.repeat(repeat, period)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class Bus:
|
|
105
|
+
ID: str
|
|
106
|
+
V: FloatVar # pu
|
|
107
|
+
Pd: TimeFunc # pu
|
|
108
|
+
Qd: TimeFunc # pu
|
|
109
|
+
ShadowPrice: FloatVar # Shadow price of generators on this bus,$/pu power
|
|
110
|
+
Lat: Optional[float]
|
|
111
|
+
Lon: Optional[float]
|
|
112
|
+
|
|
113
|
+
def __init__(self, id: str, pd_pu: FloatLike, qd_pu: FloatLike,
|
|
114
|
+
lat: Optional[float] = None, lon: Optional[float] = None, v_pu: Optional[float] = None):
|
|
115
|
+
self.ID = id
|
|
116
|
+
self.V = v_pu
|
|
117
|
+
self.Pd = _float2func(pd_pu)
|
|
118
|
+
self.Qd = _float2func(qd_pu)
|
|
119
|
+
self.ShadowPrice = None
|
|
120
|
+
self.Lat = lat
|
|
121
|
+
self.Lon = lon
|
|
122
|
+
|
|
123
|
+
def __repr__(self):
|
|
124
|
+
return f"Bus(id='{self.ID}', v_pu={self.V}, pd_pu={self.Pd}, qd_pu={self.Qd}, lat={self.Lat}, lon={self.Lon})"
|
|
125
|
+
|
|
126
|
+
def __str__(self):
|
|
127
|
+
return repr(self)
|
|
128
|
+
|
|
129
|
+
def str_t(self, _t: int, /):
|
|
130
|
+
return f"Bus(id='{self.ID}', v_pu={_tfv(self.V)}, pd_pu={self.Pd(_t)}, qd_pu={self.Qd(_t)}, lat={self.Lat}, lon={self.Lon})"
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def position(self) -> 'tuple[float, float]':
|
|
134
|
+
'''Return the position of the bus, (lat, lon)'''
|
|
135
|
+
return self.Lat, self.Lon
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def fromXML(node: 'Element', Sb_MVA: float, Ub_kV: float):
|
|
139
|
+
id = node.attrib["ID"]
|
|
140
|
+
p = _readFloatLike(node.find("Pd"), Sb_MVA, Ub_kV)
|
|
141
|
+
q = _readFloatLike(node.find("Qd"), Sb_MVA, Ub_kV)
|
|
142
|
+
lat = node.attrib.get("Lat", None)
|
|
143
|
+
lon = node.attrib.get("Lon", None)
|
|
144
|
+
return Bus(id, p, q, lat, lon)
|
|
145
|
+
|
|
146
|
+
@staticmethod
|
|
147
|
+
def load(fp: TextIO, Sb_MVA: float, loop: str = "0,0"):
|
|
148
|
+
ret = loop.split(",")
|
|
149
|
+
assert len(ret) == 2
|
|
150
|
+
loop_period = int(ret[0])
|
|
151
|
+
loop_times = int(ret[1])
|
|
152
|
+
data = fp.readlines()
|
|
153
|
+
hl = data[0].split(',')
|
|
154
|
+
if hl[0].strip() != "time": raise ValueError("Bad format of bus CSV file")
|
|
155
|
+
tl = [int(x.strip()) for x in hl[1:]]
|
|
156
|
+
if loop_period > 0 and loop_times > 0:
|
|
157
|
+
tl_old = tl.copy()
|
|
158
|
+
for i in range(loop_times - 1):
|
|
159
|
+
tl.extend([x + loop_period * (i + 1) for x in tl_old])
|
|
160
|
+
else:
|
|
161
|
+
tl_old = tl
|
|
162
|
+
|
|
163
|
+
def parseline(ln: str,i:int):
|
|
164
|
+
ret = ln.split(',')
|
|
165
|
+
if len(ret) != len(tl_old) + 1: raise ValueError(f"Bad line length at line {i} in bus CSV file")
|
|
166
|
+
p: 'list[float]' = []
|
|
167
|
+
q: 'list[float]' = []
|
|
168
|
+
for x in ret[1:]:
|
|
169
|
+
p0, q0 = x.strip().split('|')
|
|
170
|
+
p.append(float(p0) / Sb_MVA)
|
|
171
|
+
q.append(float(q0) / Sb_MVA)
|
|
172
|
+
if loop_period > 0 and loop_times > 0:
|
|
173
|
+
p = p * loop_times
|
|
174
|
+
q = q * loop_times
|
|
175
|
+
bn = ret[0].strip().split('|')
|
|
176
|
+
if len(bn) == 1:
|
|
177
|
+
return bn[0], makeFunc(tl, p), makeFunc(tl, q)
|
|
178
|
+
elif len(bn) == 3:
|
|
179
|
+
return bn[0], makeFunc(tl, p), makeFunc(tl, q), float(bn[1]), float(bn[2])
|
|
180
|
+
else:
|
|
181
|
+
raise ValueError(f"Bad bus name format at line {i} in bus CSV file, should be 'name' or 'name|lat|lon'")
|
|
182
|
+
|
|
183
|
+
return [Bus(*parseline(ln,i)) for i,ln in enumerate(data[1:],start=1)]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class Line:
|
|
187
|
+
ID: str
|
|
188
|
+
fBus: str
|
|
189
|
+
tBus: str
|
|
190
|
+
R: float # pu
|
|
191
|
+
X: float # pu
|
|
192
|
+
P: FloatVar # pu
|
|
193
|
+
Q: FloatVar # pu
|
|
194
|
+
I: FloatVar # pu
|
|
195
|
+
|
|
196
|
+
def __init__(self, id: str, fbus: str, tbus: str, r_pu: float, x_pu: float,
|
|
197
|
+
i_pu: Optional[float] = None, p_pu: Optional[float] = None, q_pu: Optional[float] = None):
|
|
198
|
+
'''
|
|
199
|
+
Initialize
|
|
200
|
+
id: Line ID
|
|
201
|
+
fbus: ID of start bus
|
|
202
|
+
tbus: ID of end bus
|
|
203
|
+
r_pu: Resistance, pu
|
|
204
|
+
x_pu: Reactance, pu
|
|
205
|
+
'''
|
|
206
|
+
self.ID = id
|
|
207
|
+
self.fBus = fbus
|
|
208
|
+
self.tBus = tbus
|
|
209
|
+
self.R = r_pu
|
|
210
|
+
self.X = x_pu
|
|
211
|
+
self.I = i_pu
|
|
212
|
+
self.P = p_pu
|
|
213
|
+
self.Q = q_pu
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def pair(self):
|
|
217
|
+
'''Syntax candy of (self.fBus, self.tBus)'''
|
|
218
|
+
return (self.fBus, self.tBus)
|
|
219
|
+
|
|
220
|
+
def __repr__(self) -> str:
|
|
221
|
+
return (f"Line(id='{self.ID}', fbus='{self.fBus}', tbus='{self.tBus}', r_pu={self.R}, " +
|
|
222
|
+
f"x_pu={self.X}, i_pu={self.I}, p_pu={self.P}, q_pu={self.Q})")
|
|
223
|
+
|
|
224
|
+
def __str__(self) -> str:
|
|
225
|
+
return repr(self)
|
|
226
|
+
|
|
227
|
+
def str_t(self, _t: int, /) -> str:
|
|
228
|
+
return self.__str__()
|
|
229
|
+
|
|
230
|
+
@staticmethod
|
|
231
|
+
def load(fp: TextIO, Zb_Ohm: float = 1.0):
|
|
232
|
+
data = fp.readlines()
|
|
233
|
+
head = [x.strip() for x in data[0].split(',')]
|
|
234
|
+
if head != ["id", "fBus", "tBus", "R", "X"]:
|
|
235
|
+
raise ValueError("Bad line CSV format: Columns must be 'id,fBus,tBus,R,X' (case sensitive). ")
|
|
236
|
+
|
|
237
|
+
def parseline(ln: str):
|
|
238
|
+
(id, f, t, r, x) = (x.strip() for x in ln.split(','))
|
|
239
|
+
return id, f, t, float(r) / Zb_Ohm, float(x) / Zb_Ohm
|
|
240
|
+
|
|
241
|
+
return [Line(*parseline(ln)) for ln in data[1:]]
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def fromXML(node: 'Element', Zb_Ohm: float):
|
|
245
|
+
id = node.attrib["ID"]
|
|
246
|
+
f = node.attrib["From"]
|
|
247
|
+
t = node.attrib["To"]
|
|
248
|
+
r = float(node.attrib["R"]) / Zb_Ohm
|
|
249
|
+
x = float(node.attrib["X"]) / Zb_Ohm
|
|
250
|
+
return Line(id, f, t, r, x)
|
|
251
|
+
|
|
252
|
+
def toXMLNode(self) -> 'Element':
|
|
253
|
+
return Element("line", {
|
|
254
|
+
"ID": self.ID,
|
|
255
|
+
"From": self.fBus,
|
|
256
|
+
"To": self.tBus,
|
|
257
|
+
"R": str(self.R),
|
|
258
|
+
"X": str(self.X),
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
class Generator:
|
|
262
|
+
ID: str
|
|
263
|
+
BusID: str
|
|
264
|
+
Pmin: TimeFunc #pu
|
|
265
|
+
Pmax: TimeFunc #pu
|
|
266
|
+
P: FloatVar #pu
|
|
267
|
+
Qmin: TimeFunc #pu
|
|
268
|
+
Qmax: TimeFunc #pu
|
|
269
|
+
Q: FloatVar #pu
|
|
270
|
+
CostA: TimeFunc #$/(pu Power·h)**2
|
|
271
|
+
CostB: TimeFunc #$/pu Power·h
|
|
272
|
+
CostC: TimeFunc #$
|
|
273
|
+
|
|
274
|
+
def __init__(self, id: str, busid: str, pmin_pu: FloatLike, pmax_pu: FloatLike, qmin_pu: FloatLike, qmax_pu: FloatLike,
|
|
275
|
+
costA: FloatLike, costB: FloatLike, costC: FloatLike, P: Optional[float] = None, Q: Optional[float] = None):
|
|
276
|
+
'''
|
|
277
|
+
Initialize
|
|
278
|
+
id: Generator ID
|
|
279
|
+
busid: ID of the bus where the generator is located
|
|
280
|
+
pmin_pu: Minimal active power output, pu
|
|
281
|
+
pmax_pu: Maximal active power output, pu
|
|
282
|
+
qmin_pu: Minimal reactive power output, pu
|
|
283
|
+
qmax_pu: Maximal reactive power output, pu
|
|
284
|
+
costA: Secondary cost, $/(pu Power·h)**2
|
|
285
|
+
costB: Primary cost, $/pu Power·h
|
|
286
|
+
costC: Fixed cost, $
|
|
287
|
+
'''
|
|
288
|
+
self.ID = id
|
|
289
|
+
self.BusID = busid
|
|
290
|
+
self.P = P
|
|
291
|
+
self.Q = Q
|
|
292
|
+
self.Pmin = _float2func(pmin_pu)
|
|
293
|
+
self.Pmax = _float2func(pmax_pu)
|
|
294
|
+
self.Qmin = _float2func(qmin_pu)
|
|
295
|
+
self.Qmax = _float2func(qmax_pu)
|
|
296
|
+
self.CostA = _float2func(costA)
|
|
297
|
+
self.CostB = _float2func(costB)
|
|
298
|
+
self.CostC = _float2func(costC)
|
|
299
|
+
self.CostShadow = None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def __repr__(self) -> str:
|
|
303
|
+
return (f"Generator(id='{self.ID}', busid='{self.BusID}', P={self.P}, Q={self.Q}, " +
|
|
304
|
+
f"pmin_pu={self.Pmin}, pmax_pu={self.Pmax}, qmin_pu={self.Qmin}, qmax_pu={self.Qmax}, " +
|
|
305
|
+
f"costA={self.CostA}, costB={self.CostB}, costC={self.CostC})")
|
|
306
|
+
|
|
307
|
+
def __str__(self) -> str:
|
|
308
|
+
return repr(self)
|
|
309
|
+
|
|
310
|
+
def str_t(self, _t: int, /) -> str:
|
|
311
|
+
return (f"Generator(id='{self.ID}', busid='{self.BusID}', P={_tfv(self.P)}, Q={_tfv(self.Q)}, " +
|
|
312
|
+
f"pmin_pu={self.Pmin(_t)}, pmax_pu={self.Pmax(_t)}, qmin_pu={self.Qmin(_t)}, qmax_pu={self.Qmax(_t)}, " +
|
|
313
|
+
f"costA={self.CostA(_t)}, costB={self.CostB(_t)}, costC={self.CostC(_t)})")
|
|
314
|
+
|
|
315
|
+
def Cost(self, _t: int, /, secondary: bool = True) -> FloatVar:
|
|
316
|
+
'''
|
|
317
|
+
Get the cost of the generator at time _t, $/h
|
|
318
|
+
_t: time
|
|
319
|
+
secondary: whether to use the secondary cost model, False for the primary cost model
|
|
320
|
+
'''
|
|
321
|
+
if self.P is None: return None
|
|
322
|
+
ret = self.CostB(_t) * self.P + self.CostC(_t)
|
|
323
|
+
if secondary: ret += self.CostA(_t) * self.P ** 2
|
|
324
|
+
return ret
|
|
325
|
+
|
|
326
|
+
def CostPerPUPower(self, _t: int, /, secondary: bool = True) -> FloatVar:
|
|
327
|
+
'''
|
|
328
|
+
Get the cost of the generator per pu power at time _t, $/pu Power·h
|
|
329
|
+
_t: time
|
|
330
|
+
secondary: whether to use the secondary cost model, False for the primary cost model
|
|
331
|
+
'''
|
|
332
|
+
if self.P is None or self.P == 0: return None
|
|
333
|
+
ret = self.CostB(_t) * self.P + self.CostC(_t)
|
|
334
|
+
if secondary: ret += self.CostA(_t) * self.P ** 2
|
|
335
|
+
return ret / self.P
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def load(fp: TextIO, SbkW: float, Sb: float = 1.0):
|
|
339
|
+
'''
|
|
340
|
+
Load generators from a CSV file
|
|
341
|
+
fp: file pointer
|
|
342
|
+
SbkW: base power for electricity cost conversion, kW: $/kWh->$/pu Power·h
|
|
343
|
+
Sb: base power, unit determined by 'info.txt': powers in the file / Sb == pu values
|
|
344
|
+
'''
|
|
345
|
+
data = fp.readlines()
|
|
346
|
+
hl = data[0].split(',')
|
|
347
|
+
if hl[0].strip() != "time": raise ValueError("Bad generator CSV file")
|
|
348
|
+
tl = [int(x.strip()) for x in hl[1:]]
|
|
349
|
+
|
|
350
|
+
def parseline(ln: str):
|
|
351
|
+
ret = ln.split(',')
|
|
352
|
+
if len(ret) != len(tl) + 1: raise ValueError("Bad generator CSV file: line length error")
|
|
353
|
+
pmin: 'list[float]' = []
|
|
354
|
+
qmin: 'list[float]' = []
|
|
355
|
+
pmax: 'list[float]' = []
|
|
356
|
+
qmax: 'list[float]' = []
|
|
357
|
+
for x in ret[1:]:
|
|
358
|
+
pmin0, pmax0, qmin0, qmax0 = x.strip().split('|')
|
|
359
|
+
pmin.append(float(pmin0) / Sb)
|
|
360
|
+
pmax.append(float(pmax0) / Sb)
|
|
361
|
+
qmin.append(float(qmin0) / Sb)
|
|
362
|
+
qmax.append(float(qmax0) / Sb)
|
|
363
|
+
(id, busid, ca, cb, cc) = (x.strip() for x in ret[0].strip().split("|"))
|
|
364
|
+
#ca:$/(kWh)**2;cb:$/kWh;cc:$
|
|
365
|
+
return (id, busid, makeFunc(tl, pmin), makeFunc(tl, pmax),
|
|
366
|
+
makeFunc(tl, qmin), makeFunc(tl, qmax), float(ca) * SbkW * SbkW, float(cb) * SbkW, float(cc))
|
|
367
|
+
|
|
368
|
+
return [Generator(*parseline(ln)) for ln in data[1:]]
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def fromXML(node: 'Element', Sb_MVA: float, Ub_kV: float):
|
|
372
|
+
id = node.attrib["ID"]
|
|
373
|
+
busid = node.attrib["Bus"]
|
|
374
|
+
pmin = _readFloatLike(node.find("Pmin"), Sb_MVA, Ub_kV)
|
|
375
|
+
pmax = _readFloatLike(node.find("Pmax"), Sb_MVA, Ub_kV)
|
|
376
|
+
qmin = _readFloatLike(node.find("Qmin"), Sb_MVA, Ub_kV)
|
|
377
|
+
qmax = _readFloatLike(node.find("Qmax"), Sb_MVA, Ub_kV)
|
|
378
|
+
ca = _readFloatLike(node.find("CostA"), Sb_MVA, Ub_kV)
|
|
379
|
+
cb = _readFloatLike(node.find("CostB"), Sb_MVA, Ub_kV)
|
|
380
|
+
cc = _readFloatLike(node.find("CostC"), Sb_MVA, Ub_kV)
|
|
381
|
+
return Generator(id, busid, pmin, pmax, qmin, qmax, ca, cb, cc)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
BusID = str
|
|
385
|
+
LineID = str
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class Grid:
|
|
389
|
+
Sb: float #MVA
|
|
390
|
+
Ub: float #kV
|
|
391
|
+
|
|
392
|
+
@property
|
|
393
|
+
def Sb_MVA(self) -> float:
|
|
394
|
+
return self.Sb
|
|
395
|
+
|
|
396
|
+
@property
|
|
397
|
+
def Sb_kVA(self) -> float:
|
|
398
|
+
return self.Sb * 1000
|
|
399
|
+
|
|
400
|
+
@property
|
|
401
|
+
def Zb(self) -> float:
|
|
402
|
+
'''Zb, unit = Ohm'''
|
|
403
|
+
return self.Ub ** 2 / self.Sb
|
|
404
|
+
|
|
405
|
+
@property
|
|
406
|
+
def Ib(self) -> float:
|
|
407
|
+
'''Ib, unit = kA'''
|
|
408
|
+
return self.Sb / (self.Ub * (3 ** 0.5))
|
|
409
|
+
|
|
410
|
+
def __init__(self, Sb_MVA: float, Ub_kV: float, buses: 'Iterable[Bus]',
|
|
411
|
+
lines: 'Iterable[Line]', gens: 'Iterable[Generator]', holdShadowPrice: bool = False):
|
|
412
|
+
'''
|
|
413
|
+
Initialize
|
|
414
|
+
Sb_MVA: base power, MVA
|
|
415
|
+
Ub_kV: base voltage, kV
|
|
416
|
+
buses: list of buses
|
|
417
|
+
lines: list of lines
|
|
418
|
+
gens: list of generators
|
|
419
|
+
holdShadowPrice: whether to hold the shadow price of the buses of the last time when failed to solve this time
|
|
420
|
+
'''
|
|
421
|
+
self.Sb = Sb_MVA
|
|
422
|
+
self.Ub = Ub_kV
|
|
423
|
+
self._buses = {bus.ID: bus for bus in buses}
|
|
424
|
+
self._lines = {line.ID: line for line in lines}
|
|
425
|
+
self._ladjfb: 'dict[str, list[Line]]' = {bus.ID: [] for bus in buses}
|
|
426
|
+
self._ladjtb: 'dict[str, list[Line]]' = {bus.ID: [] for bus in buses}
|
|
427
|
+
self._bnames = list(self._buses.keys())
|
|
428
|
+
self._gens = {gen.ID: gen for gen in gens}
|
|
429
|
+
self._gatb: 'dict[str, list[Generator]]' = {bus.ID: [] for bus in buses}
|
|
430
|
+
for line in self._lines.values():
|
|
431
|
+
if not line.fBus in self._bnames: raise ValueError(f"Bus {line.fBus} undefined")
|
|
432
|
+
if not line.tBus in self._bnames: raise ValueError(f"Bus {line.tBus} undefined")
|
|
433
|
+
self._ladjfb[line.fBus].append(line)
|
|
434
|
+
self._ladjtb[line.tBus].append(line)
|
|
435
|
+
for gen in self._gens.values():
|
|
436
|
+
assert gen.BusID in self._bnames
|
|
437
|
+
self._gatb[gen.BusID].append(gen)
|
|
438
|
+
self.__holdShadowPrice = holdShadowPrice
|
|
439
|
+
|
|
440
|
+
def AddGen(self, g: Generator):
|
|
441
|
+
self._gens[g.ID] = g
|
|
442
|
+
self._gatb[g.BusID].append(g)
|
|
443
|
+
|
|
444
|
+
@property
|
|
445
|
+
def BusNames(self) -> 'list[str]':
|
|
446
|
+
return self._bnames
|
|
447
|
+
|
|
448
|
+
def Bus(self, id: str) -> 'Bus':
|
|
449
|
+
return self._buses[id]
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def Buses(self):
|
|
453
|
+
return self._buses.values()
|
|
454
|
+
|
|
455
|
+
def LinesOfFBus(self, busid: str) -> 'list[Line]':
|
|
456
|
+
return self._ladjfb[busid]
|
|
457
|
+
|
|
458
|
+
def LinesOfTBus(self, busid: str) -> 'list[Line]':
|
|
459
|
+
return self._ladjtb[busid]
|
|
460
|
+
|
|
461
|
+
def Line(self, id: str) -> 'Line':
|
|
462
|
+
return self._lines[id]
|
|
463
|
+
|
|
464
|
+
@property
|
|
465
|
+
def Lines(self):
|
|
466
|
+
return self._lines.values()
|
|
467
|
+
|
|
468
|
+
def Gen(self, id: str) -> 'Generator':
|
|
469
|
+
return self._gens[id]
|
|
470
|
+
|
|
471
|
+
@property
|
|
472
|
+
def GenNames(self) -> 'list[str]':
|
|
473
|
+
return list(self._gens.keys())
|
|
474
|
+
|
|
475
|
+
@property
|
|
476
|
+
def Gens(self):
|
|
477
|
+
return self._gens.values()
|
|
478
|
+
|
|
479
|
+
def GensAtBus(self, busid: str) -> 'list[Generator]':
|
|
480
|
+
return self._gatb[busid]
|
|
481
|
+
|
|
482
|
+
def __repr__(self):
|
|
483
|
+
b = '\n '.join(map(str, self._buses.values()))
|
|
484
|
+
l = '\n '.join(map(str, self._lines.values()))
|
|
485
|
+
g = '\n '.join(map(str, self._gens.values()))
|
|
486
|
+
return f"Buses:\n {b}\nLines:\n {l}\nGenerators:\n {g}"
|
|
487
|
+
|
|
488
|
+
def __str__(self):
|
|
489
|
+
return repr(self)
|
|
490
|
+
|
|
491
|
+
def str_t(self, _t: int):
|
|
492
|
+
b = '\n '.join(v.str_t(_t) for v in self._buses.values())
|
|
493
|
+
l = '\n '.join(v.str_t(_t) for v in self._lines.values())
|
|
494
|
+
g = '\n '.join(v.str_t(_t) for v in self._gens.values())
|
|
495
|
+
return f"At time {_t}:\nBuses:\n {b}\nLines:\n {l}\nGenerators:\n {g}"
|
|
496
|
+
|
|
497
|
+
@staticmethod
|
|
498
|
+
def fromFile(file_name:str, holdShadowPrice: bool = False):
|
|
499
|
+
if file_name.lower().endswith(".zip"):
|
|
500
|
+
return Grid.fromFileZIP(file_name, holdShadowPrice)
|
|
501
|
+
elif file_name.lower().endswith(".xml"):
|
|
502
|
+
return Grid.fromFileXML(file_name)
|
|
503
|
+
else:
|
|
504
|
+
raise ValueError("Unsupported file type")
|
|
505
|
+
|
|
506
|
+
@staticmethod
|
|
507
|
+
def fromFileXML(xml_name: str, holdShadowPrice: bool = False):
|
|
508
|
+
rt = ElementTree(file=xml_name).getroot()
|
|
509
|
+
Sb, unit = _readVal(rt.attrib["Sb"])
|
|
510
|
+
if unit == "MVA": pass
|
|
511
|
+
elif unit == "kVA": Sb /= 1000
|
|
512
|
+
else: raise ValueError(f"Invalid base value unit: {unit}")
|
|
513
|
+
Ub, unit = _readVal(rt.attrib["Ub"])
|
|
514
|
+
if unit == "kV": pass
|
|
515
|
+
else: raise ValueError(f"Invalid base value unit: {unit}")
|
|
516
|
+
buses = []
|
|
517
|
+
lines = []
|
|
518
|
+
gens = []
|
|
519
|
+
for e in rt:
|
|
520
|
+
if e.tag == "bus":
|
|
521
|
+
buses.append(Bus.fromXML(e, Sb, Ub))
|
|
522
|
+
elif e.tag == "line":
|
|
523
|
+
lines.append(Line.fromXML(e, Ub * Ub / Sb))
|
|
524
|
+
elif e.tag == "gen" or e.tag == "generator":
|
|
525
|
+
gens.append(Generator.fromXML(e, Sb, Ub))
|
|
526
|
+
else:
|
|
527
|
+
raise ValueError(f"Unknown XML node: {e.tag}")
|
|
528
|
+
return Grid(Sb, Ub, buses, lines, gens, holdShadowPrice)
|
|
529
|
+
|
|
530
|
+
@staticmethod
|
|
531
|
+
def fromFileZIP(zip_name: str, holdShadowPrice: bool = False):
|
|
532
|
+
zf = zipfile.ZipFile(zip_name, "r")
|
|
533
|
+
with TextIOWrapper(BytesIO(zf.read("info.txt"))) as fp:
|
|
534
|
+
info: dict[str, Any] = {}
|
|
535
|
+
for item in [x.split(':') for x in fp.readlines()]:
|
|
536
|
+
if len(item) != 2: raise ValueError("Bad grid info file")
|
|
537
|
+
info[item[0].strip()] = item[1].strip()
|
|
538
|
+
Sb = float(info.pop("S_base_MVA"))
|
|
539
|
+
Ub = float(info.pop("U_base_kV"))
|
|
540
|
+
Zb = Ub * Ub / Sb
|
|
541
|
+
with TextIOWrapper(BytesIO(zf.read("buses.csv"))) as fp:
|
|
542
|
+
buses_unit = info.pop("buses_unit")
|
|
543
|
+
buses_loop = info.pop("buses_loop", "0,0")
|
|
544
|
+
if buses_unit == "pu":
|
|
545
|
+
buses = Bus.load(fp, 1, buses_loop)
|
|
546
|
+
elif buses_unit in ["kVA", "kvar", "kW"]:
|
|
547
|
+
buses = Bus.load(fp, Sb * 1000, buses_loop)
|
|
548
|
+
elif buses_unit in ["MVA", "Mvar", "MW"]:
|
|
549
|
+
buses = Bus.load(fp, Sb, buses_loop)
|
|
550
|
+
else:
|
|
551
|
+
raise ValueError(f"Invalid power unit: {buses_unit}")
|
|
552
|
+
with TextIOWrapper(BytesIO(zf.read("lines.csv"))) as fp:
|
|
553
|
+
lines_unit = info.pop("lines_unit")
|
|
554
|
+
if lines_unit == "pu":
|
|
555
|
+
lines = Line.load(fp)
|
|
556
|
+
elif lines_unit == "ohm":
|
|
557
|
+
lines = Line.load(fp, Zb)
|
|
558
|
+
else:
|
|
559
|
+
raise ValueError(f"Invalid resistance unit: {lines_unit}")
|
|
560
|
+
with TextIOWrapper(BytesIO(zf.read("gens.csv"))) as fp:
|
|
561
|
+
gens_unit = info.pop("gens_unit")
|
|
562
|
+
if gens_unit == "pu":
|
|
563
|
+
gens = Generator.load(fp, Sb * 1000)
|
|
564
|
+
elif gens_unit in ["kVA", "kvar", "kW"]:
|
|
565
|
+
gens = Generator.load(fp, Sb * 1000, Sb * 1000)
|
|
566
|
+
elif gens_unit in ["MVA", "Mvar", "MW"]:
|
|
567
|
+
gens = Generator.load(fp, Sb * 1000, Sb)
|
|
568
|
+
else:
|
|
569
|
+
raise ValueError(f"Invalid power unit: {gens_unit}")
|
|
570
|
+
return Grid(Sb, Ub, buses, lines, gens, holdShadowPrice)
|
|
571
|
+
|
|
572
|
+
def solve(self, _t: int, /, *, max_v_pu:float = 1.1, min_v_pu: float = 0.9, max_I_kA: float = 0.866, source_buses:'list[BusID]' = []) -> 'tuple[bool, float]':
|
|
573
|
+
'''Get the best result at time _t, return a tuple: (success?, optimal objective value)'''
|
|
574
|
+
model = Model("model")
|
|
575
|
+
max_v = max_v_pu ** 2
|
|
576
|
+
min_v = min_v_pu ** 2
|
|
577
|
+
max_l = (max_I_kA / self.Ib) ** 2
|
|
578
|
+
|
|
579
|
+
# pg0[k]: Generator active power
|
|
580
|
+
# qg0[k]: Generator reactive power
|
|
581
|
+
# --> pg[j]: Active power of all generators at the bus
|
|
582
|
+
# --> qg[j]: Reactive power of all generators at the bus
|
|
583
|
+
# v[j]: Bus voltage ** 2
|
|
584
|
+
# l[i,j]: Line current ** 2
|
|
585
|
+
# P[i,j]: Line active power
|
|
586
|
+
# Q[i,j]: Line reactive power
|
|
587
|
+
pg0: dict[str, Var] = {g.ID: model.addVar(name=f"pg_{g.ID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t)) for g in
|
|
588
|
+
self.Gens}
|
|
589
|
+
qg0: dict[str, Var] = {g.ID: model.addVar(name=f"qg_{g.ID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t)) for g in
|
|
590
|
+
self.Gens}
|
|
591
|
+
pg: dict[str, list[Var]] = {bus.ID: [] for bus in self.Buses}
|
|
592
|
+
qg: dict[str, list[Var]] = {bus.ID: [] for bus in self.Buses}
|
|
593
|
+
for g in self.Gens:
|
|
594
|
+
pg[g.BusID].append(pg0[g.ID])
|
|
595
|
+
qg[g.BusID].append(qg0[g.ID])
|
|
596
|
+
|
|
597
|
+
v = {bus.ID: model.addVar(name=f"v_{bus.ID}", vtype='C', lb=min_v, ub=max_v) for bus in self.Buses}
|
|
598
|
+
l = {line.ID: model.addVar(name=f"l_{line.ID}", vtype='C', lb=0, ub=max_l) for line in self.Lines}
|
|
599
|
+
P = {line.ID: model.addVar(name=f"P_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
600
|
+
self.Lines}
|
|
601
|
+
Q = {line.ID: model.addVar(name=f"Q_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
602
|
+
self.Lines}
|
|
603
|
+
Pcons: dict[str, Constr] = {}
|
|
604
|
+
Qcons: dict[str, Constr] = {}
|
|
605
|
+
|
|
606
|
+
for bus in self.Buses:
|
|
607
|
+
flow_in = self.LinesOfTBus(bus.ID)
|
|
608
|
+
flow_out = self.LinesOfFBus(bus.ID)
|
|
609
|
+
j = bus.ID
|
|
610
|
+
Pcons[j] = model.addConstr(Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in) + Qs(pg[j]) == Qs(
|
|
611
|
+
P[ln.ID] for ln in flow_out) + bus.Pd(_t), f"Pcons_{j}")
|
|
612
|
+
Qcons[j] = model.addConstr(Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in) + Qs(qg[j]) == Qs(
|
|
613
|
+
Q[ln.ID] for ln in flow_out) + bus.Qd(_t), f"Qcons_{j}")
|
|
614
|
+
|
|
615
|
+
for line in self.Lines:
|
|
616
|
+
i, j = line.pair
|
|
617
|
+
lid = line.ID
|
|
618
|
+
model.addConstr(
|
|
619
|
+
v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
|
|
620
|
+
f"ΔU2_cons_{lid}")
|
|
621
|
+
model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
|
|
622
|
+
|
|
623
|
+
assert len(source_buses) > 0, "No source bus specified"
|
|
624
|
+
for b in source_buses:
|
|
625
|
+
model.addConstr(v[b] == 1, f"v_{b}==1")
|
|
626
|
+
|
|
627
|
+
model.setObjective(
|
|
628
|
+
quicksum(g.CostA(_t) * pg0[g.ID] ** 2 + g.CostB(_t) * pg0[g.ID] + g.CostC(_t) for g in self.Gens),
|
|
629
|
+
GRB.MINIMIZE)
|
|
630
|
+
model.setParam('OutputFlag', 0)
|
|
631
|
+
model.setParam('QCPDual', 1) # 启用二次约束规划对偶
|
|
632
|
+
model.update()
|
|
633
|
+
model.optimize()
|
|
634
|
+
if model.Status != GRB.Status.OPTIMAL:
|
|
635
|
+
return False, 0
|
|
636
|
+
|
|
637
|
+
for bus in self.Buses:
|
|
638
|
+
j = bus.ID
|
|
639
|
+
bus.V = v[j].X ** 0.5
|
|
640
|
+
try:
|
|
641
|
+
sp = Pcons[j].Pi
|
|
642
|
+
except:
|
|
643
|
+
sp = None if not self.__holdShadowPrice else bus.ShadowPrice
|
|
644
|
+
bus.ShadowPrice = sp
|
|
645
|
+
|
|
646
|
+
for line in self.Lines:
|
|
647
|
+
lid = line.ID
|
|
648
|
+
line.I = l[lid].X ** 0.5
|
|
649
|
+
line.P = P[lid].X
|
|
650
|
+
line.Q = Q[lid].X
|
|
651
|
+
|
|
652
|
+
for gen in self.Gens:
|
|
653
|
+
j = gen.ID
|
|
654
|
+
gen.P = pg0[j].X
|
|
655
|
+
gen.Q = qg0[j].X
|
|
656
|
+
|
|
657
|
+
return True, model.ObjVal
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: fpowerkit
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
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.18
|
|
13
13
|
Requires-Dist: gurobipy>=9.1.0
|
|
14
14
|
|
|
15
15
|
# FPowerKit 配电网运算组件
|
|
@@ -22,7 +22,7 @@ Requires-Dist: gurobipy>=9.1.0
|
|
|
22
22
|
|
|
23
23
|
输入以下命令开始仿真:
|
|
24
24
|
```bash
|
|
25
|
-
python main.py -g cases/ieee33.zip
|
|
25
|
+
python main.py -g cases/ieee33.grid.zip
|
|
26
26
|
```
|
|
27
27
|
`ieee33`描述了IEEE 33节点配电网模型。换成`nodes3`则是一个极简版3节点辐射形配电网模型,结构如下:
|
|
28
28
|
|
|
@@ -5,7 +5,7 @@ with open("README.md", "r", encoding="utf8") as f:
|
|
|
5
5
|
|
|
6
6
|
setup(
|
|
7
7
|
name="fpowerkit",
|
|
8
|
-
version="0.0.
|
|
8
|
+
version="0.0.3",
|
|
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.18", "gurobipy>=9.1.0"],
|
|
21
21
|
)
|
|
@@ -1,487 +0,0 @@
|
|
|
1
|
-
import zipfile
|
|
2
|
-
from io import BytesIO, TextIOWrapper
|
|
3
|
-
from typing import Any, TextIO, Iterable, Optional
|
|
4
|
-
|
|
5
|
-
from feasytools import TimeFunc, ConstFunc, makeFunc, FloatLike
|
|
6
|
-
from gurobipy import Model, GRB, quicksum, Var, Constr
|
|
7
|
-
|
|
8
|
-
FloatVar = Optional[float]
|
|
9
|
-
Qs = quicksum
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _float2func(v: FloatLike) -> TimeFunc:
|
|
13
|
-
if isinstance(v, (float, int)):
|
|
14
|
-
return ConstFunc(v)
|
|
15
|
-
else:
|
|
16
|
-
assert isinstance(v, TimeFunc)
|
|
17
|
-
return v
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
def _tfv(s: FloatVar): return "<unsolved>" if s is None else str(s)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class Bus:
|
|
24
|
-
"""母线 Bus"""
|
|
25
|
-
ID: str
|
|
26
|
-
V: FloatVar # pu
|
|
27
|
-
Pd: TimeFunc # pu
|
|
28
|
-
Qd: TimeFunc # pu
|
|
29
|
-
ShadowPrice: FloatVar # 该母线上的发电机的影子价格,元/pu power
|
|
30
|
-
|
|
31
|
-
def __init__(self, id: str, p_pu: FloatLike, q_pu: FloatLike):
|
|
32
|
-
self.ID = id
|
|
33
|
-
self.V = None
|
|
34
|
-
self.Pd = _float2func(p_pu)
|
|
35
|
-
self.Qd = _float2func(q_pu)
|
|
36
|
-
self.ShadowPrice = None
|
|
37
|
-
|
|
38
|
-
def __str__(self):
|
|
39
|
-
return f"Bus[ID={self.ID}, V={_tfv(self.V)}, Pd={self.Pd}, Qd={self.Qd}]"
|
|
40
|
-
|
|
41
|
-
def __repr__(self):
|
|
42
|
-
return self.__str__()
|
|
43
|
-
|
|
44
|
-
def str_t(self, _t: int):
|
|
45
|
-
return f"Bus[ID={self.ID}, V={_tfv(self.V)}, Pd={self.Pd(_t)}, Qd={self.Qd(_t)}]"
|
|
46
|
-
|
|
47
|
-
@staticmethod
|
|
48
|
-
def load(fp: TextIO, Sb: float = 1.0, loop: str = "0,0"):
|
|
49
|
-
ret = loop.split(",")
|
|
50
|
-
assert len(ret) == 2
|
|
51
|
-
loop_period = int(ret[0])
|
|
52
|
-
loop_times = int(ret[1])
|
|
53
|
-
data = fp.readlines()
|
|
54
|
-
hl = data[0].split(',')
|
|
55
|
-
if hl[0].strip() != "time": raise ValueError("Bad format of bus CSV file")
|
|
56
|
-
tl = [int(x.strip()) for x in hl[1:]]
|
|
57
|
-
if loop_period > 0 and loop_times > 0:
|
|
58
|
-
tl_old = tl.copy()
|
|
59
|
-
for i in range(loop_times - 1):
|
|
60
|
-
tl.extend([x + loop_period * (i + 1) for x in tl_old])
|
|
61
|
-
else:
|
|
62
|
-
tl_old = tl
|
|
63
|
-
|
|
64
|
-
def parseline(ln: str,i:int):
|
|
65
|
-
ret = ln.split(',')
|
|
66
|
-
if len(ret) != len(tl_old) + 1: raise ValueError(f"Bad line length at line {i} in bus CSV file")
|
|
67
|
-
p: 'list[float]' = []
|
|
68
|
-
q: 'list[float]' = []
|
|
69
|
-
for x in ret[1:]:
|
|
70
|
-
p0, q0 = x.strip().split('|')
|
|
71
|
-
p.append(float(p0) / Sb)
|
|
72
|
-
q.append(float(q0) / Sb)
|
|
73
|
-
if loop_period > 0 and loop_times > 0:
|
|
74
|
-
p = p * loop_times
|
|
75
|
-
q = q * loop_times
|
|
76
|
-
return ret[0].strip(), makeFunc(tl, p), makeFunc(tl, q)
|
|
77
|
-
|
|
78
|
-
return [Bus(*parseline(ln,i)) for i,ln in enumerate(data[1:],start=1)]
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
class Line:
|
|
82
|
-
"""线路"""
|
|
83
|
-
ID: str
|
|
84
|
-
fBus: str
|
|
85
|
-
tBus: str
|
|
86
|
-
R: float # pu
|
|
87
|
-
X: float # pu
|
|
88
|
-
P: FloatVar # pu
|
|
89
|
-
Q: FloatVar # pu
|
|
90
|
-
I: FloatVar # pu
|
|
91
|
-
|
|
92
|
-
def __init__(self, id: str, fbus: str, tbus: str, r_pu: float, x_pu: float):
|
|
93
|
-
'''
|
|
94
|
-
初始化
|
|
95
|
-
id: 线路ID
|
|
96
|
-
fbus: 起始母线ID
|
|
97
|
-
tbus: 终止母线ID
|
|
98
|
-
r_pu: 电阻, pu
|
|
99
|
-
x_pu: 电抗, pu
|
|
100
|
-
'''
|
|
101
|
-
self.ID = id
|
|
102
|
-
self.fBus = fbus
|
|
103
|
-
self.tBus = tbus
|
|
104
|
-
self.R = r_pu
|
|
105
|
-
self.X = x_pu
|
|
106
|
-
self.I = None
|
|
107
|
-
self.P = None
|
|
108
|
-
self.Q = None
|
|
109
|
-
|
|
110
|
-
@property
|
|
111
|
-
def pair(self):
|
|
112
|
-
'''(self.fBus, self.tBus)的语法糖'''
|
|
113
|
-
return (self.fBus, self.tBus)
|
|
114
|
-
|
|
115
|
-
def __str__(self) -> str:
|
|
116
|
-
return f"Line[ID={self.ID}, fBus={self.fBus}, tBus={self.tBus}, R={self.R}, X={self.X}, I={_tfv(self.I)}, P={_tfv(self.P)}, Q={_tfv(self.Q)}]"
|
|
117
|
-
|
|
118
|
-
def __repr__(self) -> str:
|
|
119
|
-
return self.__str__()
|
|
120
|
-
|
|
121
|
-
def str_t(self, _t: int) -> str:
|
|
122
|
-
return self.__str__()
|
|
123
|
-
|
|
124
|
-
@staticmethod
|
|
125
|
-
def load(fp: TextIO, Zb: float = 1.0):
|
|
126
|
-
data = fp.readlines()
|
|
127
|
-
head = [x.strip() for x in data[0].split(',')]
|
|
128
|
-
if head != ["id", "fBus", "tBus", "R", "X"]:
|
|
129
|
-
raise ValueError("线路CSV文件格式错误: 列必须为id,fBus,tBus,R,X, 且区分大小写")
|
|
130
|
-
|
|
131
|
-
def parseline(ln: str):
|
|
132
|
-
(id, f, t, r, x) = (x.strip() for x in ln.split(','))
|
|
133
|
-
return id, f, t, float(r) / Zb, float(x) / Zb
|
|
134
|
-
|
|
135
|
-
return [Line(*parseline(ln)) for ln in data[1:]]
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
class Generator:
|
|
139
|
-
'''发电机(火电/风电/光伏通用型)'''
|
|
140
|
-
ID: str
|
|
141
|
-
BusID: str
|
|
142
|
-
Pmin: TimeFunc #pu
|
|
143
|
-
Pmax: TimeFunc #pu
|
|
144
|
-
P: FloatVar #pu
|
|
145
|
-
Qmin: TimeFunc #pu
|
|
146
|
-
Qmax: TimeFunc #pu
|
|
147
|
-
Q: FloatVar #pu
|
|
148
|
-
CostA: TimeFunc #二次成本:元/(pu Power·h)**2
|
|
149
|
-
CostB: TimeFunc #线性成本:元/pu Power·h
|
|
150
|
-
CostC: TimeFunc #开机固定成本:元
|
|
151
|
-
|
|
152
|
-
def __init__(self, id: str, busid: str, pmin_pu: FloatLike, pmax_pu: FloatLike,
|
|
153
|
-
qmin_pu: FloatLike, qmax_pu: FloatLike, costA: FloatLike, costB: FloatLike, costC: FloatLike):
|
|
154
|
-
'''
|
|
155
|
-
初始化
|
|
156
|
-
id: 发电机ID
|
|
157
|
-
busid: 发电机所在母线ID
|
|
158
|
-
pmin_pu: 最小有功出力, pu
|
|
159
|
-
pmax_pu: 最大有功出力, pu
|
|
160
|
-
qmin_pu: 最小无功出力, pu
|
|
161
|
-
qmax_pu: 最大无功出力, pu
|
|
162
|
-
costA: 二次成本系数, 元/(pu Power·h)**2
|
|
163
|
-
costB: 线性成本系数, 元/pu Power·h
|
|
164
|
-
costC: 开机固定成本, 元
|
|
165
|
-
'''
|
|
166
|
-
self.ID = id
|
|
167
|
-
self.BusID = busid
|
|
168
|
-
self.P = None
|
|
169
|
-
self.Q = None
|
|
170
|
-
self.Pmin = _float2func(pmin_pu)
|
|
171
|
-
self.Pmax = _float2func(pmax_pu)
|
|
172
|
-
self.Qmin = _float2func(qmin_pu)
|
|
173
|
-
self.Qmax = _float2func(qmax_pu)
|
|
174
|
-
self.CostA = _float2func(costA)
|
|
175
|
-
self.CostB = _float2func(costB)
|
|
176
|
-
self.CostC = _float2func(costC)
|
|
177
|
-
self.CostShadow = None
|
|
178
|
-
|
|
179
|
-
def __str__(self) -> str:
|
|
180
|
-
return f"Generator[ID={self.ID}, Bus={self.BusID}, P={_tfv(self.P)}, Q={_tfv(self.Q)}, Pmin={self.Pmin}, Pmax={self.Pmax}, Qmin={self.Qmin}, Qmax={self.Qmax}, CostA={self.CostA}, CostB={self.CostB}, CostC={self.CostC}]"
|
|
181
|
-
|
|
182
|
-
def __repr__(self) -> str:
|
|
183
|
-
return self.__str__()
|
|
184
|
-
|
|
185
|
-
def str_t(self, _t: int) -> str:
|
|
186
|
-
return f"Generator[ID={self.ID}, Bus={self.BusID}, P={_tfv(self.P)}, Q={_tfv(self.Q)}, Pmin={self.Pmin(_t)}, Pmax={self.Pmax(_t)}, Qmin={self.Qmin(_t)}, Qmax={self.Qmax(_t)}, CostA={self.CostA(_t)}, CostB={self.CostB(_t)}, CostC={self.CostC(_t)}]"
|
|
187
|
-
|
|
188
|
-
def Cost(self, _t: int, secondary: bool = True) -> FloatVar:
|
|
189
|
-
'''
|
|
190
|
-
获取当前发电功率下的发电成本, 元/h
|
|
191
|
-
_t: 时间
|
|
192
|
-
secondary: True表示使用二次函数成本模型, False表示使用一次函数成本模型
|
|
193
|
-
'''
|
|
194
|
-
if self.P is None: return None
|
|
195
|
-
ret = self.CostB(_t) * self.P + self.CostC(_t)
|
|
196
|
-
if secondary: ret += self.CostA(_t) * self.P ** 2
|
|
197
|
-
return ret
|
|
198
|
-
|
|
199
|
-
def CostPerPUPower(self, _t: int, secondary: bool = True) -> FloatVar:
|
|
200
|
-
'''
|
|
201
|
-
获取当前发电功率下的单位发电成本, 元/pu·h
|
|
202
|
-
_t: 时间
|
|
203
|
-
secondary: True表示使用二次函数成本模型, False表示使用一次函数成本模型
|
|
204
|
-
'''
|
|
205
|
-
if self.P is None or self.P == 0: return None
|
|
206
|
-
ret = self.CostB(_t) * self.P + self.CostC(_t)
|
|
207
|
-
if secondary: ret += self.CostA(_t) * self.P ** 2
|
|
208
|
-
return ret / self.P
|
|
209
|
-
|
|
210
|
-
@staticmethod
|
|
211
|
-
def load(fp: TextIO, SbkW: float, Sb: float = 1.0):
|
|
212
|
-
'''
|
|
213
|
-
从文件中加载发电机数据
|
|
214
|
-
fp: 文件指针
|
|
215
|
-
SbkW: 基准功率, kW, 用于电价单位转换: 元/kWh->元/pu Power·h
|
|
216
|
-
Sb: 基准功率, 单位不确定(取决于info.txt), 要求文件中的功率除以Sb后为标幺值
|
|
217
|
-
'''
|
|
218
|
-
data = fp.readlines()
|
|
219
|
-
hl = data[0].split(',')
|
|
220
|
-
if hl[0].strip() != "time": raise ValueError("发电机CSV文件格式错误")
|
|
221
|
-
tl = [int(x.strip()) for x in hl[1:]]
|
|
222
|
-
|
|
223
|
-
def parseline(ln: str):
|
|
224
|
-
ret = ln.split(',')
|
|
225
|
-
if len(ret) != len(tl) + 1: raise ValueError("发电机CSV文件行长度错误")
|
|
226
|
-
pmin: 'list[float]' = []
|
|
227
|
-
qmin: 'list[float]' = []
|
|
228
|
-
pmax: 'list[float]' = []
|
|
229
|
-
qmax: 'list[float]' = []
|
|
230
|
-
for x in ret[1:]:
|
|
231
|
-
pmin0, pmax0, qmin0, qmax0 = x.strip().split('|')
|
|
232
|
-
pmin.append(float(pmin0) / Sb)
|
|
233
|
-
pmax.append(float(pmax0) / Sb)
|
|
234
|
-
qmin.append(float(qmin0) / Sb)
|
|
235
|
-
qmax.append(float(qmax0) / Sb)
|
|
236
|
-
(id, busid, ca, cb, cc) = (x.strip() for x in ret[0].strip().split("|"))
|
|
237
|
-
#ca:元/(kWh)**2;cb:元/kWh;cc:元
|
|
238
|
-
return (id, busid, makeFunc(tl, pmin), makeFunc(tl, pmax),
|
|
239
|
-
makeFunc(tl, qmin), makeFunc(tl, qmax), float(ca) * SbkW * SbkW, float(cb) * SbkW, float(cc))
|
|
240
|
-
|
|
241
|
-
return [Generator(*parseline(ln)) for ln in data[1:]]
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
BusID = str
|
|
245
|
-
LineID = str
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
class Grid:
|
|
249
|
-
Sb: float #MVA
|
|
250
|
-
Ub: float #kV
|
|
251
|
-
|
|
252
|
-
@property
|
|
253
|
-
def Sb_MVA(self) -> float:
|
|
254
|
-
return self.Sb
|
|
255
|
-
|
|
256
|
-
@property
|
|
257
|
-
def Sb_kVA(self) -> float:
|
|
258
|
-
return self.Sb * 1000
|
|
259
|
-
|
|
260
|
-
@property
|
|
261
|
-
def Zb(self) -> float:
|
|
262
|
-
'''Zb, unit = Ohm'''
|
|
263
|
-
return self.Ub ** 2 / self.Sb
|
|
264
|
-
|
|
265
|
-
@property
|
|
266
|
-
def Ib(self) -> float:
|
|
267
|
-
'''Ib, unit = kA'''
|
|
268
|
-
return self.Sb / (self.Ub * (3 ** 0.5))
|
|
269
|
-
|
|
270
|
-
def __init__(self, Sb_MVA: float, Ub_kV: float, buses: 'Iterable[Bus]',
|
|
271
|
-
lines: 'Iterable[Line]', gens: 'Iterable[Generator]', holdShadowPrice: bool = False):
|
|
272
|
-
'''
|
|
273
|
-
初始化
|
|
274
|
-
Sb_MVA: 基准功率, MVA
|
|
275
|
-
Ub_kV: 基准电压, kV
|
|
276
|
-
buses: 母线列表
|
|
277
|
-
lines: 线路列表
|
|
278
|
-
gens: 发电机列表
|
|
279
|
-
holdShadowPrice: 当本次影子价格求解失败时,是否保留上次影子价格
|
|
280
|
-
'''
|
|
281
|
-
self.Sb = Sb_MVA
|
|
282
|
-
self.Ub = Ub_kV
|
|
283
|
-
self._buses = {bus.ID: bus for bus in buses}
|
|
284
|
-
self._lines = {line.ID: line for line in lines}
|
|
285
|
-
self._ladjfb: 'dict[str, list[Line]]' = {bus.ID: [] for bus in buses}
|
|
286
|
-
self._ladjtb: 'dict[str, list[Line]]' = {bus.ID: [] for bus in buses}
|
|
287
|
-
self._bnames = list(self._buses.keys())
|
|
288
|
-
self._gens = {gen.ID: gen for gen in gens}
|
|
289
|
-
self._gatb: 'dict[str, list[Generator]]' = {bus.ID: [] for bus in buses}
|
|
290
|
-
for line in self._lines.values():
|
|
291
|
-
if not line.fBus in self._bnames: raise ValueError(f"母线{line.fBus}未定义")
|
|
292
|
-
if not line.tBus in self._bnames: raise ValueError(f"母线{line.tBus}未定义")
|
|
293
|
-
self._ladjfb[line.fBus].append(line)
|
|
294
|
-
self._ladjtb[line.tBus].append(line)
|
|
295
|
-
for gen in self._gens.values():
|
|
296
|
-
assert gen.BusID in self._bnames
|
|
297
|
-
self._gatb[gen.BusID].append(gen)
|
|
298
|
-
self.__holdShadowPrice = holdShadowPrice
|
|
299
|
-
|
|
300
|
-
def AddGen(self, g: Generator):
|
|
301
|
-
self._gens[g.ID] = g
|
|
302
|
-
self._gatb[g.BusID].append(g)
|
|
303
|
-
|
|
304
|
-
@property
|
|
305
|
-
def BusNames(self) -> 'list[str]':
|
|
306
|
-
return self._bnames
|
|
307
|
-
|
|
308
|
-
def Bus(self, id: str) -> 'Bus':
|
|
309
|
-
return self._buses[id]
|
|
310
|
-
|
|
311
|
-
@property
|
|
312
|
-
def Buses(self):
|
|
313
|
-
return self._buses.values()
|
|
314
|
-
|
|
315
|
-
def LinesOfFBus(self, busid: str) -> 'list[Line]':
|
|
316
|
-
return self._ladjfb[busid]
|
|
317
|
-
|
|
318
|
-
def LinesOfTBus(self, busid: str) -> 'list[Line]':
|
|
319
|
-
return self._ladjtb[busid]
|
|
320
|
-
|
|
321
|
-
def Line(self, id: str) -> 'Line':
|
|
322
|
-
return self._lines[id]
|
|
323
|
-
|
|
324
|
-
@property
|
|
325
|
-
def Lines(self):
|
|
326
|
-
return self._lines.values()
|
|
327
|
-
|
|
328
|
-
def Gen(self, id: str) -> 'Generator':
|
|
329
|
-
return self._gens[id]
|
|
330
|
-
|
|
331
|
-
@property
|
|
332
|
-
def GenNames(self) -> 'list[str]':
|
|
333
|
-
return list(self._gens.keys())
|
|
334
|
-
|
|
335
|
-
@property
|
|
336
|
-
def Gens(self):
|
|
337
|
-
return self._gens.values()
|
|
338
|
-
|
|
339
|
-
def GensAtBus(self, busid: str) -> 'list[Generator]':
|
|
340
|
-
return self._gatb[busid]
|
|
341
|
-
|
|
342
|
-
def __str__(self):
|
|
343
|
-
b = '\n '.join(map(str, self._buses.values()))
|
|
344
|
-
l = '\n '.join(map(str, self._lines.values()))
|
|
345
|
-
g = '\n '.join(map(str, self._gens.values()))
|
|
346
|
-
return f"Buses:\n {b}\nLines:\n {l}\nGenerators:\n {g}"
|
|
347
|
-
|
|
348
|
-
def __repr__(self):
|
|
349
|
-
return self.__str__()
|
|
350
|
-
|
|
351
|
-
def str_t(self, _t: int):
|
|
352
|
-
b = '\n '.join(v.str_t(_t) for v in self._buses.values())
|
|
353
|
-
l = '\n '.join(v.str_t(_t) for v in self._lines.values())
|
|
354
|
-
g = '\n '.join(v.str_t(_t) for v in self._gens.values())
|
|
355
|
-
return f"At time {_t}:\nBuses:\n {b}\nLines:\n {l}\nGenerators:\n {g}"
|
|
356
|
-
|
|
357
|
-
@staticmethod
|
|
358
|
-
def fromFile(zip_name: str, holdShadowPrice: bool = False):
|
|
359
|
-
zf = zipfile.ZipFile(zip_name, "r")
|
|
360
|
-
with TextIOWrapper(BytesIO(zf.read("info.txt"))) as fp:
|
|
361
|
-
info: dict[str, Any] = {}
|
|
362
|
-
for item in [x.split(':') for x in fp.readlines()]:
|
|
363
|
-
if len(item) != 2: raise ValueError("电网信息文件错误")
|
|
364
|
-
info[item[0].strip()] = item[1].strip()
|
|
365
|
-
Sb = float(info.pop("S_base_MVA"))
|
|
366
|
-
Ub = float(info.pop("U_base_kV"))
|
|
367
|
-
Zb = Ub * Ub / Sb
|
|
368
|
-
with TextIOWrapper(BytesIO(zf.read("buses.csv"))) as fp:
|
|
369
|
-
buses_unit = info.pop("buses_unit")
|
|
370
|
-
buses_loop = info.pop("buses_loop", "0,0")
|
|
371
|
-
if buses_unit == "pu":
|
|
372
|
-
buses = Bus.load(fp, 1, buses_loop)
|
|
373
|
-
elif buses_unit in ["kVA", "kvar", "kW"]:
|
|
374
|
-
buses = Bus.load(fp, Sb * 1000, buses_loop)
|
|
375
|
-
elif buses_unit in ["MVA", "Mvar", "MW"]:
|
|
376
|
-
buses = Bus.load(fp, Sb, buses_loop)
|
|
377
|
-
else:
|
|
378
|
-
raise ValueError(f"无效的功率单位{buses_unit}")
|
|
379
|
-
with TextIOWrapper(BytesIO(zf.read("lines.csv"))) as fp:
|
|
380
|
-
lines_unit = info.pop("lines_unit")
|
|
381
|
-
if lines_unit == "pu":
|
|
382
|
-
lines = Line.load(fp)
|
|
383
|
-
elif lines_unit == "ohm":
|
|
384
|
-
lines = Line.load(fp, Zb)
|
|
385
|
-
else:
|
|
386
|
-
raise ValueError(f"无效的线路阻抗单位{lines_unit}")
|
|
387
|
-
with TextIOWrapper(BytesIO(zf.read("gens.csv"))) as fp:
|
|
388
|
-
gens_unit = info.pop("gens_unit")
|
|
389
|
-
if gens_unit == "pu":
|
|
390
|
-
gens = Generator.load(fp, Sb * 1000)
|
|
391
|
-
elif gens_unit in ["kVA", "kvar", "kW"]:
|
|
392
|
-
gens = Generator.load(fp, Sb * 1000, Sb * 1000)
|
|
393
|
-
elif gens_unit in ["MVA", "Mvar", "MW"]:
|
|
394
|
-
gens = Generator.load(fp, Sb * 1000, Sb)
|
|
395
|
-
else:
|
|
396
|
-
raise ValueError(f"无效的功率单位{gens_unit}")
|
|
397
|
-
return Grid(Sb, Ub, buses, lines, gens, holdShadowPrice)
|
|
398
|
-
|
|
399
|
-
def solve(self, _t: int, /, *, max_v_pu:float = 1.1, min_v_pu: float = 0.9) -> 'tuple[bool, float]':
|
|
400
|
-
'''求解_t时刻的最优解, 返回(是否求解成功, 目标函数最优值)'''
|
|
401
|
-
model = Model("model")
|
|
402
|
-
max_v = max_v_pu ** 2
|
|
403
|
-
min_v = min_v_pu ** 2
|
|
404
|
-
max_l = (0.866 / self.Ib) ** 2 # 中国10kV配网限制功率15MVA,对应电流0.866kA
|
|
405
|
-
# ---------------添加变量---------------
|
|
406
|
-
# pg0[k]: 发电机有功
|
|
407
|
-
# qg0[k]: 发电机无功
|
|
408
|
-
# --> pg[j]: 节点所有发电机的有功
|
|
409
|
-
# --> qg[j]: 节点所有发电机的无功
|
|
410
|
-
# v[j]: 节点电压平方
|
|
411
|
-
# l[i,j]: 线路电流平方
|
|
412
|
-
# P[i,j] 线路有功
|
|
413
|
-
# Q[i,j]: 线路无功
|
|
414
|
-
pg0: dict[str, Var] = {g.ID: model.addVar(name=f"pg_{g.ID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t)) for g in
|
|
415
|
-
self.Gens}
|
|
416
|
-
qg0: dict[str, Var] = {g.ID: model.addVar(name=f"qg_{g.ID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t)) for g in
|
|
417
|
-
self.Gens}
|
|
418
|
-
pg: dict[str, list[Var]] = {bus.ID: [] for bus in self.Buses}
|
|
419
|
-
qg: dict[str, list[Var]] = {bus.ID: [] for bus in self.Buses}
|
|
420
|
-
for g in self.Gens:
|
|
421
|
-
pg[g.BusID].append(pg0[g.ID])
|
|
422
|
-
qg[g.BusID].append(qg0[g.ID])
|
|
423
|
-
|
|
424
|
-
v = {bus.ID: model.addVar(name=f"v_{bus.ID}", vtype='C', lb=min_v, ub=max_v) for bus in self.Buses}
|
|
425
|
-
l = {line.ID: model.addVar(name=f"l_{line.ID}", vtype='C', lb=0, ub=max_l) for line in self.Lines}
|
|
426
|
-
P = {line.ID: model.addVar(name=f"P_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
427
|
-
self.Lines}
|
|
428
|
-
Q = {line.ID: model.addVar(name=f"Q_{line.ID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for line in
|
|
429
|
-
self.Lines}
|
|
430
|
-
Pcons: dict[str, Constr] = {}
|
|
431
|
-
Qcons: dict[str, Constr] = {}
|
|
432
|
-
|
|
433
|
-
# ---------------添加约束---------------
|
|
434
|
-
# 功率平衡约束
|
|
435
|
-
for bus in self.Buses:
|
|
436
|
-
flow_in = self.LinesOfTBus(bus.ID)
|
|
437
|
-
flow_out = self.LinesOfFBus(bus.ID)
|
|
438
|
-
j = bus.ID
|
|
439
|
-
Pcons[j] = model.addConstr(Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in) + Qs(pg[j]) == Qs(
|
|
440
|
-
P[ln.ID] for ln in flow_out) + bus.Pd(_t), f"Pcons_{j}")
|
|
441
|
-
Qcons[j] = model.addConstr(Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in) + Qs(qg[j]) == Qs(
|
|
442
|
-
Q[ln.ID] for ln in flow_out) + bus.Qd(_t), f"Qcons_{j}")
|
|
443
|
-
|
|
444
|
-
# 电压和电流平衡约束
|
|
445
|
-
for line in self.Lines:
|
|
446
|
-
i, j = line.pair
|
|
447
|
-
lid = line.ID
|
|
448
|
-
model.addConstr(
|
|
449
|
-
v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
|
|
450
|
-
f"ΔU2_cons_{lid}")
|
|
451
|
-
model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
|
|
452
|
-
|
|
453
|
-
# 配网源节点电压固定为1pu
|
|
454
|
-
model.addConstr(v['B1'] == 1, 'v_B1==1')
|
|
455
|
-
|
|
456
|
-
# 线性发电成本目标函数
|
|
457
|
-
model.setObjective(
|
|
458
|
-
quicksum(g.CostA(_t) * pg0[g.ID] ** 2 + g.CostB(_t) * pg0[g.ID] + g.CostC(_t) for g in self.Gens),
|
|
459
|
-
GRB.MINIMIZE)
|
|
460
|
-
model.setParam('OutputFlag', 0) # 关闭输出
|
|
461
|
-
model.setParam('QCPDual', 1) # 启用二次约束规划对偶
|
|
462
|
-
model.update()
|
|
463
|
-
model.optimize()
|
|
464
|
-
if model.Status != GRB.Status.OPTIMAL:
|
|
465
|
-
return False, 0
|
|
466
|
-
|
|
467
|
-
for bus in self.Buses:
|
|
468
|
-
j = bus.ID
|
|
469
|
-
bus.V = v[j].X ** 0.5
|
|
470
|
-
try:
|
|
471
|
-
sp = Pcons[j].Pi
|
|
472
|
-
except:
|
|
473
|
-
sp = None if not self.__holdShadowPrice else bus.ShadowPrice
|
|
474
|
-
bus.ShadowPrice = sp
|
|
475
|
-
|
|
476
|
-
for line in self.Lines:
|
|
477
|
-
lid = line.ID
|
|
478
|
-
line.I = l[lid].X ** 0.5
|
|
479
|
-
line.P = P[lid].X
|
|
480
|
-
line.Q = Q[lid].X
|
|
481
|
-
|
|
482
|
-
for gen in self.Gens:
|
|
483
|
-
j = gen.ID
|
|
484
|
-
gen.P = pg0[j].X
|
|
485
|
-
gen.Q = qg0[j].X
|
|
486
|
-
|
|
487
|
-
return True, model.ObjVal
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|