fpowerkit 0.3.6rc1__tar.gz → 0.3.7__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 (30) hide show
  1. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/PKG-INFO +2 -7
  2. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/lpwrapper.py +132 -71
  3. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/solcmb.py +3 -3
  4. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/soldist.py +0 -1
  5. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/solldf2.py +6 -0
  6. fpowerkit-0.3.7/fpowerkit/solnt.py +295 -0
  7. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/pyproject.toml +2 -8
  8. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/test.py +2 -2
  9. fpowerkit-0.3.7/test_cmb.py +31 -0
  10. fpowerkit-0.3.6rc1/fpowerkit/solnt.py +0 -176
  11. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/.gitignore +0 -0
  12. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/LICENSE +0 -0
  13. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/README.md +0 -0
  14. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/desc.md +0 -0
  15. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/__init__.py +0 -0
  16. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/bus.py +0 -0
  17. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/cases.py +0 -0
  18. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/ess.py +0 -0
  19. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/gen.py +0 -0
  20. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/grid.py +0 -0
  21. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/island.py +0 -0
  22. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/line.py +0 -0
  23. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/pvwind.py +0 -0
  24. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/solbase.py +0 -0
  25. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/solcvx.py +0 -0
  26. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/soldss.py +0 -0
  27. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/solldf.py +0 -0
  28. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/fpowerkit/utils.py +0 -0
  29. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/main.py +0 -0
  30. {fpowerkit-0.3.6rc1 → fpowerkit-0.3.7}/test314t.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpowerkit
3
- Version: 0.3.6rc1
3
+ Version: 0.3.7
4
4
  Summary: A PDN solver with multiple solutions.
5
5
  Author: fmy-xfk
6
6
  License-Expression: MIT
@@ -10,23 +10,18 @@ Classifier: Operating System :: OS Independent
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Requires-Python: >=3.8
12
12
  Requires-Dist: feasytools>=0.0.21
13
+ Requires-Dist: numpy>=1.19.0
13
14
  Provides-Extra: distflow
14
15
  Requires-Dist: cvxpy; extra == 'distflow'
15
16
  Requires-Dist: ecos; extra == 'distflow'
16
- Requires-Dist: numpy>=1.19.0; extra == 'distflow'
17
17
  Provides-Extra: dss
18
- Requires-Dist: numpy>=1.19.0; extra == 'dss'
19
18
  Requires-Dist: py-dss-interface; extra == 'dss'
20
19
  Provides-Extra: full
21
20
  Requires-Dist: cvxpy; extra == 'full'
22
21
  Requires-Dist: ecos; extra == 'full'
23
- Requires-Dist: numpy>=1.19.0; extra == 'full'
24
22
  Requires-Dist: py-dss-interface; extra == 'full'
25
23
  Provides-Extra: ldf
26
- Requires-Dist: numpy>=1.19.0; extra == 'ldf'
27
24
  Requires-Dist: scipy; extra == 'ldf'
28
- Provides-Extra: newton
29
- Requires-Dist: numpy>=1.19.0; extra == 'newton'
30
25
  Description-Content-Type: text/markdown
31
26
 
32
27
  # FPowerKit - A power distribution network calculation component
@@ -1,4 +1,3 @@
1
- from copy import deepcopy
2
1
  from dataclasses import dataclass
3
2
  from itertools import chain
4
3
  from typing import Dict, Iterable, List, Optional, Union
@@ -14,72 +13,100 @@ class _LPVar:
14
13
 
15
14
  def __add__(self, other):
16
15
  expr = _LPExpr()
17
- expr.add_term(self.idx, 1.0)
16
+ expr.terms[self.idx] = 1.0
18
17
  if isinstance(other, _LPExpr):
19
18
  return expr + other
20
19
  elif isinstance(other, _LPVar):
21
- expr.add_term(other.idx, 1.0)
20
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) + 1.0
22
21
  return expr
23
22
  elif isinstance(other, (int, float)):
24
- expr.add_const(other)
23
+ expr.const = other
25
24
  return expr
26
25
  else:
27
26
  raise TypeError("Unsupported type for addition")
28
27
 
29
28
  def __sub__(self, other):
30
29
  expr = _LPExpr()
31
- expr.add_term(self.idx, 1.0)
30
+ expr.terms[self.idx] = 1.0
32
31
  if isinstance(other, _LPExpr):
33
32
  return expr - other
34
33
  elif isinstance(other, _LPVar):
35
- expr.add_term(other.idx, -1.0)
34
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) - 1.0
36
35
  return expr
37
36
  elif isinstance(other, (int, float)):
38
- expr.add_const(-other)
37
+ expr.const = -other
39
38
  return expr
40
39
  else:
41
40
  raise TypeError("Unsupported type for subtraction")
42
41
 
43
42
  def __neg__(self):
44
43
  expr = _LPExpr()
45
- expr.add_term(self.idx, -1.0)
44
+ expr.terms[self.idx] = -1.0
46
45
  return expr
47
46
 
48
47
  def __mul__(self, scalar:Union[float, int]):
49
48
  expr = _LPExpr()
50
- expr.add_term(self.idx, scalar)
49
+ expr.terms[self.idx] = scalar
51
50
  return expr
52
51
 
53
52
  def __rmul__(self, scalar:Union[float, int]):
54
53
  return self.__mul__(scalar)
55
54
 
56
- def __div__(self, scalar:Union[float, int]):
55
+ def __truediv__(self, scalar:Union[float, int]):
57
56
  expr = _LPExpr()
58
- expr.add_term(self.idx, 1.0 / scalar)
57
+ expr.terms[self.idx] = 1.0 / scalar
59
58
  return expr
60
59
 
61
- class _LPEqCons: # expr == 0
60
+ def __le__(self, other):
61
+ expr = _LPExpr()
62
+ expr.terms[self.idx] = 1.0
63
+ if isinstance(other, _LPExpr):
64
+ return expr <= other
65
+ elif isinstance(other, _LPVar):
66
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) - 1.0
67
+ return expr <= 0
68
+ elif isinstance(other, (int, float)):
69
+ expr.const = -other
70
+ return expr <= 0
71
+ else:
72
+ raise TypeError("Unsupported type for comparison")
73
+
74
+ def __ge__(self, other):
75
+ expr = _LPExpr()
76
+ expr.terms[self.idx] = 1.0
77
+ if isinstance(other, _LPExpr):
78
+ return expr >= other
79
+ elif isinstance(other, _LPVar):
80
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) - 1.0
81
+ return expr >= 0
82
+ elif isinstance(other, (int, float)):
83
+ expr.const = -other
84
+ return expr >= 0
85
+ else:
86
+ raise TypeError("Unsupported type for comparison")
87
+
88
+ class _LPEqCons:
62
89
  def __init__(self, expr:'_LPExpr'):
63
90
  self.expr = expr
64
- self.rhs = -self.expr.const
91
+ self.rhs = -expr.const
65
92
  self.expr.const = 0
66
93
 
67
94
  def __str__(self):
68
95
  return f"{str(self.expr)} == {self.rhs}"
69
96
 
70
- class _LPIneqCons: # expr <= 0
97
+ class _LPIneqCons:
71
98
  def __init__(self, expr:'_LPExpr'):
72
99
  self.expr = expr
73
- self.rhs = -self.expr.const
100
+ self.rhs = -expr.const
74
101
  self.expr.const = 0
75
102
 
76
103
  def __str__ (self):
77
104
  return f"{str(self.expr)} <= {self.rhs}"
78
105
 
79
106
  class _LPExpr:
80
- def __init__(self):
81
- self.terms:Dict[int, float] = {} # var_idx -> coefficient
82
- self.const = 0.0
107
+ def __init__(self, terms:Optional[Dict[int, float]] = None, const:float = 0.0):
108
+ self.terms:Dict[int, float] = terms.copy() if terms is not None else {}
109
+ self.const = const
83
110
 
84
111
  def add_term(self, var_idx:int, coeff:float):
85
112
  if var_idx in self.terms:
@@ -91,75 +118,76 @@ class _LPExpr:
91
118
  self.const += value
92
119
 
93
120
  def __add__(self, other):
94
- result = deepcopy(self)
95
-
96
121
  if isinstance(other, _LPExpr):
122
+ result_terms = self.terms.copy()
97
123
  for var_idx, coeff in other.terms.items():
98
- result.add_term(var_idx, coeff)
99
- result.add_const(other.const)
124
+ if var_idx in result_terms:
125
+ result_terms[var_idx] += coeff
126
+ else:
127
+ result_terms[var_idx] = coeff
128
+ return _LPExpr(result_terms, self.const + other.const)
100
129
  elif isinstance(other, _LPVar):
101
- result.add_term(other.idx, 1.0)
130
+ result_terms = self.terms.copy()
131
+ result_terms[other.idx] = result_terms.get(other.idx, 0) + 1.0
132
+ return _LPExpr(result_terms, self.const)
102
133
  elif isinstance(other, (int, float)):
103
- result.add_const(other)
134
+ return _LPExpr(self.terms.copy(), self.const + other)
104
135
  else:
105
- raise TypeError("Unsupported type for addition")
106
- return result
136
+ raise TypeError(f"Unsupported type for addition: {type(other)}")
107
137
 
108
138
  def __radd__(self, other):
109
139
  return self.__add__(other)
110
140
 
111
141
  def __sub__(self, other):
112
- result = deepcopy(self)
113
-
114
142
  if isinstance(other, _LPExpr):
143
+ result_terms = self.terms.copy()
115
144
  for var_idx, coeff in other.terms.items():
116
- result.add_term(var_idx, -coeff)
117
- result.add_const(-other.const)
145
+ if var_idx in result_terms:
146
+ result_terms[var_idx] -= coeff
147
+ else:
148
+ result_terms[var_idx] = -coeff
149
+ return _LPExpr(result_terms, self.const - other.const)
118
150
  elif isinstance(other, _LPVar):
119
- result.add_term(other.idx, -1.0)
151
+ result_terms = self.terms.copy()
152
+ result_terms[other.idx] = result_terms.get(other.idx, 0) - 1.0
153
+ return _LPExpr(result_terms, self.const)
120
154
  elif isinstance(other, (int, float)):
121
- result.add_const(-other)
155
+ return _LPExpr(self.terms.copy(), self.const - other)
122
156
  else:
123
- raise TypeError("Unsupported type for subtraction")
124
- return result
157
+ raise TypeError(f"Unsupported type for subtraction: {type(other)}")
125
158
 
126
159
  def __rsub__(self, other):
127
160
  if isinstance(other, _LPExpr):
128
161
  return other - self
129
162
  elif isinstance(other, _LPVar):
130
- result = _LPExpr()
131
- result.add_term(other.idx, 1.0)
163
+ return _LPExpr({other.idx: 1.0}, 0) - self
132
164
  elif isinstance(other, (int, float)):
133
- result = _LPExpr()
134
- result.add_const(other)
165
+ return _LPExpr({}, other) - self
135
166
  else:
136
- raise TypeError("Unsupported type for subtraction")
137
-
138
- return result - self
167
+ raise TypeError(f"Unsupported type for subtraction: {type(other)}")
139
168
 
140
169
  def __neg__(self):
141
- result = deepcopy(self)
142
- for var_idx in result.terms:
143
- result.terms[var_idx] = -result.terms[var_idx]
144
- result.const = -result.const
145
- return result
170
+ result_terms = {}
171
+ for var_idx, coeff in self.terms.items():
172
+ result_terms[var_idx] = -coeff
173
+ return _LPExpr(result_terms, -self.const)
146
174
 
147
175
  def __mul__(self, scalar:Union[float, int]):
148
- result = deepcopy(self)
149
- for var_idx in result.terms:
150
- result.terms[var_idx] *= scalar
151
- result.const *= scalar
152
- return result
176
+ if scalar == 0:
177
+ return _LPExpr()
178
+ result_terms = {}
179
+ for var_idx, coeff in self.terms.items():
180
+ result_terms[var_idx] = coeff * scalar
181
+ return _LPExpr(result_terms, self.const * scalar)
153
182
 
154
183
  def __rmul__(self, scalar:Union[float, int]):
155
184
  return self.__mul__(scalar)
156
185
 
157
- def __div__(self, scalar:Union[float, int]):
158
- result = deepcopy(self)
159
- for var_idx in result.terms:
160
- result.terms[var_idx] /= scalar
161
- result.const /= scalar
162
- return result
186
+ def __truediv__(self, scalar:Union[float, int]):
187
+ result_terms = {}
188
+ for var_idx, coeff in self.terms.items():
189
+ result_terms[var_idx] = coeff / scalar
190
+ return _LPExpr(result_terms, self.const / scalar)
163
191
 
164
192
  def __eq__(self, other):
165
193
  return _LPEqCons(self - other)
@@ -175,21 +203,48 @@ class _LPExpr:
175
203
  if self.const != 0:
176
204
  terms_str.append(f"{self.const}")
177
205
  return " + ".join(terms_str) if terms_str else "0"
206
+
207
+ def to_string(self, prob:'LinProgProblem') -> str:
208
+ terms_str = [f"{coeff}*{prob.get_var_name(var_idx)}" for var_idx, coeff in self.terms.items()]
209
+ if self.const != 0:
210
+ terms_str.append(f"{self.const}")
211
+ return " + ".join(terms_str) if terms_str else "0"
212
+
213
+ def value(self, prob:'LinProgProblem') -> float:
214
+ val = self.const
215
+ for var_idx, coeff in self.terms.items():
216
+ var = prob.variables[var_idx]
217
+ if var.x is None:
218
+ raise ValueError(f"Variable {var.name} has no assigned value")
219
+ val += coeff * var.x
220
+ return val
221
+
222
+ def copy(self):
223
+ """Shallow copy of the expression."""
224
+ return _LPExpr(self.terms.copy(), self.const)
225
+
178
226
 
179
227
  def quicksum(items:Iterable[Union[_LPVar, _LPExpr]]) -> _LPExpr:
180
- result = _LPExpr()
228
+ result_terms = {}
229
+ result_const = 0.0
230
+
181
231
  for other in items:
182
232
  if isinstance(other, _LPExpr):
183
233
  for var_idx, coeff in other.terms.items():
184
- result.add_term(var_idx, coeff)
185
- result.add_const(other.const)
234
+ if var_idx in result_terms:
235
+ result_terms[var_idx] += coeff
236
+ else:
237
+ result_terms[var_idx] = coeff
238
+ result_const += other.const
186
239
  elif isinstance(other, _LPVar):
187
- result.add_term(other.idx, 1.0)
240
+ result_terms[other.idx] = result_terms.get(other.idx, 0) + 1.0
188
241
  elif isinstance(other, (int, float)):
189
- result.add_const(other)
242
+ result_const += other
190
243
  else:
191
- raise TypeError("Unsupported type for addition")
192
- return result
244
+ raise TypeError(f"Unsupported type for addition: {type(other)}")
245
+
246
+ return _LPExpr(result_terms, result_const)
247
+
193
248
 
194
249
  class LinProgProblem:
195
250
  def __init__(self):
@@ -214,6 +269,14 @@ class LinProgProblem:
214
269
  def constraints(self) -> chain[Union[_LPEqCons, _LPIneqCons]]:
215
270
  return chain(self.__eqs, self.__ineqs)
216
271
 
272
+ def get_var_name(self, idx:int) -> str:
273
+ """
274
+ Get the name of a variable by its index.
275
+ idx: Index of the variable
276
+ Returns: Name of the variable
277
+ """
278
+ return self.__vars[idx].name
279
+
217
280
  def add_var(self, name:str, lb:Optional[float] = 0, ub: Optional[float] = None):
