fpowerkit 0.1.6__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/PKG-INFO +12 -3
  2. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/__init__.py +1 -0
  3. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/cases.py +8 -8
  4. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/ess.py +7 -2
  5. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/grid.py +6 -4
  6. fpowerkit-0.2.0/fpowerkit/solcmb.py +35 -0
  7. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/soldist.py +151 -109
  8. fpowerkit-0.2.0/fpowerkit/soldss.py +102 -0
  9. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit.egg-info/PKG-INFO +12 -3
  10. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit.egg-info/SOURCES.txt +1 -0
  11. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit.egg-info/requires.txt +2 -1
  12. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/setup.py +2 -2
  13. fpowerkit-0.1.6/fpowerkit/soldss.py +0 -47
  14. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/LICENSE +0 -0
  15. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/README.md +0 -0
  16. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/bus.py +0 -0
  17. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/gen.py +0 -0
  18. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/line.py +0 -0
  19. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/pvwind.py +0 -0
  20. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/solbase.py +0 -0
  21. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/solnt.py +0 -0
  22. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit/utils.py +0 -0
  23. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit.egg-info/dependency_links.txt +0 -0
  24. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/fpowerkit.egg-info/top_level.txt +0 -0
  25. {fpowerkit-0.1.6 → fpowerkit-0.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: fpowerkit
3
- Version: 0.1.6
3
+ Version: 0.2.0
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -10,8 +10,9 @@ Requires-Python: >=3.8
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
12
  Requires-Dist: feasytools>=0.0.21
13
- Requires-Dist: gurobipy>=9.1.0
13
+ Requires-Dist: cvxpy>=1.0
14
14
  Requires-Dist: numpy>=1.20.0
15
+ Requires-Dist: ecos
15
16
  Dynamic: author
16
17
  Dynamic: classifier
17
18
  Dynamic: description
@@ -22,7 +23,15 @@ Dynamic: summary
22
23
 
23
24
  # FPowerKit - A power distribution network calculation component
24
25
 
25
- This is a package based on Gurobipy implementing optimal power flow (OPF).
26
+ This is a package designed for power distribution network solving.
27
+
28
+ There are 3 modes for this package to work:
29
+
30
+ - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
31
+
32
+ - Power flow calculation: Use OpenDSS or Netwon-Raphson method to solve the power flow with given generator ouputs.
33
+
34
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS or Newton method to perform accurate calculation.
26
35
 
27
36
  Since this package is still under development, the API is unstable and may be changed anytime.
28
37
 
@@ -3,4 +3,5 @@ from .solbase import *
3
3
  from .solnt import *
4
4
  from .soldist import *
5
5
  from .soldss import *
6
+ from .solcmb import *
6
7
  from .cases import PDNCases
@@ -274,22 +274,22 @@ def _get_buses(
274
274
  for j in range(24):
275
275
  load_fluc.append((ls[j][0], ls[j][1]))
276
276
  if grid_repeat == 1:
277
- B = [Bus("B"+str(p[0]), _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
277
+ B = [Bus("b"+str(p[0]), _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
278
278
  _create_load(p[2]/Sb_KVA,load_fluc).repeat(load_repeat,load_period),
279
279
  min_v_pu=0.9,max_v_pu=1.1) for p in LOAD]
280
280
  else:
281
281
  B = []
282
282
  for i in range(grid_repeat):
283
- B.extend([Bus(f"B{i}_{p[0]}", _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
283
+ B.extend([Bus(f"b{i}_{p[0]}", _create_load(p[1]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
284
284
  _create_load(p[2]/Sb_KVA,load_fluc).repeat(load_repeat, load_period),
285
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
- 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]
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]
289
289
  else:
290
290
  B = []
291
291
  for i in range(grid_repeat):
292
- B.extend([Bus(f"B{i}_{p[0]}", p[1]/Sb_KVA, p[2]/Sb_KVA, min_v_pu=0.9,max_v_pu=1.1) for p in LOAD])
292
+ B.extend([Bus(f"b{i}_{p[0]}", p[1]/Sb_KVA, p[2]/Sb_KVA, min_v_pu=0.9,max_v_pu=1.1) for p in LOAD])
293
293
  B[0].fixV(1.0)
294
294
  B[0].Pd = ConstFunc(0)
295
295
  B[0].Qd = ConstFunc(0)
@@ -299,20 +299,20 @@ def _get_buses(
299
299
 
300
300
  def _get_lines(Zb:float, LINE:'list[tuple[int,int,int,float,float]]', grid_repeat:int):
301
301
  if grid_repeat == 1:
302
- L = [Line("L"+str(p[0]), "B"+str(p[1]), "B"+str(p[2]), p[3]/Zb, p[4]/Zb) for p in LINE]
302
+ L = [Line("l"+str(p[0]), "b"+str(p[1]), "b"+str(p[2]), p[3]/Zb, p[4]/Zb) for p in LINE]
303
303
  else:
304
304
  L = []
305
305
  for i in range(grid_repeat):
306
- L.extend([Line(f"L{i}_{p[0]}", f"B{i}_{p[1]}", f"B{i}_{p[2]}", p[3]/Zb, p[4]/Zb) for p in LINE])
306
+ L.extend([Line(f"l{i}_{p[0]}", f"b{i}_{p[1]}", f"b{i}_{p[2]}", p[3]/Zb, p[4]/Zb) for p in LINE])
307
307
  return L
308
308
 
309
309
  def _get_gens(default_gen:GeneratorModel, gen_pos:'list[int]', grid_repeat:int):
310
310
  if grid_repeat == 1:
311
- G = [default_gen.toGenerator("G"+p, "B"+p) for p in map(str,gen_pos)]
311
+ G = [default_gen.toGenerator("g"+p, "b"+p) for p in map(str,gen_pos)]
312
312
  else:
313
313
  G = []
314
314
  for i in range(grid_repeat):
315
- G.extend([default_gen.toGenerator(f"G{i}_{p}", f"B{i}_{p}") for p in gen_pos])
315
+ G.extend([default_gen.toGenerator(f"g{i}_{p}", f"b{i}_{p}") for p in gen_pos])
316
316
  return G
317
317
 
318
318
  class PDNCases:
@@ -77,6 +77,11 @@ class ESS:
77
77
  return P * math.sqrt(1 - self._pf**2)
78
78
 
79
79
  def GetLoad(self, t: int, cprice:float, dprice:float) -> tuple[float, float]:
80
+ '''
81
+ Get the power of the ESS. Return p+jq.
82
+ p > 0 means the ESS is charging, and thus the ESS is treated as a load.
83
+ p < 0 means the ESS is discharging, and thus the ESS is treated as a generator.
84
+ '''
80
85
  if self._policy == ESSPolicy.Manual:
81
86
  if self._manstate == ESSManualState.Charge and self._elec < self._cap:
82
87
  return self._pc_max, self.__q(self._pc_max)
@@ -89,9 +94,9 @@ class ESS:
89
94
  return -self._pd_max, -self.__q(self._pd_max)
90
95
  elif self._policy == ESSPolicy.Price:
91
96
  if self._cprice is not None and self._dprice is not None:
92
- if self._cprice < cprice and self._elec < self._cap:
97
+ if cprice < self._cprice and self._elec < self._cap:
93
98
  return self._pc_max, self.__q(self._pc_max)
94
- elif self._dprice > dprice and self._elec > 0:
99
+ elif dprice > self._dprice and self._elec > 0:
95
100
  return -self._pd_max, -self.__q(self._pd_max)
96
101
  else:
97
102
  raise ValueError("Unknown ESS policy")
@@ -91,13 +91,13 @@ class Grid:
91
91
  self._ladjfb[line.fBus].append(line)
92
92
  self._ladjtb[line.tBus].append(line)
93
93
  for gen in self._gens.values():
94
- assert gen.BusID in self._bnames
94
+ assert gen.BusID in self._bnames, f"Bus {gen.BusID} undefined"
95
95
  self._gatb[gen.BusID].append(gen)
96
96
  for pvw in self._pvws.values():
97
- assert pvw.BusID in self._bnames
97
+ assert pvw.BusID in self._bnames, f"Bus {pvw.BusID} undefined"
98
98
  self._patb[pvw.BusID].append(pvw)
99
99
  for ess in self._esss.values():
100
- assert ess.BusID in self._bnames
100
+ assert ess.BusID in self._bnames, f"Bus {ess.BusID} undefined"
101
101
  self._eatb[ess.BusID].append(ess)
102
102
 
103
103
  @property
@@ -364,6 +364,8 @@ class Grid:
364
364
  rt = ElementTree(file=xml_name).getroot()
365
365
  else:
366
366
  raise ValueError("Unsupported file type")
367
+ if rt is None:
368
+ raise ValueError(f"Invalid XML file: {xml_name}")
367
369
  # Read base values
368
370
  Sb, unit = ReadVal(rt.attrib["Sb"])
369
371
  if unit == "MVA": pass
@@ -431,7 +433,7 @@ class Grid:
431
433
  raise ValueError(f"Unknown XML node: {e.tag}")
432
434
  return Grid(Sb, Ub, buses, lines, gens, pvws, esss, cp, dp, holdShadowPrice)
433
435
 
434
- def YMat(self):
436
+ def YMat(self) -> 'np.ndarray':
435
437
  '''Return the admittance matrix of the grid'''
436
438
  n = len(self._buses)
437
439
  Y = np.zeros((n, n), dtype=complex)
@@ -0,0 +1,35 @@
1
+ from .grid import Grid
2
+ from .solbase import GridSolveResult, SolverBase
3
+ from .soldist import DistFlowSolver
4
+ from .soldss import OpenDSSSolver
5
+ from .solnt import NewtonSolver
6
+ from warnings import warn
7
+
8
+ class CombinedSolver(SolverBase):
9
+ """
10
+ A class that use DistFlowSolver to estimate the power flow and then use OpenDSSSolver or NewtonSolver to solve the power flow problem.
11
+ """
12
+ def __init__(self, g: Grid, estimator:str = 'distflow', calculator:str = 'opendss', mlrp:float = 0.5 ,source_bus:str = ""):
13
+ assert estimator in ['distflow',], "Invalid estimator. Currently only 'distflow' is available."
14
+ assert calculator in ['opendss', 'newton', 'none'], "Invalid solver type. Choose from 'opendss', 'newton' of 'none'."
15
+ self.est = DistFlowSolver(g, mlrp = mlrp)
16
+ self.cal_str = calculator
17
+ if calculator == 'opendss':
18
+ assert source_bus != "", "source_bus cannot be empty when using OpenDSSSolver."
19
+ self.source_bus = source_bus
20
+ else:
21
+ if source_bus != "":
22
+ warn(Warning("source_bus is ignored when not using OpenDSSSolver."))
23
+
24
+ def solve(self, _t:int, /, *, timeout_s: float = 1):
25
+ res, obj = self.est.solve(_t, timeout_s=timeout_s)
26
+ if res == GridSolveResult.Failed:
27
+ return res, obj
28
+ if self.cal_str == 'none':
29
+ return res, obj
30
+ elif self.cal_str == 'opendss':
31
+ solver = OpenDSSSolver(self.est.grid, self.source_bus)
32
+ else:
33
+ solver = NewtonSolver(self.est.grid)
34
+ res, obj = solver.solve(_t, timeout_s=timeout_s)
35
+ return res, obj
@@ -1,30 +1,30 @@
1
1
  from itertools import chain
2
- from gurobipy import GRB, Constr, LinExpr, Model, Var
3
- from gurobipy import quicksum as Qs
2
+ import cvxpy as cp
4
3
  from pathlib import Path
5
4
  from typing import Optional, Union
6
5
  from dataclasses import dataclass
7
6
  from collections import deque
8
- import warnings, math
7
+ import math
9
8
  from .solbase import *
10
9
 
10
+ Var = cp.Variable
11
11
  VF = Union[Var, float]
12
12
 
13
13
  @dataclass
14
14
  class LoadReduceModule:
15
15
  '''Load Reduce module'''
16
- Bus:BusID
17
- Limit:TimeFunc
18
- Reduction:FloatVar = None
16
+ Bus: BusID
17
+ Limit: TimeFunc
18
+ Reduction: FloatVar = None
19
19
 
20
20
  class _Island:
21
- def __init__(self, g:Grid, buses:Iterable[BusID], cutlines:set[LineID]):
21
+ def __init__(self, g: Grid, buses: Iterable[BusID], cutlines: set[LineID]):
22
22
  self.grid = g
23
- self.Buses:set[str] = set()
24
- self.Gens:set[str] = set()
25
- self.Lines:set[str] = set()
26
- self.PVWs:set[str] = set()
27
- self.ESSs:set[str] = set()
23
+ self.Buses: set[str] = set()
24
+ self.Gens: set[str] = set()
25
+ self.Lines: set[str] = set()
26
+ self.PVWs: set[str] = set()
27
+ self.ESSs: set[str] = set()
28
28
  for b in buses:
29
29
  self.Buses.add(b)
30
30
  self.Gens.update(gen.ID for gen in g._gatb[b])
@@ -67,8 +67,8 @@ class IslandResult(IntEnum):
67
67
 
68
68
  class DistFlowSolver(SolverBase):
69
69
  '''DistFlow solver'''
70
- def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, /,
71
- *, mlrp:float = 0.5, secondary_cost:bool = True):
70
+ def __init__(self, grid: Grid, eps: float = 1e-6, default_saveto: str = DEFAULT_SAVETO, /,
71
+ *, mlrp: float = 0.5, secondary_cost: bool = True):
72
72
  '''
73
73
  Initialize
74
74
  grid: Grid object
@@ -80,11 +80,11 @@ class DistFlowSolver(SolverBase):
80
80
  which is likely to induce numerical instability.
81
81
  '''
82
82
  super().__init__(grid, eps, default_saveto)
83
- self._decb:dict[BusID, LoadReduceModule] = {}
83
+ self._decb: dict[BusID, LoadReduceModule] = {}
84
84
  self.C = 1e9
85
85
  self._mlrp = mlrp
86
- self._oflines:set[LineID] = set()
87
- self._ofbuses:set[BusID] = set()
86
+ self._oflines: set[LineID] = set()
87
+ self._ofbuses: set[BusID] = set()
88
88
  self._sec_cost = secondary_cost
89
89
  self.UpdateGrid()
90
90
 
@@ -96,22 +96,22 @@ class DistFlowSolver(SolverBase):
96
96
  def OverflowBuses(self):
97
97
  return self._ofbuses
98
98
 
99
- def UpdateGrid(self, cut_overflow_lines:bool = False):
99
+ def UpdateGrid(self, cut_overflow_lines: bool = False):
100
100
  self._islands = tuple(
101
101
  _Island(self.grid, il, self._oflines) for il in self.__detect_islands(cut_overflow_lines)
102
102
  )
103
103
  self._island_res = [(IslandResult.Undefined, -1.0) for _ in range(len(self._islands))]
104
104
  self.__il_relax = [False] * len(self._islands)
105
105
 
106
- def __detect_islands(self, cutofl:bool):
106
+ def __detect_islands(self, cutofl: bool):
107
107
  '''Detect islands'''
108
- q:deque[BusID] = deque()
109
- visited:set[BusID] = set()
110
- islands:list[set[BusID]] = []
108
+ q: deque[BusID] = deque()
109
+ visited: set[BusID] = set()
110
+ islands: list[set[BusID]] = []
111
111
  for bus in self.grid.BusNames:
112
112
  if bus in visited: continue
113
113
  q.append(bus)
114
- island:set[BusID] = set()
114
+ island: set[BusID] = set()
115
115
  while len(q) > 0:
116
116
  b = q.popleft()
117
117
  if b in visited: continue
@@ -141,22 +141,22 @@ class DistFlowSolver(SolverBase):
141
141
  '''Get the maximum load reduction proportion'''
142
142
  return self._mlrp
143
143
  @MLRP.setter
144
- def MLRP(self, v:float):
144
+ def MLRP(self, v: float):
145
145
  '''Set the maximum load reduction proportion'''
146
146
  if v < 0 or v > 1:
147
147
  raise ValueError("Invalid maximum load reduction proportion")
148
148
  self._mlrp = v
149
149
 
150
- def AddReduce(self, bus:BusID, limit:TimeFunc, reduction:Optional[FloatVar] = None):
150
+ def AddReduce(self, bus: BusID, limit: TimeFunc, reduction: Optional[FloatVar] = None):
151
151
  '''Add a load reduction module'''
152
152
  self._decb[bus] = LoadReduceModule(bus, limit, reduction)
153
153
 
154
- def RemoveReduce(self, bus:BusID):
154
+ def RemoveReduce(self, bus: BusID):
155
155
  '''Remove a load reduction module'''
156
156
  if bus in self._decb:
157
157
  del self._decb[bus]
158
158
 
159
- def GetReduce(self, bus:BusID) -> LoadReduceModule:
159
+ def GetReduce(self, bus: BusID) -> LoadReduceModule:
160
160
  '''Get the load reduction module'''
161
161
  return self._decb[bus]
162
162
 
@@ -164,7 +164,7 @@ class DistFlowSolver(SolverBase):
164
164
  def DecBuses(self):
165
165
  return self._decb
166
166
 
167
- def solve(self, _t: int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
167
+ def solve(self, _t: int, /, *, timeout_s: float = 1) -> 'tuple[GridSolveResult, float]':
168
168
  '''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
169
169
  allOK = True
170
170
  allFail = True
@@ -192,8 +192,16 @@ class DistFlowSolver(SolverBase):
192
192
  else:
193
193
  return GridSolveResult.PartialOK, val
194
194
 
195
- def __solve(self, _t: int, island:_Island, timeout_s:float, relaxV:bool, relaxI:bool, clear_results:bool=False) -> 'tuple[IslandResult, float]':
196
- model = Model("model")
195
+ def __chkv(self, d: Union[None, np.ndarray]) -> float:
196
+ assert d is not None, "Value is None"
197
+ assert isinstance(d, (np.ndarray, np.float64, float)), f"Value is {type(d)}"
198
+ ret = d.item()
199
+ assert isinstance(ret, float), f"Value is not a float: {type(ret)}"
200
+ assert ret != float('inf'), "Value is inf"
201
+ assert ret != float('-inf'), "Value is -inf"
202
+ return ret
203
+
204
+ def __solve(self, _t: int, island: _Island, timeout_s: float, relaxV: bool, relaxI: bool, clear_results: bool = False) -> 'tuple[IslandResult, float]':
197
205
 
198
206
  ''' ---------Variables----------
199
207
  pg0[k]: Generator active power
@@ -206,6 +214,7 @@ class DistFlowSolver(SolverBase):
206
214
  P[i,j]: Line active power
207
215
  Q[i,j]: Line reactive power
208
216
  '''
217
+ cons:list[cp.Constraint] = []
209
218
  # Create GEN vars
210
219
  pg0: dict[str, VF] = {}
211
220
  qg0: dict[str, VF] = {}
@@ -214,23 +223,36 @@ class DistFlowSolver(SolverBase):
214
223
  assert g.P is not None
215
224
  pg0[gID] = g.P(_t) if isinstance(g.P, TimeFunc) else g.P
216
225
  elif g.Pmin is not None and g.Pmax is not None:
217
- pg0[gID] = model.addVar(name=f"pg_{gID}", vtype='C', lb=g.Pmin(_t), ub=g.Pmax(_t))
226
+ v = Var(name=f"pg_{gID}")
227
+ cons.append(v >= g.Pmin(_t))
228
+ cons.append(v <= g.Pmax(_t))
229
+ pg0[gID] = v
218
230
  else:
219
231
  raise ValueError(f"Generator {gID} provides neither P or (pmin, pmax)")
220
232
  if g.FixedQ:
221
233
  assert g.Q is not None
222
234
  qg0[gID] = g.Q(_t) if isinstance(g.Q, TimeFunc) else g.Q
223
235
  elif g.Qmin is not None and g.Qmax is not None:
224
- qg0[gID] = model.addVar(name=f"qg_{gID}", vtype='C', lb=g.Qmin(_t), ub=g.Qmax(_t))
236
+ v = Var(name=f"qg_{gID}")
237
+ cons.append(v >= g.Qmin(_t))
238
+ cons.append(v <= g.Qmax(_t))
239
+ qg0[gID] = v
225
240
  else:
226
241
  raise ValueError(f"Generator {g.ID} provides neither Q or (qmin, qmax)")
227
242
 
228
- pvwp: dict[str, Var] = {pID: model.addVar(
229
- name=f"pvw_{pID}", vtype='C', lb=0, ub=p.P(_t)
230
- ) for pID, p in island.PVWItems()}
231
- pvwq: dict[str, Var] = {pID: model.addVar(
232
- name=f"pvw_{pID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY
233
- ) for pID in island.PVWs}
243
+ pvwp: dict[str, Var] = {
244
+ pID: Var(name=f"pvw_{pID}", nonneg=True)
245
+ for pID, p in island.PVWItems()
246
+ }
247
+ pvwq: dict[str, Var] = {
248
+ pID: Var(name=f"pvwq_{pID}")
249
+ for pID in island.PVWs
250
+ }
251
+
252
+ # Add PVW constraints
253
+ for pID, p in island.PVWItems():
254
+ cons.append(pvwp[pID] <= p.P(_t))
255
+ cons.append(pvwp[pID] * math.sqrt(1 - p.PF**2) == pvwq[pID])
234
256
 
235
257
  # Bind GEN vars to Bus
236
258
  pg: dict[str, list[VF]] = {b: [] for b in island.Buses}
@@ -254,82 +276,103 @@ class DistFlowSolver(SolverBase):
254
276
  qg[e.BusID].append(-q)
255
277
 
256
278
  # Create BUS vars
257
- v = {bID: model.addVar(name=f"v_{bID}", vtype='C') for bID in island.Buses}
258
- dvmin:dict[str, Var] = {}
259
- dvmax:dict[str, Var] = {}
279
+ v = {bID: Var(name=f"v_{bID}") for bID in island.Buses}
280
+ dvmin: dict[str, Var] = {}
281
+ dvmax: dict[str, Var] = {}
260
282
  for bid, b in island.BusItems():
261
283
  if b.FixedV:
262
284
  assert b.V is not None, f"Bus {bid} has fixed voltage but not set"
263
- model.addConstr(v[bid] == b.V ** 2)
285
+ cons.append(v[bid] == b.V ** 2)
264
286
  elif relaxV:
265
- dvmin[bid] = model.addVar(name=f"dvmin_{bid}", vtype='C', lb=0)
266
- dvmax[bid] = model.addVar(name=f"dvmax_{bid}", vtype='C', lb=0)
267
- model.addConstr(v[bid] >= b.MinV ** 2 - dvmin[bid])
268
- model.addConstr(v[bid] <= b.MaxV ** 2 + dvmax[bid])
287
+ dvmin[bid] = Var(name=f"dvmin_{bid}", nonneg=True)
288
+ dvmax[bid] = Var(name=f"dvmax_{bid}", nonneg=True)
289
+ cons.append(v[bid] >= b.MinV ** 2 - dvmin[bid])
290
+ cons.append(v[bid] <= b.MaxV ** 2 + dvmax[bid])
269
291
  else:
270
- model.addConstr(v[bid] >= b.MinV ** 2)
271
- model.addConstr(v[bid] <= b.MaxV ** 2)
292
+ cons.append(v[bid] >= b.MinV ** 2)
293
+ cons.append(v[bid] <= b.MaxV ** 2)
272
294
 
273
295
  # Create Line vars
274
- dlmax:dict[str, Var] = {}
275
- l = {lID: model.addVar(name=f"l_{lID}", vtype='C', lb=0) for lID in island.Lines}
296
+ dlmax: dict[str, Var] = {}
297
+ l = {lID: Var(name=f"l_{lID}", nonneg=True) for lID in island.Lines}
298
+
276
299
  for lID, ln in island.LineItems():
300
+ if ln.max_I == math.inf:
301
+ continue
277
302
  if relaxI:
278
- dlmax[lID] = model.addVar(name=f"dlmax_{lID}", vtype='C', lb=0)
279
- model.addConstr(l[lID] <= (ln.max_I/island.grid.Ib) ** 2 + dlmax[lID])
303
+ dlmax[lID] = Var(name=f"dlmax_{lID}", nonneg=True)
304
+ cons.append(l[lID] <= (ln.max_I/island.grid.Ib) ** 2 + dlmax[lID])
280
305
  else:
281
- model.addConstr(l[lID] <= (ln.max_I/island.grid.Ib) ** 2)
282
-
283
- P = {lID: model.addVar(name=f"P_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
284
- island.Lines}
285
- Q = {lID: model.addVar(name=f"Q_{lID}", vtype='C', lb=-GRB.INFINITY, ub=GRB.INFINITY) for lID in
286
- island.Lines}
306
+ cons.append(l[lID] <= (ln.max_I/island.grid.Ib) ** 2)
287
307
 
288
- Pdec:dict[BusID, Var] = {bus: model.addVar(name=f"Pdec_{bus}", vtype='C',
289
- lb=0, ub=lim.Limit(_t) * self._mlrp) for bus, lim in self._decb.items()}
308
+ P = {lID: Var(name=f"P_{lID}") for lID in island.Lines}
309
+ Q = {lID: Var(name=f"Q_{lID}") for lID in island.Lines}
310
+
311
+ Pdec: dict[BusID, Var] = {
312
+ bus: Var(name=f"Pdec_{bus}", nonneg=True)
313
+ for bus, lim in self._decb.items()
314
+ }
315
+ for bus, lim in self._decb.items():
316
+ cons.append(Pdec[bus] <= lim.Limit(_t) * self._mlrp)
290
317
 
291
318
  # ----------Constraints-----------
292
- Pcons: dict[str, Constr] = {}
293
- Qcons: dict[str, Constr] = {}
294
-
295
319
  for j, bus in island.BusItems():
296
320
  flow_in = island.grid.LinesOfTBus(j)
297
321
  flow_out = island.grid.LinesOfFBus(j)
298
322
  dec = Pdec[j] if j in Pdec else 0
299
- Pcons[j] = model.addConstr(
300
- Qs(P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(pg[j]) == Qs(
301
- P[ln.ID] for ln in flow_out if ln.ID in island.Lines) + pd[j] - dec, f"Pcons_{j}")
302
- Qcons[j] = model.addConstr(
303
- Qs(Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines) + Qs(qg[j]) == Qs(
304
- Q[ln.ID] for ln in flow_out if ln.ID in island.Lines) + qd[j], f"Qcons_{j}")
323
+
324
+ # P constraint
325
+ inflow = cp.sum([P[ln.ID] - ln.R * l[ln.ID] for ln in flow_in if ln.ID in island.Lines])
326
+ outflow = cp.sum([P[ln.ID] for ln in flow_out if ln.ID in island.Lines])
327
+ cons.append(
328
+ inflow + cp.sum(pg[j]) == outflow + pd[j] - dec # type: ignore
329
+ )
330
+
331
+ # Q constraint
332
+ q_inflow = cp.sum([Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines])
333
+ q_outflow = cp.sum([Q[ln.ID] for ln in flow_out if ln.ID in island.Lines])
334
+ cons.append(
335
+ q_inflow + cp.sum(qg[j]) == q_outflow + qd[j] # type: ignore
336
+ )
305
337
 
306
338
  for lid, line in island.LineItems():
307
339
  i, j = line.pair
308
340
  lid = line.ID
309
- model.addConstr(
310
- v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid],
311
- f"ΔU2_cons_{lid}")
312
- model.addConstr(P[lid] ** 2 + Q[lid] ** 2 <= l[lid] * v[i], f"SoC_cons_{lid}")
341
+ cons.append(
342
+ v[j] == v[i] - 2 * (line.R * P[lid] + line.X * Q[lid]) + (line.R ** 2 + line.X ** 2) * l[lid]
343
+ )
344
+ cons.append(
345
+ cp.quad_over_lin(cp.hstack([P[lid], Q[lid]]), v[i]) <= l[lid]
346
+ )
313
347
 
314
348
  for pID, p in island.PVWItems():
315
- model.addConstr(pvwp[pID] * math.sqrt(1 - p.PF**2) == pvwq[pID])
349
+ cons.append(pvwp[pID] + cp.sqrt(1 - p.PF**2) == pvwq[pID])
316
350
 
317
- decs = self.C * (Qs(Pdec.values()) + Qs(dvmin.values()) + Qs(dvmax.values()) + Qs(dlmax.values()))
318
- crpe = Qs(p.CC*(p.P(_t)-pvwp[pID]) for pID, p in island.PVWItems())
351
+ # Objective components
352
+ decs = self.C * (cp.sum(list(Pdec.values())) +
353
+ (cp.sum(list(dvmin.values())) if relaxV else 0) +
354
+ (cp.sum(list(dvmax.values())) if relaxV else 0) +
355
+ (cp.sum(list(dlmax.values())) if relaxI else 0))
356
+
357
+ crpe = cp.sum([p.CC*(p.P(_t)-pvwp[pID]) for pID, p in island.PVWItems()])
358
+
319
359
  if self._sec_cost:
320
- goal = Qs(g.CostA(_t) * pg0[gID] ** 2 + g.CostB(_t) * pg0[gID] + g.CostC(_t) for gID, g in island.GenItems())
360
+ goal = cp.sum([g.CostA(_t) * cp.square(pg0[gID]) + g.CostB(_t) * pg0[gID] + g.CostC(_t)
361
+ for gID, g in island.GenItems()])
321
362
  else:
322
- goal = Qs(g.CostB(_t) * pg0[gID] + g.CostC(_t) for gID, g in island.GenItems())
363
+ goal = cp.sum([g.CostB(_t) * pg0[gID] + g.CostC(_t)
364
+ for gID, g in island.GenItems()])
323
365
 
324
- model.setObjective(decs + goal + crpe, GRB.MINIMIZE)
325
- model.setParam(GRB.Param.OutputFlag, 0)
326
- model.setParam(GRB.Param.QCPDual, 1)
327
- model.setParam(GRB.Param.TimeLimit, timeout_s)
328
- model.setParam(GRB.Param.OptimalityTol, 1e-6)
329
- model.update()
330
- model.optimize()
366
+ problem = cp.Problem(cp.Minimize(decs + goal + crpe), cons)
367
+
368
+ try:
369
+ problem.solve(solver=cp.ECOS, verbose=False)
370
+ except cp.SolverError as e:
371
+ if "installed" in e.args[0]:
372
+ raise e
373
+ return IslandResult.Failed, -1
331
374
 
332
- if model.Status != GRB.Status.OPTIMAL and model.Status != GRB.Status.SUBOPTIMAL:
375
+ if problem.status not in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]:
333
376
  for _, bus in island.BusItems():
334
377
  if not bus.FixedV: bus._v = 0
335
378
  bus.ShadowPrice = 0
@@ -345,45 +388,44 @@ class DistFlowSolver(SolverBase):
345
388
  return IslandResult.Failed, -1
346
389
 
347
390
  for j, bus in island.BusItems():
348
- bus._v = v[j].X ** 0.5
349
- try:
350
- sp = Pcons[j].Pi
351
- except:
352
- sp = None if not self.grid._holdShadowPrice else bus.ShadowPrice
353
- bus.ShadowPrice = sp
391
+ bus._v = self.__chkv(v[j].value) ** 0.5
354
392
 
355
393
  for lid, line in island.LineItems():
356
- line.I = l[lid].X ** 0.5
357
- line.P = P[lid].X
358
- line.Q = Q[lid].X
394
+ line.I = self.__chkv(l[lid].value) ** 0.5
395
+ line.P = self.__chkv(P[lid].value)
396
+ line.Q = self.__chkv(Q[lid].value)
359
397
 
360
398
  for j, gen in island.GenItems():
361
399
  p = pg0[j]
362
- if isinstance(p, Var): gen._p = p.X
400
+ if isinstance(p, Var) and p.value is not None: gen._p = self.__chkv(p.value)
363
401
  q = qg0[j]
364
- if isinstance(q, Var): gen._q = q.X
402
+ if isinstance(q, Var): gen._q = self.__chkv(q.value)
365
403
 
366
404
  for pID, p in island.PVWItems():
367
- p._pr = pvwp[pID].X
368
- p._qr = pvwq[pID].X
405
+ p._pr = self.__chkv(pvwp[pID].value)
406
+ p._qr = self.__chkv(pvwq[pID].value)
369
407
  pgen = p.P(_t)
370
408
  p._cr = 1 - p._pr / pgen if pgen > 0 else 0
371
409
 
372
410
  overflow = False
373
411
  self._ofbuses.clear()
374
- for bID, bv in chain(dvmax.items(), dvmin.items()):
375
- if bv.X > 1e-8:
376
- overflow = True
377
- self._ofbuses.add(bID)
412
+ if relaxV:
413
+ for bID, bv in chain(dvmax.items(), dvmin.items()):
414
+ if self.__chkv(bv.value) > 1e-8:
415
+ overflow = True
416
+ self._ofbuses.add(bID)
378
417
 
379
418
  self._oflines.clear()
380
- for lID, lv in dlmax.items():
381
- if lv.X > 1e-8:
382
- overflow = True
383
- self._oflines.add(lID)
419
+ if relaxI:
420
+ for lID, lv in dlmax.items():
421
+ if self.__chkv(lv.value) > 1e-8:
422
+ overflow = True
423
+ self._oflines.add(lID)
384
424
 
385
425
  for bus, lim in self._decb.items():
386
- lim.Reduction = Pdec[bus].X
426
+ lim.Reduction = self.__chkv(Pdec[bus].value)
387
427
  if lim.Reduction < 1e-8: lim.Reduction = 0
388
428
 
389
- return IslandResult.OverFlow if overflow else IslandResult.OK, goal.getValue()
429
+ if not isinstance(goal, (int, float)):
430
+ goal = self.__chkv(goal.value)
431
+ return IslandResult.OverFlow if overflow else IslandResult.OK, goal
@@ -0,0 +1,102 @@
1
+ from .solbase import *
2
+
3
+ class OpenDSSSolver(SolverBase):
4
+ def __init__(self, grid:Grid, source_bus:str, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100, init_t:int = 0):
5
+ super().__init__(grid, eps, default_saveto)
6
+ from py_dss_interface import DSS
7
+ self._g = grid
8
+ t = init_t
9
+ d = DSS()
10
+ d.text("clear")
11
+ cir = f"new circuit.my_circuit basekv={grid.Ub} pu=1 MVASC3=5000000 5000000 bus1={source_bus}"
12
+ self.source_bus = source_bus
13
+ assert source_bus in grid.BusNames, f"Source bus {source_bus} not found in the grid"
14
+ d.text(cir)
15
+ for bus in grid.Buses:
16
+ bid = bus.ID
17
+ if bid != bid.lower():
18
+ raise ValueError(f"Bus ID {bid} must be lower case")
19
+ p = bus.Pd(t) * grid.Sb_kVA
20
+ q = bus.Qd(t) * grid.Sb_kVA
21
+ d.text(f"New Load.{bid} bus1={bid} kv={self.grid.Ub} kW={p} kvar={q} vmin={bus.MinV} vmax={bus.MaxV}")
22
+ for line in self.grid.Lines:
23
+ fid = line.fBus
24
+ tid = line.tBus
25
+ if line.ID != line.ID.lower():
26
+ raise ValueError(f"Line ID {line.ID} must be lower case")
27
+ d.text(f"New line.{line.ID} bus1={fid} bus2={tid} R1={line.R*grid.Zb} units=ohm X1={line.X*grid.Zb} units=ohm")
28
+ for pvw in self.grid.PVWinds:
29
+ if pvw.ID != pvw.ID.lower():
30
+ raise ValueError(f"PVWind ID {pvw.ID} must be lower case")
31
+ if pvw.Pr is None:
32
+ raise ValueError(f"PVWind {pvw.ID} has no Pr value")
33
+ p = pvw.Pr
34
+ if pvw.Qr is None:
35
+ raise ValueError(f"PVWind {pvw.ID} has no Qr value")
36
+ q = pvw.Qr
37
+ bid = pvw.BusID
38
+
39
+ s = f"New Generator.{pvw.ID} bus1={bid} kv={grid.Ub} kw={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA}"
40
+ d.text(s)
41
+ for ess in self.grid.ESSs:
42
+ if ess.ID != ess.ID.lower():
43
+ raise ValueError(f"ESS ID {ess.ID} must be lower case")
44
+ if ess.P is None:
45
+ raise ValueError(f"ESS {ess.ID} has no P value")
46
+ p = ess.P
47
+ if ess.Q is None:
48
+ raise ValueError(f"ESS {ess.ID} has no Q value")
49
+ q = ess.Q
50
+ bid = ess.BusID
51
+ if p > 0: # charging = load
52
+ bus = self.grid.Bus(bid)
53
+ s = f"New Load.{ess.ID} bus1={bid} kv={grid.Ub} kW={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA} vmin={bus.MinV} vmax={bus.MaxV}"
54
+ else: # discharging = generator
55
+ s = f"New Generator.{ess.ID} bus1={bid} kv={grid.Ub} kw={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA}"
56
+ d.text(s)
57
+ for gen in self.grid.Gens:
58
+ if gen.ID != gen.ID.lower():
59
+ raise ValueError(f"Generator ID {gen.ID} must be lower case")
60
+ if gen.P is None:
61
+ raise ValueError(f"Generator {gen.ID} has no P value")
62
+ p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
63
+ if gen.Q is None:
64
+ raise ValueError(f"Generator {gen.ID} has no Q value")
65
+ q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
66
+ bid = gen.BusID
67
+
68
+ s = f"New Generator.{gen.ID} bus1={bid} kv={grid.Ub} kw={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA}"
69
+ d.text(s)
70
+ d.text("set mode=snapshot")
71
+ self.dss = d
72
+
73
+ def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
74
+ self.dss.text(f"set Voltagebases=[{self.grid.Ub}]")
75
+ self.dss.text("calcv")
76
+ self.dss.text("solve maxcontrol=10000")
77
+ bnames = self.dss.circuit.buses_names
78
+ bvolt = np.array(self.dss.circuit.buses_volts).reshape(-1, 3, 2)
79
+ sb_theta = 0
80
+ for i, bn in enumerate(bnames):
81
+ v1 = bvolt[i,0][0] + 1j * bvolt[i,0][1]
82
+ v2 = bvolt[i,1][0] + 1j * bvolt[i,1][1]
83
+ v = v1 - v2
84
+ b = self.grid.Bus(bn)
85
+ b._v = abs(v) / self.grid.Ub / 1000
86
+ b.theta = math.atan2(v.imag, v.real)
87
+ if bn == self.source_bus:
88
+ sb_theta = b.theta
89
+
90
+ for i, bn in enumerate(bnames):
91
+ self.grid.Bus(bn).theta -= sb_theta
92
+
93
+ for l in self.grid.Lines:
94
+ vi = self.grid.Bus(l.fBus).V_cpx
95
+ vj = self.grid.Bus(l.tBus).V_cpx
96
+ assert vi is not None and vj is not None
97
+ i = (vi-vj)/l.Z
98
+ l.I = abs(i)
99
+ s = vi*i.conjugate()
100
+ l.P = s.real
101
+ l.Q = s.imag
102
+ return GridSolveResult.OK, 0.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: fpowerkit
3
- Version: 0.1.6
3
+ Version: 0.2.0
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -10,8 +10,9 @@ Requires-Python: >=3.8
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
12
  Requires-Dist: feasytools>=0.0.21
13
- Requires-Dist: gurobipy>=9.1.0
13
+ Requires-Dist: cvxpy>=1.0
14
14
  Requires-Dist: numpy>=1.20.0
15
+ Requires-Dist: ecos
15
16
  Dynamic: author
16
17
  Dynamic: classifier
17
18
  Dynamic: description
@@ -22,7 +23,15 @@ Dynamic: summary
22
23
 
23
24
  # FPowerKit - A power distribution network calculation component
24
25
 
25
- This is a package based on Gurobipy implementing optimal power flow (OPF).
26
+ This is a package designed for power distribution network solving.
27
+
28
+ There are 3 modes for this package to work:
29
+
30
+ - Optimal power flow (OPF): Use cvxpy to solve the optimal power flow and determine the output of the generators.
31
+
32
+ - Power flow calculation: Use OpenDSS or Netwon-Raphson method to solve the power flow with given generator ouputs.
33
+
34
+ - Hybrid: Use OPF to determine the initial value, and then use OpenDSS or Newton method to perform accurate calculation.
26
35
 
27
36
  Since this package is still under development, the API is unstable and may be changed anytime.
28
37
 
@@ -10,6 +10,7 @@ fpowerkit/grid.py
10
10
  fpowerkit/line.py
11
11
  fpowerkit/pvwind.py
12
12
  fpowerkit/solbase.py
13
+ fpowerkit/solcmb.py
13
14
  fpowerkit/soldist.py
14
15
  fpowerkit/soldss.py
15
16
  fpowerkit/solnt.py
@@ -1,3 +1,4 @@
1
1
  feasytools>=0.0.21
2
- gurobipy>=9.1.0
2
+ cvxpy>=1.0
3
3
  numpy>=1.20.0
4
+ ecos
@@ -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.6",
8
+ version="0.2.0",
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.21", "gurobipy>=9.1.0", "numpy>=1.20.0"],
20
+ install_requires=["feasytools>=0.0.21", "cvxpy>=1.0", "numpy>=1.20.0", "ecos"],
21
21
  )
@@ -1,47 +0,0 @@
1
- from .solbase import *
2
-
3
- class OpenDSSSolver(SolverBase):
4
-
5
- def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100, init_t:int = 0, source_bus:str=""):
6
- super().__init__(grid, eps, default_saveto)
7
- from py_dss_interface import DSS
8
- self._g = grid
9
- t = init_t
10
- d = DSS()
11
- d.text("clear")
12
- cir = f"new circuit.my_circuit basekv={grid.Ub} pu=1.0 phases=3"
13
- if source_bus != "":
14
- cir += f" bus1={source_bus}"
15
- d.text(cir)
16
- for bus in grid.Buses:
17
- bid = bus.ID
18
- p = bus.Pd(t) * grid.Sb_kVA
19
- q = bus.Qd(t) * grid.Sb_kVA
20
- print(f"bus {bid} Pd={p} Qd={q}")
21
- d.text(f"New Load.{bid} bus1={bid}.1.2.3 phases=3 kW={p} kvar={q} vmin={bus.MinV} vmax={bus.MaxV}")
22
- for line in self.grid.Lines:
23
- fid = line.fBus
24
- tid = line.tBus
25
- d.text(f"New Line.{line.ID} bus1={fid}.1.2.3 bus2={tid}.1.2.3 length={line.L} units=km R1={line.R*grid.Zb} units=ohm X1={line.X*grid.Zb} units=ohm")
26
- for gen in self.grid.Gens:
27
- if gen.P is None:
28
- p = None
29
- else:
30
- p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
31
- if gen.Q is None:
32
- q = None
33
- else:
34
- q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
35
- bid = gen.BusID
36
- s = f"New Generator.{gen.ID} bus1={bid} phases=1 kv={grid.Ub} "
37
- if p is not None:
38
- s += f"kw={p*grid.Sb_kVA} "
39
- if q is not None:
40
- s += f"kvar={q*grid.Sb_kVA} "
41
- d.text(s)
42
- d.text("set mode=snapshot")
43
- self.dss = d
44
-
45
- def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
46
- self.dss.text("solve")
47
- return GridSolveResult.OK, 0.0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes