fpowerkit 0.2.3__tar.gz → 0.3.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 (29) hide show
  1. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/PKG-INFO +1 -1
  2. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/README.md +0 -1
  3. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/__init__.py +0 -1
  4. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/grid.py +16 -5
  5. fpowerkit-0.3.0/fpowerkit/island.py +91 -0
  6. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/line.py +2 -1
  7. fpowerkit-0.3.0/fpowerkit/solbase.py +85 -0
  8. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/solcmb.py +24 -15
  9. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/soldist.py +27 -103
  10. fpowerkit-0.3.0/fpowerkit/soldss.py +125 -0
  11. fpowerkit-0.3.0/fpowerkit/solnt.py +166 -0
  12. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit.egg-info/PKG-INFO +1 -1
  13. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit.egg-info/SOURCES.txt +1 -1
  14. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/setup.py +1 -1
  15. fpowerkit-0.2.3/fpowerkit/solbase.py +0 -41
  16. fpowerkit-0.2.3/fpowerkit/soldss.py +0 -110
  17. fpowerkit-0.2.3/fpowerkit/solgcal.py +0 -124
  18. fpowerkit-0.2.3/fpowerkit/solnt.py +0 -150
  19. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/LICENSE +0 -0
  20. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/bus.py +0 -0
  21. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/cases.py +0 -0
  22. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/ess.py +0 -0
  23. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/gen.py +0 -0
  24. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/pvwind.py +0 -0
  25. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit/utils.py +0 -0
  26. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit.egg-info/dependency_links.txt +0 -0
  27. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit.egg-info/requires.txt +0 -0
  28. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/fpowerkit.egg-info/top_level.txt +0 -0
  29. {fpowerkit-0.2.3 → fpowerkit-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: fpowerkit
3
- Version: 0.2.3
3
+ Version: 0.3.0
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -6,7 +6,6 @@
6
6
  + (内置) 改进DistFlow配电网最优潮流
7
7
  + (内置) Newton-Raphson潮流计算
8
8
  + (外接) OpenDSS配电网潮流计算
9
- + (外接) GridCal潮流计算(仅限较高版本的Python)
10
9
  + 最优潮流+潮流计算核验的混合方案
11
10
  - 对于最优潮流模型,优化目标为“发电成本最小”。发电成本模型为二次函数$f(x)=ax^2+bx+c$或者一次函数$f(x)=bx+c$。
12
11
  - 依赖于feasytools和numpy: `pip install feasytools numpy`
@@ -4,5 +4,4 @@ from .solnt import *
4
4
  from .soldist import *
5
5
  from .soldss import *
6
6
  from .solcmb import *
7
- from .solgcal import *
8
7
  from .cases import PDNCases
@@ -1,3 +1,4 @@
1
+ from collections import deque
1
2
  from enum import IntEnum
2
3
  import gzip
3
4
  from xml.etree.ElementTree import ElementTree
@@ -288,11 +289,17 @@ class Grid:
288
289
  def Buses(self):
289
290
  return self._buses.values()
290
291
 
291
- def LinesOfFBus(self, busid: str) -> 'list[Line]':
292
- return self._ladjfb[busid]
292
+ def LinesOfFBus(self, busid: str, only_active:bool = True) -> 'Iterable[Line]':
293
+ if only_active:
294
+ return (l for l in self._ladjfb[busid] if l.active)
295
+ else:
296
+ return self._ladjfb[busid]
293
297
 
294
- def LinesOfTBus(self, busid: str) -> 'list[Line]':
295
- return self._ladjtb[busid]
298
+ def LinesOfTBus(self, busid: str, only_active:bool = True) -> 'Iterable[Line]':
299
+ if only_active:
300
+ return (l for l in self._ladjtb[busid] if l.active)
301
+ else:
302
+ return self._ladjtb[busid]
296
303
 
297
304
  def Line(self, id: str) -> 'Line':
298
305
  return self._lines[id]
@@ -300,6 +307,10 @@ class Grid:
300
307
  @property
301
308
  def Lines(self):
302
309
  return self._lines.values()
310
+
311
+ @property
312
+ def ActiveLines(self):
313
+ return (l for l in self._lines.values() if l.active)
303
314
 
304
315
  def Gen(self, id: str) -> 'Generator':
305
316
  return self._gens[id]
@@ -438,7 +449,7 @@ class Grid:
438
449
  '''Return the admittance matrix of the grid'''
439
450
  n = len(self._buses)
440
451
  Y = np.zeros((n, n), dtype=complex)
441
- for l in self._lines.values():
452
+ for l in self.ActiveLines:
442
453
  i = self._bnames.index(l.fBus)
443
454
  j = self._bnames.index(l.tBus)
444
455
  y = 1 / l.Z
@@ -0,0 +1,91 @@
1
+ from collections import deque
2
+ from .grid import *
3
+
4
+ class IslandResult(IntEnum):
5
+ Undefined = -1
6
+ OK = 0 # The island is solved without overflow
7
+ OverFlow = 1 # The island is solved but overflow
8
+ Failed = 2 # No island is solved
9
+
10
+ class Island:
11
+ @staticmethod
12
+ def from_grid(g: Grid) -> 'list[Island]':
13
+ """Create a list of islands from the grid. An island is a set of buses that are connected to each other."""
14
+ q: 'deque[BusID]' = deque()
15
+ visited: 'set[BusID]' = set()
16
+ islands: 'list[set[BusID]]' = []
17
+ for bus in g.BusNames:
18
+ if bus in visited: continue
19
+ q.append(bus)
20
+ island: 'set[BusID]' = set()
21
+ while len(q) > 0:
22
+ b = q.popleft()
23
+ if b in visited: continue
24
+ visited.add(b)
25
+ island.add(b)
26
+ for line in g.LinesOfFBus(b):
27
+ if line.tBus in visited: continue
28
+ q.append(line._tBus)
29
+ for line in g.LinesOfTBus(b):
30
+ if line.fBus in visited: continue
31
+ q.append(line.fBus)
32
+ islands.append(island)
33
+ return [Island(g, island) for island in islands]
34
+
35
+ def __init__(self, g: Grid, buses: Iterable[BusID]):
36
+ self.grid = g
37
+ self.Buses: 'set[str]' = set()
38
+ self.Gens: 'set[str]' = set()
39
+ self.Lines: 'set[str]' = set()
40
+ self.PVWs: 'set[str]' = set()
41
+ self.ESSs: 'set[str]' = set()
42
+ self.result: IslandResult = IslandResult.Undefined
43
+ self.result_value:float = 0.0
44
+ for b in buses:
45
+ self.Buses.add(b)
46
+ self.Gens.update(gen.ID for gen in g.GensAtBus(b))
47
+ self.Lines.update(ln.ID for ln in g.LinesOfFBus(b))
48
+ self.Lines.update(ln.ID for ln in g.LinesOfTBus(b))
49
+ self.PVWs.update(p.ID for p in g._patb[b])
50
+ self.ESSs.update(e.ID for e in g._eatb[b])
51
+
52
+ def __repr__(self):
53
+ return f"Island: {self.Buses}\nGens: {self.Gens}\nLines: {self.Lines}\nPVWs: {self.PVWs}\nESSs: {self.ESSs}"
54
+
55
+ def __str__(self):
56
+ return self.__repr__()
57
+
58
+ def BusItems(self):
59
+ for b in self.Buses:
60
+ yield b, self.grid.Bus(b)
61
+
62
+ def GenItems(self):
63
+ for g in self.Gens:
64
+ yield g, self.grid.Gen(g)
65
+
66
+ def LineItems(self):
67
+ for l in self.Lines:
68
+ yield l, self.grid.Line(l)
69
+
70
+ def PVWItems(self):
71
+ for p in self.PVWs:
72
+ yield p, self.grid.PVWind(p)
73
+
74
+ def ESSItems(self):
75
+ for e in self.ESSs:
76
+ yield e, self.grid.ESS(e)
77
+
78
+ def YMat(self) -> 'tuple[dict[str,int], np.ndarray]':
79
+ '''Return the admittance matrix of the grid'''
80
+ n = len(self.Buses)
81
+ bus_dict = {b: i for i, b in enumerate(self.Buses)}
82
+ Y = np.zeros((n, n), dtype=complex)
83
+ for _, l in self.LineItems():
84
+ i = bus_dict[l.fBus]
85
+ j = bus_dict[l.tBus]
86
+ y = 1 / l.Z
87
+ Y[i, j] -= y
88
+ Y[j, i] -= y
89
+ Y[i, i] += y
90
+ Y[j, j] += y
91
+ return bus_dict, Y
@@ -10,7 +10,7 @@ class Line:
10
10
  I: FloatVar # pu
11
11
 
12
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):
13
+ p_pu: NFloat = None, q_pu: NFloat = None, max_I_kA: float = math.inf, length_km: NFloat = None, active: bool = True):
14
14
  '''
15
15
  Initialize
16
16
  id: Line ID
@@ -29,6 +29,7 @@ class Line:
29
29
  self.P = p_pu
30
30
  self.Q = q_pu
31
31
  self.L = length_km
32
+ self.active = active
32
33
 
33
34
  @property
34
35
  def ID(self) -> str:
@@ -0,0 +1,85 @@
1
+ from abc import ABC, abstractmethod
2
+ from enum import IntEnum
3
+ from pathlib import Path
4
+ from .island import *
5
+ from .grid import *
6
+
7
+ DEFAULT_SAVETO = "./fpowerkit_logs/"
8
+
9
+ class GridSolveResult(IntEnum):
10
+ '''Result of grid solving'''
11
+ Failed = 0
12
+ OK = 1
13
+ OKwithoutVICons = 2 # Deprecated
14
+ SubOKwithoutVICons = 3 # Deprecated
15
+ PartialOK = 4
16
+
17
+
18
+ class SolverBase(ABC):
19
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, default_saveto:str = DEFAULT_SAVETO, **kwargs):
20
+ self.UpdateGrid(grid)
21
+ self.eps = eps
22
+ self.max_iter = max_iter
23
+ self.saveto = default_saveto
24
+
25
+ @property
26
+ def grid(self) -> Grid:
27
+ '''Get the grid'''
28
+ return self._g
29
+ @grid.setter
30
+ def grid(self, grid:Grid):
31
+ '''Set the grid'''
32
+ self.UpdateGrid(grid)
33
+
34
+ def UpdateGrid(self, grid:Grid):
35
+ '''Update the grid'''
36
+ self._g = grid
37
+ self._islands = Island.from_grid(grid)
38
+
39
+ @property
40
+ def Islands(self) -> 'list[Island]':
41
+ '''Get the islands of the grid'''
42
+ return self._islands
43
+
44
+ def SetErrorSaveTo(self, path:str = DEFAULT_SAVETO):
45
+ self.saveto = path
46
+ Path(path).mkdir(parents=True, exist_ok = True)
47
+
48
+ def _calc_line_params(self):
49
+ for l in self.grid.Lines:
50
+ if not l.active:
51
+ l.I = 0.0
52
+ l.P = 0.0
53
+ l.Q = 0.0
54
+ continue
55
+ vi = self.grid.Bus(l.fBus).V_cpx
56
+ vj = self.grid.Bus(l.tBus).V_cpx
57
+ assert vi is not None and vj is not None
58
+ i = (vi-vj)/l.Z
59
+ l.I = abs(i)
60
+ s = vi*i.conjugate()
61
+ l.P = s.real
62
+ l.Q = s.imag
63
+
64
+ def solve(self, _t:int, /, **kwargs):
65
+ ok_cnt = 0
66
+ res_val = 0.0
67
+ for i, il in enumerate(self._islands):
68
+ r, v = self.solve_island(i, il, _t, **kwargs)
69
+ il.result = r
70
+ il.result_value = v
71
+ if r == IslandResult.OK:
72
+ ok_cnt += 1
73
+ res_val += v
74
+ self._calc_line_params()
75
+ if ok_cnt == len(self._islands):
76
+ return GridSolveResult.OK, res_val
77
+ elif ok_cnt == 0:
78
+ return GridSolveResult.Failed, -1
79
+ else:
80
+ return GridSolveResult.PartialOK, res_val
81
+
82
+ @abstractmethod
83
+ def solve_island(self, i:int, island:Island, _t:int, /, **kwargs) -> 'tuple[IslandResult, float]':
84
+ '''Solve the island'''
85
+ raise NotImplementedError
@@ -1,21 +1,27 @@
1
+ from enum import StrEnum
2
+ from typing import Union, Iterable
1
3
  from .grid import Grid
2
4
  from .solbase import DEFAULT_SAVETO, GridSolveResult, SolverBase
3
5
  from warnings import warn
4
6
 
5
- ESTIMATORS = ['distflow']
6
- CALCULATORS = ['opendss', 'newton', 'gridcal', 'none']
7
- CALCULATORS_NEED_SOURCE_BUS = ['opendss', 'gridcal']
7
+ class Estimator(StrEnum):
8
+ DistFlow = 'DistFlow'
9
+
10
+ class Calculator(StrEnum):
11
+ OpenDSS = 'OpenDSS'
12
+ Newton = 'Newton'
13
+ NoneSolver = 'None'
14
+
15
+ CALCULATORS_NEED_SOURCE_BUS = [Calculator.OpenDSS]
8
16
 
9
17
  class CombinedSolver(SolverBase):
10
18
  """
11
19
  A class that use DistFlowSolver to estimate the power flow and then use OpenDSSSolver or NewtonSolver to solve the power flow problem.
12
20
  """
13
- def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
14
- default_saveto:str = DEFAULT_SAVETO, estimator:str = 'distflow',
15
- calculator:str = 'newton', mlrp:float = 0.5 ,source_bus:str = ""):
21
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, mlrp:float = 0.5,
22
+ default_saveto:str = DEFAULT_SAVETO, estimator:Estimator = Estimator.DistFlow,
23
+ calculator:Calculator = Calculator.Newton, source_bus:'Union[str,Iterable[str]]' = ""):
16
24
  super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
17
- assert estimator in ESTIMATORS, f"Invalid estimator '{estimator}'. Choose from: " + ','.join(ESTIMATORS) + "."
18
- assert calculator in CALCULATORS, f"Invalid solver type '{calculator}'. Choose from: " + ','.join(CALCULATORS) + "."
19
25
 
20
26
  from .soldist import DistFlowSolver
21
27
  self.est = DistFlowSolver(grid, mlrp = mlrp)
@@ -31,16 +37,19 @@ class CombinedSolver(SolverBase):
31
37
  res, obj = self.est.solve(_t, timeout_s=timeout_s)
32
38
  if res == GridSolveResult.Failed:
33
39
  return res, obj
34
- if self.cal_str == 'none':
40
+ if self.cal_str == Calculator.NoneSolver:
35
41
  return res, obj
36
- elif self.cal_str == 'opendss':
42
+ elif self.cal_str == Calculator.OpenDSS:
37
43
  from .soldss import OpenDSSSolver
38
44
  solver = OpenDSSSolver(self.est.grid, source_bus = self.source_bus)
39
- elif self.cal_str == 'gridcal':
40
- from .solgcal import GridCalSolver
41
- solver = GridCalSolver(self.est.grid, slack_bus = self.source_bus)
42
- else:
45
+ elif self.cal_str == Calculator.Newton:
43
46
  from .solnt import NewtonSolver
44
47
  solver = NewtonSolver(self.est.grid)
48
+ else:
49
+ raise ValueError(f"Invalid solver type '{self.cal_str}'.")
45
50
  res, obj = solver.solve(_t, timeout_s = timeout_s)
46
- return res, obj
51
+ return res, obj
52
+
53
+ def solve_island(self, i:int, island, _t:int):
54
+ '''Solve the island'''
55
+ raise NotImplementedError
@@ -2,9 +2,9 @@ from itertools import chain
2
2
  from pathlib import Path
3
3
  from typing import Optional, Union
4
4
  from dataclasses import dataclass
5
- from collections import deque
6
5
  import math
7
6
  from .solbase import *
7
+ from .island import *
8
8
 
9
9
  VF = Union['Var', float] # type: ignore
10
10
 
@@ -15,58 +15,10 @@ class LoadReduceModule:
15
15
  Limit: TimeFunc
16
16
  Reduction: FloatVar = None
17
17
 
18
- class _Island:
19
- def __init__(self, g: Grid, buses: Iterable[BusID], cutlines: 'set[LineID]'):
20
- self.grid = g
21
- self.Buses: 'set[str]' = set()
22
- self.Gens: 'set[str]' = set()
23
- self.Lines: 'set[str]' = set()
24
- self.PVWs: 'set[str]' = set()
25
- self.ESSs: 'set[str]' = set()
26
- for b in buses:
27
- self.Buses.add(b)
28
- self.Gens.update(gen.ID for gen in g._gatb[b])
29
- self.Lines.update(ln.ID for ln in g._ladjfb[b] if ln.ID not in cutlines)
30
- self.Lines.update(ln.ID for ln in g._ladjtb[b] if ln.ID not in cutlines)
31
- self.PVWs.update(p.ID for p in g._patb[b])
32
- self.ESSs.update(e.ID for e in g._eatb[b])
33
-
34
- def __repr__(self):
35
- return f"Island: {self.Buses}\nGens: {self.Gens}\nLines: {self.Lines}\nPVWs: {self.PVWs}\nESSs: {self.ESSs}"
36
-
37
- def __str__(self):
38
- return self.__repr__()
39
-
40
- def BusItems(self):
41
- for b in self.Buses:
42
- yield b, self.grid.Bus(b)
43
-
44
- def GenItems(self):
45
- for g in self.Gens:
46
- yield g, self.grid.Gen(g)
47
-
48
- def LineItems(self):
49
- for l in self.Lines:
50
- yield l, self.grid.Line(l)
51
-
52
- def PVWItems(self):
53
- for p in self.PVWs:
54
- yield p, self.grid.PVWind(p)
55
-
56
- def ESSItems(self):
57
- for e in self.ESSs:
58
- yield e, self.grid.ESS(e)
59
-
60
- class IslandResult(IntEnum):
61
- Undefined = -1
62
- OK = 0 # The island is solved without overflow
63
- OverFlow = 1 # The island is solved but overflow
64
- Failed = 2 # No island is solved
65
-
66
18
  class DistFlowSolver(SolverBase):
67
19
  '''DistFlow solver'''
68
20
  def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
69
- default_saveto:str = DEFAULT_SAVETO, mlrp: float = 0.5, secondary_cost: bool = True):
21
+ default_saveto:str = DEFAULT_SAVETO, mlrp: float = 0.5, secondary_cost: bool = True, bigM: float = 1e6):
70
22
  '''
71
23
  Initialize
72
24
  grid: Grid object
@@ -74,17 +26,15 @@ class DistFlowSolver(SolverBase):
74
26
  mlrp: Maximum proportion of load reduction
75
27
  secondary_cost: Whether to include the secondary cost.
76
28
  If False, the cost is calculated as CostB * Pg + CostC;
77
- If True, the cost is calculated as CostA * Pg^2 + CostB * Pg + CostC,
78
- which is likely to induce numerical instability.
29
+ If True, the cost is calculated as CostA * Pg^2 + CostB * Pg + CostC.
79
30
  '''
80
31
  super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
81
32
  self._decb: dict[BusID, LoadReduceModule] = {}
82
- self.C = 1e9
33
+ self.C = bigM
83
34
  self._mlrp = mlrp
84
35
  self._oflines: set[LineID] = set()
85
36
  self._ofbuses: set[BusID] = set()
86
- self._sec_cost = secondary_cost
87
- self.UpdateGrid()
37
+ self._sec_cost = secondary_cost
88
38
 
89
39
  @property
90
40
  def OverflowLines(self):
@@ -94,46 +44,13 @@ class DistFlowSolver(SolverBase):
94
44
  def OverflowBuses(self):
95
45
  return self._ofbuses
96
46
 
97
- def UpdateGrid(self, cut_overflow_lines: bool = False):
98
- self._islands = tuple(
99
- _Island(self.grid, il, self._oflines) for il in self.__detect_islands(cut_overflow_lines)
100
- )
101
- self._island_res = [(IslandResult.Undefined, -1.0) for _ in range(len(self._islands))]
47
+ def UpdateGrid(self, grid:Grid, cut_overflow_lines: bool = False):
48
+ if cut_overflow_lines:
49
+ for lID in self._oflines:
50
+ self.grid.Line(lID).active = False
51
+ super().UpdateGrid(grid)
102
52
  self.__il_relax = [False] * len(self._islands)
103
53
 
104
- def __detect_islands(self, cutofl: bool):
105
- '''Detect islands'''
106
- q: 'deque[BusID]' = deque()
107
- visited: 'set[BusID]' = set()
108
- islands: 'list[set[BusID]]' = []
109
- for bus in self.grid.BusNames:
110
- if bus in visited: continue
111
- q.append(bus)
112
- island: 'set[BusID]' = set()
113
- while len(q) > 0:
114
- b = q.popleft()
115
- if b in visited: continue
116
- visited.add(b)
117
- island.add(b)
118
- for line in self.grid._ladjfb[b]:
119
- if cutofl and line.ID in self._oflines: continue
120
- if line._tBus in visited: continue
121
- q.append(line._tBus)
122
- for line in self.grid._ladjtb[b]:
123
- if cutofl and line.ID in self._oflines: continue
124
- if line._fBus in visited: continue
125
- q.append(line._fBus)
126
- islands.append(island)
127
- return islands
128
-
129
- @property
130
- def Islands(self):
131
- return self._islands
132
-
133
- @property
134
- def IslandResults(self):
135
- return self._island_res
136
-
137
54
  @property
138
55
  def MLRP(self):
139
56
  '''Get the maximum load reduction proportion'''
@@ -169,15 +86,19 @@ class DistFlowSolver(SolverBase):
169
86
  val = 0
170
87
  for i, il in enumerate(self._islands):
171
88
  relax = self.__il_relax[i]
172
- self._island_res[i] = self.__solve(_t, il, timeout_s, relax, relax)
173
- if self._island_res[i][0] == IslandResult.Failed:
89
+ r, v = self.solve_island(i, il, _t, timeout_s, relax, relax)
90
+ self._islands[i].result = r
91
+ self._islands[i].result_value = v
92
+ if r == IslandResult.Failed:
174
93
  self.__il_relax[i] = True
175
- self._island_res[i] = self.__solve(_t, il, timeout_s, True, True)
176
- if self._island_res[i][0] != IslandResult.Failed:
94
+ r, v = self.solve_island(i, il, _t, timeout_s, True, True)
95
+ self._islands[i].result = r
96
+ self._islands[i].result_value = v
97
+ if r != IslandResult.Failed:
177
98
  allFail = False
178
- val += self._island_res[i][1]
179
- if self._island_res[i][0] != IslandResult.OK: allOK = False
180
- if self._island_res[i][0] == IslandResult.OverFlow: self.__il_relax[i] = False
99
+ val += v
100
+ if r != IslandResult.OK: allOK = False
101
+ if r == IslandResult.OverFlow: self.__il_relax[i] = False
181
102
  if allOK:
182
103
  return GridSolveResult.OK, val
183
104
  elif allFail:
@@ -199,7 +120,7 @@ class DistFlowSolver(SolverBase):
199
120
  assert ret != float('-inf'), "Value is -inf"
200
121
  return ret
201
122
 
202
- def __solve(self, _t: int, island: _Island, timeout_s: float, relaxV: bool, relaxI: bool, clear_results: bool = False) -> 'tuple[IslandResult, float]':
123
+ def solve_island(self, il_idx:int, island: Island, _t: int, timeout_s: float, relaxV: bool, relaxI: bool, clear_results: bool = False) -> 'tuple[IslandResult, float]':
203
124
 
204
125
  ''' ---------Variables----------