218
281
  """
219
282
  Add a variable to the linear programming problem.
@@ -241,14 +304,12 @@ class LinProgProblem:
241
304
  else:
242
305
  raise TypeError("Unsupported constraint type")
243
306
 
244
- def set_objective(self, expr:Union[int, float, _LPExpr]):
245
- """
246
- Set the objective function for the linear programming problem.
247
- """
307
+ def set_objective(self, expr:Union[int, float, _LPExpr, _LPVar]):
308
+ """设置目标函数"""
248
309
  if isinstance(expr, (int, float)):
249
- expr_obj = _LPExpr()
250
- expr_obj.add_const(expr)
251
- self.objective = expr_obj
310
+ self.objective = _LPExpr({}, expr)
311
+ elif isinstance(expr, _LPVar):
312
+ self.objective = _LPExpr({expr.idx: 1.0}, 0)
252
313
  else:
253
314
  self.objective = expr
254
315
 
@@ -1,5 +1,5 @@
1
1
  from enum import Enum
2
- from typing import Union, Iterable
2
+ from typing import Tuple, Union, Iterable
3
3
  from warnings import warn
4
4
  from .grid import Grid
5
5
  from .solbase import *
@@ -47,7 +47,7 @@ class CombinedSolver(SolverBase):
47
47
  if source_bus != "":
48
48
  warn(Warning("source_bus is ignored when not using OpenDSSSolver."))
49
49
 
50
- def solve(self, _t:int, /, *, timeout_s: float = 1):
50
+ def solve(self, _t:int, /, *, timeout_s: float = 1) -> Tuple[GridSolveResult, float]:
51
51
  res, obj = self.est.solve(_t, timeout_s=timeout_s)
52
52
  if res == GridSolveResult.Failed:
53
53
  return res, obj
@@ -58,7 +58,7 @@ class CombinedSolver(SolverBase):
58
58
  solver = OpenDSSSolver(self.est.grid, source_bus = self.source_bus, default_saveto=self.saveto)
59
59
  elif self.cal_str == Calculator.Newton:
60
60
  from .solnt import NewtonSolver
61
- solver = NewtonSolver(self.est.grid, default_saveto=self.saveto)
61
+ solver = NewtonSolver(self.est.grid, default_saveto=self.saveto, is_cmb_calculator=True)
62
62
  else:
63
63
  raise ValueError(f"Invalid solver type '{self.cal_str}'.")
64
64
  res, obj = solver.solve(_t, timeout_s = timeout_s)
@@ -1,7 +1,6 @@
1
1
  import math
2
2
  import warnings
3
3
  from itertools import chain
4
- from pathlib import Path
5
4
  from typing import Optional, Union
6
5
  from dataclasses import dataclass
7
6
  from feasytools import TimeFunc
@@ -25,6 +25,7 @@ class LinDistFlow2Solver(SolverBase):
25
25
  qg0: 'dict[str, _LPVar]' = {}
26
26
  pg: 'dict[str, list]' = {b: [] for b in island.Buses}
27
27
  qg: 'dict[str, list]' = {b: [] for b in island.Buses}
28
+ qg_abs: 'dict[str, list]' = {b: [] for b in island.Buses}
28
29
  pd: 'dict[str, float]' = {bID: b.Pd(_t) for bID, b in island.BusItems()}
29
30
  qd: 'dict[str, float]' = {bID: b.Qd(_t) for bID, b in island.BusItems()}
30
31
 
@@ -41,7 +42,12 @@ class LinDistFlow2Solver(SolverBase):
41
42
  qd[g.BusID] -= _parse(g.Q, _t)
42
43
  else:
43
44
  q = prob.add_var(f"Qg_{gID}", _parse(g.Qmin, _t), _parse(g.Qmax, _t))
45
+ q_abs = prob.add_var(f"Qg_abs_{gID}", 0, None)
44
46
  qg[g.BusID].append(q)
47
+ qg_abs[g.BusID].append(q_abs)
48
+ prob.add_cons(q_abs >= q)
49
+ prob.add_cons(q_abs >= -q)
50
+ obj = q_abs * _parse(g.CostB, _t) * 0.1 + obj # Assuming reactive power cost is 10% of active power cost
45
51
  qg0[gID] = q
46
52
  # Assuming no cost for reactive power generation
47
53
 
@@ -0,0 +1,295 @@
1
+ import numpy as np
2
+ from typing import Any
3
+ from feasytools import TimeFunc
4
+ from enum import IntEnum
5
+ from dataclasses import dataclass
6
+ from .grid import BusID, Grid
7
+ from .island import Island, IslandResult
8
+ from .solbase import *
9
+
10
+ class BusType(IntEnum):
11
+ PQ = 0
12
+ PV = 1
13
+ Slack = 2
14
+
15
+ @dataclass
16
+ class _NRProblem:
17
+ eqs: 'list[int]'
18
+ n_P: int
19
+ Ps: np.ndarray # list[float]
20
+ Qs: np.ndarray # list[float]
21
+ bus_dict: 'dict[str, int]'
22
+ G: np.ndarray # 2D
23
+ B: np.ndarray # 2D
24
+ V: np.ndarray # list[float]
25
+ theta: np.ndarray # list[float]
26
+ slack: int
27
+
28
+ def _presolve(il:Island, _t:int):
29
+ '''Check the bus type'''
30
+ busType: 'dict[BusID, BusType]' = {}
31
+ slack_cnt = 0
32
+ eq_P: 'list[int]' = []
33
+ eq_Q: 'list[int]' = []
34
+ V: 'list[float]' = []
35
+ theta: 'list[float]' = []
36
+ Ps: 'list[float]' = []
37
+ Qs: 'list[float]' = []
38
+ slack:int = -1
39
+ bus_dict, Y = il.YMat()
40
+ for bid, i in bus_dict.items():
41
+ bus = il.grid.Bus(bid)
42
+ V.append(bus.V if bus.V is not None else 1.0)
43
+ theta.append(bus.theta if bus.theta is not None else 0.0)
44
+ fixp = fixq = True
45
+ p = -bus.Pd(_t)
46
+ q = -bus.Qd(_t)
47
+ for g in il.grid.GensAtBus(bus.ID):
48
+ if not g.FixedP: fixp = False
49
+ else:
50
+ assert g.P is not None
51
+ if isinstance(g.P, TimeFunc): p += g.P(_t)
52
+ else: p += g.P
53
+ if not g.FixedQ: fixq = False
54
+ else:
55
+ assert g.Q is not None
56
+ if isinstance(g.Q, TimeFunc): q += g.Q(_t)
57
+ else: q += g.Q
58
+ if bus.FixedV:
59
+ if fixp and fixq:
60
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
61
+ elif fixp:
62
+ busType[bus.ID] = BusType.PV
63
+ eq_P.append(i)
64
+ elif fixq:
65
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
66
+ else:
67
+ busType[bus.ID] = BusType.Slack
68
+ slack = i
69
+ slack_cnt += 1
70
+ if slack_cnt > 1:
71
+ raise ValueError('Only one slack bus is allowed')
72
+ else:
73
+ if fixp and fixq:
74
+ busType[bus.ID] = BusType.PQ
75
+ bus.V = 1.0
76
+ eq_P.append(i)
77
+ eq_Q.append(i)
78
+ elif fixp:
79
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
80
+ elif fixq:
81
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
82
+ else:
83
+ raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
84
+ Ps.append(p)
85
+ Qs.append(q)
86
+ if slack_cnt == 0:
87
+ raise ValueError('No slack bus is found')
88
+ return _NRProblem(
89
+ eq_P + eq_Q, len(eq_P), np.asarray(Ps), np.asarray(Qs),
90
+ bus_dict, Y.real, Y.imag, np.asarray(V), np.asarray(theta), slack
91
+ )
92
+
93
+ def _presolve2(il:Island, _t:int):
94
+ '''Check the bus type after using distflow-like algorithm'''
95
+ busType: 'dict[BusID, BusType]' = {}
96
+ slack_cnt = 0
97
+ eq_P: 'list[int]' = []
98
+ eq_Q: 'list[int]' = []
99
+ V: 'list[float]' = []
100
+ theta: 'list[float]' = []
101
+ Ps: 'list[float]' = []
102
+ Qs: 'list[float]' = []
103
+ bus_dict, Y = il.YMat()
104
+ slack = -1
105
+
106
+ for bid, i in bus_dict.items():
107
+ bus = il.grid.Bus(bid)
108
+ V.append(bus.V if bus.V is not None else 1.0)
109
+ theta.append(bus.theta if bus.theta is not None else 0.0)
110
+
111
+ p = -bus.Pd(_t)
112
+ q = -bus.Qd(_t)
113
+ for g in il.grid.GensAtBus(bus.ID):
114
+ assert g.P is not None
115
+ if isinstance(g.P, TimeFunc): p += g.P(_t)
116
+ else: p += g.P
117
+
118
+ assert g.Q is not None
119
+ if isinstance(g.Q, TimeFunc): q += g.Q(_t)
120
+ else: q += g.Q
121
+
122
+ if bus.FixedV:
123
+ # After Distflow presolve, all the output of generator are fixed, except for the source bus whose V is fixed.
124
+ busType[bus.ID] = BusType.Slack
125
+ slack_cnt += 1
126
+ slack = i
127
+ if slack_cnt > 1:
128
+ raise ValueError('Only one slack bus is allowed')
129
+ else:
130
+ # All other nodes are treated as PQ
131
+
132
+ busType[bus.ID] = BusType.PQ
133
+ bus.V = 1.0
134
+ eq_P.append(i)
135
+ eq_Q.append(i)
136
+
137
+ Ps.append(p)
138
+ Qs.append(q)
139
+
140
+ if slack_cnt == 0:
141
+ raise ValueError('No slack bus is found')
142
+ return _NRProblem(eq_P + eq_Q, len(eq_P), np.asarray(Ps), np.asarray(Qs),
143
+ bus_dict, Y.real, Y.imag, np.asarray(V), np.asarray(theta), slack
144
+ )
145
+
146
+ def _solve(prb: _NRProblem, max_iter: int = 100, eps: float = 1e-6):
147
+ # ---- unpack ----
148
+ G = prb.G
149
+ B = prb.B
150
+ V = prb.V
151
+ T = prb.theta
152
+
153
+ eqs = np.array(prb.eqs, dtype=int)
154
+ Ps = prb.Ps
155
+ Qs = prb.Qs
156
+
157
+ n_P = prb.n_P
158
+ n = len(eqs)
159
+ # m = len(V)
160
+
161
+ # ---- helper: compute P, Q for all buses ----
162
+ def calc_PQ():
163
+ # angle difference matrix
164
+ dT = T[:, None] - T[None, :]
165
+ cosT = np.cos(dT)
166
+ sinT = np.sin(dT)
167
+
168
+ VmVn = V[:, None] * V[None, :]
169
+
170
+ P:np.ndarray = np.sum(VmVn * (G * cosT + B * sinT), axis=1)
171
+ Q:np.ndarray = np.sum(VmVn * (G * sinT - B * cosT), axis=1)
172
+ return P, Q, cosT, sinT
173
+
174
+ cnt = 0
175
+ while cnt < max_iter:
176
+ P, Q, cosT, sinT = calc_PQ()
177
+
178
+ # ---- mismatch vector y ----
179
+ y = np.empty(n)
180
+ y[:n_P] = Ps[eqs[:n_P]] - P[eqs[:n_P]]
181
+ y[n_P:] = Qs[eqs[n_P:]] - Q[eqs[n_P:]]
182
+
183
+ if np.max(np.abs(y)) < eps:
184
+ break
185
+
186
+ cnt += 1
187
+
188
+ # ---- Jacobian blocks ----
189
+ VmVn = V[:, None] * V[None, :]
190
+
191
+ # H = dP/dθ
192
+ H = -(VmVn * (G * sinT - B * cosT))
193
+ np.fill_diagonal(H, Q + V * V * B.diagonal())
194
+
195
+ # N = dP/dV * V
196
+ N = -(VmVn * (G * cosT + B * sinT)) # type: ignore
197
+ np.fill_diagonal(N, -P - V * V * G.diagonal())
198
+
199
+ # M = dQ/dθ
200
+ M = VmVn * (G * cosT + B * sinT)
201
+ np.fill_diagonal(M, -P + V * V * G.diagonal())
202
+
203
+ # L = dQ/dV * V
204
+ L = -(VmVn * (G * sinT - B * cosT))
205
+ np.fill_diagonal(L, -Q + V * V * B.diagonal())
206
+
207
+ # ---- assemble reduced Jacobian ----
208
+ buses_P = eqs[:n_P]
209
+ buses_Q = eqs[n_P:]
210
+
211
+ J = np.block([
212
+ [H[np.ix_(buses_P, buses_P)], N[np.ix_(buses_P, buses_Q)]],
213
+ [M[np.ix_(buses_Q, buses_P)], L[np.ix_(buses_Q, buses_Q)]]
214
+ ])
215
+
216
+ # ---- solve ----
217
+ dx = np.linalg.solve(J, -y)
218
+
219
+ # ---- update state ----
220
+ T[buses_P] += dx[:n_P]
221
+ V[buses_Q] *= (1.0 + dx[n_P:])
222
+
223
+ if cnt >= max_iter:
224
+ raise ValueError("Bad solution")
225
+
226
+ # ---- final injections ----
227
+ P, Q, *_ = calc_PQ()
228
+ return cnt, V, T, P, Q, prb.bus_dict
229
+
230
+
231
+ class NewtonSolver(SolverBase):
232
+ def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100, is_cmb_calculator:bool = False):
233
+ super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
234
+ self.__is_cmb_calc = is_cmb_calculator
235
+
236
+ def solve_island(self, i:int, island:Island, _t:int, **kwargs) -> 'tuple[IslandResult, float]':
237
+ try:
238
+ if self.__is_cmb_calc:
239
+ prb = _presolve2(island, _t)
240
+ else:
241
+ prb = _presolve(island, _t)
242
+ cnt, V, theta, P_inject, Q_inject, bus_dict = _solve(prb, self.max_iter, self.eps)
243
+ except ValueError as e:
244
+ return IslandResult.Failed, 0.0
245
+
246
+ for b, i in bus_dict.items():
247
+ bus = island.grid.Bus(b)
248
+ bus.V = V[bus_dict[b]].item()
249
+ bus.theta = theta[bus_dict[b]].item()
250
+ gens = self.grid.GensAtBus(b)
251
+ if len(gens) == 0:
252
+ continue
253
+ pg = P_inject[i].item() + bus.Pd(_t)
254
+ qg = Q_inject[i].item() + bus.Qd(_t)
255
+
256
+ # Allocate the generation to minimize generation cost
257
+ from .lpwrapper import LinProgProblem, quicksum
258
+ prob = LinProgProblem()
259
+ p_dict = {}; q_dict = {}; obj = 0
260
+ for g in gens:
261
+ if g.FixedP:
262
+ if isinstance(g.P, TimeFunc):
263
+ pg -= g.P(_t)
264
+ else:
265
+ assert g.P is not None
266
+ pg -= g.P
267
+ else:
268
+ assert g.Pmin is not None and g.Pmax is not None
269
+ p_dict[g.ID] = prob.add_var(f'pg_{g.ID}', lb=g.Pmin(_t), ub=g.Pmax(_t))
270
+ obj += g.CostB(_t) * p_dict[g.ID] + g.CostC(_t)
271
+ if g.FixedQ:
272
+ if isinstance(g.Q, TimeFunc):
273
+ qg -= g.Q(_t)
274
+ else:
275
+ assert g.Q is not None
276
+ qg -= g.Q
277
+ else:
278
+ assert g.Qmin is not None and g.Qmax is not None
279
+ q_dict[g.ID] = prob.add_var(f'qg_{g.ID}', lb=g.Qmin(_t), ub=g.Qmax(_t))
280
+ q_abs = prob.add_var(f'qg_abs_{g.ID}', lb=0.0)
281
+ prob.add_cons(q_abs >= q_dict[g.ID])
282
+ prob.add_cons(q_abs >= -q_dict[g.ID])
283
+ obj += g.CostB(_t) * q_abs * 0.1
284
+ prob.add_cons(quicksum(p_dict.values()) == pg)
285
+ prob.add_cons(quicksum(q_dict.values()) == qg)
286
+ prob.set_objective(obj)
287
+ prob.solve()
288
+ for gid, var in p_dict.items():
289
+ island.grid.Gen(gid)._p = var.x
290
+ for gid, var in q_dict.items():
291
+ island.grid.Gen(gid)._q = var.x
292
+
293
+ return IslandResult.OK, 0.0
294
+
295
+ __all__ = ['NewtonSolver', 'BusType']
@@ -12,7 +12,7 @@ exclude = [
12
12
 
13
13
  [project]
14
14
  name = "fpowerkit"
15
- version = "0.3.6rc1"
15
+ version = "0.3.7"
16
16
  requires-python = ">=3.8"
17
17
  description = "A PDN solver with multiple solutions."
18
18
  readme = "desc.md"
@@ -25,6 +25,7 @@ classifiers = [
25
25
  ]
26
26
  dependencies = [
27
27
  "feasytools>=0.0.21",
28
+ "numpy>=1.19.0"
28
29
  ]
29
30
  authors = [
30
31
  {name = "fmy-xfk"},
@@ -32,24 +33,17 @@ authors = [
32
33
 
33
34
  [project.optional-dependencies]
34
35
  full = [
35
- "numpy>=1.19.0",
36
36
  "cvxpy",
37
37
  "ecos",
38
38
  "py_dss_interface",
39
39
  ]
40
40
  distflow = [
41
- "numpy>=1.19.0",
42
41
  "cvxpy",
43
42
  "ecos",
44
43
  ]
45
44
  ldf = [
46
- "numpy>=1.19.0",
47
45
  "scipy"
48
46
  ]
49
47
  dss = [
50
- "numpy>=1.19.0",
51
48
  "py_dss_interface",
52
49
  ]
53
- newton = [
54
- "numpy>=1.19.0",
55
- ]
@@ -85,7 +85,7 @@ def compare(file1:str, file2:str):
85
85
  r2 = load_result(file2)
86
86
  assert len(r1) == len(r2), "Number of time slices differ"
87
87
  for s1, s2 in zip(r1, r2):
88
- assert __cmp(s1.obj, s2.obj), "Objective values differ"
88
+ assert __cmp(s1.obj, s2.obj), "Objective values differ: {} vs {}".format(s1.obj, s2.obj)
89
89
  for mod in ['bus', 'line', 'gen', 'pvwind', 'ess']:
90
90
  d1 = getattr(s1, mod)
91
91
  d2 = getattr(s2, mod)
@@ -115,7 +115,7 @@ if __name__ == "__main__":
115
115
  os.system('python main.py -g cases/2islands.xml -o test/2islands_d.out -m DistFlow')
116
116
 
117
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")
118
+ # test_one("33base.xml", "33base_ldf2.out", 'test/33base_ldf.ans', "-m LinDistFlow2")
119
119
  test_one("33base.xml", "33base_ldf.out", 'test/33base_ldf.ans', "-m LinDistFlow")
120
120
  test_one("33base.xml", "33base_nt.out", 'test/33base_nt.ans', "-m Newton")
121
121
 
@@ -0,0 +1,31 @@
1
+ from fpowerkit import Grid, CombinedSolver, Estimator, Calculator, LinDistFlow2Solver, NewtonSolver
2
+
3
+ def test_cmb():
4
+ grid = Grid.fromFile("cases/3nodes.xml")
5
+ solver = CombinedSolver(grid=grid, estimator=Estimator.LinDistFlow2, calculator=Calculator.Newton)
6
+ res, obj = solver.solve(0)
7
+ print(res, obj)
8
+
9
+ def test_spl():
10
+ grid = Grid.fromFile("cases/3nodes.xml")
11
+ solver0 = LinDistFlow2Solver(grid=grid)
12
+ res, obj = solver0.solve(0)
13
+ print(res, obj)
14
+ for b in grid.Buses:
15
+ print(b.ID, b.V, b.theta, b.Pd, b.Qd)
16
+ for l in grid.Lines:
17
+ print(l.ID, l.P, l.Q, l.I)
18
+ for g in grid.Gens:
19
+ print(g.ID, g.P, g.Q)
20
+ solver1 = NewtonSolver(grid=grid, is_cmb_calculator=True)
21
+ res, obj = solver1.solve(0)
22
+ print(res, obj)
23
+ for b in grid.Buses:
24
+ print(b.ID, b.V, b.theta, b.Pd, b.Qd)
25
+ for l in grid.Lines:
26
+ print(l.ID, l.P, l.Q, l.I)
27
+ for g in grid.Gens:
28
+ print(g.ID, g.P, g.Q)
29
+
30
+ if __name__ == "__main__":
31
+ test_spl()
@@ -1,176 +0,0 @@
1
- import math
2
- from typing import Any
3
- from feasytools import TimeFunc
4
- from enum import IntEnum
5
- from dataclasses import dataclass
6
- from .grid import BusID, Grid
7
- from .island import Island, IslandResult
8
- from .solbase import *
9
-
10
- class BusType(IntEnum):
11
- PQ = 0
12
- PV = 1
13
- Slack = 2
14
-
15
- @dataclass
16
- class _NRProblem:
17
- eqs: 'list[int]'
18
- n_P: int
19
- Ps: 'list[float]'
20
- Qs: 'list[float]'
21
- bus_dict: 'dict[str, int]'
22
- G: Any # np.ndarray 2D
23
- B: Any # np.ndarray 2D
24
- V: 'list[float]'
25
- theta: 'list[float]'
26
-
27
- def _presolve(il:Island, _t:int):
28
- '''Check the bus type'''
29
- busType: 'dict[BusID, BusType]' = {}
30
- slack_cnt = 0
31
- eq_P: 'list[int]' = []
32
- eq_Q: 'list[int]' = []
33
- V: 'list[float]' = []
34
- theta: 'list[float]' = []
35
- Ps: 'list[float]' = []
36
- Qs: 'list[float]' = []
37
- bus_dict, Y = il.YMat()
38
- for bid, i in bus_dict.items():
39
- bus = il.grid.Bus(bid)
40
- V.append(bus.V if bus.V is not None else 1.0)
41
- theta.append(bus.theta if bus.theta is not None else 0.0)
42
- fixp = fixq = True
43
- p = -bus.Pd(_t)
44
- q = -bus.Qd(_t)
45
- for g in il.grid.GensAtBus(bus.ID):
46
- if not g.FixedP: fixp = False
47
- else:
48
- assert g.P is not None
49
- if isinstance(g.P, TimeFunc): p += g.P(_t)
50
- else: p += g.P
51
- if not g.FixedQ: fixq = False
52
- else:
53
- assert g.Q is not None
54
- if isinstance(g.Q, TimeFunc): q += g.Q(_t)
55
- else: q += g.Q
56
- if bus.FixedV:
57
- if fixp and fixq:
58
- raise ValueError(f"Bus {bus.ID}: Invalid bus type PQV")
59
- elif fixp:
60
- busType[bus.ID] = BusType.PV
61
- eq_P.append(i)
62
- elif fixq:
63
- raise ValueError(f"Bus {bus.ID}: Invalid bus type VQ")
64
- else:
65
- busType[bus.ID] = BusType.Slack
66
- slack_cnt += 1
67
- if slack_cnt > 1:
68
- raise ValueError('Only one slack bus is allowed')
69
- else:
70
- if fixp and fixq:
71
- busType[bus.ID] = BusType.PQ
72
- bus.V = 1.0
73
- eq_P.append(i)
74
- eq_Q.append(i)
75
- elif fixp:
76
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: Pθ")
77
- elif fixq:
78
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: Qθ")
79
- else:
80
- raise ValueError(f"Bus {bus.ID}: Invalid bus type: θ")
81
- Ps.append(p)
82
- Qs.append(q)
83
- if slack_cnt == 0:
84
- raise ValueError('No slack bus is found')
85
- return _NRProblem(eq_P + eq_Q, len(eq_P), Ps, Qs, bus_dict, Y.real, Y.imag, V, theta)
86
-
87
- def _solve(prb: _NRProblem, max_iter:int = 100, eps:float = 1e-6):
88
- '''Solve the power flow problem'''
89
- try:
90
- import numpy as np
91
- except ImportError:
92
- raise ImportError("numpy is required for NewtonSolver. Please install it via 'pip install numpy'.")
93
- G = prb.G
94
- B = prb.B
95
- V = prb.V
96
- T = prb.theta
97
- eqs = prb.eqs
98
- Ps = prb.Ps
99
- Qs = prb.Qs
100
- n_P = prb.n_P
101
- n = len(prb.eqs)
102
- m = len(prb.bus_dict)
103
-
104
- def P(i:int):
105
- return V[i]*sum(V[j]*(
106
- G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j])
107
- ) for j in range(m))
108
-
109
- def Q(i:int):
110
- return V[i]*sum(V[j]*(
111
- G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j])
112
- ) for j in range(m))
113
-
114
- def H(i:int, j:int) -> float:
115
- if i == j: return Q(i)+V[i]**2*B[i,i]
116
- return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
117
-
118
- def N(i:int, j:int) -> float:
119
- if i == j: return -P(i)-V[i]**2*G[i,i]
120
- return -V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
121
-
122
- def M(i:int, j:int) -> float:
123
- if i == j: return -P(i)+V[i]**2*G[i,i]
124
- return V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
125
-
126
- def L(i:int, j:int) -> float:
127
- if i == j: return -Q(i)+V[i]**2*B[i,i]
128
- return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
129
-
130
- cnt = 0
131
- while cnt < max_iter:
132
- y = np.zeros(n, dtype=np.float64)
133
- for i, b in enumerate(eqs):
134
- y[i] = Ps[b] - P(b) if i < n_P else Qs[b] - Q(b)
135
- if np.abs(y).max() < eps:
136
- break
137
- cnt += 1
138
- J = np.zeros((n, n), dtype=np.float64)
139
- for i, b0 in enumerate(eqs):
140
- for j, b1 in enumerate(eqs):
141
- if i < n_P and j < n_P: #dp/dθ
142
- J[i,j] = H(b0, b1)
143
- elif i < n_P and j >= n_P: #V*dp/dV
144
- J[i,j] = N(b0, b1)
145
- elif i >= n_P and j < n_P: #dp/dV
146
- J[i,j] = M(b0, b1)
147
- elif i >= n_P and j >= n_P: #V*dq/dV
148
- J[i,j] = L(b0, b1)
149
- x = np.linalg.solve(J, -y)
150
- for i, (x0, b) in enumerate(zip(x, eqs)):
151
- if i < n_P: # Δθ
152
- T[b] += x0
153
- else: # ΔU/U
154
- V[b] += V[b] * x0
155
- if cnt >= max_iter:
156
- raise ValueError("Bad solution")
157
- return cnt, V, T, prb.bus_dict
158
-
159
- class NewtonSolver(SolverBase):
160
- def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100):
161
- super().__init__(grid, eps, max_iter, default_saveto = default_saveto)
162
-
163
- def solve_island(self, i:int, island:Island, _t:int, **kwargs) -> 'tuple[IslandResult, float]':
164
- try:
165
- prb = _presolve(island, _t)
166
- cnt, V, theta, bus_dict = _solve(prb, self.max_iter, self.eps)
167
- except ValueError as e:
168
- return IslandResult.Failed, 0.0
169
-
170
- for b in bus_dict.keys():
171
- bus = island.grid.Bus(b)
172
- bus.V = V[bus_dict[b]]
173
- bus.theta = theta[bus_dict[b]]
174
- return IslandResult.OK, 0.0
175
-
176
- __all__ = ['NewtonSolver', 'BusType']
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes