fpowerkit 0.1.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fpowerkit
3
- Version: 0.1.0
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.18
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
 
@@ -0,0 +1,5 @@
1
+ from .grid import *
2
+ from .solbase import *
3
+ from .solnt import *
4
+ from .soldist import *
5
+ from .cases import PDNCases
@@ -130,8 +130,8 @@ class Bus:
130
130
  def toXMLNode(self, Ub_kV:Optional[float] = None,
131
131
  Sb_MVA:Optional[float] = None, Sb_kVA:Optional[float] = None) -> 'Element':
132
132
  e = Element("bus", {"ID": self.ID})
133
- if self.Lat is not None: e.attrib["Lat"] = str(self.Lat)
134
- if self.Lon is not None: e.attrib["Lon"] = str(self.Lon)
133
+ if self.Lat is not None: e.attrib["Lat"] = f"{self.Lat:.6f}"
134
+ if self.Lon is not None: e.attrib["Lon"] = f"{self.Lon:.6f}"
135
135
  if self.V is not None and self.FixedV:
136
136
  e.attrib["V"] = str(self.V * Ub_kV)+"kV" if Ub_kV else str(self.V)
137
137
  else:
@@ -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
- load_fluctuation:'list[tuple[int,float]]',
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(load_fluctuation) == 0:
269
- for i in range(load_repeat):
270
- for j in range(24):
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 = load_fluctuation
274
- load_fluctuation = []
275
- for i in range(load_repeat):
276
- for j in range(24):
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,load_fluctuation),
280
- _create_load(p[2]/Sb_KVA,load_fluctuation),min_v_pu=0.9,max_v_pu=1.1) for p in LOAD]
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,load_fluctuation),
285
- _create_load(p[2]/Sb_KVA,load_fluctuation),min_v_pu=0.9,max_v_pu=1.1) for p in LOAD])
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
- load_fluctuation:'list[tuple[int, float]]' = [],
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, load_fluctuation, load_repeat, load_period),
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
- load_fluctuation:'list[tuple[int, float]]' = [],
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, load_fluctuation, load_repeat, load_period),
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
@@ -199,6 +199,8 @@ class Generator:
199
199
  "ID": self.ID,
200
200
  "Bus": self.BusID,
201
201
  })
202
+ if self.Lat is not None: e.attrib["Lat"] = f"{self.Lat:.6f}"
203
+ if self.Lon is not None: e.attrib["Lon"] = f"{self.Lon:.6f}"
202
204
  if Sb_MVA is not None and Sb_kVA is not None:
203
205
  raise ValueError("Provide only ONE of Sb_MVA or Sb_kVA.")
204
206
  if Sb_MVA is not None:
@@ -210,8 +212,6 @@ class Generator:
210
212
  else:
211
213
  mul = 1
212
214
  unit = ["pu", "pu", "$/puh2", "$/puh", "$"]
213
- if self.Lat is not None: e.attrib["Lat"] = str(self.Lat)
214
- if self.Lon is not None: e.attrib["Lon"] = str(self.Lon)
215
215
  if self.Pmin: e.append(Func2Elem(self.Pmin, "Pmin", mul, unit[0]))
216
216
  if self.Pmax: e.append(Func2Elem(self.Pmax, "Pmax", mul, unit[0]))
217
217
  if self.Qmin: e.append(Func2Elem(self.Qmin, "Qmin", mul, unit[1]))
@@ -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]', holdShadowPrice: bool = False):
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,11 +95,85 @@ 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):
112
+ '''Add a generator'''
93
113
  self._gens[g.ID] = g
114
+ assert g.BusID in self._bnames, f"Bus {g.BusID} undefined"
94
115
  self._gatb[g.BusID].append(g)
