fpowerkit 0.3.6.post1__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 (29) hide show
  1. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/PKG-INFO +2 -7
  2. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/lpwrapper.py +87 -77
  3. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solnt.py +89 -73
  4. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/pyproject.toml +2 -8
  5. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/test.py +2 -2
  6. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/.gitignore +0 -0
  7. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/LICENSE +0 -0
  8. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/README.md +0 -0
  9. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/desc.md +0 -0
  10. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/__init__.py +0 -0
  11. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/bus.py +0 -0
  12. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/cases.py +0 -0
  13. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/ess.py +0 -0
  14. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/gen.py +0 -0
  15. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/grid.py +0 -0
  16. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/island.py +0 -0
  17. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/line.py +0 -0
  18. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/pvwind.py +0 -0
  19. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solbase.py +0 -0
  20. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solcmb.py +0 -0
  21. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solcvx.py +0 -0
  22. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/soldist.py +0 -0
  23. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/soldss.py +0 -0
  24. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solldf.py +0 -0
  25. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/solldf2.py +0 -0
  26. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/fpowerkit/utils.py +0 -0
  27. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/main.py +0 -0
  28. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/test314t.py +0 -0
  29. {fpowerkit-0.3.6.post1 → fpowerkit-0.3.7}/test_cmb.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fpowerkit
3
- Version: 0.3.6.post1
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,100 +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
60
  def __le__(self, other):
62
61
  expr = _LPExpr()
63
- expr.add_term(self.idx, 1.0)
62
+ expr.terms[self.idx] = 1.0
64
63
  if isinstance(other, _LPExpr):
65
64
  return expr <= other
66
65
  elif isinstance(other, _LPVar):
67
- expr.add_term(other.idx, -1.0)
66
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) - 1.0
68
67
  return expr <= 0
69
68
  elif isinstance(other, (int, float)):
70
- expr.add_const(-other)
69
+ expr.const = -other
71
70
  return expr <= 0
72
71
  else:
73
72
  raise TypeError("Unsupported type for comparison")
74
73
 
75
74
  def __ge__(self, other):
76
75
  expr = _LPExpr()
77
- expr.add_term(self.idx, 1.0)
76
+ expr.terms[self.idx] = 1.0
78
77
  if isinstance(other, _LPExpr):
79
78
  return expr >= other
80
79
  elif isinstance(other, _LPVar):
81
- expr.add_term(other.idx, -1.0)
80
+ expr.terms[other.idx] = expr.terms.get(other.idx, 0) - 1.0
82
81
  return expr >= 0
83
82
  elif isinstance(other, (int, float)):
84
- expr.add_const(-other)
83
+ expr.const = -other
85
84
  return expr >= 0
86
85
  else:
87
86
  raise TypeError("Unsupported type for comparison")
88
87
 
89
- class _LPEqCons: # expr == 0
88
+ class _LPEqCons:
90
89
  def __init__(self, expr:'_LPExpr'):
91
90
  self.expr = expr
92
- self.rhs = -self.expr.const
91
+ self.rhs = -expr.const
93
92
  self.expr.const = 0
94
93
 
95
94
  def __str__(self):
96
95
  return f"{str(self.expr)} == {self.rhs}"
97
96
 
98
- class _LPIneqCons: # expr <= 0
97
+ class _LPIneqCons:
99
98
  def __init__(self, expr:'_LPExpr'):
100
99
  self.expr = expr
101
- self.rhs = -self.expr.const
100
+ self.rhs = -expr.const
102
101
  self.expr.const = 0
103
102
 
104
103
  def __str__ (self):
105
104
  return f"{str(self.expr)} <= {self.rhs}"
106
105
 
107
106
  class _LPExpr:
108
- def __init__(self):
109
- self.terms:Dict[int, float] = {} # var_idx -> coefficient
110
- 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
111
110
 
112
111
  def add_term(self, var_idx:int, coeff:float):
113
112
  if var_idx in self.terms:
@@ -119,75 +118,76 @@ class _LPExpr:
119
118
  self.const += value
120
119
 
121
120
  def __add__(self, other):
122
- result = deepcopy(self)
123
-
124
121
  if isinstance(other, _LPExpr):
122
+ result_terms = self.terms.copy()
125
123
  for var_idx, coeff in other.terms.items():
126
- result.add_term(var_idx, coeff)
127
- 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)
128
129
  elif isinstance(other, _LPVar):
129
- 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)
130
133
  elif isinstance(other, (int, float)):
131
- result.add_const(other)
134
+ return _LPExpr(self.terms.copy(), self.const + other)
132
135
  else:
133
- raise TypeError("Unsupported type for addition")
134
- return result
136
+ raise TypeError(f"Unsupported type for addition: {type(other)}")
135
137
 
136
138
  def __radd__(self, other):
137
139
  return self.__add__(other)
138
140
 
139
141
  def __sub__(self, other):
140
- result = deepcopy(self)
141
-
142
142
  if isinstance(other, _LPExpr):
143
+ result_terms = self.terms.copy()
143
144
  for var_idx, coeff in other.terms.items():
144
- result.add_term(var_idx, -coeff)
145
- 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)
146
150
  elif isinstance(other, _LPVar):
147
- 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)
148
154
  elif isinstance(other, (int, float)):
149
- result.add_const(-other)
155
+ return _LPExpr(self.terms.copy(), self.const - other)
150
156
  else:
151
- raise TypeError("Unsupported type for subtraction")
152
- return result
157
+ raise TypeError(f"Unsupported type for subtraction: {type(other)}")
153
158
 
154
159
  def __rsub__(self, other):
155
160
  if isinstance(other, _LPExpr):
156
161
  return other - self
157
162
  elif isinstance(other, _LPVar):
158
- result = _LPExpr()
159
- result.add_term(other.idx, 1.0)
163
+ return _LPExpr({other.idx: 1.0}, 0) - self
160
164
  elif isinstance(other, (int, float)):
161
- result = _LPExpr()
162
- result.add_const(other)
165
+ return _LPExpr({}, other) - self
163
166
  else:
164
- raise TypeError("Unsupported type for subtraction")
165
-
166
- return result - self
167
+ raise TypeError(f"Unsupported type for subtraction: {type(other)}")
167
168
 
168
169
  def __neg__(self):
169
- result = deepcopy(self)
170
- for var_idx in result.terms:
171
- result.terms[var_idx] = -result.terms[var_idx]
172
- result.const = -result.const
173
- 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)
174
174
 
175
175
  def __mul__(self, scalar:Union[float, int]):
176
- result = deepcopy(self)
177
- for var_idx in result.terms:
178
- result.terms[var_idx] *= scalar
179
- result.const *= scalar
180
- 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)
181
182
 
182
183
  def __rmul__(self, scalar:Union[float, int]):
183
184
  return self.__mul__(scalar)
184
185
 
185
- def __div__(self, scalar:Union[float, int]):
186
- result = deepcopy(self)
187
- for var_idx in result.terms:
188
- result.terms[var_idx] /= scalar
189
- result.const /= scalar
190
- 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)
191
191
 
192
192
  def __eq__(self, other):
193
193
  return _LPEqCons(self - other)
@@ -218,21 +218,33 @@ class _LPExpr:
218
218
  raise ValueError(f"Variable {var.name} has no assigned value")
219
219
  val += coeff * var.x
220
220
  return val
221
+
222
+ def copy(self):
223
+ """Shallow copy of the expression."""
224
+ return _LPExpr(self.terms.copy(), self.const)
225
+
221
226
 
222
227
  def quicksum(items:Iterable[Union[_LPVar, _LPExpr]]) -> _LPExpr:
223
- result = _LPExpr()
228
+ result_terms = {}
229
+ result_const = 0.0
230
+
224
231
  for other in items:
225
232
  if isinstance(other, _LPExpr):
226
233
  for var_idx, coeff in other.terms.items():
227
- result.add_term(var_idx, coeff)
228
- 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
229
239
  elif isinstance(other, _LPVar):
230
- result.add_term(other.idx, 1.0)
240
+ result_terms[other.idx] = result_terms.get(other.idx, 0) + 1.0
231
241
  elif isinstance(other, (int, float)):
232
- result.add_const(other)
242
+ result_const += other
233
243
  else:
234
- raise TypeError("Unsupported type for addition")
235
- return result
244
+ raise TypeError(f"Unsupported type for addition: {type(other)}")
245
+
246
+ return _LPExpr(result_terms, result_const)
247
+
236
248
 
237
249
  class LinProgProblem:
238
250
  def __init__(self):
@@ -292,14 +304,12 @@ class LinProgProblem:
292
304
  else:
293
305
  raise TypeError("Unsupported constraint type")
294
306
 
295
- def set_objective(self, expr:Union[int, float, _LPExpr]):
296
- """
297
- Set the objective function for the linear programming problem.
298
- """
307
+ def set_objective(self, expr:Union[int, float, _LPExpr, _LPVar]):
308
+ """设置目标函数"""
299
309
  if isinstance(expr, (int, float)):
300
- expr_obj = _LPExpr()
301
- expr_obj.add_const(expr)
302
- self.objective = expr_obj
310
+ self.objective = _LPExpr({}, expr)
311
+ elif isinstance(expr, _LPVar):
312
+ self.objective = _LPExpr({expr.idx: 1.0}, 0)
303
313
  else:
304
314
  self.objective = expr
305
315
 
@@ -1,4 +1,4 @@
1
- import math
1
+ import numpy as np
2
2
  from typing import Any
3
3
  from feasytools import TimeFunc
4
4
  from enum import IntEnum
@@ -16,13 +16,13 @@ class BusType(IntEnum):
16
16
  class _NRProblem:
17
17
  eqs: 'list[int]'
18
18
  n_P: int
19
- Ps: 'list[float]'
20
- Qs: 'list[float]'
19
+ Ps: np.ndarray # list[float]
20
+ Qs: np.ndarray # list[float]
21
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]'
22
+ G: np.ndarray # 2D
23
+ B: np.ndarray # 2D
24
+ V: np.ndarray # list[float]
25
+ theta: np.ndarray # list[float]
26
26
  slack: int
27
27
 
28
28
  def _presolve(il:Island, _t:int):
@@ -85,7 +85,10 @@ def _presolve(il:Island, _t:int):
85
85
  Qs.append(q)
86
86
  if slack_cnt == 0:
87
87
  raise ValueError('No slack bus is found')
88
- return _NRProblem(eq_P + eq_Q, len(eq_P), Ps, Qs, bus_dict, Y.real, Y.imag, V, theta, slack)
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
+ )
89
92
 
90
93
  def _presolve2(il:Island, _t:int):
91
94
  '''Check the bus type after using distflow-like algorithm'''
@@ -136,81 +139,94 @@ def _presolve2(il:Island, _t:int):
136
139
 
137
140
  if slack_cnt == 0:
138
141
  raise ValueError('No slack bus is found')
139
- return _NRProblem(eq_P + eq_Q, len(eq_P), Ps, Qs, bus_dict, Y.real, Y.imag, V, theta, slack)
140
-
141
- def _solve(prb: _NRProblem, max_iter:int = 100, eps:float = 1e-6):
142
- '''Solve the power flow problem'''
143
- try:
144
- import numpy as np
145
- except ImportError:
146
- raise ImportError("numpy is required for NewtonSolver. Please install it via 'pip install numpy'.")
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 ----
147
148
  G = prb.G
148
149
  B = prb.B
149
150
  V = prb.V
150
151
  T = prb.theta
151
- eqs = prb.eqs
152
+
153
+ eqs = np.array(prb.eqs, dtype=int)
152
154
  Ps = prb.Ps
153
155
  Qs = prb.Qs
156
+
154
157
  n_P = prb.n_P
155
- n = len(prb.eqs)
156
- m = len(prb.bus_dict)
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
157
173
 
158
- def P(i:int):
159
- return V[i]*sum(V[j]*(
160
- G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j])
161
- ) for j in range(m))
162
-
163
- def Q(i:int):
164
- return V[i]*sum(V[j]*(
165
- G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j])
166
- ) for j in range(m))
167
-
168
- def H(i:int, j:int) -> float:
169
- if i == j: return Q(i)+V[i]**2*B[i,i]
170
- return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
171
-
172
- def N(i:int, j:int) -> float:
173
- if i == j: return -P(i)-V[i]**2*G[i,i]
174
- return -V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
175
-
176
- def M(i:int, j:int) -> float:
177
- if i == j: return -P(i)+V[i]**2*G[i,i]
178
- return V[i]*V[j]*(G[i,j]*math.cos(T[i]-T[j]) + B[i,j]*math.sin(T[i]-T[j]))
179
-
180
- def L(i:int, j:int) -> float:
181
- if i == j: return -Q(i)+V[i]**2*B[i,i]
182
- return -V[i]*V[j]*(G[i,j]*math.sin(T[i]-T[j]) - B[i,j]*math.cos(T[i]-T[j]))
183
-
184
174
  cnt = 0
185
175
  while cnt < max_iter:
186
- y = np.zeros(n, dtype=np.float64)
187
- for i, b in enumerate(eqs):
188
- y[i] = Ps[b] - P(b) if i < n_P else Qs[b] - Q(b)
189
- if np.abs(y).max() < eps:
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:
190
184
  break
185
+
191
186
  cnt += 1
192
- J = np.zeros((n, n), dtype=np.float64)
193
- for i, b0 in enumerate(eqs):
194
- for j, b1 in enumerate(eqs):
195
- if i < n_P and j < n_P: #dp/dθ
196
- J[i,j] = H(b0, b1)
197
- elif i < n_P and j >= n_P: #V*dp/dV
198
- J[i,j] = N(b0, b1)
199
- elif i >= n_P and j < n_P: #dp/dV
200
- J[i,j] = M(b0, b1)
201
- elif i >= n_P and j >= n_P: #V*dq/dV
202
- J[i,j] = L(b0, b1)
203
- x = np.linalg.solve(J, -y)
204
- for i, (x0, b) in enumerate(zip(x, eqs)):
205
- if i < n_P: # Δθ
206
- T[b] += x0
207
- else: # ΔU/U
208
- V[b] += V[b] * x0
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
+
209
223
  if cnt >= max_iter:
210
224
  raise ValueError("Bad solution")
211
- P_inject = [P(i) for i in range(m)]
212
- Q_inject = [Q(i) for i in range(m)]
213
- return cnt, V, T, P_inject, Q_inject, prb.bus_dict
225
+
226
+ # ---- final injections ----
227
+ P, Q, *_ = calc_PQ()
228
+ return cnt, V, T, P, Q, prb.bus_dict
229
+
214
230
 
215
231
  class NewtonSolver(SolverBase):
216
232
  def __init__(self, grid:Grid, eps:float = 1e-6, default_saveto:str = DEFAULT_SAVETO, max_iter:int = 100, is_cmb_calculator:bool = False):
@@ -229,13 +245,13 @@ class NewtonSolver(SolverBase):
229
245
 
230
246
  for b, i in bus_dict.items():
231
247
  bus = island.grid.Bus(b)
232
- bus.V = V[bus_dict[b]]
233
- bus.theta = theta[bus_dict[b]]
248
+ bus.V = V[bus_dict[b]].item()
249
+ bus.theta = theta[bus_dict[b]].item()
234
250
  gens = self.grid.GensAtBus(b)
235
251
  if len(gens) == 0:
236
252
  continue
237
- pg = P_inject[i] + bus.Pd(_t)
238
- qg = Q_inject[i] + bus.Qd(_t)
253
+ pg = P_inject[i].item() + bus.Pd(_t)
254
+ qg = Q_inject[i].item() + bus.Qd(_t)
239
255
 
240
256
  # Allocate the generation to minimize generation cost
241
257
  from .lpwrapper import LinProgProblem, quicksum
@@ -12,7 +12,7 @@ exclude = [
12
12
 
13
13
  [project]
14
14
  name = "fpowerkit"
15
- version = "0.3.6.post1"
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
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes