fpowerkit 0.2.3__tar.gz → 0.3.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/PKG-INFO +2 -2
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/README.md +0 -1
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/__init__.py +0 -1
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/grid.py +16 -5
- fpowerkit-0.3.1/fpowerkit/island.py +91 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/line.py +2 -1
- fpowerkit-0.3.1/fpowerkit/solbase.py +85 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/solcmb.py +25 -15
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/soldist.py +29 -103
- fpowerkit-0.3.1/fpowerkit/soldss.py +125 -0
- fpowerkit-0.3.1/fpowerkit/solnt.py +166 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit.egg-info/PKG-INFO +2 -2
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit.egg-info/SOURCES.txt +1 -1
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/setup.py +2 -2
- fpowerkit-0.2.3/fpowerkit/solbase.py +0 -41
- fpowerkit-0.2.3/fpowerkit/soldss.py +0 -110
- fpowerkit-0.2.3/fpowerkit/solgcal.py +0 -124
- fpowerkit-0.2.3/fpowerkit/solnt.py +0 -150
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/LICENSE +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/bus.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/cases.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/ess.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/gen.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/pvwind.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit/utils.py +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit.egg-info/dependency_links.txt +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit.egg-info/requires.txt +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/fpowerkit.egg-info/top_level.txt +0 -0
- {fpowerkit-0.2.3 → fpowerkit-0.3.1}/setup.cfg +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: fpowerkit
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: A
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: A PDN solver with multiple solutions.
|
|
5
5
|
Author: fmy_xfk
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
7
7
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -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) -> '
|
|
292
|
-
|
|
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) -> '
|
|
295
|
-
|
|
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.
|
|
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,23 +1,30 @@
|
|
|
1
|
+
from enum import Enum
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
class Estimator(Enum):
|
|
8
|
+
DistFlow = 'DistFlow'
|
|
9
|
+
|
|
10
|
+
class Calculator(Enum):
|
|
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:
|
|
15
|
-
calculator:
|
|
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
|
|
27
|
+
assert estimator == Estimator.DistFlow, "Only DistFlow is supported for now."
|
|
21
28
|
self.est = DistFlowSolver(grid, mlrp = mlrp)
|
|
22
29
|
self.cal_str = calculator
|
|
23
30
|
if calculator in CALCULATORS_NEED_SOURCE_BUS:
|
|
@@ -31,16 +38,19 @@ class CombinedSolver(SolverBase):
|
|
|
31
38
|
res, obj = self.est.solve(_t, timeout_s=timeout_s)
|
|
32
39
|
if res == GridSolveResult.Failed:
|
|
33
40
|
return res, obj
|
|
34
|
-
if self.cal_str ==
|
|
41
|
+
if self.cal_str == Calculator.NoneSolver:
|
|
35
42
|
return res, obj
|
|
36
|
-
elif self.cal_str ==
|
|
43
|
+
elif self.cal_str == Calculator.OpenDSS:
|
|
37
44
|
from .soldss import OpenDSSSolver
|
|
38
45
|
solver = OpenDSSSolver(self.est.grid, source_bus = self.source_bus)
|
|
39
|
-
elif self.cal_str ==
|
|
40
|
-
from .solgcal import GridCalSolver
|
|
41
|
-
solver = GridCalSolver(self.est.grid, slack_bus = self.source_bus)
|
|
42
|
-
else:
|
|
46
|
+
elif self.cal_str == Calculator.Newton:
|
|
43
47
|
from .solnt import NewtonSolver
|
|
44
48
|
solver = NewtonSolver(self.est.grid)
|
|
49
|
+
else:
|
|
50
|
+
raise ValueError(f"Invalid solver type '{self.cal_str}'.")
|
|
45
51
|
res, obj = solver.solve(_t, timeout_s = timeout_s)
|
|
46
|
-
return res, obj
|
|
52
|
+
return res, obj
|
|
53
|
+
|
|
54
|
+
def solve_island(self, i:int, island, _t:int):
|
|
55
|
+
'''Solve the island'''
|
|
56
|
+
raise NotImplementedError
|
|
@@ -2,9 +2,10 @@ 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
|
|
6
|
+
import warnings
|
|
7
7
|
from .solbase import *
|
|
8
|
+
from .island import *
|
|
8
9
|
|
|
9
10
|
VF = Union['Var', float] # type: ignore
|
|
10
11
|
|
|
@@ -15,58 +16,10 @@ class LoadReduceModule:
|
|
|
15
16
|
Limit: TimeFunc
|
|
16
17
|
Reduction: FloatVar = None
|
|
17
18
|
|
|
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
19
|
class DistFlowSolver(SolverBase):
|
|
67
20
|
'''DistFlow solver'''
|
|
68
21
|
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):
|
|
22
|
+
default_saveto:str = DEFAULT_SAVETO, mlrp: float = 0.5, secondary_cost: bool = True, bigM: float = 1e6):
|
|
70
23
|
'''
|
|
71
24
|
Initialize
|
|
72
25
|
grid: Grid object
|
|
@@ -74,17 +27,15 @@ class DistFlowSolver(SolverBase):
|
|
|
74
27
|
mlrp: Maximum proportion of load reduction
|
|
75
28
|
secondary_cost: Whether to include the secondary cost.
|
|
76
29
|
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.
|
|
30
|
+
If True, the cost is calculated as CostA * Pg^2 + CostB * Pg + CostC.
|
|
79
31
|
'''
|
|
80
32
|
super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
|
|
81
33
|
self._decb: dict[BusID, LoadReduceModule] = {}
|
|
82
|
-
self.C =
|
|
34
|
+
self.C = bigM
|
|
83
35
|
self._mlrp = mlrp
|
|
84
36
|
self._oflines: set[LineID] = set()
|
|
85
37
|
self._ofbuses: set[BusID] = set()
|
|
86
|
-
self._sec_cost = secondary_cost
|
|
87
|
-
self.UpdateGrid()
|
|
38
|
+
self._sec_cost = secondary_cost
|
|
88
39
|
|
|
89
40
|
@property
|
|
90
41
|
def OverflowLines(self):
|
|
@@ -94,46 +45,13 @@ class DistFlowSolver(SolverBase):
|
|
|
94
45
|
def OverflowBuses(self):
|
|
95
46
|
return self._ofbuses
|
|
96
47
|
|
|
97
|
-
def UpdateGrid(self, cut_overflow_lines: bool = False):
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
48
|
+
def UpdateGrid(self, grid:Grid, cut_overflow_lines: bool = False):
|
|
49
|
+
if cut_overflow_lines:
|
|
50
|
+
for lID in self._oflines:
|
|
51
|
+
self.grid.Line(lID).active = False
|
|
52
|
+
super().UpdateGrid(grid)
|
|
102
53
|
self.__il_relax = [False] * len(self._islands)
|
|
103
54
|
|
|
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
55
|
@property
|
|
138
56
|
def MLRP(self):
|
|
139
57
|
'''Get the maximum load reduction proportion'''
|
|
@@ -169,15 +87,19 @@ class DistFlowSolver(SolverBase):
|
|
|
169
87
|
val = 0
|
|
170
88
|
for i, il in enumerate(self._islands):
|
|
171
89
|
relax = self.__il_relax[i]
|
|
172
|
-
|
|
173
|
-
|
|
90
|
+
r, v = self.solve_island(i, il, _t, timeout_s, relax, relax)
|
|
91
|
+
self._islands[i].result = r
|
|
92
|
+
self._islands[i].result_value = v
|
|
93
|
+
if r == IslandResult.Failed:
|
|
174
94
|
self.__il_relax[i] = True
|
|
175
|
-
|
|
176
|
-
|
|
95
|
+
r, v = self.solve_island(i, il, _t, timeout_s, True, True)
|
|
96
|
+
self._islands[i].result = r
|
|
97
|
+
self._islands[i].result_value = v
|
|
98
|
+
if r != IslandResult.Failed:
|
|
177
99
|
allFail = False
|
|
178
|
-
val +=
|
|
179
|
-
if
|
|
180
|
-
if
|
|
100
|
+
val += v
|
|
101
|
+
if r != IslandResult.OK: allOK = False
|
|
102
|
+
if r == IslandResult.OverFlow: self.__il_relax[i] = False
|
|
181
103
|
if allOK:
|
|
182
104
|
return GridSolveResult.OK, val
|
|
183
105
|
elif allFail:
|
|
@@ -199,7 +121,7 @@ class DistFlowSolver(SolverBase):
|
|
|
199
121
|
assert ret != float('-inf'), "Value is -inf"
|
|
200
122
|
return ret
|
|
201
123
|
|
|
202
|
-
def
|
|
124
|
+
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
125
|
|
|
204
126
|
''' ---------Variables----------
|
|
205
127
|
pg0[k]: Generator active power
|
|
@@ -217,6 +139,7 @@ class DistFlowSolver(SolverBase):
|
|
|
217
139
|
from cvxpy import Variable as Var
|
|
218
140
|
except ImportError:
|
|
219
141
|
raise ImportError("cvxpy or ecos is not installed. Please install them using 'pip install cvxpy ecos'")
|
|
142
|
+
warnings.filterwarnings("ignore", category=FutureWarning, module="cvxpy")
|
|
220
143
|
cons: 'list[cp.Constraint]' = []
|
|
221
144
|
# Create GEN vars
|
|
222
145
|
pg0: 'dict[str, VF]' = {}
|
|
@@ -330,7 +253,10 @@ class DistFlowSolver(SolverBase):
|
|
|
330
253
|
cons.append(
|
|
331
254
|
inflow + cp.sum(pg[j]) == outflow + pd[j] - dec # type: ignore
|
|
332
255
|
)
|
|
333
|
-
|
|
256
|
+
|
|
257
|
+
# flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
|
|
258
|
+
flow_in = island.grid.LinesOfTBus(j)
|
|
259
|
+
flow_out = island.grid.LinesOfFBus(j)
|
|
334
260
|
# Q constraint
|
|
335
261
|
q_inflow = cp.sum([Q[ln.ID] - ln.X * l[ln.ID] for ln in flow_in if ln.ID in island.Lines])
|
|
336
262
|
q_outflow = cp.sum([Q[ln.ID] for ln in flow_out if ln.ID in island.Lines])
|
|
@@ -367,7 +293,7 @@ class DistFlowSolver(SolverBase):
|
|
|
367
293
|
for gID, g in island.GenItems()])
|
|
368
294
|
|
|
369
295
|
problem = cp.Problem(cp.Minimize(decs + goal + crpe), cons)
|
|
370
|
-
|
|
296
|
+
|
|
371
297
|
try:
|
|
372
298
|
problem.solve(solver=cp.ECOS, verbose=False, max_iters=self.max_iter)
|
|
373
299
|
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() # type: ignore
|
|
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 # type: ignore
|
|
107
|
+
bvolt = np.array(self.dss.circuit.buses_volts).reshape(-1, 3, 2) # type: ignore
|
|
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
|