fpowerkit 0.3.4__tar.gz → 0.3.5.post1__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.3.4 → fpowerkit-0.3.5.post1}/PKG-INFO +21 -2
  2. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/desc.md +17 -1
  3. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/__init__.py +1 -0
  4. fpowerkit-0.3.5.post1/fpowerkit/lpwrapper.py +286 -0
  5. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/solbase.py +2 -1
  6. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/solcmb.py +3 -1
  7. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/solcvx.py +5 -2
  8. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/soldist.py +3 -1
  9. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/soldss.py +3 -1
  10. fpowerkit-0.3.5.post1/fpowerkit/solldf.py +156 -0
  11. fpowerkit-0.3.5.post1/fpowerkit/solldf2.py +143 -0
  12. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/solnt.py +3 -1
  13. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/main.py +45 -18
  14. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/pyproject.toml +5 -1
  15. fpowerkit-0.3.5.post1/test.py +127 -0
  16. fpowerkit-0.3.4/test.py → fpowerkit-0.3.5.post1/test314t.py +15 -10
  17. fpowerkit-0.3.4/fpowerkit/solldf.py +0 -91
  18. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/.gitignore +0 -0
  19. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/LICENSE +0 -0
  20. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/README.md +0 -0
  21. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/bus.py +0 -0
  22. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/cases.py +0 -0
  23. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/ess.py +0 -0
  24. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/gen.py +0 -0
  25. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/grid.py +0 -0
  26. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/island.py +0 -0
  27. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/line.py +0 -0
  28. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/pvwind.py +0 -0
  29. {fpowerkit-0.3.4 → fpowerkit-0.3.5.post1}/fpowerkit/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpowerkit
3
- Version: 0.3.4
3
+ Version: 0.3.5.post1
4
4
  Summary: A PDN solver with multiple solutions.
5
5
  Author: fmy-xfk
6
6
  License-Expression: MIT
@@ -22,13 +22,16 @@ Requires-Dist: cvxpy; extra == 'full'
22
22
  Requires-Dist: ecos; extra == 'full'
23
23
  Requires-Dist: numpy>=1.19.0; extra == 'full'
24
24
  Requires-Dist: py-dss-interface; extra == 'full'
25
+ Provides-Extra: ldf
26
+ Requires-Dist: numpy>=1.19.0; extra == 'ldf'
27
+ Requires-Dist: scipy; extra == 'ldf'
25
28
  Provides-Extra: newton
26
29
  Requires-Dist: numpy>=1.19.0; extra == 'newton'
27
30
  Description-Content-Type: text/markdown
28
31
 
29
32
  # FPowerKit - A power distribution network calculation component
30
33
 
31
- This is a package designed for power distribution network description and solving. Solvers include Newton method, DistFlow and OpenDSS.
34
+ This is a package designed for power distribution network description and solving.
32
35
 
33
36
  This package is affiliated to V2Sim, an open-aource microscopic V2G simulation platform in urban power and transportation network. If you are using the modified DistFlow model in this package, please cite the [paper](https://ieeexplore.ieee.org/document/10970754):
34
37
 
@@ -45,6 +48,21 @@ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation p
45
48
  doi={10.1109/TSG.2025.3560976}}
46
49
  ```
47
50
 
51
+ ### Solvers available
52
+ There are multiple solvers can be used in FPowerKit.
53
+ - **Power flow calculation**
54
+ - **Newton-Raphson**: Classical method for power flow calculation. **(GIL-free Compatible)**
55
+ - **OpenDSS**: Call external OpenDSS for distribution network solving.
56
+ - **Optimal power flow (OPF)**
57
+ - **DistFlow**: A classical OPF model for radial distribution network, with both quadratic and linear objective of minimal active generation cost.
58
+ - **LinDistFlow**: A typical simplification of DistFlow.
59
+ - **LinDistFlow2**: A **GIL-free compatible** version of LinDistFlow, only supporting linear objective.
60
+
61
+
62
+ There are also some abstract solvers for users to customize:
63
+ - **Combined Solver**: Combine two solvers to accomplish both OPF and accuracte power flow calculation. For example, use LinDistFlow + OpenDSS to get the optimal generation and the accurate power flow. The only GIL-free compatible combination is LinDistFlow2 + Newton.
64
+ - **Manual Solver**: Allow user to customize constraints
65
+
48
66
  ### Installation options
49
67
  If you want to use different features, install with different command:
50
68
 
@@ -54,6 +72,7 @@ If you want to use different features, install with different command:
54
72
  |Y matrix & Newton|`pip install fpowerkit[newton]`|
55
73
  |OpenDSS|`pip install fpowerkit[dss]`|
56
74
  |DistFlow|`pip install fpowerkit[distflow]`|
75
+ |LinDistFlow|`pip install fpowerkit[ldf]`|
57
76
  |All|`pip install fpowerkit[full]`|
58
77
 
59
78
  Secondary development on this package requires all features.
@@ -1,6 +1,6 @@
1
1
  # FPowerKit - A power distribution network calculation component
2
2
 
3
- This is a package designed for power distribution network description and solving. Solvers include Newton method, DistFlow and OpenDSS.
3
+ This is a package designed for power distribution network description and solving.
4
4
 
5
5
  This package is affiliated to V2Sim, an open-aource microscopic V2G simulation platform in urban power and transportation network. If you are using the modified DistFlow model in this package, please cite the [paper](https://ieeexplore.ieee.org/document/10970754):
6
6
 
@@ -17,6 +17,21 @@ This package is affiliated to V2Sim, an open-aource microscopic V2G simulation p
17
17
  doi={10.1109/TSG.2025.3560976}}
18
18
  ```
19
19
 
20
+ ### Solvers available
21
+ There are multiple solvers can be used in FPowerKit.
22
+ - **Power flow calculation**
23
+ - **Newton-Raphson**: Classical method for power flow calculation. **(GIL-free Compatible)**
24
+ - **OpenDSS**: Call external OpenDSS for distribution network solving.
25
+ - **Optimal power flow (OPF)**
26
+ - **DistFlow**: A classical OPF model for radial distribution network, with both quadratic and linear objective of minimal active generation cost.
27
+ - **LinDistFlow**: A typical simplification of DistFlow.
28
+ - **LinDistFlow2**: A **GIL-free compatible** version of LinDistFlow, only supporting linear objective.
29
+
30
+
31
+ There are also some abstract solvers for users to customize:
32
+ - **Combined Solver**: Combine two solvers to accomplish both OPF and accuracte power flow calculation. For example, use LinDistFlow + OpenDSS to get the optimal generation and the accurate power flow. The only GIL-free compatible combination is LinDistFlow2 + Newton.
33
+ - **Manual Solver**: Allow user to customize constraints
34
+
20
35
  ### Installation options
21
36
  If you want to use different features, install with different command:
22
37
 
@@ -26,6 +41,7 @@ If you want to use different features, install with different command:
26
41
  |Y matrix & Newton|`pip install fpowerkit[newton]`|
27
42
  |OpenDSS|`pip install fpowerkit[dss]`|
28
43
  |DistFlow|`pip install fpowerkit[distflow]`|
44
+ |LinDistFlow|`pip install fpowerkit[ldf]`|
29
45
  |All|`pip install fpowerkit[full]`|
30
46
 
31
47
  Secondary development on this package requires all features.
@@ -12,5 +12,6 @@ from .solcvx import *
12
12
  from .soldist import *
13
13
  from .soldss import *
14
14
  from .solldf import *
15
+ from .solldf2 import *
15
16
  from .solnt import *
16
17
  from .utils import *
@@ -0,0 +1,286 @@
1
+ from copy import deepcopy
2
+ from dataclasses import dataclass
3
+ from typing import Dict, Iterable, List, Optional, Union
4
+
5
+
6
+ @dataclass
7
+ class _LPVar:
8
+ name:str
9
+ idx:int
10
+ lb:Optional[float] = 0
11
+ ub:Optional[float] = None
12
+ x:Optional[float] = None # Solution value
13
+
14
+ def __add__(self, other):
15
+ expr = _LPExpr()
16
+ expr.add_term(self.idx, 1.0)
17
+ if isinstance(other, _LPExpr):
18
+ return expr + other
19
+ elif isinstance(other, _LPVar):
20
+ expr.add_term(other.idx, 1.0)
21
+ return expr
22
+ elif isinstance(other, (int, float)):
23
+ expr.add_const(other)
24
+ return expr
25
+ else:
26
+ raise TypeError("Unsupported type for addition")
27
+
28
+ def __sub__(self, other):
29
+ expr = _LPExpr()
30
+ expr.add_term(self.idx, 1.0)
31
+ if isinstance(other, _LPExpr):
32
+ return expr - other
33
+ elif isinstance(other, _LPVar):
34
+ expr.add_term(other.idx, -1.0)
35
+ return expr
36
+ elif isinstance(other, (int, float)):
37
+ expr.add_const(-other)
38
+ return expr
39
+ else:
40
+ raise TypeError("Unsupported type for subtraction")
41
+
42
+ def __neg__(self):
43
+ expr = _LPExpr()
44
+ expr.add_term(self.idx, -1.0)
45
+ return expr
46
+
47
+ def __mul__(self, scalar:Union[float, int]):
48
+ expr = _LPExpr()
49
+ expr.add_term(self.idx, scalar)
50
+ return expr
51
+
52
+ def __rmul__(self, scalar:Union[float, int]):
53
+ return self.__mul__(scalar)
54
+
55
+ def __div__(self, scalar:Union[float, int]):
56
+ expr = _LPExpr()
57
+ expr.add_term(self.idx, 1.0 / scalar)
58
+ return expr
59
+
60
+ class _LPEqCons: # expr == 0
61
+ def __init__(self, expr:'_LPExpr'):
62
+ self.expr = expr
63
+ self.rhs = -self.expr.const
64
+ self.expr.const = 0
65
+
66
+ class _LPIneqCons: # expr <= 0
67
+ def __init__(self, expr:'_LPExpr'):
68
+ self.expr = expr
69
+ self.rhs = -self.expr.const
70
+ self.expr.const = 0
71
+
72
+ class _LPExpr:
73
+ def __init__(self):
74
+ self.terms:Dict[int, float] = {} # var_idx -> coefficient
75
+ self.const = 0.0
76
+
77
+ def add_term(self, var_idx:int, coeff:float):
78
+ if var_idx in self.terms:
79
+ self.terms[var_idx] += coeff
80
+ else:
81
+ self.terms[var_idx] = coeff
82
+
83
+ def add_const(self, value:float):
84
+ self.const += value
85
+
86
+ def __add__(self, other):
87
+ result = deepcopy(self)
88
+
89
+ if isinstance(other, _LPExpr):
90
+ for var_idx, coeff in other.terms.items():
91
+ result.add_term(var_idx, coeff)
92
+ result.add_const(other.const)
93
+ elif isinstance(other, _LPVar):
94
+ result.add_term(other.idx, 1.0)
95
+ elif isinstance(other, (int, float)):
96
+ result.add_const(other)
97
+ else:
98
+ raise TypeError("Unsupported type for addition")
99
+ return result
100
+
101
+ def __radd__(self, other):
102
+ return self.__add__(other)
103
+
104
+ def __sub__(self, other):
105
+ result = deepcopy(self)
106
+
107
+ if isinstance(other, _LPExpr):
108
+ for var_idx, coeff in other.terms.items():
109
+ result.add_term(var_idx, -coeff)
110
+ result.add_const(-other.const)
111
+ elif isinstance(other, _LPVar):
112
+ result.add_term(other.idx, -1.0)
113
+ elif isinstance(other, (int, float)):
114
+ result.add_const(-other)
115
+ else:
116
+ raise TypeError("Unsupported type for subtraction")
117
+ return result
118
+
119
+ def __rsub__(self, other):
120
+ if isinstance(other, _LPExpr):
121
+ return other - self
122
+ elif isinstance(other, _LPVar):
123
+ result = _LPExpr()
124
+ result.add_term(other.idx, 1.0)
125
+ elif isinstance(other, (int, float)):
126
+ result = _LPExpr()
127
+ result.add_const(other)
128
+ else:
129
+ raise TypeError("Unsupported type for subtraction")
130
+
131
+ return result - self
132
+
133
+ def __neg__(self):
134
+ result = deepcopy(self)
135
+ for var_idx in result.terms:
136
+ result.terms[var_idx] = -result.terms[var_idx]
137
+ result.const = -result.const
138
+ return result
139
+
140
+ def __mul__(self, scalar:Union[float, int]):
141
+ result = deepcopy(self)
142
+ for var_idx in result.terms:
143
+ result.terms[var_idx] *= scalar
144
+ result.const *= scalar
145
+ return result
146
+
147
+ def __rmul__(self, scalar:Union[float, int]):
148
+ return self.__mul__(scalar)
149
+
150
+ def __div__(self, scalar:Union[float, int]):
151
+ result = deepcopy(self)
152
+ for var_idx in result.terms:
153
+ result.terms[var_idx] /= scalar
154
+ result.const /= scalar
155
+ return result
156
+
157
+ def __eq__(self, other):
158
+ return _LPEqCons(self - other)
159
+
160
+ def __le__(self, other):
161
+ return _LPIneqCons(self - other)
162
+
163
+ def __ge__(self, other):
164
+ return _LPIneqCons(other - self)
165
+
166
+ def quicksum(items:Iterable[Union[_LPVar, _LPExpr]]) -> _LPExpr:
167
+ result = _LPExpr()
168
+ for other in items:
169
+ if isinstance(other, _LPExpr):
170
+ for var_idx, coeff in other.terms.items():
171
+ result.add_term(var_idx, coeff)
172
+ result.add_const(other.const)
173
+ elif isinstance(other, _LPVar):
174
+ result.add_term(other.idx, 1.0)
175
+ elif isinstance(other, (int, float)):
176
+ result.add_const(other)
177
+ else:
178
+ raise TypeError("Unsupported type for addition")
179
+ return result
180
+
181
+ class LinProgProblem:
182
+ def __init__(self):
183
+ self.__vars:List[_LPVar] = []
184
+ self.__eqs:List[_LPEqCons] = []
185
+ self.__ineqs:List[_LPIneqCons] = []
186
+ self.objective:_LPExpr = _LPExpr()
187
+
188
+ def add_var(self, name:str, lb:Optional[float] = 0, ub: Optional[float] = None):
189
+ """
190
+ Add a variable to the linear programming problem.
191
+ name: Name of the variable
192
+ lb: Lower bound of the variable
193
+ ub: Upper bound of the variable
194
+ """
195
+ idx = len(self.__vars)
196
+ v = _LPVar(name, idx, lb, ub)
197
+ self.__vars.append(v)
198
+ return v
199
+
200
+ def add_cons(self, cons:Union[_LPEqCons, _LPIneqCons, bool]):
201
+ """
202
+ Add a constraint to the linear programming problem.
203
+ cons: The constraint to add (either equality or inequality)
204
+ """
205
+ if isinstance(cons, _LPEqCons):
206
+ self.__eqs.append(cons)
207
+ elif isinstance(cons, _LPIneqCons):
208
+ self.__ineqs.append(cons)
209
+ elif isinstance(cons, bool):
210
+ if not cons:
211
+ raise ValueError("Infeasible constraint (False) added to the problem")
212
+ else:
213
+ raise TypeError("Unsupported constraint type")
214
+
215
+ def set_objective(self, expr:Union[int, float, _LPExpr]):
216
+ """
217
+ Set the objective function for the linear programming problem.
218
+ """
219
+ if isinstance(expr, (int, float)):
220
+ expr_obj = _LPExpr()
221
+ expr_obj.add_const(expr)
222
+ self.objective = expr_obj
223
+ else:
224
+ self.objective = expr
225
+
226
+ def solve(self, minimize:bool = True):
227
+ """
228
+ Solve the linear programming problem.
229
+ minimize: If True, minimize the objective; if False, maximize it.
230
+ Returns: (status_code:int, objective_value:float)
231
+ status_code: 0 if successful, non-zero otherwise.
232
+ objective_value: The optimal objective value if successful, 0.0 otherwise.
233
+ """
234
+ obj = self.objective
235
+ if not minimize:
236
+ obj = -obj
237
+ try:
238
+ from scipy.optimize import linprog
239
+ import numpy as np
240
+ except Exception as e:
241
+ raise RuntimeError("scipy.optimize.linprog is required") from e
242
+
243
+ # objective coefficients
244
+ n = len(self.__vars)
245
+ c = np.zeros(n)
246
+ for var_idx, coeff in obj.terms.items():
247
+ c[var_idx] = coeff
248
+
249
+ # variable bounds (None means unbounded for linprog)
250
+ bounds = [(v.lb, v.ub) for v in self.__vars]
251
+
252
+ # equality constraints
253
+ m1 = len(self.__eqs)
254
+ if m1 > 0:
255
+ A_eq = np.zeros((m1, n))
256
+ b_eq = np.zeros(m1)
257
+ for i, eq in enumerate(self.__eqs):
258
+ for var_idx, coeff in eq.expr.terms.items():
259
+ A_eq[i, var_idx] = coeff
260
+ b_eq[i] = eq.rhs
261
+ else:
262
+ A_eq = None
263
+ b_eq = None
264
+
265
+ # inequality constraints (A_ub x <= b_ub)
266
+ m2 = len(self.__ineqs)
267
+ if m2 > 0:
268
+ A_ub = np.zeros((m2, n))
269
+ b_ub = np.zeros(m2)
270
+ for i, ineq in enumerate(self.__ineqs):
271
+ for var_idx, coeff in ineq.expr.terms.items():
272
+ A_ub[i, var_idx] = coeff
273
+ b_ub[i] = ineq.rhs
274
+ else:
275
+ A_ub = None
276
+ b_ub = None
277
+
278
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')
279
+
280
+ if not res.success:
281
+ return res.status, 0.0
282
+
283
+ for i, v in enumerate(self.__vars):
284
+ v.x = res.x[i]
285
+
286
+ return res.status, float(res.fun) + obj.const
@@ -54,7 +54,8 @@ class SolverBase(ABC):
54
54
  continue
55
55
  vi = self.grid.Bus(l.fBus).V_cpx
56
56
  vj = self.grid.Bus(l.tBus).V_cpx
57
- assert vi is not None and vj is not None
57
+ assert vi is not None, f"Voltage at from bus {l.fBus} is None"
58
+ assert vj is not None, f"Voltage at to bus {l.tBus} is None"
58
59
  i = (vi-vj)/l.Z
59
60
  l.I = abs(i)
60
61
  s = vi*i.conjugate()
@@ -55,4 +55,6 @@ class CombinedSolver(SolverBase):
55
55
 
56
56
  def solve_island(self, i:int, island, _t:int):
57
57
  '''Solve the island'''
58
- raise NotImplementedError
58
+ raise NotImplementedError
59
+
60
+ __all__ = ["CombinedSolver", "Estimator", "Calculator", "CALCULATORS_NEED_SOURCE_BUS"]
@@ -30,9 +30,10 @@ class ManualSolver(SolverBase):
30
30
  """
31
31
  raise NotImplementedError
32
32
 
33
- def solve(self, _t:int, /, *, timeout_s: float = 1, **kwargs) -> Tuple[GridSolveResult, float]:
33
+ def solve(self, _t:int, /, calc_line:bool = True, *, timeout_s: float = 1, **kwargs) -> Tuple[GridSolveResult, float]:
34
34
  ret = super().solve(_t, timeout_s=timeout_s, **kwargs)
35
35
  self.bank.apply()
36
+ if calc_line: self._calc_line_params()
36
37
  return ret
37
38
 
38
39
  def solve_island(self, i:int, island:Island, _t:int, /, **kwargs) -> Tuple[IslandResult, float]:
@@ -55,4 +56,6 @@ class ManualSolver(SolverBase):
55
56
  return IslandResult.Failed, -1
56
57
  if prob.status not in (cp.OPTIMAL, cp.OPTIMAL_INACCURATE):
57
58
  return IslandResult.Failed, -1
58
- return IslandResult.OK, prob.value # type: ignore
59
+ return IslandResult.OK, prob.value # type: ignore
60
+
61
+ __all__ = ['ManualSolver']
@@ -359,4 +359,6 @@ class DistFlowSolver(SolverBase):
359
359
 
360
360
  if not isinstance(goal, (int, float)):
361
361
  goal = self.__chkv(goal.value)
362
- return IslandResult.OverFlow if overflow else IslandResult.OK, goal
362
+ return IslandResult.OverFlow if overflow else IslandResult.OK, goal
363
+
364
+ __all__ = ['DistFlowSolver', 'LoadReduceModule']
@@ -126,4 +126,6 @@ class OpenDSSSolver(SolverBase):
126
126
  for i, bn in enumerate(bnames):
127
127
  self.grid.Bus(bn).theta -= sb_theta
128
128
 
129
- return IslandResult.OK, 0.0
129
+ return IslandResult.OK, 0.0
130
+
131
+ __all__ = ['OpenDSSSolver']
@@ -0,0 +1,156 @@
1
+ from typing import Dict, Optional, Tuple, Union
2
+ from feasytools import TimeFunc
3
+ from .solbase import DEFAULT_SAVETO, IslandResult, SolverBase
4
+ from .grid import Grid
5
+ from .island import Island
6
+
7
+
8
+ def _parse(x, t:int):
9
+ if x is None: raise ValueError("Cannot be None")
10
+ if isinstance(x, (int, float)): return x
11
+ if isinstance(x, TimeFunc): return x(t)
12
+ raise TypeError("Unsupported type for parsing")
13
+
14
+ class LinDistFlowSolver(SolverBase):
15
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
16
+ default_saveto:str = DEFAULT_SAVETO, solver = "ECOS"):
17
+ super().__init__(grid, eps, max_iter, default_saveto=default_saveto)
18
+ self.__solver = solver
19
+
20
+ def solve_island(self, i:int, island:Island, _t:int, **kwargs) -> Tuple[IslandResult, float]:
21
+ import cvxpy as cp
22
+ cons = []
23
+ obj = 0
24
+ # Bind GEN vars to Bus
25
+ pg0: 'dict[str, cp.Variable]' = {}
26
+ qg0: 'dict[str, cp.Variable]' = {}
27
+ pg: 'dict[str, list]' = {b: [] for b in island.Buses}
28
+ qg: 'dict[str, list]' = {b: [] for b in island.Buses}
29
+ pd: 'dict[str, float]' = {bID: b.Pd(_t) for bID, b in island.BusItems()}
30
+ qd: 'dict[str, float]' = {bID: b.Qd(_t) for bID, b in island.BusItems()}
31
+
32
+ # Collect power generation data and set objective
33
+ for gID, g in island.GenItems():
34
+ if g.FixedP:
35
+ pd[g.BusID] -= _parse(g.P, _t)
36
+ else:
37
+ p = cp.Variable(name = f"Pg_{gID}", bounds=[_parse(g.Pmin, _t), _parse(g.Pmax, _t)])
38
+ pg[g.BusID].append(p)
39
+ pg0[gID] = p
40
+ obj = p * _parse(g.CostA, _t) ** 2 + p * _parse(g.CostB, _t) + g.CostC(_t) + obj
41
+ if g.FixedQ:
42
+ qd[g.BusID] -= _parse(g.Q, _t)
43
+ else:
44
+ q = cp.Variable(name = f"Qg_{gID}", bounds=[_parse(g.Qmin, _t), _parse(g.Qmax, _t)])
45
+ qg[g.BusID].append(q)
46
+ qg0[gID] = q
47
+ # Assuming no cost for reactive power generation
48
+
49
+ # Collect power generation data for PV and ESS
50
+ pv0: 'dict[str, cp.Variable]' = {}
51
+
52
+ for pID, p in island.PVWItems():
53
+ p_var = cp.Variable(name = f"P_pv_{pID}", bounds=[0, p.P(_t)])
54
+ pv0[pID] = p_var
55
+ pg[p.BusID].append(p_var)
56
+ qg[p.BusID].append(p_var * p.PF)
57
+
58
+ for eID, e in island.ESSItems():
59
+ p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
60
+ e.P = p
61
+ if p > 0:
62
+ pd[e.BusID] += p
63
+ qd[e.BusID] += q
64
+ elif p < 0:
65
+ pg[e.BusID].append(-p)
66
+ qg[e.BusID].append(-q)
67
+
68
+ # Create p,q vars for lines
69
+ pl:Dict[str, cp.Variable] = {}
70
+ ql:Dict[str, cp.Variable] = {}
71
+ l2:Dict[str, cp.Variable] = {}
72
+ for lid, l in island.LineItems():
73
+ pl[lid] = cp.Variable(name = f"p_{l.ID}", bounds=[None, None])
74
+ ql[lid] = cp.Variable(name = f"q_{l.ID}", bounds=[None, None])
75
+ l2[lid] = cp.Variable(name = f"l2_{l.ID}", nonneg=True)
76
+
77
+ # Create voltage vars for buses
78
+ v2:Dict[str, Union[float, cp.Variable]] = {}
79
+ for bID, b in island.BusItems():
80
+ if not b.FixedV:
81
+ v2[bID] = cp.Variable(name = f"v2_{bID}", bounds=[b.MinV ** 2, b.MaxV ** 2])
82
+ else:
83
+ assert b.V is not None
84
+ v2[bID] = b.V ** 2
85
+
86
+ # Add power constraints for each bus
87
+ for j, bus in island.BusItems():
88
+ flow_in = island.grid.LinesOfTBus(j)
89
+ flow_out = island.grid.LinesOfFBus(j)
90
+
91
+ # P constraint
92
+ inflow = cp.sum([pl[ln.ID] for ln in flow_in if ln.ID in island.Lines])
93
+ outflow = cp.sum([pl[ln.ID] for ln in flow_out if ln.ID in island.Lines])
94
+ cons.append(inflow + cp.sum(pg[j]) == outflow + pd[j])
95
+
96
+ # flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
97
+ flow_in = island.grid.LinesOfTBus(j)
98
+ flow_out = island.grid.LinesOfFBus(j)
99
+ # Q constraint
100
+ q_inflow = cp.sum([ql[ln.ID] for ln in flow_in if ln.ID in island.Lines])
101
+ q_outflow = cp.sum([ql[ln.ID] for ln in flow_out if ln.ID in island.Lines])
102
+ cons.append(q_inflow + cp.sum(qg[j]) == q_outflow + qd[j])
103
+
104
+ # Add line constraints
105
+ for lid, l in island.LineItems():
106
+ fbus = island.grid.Bus(l.fBus)
107
+ tbus = island.grid.Bus(l.tBus)
108
+ if fbus is None or tbus is None:
109
+ raise ValueError(f"Line {l.ID} has no bus {l.fBus} or {l.tBus}")
110
+ cons.append(v2[tbus.ID] == v2[fbus.ID] - 2*l.R*pl[lid] - 2*l.X*ql[lid])
111
+ l.I = None # Clear the current variable to avoid confusion
112
+
113
+ prob = cp.Problem(cp.Minimize(obj), cons)
114
+ prob.solve(solver=self.__solver, verbose=False, max_iters=self.max_iter)
115
+ if prob.status in (cp.OPTIMAL, cp.OPTIMAL_INACCURATE):
116
+ # Solution found
117
+ for lid, l in island.LineItems():
118
+ this_P = pl[lid].value
119
+ if this_P is not None:
120
+ l.P = this_P.item()
121
+ this_Q = ql[lid].value
122
+ if this_Q is not None:
123
+ l.Q = this_Q.item()
124
+ this_I2 = l2[lid].value
125
+ if this_I2 is not None:
126
+ l.I = this_I2.item() ** 0.5
127
+
128
+ for bID, b in island.BusItems():
129
+ this_v2 = v2[bID]
130
+ if isinstance(this_v2, cp.Variable) and this_v2.value is not None:
131
+ b.V = this_v2.value.item() ** 0.5
132
+ b.theta = 0.0 # Angle is not calculated in LinDistFlow
133
+
134
+ for gID, g in island.GenItems():
135
+ if not g.FixedP:
136
+ this_pg = pg0[gID].value
137
+ if this_pg is not None:
138
+ g._p = this_pg.item()
139
+ if not g.FixedQ:
140
+ this_qg = qg0[gID].value
141
+ if this_qg is not None:
142
+ g._q = this_qg.item()
143
+
144
+ for pID, p in island.PVWItems():
145
+ this_pr = pv0[pID].value
146
+ if this_pr is not None:
147
+ p._pr = this_pr.item()
148
+ p._qr = p._pr * p.PF if p._pr is not None else 0
149
+
150
+ obj_out = prob.value
151
+ assert isinstance(obj_out, (int, float))
152
+ return IslandResult.OK, float(obj_out)
153
+ else:
154
+ return IslandResult.Failed, 0.0
155
+
156
+ __all__ = ['LinDistFlowSolver']
@@ -0,0 +1,143 @@
1
+ from typing import Dict, Tuple, Union
2
+ from feasytools import TimeFunc
3
+ from .solbase import DEFAULT_SAVETO, IslandResult, SolverBase
4
+ from .grid import Grid
5
+ from .island import Island
6
+
7
+
8
+ def _parse(x, t:int):
9
+ if x is None: raise ValueError("Cannot be None")
10
+ if isinstance(x, (int, float)): return x
11
+ if isinstance(x, TimeFunc): return x(t)
12
+ raise TypeError("Unsupported type for parsing")
13
+
14
+ class LinDistFlow2Solver(SolverBase):
15
+ def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *, default_saveto:str = DEFAULT_SAVETO):
16
+ super().__init__(grid, eps, max_iter, default_saveto=default_saveto)
17
+
18
+ def solve_island(self, i:int, island:Island, _t:int, **kwargs) -> Tuple[IslandResult, float]:
19
+ from .lpwrapper import LinProgProblem, quicksum, _LPVar
20
+ prob = LinProgProblem()
21
+
22
+ obj = 0
23
+ # Bind GEN vars to Bus
24
+ pg0: 'dict[str, _LPVar]' = {}
25
+ qg0: 'dict[str, _LPVar]' = {}
26
+ pg: 'dict[str, list]' = {b: [] for b in island.Buses}
27
+ qg: 'dict[str, list]' = {b: [] for b in island.Buses}
28
+ pd: 'dict[str, float]' = {bID: b.Pd(_t) for bID, b in island.BusItems()}
29
+ qd: 'dict[str, float]' = {bID: b.Qd(_t) for bID, b in island.BusItems()}
30
+
31
+ # Collect power generation data and set objective
32
+ for gID, g in island.GenItems():
33
+ if g.FixedP:
34
+ pd[g.BusID] -= _parse(g.P, _t)
35
+ else:
36
+ p = prob.add_var(f"Pg_{gID}", _parse(g.Pmin, _t), _parse(g.Pmax, _t))
37
+ pg[g.BusID].append(p)
38
+ pg0[gID] = p
39
+ obj = p * _parse(g.CostB, _t) + g.CostC(_t) + obj
40
+ if g.FixedQ:
41
+ qd[g.BusID] -= _parse(g.Q, _t)
42
+ else:
43
+ q = prob.add_var(f"Qg_{gID}", _parse(g.Qmin, _t), _parse(g.Qmax, _t))
44
+ qg[g.BusID].append(q)
45
+ qg0[gID] = q
46
+ # Assuming no cost for reactive power generation
47
+
48
+ # Collect power generation data for PV and ESS
49
+ pv0: 'dict[str, _LPVar]' = {}
50
+
51
+ for pID, p in island.PVWItems():
52
+ p_var = prob.add_var(f"P_pv_{pID}", 0, p.P(_t))
53
+ pv0[pID] = p_var
54
+ pg[p.BusID].append(p_var)
55
+ qg[p.BusID].append(p_var * p.PF)
56
+
57
+ for eID, e in island.ESSItems():
58
+ p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
59
+ e.P = p
60
+ if p > 0:
61
+ pd[e.BusID] += p
62
+ qd[e.BusID] += q
63
+ elif p < 0:
64
+ pg[e.BusID].append(-p)
65
+ qg[e.BusID].append(-q)
66
+
67
+ # Create p,q vars for lines
68
+ pl:Dict[str, _LPVar] = {}
69
+ ql:Dict[str, _LPVar] = {}
70
+ l2:Dict[str, _LPVar] = {}
71
+ for lid, l in island.LineItems():
72
+ pl[lid] = prob.add_var(f"p_{l.ID}", None, None)
73
+ ql[lid] = prob.add_var(f"q_{l.ID}", None, None)
74
+ l2[lid] = prob.add_var(f"l2_{l.ID}")
75
+
76
+ # Create voltage vars for buses
77
+ v2:Dict[str, Union[float, _LPVar]] = {}
78
+ for bID, b in island.BusItems():
79
+ if not b.FixedV:
80
+ v2[bID] = prob.add_var(f"v2_{bID}", b.MinV ** 2, b.MaxV ** 2)
81
+ else:
82
+ assert b.V is not None
83
+ v2[bID] = b.V ** 2
84
+
85
+ # Add power constraints for each bus
86
+ for j, bus in island.BusItems():
87
+ flow_in = island.grid.LinesOfTBus(j)
88
+ flow_out = island.grid.LinesOfFBus(j)
89
+
90
+ # P constraint
91
+ inflow = quicksum(pl[ln.ID] for ln in flow_in if ln.ID in island.Lines)
92
+ outflow = quicksum(pl[ln.ID] for ln in flow_out if ln.ID in island.Lines)
93
+ prob.add_cons(inflow + quicksum(pg[j]) == outflow + pd[j])
94
+
95
+ # flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
96
+ flow_in = island.grid.LinesOfTBus(j)
97
+ flow_out = island.grid.LinesOfFBus(j)
98
+ # Q constraint
99
+ q_inflow = quicksum(ql[ln.ID] for ln in flow_in if ln.ID in island.Lines)
100
+ q_outflow = quicksum(ql[ln.ID] for ln in flow_out if ln.ID in island.Lines)
101
+ prob.add_cons(q_inflow + quicksum(qg[j]) == q_outflow + qd[j])
102
+
103
+ # Add line constraints
104
+ for lid, l in island.LineItems():
105
+ fbus = island.grid.Bus(l.fBus)
106
+ tbus = island.grid.Bus(l.tBus)
107
+ if fbus is None or tbus is None:
108
+ raise ValueError(f"Line {l.ID} has no bus {l.fBus} or {l.tBus}")
109
+ prob.add_cons(v2[tbus.ID] == v2[fbus.ID] - 2*l.R*pl[lid] - 2*l.X*ql[lid])
110
+ l.I = None # Clear the current variable to avoid confusion
111
+
112
+ prob.set_objective(obj)
113
+ status, obj = prob.solve(minimize=True)
114
+ if status == 0:
115
+ # Solution found
116
+ for lid, l in island.LineItems():
117
+ l.P = pl[lid].x
118
+ l.Q = ql[lid].x
119
+ this_I2 = l2[lid]
120
+ if this_I2.x is not None:
121
+ l.I = this_I2.x ** 0.5
122
+
123
+ for bID, b in island.BusItems():
124
+ this_v2 = v2[bID]
125
+ if isinstance(this_v2, _LPVar) and this_v2.x is not None:
126
+ b.V = this_v2.x ** 0.5
127
+ b.theta = 0.0 # Angle is not calculated in LinDistFlow
128
+
129
+ for gID, g in island.GenItems():
130
+ if not g.FixedP:
131
+ g._p = pg0[gID].x
132
+ if not g.FixedQ:
133
+ g._q = qg0[gID].x
134
+
135
+ for pID, p in island.PVWItems():
136
+ p._pr = pv0[pID].x
137
+ p._qr = p._pr * p.PF if p._pr is not None else 0
138
+
139
+ return IslandResult.OK, obj
140
+ else:
141
+ return IslandResult.Failed, obj
142
+
143
+ __all__ = ['LinDistFlow2Solver']
@@ -171,4 +171,6 @@ class NewtonSolver(SolverBase):
171
171
  bus = island.grid.Bus(b)
172
172
  bus.V = V[bus_dict[b]]
173
173
  bus.theta = theta[bus_dict[b]]
174
- return IslandResult.OK, 0.0
174
+ return IslandResult.OK, 0.0
175
+
176
+ __all__ = ['NewtonSolver', 'BusType']
@@ -1,7 +1,11 @@
1
1
  import sys
2
- from fpowerkit import *
3
2
  import argparse
3
+ from feasytools import TimeFunc
4
+ from fpowerkit import *
4
5
 
6
+ OPF_MODEL = ['DistFlow','LinDistFlow','LinDistFlow2']
7
+ PF_MODEL = ['Newton','OpenDSS']
8
+ ALL_MODEL = OPF_MODEL + PF_MODEL
5
9
 
6
10
  if __name__=="__main__":
7
11
  parser = argparse.ArgumentParser(description='Gurobi DistFlow Model Solver')
@@ -15,6 +19,7 @@ if __name__=="__main__":
15
19
  parser.add_argument('-sb',type=str,metavar='source_bus',help="Source bus/Slack bus ID for OpenDSS/GridCal solver", default="")
16
20
  opt = parser.parse_args()
17
21
  gr = Grid.fromFile(opt.g)
22
+
18
23
  if opt.o == "":
19
24
  output = sys.stdout
20
25
  req_close = False
@@ -23,52 +28,71 @@ if __name__=="__main__":
23
28
  else:
24
29
  output = open(opt.o,"w")
25
30
  req_close = True
26
- if opt.m == "DistFlow":
31
+
32
+ # Create Solver
33
+ model = opt.m
34
+ assert model in ALL_MODEL, f"Invalid solver method: {model}"
35
+ if model == "DistFlow":
27
36
  svr = DistFlowSolver(gr)
28
- elif opt.m == "Newton":
37
+ elif model == "Newton":
29
38
  svr = NewtonSolver(gr)
30
- elif opt.m == "OpenDSS":
39
+ elif model == "OpenDSS":
31
40
  svr = OpenDSSSolver(gr, source_bus=opt.sb.split(','))
32
- elif opt.m == "Combined":
41
+ elif model == "Combined":
33
42
  svr = CombinedSolver(gr, source_bus=opt.sb)
34
- elif opt.m == "LinDistFlow":
43
+ elif model == "LinDistFlow":
35
44
  svr = LinDistFlowSolver(gr)
45
+ elif model == "LinDistFlow2":
46
+ svr = LinDistFlow2Solver(gr)
36
47
  else:
37
- raise ValueError(f"Invalid sovler: {opt.m}")
48
+ raise ValueError(f"Invalid solver: {model}")
49
+
38
50
  def _chk(x):
39
51
  if x is None: return "None"
40
52
  else: return f"{x:.4f}"
53
+
41
54
  logs = [x.strip().lower() for x in opt.l.split(',')]
55
+
42
56
  for t in range(opt.b,opt.e+1,opt.s):
43
57
  print(f"Time {t}:", file=output)
44
- ret,val = svr.solve(t)
58
+ ret, val = svr.solve(t)
45
59
  if ret:
46
- print(f"Obj = {val:.6f}", file=output)
47
- if "bus" in logs:
48
- if opt.m=='DistFlow' or opt.m=='LinDistFlow':
60
+ if model in OPF_MODEL:
61
+ print(f"OBJ {val:.6f}", file=output)
62
+
63
+ if "bus" in logs and len(gr.Buses)>0:
64
+ print(f"BUS {len(gr.Buses)}", file=output)
65
+ if model in OPF_MODEL:
49
66
  print("BusID\tV/pu", file=output)
50
67
  for bus in gr.Buses:
51
68
  print(f"{bus.ID:5}\t{_chk(bus.V)}", file=output)
52
69
  else:
53
- print("BusID\tV/pu\tθ/rad", file=output)
70
+ print("BusID\tV/pu\ttheta/rad", file=output)
54
71
  for bus in gr.Buses:
55
72
  print(f"{bus.ID:5}\t{_chk(bus.V)}\t{_chk(bus.theta)}", file=output)
56
- if "line" in logs:
73
+
74
+ if "line" in logs and len(gr.Lines)>0:
75
+ print(f"LINE {len(gr.Lines)}", file=output)
57
76
  print("LineID\tI/kA \tP/pu \tQ/pu ", file=output)
58
77
  for line in gr.Lines:
59
78
  i = _chk(line.I*gr.Ib) if line.I is not None else "None"
60
79
  print(f"{line.ID:6}\t{i}\t{_chk(line.P)}\t{_chk(line.Q)}", file=output)
80
+
61
81
  if isinstance(svr,DistFlowSolver) and len(svr.OverflowLines)>0:
62
82
  ofl = ','.join(map(str,svr.OverflowLines))
63
83
  print(f"Overflow lines: {ofl}", file=output)
64
- if opt.m=='DistFlow':
65
- if "gen" in logs:
84
+
85
+ if model in OPF_MODEL:
86
+ if "gen" in logs and len(gr.Gens)>0:
87
+ print(f"GEN {len(gr.Gens)}", file=output)
66
88
  print(f"GenID\tP/pu \tQ/pu ", file=output)
67
89
  for gen in gr.Gens:
68
90
  p = gen.P(t) if isinstance(gen.P, TimeFunc) else gen.P
69
91
  q = gen.Q(t) if isinstance(gen.Q, TimeFunc) else gen.Q
70
92
  print(f"{gen.ID:5}\t{_chk(p)}\t{_chk(q)}", file=output)
71
- if "pvwind" in logs:
93
+
94
+ if "pvwind" in logs and len(gr.PVWinds)>0:
95
+ print(f"PVWIND {len(gr.PVWinds)}", file=output)
72
96
  print("PVWID\tP/pu \tQ/pu \tCR/% ", file=output)
73
97
  for pvw in gr.PVWinds:
74
98
  p = pvw.Pr
@@ -76,7 +100,9 @@ if __name__=="__main__":
76
100
  cr = pvw.CR
77
101
  cr_str = f"{cr*100:.2f}%" if cr is not None else "None"
78
102
  print(f"{pvw.ID:5}\t{_chk(p)}\t{_chk(q)}\t{cr_str}", file=output)
79
- if "ess" in logs:
103
+
104
+ if "ess" in logs and len(gr.ESSs)>0:
105
+ print(f"ESS {len(gr.ESSs)}", file=output)
80
106
  print("ESSID\tP/pu \tQ/pu \tSOC/% \tElec/puh", file=output)
81
107
  for ess in gr.ESSs:
82
108
  p = ess.P
@@ -87,4 +113,5 @@ if __name__=="__main__":
87
113
  gr.ApplyAllESS(opt.s)
88
114
  else:
89
115
  print("Fail", file=output)
90
- if req_close: output.close()
116
+ if req_close:
117
+ output.close()
@@ -12,7 +12,7 @@ exclude = [
12
12
 
13
13
  [project]
14
14
  name = "fpowerkit"
15
- version = "0.3.4"
15
+ version = "0.3.5.post1"
16
16
  requires-python = ">=3.8"
17
17
  description = "A PDN solver with multiple solutions."
18
18
  readme = "desc.md"
@@ -42,6 +42,10 @@ distflow = [
42
42
  "cvxpy",
43
43
  "ecos",
44
44
  ]
45
+ ldf = [
46
+ "numpy>=1.19.0",
47
+ "scipy"
48
+ ]
45
49
  dss = [
46
50
  "numpy>=1.19.0",
47
51
  "py_dss_interface",
@@ -0,0 +1,127 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from typing import Dict, List, Optional, TextIO
4
+
5
+ @dataclass
6
+ class TimeSlice:
7
+ obj: Optional[float]
8
+ bus: Dict[str, List[float]]
9
+ line: Dict[str, List[float]]
10
+ gen: Dict[str, List[float]]
11
+ pvwind: Dict[str, List[float]]
12
+ ess: Dict[str, List[float]]
13
+
14
+ def read_module(f:TextIO):
15
+ ln = f.readline().strip()
16
+ if not ln:
17
+ return "", {}
18
+ op, cnt = ln.split()
19
+ if op.upper() == "OBJ":
20
+ return op, {"obj": [float(cnt)]}
21
+ data = {}
22
+ f.readline() # header
23
+ for i in range(int(cnt)):
24
+ items = f.readline().strip().split()
25
+ data[items[0]] = [float(x) for x in items[1:]]
26
+ return op, data
27
+
28
+ def read_timeslice(f:TextIO) -> TimeSlice:
29
+ obj = None
30
+ bus_data = {}
31
+ line_data = {}
32
+ gen_data = {}
33
+ pvwind_data = {}
34
+ ess_data = {}
35
+
36
+ while True:
37
+ op, data = read_module(f)
38
+ op = op.upper()
39
+ if op == "OBJ":
40
+ obj = data["obj"][0]
41
+ elif op == "BUS":
42
+ bus_data = data
43
+ elif op == "LINE":
44
+ line_data = data
45
+ elif op == "GEN":
46
+ gen_data = data
47
+ elif op == "PVWIND":
48
+ pvwind_data = data
49
+ elif op == "ESS":
50
+ ess_data = data
51
+ else:
52
+ break
53
+
54
+ return TimeSlice(
55
+ obj=obj,
56
+ bus=bus_data,
57
+ line=line_data,
58
+ gen=gen_data,
59
+ pvwind=pvwind_data,
60
+ ess=ess_data
61
+ )
62
+
63
+ def load_result(file_path: str):
64
+ f = open(file_path)
65
+ slices:List[TimeSlice] = []
66
+ while True:
67
+ ln = f.readline().strip()
68
+ if not ln:
69
+ break
70
+ if ln.startswith("Time "):
71
+ ts = read_timeslice(f)
72
+ slices.append(ts)
73
+ f.close()
74
+ return slices
75
+
76
+ def __cmp(x1, x2):
77
+ if x1 is None and x2 is None:
78
+ return True
79
+ if x1 is None or x2 is None:
80
+ return False
81
+ return abs(x1 - x2) < 1e-4
82
+
83
+ def compare(file1:str, file2:str):
84
+ r1 = load_result(file1)
85
+ r2 = load_result(file2)
86
+ assert len(r1) == len(r2), "Number of time slices differ"
87
+ for s1, s2 in zip(r1, r2):
88
+ assert __cmp(s1.obj, s2.obj), "Objective values differ"
89
+ for mod in ['bus', 'line', 'gen', 'pvwind', 'ess']:
90
+ d1 = getattr(s1, mod)
91
+ d2 = getattr(s2, mod)
92
+ assert d1.keys() == d2.keys(), f"{mod} IDs differ"
93
+ for key in d1.keys():
94
+ vals1 = d1[key]
95
+ vals2 = d2[key]
96
+ assert len(vals1) == len(vals2), f"Number of values for {mod} ID {key} differ"
97
+ for v1, v2 in zip(vals1, vals2):
98
+ if abs(v1 - v2) > 1e-4:
99
+ print(f"Difference found in {mod} ID {key}: {v1} vs {v2}")
100
+ return 1
101
+ return 0
102
+
103
+ def test_one(case_name:str, output_file:str, answer_file:str, extra_opts:str=""):
104
+ print(f"Test {case_name}: {extra_opts}")
105
+ os.system(f'python main.py -g cases/{case_name} -o test/{output_file} {extra_opts}')
106
+ diffs = compare(f'test/{output_file}', answer_file)
107
+ if diffs == 0:
108
+ print(f" Test passed for {output_file}")
109
+ else:
110
+ print(f" Test failed for {output_file} with {diffs} diffs")
111
+
112
+ if __name__ == "__main__":
113
+ print("Testing...")
114
+ print("2islands DistFlow")
115
+ os.system('python main.py -g cases/2islands.xml -o test/2islands_d.out -m DistFlow')
116
+
117
+ test_one("33base.xml", "33base_df.out", 'test/33base_df.ans', "-m DistFlow")
118
+ test_one("33base.xml", "33base_ldf2.out", 'test/33base_ldf.ans', "-m LinDistFlow2")
119
+ test_one("33base.xml", "33base_ldf.out", 'test/33base_ldf.ans', "-m LinDistFlow")
120
+ test_one("33base.xml", "33base_nt.out", 'test/33base_nt.ans', "-m Newton")
121
+
122
+ print("33mulg DistFlow")
123
+ os.system('python main.py -g cases/33mulg.xml -o test/33mulg_d.out -m DistFlow -b 0 -e 86400 -s 3600')
124
+ print("33pvwd DistFlow")
125
+ os.system('python main.py -g cases/33pvwd.xml -o test/33pvwd_d.out -m DistFlow -b 0 -e 86400 -s 3600')
126
+ print("33esss DistFlow")
127
+ os.system('python main.py -g cases/33esss.xml -o test/33esss_d.out -m DistFlow -b 0 -e 86400 -s 3600')
@@ -18,15 +18,20 @@ def compare(file1:str, file2:str):
18
18
 
19
19
  if __name__ == "__main__":
20
20
  print("Testing...")
21
- print("2islands DistFlow")
22
- os.system('python main.py -g cases/2islands.xml -o test/2islands_d.out -m DistFlow')
23
21
  print("33base DistFlow")
24
- os.system('python main.py -g cases/33base.xml -o test/33base_d.out -m DistFlow')
22
+ os.system('python main.py -g cases/33base.xml -o test/33base_df.out -m LinDistFlow2')
23
+ print("33base LinDistFlow")
24
+ os.system('python main.py -g cases/33base.xml -o test/33base_ldf.out -m LinDistFlow2')
25
+ print("33base LinDistFlow2")
26
+ os.system('python main.py -g cases/33base.xml -o test/33base_ldf2.out -m LinDistFlow2')
25
27
  print("33base Newton")
26
- os.system('python main.py -g cases/33base.xml -o test/33base_n.out -m Newton')
27
- print("33mulg DistFlow")
28
- os.system('python main.py -g cases/33mulg.xml -o test/33mulg_d.out -m DistFlow -b 0 -e 86400 -s 3600')
29
- print("33pvwd DistFlow")
30
- os.system('python main.py -g cases/33pvwd.xml -o test/33pvwd_d.out -m DistFlow -b 0 -e 86400 -s 3600')
31
- print("33esss DistFlow")
32
- os.system('python main.py -g cases/33esss.xml -o test/33esss_d.out -m DistFlow -b 0 -e 86400 -s 3600')
28
+ os.system('python main.py -g cases/33base.xml -o test/33base_nt.out -m Newton')
29
+
30
+ print("2islands LinDistFlow2")
31
+ os.system('python main.py -g cases/2islands.xml -o test/2islands_d.out -m LinDistFlow2')
32
+ print("33mulg LinDistFlow2")
33
+ os.system('python main.py -g cases/33mulg.xml -o test/33mulg_d.out -m LinDistFlow2 -b 0 -e 86400 -s 3600')
34
+ print("33pvwd LinDistFlow2")
35
+ os.system('python main.py -g cases/33pvwd.xml -o test/33pvwd_d.out -m LinDistFlow2 -b 0 -e 86400 -s 3600')
36
+ print("33esss LinDistFlow2")
37
+ os.system('python main.py -g cases/33esss.xml -o test/33esss_d.out -m LinDistFlow2 -b 0 -e 86400 -s 3600')
@@ -1,91 +0,0 @@
1
- from typing import Any, List, Optional, Tuple
2
- from .solbase import DEFAULT_SAVETO, GridSolveResult
3
- from .grid import Grid
4
- from .island import Island
5
- from .utils import VarBank
6
- from .solcvx import ManualSolver
7
-
8
-
9
- class LinDistFlowSolver(ManualSolver):
10
- def __init__(self, grid:Grid, eps:float = 1e-6, max_iter:int = 1000, *,
11
- default_saveto:str = DEFAULT_SAVETO, bank: Optional[VarBank] = None,
12
- solver = "ECOS_BB"):
13
- super().__init__(grid, eps, max_iter, default_saveto=default_saveto, bank=bank, solver=solver)
14
-
15
- def solve(self, _t:int, /, *, timeout_s: float = 1) -> Tuple[GridSolveResult, float]:
16
- return super().solve(_t, timeout_s=timeout_s, calc_line=False)
17
-
18
- def proc_solution(self, i: int, _t:int, bank: VarBank, grid: Grid, island: Island) -> Tuple[List, Any]:
19
- try:
20
- import cvxpy as cp
21
- except ImportError:
22
- raise ImportError("cvxpy is required for LinDistFlowSolver. Please install it via 'pip install cvxpy'.")
23
- cons = []
24
- obj = 0
25
- # Bind GEN vars to Bus
26
- pg: 'dict[str, list]' = {b: [] for b in island.Buses}
27
- qg: 'dict[str, list]' = {b: [] for b in island.Buses}
28
- pd: 'dict[str, float]' = {bID: b.Pd(_t) for bID, b in island.BusItems()}
29
- qd: 'dict[str, float]' = {bID: b.Qd(_t) for bID, b in island.BusItems()}
30
-
31
- # Collect power generation data and set objective
32
- for gID, g in island.GenItems():
33
- act = g.active_var(bank)
34
- p = g.P_var(bank, _t)
35
- q = g.Q_var(bank, _t)
36
- pg[g.BusID].append(p)
37
- qg[g.BusID].append(q)
38
- obj += g.CostA(_t) * p ** 2 + g.CostB(_t) * p + g.CostC(_t)
39
-
40
- # Collect power generation data for PV and ESS
41
- for pID, p in island.PVWItems():
42
- pg[p.BusID].append(p.Pr_var(bank, _t))
43
- qg[p.BusID].append(p.Qr_var(bank, _t))
44
-
45
- for eID, e in island.ESSItems():
46
- p, q = e.GetLoad(_t, island.grid.ChargePrice(_t), island.grid.DischargePrice(_t))
47
- e.P = p
48
- if p > 0:
49
- pd[e.BusID] += p
50
- qd[e.BusID] += q
51
- elif p < 0:
52
- pg[e.BusID].append(-p)
53
- qg[e.BusID].append(-q)
54
-
55
- # Add power constraints for each bus
56
- for j, bus in island.BusItems():
57
- flow_in = island.grid.LinesOfTBus(j)
58
- flow_out = island.grid.LinesOfFBus(j)
59
-
60
- # P constraint
61
- inflow = cp.sum([ln.P_var(bank) for ln in flow_in if ln.ID in island.Lines])
62
- outflow = cp.sum([ln.P_var(bank) for ln in flow_out if ln.ID in island.Lines])
63
- cons.append(
64
- inflow + cp.sum(pg[j]) == outflow + pd[j]
65
- )
66
-
67
- # flow_in and flow_out are Python generators, which cannot be reused, thus needed to be re-assigned
68
- flow_in = island.grid.LinesOfTBus(j)
69
- flow_out = island.grid.LinesOfFBus(j)
70
- # Q constraint
71
- q_inflow = cp.sum([ln.Q_var(bank) for ln in flow_in if ln.ID in island.Lines])
72
- q_outflow = cp.sum([ln.Q_var(bank) for ln in flow_out if ln.ID in island.Lines])
73
- cons.append(
74
- q_inflow + cp.sum(qg[j]) == q_outflow + qd[j]
75
- )
76
-
77
- # Add line constraints
78
- for lid, l in island.LineItems():
79
- fbus = grid.Bus(l.fBus)
80
- tbus = grid.Bus(l.tBus)
81
- if fbus is None or tbus is None:
82
- raise ValueError(f"Line {l.ID} has no bus {l.fBus} or {l.tBus}")
83
- act = l.active_var(bank)
84
- vf = fbus.V2_var(bank) if not fbus.FixedV else fbus.V ** 2 # type: ignore
85
- vt = tbus.V2_var(bank) if not tbus.FixedV else tbus.V ** 2 # type: ignore
86
- p = l.P_var(bank)
87
- q = l.Q_var(bank)
88
- cons.append(vt == (vf - 2*l.R*p - 2*l.X*q))
89
- l.I = None # Clear the current variable to avoid confusion
90
-
91
- return cons, obj # type: ignore
File without changes
File without changes
File without changes