205
126
  pg0[k]: Generator active power
@@ -330,7 +251,10 @@ class DistFlowSolver(SolverBase):
330
251
  cons.append(
331
252
  inflow + cp.sum(pg[j]) == outflow + pd[j] - dec # type: ignore
332
253
  )
333
-
254
+
255
+ # flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
256
+ flow_in = island.grid.LinesOfTBus(j)
257
+ flow_out = island.grid.LinesOfFBus(j)
334
258
  # Q constraint
335
259
  q_inflow = cp.sum([Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines])
336
260
  q_outflow = cp.sum([Q[ln.ID] for ln in flow_out if ln.ID in island.Lines])
@@ -367,7 +291,7 @@ class DistFlowSolver(SolverBase):
367
291
  for gID, g in island.GenItems()])
368
292
 
369
293
  problem = cp.Problem(cp.Minimize(decs + goal + crpe), cons)
370
-
294
+
371
295
  try:
372
296
  problem.solve(solver=cp.ECOS, verbose=False, max_iters=self.max_iter)
373
297
  except cp.SolverError as e:
@@ -0,0 +1,125 @@
1
+ from fpowerkit.grid import Grid
2
+ from .solbase import *
3
+
4
+ def _convert(il:Island, t:int, source_bus:str):
5
+ try:
6
+ from py_dss_interface import DSS
7
+ except ImportError:
8
+ raise ImportError("py_dss_interface or OpenDSS is not installed. Please install OpenDSS first and then py_dss_interface using 'pip install py_dss_interface'")
9
+
10
+ try:
11
+ d = DSS()
12
+ except:
13
+ d = DSS.DSSDLL() # type: ignore
14
+ d.text("clear")
15
+ Ub = il.grid.Ub
16
+ Sb_MVA = il.grid.Sb_MVA
17
+ Sb_kVA = il.grid.Sb_kVA
18
+ Zb = il.grid.Zb
19
+ cir = f"new circuit.my_circuit basekv={Ub} pu=1 MVASC3=5000000 5000000 bus1={source_bus}"
20
+ assert source_bus in il.grid.BusNames, f"Source bus {source_bus} not found in the grid"
21
+ d.text(cir)
22
+ for bid, bus in il.BusItems():
23
+ if bid != bid.lower():
24
+ raise ValueError(f"Bus ID {bid} must be lower case")
25
+ p = bus.Pd(t)
26
+ q = bus.Qd(t)
27
+ d.text(f"New Load.{bid} bus1={bid} kv={Ub} kW={p*Sb_kVA} kvar={q*Sb_kVA} vmin={bus.MinV} vmax={bus.MaxV}")
28
+ for lid, line in il.LineItems():
29
+ fid = line.fBus
30
+ tid = line.tBus
31
+ if lid != lid.lower():
32
+ raise ValueError(f"Line ID {lid} must be lower case")
33
+ d.text(f"New line.{lid} bus1={fid} bus2={tid} R1={line.R*Zb} units=ohm X1={line.X*Zb} units=ohm")
34
+ for pid, pvw in il.PVWItems():
35
+ if pid != pid.lower():
36
+ raise ValueError(f"PVWind ID {pid} must be lower case")
37
+ if pvw.Pr is None:
38
+ raise ValueError(f"PVWind {pid} has no Pr value")
39
+ p = pvw.Pr
40
+ if pvw.Qr is None:
41
+ raise ValueError(f"PVWind {pid} has no Qr value")
42
+ q = pvw.Qr
43
+ bid = pvw.BusID
44
+
45
+ s = f"New Generator.{pvw.ID} bus1={bid} kv={Ub} kw={p*Sb_kVA} kvar={q*Sb_kVA}"
46
+ d.text(s)
47
+ for eid, ess in il.ESSItems():
48
+ if eid != eid.lower():
49
+ raise ValueError(f"ESS ID {eid} must be lower case")
50
+ if ess.P is None:
51
+ raise ValueError(f"ESS {eid} has no P value")
52
+ p = ess.P
53
+ if ess.Q is None:
54
+ raise ValueError(f"ESS {eid} has no Q value")
55
+ q = ess.Q
56
+ bid = ess.BusID
57
+ if p > 0: # charging = load
58
+ bus = il.grid.Bus(bid)
59
+ s = f"New Load.{ess.ID} bus1={bid} kv={Ub} kW={p*Sb_kVA} kvar={q*Sb_kVA} vmin={bus.MinV} vmax={bus.MaxV}"
60
+ else: # discharging = generator
61
+ s = f"New Generator.{ess.ID} bus1={bid} kv={Ub} kw={p*Sb_kVA} kvar={q*Sb_kVA}"
62
+ d.text(s)
63
+ for gid, gen in il.GenItems():
64
+ if gid != gid.lower():
65
+ raise ValueError(f"Generator ID {gid} must be lower case")
66
+ bid = gen.BusID
67
+ if gen.P is None and bid != source_bus:
68
+ raise ValueError(f"Generator {gen.ID} has no P value")
69
+ p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
70
+ if gen.Q is None and bid != source_bus:
71
+ raise ValueError(f"Generator {gen.ID} has no Q value")
72
+ q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
73
+
74
+ s = f"New Generator.{gen.ID} bus1={bid} kv={Ub} "
75
+ if p is not None:
76
+ s+=f"kw={p*Sb_kVA} "
77
+ if q is not None:
78
+ s+=f"kvar={q*Sb_kVA}"
79
+ d.text(s)
80
+ d.text("set mode=snapshot")
81
+ return d
82
+
83
+
84
+ class OpenDSSSolver(SolverBase):
85
+ def UpdateGrid(self, grid: Grid):
86
+ super().UpdateGrid(grid)
87
+ self.__sbus:'list[str]' = []
88
+ for il in self.Islands:
89
+ b = self.source_buses.intersection(il.Buses)
90
+ assert len(b) == 1, f"Source bus {self.source_buses} not found in an island"
91
+ self.__sbus.append(b.pop())
92
+
93
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
94
+ default_saveto:str = DEFAULT_SAVETO, source_bus:'Union[str,Iterable[str]]'):
95
+ if isinstance(source_bus, str): source_bus = [source_bus]
96
+ assert isinstance(source_bus, Iterable), "source_bus must be a string or a list of strings"
97
+ self.source_buses = set(source_bus)
98
+ super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
99
+
100
+ def solve_island(self, il_no:int, il:Island, _t:int, /, *, timeout_s:float = 1) -> 'tuple[IslandResult, float]':
101
+ self.dss = _convert(il, _t, self.__sbus[il_no])
102
+ self.dss.text(f"set Voltagebases=[{self.grid.Ub}]")
103
+ self.dss.text("calcv")
104
+ self.dss.text("solve maxcontrol=10000")
105
+ if hasattr(self.dss, "circuit"):
106
+ bnames = self.dss.circuit.buses_names
107
+ bvolt = np.array(self.dss.circuit.buses_volts).reshape(-1, 3, 2)
108
+ else:
109
+ bnames = self.dss.circuit_all_bus_names() # type: ignore
110
+ bvolt = np.array(self.dss.circuit_all_bus_volts()).reshape(-1, 3, 2) # type: ignore
111
+ sb_theta = 0
112
+ for i, bn in enumerate(bnames):
113
+ v1 = bvolt[i,0][0] + 1j * bvolt[i,0][1]
114
+ v2 = bvolt[i,1][0] + 1j * bvolt[i,1][1]
115
+ v = v1 - v2
116
+ b = self.grid.Bus(bn)
117
+ b._v = abs(v) / self.grid.Ub / 1000
118
+ b.theta = math.atan2(v.imag, v.real)
119
+ if bn == self.__sbus[il_no]:
120
+ sb_theta = b.theta
121
+
122
+ for i, bn in enumerate(bnames):
123
+ self.grid.Bus(bn).theta -= sb_theta
124
+
125
+ return IslandResult.OK, 0.0
@@ -0,0 +1,166 @@
1
+ import numpy as np
2
+ import math
3
+ from dataclasses import dataclass
4
+ from .solbase import *
5
+
6
+ class BusType(IntEnum):
7
+ PQ = 0
8
+ PV = 1
9
+ Slack = 2
10
+
11
+ @dataclass
12
+ class _NRProblem:
13
+ eqs: 'list[int]'
14
+ n_P: int
15
+ Ps: 'list[float]'
16
+ Qs: 'list[float]'
17
+ bus_dict: 'dict[str, int]'
18
+ G: 'np.ndarray'
19
+ B: 'np.ndarray'
20
+ V: 'list[float]'
21
+ theta: 'list[float]'
22
+
23
+ def _presolve(il:Island, _t:int):
24
+ '''Check the bus type'''
25
+ busType: 'dict[BusID, BusType]' = {}
26
+ slack_cnt = 0
27
+ eq_P: 'list[int]' = []
28
+ eq_Q: 'list[int]' = []
29
+ V: 'list[float]' = []
30
+ theta: 'list[float]' = []
31
+ Ps: 'list[float]' = []
32
+ Qs: 'list[float]' = []
33
+ bus_dict, Y = il.YMat()
34
+ for bid, i in bus_dict.items():
35
+ bus = il.grid.Bus(bid)
36
+ V.append(bus.V if bus.V is not None else 1.0)
37
+ theta.append(bus.theta if bus.theta is not None else 0.0)
38
+ fixp = fixq = True
39
+ p = -bus.Pd(_t)
40
+ q = -bus.Qd(_t)
41
+ for g in il.grid.GensAtBus(bus.ID):
42
+ if not g.FixedP: fixp = False
43
+ else:
44
+ assert g.P is not None
45
+ if isinstance(g.P, TimeFunc): p += g.P(_t)
46
+ else: p += g.P
47
+ if not g.FixedQ: fixq = False
48
+ else:
49
+ assert g.Q is not None
50
+ if isinstance(g.Q, TimeFunc): q += g.Q(_t)
51
+ else: q += g.Q
52
+ if bus.FixedV:
53
+ if fixp and fixq:
54
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
55
+ elif fixp:
56
+ busType[bus.ID] = BusType.PV
57
+ eq_P.append(i)
58
+ elif fixq:
59
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
60
+ else:
61
+ busType[bus.ID] = BusType.Slack
62
+ slack_cnt += 1
63
+ if slack_cnt > 1:
64
+ raise ValueError('Only one slack bus is allowed')
65
+ else:
66
+ if fixp and fixq:
67
+ busType[bus.ID] = BusType.PQ
68
+ bus.V = 1.0
69
+ eq_P.append(i)
70
+ eq_Q.append(i)
71
+ elif fixp:
72
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
73
+ elif fixq:
74
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
75
+ else:
76
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
77
+ Ps.append(p)
78
+ Qs.append(q)
79
+ if slack_cnt == 0:
80
+ raise ValueError('No slack bus is found')
81
+ return _NRProblem(eq_P + eq_Q, len(eq_P), Ps, Qs, bus_dict, Y.real, Y.imag, V, theta)
82
+
83
+ def _solve(prb: _NRProblem, max_iter:int = 100, eps:float = 1e-6):
84
+ '''Solve the power flow problem'''
85
+ G = prb.G
86
+ B = prb.B
87
+ V = prb.V
88
+ T = prb.theta
89
+ eqs = prb.eqs
90
+ Ps = prb.Ps
91
+ Qs = prb.Qs
92
+ n_P = prb.n_P
93
+ n = len(prb.eqs)
94
+ m = len(prb.bus_dict)
95
+
96
+ def P(i:int):
97
+ return V[i]*sum(V[j]*(
98
+ G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j])
99
+ ) for j in range(m))
100
+
101
+ def Q(i:int):
102
+ return V[i]*sum(V[j]*(
103
+ G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j])
104
+ ) for j in range(m))
105
+
106
+ def H(i:int, j:int) -> float:
107
+ if i == j: return Q(i)+V[i]**2*B[i,i]
108
+ return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
109
+
110
+ def N(i:int, j:int) -> float:
111
+ if i == j: return -P(i)-V[i]**2*G[i,i]
112
+ return -V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
113
+
114
+ def M(i:int, j:int) -> float:
115
+ if i == j: return -P(i)+V[i]**2*G[i,i]
116
+ return V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
117
+
118
+ def L(i:int, j:int) -> float:
119
+ if i == j: return -Q(i)+V[i]**2*B[i,i]
120
+ return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
121
+
122
+ cnt = 0
123
+ while cnt < max_iter:
124
+ y = np.zeros(n, dtype=np.float64)
125
+ for i, b in enumerate(eqs):
126
+ y[i] = Ps[b] - P(b) if i < n_P else Qs[b] - Q(b)
127
+ if np.abs(y).max() < eps:
128
+ break
129
+ cnt += 1
130
+ J = np.zeros((n, n), dtype=np.float64)
131
+ for i, b0 in enumerate(eqs):
132
+ for j, b1 in enumerate(eqs):
133
+ if i < n_P and j < n_P: #dp/dθ
134
+ J[i,j] = H(b0, b1)
135
+ elif i < n_P and j >= n_P: #V*dp/dV
136
+ J[i,j] = N(b0, b1)
137
+ elif i >= n_P and j < n_P: #dp/dV
138
+ J[i,j] = M(b0, b1)
139
+ elif i >= n_P and j >= n_P: #V*dq/dV
140
+ J[i,j] = L(b0, b1)
141
+ x = np.linalg.solve(J, -y)
142
+ for i, (x0, b) in enumerate(zip(x, eqs)):
143
+ if i < n_P: # Δθ
144
+ T[b] += x0
145
+ else: # ΔU/U
146
+ V[b] += V[b] * x0
147
+ if cnt >= max_iter:
148
+ raise ValueError("Bad solution")
149
+ return cnt, V, T, prb.bus_dict
150
+
151
+ class NewtonSolver(SolverBase):
152
+ def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100):
153
+ super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
154
+
155
+ def solve_island(self, i:int, island:Island, _t:int, **kwargs) -> 'tuple[IslandResult, float]':
156
+ try:
157
+ prb = _presolve(island, _t)
158
+ cnt, V, theta, bus_dict = _solve(prb, self.max_iter, self.eps)
159
+ except ValueError as e:
160
+ return IslandResult.Failed, 0.0
161
+
162
+ for b in bus_dict.keys():
163
+ bus = island.grid.Bus(b)
164
+ bus.V = V[bus_dict[b]]
165
+ bus.theta = theta[bus_dict[b]]
166
+ return IslandResult.OK, 0.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: fpowerkit
3
- Version: 0.2.3
3
+ Version: 0.3.0
4
4
  Summary: A Distflow PDN solver based on Gurobi.
5
5
  Author: fmy_xfk
6
6
  Classifier: Programming Language :: Python :: 3
@@ -7,13 +7,13 @@ fpowerkit/cases.py
7
7
  fpowerkit/ess.py
8
8
  fpowerkit/gen.py
9
9
  fpowerkit/grid.py
10
+ fpowerkit/island.py
10
11
  fpowerkit/line.py
11
12
  fpowerkit/pvwind.py
12
13
  fpowerkit/solbase.py
13
14
  fpowerkit/solcmb.py
14
15
  fpowerkit/soldist.py
15
16
  fpowerkit/soldss.py
16
- fpowerkit/solgcal.py
17
17
  fpowerkit/solnt.py
18
18
  fpowerkit/utils.py
19
19
  fpowerkit.egg-info/PKG-INFO
@@ -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.2.3",
8
+ version="0.3.0",
9
9
  author="fmy_xfk",
10
10
  packages=find_packages(),
11
11
  description="A Distflow PDN solver based on Gurobi.",
@@ -1,41 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from enum import IntEnum
3
- from pathlib import Path
4
- from .grid import *
5
-
6
- DEFAULT_SAVETO = "./fpowerkit_logs/"
7
-
8
- class GridSolveResult(IntEnum):
9
- '''Result of grid solving'''
10
- Failed = 0
11
- OK = 1
12
- OKwithoutVICons = 2 # Deprecated
13
- SubOKwithoutVICons = 3 # Deprecated
14
- PartialOK = 4
15
-
16
-
17
- class SolverBase(ABC):
18
- def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, default_saveto:str = DEFAULT_SAVETO, **kwargs):
19
- self.grid = grid
20
- self.eps = eps
21
- self.max_iter = max_iter
22
- self.saveto = default_saveto
23
-
24
- def SetErrorSaveTo(self, path:str = DEFAULT_SAVETO):
25
- self.saveto = path
26
- Path(path).mkdir(parents=True, exist_ok = True)
27
-
28
- def _calc_line_params(self):
29
- for l in self.grid.Lines:
30
- vi = self.grid.Bus(l.fBus).V_cpx
31
- vj = self.grid.Bus(l.tBus).V_cpx
32
- assert vi is not None and vj is not None
33
- i = (vi-vj)/l.Z
34
- l.I = abs(i)
35
- s = vi*i.conjugate()
36
- l.P = s.real
37
- l.Q = s.imag
38
-
39
- @abstractmethod
40
- def solve(self, grid:Grid, _t:int, /, **kwargs):
41
- raise NotImplementedError
@@ -1,110 +0,0 @@
1
- from .solbase import *
2
-
3
- class OpenDSSSolver(SolverBase):
4
- def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
5
- default_saveto:str = DEFAULT_SAVETO, source_bus:str, init_t:int = 0):
6
- super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
7
- try:
8
- from py_dss_interface import DSS
9
- except ImportError:
10
- raise ImportError("py_dss_interface or OpenDSS is not installed. Please install OpenDSS first and then py_dss_interface using 'pip install py_dss_interface'")
11
- self._g = grid
12
- t = init_t
13
- try:
14
- d = DSS()
15
- except:
16
- d = DSS.DSSDLL()
17
- d.text("clear")
18
- cir = f"new circuit.my_circuit basekv={grid.Ub} pu=1 MVASC3=5000000 5000000 bus1={source_bus}"
19
- self.source_bus = source_bus
20
- assert source_bus in grid.BusNames, f"Source bus {source_bus} not found in the grid"
21
- d.text(cir)
22
- for bus in grid.Buses:
23
- bid = bus.ID
24
- if bid != bid.lower():
25
- raise ValueError(f"Bus ID {bid} must be lower case")
26
- p = bus.Pd(t)
27
- q = bus.Qd(t)
28
- d.text(f"New Load.{bid} bus1={bid} kv={self.grid.Ub} kW={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA} vmin={bus.MinV} vmax={bus.MaxV}")
29
- for line in self.grid.Lines:
30
- fid = line.fBus
31
- tid = line.tBus
32
- if line.ID != line.ID.lower():
33
- raise ValueError(f"Line ID {line.ID} must be lower case")
34
- 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")
35
- for pvw in self.grid.PVWinds:
36
- if pvw.ID != pvw.ID.lower():
37
- raise ValueError(f"PVWind ID {pvw.ID} must be lower case")
38
- if pvw.Pr is None:
39
- raise ValueError(f"PVWind {pvw.ID} has no Pr value")
40
- p = pvw.Pr
41
- if pvw.Qr is None:
42
- raise ValueError(f"PVWind {pvw.ID} has no Qr value")
43
- q = pvw.Qr
44
- bid = pvw.BusID
45
-
46
- s = f"New Generator.{pvw.ID} bus1={bid} kv={grid.Ub} kw={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA}"
47
- d.text(s)
48
- for ess in self.grid.ESSs:
49
- if ess.ID != ess.ID.lower():
50
- raise ValueError(f"ESS ID {ess.ID} must be lower case")
51
- if ess.P is None:
52
- raise ValueError(f"ESS {ess.ID} has no P value")
53
- p = ess.P
54
- if ess.Q is None:
55
- raise ValueError(f"ESS {ess.ID} has no Q value")
56
- q = ess.Q
57
- bid = ess.BusID
58
- if p > 0: # charging = load
59
- bus = self.grid.Bus(bid)
60
- 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}"
61
- else: # discharging = generator
62
- s = f"New Generator.{ess.ID} bus1={bid} kv={grid.Ub} kw={p*grid.Sb_kVA} kvar={q*grid.Sb_kVA}"
63
- d.text(s)
64
- for gen in self.grid.Gens:
65
- if gen.ID != gen.ID.lower():
66
- raise ValueError(f"Generator ID {gen.ID} must be lower case")
67
- bid = gen.BusID
68
- if gen.P is None and bid != self.source_bus:
69
- raise ValueError(f"Generator {gen.ID} has no P value")
70
- p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
71
- if gen.Q is None and bid != self.source_bus:
72
- raise ValueError(f"Generator {gen.ID} has no Q value")
73
- q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
74
-
75
- s = f"New Generator.{gen.ID} bus1={bid} kv={grid.Ub} "
76
- if p is not None:
77
- s+=f"kw={p*grid.Sb_kVA} "
78
- if q is not None:
79
- s+=f"kvar={q*grid.Sb_kVA}"
80
- d.text(s)
81
- d.text("set mode=snapshot")
82
- self.dss = d
83
-
84
- def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
85
- self.dss.text(f"set Voltagebases=[{self.grid.Ub}]")
86
- self.dss.text("calcv")
87
- self.dss.text("solve maxcontrol=10000")
88
- if hasattr(self.dss, "circuit"):
89
- bnames = self.dss.circuit.buses_names
90
- bvolt = np.array(self.dss.circuit.buses_volts).reshape(-1, 3, 2)
91
- else:
92
- bnames = self.dss.circuit_all_bus_names()
93
- bvolt = np.array(self.dss.circuit_all_bus_volts()).reshape(-1, 3, 2)
94
- sb_theta = 0
95
- for i, bn in enumerate(bnames):
96
- v1 = bvolt[i,0][0] + 1j * bvolt[i,0][1]
97
- v2 = bvolt[i,1][0] + 1j * bvolt[i,1][1]
98
- v = v1 - v2
99
- b = self.grid.Bus(bn)
100
- b._v = abs(v) / self.grid.Ub / 1000
101
- b.theta = math.atan2(v.imag, v.real)
102
- if bn == self.source_bus:
103
- sb_theta = b.theta
104
-
105
- for i, bn in enumerate(bnames):
106
- self.grid.Bus(bn).theta -= sb_theta
107
-
108
- self._calc_line_params()
109
-
110
- return GridSolveResult.OK, 0.0
@@ -1,124 +0,0 @@
1
- from warnings import warn
2
- from .solbase import *
3
-
4
- class GridCalSolver(SolverBase):
5
- def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, default_saveto:str = DEFAULT_SAVETO,
6
- slack_bus:str, slack_gen:str = "", init_t:int = 0):
7
- try:
8
- import GridCalEngine as gce
9
- except ImportError:
10
- raise ImportError("GridCalEngine is not installed. Please install it using 'pip install GridCalEngine'")
11
- super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
12
- self.max_iter = max_iter
13
- self._g = grid
14
- assert slack_bus in grid.BusNames
15
- self.slack_bus = slack_bus
16
- if slack_gen == "":
17
- slack_gens = grid.GensAtBus(slack_bus)
18
- if len(slack_gens) == 0:
19
- raise RuntimeError("Slack generator not identified, and no generator connects with the slack bus.")
20
- slack_gen = slack_gens[0].ID
21
- #print(f"FPowerKit Info: Use {slack_gen} as the slack generator.")
22
- assert slack_gen in grid.GenNames
23
- self.slack_gen = slack_gen
24
- gcg = gce.MultiCircuit(Sbase=grid.Sb_MVA)
25
- t = init_t
26
- buses:dict[str, gce.Bus] = {}
27
- for bus in grid.Buses:
28
- bid = bus.ID
29
- p = bus.Pd(t)
30
- q = bus.Qd(t)
31
- b_inst = gce.Bus(bid,
32
- Vnom=grid.Ub, # type:ignore
33
- vmin=bus.MinV, vmax=bus.MaxV, is_slack=bid==slack_bus)
34
- buses[bid] = b_inst
35
- gcg.add_bus(b_inst)
36
- gcg.add_load(b_inst, gce.Load(bid+"_load", P = p*grid.Sb_MVA, Q = q*grid.Sb_MVA))
37
-
38
- for line in self.grid.Lines:
39
- fid = line.fBus
40
- tid = line.tBus
41
- gcg.add_line(gce.Line(buses[fid], buses[tid], name=line.ID, r=line.R, x=line.X))
42
-
43
- for pvw in self.grid.PVWinds:
44
- if pvw.Pr is None:
45
- raise ValueError(f"PVWind {pvw.ID} has no Pr value")
46
- p = pvw.Pr
47
- if pvw.Qr is None:
48
- raise ValueError(f"PVWind {pvw.ID} has no Qr value")
49
- q = pvw.Qr
50
- bid = pvw.BusID
51
- g_inst = gce.Generator(pvw.ID, P=p*grid.Sb_MVA, power_factor=pvw.PF, Sbase = grid.Sb_MVA)
52
- gcg.add_generator(buses[bid], g_inst)
53
-
54
- for ess in self.grid.ESSs:
55
- if ess.ID != ess.ID.lower():
56
- raise ValueError(f"ESS ID {ess.ID} must be lower case")
57
- if ess.P is None:
58
- raise ValueError(f"ESS {ess.ID} has no P value")
59
- p = ess.P
60
- if ess.Q is None:
61
- raise ValueError(f"ESS {ess.ID} has no Q value")
62
- q = ess.Q
63
- bid = ess.BusID
64
- if p > 0: # charging = load
65
- bus = self.grid.Bus(bid)
66
- gcg.add_load(buses[bid], gce.Load(ess.ID, P=p*grid.Sb_MVA, Q=q*grid.Sb_MVA))
67
- else: # discharging = generator
68
- g_inst = gce.Generator(ess.ID, P=p*grid.Sb_MVA, power_factor=ess.PF, Sbase = grid.Sb_MVA)
69
- gcg.add_generator(buses[bid], g_inst)
70
-
71
- for gen in self.grid.Gens:
72
- bid = gen.BusID
73
- if gen.ID == slack_gen:
74
- g_inst = gce.Generator(gen.ID, vset=1.0)
75
- if gen.P is not None or gen.Q is not None:
76
- warn(f"Given value of P and Q of the slack generator {gen.ID} is ignored.")
77
- else:
78
- if gen.P is None:
79
- p = 0
80
- else:
81
- p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
82
- if gen.Q is None:
83
- pf = 0.8
84
- else:
85
- q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
86
- pf = p / (p**2 + q**2) ** 0.5
87
- g_inst = gce.Generator(gen.ID, P=p*grid.Sb_MVA, power_factor=pf, Sbase = grid.Sb_MVA, vset=1.0)
88
- gcg.add_generator(buses[bid], g_inst)
89
-
90
- self.grid_cal = gcg
91
-
92
- def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
93
- import GridCalEngine as gce
94
- options = gce.PowerFlowOptions(gce.SolverType.NR,
95
- max_iter=self.max_iter,
96
- retry_with_other_methods=False,
97
- tolerance=self.eps,
98
- control_q=False,
99
- control_taps_phase=False,
100
- control_taps_modules=False,
101
- apply_temperature_correction=False,
102
- use_stored_guess=False,
103
- initialize_angles=True,
104
- verbose=False)
105
-
106
- power_flow = gce.PowerFlowDriver(self.grid_cal, options)
107
- power_flow.run()
108
- assert isinstance(power_flow.results, gce.PowerFlowResults)
109
- if not power_flow.results.converged:
110
- return GridSolveResult.Failed, 0.0
111
- bus_res = power_flow.results.get_bus_df()
112
-
113
- for i, bn in enumerate(self._g.BusNames):
114
- b = self.grid.Bus(bn)
115
- v = bus_res.loc[bn, 'Vm']
116
- assert isinstance(v, (float, np.floating)), f"Bus {bn} voltage is not a float: {type(v)}"
117
- b._v = float(v)
118
- angle = bus_res.loc[bn, 'Va']
119
- assert isinstance(angle, (float, np.floating)), f"Bus {bn} angle is not a float: {type(angle)}"
120
- b.theta = float(angle) / 180 * math.pi
121
-
122
- self._calc_line_params()
123
-
124
- return GridSolveResult.OK, 0.0
@@ -1,150 +0,0 @@
1
- import numpy as np
2
- import math
3
- from .solbase import *
4
-
5
- class BusType(IntEnum):
6
- PQ = 0
7
- PV = 1
8
- Slack = 2
9
-
10
- class NewtonSolver(SolverBase):
11
- def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100):
12
- super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
13
- self.Y = grid.YMat()
14
- self.G, self.B = self.Y.real, self.Y.imag
15
- self.max_iter = max_iter
16
-
17
- def CheckBusType(self, _t:int):
18
- '''Check the bus type'''
19
- busType: 'dict[BusID, BusType]' = {}
20
- slack_cnt = 0
21
- eq_P: 'list[int]' = []
22
- eq_Q: 'list[int]' = []
23
- self.Ps = []
24
- self.Qs = []
25
- for i, bus in enumerate(self.grid._busl):
26
- fixp = fixq = True
27
- p = -bus.Pd(_t)
28
- q = -bus.Qd(_t)
29
- for g in self.grid.GensAtBus(bus.ID):
30
- if not g.FixedP: fixp = False
31
- else:
32
- assert g.P is not None
33
- if isinstance(g.P, TimeFunc): p += g.P(_t)
34
- else: p += g.P
35
- if not g.FixedQ: fixq = False
36
- else:
37
- assert g.Q is not None
38
- if isinstance(g.Q, TimeFunc): q += g.Q(_t)
39
- else: q += g.Q
40
- if bus.FixedV:
41
- if fixp and fixq:
42
- raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
43
- elif fixp:
44
- busType[bus.ID] = BusType.PV
45
- eq_P.append(i)
46
- elif fixq:
47
- raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
48
- else:
49
- busType[bus.ID] = BusType.Slack
50
- slack_cnt += 1
51
- if slack_cnt > 1:
52
- raise ValueError('Only one slack bus is allowed')
53
- else:
54
- if fixp and fixq:
55
- busType[bus.ID] = BusType.PQ
56
- bus.V = 1.0
57
- eq_P.append(i)
58
- eq_Q.append(i)
59
- elif fixp:
60
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
61
- elif fixq:
62
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
63
- else:
64
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
65
- self.Ps.append(p)
66
- self.Qs.append(q)
67
- self.busType = busType
68
- if slack_cnt == 0:
69
- raise ValueError('No slack bus is found')
70
- return eq_P + eq_Q, len(eq_P)
71
-
72
- def dt(self, i:int, j:int) -> float:
73
- return self.grid._busl[i].theta -self.grid._busl[j].theta
74
-
75
- def V(self, i:int) -> float:
76
- r = self.grid._busl[i].V
77
- assert isinstance(r, float)
78
- return r
79
-
80
- def P(self,i:int):
81
- return self.V(i)*sum(self.V(j)*(
82
- self.G[i,j]*math.cos(self.dt(i,j))+
83
- self.B[i,j]*math.sin(self.dt(i,j))
84
- ) for j in range(self.m))
85
-
86
- def Q(self,i:int):
87
- return self.V(i)*sum(self.V(j)*(
88
- self.G[i,j]*math.sin(self.dt(i,j))-
89
- self.B[i,j]*math.cos(self.dt(i,j))
90
- ) for j in range(self.m))
91
-
92
- def H(self, i:int, j:int) -> float:
93
- if i == j: return self.Q(i)+self.V(i)**2*self.B[i,i]
94
- return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
95
-
96
- def N(self, i:int, j:int) -> float:
97
- if i == j: return -self.P(i)-self.V(i)**2*self.G[i,i]
98
- return -self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
99
-
100
- def M(self, i:int, j:int) -> float:
101
- if i == j: return -self.P(i)+self.V(i)**2*self.G[i,i]
102
- return self.V(i)*self.V(j)*(self.G[i,j]*math.cos(self.dt(i,j)) + self.B[i,j]*math.sin(self.dt(i,j)))
103
-
104
- def L(self, i:int, j:int) -> float:
105
- if i == j: return -self.Q(i)+self.V(i)**2*self.B[i,i]
106
- return -self.V(i)*self.V(j)*(self.G[i,j]*math.sin(self.dt(i,j)) - self.B[i,j]*math.cos(self.dt(i,j)))
107
-
108
- def _solve(self) -> int:
109
- cnt = 0
110
- while cnt < self.max_iter:
111
- y = np.zeros(self.n, dtype=np.float64)
112
- for i, b in enumerate(self.eqs):
113
- y[i] = self.Ps[b] - self.P(b) if i < self.n_P else self.Qs[b] - self.Q(b)
114
- if np.abs(y).max() < self.eps:
115
- break
116
- cnt += 1
117
- J = np.zeros((self.n, self.n), dtype=np.float64)
118
- for i, b0 in enumerate(self.eqs):
119
- for j, b1 in enumerate(self.eqs):
120
- if i < self.n_P and j <self. n_P: #dp/dθ
121
- J[i,j] = self.H(b0, b1)
122
- elif i < self.n_P and j >= self.n_P: #V*dp/dV
123
- J[i,j] = self.N(b0, b1)
124
- elif i >= self.n_P and j < self.n_P: #dp/dV
125
- J[i,j] = self.M(b0, b1)
126
- elif i >= self.n_P and j >= self.n_P: #V*dq/dV
127
- J[i,j] = self.L(b0, b1)
128
- x = np.linalg.solve(J, -y)
129
- for i, (x0, b) in enumerate(zip(x, self.eqs)):
130
- if i < self.n_P: # Δθ
131
- self.grid._busl[b].theta += x0
132
- else: # ΔU/U
133
- self.grid._busl[b].V += self.V(b) * x0
134
- if cnt >= self.max_iter:
135
- raise ValueError("Bad solution")
136
- return cnt
137
-
138
- def solve(self, _t:int, /, *, timeout_s:float = 1) -> 'tuple[GridSolveResult, float]':
139
- '''Get the best result at time _t, return a tuple: (result status, optimal objective value)'''
140
- self.eqs, self.n_P = self.CheckBusType(_t)
141
- self.n = len(self.eqs)
142
- self.m = len(self.grid._bnames)
143
- try:
144
- self._solve()
145
- except ValueError:
146
- return GridSolveResult.Failed, -1
147
-
148
- self._calc_line_params()
149
-
150
- return GridSolveResult.OK, 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