116
+
117
+ def DelGen(self, id: str):
118
+ '''Delete a generator'''
119
+ g = self._gens.pop(id)
120
+ self._gatb[g.BusID].remove(g)
121
+
122
+ def AddBus(self, b: Bus):
123
+ '''Add a bus'''
124
+ self._buses[b.ID] = b
125
+ self._bnames.append(b.ID)
126
+ self._ladjfb[b.ID] = []
127
+ self._ladjtb[b.ID] = []
128
+ self._gatb[b.ID] = []
129
+ self._patb[b.ID] = []
130
+
131
+ def DelBus(self, id: str):
132
+ '''Delete a bus and all related lines, generators and PVWinds'''
133
+ b = self._buses.pop(id)
134
+ self._bnames.remove(id)
135
+ for l in self._ladjfb[b.ID]: self._lines.pop(l.ID)
136
+ for l in self._ladjtb[b.ID]: self._lines.pop(l.ID)
137
+ for g in self._gatb[b.ID]: self._gens.pop(g.ID)
138
+ for p in self._patb[b.ID]: self._pvws.pop(p.ID)
139
+ self._ladjfb.pop(b.ID)
140
+ self._ladjtb.pop(b.ID)
141
+ self._gatb.pop(b.ID)
142
+ self._patb.pop(b.ID)
143
+
144
+ def AddLine(self, l: Line):
145
+ '''Add a line'''
146
+ self._lines[l.ID] = l
147
+ assert l.fBus in self._bnames, f"Bus {l.fBus} undefined"
148
+ assert l.tBus in self._bnames, f"Bus {l.tBus} undefined"
149
+ self._ladjfb[l.fBus].append(l)
150
+ self._ladjtb[l.tBus].append(l)
151
+
152
+ def DelLine(self, id: str):
153
+ '''Delete a line'''
154
+ l = self._lines.pop(id)
155
+ self._ladjfb[l.fBus].remove(l)
156
+ self._ladjtb[l.tBus].remove(l)
157
+
158
+ def AddPVWind(self, p: PVWind):
159
+ '''Add a PVWind'''
160
+ self._pvws[p.ID] = p
161
+ assert p.BusID in self._bnames, f"Bus {p.BusID} undefined"
162
+ self._patb[p.BusID].append(p)
163
+
164
+ def DelPVWind(self, id: str):
165
+ '''Delete a PVWind'''
166
+ p = self._pvws.pop(id)
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)
95
177
 
96
178
  @property
97
179
  def BusNames(self) -> 'list[str]':
@@ -183,6 +265,24 @@ class Grid:
183
265
  self._bnames.remove(old_id)
184
266
  self._bnames.append(new_id)
185
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
+
186
286
  @property
187
287
  def Buses(self):
188
288
  return self._buses.values()
@@ -225,6 +325,16 @@ class Grid:
225
325
  def PVWindNames(self) -> 'list[str]':
226
326
  return list(self._pvws.keys())
227
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
+
228
338
  def __repr__(self):
229
339
  b = '\n '.join(map(str, self._buses.values()))
230
340
  l = '\n '.join(map(str, self._lines.values()))
@@ -289,7 +399,10 @@ class Grid:
289
399
  lines:list[Line] = []
290
400
  gens:list[Generator] = []
291
401
  pvws:list[PVWind] = []
402
+ esss:list[ESS] = []
292
403
  #Read buses, lines and generators
404
+ cp = 0
405
+ dp = 0
293
406
 
294
407
  gen_models:dict[str, GeneratorModel] = {}
295
408
  for e in rt:
@@ -308,9 +421,15 @@ class Grid:
308
421
  gen_models[e.attrib["name"]] = GeneratorModel.fromXML(e, Sb, Ub)
309
422
  elif e.tag == "pv" or e.tag == "wind":
310
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)
311
430
  else:
312
431
  raise ValueError(f"Unknown XML node: {e.tag}")
313
- return Grid(Sb, Ub, buses, lines, gens, pvws, holdShadowPrice)
432
+ return Grid(Sb, Ub, buses, lines, gens, pvws, esss, cp, dp, holdShadowPrice)
314
433
 
315
434
  def YMat(self):
316
435
  '''Return the admittance matrix of the grid'''
@@ -350,6 +469,11 @@ class Grid:
350
469
  Sb_MVA = self.Sb_MVA if PQmode == PQSaveMode.MVA else None,
351
470
  Sb_kVA = self.Sb_kVA if PQmode == PQSaveMode.KVA else None
352
471
  ))
472
+ for p in self.PVWinds:
473
+ e.append(p.toXMLNode(
474
+ Sb_MVA = self.Sb_MVA if PQmode == PQSaveMode.MVA else None,
475
+ Sb_kVA = self.Sb_kVA if PQmode == PQSaveMode.KVA else None
476
+ ))
353
477
  return e
354
478
 
355
479
  def saveFileXML(self, path:str,
@@ -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
- i_pu: NFloat = None, p_pu: NFloat = None, q_pu: NFloat = None, max_I_kA: float = math.inf):
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
- return Line(id, f, t, r, x, max_I_kA=max_I)
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
  })